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": "trings]))\n\n(def ^:private ^:const cookie-session \"53616c7465645f5f8c5005d5f2ab470188544bbb81a7657eb3245f7360b10b4ea2c23195f492efead11cf4c2622930c1\")\n\n(defn split-newline [data]\n (strings/split-li", "end": 250, "score": 0.8917703628540039, "start": 154, "tag": "KEY", "value": "53616c7465645f5f8c5005d5f2ab470188544bbb81a7657eb3245f7360b10b4ea2c23195f492efead11cf4c2622930c1" } ]
aoc-2021/src/aoc_2021/utils/data-utils.clj
tupini07/advent-of-code
0
(ns aoc-2021.utils.data-utils (:require [clj-http.client :as client] [clojure.string :as strings])) (def ^:private ^:const cookie-session "53616c7465645f5f8c5005d5f2ab470188544bbb81a7657eb3245f7360b10b4ea2c23195f492efead11cf4c2622930c1") (defn split-newline [data] (strings/split-lines data)) (defn- get-file-path-for-day [dayn] (str "resources/data-day-" dayn ".txt")) (defn- download-data-for-day [dayn] (let [request-body (:body (client/get (str "https://adventofcode.com/2021/day/" dayn "/input") {:cookies {"session" {:value cookie-session}} :as :stream}))] (clojure.java.io/copy request-body (java.io.File. (get-file-path-for-day dayn))))) (defn- read-data-for-day [dayn] (slurp (get-file-path-for-day dayn))) (defn get-problem-input-for-day "Gets problem data for the specified day. Data is cached inside `resources/` directory." [dayn] (when (not (.exists (clojure.java.io/file (get-file-path-for-day dayn)))) (download-data-for-day dayn)) (read-data-for-day dayn))
62062
(ns aoc-2021.utils.data-utils (:require [clj-http.client :as client] [clojure.string :as strings])) (def ^:private ^:const cookie-session "<KEY>") (defn split-newline [data] (strings/split-lines data)) (defn- get-file-path-for-day [dayn] (str "resources/data-day-" dayn ".txt")) (defn- download-data-for-day [dayn] (let [request-body (:body (client/get (str "https://adventofcode.com/2021/day/" dayn "/input") {:cookies {"session" {:value cookie-session}} :as :stream}))] (clojure.java.io/copy request-body (java.io.File. (get-file-path-for-day dayn))))) (defn- read-data-for-day [dayn] (slurp (get-file-path-for-day dayn))) (defn get-problem-input-for-day "Gets problem data for the specified day. Data is cached inside `resources/` directory." [dayn] (when (not (.exists (clojure.java.io/file (get-file-path-for-day dayn)))) (download-data-for-day dayn)) (read-data-for-day dayn))
true
(ns aoc-2021.utils.data-utils (:require [clj-http.client :as client] [clojure.string :as strings])) (def ^:private ^:const cookie-session "PI:KEY:<KEY>END_PI") (defn split-newline [data] (strings/split-lines data)) (defn- get-file-path-for-day [dayn] (str "resources/data-day-" dayn ".txt")) (defn- download-data-for-day [dayn] (let [request-body (:body (client/get (str "https://adventofcode.com/2021/day/" dayn "/input") {:cookies {"session" {:value cookie-session}} :as :stream}))] (clojure.java.io/copy request-body (java.io.File. (get-file-path-for-day dayn))))) (defn- read-data-for-day [dayn] (slurp (get-file-path-for-day dayn))) (defn get-problem-input-for-day "Gets problem data for the specified day. Data is cached inside `resources/` directory." [dayn] (when (not (.exists (clojure.java.io/file (get-file-path-for-day dayn)))) (download-data-for-day dayn)) (read-data-for-day dayn))
[ { "context": "ator\n; Date: March 17, 2016.\n; Authors:\n; A01371743 Luis Eduardo Ballinas Aguilar\n;------------------", "end": 147, "score": 0.9910760521888733, "start": 138, "tag": "USERNAME", "value": "A01371743" }, { "context": "e: March 17, 2016.\n; Authors:\n; A01371743 Luis Eduardo Ballinas Aguilar\n;------------------------------------------------", "end": 177, "score": 0.999850869178772, "start": 148, "tag": "NAME", "value": "Luis Eduardo Ballinas Aguilar" } ]
4clojure/problem_135.clj
lu15v/TC2006
0
;---------------------------------------------------------- ; Problem 135: Infix Calculator ; Date: March 17, 2016. ; Authors: ; A01371743 Luis Eduardo Ballinas Aguilar ;---------------------------------------------------------- (use 'clojure.test) (def problem135 (fn [& args] (reduce #(if (fn? %1) (%1 %2) (partial %2 %1)) args))) (deftest test-problem135 (is (= 7 (problem135 2 + 5))) (is (= 42 (problem135 38 + 48 - 2 / 2))) (is (= 8 (problem135 10 / 2 - 1 * 2))) (is (= 72 (problem135 20 / 2 + 2 + 4 + 8 - 6 - 10 * 9)))) (run-tests)
51434
;---------------------------------------------------------- ; Problem 135: Infix Calculator ; Date: March 17, 2016. ; Authors: ; A01371743 <NAME> ;---------------------------------------------------------- (use 'clojure.test) (def problem135 (fn [& args] (reduce #(if (fn? %1) (%1 %2) (partial %2 %1)) args))) (deftest test-problem135 (is (= 7 (problem135 2 + 5))) (is (= 42 (problem135 38 + 48 - 2 / 2))) (is (= 8 (problem135 10 / 2 - 1 * 2))) (is (= 72 (problem135 20 / 2 + 2 + 4 + 8 - 6 - 10 * 9)))) (run-tests)
true
;---------------------------------------------------------- ; Problem 135: Infix Calculator ; Date: March 17, 2016. ; Authors: ; A01371743 PI:NAME:<NAME>END_PI ;---------------------------------------------------------- (use 'clojure.test) (def problem135 (fn [& args] (reduce #(if (fn? %1) (%1 %2) (partial %2 %1)) args))) (deftest test-problem135 (is (= 7 (problem135 2 + 5))) (is (= 42 (problem135 38 + 48 - 2 / 2))) (is (= 8 (problem135 10 / 2 - 1 * 2))) (is (= 72 (problem135 20 / 2 + 2 + 4 + 8 - 6 - 10 * 9)))) (run-tests)
[ { "context": "ic \n; Examples: Truth tables\n\n; Copyright (c) 2016 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu", "end": 107, "score": 0.999876081943512, "start": 93, "tag": "NAME", "value": "Burkhardt Renz" }, { "context": "ot (or phi psi))))\n; => true\n\n;; Exercise 2.5 from Volkar Halbach's Exercises Booklet\n\n; Modus ponens\n(ptt '(impl (", "end": 1631, "score": 0.9822915196418762, "start": 1617, "tag": "NAME", "value": "Volkar Halbach" } ]
src/lwb/prop/examples/truthtable.clj
esb-lwb/lwb
22
; lwb Logic WorkBench -- Propositional Logic ; Examples: Truth tables ; Copyright (c) 2016 Burkhardt Renz, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.prop.examples.truthtable (:require [lwb.prop :refer :all]) (:require [lwb.prop.sat :refer [valid? sat?]])) (def phi '(and (impl (and P Q S) P) (impl (and P S) Q))) (ptt phi) ;; Examples from Volker Halbach: The Logic Manual ;; p. 38 (def phi1 '(impl (not (impl P Q)) (and P Q))) (ptt phi1) ; | P | Q | :result | ; |---+---+---------| ; | T | T | T | ; | T | F | F | ; | F | T | T | ; | F | F | T | ;; p.43 (def phi2 '(impl (and (impl P (not Q)) Q) (not P))) (ptt phi2) ; | P | Q | :result | ; |---+---+---------| ; | T | T | T | ; | T | F | T | ; | F | T | T | ; | F | F | T | ;; p. 46 (def phi3 '(equiv (or P (not Q)) (impl Q P))) (ptt phi3) ; a tautology ;; p.47 (def phi4 '(impl (and (impl P Q) (or (not (impl P1 Q)) (and P P1))) (and (equiv P Q) P1))) (ptt phi4) ; a tautology ;; p. 50 nor (def phi5 '(and (not phi) (not psi))) (ptt phi5) ; | phi | psi | :result | ; |-----+-----+---------| ; | T | T | F | ; | T | F | F | ; | F | T | F | ; | F | F | T | (valid? '(equiv (and (not phi) (not psi)) (not (or phi psi)))) ; => true (valid? (list 'equiv phi5 '(not (or phi psi)))) ; => true ;; Exercise 2.5 from Volkar Halbach's Exercises Booklet ; Modus ponens (ptt '(impl (and P (impl P Q)) Q)) ; Modus tollens (ptt '(impl (and (not Q) (impl P Q)) (not P))) ; Law of the excluded middle (ptt '(or P (not P))) ; Law of contradiction (ptt '(not (and P (not P)))) ; Consequentia mirabilis (ptt '(impl (impl (not P) P) P)) ; Classical dilemma (ptt '(impl (and (impl P Q) (impl (not P) Q)) Q)) ; de Morgan (ptt '(equiv (not (and P Q)) (or (not P) (not Q)))) ; de Morgan (ptt '(equiv (not (or P Q)) (and (not P) (not Q)))) ; Ex falso quodlibet (ptt '(impl (and P (not P)) Q)) ;; Exercise 2.6 (def phi261 '(and P P)) (and (sat? phi261) (not (valid? phi261))) ; neither a tautology nor a contradiction (def phi262 '(equiv (impl (impl P Q) R) (impl P (impl Q R)))) (and (sat? phi262) (not (valid? phi262))) ; neither a tautology nor a contradiction (def phi263 '(equiv (equiv P (equiv Q R)) (equiv (equiv P Q) R))) (valid? phi263) ; a tautology (def phi264 '(equiv (not (impl P Q)) (or P (not Q)))) (and (sat? phi264) (not (valid? phi264))) ; neither a tautology nor a contradiction ; Example of a specification of two trafic lights ; (i) the trafic lights have three lights: red, green, yellow. Exactly one of them ; is on at a time. (def ai '(and (or ar ay ag) (or (not ar) (not ay)) (or (not ar) (not ag)) (or (not ay) (not ag)))) (def bi '(and (or br by bg) (or (not br) (not by)) (or (not br) (not bg)) (or (not by) (not bg)))) ; (ii) never ever are both lights green (def ii '(or (not ag) (not bg))) ; (iii) is a light red is the other one green or yellow (def iii '(and (impl ar (or bg by)) (impl br (or ag ay)))) (defn ptt' [phi] (print-truth-table (truth-table phi :true-only))) (ptt' (list 'and ai bi ii iii)) ; (iv) never ever are both red (def iv '(or (not ar) (not br))) (ptt' (list 'equiv (list 'and ai bi ii iii) (list 'and ai bi ii iv))) (valid? (list 'equiv (list 'and ai bi ii iii) (list 'and ai bi ii iv))) ; => true
107022
; lwb Logic WorkBench -- Propositional Logic ; Examples: Truth tables ; Copyright (c) 2016 <NAME>, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.prop.examples.truthtable (:require [lwb.prop :refer :all]) (:require [lwb.prop.sat :refer [valid? sat?]])) (def phi '(and (impl (and P Q S) P) (impl (and P S) Q))) (ptt phi) ;; Examples from Volker Halbach: The Logic Manual ;; p. 38 (def phi1 '(impl (not (impl P Q)) (and P Q))) (ptt phi1) ; | P | Q | :result | ; |---+---+---------| ; | T | T | T | ; | T | F | F | ; | F | T | T | ; | F | F | T | ;; p.43 (def phi2 '(impl (and (impl P (not Q)) Q) (not P))) (ptt phi2) ; | P | Q | :result | ; |---+---+---------| ; | T | T | T | ; | T | F | T | ; | F | T | T | ; | F | F | T | ;; p. 46 (def phi3 '(equiv (or P (not Q)) (impl Q P))) (ptt phi3) ; a tautology ;; p.47 (def phi4 '(impl (and (impl P Q) (or (not (impl P1 Q)) (and P P1))) (and (equiv P Q) P1))) (ptt phi4) ; a tautology ;; p. 50 nor (def phi5 '(and (not phi) (not psi))) (ptt phi5) ; | phi | psi | :result | ; |-----+-----+---------| ; | T | T | F | ; | T | F | F | ; | F | T | F | ; | F | F | T | (valid? '(equiv (and (not phi) (not psi)) (not (or phi psi)))) ; => true (valid? (list 'equiv phi5 '(not (or phi psi)))) ; => true ;; Exercise 2.5 from <NAME>'s Exercises Booklet ; Modus ponens (ptt '(impl (and P (impl P Q)) Q)) ; Modus tollens (ptt '(impl (and (not Q) (impl P Q)) (not P))) ; Law of the excluded middle (ptt '(or P (not P))) ; Law of contradiction (ptt '(not (and P (not P)))) ; Consequentia mirabilis (ptt '(impl (impl (not P) P) P)) ; Classical dilemma (ptt '(impl (and (impl P Q) (impl (not P) Q)) Q)) ; de Morgan (ptt '(equiv (not (and P Q)) (or (not P) (not Q)))) ; de Morgan (ptt '(equiv (not (or P Q)) (and (not P) (not Q)))) ; Ex falso quodlibet (ptt '(impl (and P (not P)) Q)) ;; Exercise 2.6 (def phi261 '(and P P)) (and (sat? phi261) (not (valid? phi261))) ; neither a tautology nor a contradiction (def phi262 '(equiv (impl (impl P Q) R) (impl P (impl Q R)))) (and (sat? phi262) (not (valid? phi262))) ; neither a tautology nor a contradiction (def phi263 '(equiv (equiv P (equiv Q R)) (equiv (equiv P Q) R))) (valid? phi263) ; a tautology (def phi264 '(equiv (not (impl P Q)) (or P (not Q)))) (and (sat? phi264) (not (valid? phi264))) ; neither a tautology nor a contradiction ; Example of a specification of two trafic lights ; (i) the trafic lights have three lights: red, green, yellow. Exactly one of them ; is on at a time. (def ai '(and (or ar ay ag) (or (not ar) (not ay)) (or (not ar) (not ag)) (or (not ay) (not ag)))) (def bi '(and (or br by bg) (or (not br) (not by)) (or (not br) (not bg)) (or (not by) (not bg)))) ; (ii) never ever are both lights green (def ii '(or (not ag) (not bg))) ; (iii) is a light red is the other one green or yellow (def iii '(and (impl ar (or bg by)) (impl br (or ag ay)))) (defn ptt' [phi] (print-truth-table (truth-table phi :true-only))) (ptt' (list 'and ai bi ii iii)) ; (iv) never ever are both red (def iv '(or (not ar) (not br))) (ptt' (list 'equiv (list 'and ai bi ii iii) (list 'and ai bi ii iv))) (valid? (list 'equiv (list 'and ai bi ii iii) (list 'and ai bi ii iv))) ; => true
true
; lwb Logic WorkBench -- Propositional Logic ; Examples: Truth tables ; Copyright (c) 2016 PI:NAME:<NAME>END_PI, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.prop.examples.truthtable (:require [lwb.prop :refer :all]) (:require [lwb.prop.sat :refer [valid? sat?]])) (def phi '(and (impl (and P Q S) P) (impl (and P S) Q))) (ptt phi) ;; Examples from Volker Halbach: The Logic Manual ;; p. 38 (def phi1 '(impl (not (impl P Q)) (and P Q))) (ptt phi1) ; | P | Q | :result | ; |---+---+---------| ; | T | T | T | ; | T | F | F | ; | F | T | T | ; | F | F | T | ;; p.43 (def phi2 '(impl (and (impl P (not Q)) Q) (not P))) (ptt phi2) ; | P | Q | :result | ; |---+---+---------| ; | T | T | T | ; | T | F | T | ; | F | T | T | ; | F | F | T | ;; p. 46 (def phi3 '(equiv (or P (not Q)) (impl Q P))) (ptt phi3) ; a tautology ;; p.47 (def phi4 '(impl (and (impl P Q) (or (not (impl P1 Q)) (and P P1))) (and (equiv P Q) P1))) (ptt phi4) ; a tautology ;; p. 50 nor (def phi5 '(and (not phi) (not psi))) (ptt phi5) ; | phi | psi | :result | ; |-----+-----+---------| ; | T | T | F | ; | T | F | F | ; | F | T | F | ; | F | F | T | (valid? '(equiv (and (not phi) (not psi)) (not (or phi psi)))) ; => true (valid? (list 'equiv phi5 '(not (or phi psi)))) ; => true ;; Exercise 2.5 from PI:NAME:<NAME>END_PI's Exercises Booklet ; Modus ponens (ptt '(impl (and P (impl P Q)) Q)) ; Modus tollens (ptt '(impl (and (not Q) (impl P Q)) (not P))) ; Law of the excluded middle (ptt '(or P (not P))) ; Law of contradiction (ptt '(not (and P (not P)))) ; Consequentia mirabilis (ptt '(impl (impl (not P) P) P)) ; Classical dilemma (ptt '(impl (and (impl P Q) (impl (not P) Q)) Q)) ; de Morgan (ptt '(equiv (not (and P Q)) (or (not P) (not Q)))) ; de Morgan (ptt '(equiv (not (or P Q)) (and (not P) (not Q)))) ; Ex falso quodlibet (ptt '(impl (and P (not P)) Q)) ;; Exercise 2.6 (def phi261 '(and P P)) (and (sat? phi261) (not (valid? phi261))) ; neither a tautology nor a contradiction (def phi262 '(equiv (impl (impl P Q) R) (impl P (impl Q R)))) (and (sat? phi262) (not (valid? phi262))) ; neither a tautology nor a contradiction (def phi263 '(equiv (equiv P (equiv Q R)) (equiv (equiv P Q) R))) (valid? phi263) ; a tautology (def phi264 '(equiv (not (impl P Q)) (or P (not Q)))) (and (sat? phi264) (not (valid? phi264))) ; neither a tautology nor a contradiction ; Example of a specification of two trafic lights ; (i) the trafic lights have three lights: red, green, yellow. Exactly one of them ; is on at a time. (def ai '(and (or ar ay ag) (or (not ar) (not ay)) (or (not ar) (not ag)) (or (not ay) (not ag)))) (def bi '(and (or br by bg) (or (not br) (not by)) (or (not br) (not bg)) (or (not by) (not bg)))) ; (ii) never ever are both lights green (def ii '(or (not ag) (not bg))) ; (iii) is a light red is the other one green or yellow (def iii '(and (impl ar (or bg by)) (impl br (or ag ay)))) (defn ptt' [phi] (print-truth-table (truth-table phi :true-only))) (ptt' (list 'and ai bi ii iii)) ; (iv) never ever are both red (def iv '(or (not ar) (not br))) (ptt' (list 'equiv (list 'and ai bi ii iii) (list 'and ai bi ii iv))) (valid? (list 'equiv (list 'and ai bi ii iii) (list 'and ai bi ii iv))) ; => true
[ { "context": "logy House, 151 Silbury Blvd.\"]\n [:p \"Milton Keynes, MK9 1LH\"]\n [:p \"United Kingdom\"]\n ", "end": 3038, "score": 0.9998242259025574, "start": 3025, "tag": "NAME", "value": "Milton Keynes" } ]
crux-http-server/src/crux/http_server.clj
msladecek/crux
0
(ns crux.http-server "HTTP API for Crux. The optional SPARQL handler requires juxt.crux/rdf." (:require [clojure.edn :as edn] [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.pprint :as pp] [clojure.set :as set] [clojure.spec.alpha :as s] [clojure.string :as str] [clojure.tools.logging :as log] [clojure.instant :as instant] [crux.api :as api] [crux.codec :as c] [crux.io :as cio] [crux.tx :as tx] [ring.adapter.jetty :as j] [ring.middleware.resource :refer [wrap-resource]] [muuntaja.middleware :refer [wrap-format]] [muuntaja.core :as m] [muuntaja.format.core :as mfc] [ring.middleware.params :as p] [ring.util.io :as rio] [ring.util.request :as req] [ring.util.response :as resp] [ring.util.time :as rt] [hiccup2.core :as hiccup2]) (:import [crux.api ICruxAPI ICruxDatasource NodeOutOfSyncException] [java.io Closeable IOException OutputStream] [java.time Duration ZonedDateTime ZoneId Instant] java.util.Date java.time.format.DateTimeFormatter [java.net URLDecoder URLEncoder] org.eclipse.jetty.server.Server [com.nimbusds.jose.jwk JWK JWKSet KeyType RSAKey ECKey] com.nimbusds.jose.JWSObject com.nimbusds.jwt.SignedJWT [com.nimbusds.jose.crypto RSASSAVerifier ECDSAVerifier])) ;; --------------------------------------------------- ;; Utils (defn- raw-html [{:keys [body title options]}] (str (hiccup2/html [:html {:lang "en"} [:head [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge,chrome=1"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0, maximum-scale=1.0"}] [:link {:rel "icon" :href "/favicon.ico" :type "image/x-icon"}] (when options [:meta {:title "options" :content (str options)}]) [:link {:rel "stylesheet" :href "/css/all.css"}] [:link {:rel "stylesheet" :href "/latofonts.css"}] [:link {:rel "stylesheet" :href "/css/table.css"}] [:link {:rel "stylesheet" :href "/css/codemirror.css"}] [:link {:rel "stylesheet" :href "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css"}] [:title "Crux Console"]] [:body [:div.console [:div#app body]] [:footer.footer [:section.footer-section [:img.footer__juxt-logo {:src "https://www.opencrux.com/images/juxt-logo-white.svg"}] [:div.footer__juxt-info [:p "Copyright © JUXT LTD 2012-2019"] [:p [:strong "Headquarters:"]] [:p "Technology House, 151 Silbury Blvd."] [:p "Milton Keynes, MK9 1LH"] [:p "United Kingdom"] [:p "Company registration: 08457399"]]]] [:script {:src "/cljs-out/dev-main.js" :type "text/javascript"}]]]))) (defn- body->edn [request] (->> request req/body-string (c/read-edn-string-with-readers))) (defn- check-path [[path-pattern valid-methods] request] (let [path (req/path-info request) method (:request-method request)] (and (re-find path-pattern path) (some #{method} valid-methods)))) (defn- response ([status headers body] {:status status :headers headers :body body})) (defn- redirect-response [url] {:status 302 :headers {"Location" url}}) (defn- success-response [m] (response (if (some? m) 200 404) {"Content-Type" "application/edn"} (cio/pr-edn-str m))) (defn- exception-response [status ^Exception e] (response status {"Content-Type" "application/edn"} (with-out-str (pp/pprint (Throwable->map e))))) (defn- wrap-exception-handling [handler] (fn [request] (try (try (handler request) (catch Exception e (if (or (instance? IllegalArgumentException e) (and (.getMessage e) (str/starts-with? (.getMessage e) "Spec assertion failed"))) (exception-response 400 e) ;; Valid edn, invalid content (do (log/error e "Exception while handling request:" (cio/pr-edn-str request)) (exception-response 500 e))))) ;; Valid content; something internal failed, or content validity is not properly checked (catch Exception e (exception-response 400 e))))) ;;Invalid edn (defn- add-last-modified [response date] (cond-> response date (assoc-in [:headers "Last-Modified"] (rt/format-date date)))) ;; --------------------------------------------------- ;; Services (defn- status [^ICruxAPI crux-node] (let [status-map (.status crux-node)] (if (or (not (contains? status-map :crux.zk/zk-active?)) (:crux.zk/zk-active? status-map)) (success-response status-map) (response 500 {"Content-Type" "application/edn"} (cio/pr-edn-str status-map))))) (defn- db-for-request ^ICruxDatasource [^ICruxAPI crux-node {:keys [valid-time transact-time]}] (cond (and valid-time transact-time) (.db crux-node valid-time transact-time) valid-time (.db crux-node valid-time) ;; TODO: This could also be an error, depending how you see it, ;; not supported via the Java API itself. transact-time (.db crux-node (cio/next-monotonic-date) transact-time) :else (.db crux-node))) (defn- streamed-edn-response [^Closeable ctx edn] (try (->> (rio/piped-input-stream (fn [out] (with-open [ctx ctx out (io/writer out)] (.write out "(") (doseq [x edn] (.write out (cio/pr-edn-str x))) (.write out ")")))) (response 200 {"Content-Type" "application/edn"})) (catch Throwable t (.close ctx) (throw t)))) (def ^:private date? (partial instance? Date)) (s/def ::valid-time date?) (s/def ::transact-time date?) (s/def ::query-map (s/and #(set/superset? #{:query :valid-time :transact-time} (keys %)) (s/keys :req-un [:crux.query/query] :opt-un [::valid-time ::transact-time]))) (defn- validate-or-throw [body-edn spec] (when-not (s/valid? spec body-edn) (throw (ex-info (str "Spec assertion failed\n" (s/explain-str spec body-edn)) (s/explain-data spec body-edn))))) (defn- query [^ICruxAPI crux-node request] (let [query-map (doto (body->edn request) (validate-or-throw ::query-map)) db (db-for-request crux-node query-map) result (api/open-q db (:query query-map))] (-> (streamed-edn-response result (iterator-seq result)) (add-last-modified (.transactionTime db))))) (s/def ::eid c/valid-id?) (s/def ::entity-map (s/and (s/keys :opt-un [::valid-time ::transact-time]))) (defn- entity [^ICruxAPI crux-node {:keys [query-params] :as request}] (let [body (doto (body->edn request) (validate-or-throw ::entity-map)) eid (or (:eid body) (some-> (re-find #"^/entity/(.+)$" (req/path-info request)) second c/id-edn-reader) (throw (IllegalArgumentException. "missing eid"))) db (db-for-request crux-node {:valid-time (or (:valid-time body) (some-> (get query-params "valid-time") (instant/read-instant-date))) :transact-time (or (:transact-time body) (some-> (get query-params "transaction-time") (instant/read-instant-date)))}) {:keys [crux.tx/tx-time] :as entity-tx} (.entityTx db eid)] (-> (success-response (.entity db eid)) (add-last-modified tx-time)))) (defn- entity-tx [^ICruxAPI crux-node {:keys [query-params] :as request}] (let [body (doto (body->edn request) (validate-or-throw ::entity-map)) eid (or (:eid body) (some-> (re-find #"^/entity-tx/(.+)$" (req/path-info request)) second c/id-edn-reader) (throw (IllegalArgumentException. "missing eid"))) db (db-for-request crux-node {:valid-time (or (:valid-time body) (some-> (get query-params "valid-time") (instant/read-instant-date))) :transact-time (or (:transact-time body) (some-> (get query-params "transaction-time") (instant/read-instant-date)))}) {:keys [crux.tx/tx-time] :as entity-tx} (.entityTx db eid)] (-> (success-response entity-tx) (add-last-modified tx-time)))) (defn- entity-history [^ICruxAPI node {{:strs [sort-order valid-time transaction-time start-valid-time start-transaction-time end-valid-time end-transaction-time with-corrections with-docs]} :query-params :as req}] (let [db (db-for-request node {:valid-time (some-> valid-time (instant/read-instant-date)) :transact-time (some-> transaction-time (instant/read-instant-date))}) eid (or (some-> (re-find #"^/entity-history/(.+)$" (req/path-info req)) second c/id-edn-reader) (throw (IllegalArgumentException. "missing eid"))) sort-order (or (some-> sort-order keyword) (throw (IllegalArgumentException. "missing sort-order query parameter"))) opts {:with-corrections? (some-> ^String with-corrections Boolean/valueOf) :with-docs? (some-> ^String with-docs Boolean/valueOf) :start {:crux.db/valid-time (some-> start-valid-time (instant/read-instant-date)) :crux.tx/tx-time (some-> start-transaction-time (instant/read-instant-date))} :end {:crux.db/valid-time (some-> end-valid-time (instant/read-instant-date)) :crux.tx/tx-time (some-> end-transaction-time (instant/read-instant-date))}} history (api/open-entity-history db eid sort-order opts)] (-> (streamed-edn-response history (iterator-seq history)) (add-last-modified (:crux.tx/tx-time (api/latest-completed-tx node)))))) (defn- transact [^ICruxAPI crux-node request] (let [tx-ops (body->edn request) {:keys [crux.tx/tx-time] :as submitted-tx} (.submitTx crux-node tx-ops)] (-> (success-response submitted-tx) (assoc :status 202) (add-last-modified tx-time)))) ;; TODO: Could add from date parameter. (defn- tx-log [^ICruxAPI crux-node request] (let [with-ops? (Boolean/parseBoolean (get-in request [:query-params "with-ops"])) after-tx-id (some->> (get-in request [:query-params "after-tx-id"]) (Long/parseLong)) result (.openTxLog crux-node after-tx-id with-ops?)] (-> (streamed-edn-response result (iterator-seq result)) (add-last-modified (:crux.tx/tx-time (.latestCompletedTx crux-node)))))) (defn- sync-handler [^ICruxAPI crux-node request] (let [timeout (some->> (get-in request [:query-params "timeout"]) (Long/parseLong) (Duration/ofMillis)) ;; TODO this'll get cut down with the rest of the sync deprecation transaction-time (some->> (get-in request [:query-params "transactionTime"]) (cio/parse-rfc3339-or-millis-date))] (let [last-modified (if transaction-time (.awaitTxTime crux-node transaction-time timeout) (.sync crux-node timeout))] (-> (success-response last-modified) (add-last-modified last-modified))))) (defn- await-tx-time-handler [^ICruxAPI crux-node request] (let [timeout (some->> (get-in request [:query-params "timeout"]) (Long/parseLong) (Duration/ofMillis)) tx-time (some->> (get-in request [:query-params "tx-time"]) (cio/parse-rfc3339-or-millis-date))] (let [last-modified (.awaitTxTime crux-node tx-time timeout)] (-> (success-response last-modified) (add-last-modified last-modified))))) (defn- await-tx-handler [^ICruxAPI crux-node request] (let [timeout (some->> (get-in request [:query-params "timeout"]) (Long/parseLong) (Duration/ofMillis)) tx-id (-> (get-in request [:query-params "tx-id"]) (Long/parseLong))] (let [{:keys [crux.tx/tx-time] :as tx} (.awaitTx crux-node {:crux.tx/tx-id tx-id} timeout)] (-> (success-response tx) (add-last-modified tx-time))))) (defn- attribute-stats [^ICruxAPI crux-node] (success-response (.attributeStats crux-node))) (defn- tx-committed? [^ICruxAPI crux-node request] (try (let [tx-id (-> (get-in request [:query-params "tx-id"]) (Long/parseLong))] (success-response (.hasTxCommitted crux-node {:crux.tx/tx-id tx-id}))) (catch NodeOutOfSyncException e (exception-response 400 e)))) (defn latest-completed-tx [^ICruxAPI crux-node] (success-response (.latestCompletedTx crux-node))) (defn latest-submitted-tx [^ICruxAPI crux-node] (success-response (.latestSubmittedTx crux-node))) (def ^:private sparql-available? (try ; you can change it back to require when clojure.core fixes it to be thread-safe (requiring-resolve 'crux.sparql.protocol/sparql-query) true (catch IOException _ false))) ;; --------------------------------------------------- ;; Jetty server (defn- handler [request {:keys [crux-node ::read-only?]}] (condp check-path request [#"^/$" [:get]] (redirect-response "/_crux/index") [#"^/_crux/status" [:get]] (status crux-node) [#"^/entity/.+$" [:get]] (entity crux-node request) [#"^/entity-tx/.+$" [:get]] (entity-tx crux-node request) [#"^/entity$" [:post]] (entity crux-node request) [#"^/entity-tx$" [:post]] (entity-tx crux-node request) [#"^/entity-history/.+$" [:get]] (entity-history crux-node request) [#"^/query$" [:post]] (query crux-node request) [#"^/attribute-stats" [:get]] (attribute-stats crux-node) [#"^/sync$" [:get]] (sync-handler crux-node request) [#"^/await-tx$" [:get]] (await-tx-handler crux-node request) [#"^/await-tx-time$" [:get]] (await-tx-time-handler crux-node request) [#"^/tx-log$" [:get]] (tx-log crux-node request) [#"^/tx-log$" [:post]] (if read-only? (-> (resp/response "forbidden: read-only HTTP node") (resp/status 403)) (transact crux-node request)) [#"^/tx-committed$" [:get]] (tx-committed? crux-node request) [#"^/latest-completed-tx" [:get]] (latest-completed-tx crux-node) [#"^/latest-submitted-tx" [:get]] (latest-submitted-tx crux-node) (if (and (check-path [#"^/sparql/?$" [:get :post]] request) sparql-available?) ((resolve 'crux.sparql.protocol/sparql-query) crux-node request) nil))) (defn html-request? [request] (= (get-in request [:muuntaja/response :format]) "text/html")) (defn- root-page [] [:div.root-contents [:p "Welcome to the Crux Console! Get started below:"] [:p [:a {:href "/_crux/query"} "Performing a query"]] [:p [:a {:href "/_crux/entity"} "Searching for an entity"]]]) (defn- root-handler [^ICruxAPI crux-node options request] {:status 200 :headers {"Content-Location" "/_crux/index.html"} :body (when (html-request? request) (raw-html {:body (root-page) :title "/_crux" :options options}))}) (def ^DateTimeFormatter default-date-formatter (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ss.SSS")) (defn- entity-root-html [] [:div.entity-root [:div.entity-root__title "Getting Started"] [:p "To look for a particular entity, simply use the entity search below:"] [:div.entity-root__contents [:div.entity-editor__title "Entity selector"] [:div.entity-editor__contents [:form {:action "/_crux/entity"} [:textarea.textarea {:name "eid" :rows 1}] [:div.entity-editor-datetime [:b "Valid Time"] [:input.input.input-time {:type "datetime-local" :name "valid-time" :step "0.01" :value (.format default-date-formatter (ZonedDateTime/now))}] [:b "Transaction Time"] [:input.input.input-time {:type "datetime-local" :name "transaction-time" :step "0.01"}]] [:button.button {:type "submit"} "Submit Query"]]]]]) (defn link-all-entities [db path result] (letfn [(recur-on-result [result links] (if (and (c/valid-id? result) (api/entity db result)) (let [encoded-eid (URLEncoder/encode (str result) "UTF-8") query-params (format "?eid=%s&valid-time=%s&transaction-time=%s" encoded-eid (.toInstant ^Date (api/valid-time db)) (.toInstant ^Date (api/transaction-time db)))] (assoc links result (str path query-params))) (cond (map? result) (apply merge (map #(recur-on-result % links) (vals result))) (sequential? result) (apply merge (map #(recur-on-result % links) result)) :else links)))] (recur-on-result result {}))) (defn resolve-entity-map [linked-entities entity-map] (if-let [href (get linked-entities entity-map)] [:a {:href href} (str entity-map)] (cond (map? entity-map) (for [[k v] entity-map] ^{:key (str (gensym))} [:div.entity-group [:div.entity-group__key (resolve-entity-map linked-entities k)] [:div.entity-group__value (resolve-entity-map linked-entities v)]]) (sequential? entity-map) [:ol.entity-group__value (for [v entity-map] ^{:key (str (gensym))} [:li (resolve-entity-map linked-entities v)])] (set? entity-map) [:ul.entity-group__value (for [v entity-map] ^{:key v} [:li (resolve-entity-map linked-entities v)])] :else (str entity-map)))) (def ^DateTimeFormatter iso-format (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")) (defn vt-tt-entity-box [vt tt] [:div.entity-vt-tt [:div.entity-vt-tt__title "Valid Time"] [:div.entity-vt-tt__value (->> (or ^Date vt (java.util.Date.)) (.toInstant) ^ZonedDateTime ((fn [^Instant inst] (.atZone inst (ZoneId/of "Z")))) (.format iso-format) (str))] [:div.entity-vt-tt__title "Transaction Time"] [:div.entity-vt-tt__value (or (some-> ^Date tt (.toInstant) ^ZonedDateTime ((fn [^Instant inst] (.atZone inst (ZoneId/of "Z")))) (.format iso-format) (str)) "Using Latest")]]) (defn- entity->html [eid linked-entities entity-map vt tt] [:div.entity-map__container (if entity-map [:div.entity-map [:div.entity-group [:div.entity-group__key ":crux.db/id"] [:div.entity-group__value (str (:crux.db/id entity-map))]] [:hr.entity-group__separator] (resolve-entity-map (linked-entities) (dissoc entity-map :crux.db/id))] [:div.entity-map [:strong (str eid)] " entity not found"]) (vt-tt-entity-box vt tt)]) (defn- entity-history->html [eid entity-history] [:div.entity-histories__container [:div.entity-histories (if (not-empty entity-history) (for [{:keys [crux.tx/tx-time crux.db/valid-time crux.db/doc]} entity-history] [:div.entity-history__container [:div.entity-map (resolve-entity-map {} doc)] (vt-tt-entity-box valid-time tx-time)]) [:div.entity-histories [:strong (str eid)] " entity not found"])]]) (defn- entity-state [^ICruxAPI crux-node options {{:strs [eid history sort-order valid-time transaction-time start-valid-time start-transaction-time end-valid-time end-transaction-time with-corrections with-docs link-entities?]} :query-params :as request}] (let [html? (html-request? request)] (if (nil? eid) (if html? {:status 200 :body (raw-html {:body (entity-root-html) :title "/entity" :options options})} (throw (IllegalArgumentException. "missing eid"))) (let [decoded-eid (-> eid URLDecoder/decode c/id-edn-reader) vt (when-not (str/blank? valid-time) (instant/read-instant-date valid-time)) tt (when-not (str/blank? transaction-time) (instant/read-instant-date transaction-time)) db (db-for-request crux-node {:valid-time vt :transact-time tt})] (if history (let [sort-order (or (some-> sort-order keyword) (throw (IllegalArgumentException. "missing sort-order query parameter"))) history-opts {:with-corrections? (some-> ^String with-corrections Boolean/valueOf) :with-docs? (or html? (some-> ^String with-docs Boolean/valueOf)) :start {:crux.db/valid-time (some-> start-valid-time (instant/read-instant-date)) :crux.tx/tx-time (some-> start-transaction-time (instant/read-instant-date))} :end {:crux.db/valid-time (some-> end-valid-time (instant/read-instant-date)) :crux.tx/tx-time (some-> end-transaction-time (instant/read-instant-date))}} entity-history (api/entity-history db decoded-eid sort-order history-opts)] {:status (if (not-empty entity-history) 200 404) :body (if html? (raw-html {:body (entity-history->html eid entity-history) :title "/entity?history=true" :options options}) ;; Stringifying #crux/id values, caused issues with AJAX (map #(update % :crux.db/content-hash str) entity-history))}) (let [entity-map (api/entity db decoded-eid) linked-entities #(link-all-entities db "/_crux/entity" entity-map)] {:status (if (some? entity-map) 200 404) :body (cond html? (raw-html {:body (entity->html eid linked-entities entity-map vt tt) :title "/entity" :options options}) link-entities? {"linked-entities" (linked-entities) "entity" entity-map} :else entity-map)})))))) (defn- query-root-html [] [:div.query-root [:div.query-root__title "Getting Started"] [:div.query-root__contents [:p "To perform a query, use the editor below:"] [:div.query-editor__title "Query editor"] [:div.query-editor__contents [:form {:action "/_crux/query"} [:textarea.textarea {:name "q" :rows 10 :cols 40}] [:div.query-editor-datetime [:b "Valid Time"] [:input.input.input-time {:type "datetime-local" :name "valid-time" :step "0.01" :value (.format default-date-formatter (ZonedDateTime/now (ZoneId/of "Z")))}] [:b "Transaction Time"] [:input.input.input-time {:type "datetime-local" :name "transaction-time" :step "0.01"}]] [:button.button {:type "submit"} "Submit Query"]]]]]) (defn- vectorize-param [param] (if (vector? param) param [param])) (defn- build-query [{:strs [find where args order-by limit offset full-results]}] (let [new-offset (if offset (Integer/parseInt offset) 0)] (cond-> {:find (c/read-edn-string-with-readers find) :where (->> where vectorize-param (mapv c/read-edn-string-with-readers)) :offset new-offset} args (assoc :args (->> args vectorize-param (mapv c/read-edn-string-with-readers))) order-by (assoc :order-by (->> order-by vectorize-param (mapv c/read-edn-string-with-readers))) limit (assoc :limit (Integer/parseInt limit)) full-results (assoc :full-results? true)))) (defn link-top-level-entities [db path results] (->> (apply concat results) (filter (every-pred c/valid-id? #(api/entity db %))) (map (fn [id] (let [encoded-eid (URLEncoder/encode (str id) "UTF-8") query-params (format "?eid=%s&valid-time=%s&transaction-time=%s" encoded-eid (.toInstant ^Date (api/valid-time db)) (.toInstant ^Date (api/transaction-time db)))] [id (str path query-params)]))) (into {}))) (defn resolve-prev-next-offset [query-params prev-offset next-offset] (let [url (str "/_crux/query?" (subs (->> (dissoc query-params "offset") (reduce-kv (fn [coll k v] (if (vector? v) (apply str coll (mapv #(str "&" k "=" %) v)) (str coll "&" k "=" v))) "")) 1)) prev-url (when prev-offset (str url "&offset=" prev-offset)) next-url (when next-offset (str url "&offset=" next-offset))] {:prev-url prev-url :next-url next-url})) (defn query->html [links {headers :find} results] [:body [:div.uikit-table [:div.table__main [:table.table [:thead.table__head [:tr (for [header headers] [:th.table__cell.head__cell.no-js-head__cell header])]] (if (seq results) [:tbody.table__body (for [row results] [:tr.table__row.body__row (for [[header cell-value] (map vector headers row)] [:td.table__cell.body__cell (if-let [href (get links cell-value)] [:a {:href href} (str cell-value)] (str cell-value))])])] [:tbody.table__body.table__no-data [:tr [:td.td__no-data "Nothing to show"]]])]] [:table.table__foot]]]) (defn data-browser-query [^ICruxAPI crux-node options {{:strs [valid-time transaction-time q]} :query-params :as request}] (let [query-params (:query-params request) link-entities? (get query-params "link-entities?") html? (html-request? request) csv? (= (get-in request [:muuntaja/response :format]) "text/csv") tsv? (= (get-in request [:muuntaja/response :format]) "text/tsv")] (cond (empty? query-params) (if html? {:status 200 :body (raw-html {:body (query-root-html) :title "/query" :options options})} {:status 400 :body "No query provided."}) :else (try (let [query (cond-> (or (some-> q (edn/read-string)) (build-query query-params)) (or html? csv? tsv?) (dissoc :full-results?)) vt (when-not (str/blank? valid-time) (instant/read-instant-date valid-time)) tt (when-not (str/blank? transaction-time) (instant/read-instant-date transaction-time)) db (db-for-request crux-node {:valid-time vt :transact-time tt}) results (api/q db query)] {:status 200 :body (cond html? (let [links (link-top-level-entities db "/_crux/entity" results)] (raw-html {:body (query->html links query results) :title "/query" :options options})) csv? (with-out-str (csv/write-csv *out* results)) tsv? (with-out-str (csv/write-csv *out* results :separator \tab)) link-entities? {"linked-entities" (link-top-level-entities db "/_crux/entity" results) "query-results" results} :else results)}) (catch Exception e {:status 400 :body (if html? (raw-html {:title "/query" :body [:div.error-box (.getMessage e)]}) (with-out-str (pp/pprint (Throwable->map e))))}))))) (defn- data-browser-handler [crux-node options request] (condp check-path request [#"^/_crux/index$" [:get]] (root-handler crux-node options request) [#"^/_crux/index.html$" [:get]] (root-handler crux-node options (assoc-in request [:muuntaja/response :format] "text/html")) [#"^/_crux/entity$" [:get]] (entity-state crux-node options request) [#"^/_crux/query$" [:get]] (data-browser-query crux-node options request) [#"^/_crux/query.csv$" [:get]] (data-browser-query crux-node options (assoc-in request [:muuntaja/response :format] "text/csv")) [#"^/_crux/query.tsv$" [:get]] (data-browser-query crux-node options (assoc-in request [:muuntaja/response :format] "text/tsv")) nil)) (def ^:const default-server-port 3000) (defrecord HTTPServer [^Server server options] Closeable (close [_] (.stop server))) (defn- unsupported-encoder [_] (reify mfc/EncodeToBytes (encode-to-bytes [_ data charset] (throw (UnsupportedOperationException.))) mfc/EncodeToOutputStream (encode-to-output-stream [_ data charset] (throw (UnsupportedOperationException.))))) (defn valid-jwt? "Return true if the given JWS is valid with respect to the given signing key." [^String jwt ^JWKSet jwks] (try (let [jws (SignedJWT/parse ^String jwt) kid (.. jws getHeader getKeyID) jwk (.getKeyByKeyId jwks kid) verifier (case (.getValue ^KeyType (.getKeyType jwk)) "RSA" (RSASSAVerifier. ^RSAKey jwk) "EC" (ECDSAVerifier. ^ECKey jwk))] (.verify jws verifier)) (catch Exception e false))) (defn wrap-jwt [handler jwks] (fn [request] (if-not (valid-jwt? (or (get-in request [:headers "x-amzn-oidc-accesstoken"]) (some->> (get-in request [:headers "authorization"]) (re-matches #"Bearer (.*)") (second))) jwks) {:status 401 :body "JWT Failed to validate"} (handler request)))) (def muuntaja-handler (-> m/default-options (assoc-in [:formats "text/html"] (mfc/map->Format {:name "text/html" :encoder [unsupported-encoder]})) (assoc-in [:formats "text/csv"] (mfc/map->Format {:name "text/csv" :encoder [unsupported-encoder]})) (assoc-in [:formats "text/tsv"] (mfc/map->Format {:name "text/tsv" :encoder [unsupported-encoder]})))) (def module {::server {:start-fn (fn [{:keys [crux.node/node]} {::keys [port read-only? ^String jwks] :as options}] (let [server (j/run-jetty (-> (some-fn (-> #(handler % {:crux-node node, ::read-only? read-only?}) (p/wrap-params) (wrap-exception-handling)) (-> (partial data-browser-handler node options) (p/wrap-params) (wrap-resource "public") (wrap-format muuntaja-handler) (wrap-exception-handling)) (fn [request] {:status 404 :headers {"Content-Type" "text/plain"} :body "Could not find resource."})) (cond-> jwks (wrap-jwt (JWKSet/parse jwks)))) {:port port :join? false})] (log/info "HTTP server started on port: " port) (->HTTPServer server options))) :deps #{:crux.node/node} ;; I'm deliberately not porting across CORS here as I don't think we should be encouraging ;; Crux servers to be exposed directly to browsers. Better pattern here for individual apps ;; to expose the functionality they need to? (JH) :args {::port {:crux.config/type :crux.config/nat-int :doc "Port to start the HTTP server on" :default default-server-port} ::read-only? {:crux.config/type :crux.config/boolean :doc "Whether to start the Crux HTTP server in read-only mode" :default false} ::jwks {:crux.config/type :crux.config/string :doc "JWKS string to validate against"}}}})
874
(ns crux.http-server "HTTP API for Crux. The optional SPARQL handler requires juxt.crux/rdf." (:require [clojure.edn :as edn] [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.pprint :as pp] [clojure.set :as set] [clojure.spec.alpha :as s] [clojure.string :as str] [clojure.tools.logging :as log] [clojure.instant :as instant] [crux.api :as api] [crux.codec :as c] [crux.io :as cio] [crux.tx :as tx] [ring.adapter.jetty :as j] [ring.middleware.resource :refer [wrap-resource]] [muuntaja.middleware :refer [wrap-format]] [muuntaja.core :as m] [muuntaja.format.core :as mfc] [ring.middleware.params :as p] [ring.util.io :as rio] [ring.util.request :as req] [ring.util.response :as resp] [ring.util.time :as rt] [hiccup2.core :as hiccup2]) (:import [crux.api ICruxAPI ICruxDatasource NodeOutOfSyncException] [java.io Closeable IOException OutputStream] [java.time Duration ZonedDateTime ZoneId Instant] java.util.Date java.time.format.DateTimeFormatter [java.net URLDecoder URLEncoder] org.eclipse.jetty.server.Server [com.nimbusds.jose.jwk JWK JWKSet KeyType RSAKey ECKey] com.nimbusds.jose.JWSObject com.nimbusds.jwt.SignedJWT [com.nimbusds.jose.crypto RSASSAVerifier ECDSAVerifier])) ;; --------------------------------------------------- ;; Utils (defn- raw-html [{:keys [body title options]}] (str (hiccup2/html [:html {:lang "en"} [:head [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge,chrome=1"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0, maximum-scale=1.0"}] [:link {:rel "icon" :href "/favicon.ico" :type "image/x-icon"}] (when options [:meta {:title "options" :content (str options)}]) [:link {:rel "stylesheet" :href "/css/all.css"}] [:link {:rel "stylesheet" :href "/latofonts.css"}] [:link {:rel "stylesheet" :href "/css/table.css"}] [:link {:rel "stylesheet" :href "/css/codemirror.css"}] [:link {:rel "stylesheet" :href "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css"}] [:title "Crux Console"]] [:body [:div.console [:div#app body]] [:footer.footer [:section.footer-section [:img.footer__juxt-logo {:src "https://www.opencrux.com/images/juxt-logo-white.svg"}] [:div.footer__juxt-info [:p "Copyright © JUXT LTD 2012-2019"] [:p [:strong "Headquarters:"]] [:p "Technology House, 151 Silbury Blvd."] [:p "<NAME>, MK9 1LH"] [:p "United Kingdom"] [:p "Company registration: 08457399"]]]] [:script {:src "/cljs-out/dev-main.js" :type "text/javascript"}]]]))) (defn- body->edn [request] (->> request req/body-string (c/read-edn-string-with-readers))) (defn- check-path [[path-pattern valid-methods] request] (let [path (req/path-info request) method (:request-method request)] (and (re-find path-pattern path) (some #{method} valid-methods)))) (defn- response ([status headers body] {:status status :headers headers :body body})) (defn- redirect-response [url] {:status 302 :headers {"Location" url}}) (defn- success-response [m] (response (if (some? m) 200 404) {"Content-Type" "application/edn"} (cio/pr-edn-str m))) (defn- exception-response [status ^Exception e] (response status {"Content-Type" "application/edn"} (with-out-str (pp/pprint (Throwable->map e))))) (defn- wrap-exception-handling [handler] (fn [request] (try (try (handler request) (catch Exception e (if (or (instance? IllegalArgumentException e) (and (.getMessage e) (str/starts-with? (.getMessage e) "Spec assertion failed"))) (exception-response 400 e) ;; Valid edn, invalid content (do (log/error e "Exception while handling request:" (cio/pr-edn-str request)) (exception-response 500 e))))) ;; Valid content; something internal failed, or content validity is not properly checked (catch Exception e (exception-response 400 e))))) ;;Invalid edn (defn- add-last-modified [response date] (cond-> response date (assoc-in [:headers "Last-Modified"] (rt/format-date date)))) ;; --------------------------------------------------- ;; Services (defn- status [^ICruxAPI crux-node] (let [status-map (.status crux-node)] (if (or (not (contains? status-map :crux.zk/zk-active?)) (:crux.zk/zk-active? status-map)) (success-response status-map) (response 500 {"Content-Type" "application/edn"} (cio/pr-edn-str status-map))))) (defn- db-for-request ^ICruxDatasource [^ICruxAPI crux-node {:keys [valid-time transact-time]}] (cond (and valid-time transact-time) (.db crux-node valid-time transact-time) valid-time (.db crux-node valid-time) ;; TODO: This could also be an error, depending how you see it, ;; not supported via the Java API itself. transact-time (.db crux-node (cio/next-monotonic-date) transact-time) :else (.db crux-node))) (defn- streamed-edn-response [^Closeable ctx edn] (try (->> (rio/piped-input-stream (fn [out] (with-open [ctx ctx out (io/writer out)] (.write out "(") (doseq [x edn] (.write out (cio/pr-edn-str x))) (.write out ")")))) (response 200 {"Content-Type" "application/edn"})) (catch Throwable t (.close ctx) (throw t)))) (def ^:private date? (partial instance? Date)) (s/def ::valid-time date?) (s/def ::transact-time date?) (s/def ::query-map (s/and #(set/superset? #{:query :valid-time :transact-time} (keys %)) (s/keys :req-un [:crux.query/query] :opt-un [::valid-time ::transact-time]))) (defn- validate-or-throw [body-edn spec] (when-not (s/valid? spec body-edn) (throw (ex-info (str "Spec assertion failed\n" (s/explain-str spec body-edn)) (s/explain-data spec body-edn))))) (defn- query [^ICruxAPI crux-node request] (let [query-map (doto (body->edn request) (validate-or-throw ::query-map)) db (db-for-request crux-node query-map) result (api/open-q db (:query query-map))] (-> (streamed-edn-response result (iterator-seq result)) (add-last-modified (.transactionTime db))))) (s/def ::eid c/valid-id?) (s/def ::entity-map (s/and (s/keys :opt-un [::valid-time ::transact-time]))) (defn- entity [^ICruxAPI crux-node {:keys [query-params] :as request}] (let [body (doto (body->edn request) (validate-or-throw ::entity-map)) eid (or (:eid body) (some-> (re-find #"^/entity/(.+)$" (req/path-info request)) second c/id-edn-reader) (throw (IllegalArgumentException. "missing eid"))) db (db-for-request crux-node {:valid-time (or (:valid-time body) (some-> (get query-params "valid-time") (instant/read-instant-date))) :transact-time (or (:transact-time body) (some-> (get query-params "transaction-time") (instant/read-instant-date)))}) {:keys [crux.tx/tx-time] :as entity-tx} (.entityTx db eid)] (-> (success-response (.entity db eid)) (add-last-modified tx-time)))) (defn- entity-tx [^ICruxAPI crux-node {:keys [query-params] :as request}] (let [body (doto (body->edn request) (validate-or-throw ::entity-map)) eid (or (:eid body) (some-> (re-find #"^/entity-tx/(.+)$" (req/path-info request)) second c/id-edn-reader) (throw (IllegalArgumentException. "missing eid"))) db (db-for-request crux-node {:valid-time (or (:valid-time body) (some-> (get query-params "valid-time") (instant/read-instant-date))) :transact-time (or (:transact-time body) (some-> (get query-params "transaction-time") (instant/read-instant-date)))}) {:keys [crux.tx/tx-time] :as entity-tx} (.entityTx db eid)] (-> (success-response entity-tx) (add-last-modified tx-time)))) (defn- entity-history [^ICruxAPI node {{:strs [sort-order valid-time transaction-time start-valid-time start-transaction-time end-valid-time end-transaction-time with-corrections with-docs]} :query-params :as req}] (let [db (db-for-request node {:valid-time (some-> valid-time (instant/read-instant-date)) :transact-time (some-> transaction-time (instant/read-instant-date))}) eid (or (some-> (re-find #"^/entity-history/(.+)$" (req/path-info req)) second c/id-edn-reader) (throw (IllegalArgumentException. "missing eid"))) sort-order (or (some-> sort-order keyword) (throw (IllegalArgumentException. "missing sort-order query parameter"))) opts {:with-corrections? (some-> ^String with-corrections Boolean/valueOf) :with-docs? (some-> ^String with-docs Boolean/valueOf) :start {:crux.db/valid-time (some-> start-valid-time (instant/read-instant-date)) :crux.tx/tx-time (some-> start-transaction-time (instant/read-instant-date))} :end {:crux.db/valid-time (some-> end-valid-time (instant/read-instant-date)) :crux.tx/tx-time (some-> end-transaction-time (instant/read-instant-date))}} history (api/open-entity-history db eid sort-order opts)] (-> (streamed-edn-response history (iterator-seq history)) (add-last-modified (:crux.tx/tx-time (api/latest-completed-tx node)))))) (defn- transact [^ICruxAPI crux-node request] (let [tx-ops (body->edn request) {:keys [crux.tx/tx-time] :as submitted-tx} (.submitTx crux-node tx-ops)] (-> (success-response submitted-tx) (assoc :status 202) (add-last-modified tx-time)))) ;; TODO: Could add from date parameter. (defn- tx-log [^ICruxAPI crux-node request] (let [with-ops? (Boolean/parseBoolean (get-in request [:query-params "with-ops"])) after-tx-id (some->> (get-in request [:query-params "after-tx-id"]) (Long/parseLong)) result (.openTxLog crux-node after-tx-id with-ops?)] (-> (streamed-edn-response result (iterator-seq result)) (add-last-modified (:crux.tx/tx-time (.latestCompletedTx crux-node)))))) (defn- sync-handler [^ICruxAPI crux-node request] (let [timeout (some->> (get-in request [:query-params "timeout"]) (Long/parseLong) (Duration/ofMillis)) ;; TODO this'll get cut down with the rest of the sync deprecation transaction-time (some->> (get-in request [:query-params "transactionTime"]) (cio/parse-rfc3339-or-millis-date))] (let [last-modified (if transaction-time (.awaitTxTime crux-node transaction-time timeout) (.sync crux-node timeout))] (-> (success-response last-modified) (add-last-modified last-modified))))) (defn- await-tx-time-handler [^ICruxAPI crux-node request] (let [timeout (some->> (get-in request [:query-params "timeout"]) (Long/parseLong) (Duration/ofMillis)) tx-time (some->> (get-in request [:query-params "tx-time"]) (cio/parse-rfc3339-or-millis-date))] (let [last-modified (.awaitTxTime crux-node tx-time timeout)] (-> (success-response last-modified) (add-last-modified last-modified))))) (defn- await-tx-handler [^ICruxAPI crux-node request] (let [timeout (some->> (get-in request [:query-params "timeout"]) (Long/parseLong) (Duration/ofMillis)) tx-id (-> (get-in request [:query-params "tx-id"]) (Long/parseLong))] (let [{:keys [crux.tx/tx-time] :as tx} (.awaitTx crux-node {:crux.tx/tx-id tx-id} timeout)] (-> (success-response tx) (add-last-modified tx-time))))) (defn- attribute-stats [^ICruxAPI crux-node] (success-response (.attributeStats crux-node))) (defn- tx-committed? [^ICruxAPI crux-node request] (try (let [tx-id (-> (get-in request [:query-params "tx-id"]) (Long/parseLong))] (success-response (.hasTxCommitted crux-node {:crux.tx/tx-id tx-id}))) (catch NodeOutOfSyncException e (exception-response 400 e)))) (defn latest-completed-tx [^ICruxAPI crux-node] (success-response (.latestCompletedTx crux-node))) (defn latest-submitted-tx [^ICruxAPI crux-node] (success-response (.latestSubmittedTx crux-node))) (def ^:private sparql-available? (try ; you can change it back to require when clojure.core fixes it to be thread-safe (requiring-resolve 'crux.sparql.protocol/sparql-query) true (catch IOException _ false))) ;; --------------------------------------------------- ;; Jetty server (defn- handler [request {:keys [crux-node ::read-only?]}] (condp check-path request [#"^/$" [:get]] (redirect-response "/_crux/index") [#"^/_crux/status" [:get]] (status crux-node) [#"^/entity/.+$" [:get]] (entity crux-node request) [#"^/entity-tx/.+$" [:get]] (entity-tx crux-node request) [#"^/entity$" [:post]] (entity crux-node request) [#"^/entity-tx$" [:post]] (entity-tx crux-node request) [#"^/entity-history/.+$" [:get]] (entity-history crux-node request) [#"^/query$" [:post]] (query crux-node request) [#"^/attribute-stats" [:get]] (attribute-stats crux-node) [#"^/sync$" [:get]] (sync-handler crux-node request) [#"^/await-tx$" [:get]] (await-tx-handler crux-node request) [#"^/await-tx-time$" [:get]] (await-tx-time-handler crux-node request) [#"^/tx-log$" [:get]] (tx-log crux-node request) [#"^/tx-log$" [:post]] (if read-only? (-> (resp/response "forbidden: read-only HTTP node") (resp/status 403)) (transact crux-node request)) [#"^/tx-committed$" [:get]] (tx-committed? crux-node request) [#"^/latest-completed-tx" [:get]] (latest-completed-tx crux-node) [#"^/latest-submitted-tx" [:get]] (latest-submitted-tx crux-node) (if (and (check-path [#"^/sparql/?$" [:get :post]] request) sparql-available?) ((resolve 'crux.sparql.protocol/sparql-query) crux-node request) nil))) (defn html-request? [request] (= (get-in request [:muuntaja/response :format]) "text/html")) (defn- root-page [] [:div.root-contents [:p "Welcome to the Crux Console! Get started below:"] [:p [:a {:href "/_crux/query"} "Performing a query"]] [:p [:a {:href "/_crux/entity"} "Searching for an entity"]]]) (defn- root-handler [^ICruxAPI crux-node options request] {:status 200 :headers {"Content-Location" "/_crux/index.html"} :body (when (html-request? request) (raw-html {:body (root-page) :title "/_crux" :options options}))}) (def ^DateTimeFormatter default-date-formatter (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ss.SSS")) (defn- entity-root-html [] [:div.entity-root [:div.entity-root__title "Getting Started"] [:p "To look for a particular entity, simply use the entity search below:"] [:div.entity-root__contents [:div.entity-editor__title "Entity selector"] [:div.entity-editor__contents [:form {:action "/_crux/entity"} [:textarea.textarea {:name "eid" :rows 1}] [:div.entity-editor-datetime [:b "Valid Time"] [:input.input.input-time {:type "datetime-local" :name "valid-time" :step "0.01" :value (.format default-date-formatter (ZonedDateTime/now))}] [:b "Transaction Time"] [:input.input.input-time {:type "datetime-local" :name "transaction-time" :step "0.01"}]] [:button.button {:type "submit"} "Submit Query"]]]]]) (defn link-all-entities [db path result] (letfn [(recur-on-result [result links] (if (and (c/valid-id? result) (api/entity db result)) (let [encoded-eid (URLEncoder/encode (str result) "UTF-8") query-params (format "?eid=%s&valid-time=%s&transaction-time=%s" encoded-eid (.toInstant ^Date (api/valid-time db)) (.toInstant ^Date (api/transaction-time db)))] (assoc links result (str path query-params))) (cond (map? result) (apply merge (map #(recur-on-result % links) (vals result))) (sequential? result) (apply merge (map #(recur-on-result % links) result)) :else links)))] (recur-on-result result {}))) (defn resolve-entity-map [linked-entities entity-map] (if-let [href (get linked-entities entity-map)] [:a {:href href} (str entity-map)] (cond (map? entity-map) (for [[k v] entity-map] ^{:key (str (gensym))} [:div.entity-group [:div.entity-group__key (resolve-entity-map linked-entities k)] [:div.entity-group__value (resolve-entity-map linked-entities v)]]) (sequential? entity-map) [:ol.entity-group__value (for [v entity-map] ^{:key (str (gensym))} [:li (resolve-entity-map linked-entities v)])] (set? entity-map) [:ul.entity-group__value (for [v entity-map] ^{:key v} [:li (resolve-entity-map linked-entities v)])] :else (str entity-map)))) (def ^DateTimeFormatter iso-format (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")) (defn vt-tt-entity-box [vt tt] [:div.entity-vt-tt [:div.entity-vt-tt__title "Valid Time"] [:div.entity-vt-tt__value (->> (or ^Date vt (java.util.Date.)) (.toInstant) ^ZonedDateTime ((fn [^Instant inst] (.atZone inst (ZoneId/of "Z")))) (.format iso-format) (str))] [:div.entity-vt-tt__title "Transaction Time"] [:div.entity-vt-tt__value (or (some-> ^Date tt (.toInstant) ^ZonedDateTime ((fn [^Instant inst] (.atZone inst (ZoneId/of "Z")))) (.format iso-format) (str)) "Using Latest")]]) (defn- entity->html [eid linked-entities entity-map vt tt] [:div.entity-map__container (if entity-map [:div.entity-map [:div.entity-group [:div.entity-group__key ":crux.db/id"] [:div.entity-group__value (str (:crux.db/id entity-map))]] [:hr.entity-group__separator] (resolve-entity-map (linked-entities) (dissoc entity-map :crux.db/id))] [:div.entity-map [:strong (str eid)] " entity not found"]) (vt-tt-entity-box vt tt)]) (defn- entity-history->html [eid entity-history] [:div.entity-histories__container [:div.entity-histories (if (not-empty entity-history) (for [{:keys [crux.tx/tx-time crux.db/valid-time crux.db/doc]} entity-history] [:div.entity-history__container [:div.entity-map (resolve-entity-map {} doc)] (vt-tt-entity-box valid-time tx-time)]) [:div.entity-histories [:strong (str eid)] " entity not found"])]]) (defn- entity-state [^ICruxAPI crux-node options {{:strs [eid history sort-order valid-time transaction-time start-valid-time start-transaction-time end-valid-time end-transaction-time with-corrections with-docs link-entities?]} :query-params :as request}] (let [html? (html-request? request)] (if (nil? eid) (if html? {:status 200 :body (raw-html {:body (entity-root-html) :title "/entity" :options options})} (throw (IllegalArgumentException. "missing eid"))) (let [decoded-eid (-> eid URLDecoder/decode c/id-edn-reader) vt (when-not (str/blank? valid-time) (instant/read-instant-date valid-time)) tt (when-not (str/blank? transaction-time) (instant/read-instant-date transaction-time)) db (db-for-request crux-node {:valid-time vt :transact-time tt})] (if history (let [sort-order (or (some-> sort-order keyword) (throw (IllegalArgumentException. "missing sort-order query parameter"))) history-opts {:with-corrections? (some-> ^String with-corrections Boolean/valueOf) :with-docs? (or html? (some-> ^String with-docs Boolean/valueOf)) :start {:crux.db/valid-time (some-> start-valid-time (instant/read-instant-date)) :crux.tx/tx-time (some-> start-transaction-time (instant/read-instant-date))} :end {:crux.db/valid-time (some-> end-valid-time (instant/read-instant-date)) :crux.tx/tx-time (some-> end-transaction-time (instant/read-instant-date))}} entity-history (api/entity-history db decoded-eid sort-order history-opts)] {:status (if (not-empty entity-history) 200 404) :body (if html? (raw-html {:body (entity-history->html eid entity-history) :title "/entity?history=true" :options options}) ;; Stringifying #crux/id values, caused issues with AJAX (map #(update % :crux.db/content-hash str) entity-history))}) (let [entity-map (api/entity db decoded-eid) linked-entities #(link-all-entities db "/_crux/entity" entity-map)] {:status (if (some? entity-map) 200 404) :body (cond html? (raw-html {:body (entity->html eid linked-entities entity-map vt tt) :title "/entity" :options options}) link-entities? {"linked-entities" (linked-entities) "entity" entity-map} :else entity-map)})))))) (defn- query-root-html [] [:div.query-root [:div.query-root__title "Getting Started"] [:div.query-root__contents [:p "To perform a query, use the editor below:"] [:div.query-editor__title "Query editor"] [:div.query-editor__contents [:form {:action "/_crux/query"} [:textarea.textarea {:name "q" :rows 10 :cols 40}] [:div.query-editor-datetime [:b "Valid Time"] [:input.input.input-time {:type "datetime-local" :name "valid-time" :step "0.01" :value (.format default-date-formatter (ZonedDateTime/now (ZoneId/of "Z")))}] [:b "Transaction Time"] [:input.input.input-time {:type "datetime-local" :name "transaction-time" :step "0.01"}]] [:button.button {:type "submit"} "Submit Query"]]]]]) (defn- vectorize-param [param] (if (vector? param) param [param])) (defn- build-query [{:strs [find where args order-by limit offset full-results]}] (let [new-offset (if offset (Integer/parseInt offset) 0)] (cond-> {:find (c/read-edn-string-with-readers find) :where (->> where vectorize-param (mapv c/read-edn-string-with-readers)) :offset new-offset} args (assoc :args (->> args vectorize-param (mapv c/read-edn-string-with-readers))) order-by (assoc :order-by (->> order-by vectorize-param (mapv c/read-edn-string-with-readers))) limit (assoc :limit (Integer/parseInt limit)) full-results (assoc :full-results? true)))) (defn link-top-level-entities [db path results] (->> (apply concat results) (filter (every-pred c/valid-id? #(api/entity db %))) (map (fn [id] (let [encoded-eid (URLEncoder/encode (str id) "UTF-8") query-params (format "?eid=%s&valid-time=%s&transaction-time=%s" encoded-eid (.toInstant ^Date (api/valid-time db)) (.toInstant ^Date (api/transaction-time db)))] [id (str path query-params)]))) (into {}))) (defn resolve-prev-next-offset [query-params prev-offset next-offset] (let [url (str "/_crux/query?" (subs (->> (dissoc query-params "offset") (reduce-kv (fn [coll k v] (if (vector? v) (apply str coll (mapv #(str "&" k "=" %) v)) (str coll "&" k "=" v))) "")) 1)) prev-url (when prev-offset (str url "&offset=" prev-offset)) next-url (when next-offset (str url "&offset=" next-offset))] {:prev-url prev-url :next-url next-url})) (defn query->html [links {headers :find} results] [:body [:div.uikit-table [:div.table__main [:table.table [:thead.table__head [:tr (for [header headers] [:th.table__cell.head__cell.no-js-head__cell header])]] (if (seq results) [:tbody.table__body (for [row results] [:tr.table__row.body__row (for [[header cell-value] (map vector headers row)] [:td.table__cell.body__cell (if-let [href (get links cell-value)] [:a {:href href} (str cell-value)] (str cell-value))])])] [:tbody.table__body.table__no-data [:tr [:td.td__no-data "Nothing to show"]]])]] [:table.table__foot]]]) (defn data-browser-query [^ICruxAPI crux-node options {{:strs [valid-time transaction-time q]} :query-params :as request}] (let [query-params (:query-params request) link-entities? (get query-params "link-entities?") html? (html-request? request) csv? (= (get-in request [:muuntaja/response :format]) "text/csv") tsv? (= (get-in request [:muuntaja/response :format]) "text/tsv")] (cond (empty? query-params) (if html? {:status 200 :body (raw-html {:body (query-root-html) :title "/query" :options options})} {:status 400 :body "No query provided."}) :else (try (let [query (cond-> (or (some-> q (edn/read-string)) (build-query query-params)) (or html? csv? tsv?) (dissoc :full-results?)) vt (when-not (str/blank? valid-time) (instant/read-instant-date valid-time)) tt (when-not (str/blank? transaction-time) (instant/read-instant-date transaction-time)) db (db-for-request crux-node {:valid-time vt :transact-time tt}) results (api/q db query)] {:status 200 :body (cond html? (let [links (link-top-level-entities db "/_crux/entity" results)] (raw-html {:body (query->html links query results) :title "/query" :options options})) csv? (with-out-str (csv/write-csv *out* results)) tsv? (with-out-str (csv/write-csv *out* results :separator \tab)) link-entities? {"linked-entities" (link-top-level-entities db "/_crux/entity" results) "query-results" results} :else results)}) (catch Exception e {:status 400 :body (if html? (raw-html {:title "/query" :body [:div.error-box (.getMessage e)]}) (with-out-str (pp/pprint (Throwable->map e))))}))))) (defn- data-browser-handler [crux-node options request] (condp check-path request [#"^/_crux/index$" [:get]] (root-handler crux-node options request) [#"^/_crux/index.html$" [:get]] (root-handler crux-node options (assoc-in request [:muuntaja/response :format] "text/html")) [#"^/_crux/entity$" [:get]] (entity-state crux-node options request) [#"^/_crux/query$" [:get]] (data-browser-query crux-node options request) [#"^/_crux/query.csv$" [:get]] (data-browser-query crux-node options (assoc-in request [:muuntaja/response :format] "text/csv")) [#"^/_crux/query.tsv$" [:get]] (data-browser-query crux-node options (assoc-in request [:muuntaja/response :format] "text/tsv")) nil)) (def ^:const default-server-port 3000) (defrecord HTTPServer [^Server server options] Closeable (close [_] (.stop server))) (defn- unsupported-encoder [_] (reify mfc/EncodeToBytes (encode-to-bytes [_ data charset] (throw (UnsupportedOperationException.))) mfc/EncodeToOutputStream (encode-to-output-stream [_ data charset] (throw (UnsupportedOperationException.))))) (defn valid-jwt? "Return true if the given JWS is valid with respect to the given signing key." [^String jwt ^JWKSet jwks] (try (let [jws (SignedJWT/parse ^String jwt) kid (.. jws getHeader getKeyID) jwk (.getKeyByKeyId jwks kid) verifier (case (.getValue ^KeyType (.getKeyType jwk)) "RSA" (RSASSAVerifier. ^RSAKey jwk) "EC" (ECDSAVerifier. ^ECKey jwk))] (.verify jws verifier)) (catch Exception e false))) (defn wrap-jwt [handler jwks] (fn [request] (if-not (valid-jwt? (or (get-in request [:headers "x-amzn-oidc-accesstoken"]) (some->> (get-in request [:headers "authorization"]) (re-matches #"Bearer (.*)") (second))) jwks) {:status 401 :body "JWT Failed to validate"} (handler request)))) (def muuntaja-handler (-> m/default-options (assoc-in [:formats "text/html"] (mfc/map->Format {:name "text/html" :encoder [unsupported-encoder]})) (assoc-in [:formats "text/csv"] (mfc/map->Format {:name "text/csv" :encoder [unsupported-encoder]})) (assoc-in [:formats "text/tsv"] (mfc/map->Format {:name "text/tsv" :encoder [unsupported-encoder]})))) (def module {::server {:start-fn (fn [{:keys [crux.node/node]} {::keys [port read-only? ^String jwks] :as options}] (let [server (j/run-jetty (-> (some-fn (-> #(handler % {:crux-node node, ::read-only? read-only?}) (p/wrap-params) (wrap-exception-handling)) (-> (partial data-browser-handler node options) (p/wrap-params) (wrap-resource "public") (wrap-format muuntaja-handler) (wrap-exception-handling)) (fn [request] {:status 404 :headers {"Content-Type" "text/plain"} :body "Could not find resource."})) (cond-> jwks (wrap-jwt (JWKSet/parse jwks)))) {:port port :join? false})] (log/info "HTTP server started on port: " port) (->HTTPServer server options))) :deps #{:crux.node/node} ;; I'm deliberately not porting across CORS here as I don't think we should be encouraging ;; Crux servers to be exposed directly to browsers. Better pattern here for individual apps ;; to expose the functionality they need to? (JH) :args {::port {:crux.config/type :crux.config/nat-int :doc "Port to start the HTTP server on" :default default-server-port} ::read-only? {:crux.config/type :crux.config/boolean :doc "Whether to start the Crux HTTP server in read-only mode" :default false} ::jwks {:crux.config/type :crux.config/string :doc "JWKS string to validate against"}}}})
true
(ns crux.http-server "HTTP API for Crux. The optional SPARQL handler requires juxt.crux/rdf." (:require [clojure.edn :as edn] [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.pprint :as pp] [clojure.set :as set] [clojure.spec.alpha :as s] [clojure.string :as str] [clojure.tools.logging :as log] [clojure.instant :as instant] [crux.api :as api] [crux.codec :as c] [crux.io :as cio] [crux.tx :as tx] [ring.adapter.jetty :as j] [ring.middleware.resource :refer [wrap-resource]] [muuntaja.middleware :refer [wrap-format]] [muuntaja.core :as m] [muuntaja.format.core :as mfc] [ring.middleware.params :as p] [ring.util.io :as rio] [ring.util.request :as req] [ring.util.response :as resp] [ring.util.time :as rt] [hiccup2.core :as hiccup2]) (:import [crux.api ICruxAPI ICruxDatasource NodeOutOfSyncException] [java.io Closeable IOException OutputStream] [java.time Duration ZonedDateTime ZoneId Instant] java.util.Date java.time.format.DateTimeFormatter [java.net URLDecoder URLEncoder] org.eclipse.jetty.server.Server [com.nimbusds.jose.jwk JWK JWKSet KeyType RSAKey ECKey] com.nimbusds.jose.JWSObject com.nimbusds.jwt.SignedJWT [com.nimbusds.jose.crypto RSASSAVerifier ECDSAVerifier])) ;; --------------------------------------------------- ;; Utils (defn- raw-html [{:keys [body title options]}] (str (hiccup2/html [:html {:lang "en"} [:head [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge,chrome=1"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0, maximum-scale=1.0"}] [:link {:rel "icon" :href "/favicon.ico" :type "image/x-icon"}] (when options [:meta {:title "options" :content (str options)}]) [:link {:rel "stylesheet" :href "/css/all.css"}] [:link {:rel "stylesheet" :href "/latofonts.css"}] [:link {:rel "stylesheet" :href "/css/table.css"}] [:link {:rel "stylesheet" :href "/css/codemirror.css"}] [:link {:rel "stylesheet" :href "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css"}] [:title "Crux Console"]] [:body [:div.console [:div#app body]] [:footer.footer [:section.footer-section [:img.footer__juxt-logo {:src "https://www.opencrux.com/images/juxt-logo-white.svg"}] [:div.footer__juxt-info [:p "Copyright © JUXT LTD 2012-2019"] [:p [:strong "Headquarters:"]] [:p "Technology House, 151 Silbury Blvd."] [:p "PI:NAME:<NAME>END_PI, MK9 1LH"] [:p "United Kingdom"] [:p "Company registration: 08457399"]]]] [:script {:src "/cljs-out/dev-main.js" :type "text/javascript"}]]]))) (defn- body->edn [request] (->> request req/body-string (c/read-edn-string-with-readers))) (defn- check-path [[path-pattern valid-methods] request] (let [path (req/path-info request) method (:request-method request)] (and (re-find path-pattern path) (some #{method} valid-methods)))) (defn- response ([status headers body] {:status status :headers headers :body body})) (defn- redirect-response [url] {:status 302 :headers {"Location" url}}) (defn- success-response [m] (response (if (some? m) 200 404) {"Content-Type" "application/edn"} (cio/pr-edn-str m))) (defn- exception-response [status ^Exception e] (response status {"Content-Type" "application/edn"} (with-out-str (pp/pprint (Throwable->map e))))) (defn- wrap-exception-handling [handler] (fn [request] (try (try (handler request) (catch Exception e (if (or (instance? IllegalArgumentException e) (and (.getMessage e) (str/starts-with? (.getMessage e) "Spec assertion failed"))) (exception-response 400 e) ;; Valid edn, invalid content (do (log/error e "Exception while handling request:" (cio/pr-edn-str request)) (exception-response 500 e))))) ;; Valid content; something internal failed, or content validity is not properly checked (catch Exception e (exception-response 400 e))))) ;;Invalid edn (defn- add-last-modified [response date] (cond-> response date (assoc-in [:headers "Last-Modified"] (rt/format-date date)))) ;; --------------------------------------------------- ;; Services (defn- status [^ICruxAPI crux-node] (let [status-map (.status crux-node)] (if (or (not (contains? status-map :crux.zk/zk-active?)) (:crux.zk/zk-active? status-map)) (success-response status-map) (response 500 {"Content-Type" "application/edn"} (cio/pr-edn-str status-map))))) (defn- db-for-request ^ICruxDatasource [^ICruxAPI crux-node {:keys [valid-time transact-time]}] (cond (and valid-time transact-time) (.db crux-node valid-time transact-time) valid-time (.db crux-node valid-time) ;; TODO: This could also be an error, depending how you see it, ;; not supported via the Java API itself. transact-time (.db crux-node (cio/next-monotonic-date) transact-time) :else (.db crux-node))) (defn- streamed-edn-response [^Closeable ctx edn] (try (->> (rio/piped-input-stream (fn [out] (with-open [ctx ctx out (io/writer out)] (.write out "(") (doseq [x edn] (.write out (cio/pr-edn-str x))) (.write out ")")))) (response 200 {"Content-Type" "application/edn"})) (catch Throwable t (.close ctx) (throw t)))) (def ^:private date? (partial instance? Date)) (s/def ::valid-time date?) (s/def ::transact-time date?) (s/def ::query-map (s/and #(set/superset? #{:query :valid-time :transact-time} (keys %)) (s/keys :req-un [:crux.query/query] :opt-un [::valid-time ::transact-time]))) (defn- validate-or-throw [body-edn spec] (when-not (s/valid? spec body-edn) (throw (ex-info (str "Spec assertion failed\n" (s/explain-str spec body-edn)) (s/explain-data spec body-edn))))) (defn- query [^ICruxAPI crux-node request] (let [query-map (doto (body->edn request) (validate-or-throw ::query-map)) db (db-for-request crux-node query-map) result (api/open-q db (:query query-map))] (-> (streamed-edn-response result (iterator-seq result)) (add-last-modified (.transactionTime db))))) (s/def ::eid c/valid-id?) (s/def ::entity-map (s/and (s/keys :opt-un [::valid-time ::transact-time]))) (defn- entity [^ICruxAPI crux-node {:keys [query-params] :as request}] (let [body (doto (body->edn request) (validate-or-throw ::entity-map)) eid (or (:eid body) (some-> (re-find #"^/entity/(.+)$" (req/path-info request)) second c/id-edn-reader) (throw (IllegalArgumentException. "missing eid"))) db (db-for-request crux-node {:valid-time (or (:valid-time body) (some-> (get query-params "valid-time") (instant/read-instant-date))) :transact-time (or (:transact-time body) (some-> (get query-params "transaction-time") (instant/read-instant-date)))}) {:keys [crux.tx/tx-time] :as entity-tx} (.entityTx db eid)] (-> (success-response (.entity db eid)) (add-last-modified tx-time)))) (defn- entity-tx [^ICruxAPI crux-node {:keys [query-params] :as request}] (let [body (doto (body->edn request) (validate-or-throw ::entity-map)) eid (or (:eid body) (some-> (re-find #"^/entity-tx/(.+)$" (req/path-info request)) second c/id-edn-reader) (throw (IllegalArgumentException. "missing eid"))) db (db-for-request crux-node {:valid-time (or (:valid-time body) (some-> (get query-params "valid-time") (instant/read-instant-date))) :transact-time (or (:transact-time body) (some-> (get query-params "transaction-time") (instant/read-instant-date)))}) {:keys [crux.tx/tx-time] :as entity-tx} (.entityTx db eid)] (-> (success-response entity-tx) (add-last-modified tx-time)))) (defn- entity-history [^ICruxAPI node {{:strs [sort-order valid-time transaction-time start-valid-time start-transaction-time end-valid-time end-transaction-time with-corrections with-docs]} :query-params :as req}] (let [db (db-for-request node {:valid-time (some-> valid-time (instant/read-instant-date)) :transact-time (some-> transaction-time (instant/read-instant-date))}) eid (or (some-> (re-find #"^/entity-history/(.+)$" (req/path-info req)) second c/id-edn-reader) (throw (IllegalArgumentException. "missing eid"))) sort-order (or (some-> sort-order keyword) (throw (IllegalArgumentException. "missing sort-order query parameter"))) opts {:with-corrections? (some-> ^String with-corrections Boolean/valueOf) :with-docs? (some-> ^String with-docs Boolean/valueOf) :start {:crux.db/valid-time (some-> start-valid-time (instant/read-instant-date)) :crux.tx/tx-time (some-> start-transaction-time (instant/read-instant-date))} :end {:crux.db/valid-time (some-> end-valid-time (instant/read-instant-date)) :crux.tx/tx-time (some-> end-transaction-time (instant/read-instant-date))}} history (api/open-entity-history db eid sort-order opts)] (-> (streamed-edn-response history (iterator-seq history)) (add-last-modified (:crux.tx/tx-time (api/latest-completed-tx node)))))) (defn- transact [^ICruxAPI crux-node request] (let [tx-ops (body->edn request) {:keys [crux.tx/tx-time] :as submitted-tx} (.submitTx crux-node tx-ops)] (-> (success-response submitted-tx) (assoc :status 202) (add-last-modified tx-time)))) ;; TODO: Could add from date parameter. (defn- tx-log [^ICruxAPI crux-node request] (let [with-ops? (Boolean/parseBoolean (get-in request [:query-params "with-ops"])) after-tx-id (some->> (get-in request [:query-params "after-tx-id"]) (Long/parseLong)) result (.openTxLog crux-node after-tx-id with-ops?)] (-> (streamed-edn-response result (iterator-seq result)) (add-last-modified (:crux.tx/tx-time (.latestCompletedTx crux-node)))))) (defn- sync-handler [^ICruxAPI crux-node request] (let [timeout (some->> (get-in request [:query-params "timeout"]) (Long/parseLong) (Duration/ofMillis)) ;; TODO this'll get cut down with the rest of the sync deprecation transaction-time (some->> (get-in request [:query-params "transactionTime"]) (cio/parse-rfc3339-or-millis-date))] (let [last-modified (if transaction-time (.awaitTxTime crux-node transaction-time timeout) (.sync crux-node timeout))] (-> (success-response last-modified) (add-last-modified last-modified))))) (defn- await-tx-time-handler [^ICruxAPI crux-node request] (let [timeout (some->> (get-in request [:query-params "timeout"]) (Long/parseLong) (Duration/ofMillis)) tx-time (some->> (get-in request [:query-params "tx-time"]) (cio/parse-rfc3339-or-millis-date))] (let [last-modified (.awaitTxTime crux-node tx-time timeout)] (-> (success-response last-modified) (add-last-modified last-modified))))) (defn- await-tx-handler [^ICruxAPI crux-node request] (let [timeout (some->> (get-in request [:query-params "timeout"]) (Long/parseLong) (Duration/ofMillis)) tx-id (-> (get-in request [:query-params "tx-id"]) (Long/parseLong))] (let [{:keys [crux.tx/tx-time] :as tx} (.awaitTx crux-node {:crux.tx/tx-id tx-id} timeout)] (-> (success-response tx) (add-last-modified tx-time))))) (defn- attribute-stats [^ICruxAPI crux-node] (success-response (.attributeStats crux-node))) (defn- tx-committed? [^ICruxAPI crux-node request] (try (let [tx-id (-> (get-in request [:query-params "tx-id"]) (Long/parseLong))] (success-response (.hasTxCommitted crux-node {:crux.tx/tx-id tx-id}))) (catch NodeOutOfSyncException e (exception-response 400 e)))) (defn latest-completed-tx [^ICruxAPI crux-node] (success-response (.latestCompletedTx crux-node))) (defn latest-submitted-tx [^ICruxAPI crux-node] (success-response (.latestSubmittedTx crux-node))) (def ^:private sparql-available? (try ; you can change it back to require when clojure.core fixes it to be thread-safe (requiring-resolve 'crux.sparql.protocol/sparql-query) true (catch IOException _ false))) ;; --------------------------------------------------- ;; Jetty server (defn- handler [request {:keys [crux-node ::read-only?]}] (condp check-path request [#"^/$" [:get]] (redirect-response "/_crux/index") [#"^/_crux/status" [:get]] (status crux-node) [#"^/entity/.+$" [:get]] (entity crux-node request) [#"^/entity-tx/.+$" [:get]] (entity-tx crux-node request) [#"^/entity$" [:post]] (entity crux-node request) [#"^/entity-tx$" [:post]] (entity-tx crux-node request) [#"^/entity-history/.+$" [:get]] (entity-history crux-node request) [#"^/query$" [:post]] (query crux-node request) [#"^/attribute-stats" [:get]] (attribute-stats crux-node) [#"^/sync$" [:get]] (sync-handler crux-node request) [#"^/await-tx$" [:get]] (await-tx-handler crux-node request) [#"^/await-tx-time$" [:get]] (await-tx-time-handler crux-node request) [#"^/tx-log$" [:get]] (tx-log crux-node request) [#"^/tx-log$" [:post]] (if read-only? (-> (resp/response "forbidden: read-only HTTP node") (resp/status 403)) (transact crux-node request)) [#"^/tx-committed$" [:get]] (tx-committed? crux-node request) [#"^/latest-completed-tx" [:get]] (latest-completed-tx crux-node) [#"^/latest-submitted-tx" [:get]] (latest-submitted-tx crux-node) (if (and (check-path [#"^/sparql/?$" [:get :post]] request) sparql-available?) ((resolve 'crux.sparql.protocol/sparql-query) crux-node request) nil))) (defn html-request? [request] (= (get-in request [:muuntaja/response :format]) "text/html")) (defn- root-page [] [:div.root-contents [:p "Welcome to the Crux Console! Get started below:"] [:p [:a {:href "/_crux/query"} "Performing a query"]] [:p [:a {:href "/_crux/entity"} "Searching for an entity"]]]) (defn- root-handler [^ICruxAPI crux-node options request] {:status 200 :headers {"Content-Location" "/_crux/index.html"} :body (when (html-request? request) (raw-html {:body (root-page) :title "/_crux" :options options}))}) (def ^DateTimeFormatter default-date-formatter (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ss.SSS")) (defn- entity-root-html [] [:div.entity-root [:div.entity-root__title "Getting Started"] [:p "To look for a particular entity, simply use the entity search below:"] [:div.entity-root__contents [:div.entity-editor__title "Entity selector"] [:div.entity-editor__contents [:form {:action "/_crux/entity"} [:textarea.textarea {:name "eid" :rows 1}] [:div.entity-editor-datetime [:b "Valid Time"] [:input.input.input-time {:type "datetime-local" :name "valid-time" :step "0.01" :value (.format default-date-formatter (ZonedDateTime/now))}] [:b "Transaction Time"] [:input.input.input-time {:type "datetime-local" :name "transaction-time" :step "0.01"}]] [:button.button {:type "submit"} "Submit Query"]]]]]) (defn link-all-entities [db path result] (letfn [(recur-on-result [result links] (if (and (c/valid-id? result) (api/entity db result)) (let [encoded-eid (URLEncoder/encode (str result) "UTF-8") query-params (format "?eid=%s&valid-time=%s&transaction-time=%s" encoded-eid (.toInstant ^Date (api/valid-time db)) (.toInstant ^Date (api/transaction-time db)))] (assoc links result (str path query-params))) (cond (map? result) (apply merge (map #(recur-on-result % links) (vals result))) (sequential? result) (apply merge (map #(recur-on-result % links) result)) :else links)))] (recur-on-result result {}))) (defn resolve-entity-map [linked-entities entity-map] (if-let [href (get linked-entities entity-map)] [:a {:href href} (str entity-map)] (cond (map? entity-map) (for [[k v] entity-map] ^{:key (str (gensym))} [:div.entity-group [:div.entity-group__key (resolve-entity-map linked-entities k)] [:div.entity-group__value (resolve-entity-map linked-entities v)]]) (sequential? entity-map) [:ol.entity-group__value (for [v entity-map] ^{:key (str (gensym))} [:li (resolve-entity-map linked-entities v)])] (set? entity-map) [:ul.entity-group__value (for [v entity-map] ^{:key v} [:li (resolve-entity-map linked-entities v)])] :else (str entity-map)))) (def ^DateTimeFormatter iso-format (DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")) (defn vt-tt-entity-box [vt tt] [:div.entity-vt-tt [:div.entity-vt-tt__title "Valid Time"] [:div.entity-vt-tt__value (->> (or ^Date vt (java.util.Date.)) (.toInstant) ^ZonedDateTime ((fn [^Instant inst] (.atZone inst (ZoneId/of "Z")))) (.format iso-format) (str))] [:div.entity-vt-tt__title "Transaction Time"] [:div.entity-vt-tt__value (or (some-> ^Date tt (.toInstant) ^ZonedDateTime ((fn [^Instant inst] (.atZone inst (ZoneId/of "Z")))) (.format iso-format) (str)) "Using Latest")]]) (defn- entity->html [eid linked-entities entity-map vt tt] [:div.entity-map__container (if entity-map [:div.entity-map [:div.entity-group [:div.entity-group__key ":crux.db/id"] [:div.entity-group__value (str (:crux.db/id entity-map))]] [:hr.entity-group__separator] (resolve-entity-map (linked-entities) (dissoc entity-map :crux.db/id))] [:div.entity-map [:strong (str eid)] " entity not found"]) (vt-tt-entity-box vt tt)]) (defn- entity-history->html [eid entity-history] [:div.entity-histories__container [:div.entity-histories (if (not-empty entity-history) (for [{:keys [crux.tx/tx-time crux.db/valid-time crux.db/doc]} entity-history] [:div.entity-history__container [:div.entity-map (resolve-entity-map {} doc)] (vt-tt-entity-box valid-time tx-time)]) [:div.entity-histories [:strong (str eid)] " entity not found"])]]) (defn- entity-state [^ICruxAPI crux-node options {{:strs [eid history sort-order valid-time transaction-time start-valid-time start-transaction-time end-valid-time end-transaction-time with-corrections with-docs link-entities?]} :query-params :as request}] (let [html? (html-request? request)] (if (nil? eid) (if html? {:status 200 :body (raw-html {:body (entity-root-html) :title "/entity" :options options})} (throw (IllegalArgumentException. "missing eid"))) (let [decoded-eid (-> eid URLDecoder/decode c/id-edn-reader) vt (when-not (str/blank? valid-time) (instant/read-instant-date valid-time)) tt (when-not (str/blank? transaction-time) (instant/read-instant-date transaction-time)) db (db-for-request crux-node {:valid-time vt :transact-time tt})] (if history (let [sort-order (or (some-> sort-order keyword) (throw (IllegalArgumentException. "missing sort-order query parameter"))) history-opts {:with-corrections? (some-> ^String with-corrections Boolean/valueOf) :with-docs? (or html? (some-> ^String with-docs Boolean/valueOf)) :start {:crux.db/valid-time (some-> start-valid-time (instant/read-instant-date)) :crux.tx/tx-time (some-> start-transaction-time (instant/read-instant-date))} :end {:crux.db/valid-time (some-> end-valid-time (instant/read-instant-date)) :crux.tx/tx-time (some-> end-transaction-time (instant/read-instant-date))}} entity-history (api/entity-history db decoded-eid sort-order history-opts)] {:status (if (not-empty entity-history) 200 404) :body (if html? (raw-html {:body (entity-history->html eid entity-history) :title "/entity?history=true" :options options}) ;; Stringifying #crux/id values, caused issues with AJAX (map #(update % :crux.db/content-hash str) entity-history))}) (let [entity-map (api/entity db decoded-eid) linked-entities #(link-all-entities db "/_crux/entity" entity-map)] {:status (if (some? entity-map) 200 404) :body (cond html? (raw-html {:body (entity->html eid linked-entities entity-map vt tt) :title "/entity" :options options}) link-entities? {"linked-entities" (linked-entities) "entity" entity-map} :else entity-map)})))))) (defn- query-root-html [] [:div.query-root [:div.query-root__title "Getting Started"] [:div.query-root__contents [:p "To perform a query, use the editor below:"] [:div.query-editor__title "Query editor"] [:div.query-editor__contents [:form {:action "/_crux/query"} [:textarea.textarea {:name "q" :rows 10 :cols 40}] [:div.query-editor-datetime [:b "Valid Time"] [:input.input.input-time {:type "datetime-local" :name "valid-time" :step "0.01" :value (.format default-date-formatter (ZonedDateTime/now (ZoneId/of "Z")))}] [:b "Transaction Time"] [:input.input.input-time {:type "datetime-local" :name "transaction-time" :step "0.01"}]] [:button.button {:type "submit"} "Submit Query"]]]]]) (defn- vectorize-param [param] (if (vector? param) param [param])) (defn- build-query [{:strs [find where args order-by limit offset full-results]}] (let [new-offset (if offset (Integer/parseInt offset) 0)] (cond-> {:find (c/read-edn-string-with-readers find) :where (->> where vectorize-param (mapv c/read-edn-string-with-readers)) :offset new-offset} args (assoc :args (->> args vectorize-param (mapv c/read-edn-string-with-readers))) order-by (assoc :order-by (->> order-by vectorize-param (mapv c/read-edn-string-with-readers))) limit (assoc :limit (Integer/parseInt limit)) full-results (assoc :full-results? true)))) (defn link-top-level-entities [db path results] (->> (apply concat results) (filter (every-pred c/valid-id? #(api/entity db %))) (map (fn [id] (let [encoded-eid (URLEncoder/encode (str id) "UTF-8") query-params (format "?eid=%s&valid-time=%s&transaction-time=%s" encoded-eid (.toInstant ^Date (api/valid-time db)) (.toInstant ^Date (api/transaction-time db)))] [id (str path query-params)]))) (into {}))) (defn resolve-prev-next-offset [query-params prev-offset next-offset] (let [url (str "/_crux/query?" (subs (->> (dissoc query-params "offset") (reduce-kv (fn [coll k v] (if (vector? v) (apply str coll (mapv #(str "&" k "=" %) v)) (str coll "&" k "=" v))) "")) 1)) prev-url (when prev-offset (str url "&offset=" prev-offset)) next-url (when next-offset (str url "&offset=" next-offset))] {:prev-url prev-url :next-url next-url})) (defn query->html [links {headers :find} results] [:body [:div.uikit-table [:div.table__main [:table.table [:thead.table__head [:tr (for [header headers] [:th.table__cell.head__cell.no-js-head__cell header])]] (if (seq results) [:tbody.table__body (for [row results] [:tr.table__row.body__row (for [[header cell-value] (map vector headers row)] [:td.table__cell.body__cell (if-let [href (get links cell-value)] [:a {:href href} (str cell-value)] (str cell-value))])])] [:tbody.table__body.table__no-data [:tr [:td.td__no-data "Nothing to show"]]])]] [:table.table__foot]]]) (defn data-browser-query [^ICruxAPI crux-node options {{:strs [valid-time transaction-time q]} :query-params :as request}] (let [query-params (:query-params request) link-entities? (get query-params "link-entities?") html? (html-request? request) csv? (= (get-in request [:muuntaja/response :format]) "text/csv") tsv? (= (get-in request [:muuntaja/response :format]) "text/tsv")] (cond (empty? query-params) (if html? {:status 200 :body (raw-html {:body (query-root-html) :title "/query" :options options})} {:status 400 :body "No query provided."}) :else (try (let [query (cond-> (or (some-> q (edn/read-string)) (build-query query-params)) (or html? csv? tsv?) (dissoc :full-results?)) vt (when-not (str/blank? valid-time) (instant/read-instant-date valid-time)) tt (when-not (str/blank? transaction-time) (instant/read-instant-date transaction-time)) db (db-for-request crux-node {:valid-time vt :transact-time tt}) results (api/q db query)] {:status 200 :body (cond html? (let [links (link-top-level-entities db "/_crux/entity" results)] (raw-html {:body (query->html links query results) :title "/query" :options options})) csv? (with-out-str (csv/write-csv *out* results)) tsv? (with-out-str (csv/write-csv *out* results :separator \tab)) link-entities? {"linked-entities" (link-top-level-entities db "/_crux/entity" results) "query-results" results} :else results)}) (catch Exception e {:status 400 :body (if html? (raw-html {:title "/query" :body [:div.error-box (.getMessage e)]}) (with-out-str (pp/pprint (Throwable->map e))))}))))) (defn- data-browser-handler [crux-node options request] (condp check-path request [#"^/_crux/index$" [:get]] (root-handler crux-node options request) [#"^/_crux/index.html$" [:get]] (root-handler crux-node options (assoc-in request [:muuntaja/response :format] "text/html")) [#"^/_crux/entity$" [:get]] (entity-state crux-node options request) [#"^/_crux/query$" [:get]] (data-browser-query crux-node options request) [#"^/_crux/query.csv$" [:get]] (data-browser-query crux-node options (assoc-in request [:muuntaja/response :format] "text/csv")) [#"^/_crux/query.tsv$" [:get]] (data-browser-query crux-node options (assoc-in request [:muuntaja/response :format] "text/tsv")) nil)) (def ^:const default-server-port 3000) (defrecord HTTPServer [^Server server options] Closeable (close [_] (.stop server))) (defn- unsupported-encoder [_] (reify mfc/EncodeToBytes (encode-to-bytes [_ data charset] (throw (UnsupportedOperationException.))) mfc/EncodeToOutputStream (encode-to-output-stream [_ data charset] (throw (UnsupportedOperationException.))))) (defn valid-jwt? "Return true if the given JWS is valid with respect to the given signing key." [^String jwt ^JWKSet jwks] (try (let [jws (SignedJWT/parse ^String jwt) kid (.. jws getHeader getKeyID) jwk (.getKeyByKeyId jwks kid) verifier (case (.getValue ^KeyType (.getKeyType jwk)) "RSA" (RSASSAVerifier. ^RSAKey jwk) "EC" (ECDSAVerifier. ^ECKey jwk))] (.verify jws verifier)) (catch Exception e false))) (defn wrap-jwt [handler jwks] (fn [request] (if-not (valid-jwt? (or (get-in request [:headers "x-amzn-oidc-accesstoken"]) (some->> (get-in request [:headers "authorization"]) (re-matches #"Bearer (.*)") (second))) jwks) {:status 401 :body "JWT Failed to validate"} (handler request)))) (def muuntaja-handler (-> m/default-options (assoc-in [:formats "text/html"] (mfc/map->Format {:name "text/html" :encoder [unsupported-encoder]})) (assoc-in [:formats "text/csv"] (mfc/map->Format {:name "text/csv" :encoder [unsupported-encoder]})) (assoc-in [:formats "text/tsv"] (mfc/map->Format {:name "text/tsv" :encoder [unsupported-encoder]})))) (def module {::server {:start-fn (fn [{:keys [crux.node/node]} {::keys [port read-only? ^String jwks] :as options}] (let [server (j/run-jetty (-> (some-fn (-> #(handler % {:crux-node node, ::read-only? read-only?}) (p/wrap-params) (wrap-exception-handling)) (-> (partial data-browser-handler node options) (p/wrap-params) (wrap-resource "public") (wrap-format muuntaja-handler) (wrap-exception-handling)) (fn [request] {:status 404 :headers {"Content-Type" "text/plain"} :body "Could not find resource."})) (cond-> jwks (wrap-jwt (JWKSet/parse jwks)))) {:port port :join? false})] (log/info "HTTP server started on port: " port) (->HTTPServer server options))) :deps #{:crux.node/node} ;; I'm deliberately not porting across CORS here as I don't think we should be encouraging ;; Crux servers to be exposed directly to browsers. Better pattern here for individual apps ;; to expose the functionality they need to? (JH) :args {::port {:crux.config/type :crux.config/nat-int :doc "Port to start the HTTP server on" :default default-server-port} ::read-only? {:crux.config/type :crux.config/boolean :doc "Whether to start the Crux HTTP server in read-only mode" :default false} ::jwks {:crux.config/type :crux.config/string :doc "JWKS string to validate against"}}}})
[ { "context": "any?])]\n [\"author\" \"Mr. Poopybutthole\"]])))\n\n(defn parse-files\n [file->schema-type-vs ", "end": 8779, "score": 0.6673015356063843, "start": 8766, "tag": "NAME", "value": "Poopybutthole" } ]
src/malli_ts/core.cljc
flowyourmoney/malli-ts
0
(ns malli-ts.core (:require [malli-ts.ast :refer [->ast]] [malli.core :as m] [camel-snake-kebab.core :as csk] [clojure.string :as string] [clojure.set :as set] #?(:cljs ["path" :as path]))) #?(:clj (defn- get-path [f] (java.nio.file.Paths/get f (into-array String [])))) (defn- path-relative [f1 f2] #?(:cljs (path/relative (path/dirname f1) f2) :clj (let [p1 (get-path f1) p2 (get-path f2)] (str (.relativize p1 p2))))) (defn- -dispatch-parse-ast-node [node options] (cond (some-> node :schema (m/properties options) ::external-type) :external-type (not (some? node)) :nil-node (:$ref node) :$ref (:type node) [:type (:type node)] (:union node) :union (:intersection node) :intersection (some? (:const node)) :const :else [:type :any])) (defmulti ^:private -parse-ast-node #'-dispatch-parse-ast-node) (defmethod -parse-ast-node :$ref [{:keys [$ref] :as node} {:keys [deref-types schema-id->type-desc files-import-alias* file-imports* file] :as options}] (if (or (get deref-types $ref) (not (get schema-id->type-desc $ref))) (-parse-ast-node (or (get-in node [:definitions $ref]) (->ast (:schema node))) options) (let [ref-file (get-in schema-id->type-desc [$ref :file]) import-alias (get @files-import-alias* ref-file) ref-type-name (get-in schema-id->type-desc [$ref :t-name]) same-file? (= file ref-file)] (when-not same-file? (swap! file-imports* update file set/union #{ref-file})) (str (if-not same-file? (str import-alias ".")) ref-type-name)))) (defmethod -parse-ast-node [:type :number] [_ _] "number") (defmethod -parse-ast-node [:type :string] [_ _] "string") (defmethod -parse-ast-node [:type :boolean] [_ _] "boolean") (defmethod -parse-ast-node [:type :any] [_ _] "any") (defmethod -parse-ast-node [:type :undefined] [_ _] "undefined") (defmethod -parse-ast-node :const [{:keys [const] :as node} options] (cond (keyword? const) (str \" (name const) \") (string? const) (str \" const \") (some #(% const) [boolean? number?]) (str const) :else (-parse-ast-node {:type :any} options))) (defmethod -parse-ast-node [:type :array] [{:keys [items]} options] (str "Array<" (-parse-ast-node items options) ">")) (comment (-parse-ast-node {:type :array :items {:type :number}} nil)) (defmethod -parse-ast-node [:type :tuple] [{:keys [items]} options] (str "[" (string/join "," (map #(-parse-ast-node % options) items)) "]")) (comment (-parse-ast-node (parse-ast [:tuple :int :string :boolean]))) (defmethod -parse-ast-node :union [{items :union} options] (str "(" (string/join "|" (map #(-parse-ast-node % options) items)) ")")) (defmethod -parse-ast-node :intersection [{items :intersection} options] (str "(" (string/join "&" (map #(-parse-ast-node % options) items)) ")")) (defmethod -parse-ast-node [:type :object] [{:keys [properties optional index-signature]} {:keys [default-to-camel-case] :as options}] (let [idx-sign-literal (if index-signature (str "[k:" (-parse-ast-node (first index-signature) options) "]:" (-parse-ast-node (second index-signature) options))) properties-literal (if-not (empty? properties) (string/join "," (map (fn [[k v]] (let [property-name (if default-to-camel-case (csk/->camelCase (name k)) (name k))] (str \" property-name \" (if (get optional k) "?") ":" (do (-parse-ast-node v options))))) properties)))] (str "{" (string/join "," (filter (comp not string/blank?) [idx-sign-literal properties-literal])) "}"))) (defmethod -parse-ast-node :external-type [{:keys [schema]} {:keys [file files-import-alias* file-imports*] :as options}] (let [{:keys [t-name t-path t-alias]} (::external-type (m/properties schema)) is-imported-already (if t-path (@file-imports* t-path)) canonical-alias (if t-path (get @files-import-alias* t-path)) import-alias (if (or canonical-alias (not t-path)) canonical-alias (if t-alias t-alias (csk/->camelCase (string/join "-" (take-last 2 (string/split t-path "/"))))))] (when (and t-path (not is-imported-already)) (swap! file-imports* update file set/union #{t-path})) (when (and t-path (not canonical-alias)) (swap! files-import-alias* assoc t-path import-alias)) (str (if t-path (str import-alias ".")) t-name))) (defn- letter-args ([letter-arg] (if letter-arg (let [letter-count (.substring letter-arg 1) next-count (if-not (empty? letter-count) (-> letter-count #?(:cljs js/Number :clj Integer/parseInt) inc) 1) char-code #?(:cljs (.charCodeAt letter-arg 0) :clj (int (.charAt letter-arg 0))) z? (= char-code 122) next-letter (if-not z? (let [next-char-code (inc char-code)] #?(:cljs (.fromCharCode js/String next-char-code) :clj (char next-char-code))) "a") next-letter-arg (str next-letter (if z? next-count letter-count))] (cons next-letter-arg (lazy-seq (letter-args next-letter-arg)))) (cons "a" (lazy-seq (letter-args "a"))))) ([] (letter-args nil))) (comment (->> (take 69 (letter-args)) (take-last 5))) (defmethod -parse-ast-node [:type :=>] [{:keys [args ret]} {:keys [args-names] :as options}] (let [args-type (get args :type) args-items (get args :items) args-names (cond args-names args-names (= args-type :catn) (map (fn [[n]] (csk/->camelCaseString n)) args-items) :else (take (count args) (letter-args))) args (if (= args-type :catn) (map (fn [[_ a]] a) args-items) args-items)] (str "(" (string/join ", " (map (fn [arg-name arg] (str arg-name ":" (-parse-ast-node arg options))) args-names args)) ") => " (-parse-ast-node ret options)))) (comment (-parse-ast-node (->ast [:=> [:cat :string :int] [:map [:a :int] [:b :string]]]))) (defn import-literal [from alias] (str "import * as " alias " from " \' from \' \;)) (comment (import-literal (path/relative (path/dirname "flow/person/index.d.ts") "flow/index.d.ts") "flow")) (defn ->type-declaration-str [type-name literal jsdoc-literal options] (let [{:keys [export declare]} options] (str (if jsdoc-literal (str jsdoc-literal \newline)) (if export "export ") (if declare "var " "type ") type-name (if declare ": " " = ") literal ";"))) (defn -dispatch-provide-jsdoc [jsdoc-k _ _ _] jsdoc-k) (defmulti provide-jsdoc #'-dispatch-provide-jsdoc) (defmethod provide-jsdoc ::schema [jsdoc-k schema-id t-options options] ["schema" (-> schema-id (m/deref options) m/form str)]) (defn -jsdoc-literal [jsdoc-pairs] (if-not (empty? jsdoc-pairs) (str "/**\n" (->> jsdoc-pairs (map (fn [[attribute value]] (str " * @" attribute " " value))) (string/join "\n")) "\n */"))) (comment (println (-jsdoc-literal [["schema" (str '[:map-of any?])] ["author" "Mr. Poopybutthole"]]))) (defn parse-files [file->schema-type-vs options] (let [schema-id->type-desc (reduce (fn [m [file schema-type-vs]] (merge m (reduce (fn [m [schema-id type-desc]] (assoc m schema-id (assoc type-desc :file file))) {} schema-type-vs))) {} file->schema-type-vs) {:keys [registry use-default-schemas] :or {registry {} use-default-schemas true}} options options (merge options {:schema-id->type-desc schema-id->type-desc :file-imports* (atom {}) :files-import-alias* (atom {}) :registry (if use-default-schemas (merge registry (m/default-schemas)) registry)}) jsdoc-default (get options :jsdoc-default) schema-id->type-desc ;; assocs literal into type-desc (reduce (fn [m [file schema-type-vs]] (reduce (fn [m [schema-id {:keys [t-name jsdoc] :as t-options}]] (let [literal (-parse-ast-node (->ast schema-id options) (merge options {:deref-types {schema-id true} :file file :t-options t-options})) jsdoc-literal (->> (concat jsdoc-default jsdoc) (map #(provide-jsdoc % schema-id t-options options)) -jsdoc-literal)] (-> m (assoc-in [schema-id :literal] literal) (assoc-in [schema-id :jsdoc-literal] jsdoc-literal)))) m schema-type-vs)) schema-id->type-desc file->schema-type-vs) {:keys [export-default files-import-alias* file-imports*]} options files (map (fn [[k _]] k) file->schema-type-vs) file->import-literals (reduce (fn [m file] (assoc-in m [file] (map (fn [import-file] (import-literal (path-relative file import-file) (get @files-import-alias* import-file))) (get @file-imports* file)))) {} files) file->type-literals (reduce (fn [m [file scheva-type-vs]] (assoc m file (map (fn [[schema-id _]] (let [{:keys [t-name literal jsdoc-literal export] :as t-options} (get schema-id->type-desc schema-id)] (->type-declaration-str t-name literal jsdoc-literal (merge t-options {:export (if (some? export) export export-default)})))) scheva-type-vs))) {} file->schema-type-vs) file-contents (reduce (fn [m file] (assoc-in m [file] (let [import (string/join "\n" (get file->import-literals file)) types (string/join "\n" (get file->type-literals file))] (str (if-not (string/blank? import) (str import "\n\n")) types)))) {} files)] file-contents)) (defn external-type ([type-name type-path type-import-alias] [any? {::external-type {:t-name type-name :t-path type-path :t-alias type-import-alias}}]) ([type-name type-path] (external-type type-name type-path nil)) ([type-name] (external-type type-name nil nil)))
102113
(ns malli-ts.core (:require [malli-ts.ast :refer [->ast]] [malli.core :as m] [camel-snake-kebab.core :as csk] [clojure.string :as string] [clojure.set :as set] #?(:cljs ["path" :as path]))) #?(:clj (defn- get-path [f] (java.nio.file.Paths/get f (into-array String [])))) (defn- path-relative [f1 f2] #?(:cljs (path/relative (path/dirname f1) f2) :clj (let [p1 (get-path f1) p2 (get-path f2)] (str (.relativize p1 p2))))) (defn- -dispatch-parse-ast-node [node options] (cond (some-> node :schema (m/properties options) ::external-type) :external-type (not (some? node)) :nil-node (:$ref node) :$ref (:type node) [:type (:type node)] (:union node) :union (:intersection node) :intersection (some? (:const node)) :const :else [:type :any])) (defmulti ^:private -parse-ast-node #'-dispatch-parse-ast-node) (defmethod -parse-ast-node :$ref [{:keys [$ref] :as node} {:keys [deref-types schema-id->type-desc files-import-alias* file-imports* file] :as options}] (if (or (get deref-types $ref) (not (get schema-id->type-desc $ref))) (-parse-ast-node (or (get-in node [:definitions $ref]) (->ast (:schema node))) options) (let [ref-file (get-in schema-id->type-desc [$ref :file]) import-alias (get @files-import-alias* ref-file) ref-type-name (get-in schema-id->type-desc [$ref :t-name]) same-file? (= file ref-file)] (when-not same-file? (swap! file-imports* update file set/union #{ref-file})) (str (if-not same-file? (str import-alias ".")) ref-type-name)))) (defmethod -parse-ast-node [:type :number] [_ _] "number") (defmethod -parse-ast-node [:type :string] [_ _] "string") (defmethod -parse-ast-node [:type :boolean] [_ _] "boolean") (defmethod -parse-ast-node [:type :any] [_ _] "any") (defmethod -parse-ast-node [:type :undefined] [_ _] "undefined") (defmethod -parse-ast-node :const [{:keys [const] :as node} options] (cond (keyword? const) (str \" (name const) \") (string? const) (str \" const \") (some #(% const) [boolean? number?]) (str const) :else (-parse-ast-node {:type :any} options))) (defmethod -parse-ast-node [:type :array] [{:keys [items]} options] (str "Array<" (-parse-ast-node items options) ">")) (comment (-parse-ast-node {:type :array :items {:type :number}} nil)) (defmethod -parse-ast-node [:type :tuple] [{:keys [items]} options] (str "[" (string/join "," (map #(-parse-ast-node % options) items)) "]")) (comment (-parse-ast-node (parse-ast [:tuple :int :string :boolean]))) (defmethod -parse-ast-node :union [{items :union} options] (str "(" (string/join "|" (map #(-parse-ast-node % options) items)) ")")) (defmethod -parse-ast-node :intersection [{items :intersection} options] (str "(" (string/join "&" (map #(-parse-ast-node % options) items)) ")")) (defmethod -parse-ast-node [:type :object] [{:keys [properties optional index-signature]} {:keys [default-to-camel-case] :as options}] (let [idx-sign-literal (if index-signature (str "[k:" (-parse-ast-node (first index-signature) options) "]:" (-parse-ast-node (second index-signature) options))) properties-literal (if-not (empty? properties) (string/join "," (map (fn [[k v]] (let [property-name (if default-to-camel-case (csk/->camelCase (name k)) (name k))] (str \" property-name \" (if (get optional k) "?") ":" (do (-parse-ast-node v options))))) properties)))] (str "{" (string/join "," (filter (comp not string/blank?) [idx-sign-literal properties-literal])) "}"))) (defmethod -parse-ast-node :external-type [{:keys [schema]} {:keys [file files-import-alias* file-imports*] :as options}] (let [{:keys [t-name t-path t-alias]} (::external-type (m/properties schema)) is-imported-already (if t-path (@file-imports* t-path)) canonical-alias (if t-path (get @files-import-alias* t-path)) import-alias (if (or canonical-alias (not t-path)) canonical-alias (if t-alias t-alias (csk/->camelCase (string/join "-" (take-last 2 (string/split t-path "/"))))))] (when (and t-path (not is-imported-already)) (swap! file-imports* update file set/union #{t-path})) (when (and t-path (not canonical-alias)) (swap! files-import-alias* assoc t-path import-alias)) (str (if t-path (str import-alias ".")) t-name))) (defn- letter-args ([letter-arg] (if letter-arg (let [letter-count (.substring letter-arg 1) next-count (if-not (empty? letter-count) (-> letter-count #?(:cljs js/Number :clj Integer/parseInt) inc) 1) char-code #?(:cljs (.charCodeAt letter-arg 0) :clj (int (.charAt letter-arg 0))) z? (= char-code 122) next-letter (if-not z? (let [next-char-code (inc char-code)] #?(:cljs (.fromCharCode js/String next-char-code) :clj (char next-char-code))) "a") next-letter-arg (str next-letter (if z? next-count letter-count))] (cons next-letter-arg (lazy-seq (letter-args next-letter-arg)))) (cons "a" (lazy-seq (letter-args "a"))))) ([] (letter-args nil))) (comment (->> (take 69 (letter-args)) (take-last 5))) (defmethod -parse-ast-node [:type :=>] [{:keys [args ret]} {:keys [args-names] :as options}] (let [args-type (get args :type) args-items (get args :items) args-names (cond args-names args-names (= args-type :catn) (map (fn [[n]] (csk/->camelCaseString n)) args-items) :else (take (count args) (letter-args))) args (if (= args-type :catn) (map (fn [[_ a]] a) args-items) args-items)] (str "(" (string/join ", " (map (fn [arg-name arg] (str arg-name ":" (-parse-ast-node arg options))) args-names args)) ") => " (-parse-ast-node ret options)))) (comment (-parse-ast-node (->ast [:=> [:cat :string :int] [:map [:a :int] [:b :string]]]))) (defn import-literal [from alias] (str "import * as " alias " from " \' from \' \;)) (comment (import-literal (path/relative (path/dirname "flow/person/index.d.ts") "flow/index.d.ts") "flow")) (defn ->type-declaration-str [type-name literal jsdoc-literal options] (let [{:keys [export declare]} options] (str (if jsdoc-literal (str jsdoc-literal \newline)) (if export "export ") (if declare "var " "type ") type-name (if declare ": " " = ") literal ";"))) (defn -dispatch-provide-jsdoc [jsdoc-k _ _ _] jsdoc-k) (defmulti provide-jsdoc #'-dispatch-provide-jsdoc) (defmethod provide-jsdoc ::schema [jsdoc-k schema-id t-options options] ["schema" (-> schema-id (m/deref options) m/form str)]) (defn -jsdoc-literal [jsdoc-pairs] (if-not (empty? jsdoc-pairs) (str "/**\n" (->> jsdoc-pairs (map (fn [[attribute value]] (str " * @" attribute " " value))) (string/join "\n")) "\n */"))) (comment (println (-jsdoc-literal [["schema" (str '[:map-of any?])] ["author" "Mr. <NAME>"]]))) (defn parse-files [file->schema-type-vs options] (let [schema-id->type-desc (reduce (fn [m [file schema-type-vs]] (merge m (reduce (fn [m [schema-id type-desc]] (assoc m schema-id (assoc type-desc :file file))) {} schema-type-vs))) {} file->schema-type-vs) {:keys [registry use-default-schemas] :or {registry {} use-default-schemas true}} options options (merge options {:schema-id->type-desc schema-id->type-desc :file-imports* (atom {}) :files-import-alias* (atom {}) :registry (if use-default-schemas (merge registry (m/default-schemas)) registry)}) jsdoc-default (get options :jsdoc-default) schema-id->type-desc ;; assocs literal into type-desc (reduce (fn [m [file schema-type-vs]] (reduce (fn [m [schema-id {:keys [t-name jsdoc] :as t-options}]] (let [literal (-parse-ast-node (->ast schema-id options) (merge options {:deref-types {schema-id true} :file file :t-options t-options})) jsdoc-literal (->> (concat jsdoc-default jsdoc) (map #(provide-jsdoc % schema-id t-options options)) -jsdoc-literal)] (-> m (assoc-in [schema-id :literal] literal) (assoc-in [schema-id :jsdoc-literal] jsdoc-literal)))) m schema-type-vs)) schema-id->type-desc file->schema-type-vs) {:keys [export-default files-import-alias* file-imports*]} options files (map (fn [[k _]] k) file->schema-type-vs) file->import-literals (reduce (fn [m file] (assoc-in m [file] (map (fn [import-file] (import-literal (path-relative file import-file) (get @files-import-alias* import-file))) (get @file-imports* file)))) {} files) file->type-literals (reduce (fn [m [file scheva-type-vs]] (assoc m file (map (fn [[schema-id _]] (let [{:keys [t-name literal jsdoc-literal export] :as t-options} (get schema-id->type-desc schema-id)] (->type-declaration-str t-name literal jsdoc-literal (merge t-options {:export (if (some? export) export export-default)})))) scheva-type-vs))) {} file->schema-type-vs) file-contents (reduce (fn [m file] (assoc-in m [file] (let [import (string/join "\n" (get file->import-literals file)) types (string/join "\n" (get file->type-literals file))] (str (if-not (string/blank? import) (str import "\n\n")) types)))) {} files)] file-contents)) (defn external-type ([type-name type-path type-import-alias] [any? {::external-type {:t-name type-name :t-path type-path :t-alias type-import-alias}}]) ([type-name type-path] (external-type type-name type-path nil)) ([type-name] (external-type type-name nil nil)))
true
(ns malli-ts.core (:require [malli-ts.ast :refer [->ast]] [malli.core :as m] [camel-snake-kebab.core :as csk] [clojure.string :as string] [clojure.set :as set] #?(:cljs ["path" :as path]))) #?(:clj (defn- get-path [f] (java.nio.file.Paths/get f (into-array String [])))) (defn- path-relative [f1 f2] #?(:cljs (path/relative (path/dirname f1) f2) :clj (let [p1 (get-path f1) p2 (get-path f2)] (str (.relativize p1 p2))))) (defn- -dispatch-parse-ast-node [node options] (cond (some-> node :schema (m/properties options) ::external-type) :external-type (not (some? node)) :nil-node (:$ref node) :$ref (:type node) [:type (:type node)] (:union node) :union (:intersection node) :intersection (some? (:const node)) :const :else [:type :any])) (defmulti ^:private -parse-ast-node #'-dispatch-parse-ast-node) (defmethod -parse-ast-node :$ref [{:keys [$ref] :as node} {:keys [deref-types schema-id->type-desc files-import-alias* file-imports* file] :as options}] (if (or (get deref-types $ref) (not (get schema-id->type-desc $ref))) (-parse-ast-node (or (get-in node [:definitions $ref]) (->ast (:schema node))) options) (let [ref-file (get-in schema-id->type-desc [$ref :file]) import-alias (get @files-import-alias* ref-file) ref-type-name (get-in schema-id->type-desc [$ref :t-name]) same-file? (= file ref-file)] (when-not same-file? (swap! file-imports* update file set/union #{ref-file})) (str (if-not same-file? (str import-alias ".")) ref-type-name)))) (defmethod -parse-ast-node [:type :number] [_ _] "number") (defmethod -parse-ast-node [:type :string] [_ _] "string") (defmethod -parse-ast-node [:type :boolean] [_ _] "boolean") (defmethod -parse-ast-node [:type :any] [_ _] "any") (defmethod -parse-ast-node [:type :undefined] [_ _] "undefined") (defmethod -parse-ast-node :const [{:keys [const] :as node} options] (cond (keyword? const) (str \" (name const) \") (string? const) (str \" const \") (some #(% const) [boolean? number?]) (str const) :else (-parse-ast-node {:type :any} options))) (defmethod -parse-ast-node [:type :array] [{:keys [items]} options] (str "Array<" (-parse-ast-node items options) ">")) (comment (-parse-ast-node {:type :array :items {:type :number}} nil)) (defmethod -parse-ast-node [:type :tuple] [{:keys [items]} options] (str "[" (string/join "," (map #(-parse-ast-node % options) items)) "]")) (comment (-parse-ast-node (parse-ast [:tuple :int :string :boolean]))) (defmethod -parse-ast-node :union [{items :union} options] (str "(" (string/join "|" (map #(-parse-ast-node % options) items)) ")")) (defmethod -parse-ast-node :intersection [{items :intersection} options] (str "(" (string/join "&" (map #(-parse-ast-node % options) items)) ")")) (defmethod -parse-ast-node [:type :object] [{:keys [properties optional index-signature]} {:keys [default-to-camel-case] :as options}] (let [idx-sign-literal (if index-signature (str "[k:" (-parse-ast-node (first index-signature) options) "]:" (-parse-ast-node (second index-signature) options))) properties-literal (if-not (empty? properties) (string/join "," (map (fn [[k v]] (let [property-name (if default-to-camel-case (csk/->camelCase (name k)) (name k))] (str \" property-name \" (if (get optional k) "?") ":" (do (-parse-ast-node v options))))) properties)))] (str "{" (string/join "," (filter (comp not string/blank?) [idx-sign-literal properties-literal])) "}"))) (defmethod -parse-ast-node :external-type [{:keys [schema]} {:keys [file files-import-alias* file-imports*] :as options}] (let [{:keys [t-name t-path t-alias]} (::external-type (m/properties schema)) is-imported-already (if t-path (@file-imports* t-path)) canonical-alias (if t-path (get @files-import-alias* t-path)) import-alias (if (or canonical-alias (not t-path)) canonical-alias (if t-alias t-alias (csk/->camelCase (string/join "-" (take-last 2 (string/split t-path "/"))))))] (when (and t-path (not is-imported-already)) (swap! file-imports* update file set/union #{t-path})) (when (and t-path (not canonical-alias)) (swap! files-import-alias* assoc t-path import-alias)) (str (if t-path (str import-alias ".")) t-name))) (defn- letter-args ([letter-arg] (if letter-arg (let [letter-count (.substring letter-arg 1) next-count (if-not (empty? letter-count) (-> letter-count #?(:cljs js/Number :clj Integer/parseInt) inc) 1) char-code #?(:cljs (.charCodeAt letter-arg 0) :clj (int (.charAt letter-arg 0))) z? (= char-code 122) next-letter (if-not z? (let [next-char-code (inc char-code)] #?(:cljs (.fromCharCode js/String next-char-code) :clj (char next-char-code))) "a") next-letter-arg (str next-letter (if z? next-count letter-count))] (cons next-letter-arg (lazy-seq (letter-args next-letter-arg)))) (cons "a" (lazy-seq (letter-args "a"))))) ([] (letter-args nil))) (comment (->> (take 69 (letter-args)) (take-last 5))) (defmethod -parse-ast-node [:type :=>] [{:keys [args ret]} {:keys [args-names] :as options}] (let [args-type (get args :type) args-items (get args :items) args-names (cond args-names args-names (= args-type :catn) (map (fn [[n]] (csk/->camelCaseString n)) args-items) :else (take (count args) (letter-args))) args (if (= args-type :catn) (map (fn [[_ a]] a) args-items) args-items)] (str "(" (string/join ", " (map (fn [arg-name arg] (str arg-name ":" (-parse-ast-node arg options))) args-names args)) ") => " (-parse-ast-node ret options)))) (comment (-parse-ast-node (->ast [:=> [:cat :string :int] [:map [:a :int] [:b :string]]]))) (defn import-literal [from alias] (str "import * as " alias " from " \' from \' \;)) (comment (import-literal (path/relative (path/dirname "flow/person/index.d.ts") "flow/index.d.ts") "flow")) (defn ->type-declaration-str [type-name literal jsdoc-literal options] (let [{:keys [export declare]} options] (str (if jsdoc-literal (str jsdoc-literal \newline)) (if export "export ") (if declare "var " "type ") type-name (if declare ": " " = ") literal ";"))) (defn -dispatch-provide-jsdoc [jsdoc-k _ _ _] jsdoc-k) (defmulti provide-jsdoc #'-dispatch-provide-jsdoc) (defmethod provide-jsdoc ::schema [jsdoc-k schema-id t-options options] ["schema" (-> schema-id (m/deref options) m/form str)]) (defn -jsdoc-literal [jsdoc-pairs] (if-not (empty? jsdoc-pairs) (str "/**\n" (->> jsdoc-pairs (map (fn [[attribute value]] (str " * @" attribute " " value))) (string/join "\n")) "\n */"))) (comment (println (-jsdoc-literal [["schema" (str '[:map-of any?])] ["author" "Mr. PI:NAME:<NAME>END_PI"]]))) (defn parse-files [file->schema-type-vs options] (let [schema-id->type-desc (reduce (fn [m [file schema-type-vs]] (merge m (reduce (fn [m [schema-id type-desc]] (assoc m schema-id (assoc type-desc :file file))) {} schema-type-vs))) {} file->schema-type-vs) {:keys [registry use-default-schemas] :or {registry {} use-default-schemas true}} options options (merge options {:schema-id->type-desc schema-id->type-desc :file-imports* (atom {}) :files-import-alias* (atom {}) :registry (if use-default-schemas (merge registry (m/default-schemas)) registry)}) jsdoc-default (get options :jsdoc-default) schema-id->type-desc ;; assocs literal into type-desc (reduce (fn [m [file schema-type-vs]] (reduce (fn [m [schema-id {:keys [t-name jsdoc] :as t-options}]] (let [literal (-parse-ast-node (->ast schema-id options) (merge options {:deref-types {schema-id true} :file file :t-options t-options})) jsdoc-literal (->> (concat jsdoc-default jsdoc) (map #(provide-jsdoc % schema-id t-options options)) -jsdoc-literal)] (-> m (assoc-in [schema-id :literal] literal) (assoc-in [schema-id :jsdoc-literal] jsdoc-literal)))) m schema-type-vs)) schema-id->type-desc file->schema-type-vs) {:keys [export-default files-import-alias* file-imports*]} options files (map (fn [[k _]] k) file->schema-type-vs) file->import-literals (reduce (fn [m file] (assoc-in m [file] (map (fn [import-file] (import-literal (path-relative file import-file) (get @files-import-alias* import-file))) (get @file-imports* file)))) {} files) file->type-literals (reduce (fn [m [file scheva-type-vs]] (assoc m file (map (fn [[schema-id _]] (let [{:keys [t-name literal jsdoc-literal export] :as t-options} (get schema-id->type-desc schema-id)] (->type-declaration-str t-name literal jsdoc-literal (merge t-options {:export (if (some? export) export export-default)})))) scheva-type-vs))) {} file->schema-type-vs) file-contents (reduce (fn [m file] (assoc-in m [file] (let [import (string/join "\n" (get file->import-literals file)) types (string/join "\n" (get file->type-literals file))] (str (if-not (string/blank? import) (str import "\n\n")) types)))) {} files)] file-contents)) (defn external-type ([type-name type-path type-import-alias] [any? {::external-type {:t-name type-name :t-path type-path :t-alias type-import-alias}}]) ([type-name type-path] (external-type type-name type-path nil)) ([type-name] (external-type type-name nil nil)))
[ { "context": "\"Tagged data from SICP section 2.4.2\"\n {:author \"Vasily Kolesnikov\"}\n (:require [sicp.common.pairs :as p]))\n\n(defn ", "end": 97, "score": 0.9998140931129456, "start": 80, "tag": "NAME", "value": "Vasily Kolesnikov" } ]
src/sicp/common/tagged_data.clj
justCxx/SICP
90
(ns sicp.common.tagged-data "Tagged data from SICP section 2.4.2" {:author "Vasily Kolesnikov"} (:require [sicp.common.pairs :as p])) (defn attach-tag [type-tag contents] (p/cons type-tag contents)) (defn tag [item] (p/car item)) (defn contents [item] (p/cdr item))
5730
(ns sicp.common.tagged-data "Tagged data from SICP section 2.4.2" {:author "<NAME>"} (:require [sicp.common.pairs :as p])) (defn attach-tag [type-tag contents] (p/cons type-tag contents)) (defn tag [item] (p/car item)) (defn contents [item] (p/cdr item))
true
(ns sicp.common.tagged-data "Tagged data from SICP section 2.4.2" {:author "PI:NAME:<NAME>END_PI"} (:require [sicp.common.pairs :as p])) (defn attach-tag [type-tag contents] (p/cons type-tag contents)) (defn tag [item] (p/car item)) (defn contents [item] (p/cdr item))
[ { "context": ";; Test routines for monads.clj\n\n;; by Konrad Hinsen\n;; last updated March 28, 2009\n\n;; Copyright (c) ", "end": 52, "score": 0.999865710735321, "start": 39, "tag": "NAME", "value": "Konrad Hinsen" }, { "context": "n\n;; last updated March 28, 2009\n\n;; Copyright (c) Konrad Hinsen, 2008. All rights reserved. The use\n;; and distr", "end": 115, "score": 0.999860405921936, "start": 102, "tag": "NAME", "value": "Konrad Hinsen" } ]
ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/test_contrib/monads.clj
allertonm/Couverjure
3
;; Test routines for monads.clj ;; by Konrad Hinsen ;; last updated March 28, 2009 ;; Copyright (c) Konrad Hinsen, 2008. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns clojure.contrib.test-contrib.monads (:use [clojure.test :only (deftest is are run-tests)] [clojure.contrib.monads :only (with-monad domonad m-lift m-seq m-chain sequence-m maybe-m state-m maybe-t sequence-t)])) (deftest sequence-monad (with-monad sequence-m (are [a b] (= a b) (domonad [x (range 3) y (range 2)] (+ x y)) '(0 1 1 2 2 3) (domonad [x (range 5) y (range (+ 1 x)) :when (= (+ x y) 2)] (list x y)) '((1 1) (2 0)) ((m-lift 2 #(list %1 %2)) (range 3) (range 2)) '((0 0) (0 1) (1 0) (1 1) (2 0) (2 1)) (m-seq (replicate 3 (range 2))) '((0 0 0) (0 0 1) (0 1 0) (0 1 1) (1 0 0) (1 0 1) (1 1 0) (1 1 1)) ((m-chain (replicate 3 range)) 5) '(0 0 0 1 0 0 1 0 1 2) (m-plus (range 3) (range 2)) '(0 1 2 0 1)))) (deftest maybe-monad (with-monad maybe-m (let [m+ (m-lift 2 +) mdiv (fn [x y] (domonad [a x b y :when (not (zero? b))] (/ a b)))] (are [a b] (= a b) (m+ (m-result 1) (m-result 3)) (m-result 4) (mdiv (m-result 1) (m-result 3)) (m-result (/ 1 3)) (m+ 1 (mdiv (m-result 1) (m-result 0))) m-zero (m-plus m-zero (m-result 1) m-zero (m-result 2)) (m-result 1))))) (deftest seq-maybe-monad (with-monad (maybe-t sequence-m) (letfn [(pairs [xs] ((m-lift 2 #(list %1 %2)) xs xs))] (are [a b] (= a b) ((m-lift 1 inc) (for [n (range 10)] (when (odd? n) n))) '(nil 2 nil 4 nil 6 nil 8 nil 10) (pairs (for [n (range 5)] (when (odd? n) n))) '(nil nil (1 1) nil (1 3) nil nil nil (3 1) nil (3 3) nil nil))))) (deftest state-maybe-monad (with-monad (maybe-t state-m) (is (= (for [[a b c d] (list [1 2 3 4] [nil 2 3 4] [ 1 nil 3 4] [nil nil 3 4] [1 2 nil nil])] (let [f (domonad [x (m-plus (m-result a) (m-result b)) y (m-plus (m-result c) (m-result d))] (+ x y))] (f :state))) (list [4 :state] [5 :state] [4 :state] [nil :state] [nil :state]))))) (deftest state-seq-monad (with-monad (sequence-t state-m) (is (= (let [[a b c d] [1 2 10 20] f (domonad [x (m-plus (m-result a) (m-result b)) y (m-plus (m-result c) (m-result d))] (+ x y))] (f :state))) (list [(list 11 21 12 22) :state]))))
86637
;; Test routines for monads.clj ;; by <NAME> ;; last updated March 28, 2009 ;; Copyright (c) <NAME>, 2008. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns clojure.contrib.test-contrib.monads (:use [clojure.test :only (deftest is are run-tests)] [clojure.contrib.monads :only (with-monad domonad m-lift m-seq m-chain sequence-m maybe-m state-m maybe-t sequence-t)])) (deftest sequence-monad (with-monad sequence-m (are [a b] (= a b) (domonad [x (range 3) y (range 2)] (+ x y)) '(0 1 1 2 2 3) (domonad [x (range 5) y (range (+ 1 x)) :when (= (+ x y) 2)] (list x y)) '((1 1) (2 0)) ((m-lift 2 #(list %1 %2)) (range 3) (range 2)) '((0 0) (0 1) (1 0) (1 1) (2 0) (2 1)) (m-seq (replicate 3 (range 2))) '((0 0 0) (0 0 1) (0 1 0) (0 1 1) (1 0 0) (1 0 1) (1 1 0) (1 1 1)) ((m-chain (replicate 3 range)) 5) '(0 0 0 1 0 0 1 0 1 2) (m-plus (range 3) (range 2)) '(0 1 2 0 1)))) (deftest maybe-monad (with-monad maybe-m (let [m+ (m-lift 2 +) mdiv (fn [x y] (domonad [a x b y :when (not (zero? b))] (/ a b)))] (are [a b] (= a b) (m+ (m-result 1) (m-result 3)) (m-result 4) (mdiv (m-result 1) (m-result 3)) (m-result (/ 1 3)) (m+ 1 (mdiv (m-result 1) (m-result 0))) m-zero (m-plus m-zero (m-result 1) m-zero (m-result 2)) (m-result 1))))) (deftest seq-maybe-monad (with-monad (maybe-t sequence-m) (letfn [(pairs [xs] ((m-lift 2 #(list %1 %2)) xs xs))] (are [a b] (= a b) ((m-lift 1 inc) (for [n (range 10)] (when (odd? n) n))) '(nil 2 nil 4 nil 6 nil 8 nil 10) (pairs (for [n (range 5)] (when (odd? n) n))) '(nil nil (1 1) nil (1 3) nil nil nil (3 1) nil (3 3) nil nil))))) (deftest state-maybe-monad (with-monad (maybe-t state-m) (is (= (for [[a b c d] (list [1 2 3 4] [nil 2 3 4] [ 1 nil 3 4] [nil nil 3 4] [1 2 nil nil])] (let [f (domonad [x (m-plus (m-result a) (m-result b)) y (m-plus (m-result c) (m-result d))] (+ x y))] (f :state))) (list [4 :state] [5 :state] [4 :state] [nil :state] [nil :state]))))) (deftest state-seq-monad (with-monad (sequence-t state-m) (is (= (let [[a b c d] [1 2 10 20] f (domonad [x (m-plus (m-result a) (m-result b)) y (m-plus (m-result c) (m-result d))] (+ x y))] (f :state))) (list [(list 11 21 12 22) :state]))))
true
;; Test routines for monads.clj ;; by PI:NAME:<NAME>END_PI ;; last updated March 28, 2009 ;; Copyright (c) PI:NAME:<NAME>END_PI, 2008. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns clojure.contrib.test-contrib.monads (:use [clojure.test :only (deftest is are run-tests)] [clojure.contrib.monads :only (with-monad domonad m-lift m-seq m-chain sequence-m maybe-m state-m maybe-t sequence-t)])) (deftest sequence-monad (with-monad sequence-m (are [a b] (= a b) (domonad [x (range 3) y (range 2)] (+ x y)) '(0 1 1 2 2 3) (domonad [x (range 5) y (range (+ 1 x)) :when (= (+ x y) 2)] (list x y)) '((1 1) (2 0)) ((m-lift 2 #(list %1 %2)) (range 3) (range 2)) '((0 0) (0 1) (1 0) (1 1) (2 0) (2 1)) (m-seq (replicate 3 (range 2))) '((0 0 0) (0 0 1) (0 1 0) (0 1 1) (1 0 0) (1 0 1) (1 1 0) (1 1 1)) ((m-chain (replicate 3 range)) 5) '(0 0 0 1 0 0 1 0 1 2) (m-plus (range 3) (range 2)) '(0 1 2 0 1)))) (deftest maybe-monad (with-monad maybe-m (let [m+ (m-lift 2 +) mdiv (fn [x y] (domonad [a x b y :when (not (zero? b))] (/ a b)))] (are [a b] (= a b) (m+ (m-result 1) (m-result 3)) (m-result 4) (mdiv (m-result 1) (m-result 3)) (m-result (/ 1 3)) (m+ 1 (mdiv (m-result 1) (m-result 0))) m-zero (m-plus m-zero (m-result 1) m-zero (m-result 2)) (m-result 1))))) (deftest seq-maybe-monad (with-monad (maybe-t sequence-m) (letfn [(pairs [xs] ((m-lift 2 #(list %1 %2)) xs xs))] (are [a b] (= a b) ((m-lift 1 inc) (for [n (range 10)] (when (odd? n) n))) '(nil 2 nil 4 nil 6 nil 8 nil 10) (pairs (for [n (range 5)] (when (odd? n) n))) '(nil nil (1 1) nil (1 3) nil nil nil (3 1) nil (3 3) nil nil))))) (deftest state-maybe-monad (with-monad (maybe-t state-m) (is (= (for [[a b c d] (list [1 2 3 4] [nil 2 3 4] [ 1 nil 3 4] [nil nil 3 4] [1 2 nil nil])] (let [f (domonad [x (m-plus (m-result a) (m-result b)) y (m-plus (m-result c) (m-result d))] (+ x y))] (f :state))) (list [4 :state] [5 :state] [4 :state] [nil :state] [nil :state]))))) (deftest state-seq-monad (with-monad (sequence-t state-m) (is (= (let [[a b c d] [1 2 10 20] f (domonad [x (m-plus (m-result a) (m-result b)) y (m-plus (m-result c) (m-result d))] (+ x y))] (f :state))) (list [(list 11 21 12 22) :state]))))
[ { "context": " (utils/get-main-parent))\n\n\n(def window-list-key \"flyer_WindowReferences\")\n\n\n(defn init-window-refs \n \"Initializes our wi", "end": 312, "score": 0.9730815887451172, "start": 290, "tag": "KEY", "value": "flyer_WindowReferences" } ]
src-cljs/flyer/storage.cljs
benzap/flyer.js
35
(ns flyer.storage "includes functions for storing window information. This window information is stored in the parent window under the `window-list-key`." (:require [flyer.utils :as utils])) (declare get-window-refs) (def storage (utils/get-main-parent)) (def window-list-key "flyer_WindowReferences") (defn init-window-refs "Initializes our window references" [] (when (nil? (get-window-refs)) (aset storage window-list-key (set nil)))) (defn get-window-refs "Returns the window references, or an empty set" [] (or (aget storage window-list-key) nil)) (defn insert-window-ref! [window] (init-window-refs) (aset storage window-list-key (conj (get-window-refs) window))) (defn remove-window-ref! [window] (init-window-refs) (aset storage window-list-key (disj (get-window-refs) window)))
49577
(ns flyer.storage "includes functions for storing window information. This window information is stored in the parent window under the `window-list-key`." (:require [flyer.utils :as utils])) (declare get-window-refs) (def storage (utils/get-main-parent)) (def window-list-key "<KEY>") (defn init-window-refs "Initializes our window references" [] (when (nil? (get-window-refs)) (aset storage window-list-key (set nil)))) (defn get-window-refs "Returns the window references, or an empty set" [] (or (aget storage window-list-key) nil)) (defn insert-window-ref! [window] (init-window-refs) (aset storage window-list-key (conj (get-window-refs) window))) (defn remove-window-ref! [window] (init-window-refs) (aset storage window-list-key (disj (get-window-refs) window)))
true
(ns flyer.storage "includes functions for storing window information. This window information is stored in the parent window under the `window-list-key`." (:require [flyer.utils :as utils])) (declare get-window-refs) (def storage (utils/get-main-parent)) (def window-list-key "PI:KEY:<KEY>END_PI") (defn init-window-refs "Initializes our window references" [] (when (nil? (get-window-refs)) (aset storage window-list-key (set nil)))) (defn get-window-refs "Returns the window references, or an empty set" [] (or (aget storage window-list-key) nil)) (defn insert-window-ref! [window] (init-window-refs) (aset storage window-list-key (conj (get-window-refs) window))) (defn remove-window-ref! [window] (init-window-refs) (aset storage window-list-key (disj (get-window-refs) window)))
[ { "context": "value\":\"nil\"}\n;; <=\n\n;; @@\n(def bob {:first-name \"Bob\" :last-name \"Smith\" :age 44 :children [{:age 10, ", "end": 422, "score": 0.9998229146003723, "start": 419, "tag": "NAME", "value": "Bob" }, { "context": "<=\n\n;; @@\n(def bob {:first-name \"Bob\" :last-name \"Smith\" :age 44 :children [{:age 10, :name \"Anna\"} {:age", "end": 441, "score": 0.999669075012207, "start": 436, "tag": "NAME", "value": "Smith" }, { "context": "-name \"Smith\" :age 44 :children [{:age 10, :name \"Anna\"} {:age 6, :name \"Zach\"}] :jobs {:main \"Barrista\"", "end": 483, "score": 0.9996961951255798, "start": 479, "tag": "NAME", "value": "Anna" }, { "context": "children [{:age 10, :name \"Anna\"} {:age 6, :name \"Zach\"}] :jobs {:main \"Barrista\"} :address {:street1 \"1", "end": 506, "score": 0.9996718168258667, "start": 502, "tag": "NAME", "value": "Zach" }, { "context": ";CA&quot;},\n;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :l", "end": 899, "score": 0.9992786049842834, "start": 895, "tag": "NAME", "value": "Anna" }, { "context": " 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; ", "end": 932, "score": 0.999176025390625, "start": 928, "tag": "NAME", "value": "Zach" }, { "context": ", :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&q", "end": 969, "score": 0.9996975660324097, "start": 964, "tag": "NAME", "value": "Smith" }, { "context": "Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&quot;,\n;;; :jobs {:main &quot;Barrista&quot;}}\n;", "end": 1017, "score": 0.9998533725738525, "start": 1014, "tag": "NAME", "value": "Bob" }, { "context": "; @@\n(show-examples\n (assoc-in bob [:last-name] \"Jones\") ; change a field, just like assoc\n (assoc-in b", "end": 1343, "score": 0.9996719360351562, "start": 1338, "tag": "NAME", "value": "Jones" }, { "context": "@\n;; ->\n;;; &gt; (assoc-in bob [:last-name] &quot;Jones&quot;)\n;;; {:address {:street1 &quot;123 Anystree", "end": 1577, "score": 0.9995758533477783, "start": 1572, "tag": "NAME", "value": "Jones" }, { "context": ";CA&quot;},\n;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :l", "end": 1729, "score": 0.9995070695877075, "start": 1725, "tag": "NAME", "value": "Anna" }, { "context": " 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :last-name &quot;Jones&quot;,\n;;; ", "end": 1762, "score": 0.9987365007400513, "start": 1758, "tag": "NAME", "value": "Zach" }, { "context": ", :name &quot;Zach&quot;}],\n;;; :last-name &quot;Jones&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&q", "end": 1799, "score": 0.9996916055679321, "start": 1794, "tag": "NAME", "value": "Jones" }, { "context": "Jones&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&quot;,\n;;; :jobs {:main &quot;Barrista&quot;}}\n;", "end": 1847, "score": 0.999609649181366, "start": 1844, "tag": "NAME", "value": "Bob" }, { "context": "029&quot;},\n;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :l", "end": 2145, "score": 0.9991750717163086, "start": 2141, "tag": "NAME", "value": "Anna" }, { "context": " 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; ", "end": 2178, "score": 0.9978281259536743, "start": 2174, "tag": "NAME", "value": "Zach" }, { "context": ", :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&q", "end": 2215, "score": 0.9996508955955505, "start": 2210, "tag": "NAME", "value": "Smith" }, { "context": "Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&quot;,\n;;; :jobs {:main &quot;Barrista&quot;}}\n;", "end": 2263, "score": 0.9997841715812683, "start": 2260, "tag": "NAME", "value": "Bob" }, { "context": ";CA&quot;},\n;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :l", "end": 2518, "score": 0.9990471601486206, "start": 2514, "tag": "NAME", "value": "Anna" }, { "context": " 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; ", "end": 2551, "score": 0.9942296147346497, "start": 2547, "tag": "NAME", "value": "Zach" }, { "context": ", :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&q", "end": 2588, "score": 0.9997228980064392, "start": 2583, "tag": "NAME", "value": "Smith" }, { "context": "Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&quot;,\n;;; :jobs {:main &quot;Barrista&quot;},\n;", "end": 2636, "score": 0.9990869760513306, "start": 2633, "tag": "NAME", "value": "Bob" }, { "context": "ow-examples\n (assoc-in bob [:children 2] {:name \"Jimmy\" :age 0}) ; when vector already exists, an elemen", "end": 2949, "score": 0.9995589256286621, "start": 2944, "tag": "NAME", "value": "Jimmy" }, { "context": "ent is added\n (assoc-in bob [:friends 0] {:name \"Jerry\"})) ; when auto-creating paths, uses a map instea", "end": 3052, "score": 0.9996142387390137, "start": 3047, "tag": "NAME", "value": "Jerry" }, { "context": ";;; &gt; (assoc-in bob [:children 2] {:name &quot;Jimmy&quot;, :age 0})\n;;; {:address {:street1 &quot;123", "end": 3183, "score": 0.9993748068809509, "start": 3178, "tag": "NAME", "value": "Jimmy" }, { "context": "uot;},\n;;; :children\n;;; [{:age 10, :name &quot;Anna&quot;}\n;;; {:age 6, :name &quot;Zach&quot;}\n;;;", "end": 3349, "score": 0.998863935470581, "start": 3345, "tag": "NAME", "value": "Anna" }, { "context": "name &quot;Anna&quot;}\n;;; {:age 6, :name &quot;Zach&quot;}\n;;; {:age 0, :name &quot;Jimmy&quot;}],\n", "end": 3388, "score": 0.9915827512741089, "start": 3384, "tag": "NAME", "value": "Zach" }, { "context": "name &quot;Zach&quot;}\n;;; {:age 0, :name &quot;Jimmy&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; ", "end": 3428, "score": 0.9993965029716492, "start": 3423, "tag": "NAME", "value": "Jimmy" }, { "context": " :name &quot;Jimmy&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&q", "end": 3465, "score": 0.9996796250343323, "start": 3460, "tag": "NAME", "value": "Smith" }, { "context": "Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&quot;,\n;;; :jobs {:main &quot;Barrista&quot;}}\n;", "end": 3513, "score": 0.9994223713874817, "start": 3510, "tag": "NAME", "value": "Bob" }, { "context": "\n;;; &gt; (assoc-in bob [:friends 0] {:name &quot;Jerry&quot;})\n;;; {:address {:street1 &quot;123 Anystre", "end": 3616, "score": 0.9993511438369751, "start": 3611, "tag": "NAME", "value": "Jerry" }, { "context": ";CA&quot;},\n;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :l", "end": 3769, "score": 0.996451735496521, "start": 3765, "tag": "NAME", "value": "Anna" }, { "context": " 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; ", "end": 3802, "score": 0.8665957450866699, "start": 3798, "tag": "NAME", "value": "Zach" }, { "context": ", :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&q", "end": 3839, "score": 0.9997344017028809, "start": 3834, "tag": "NAME", "value": "Smith" }, { "context": "Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&quot;,\n;;; :jobs {:main &quot;Barrista&quot;},\n;", "end": 3887, "score": 0.9997615218162537, "start": 3884, "tag": "NAME", "value": "Bob" }, { "context": "ot;Barrista&quot;},\n;;; :friends {0 {:name &quot;Jerry&quot;}}}\n;;; \n;; <-\n;; =>\n;;; {\"type\":\"html\",\"con", "end": 3971, "score": 0.9996895790100098, "start": 3966, "tag": "NAME", "value": "Jerry" }, { "context": ";CA&quot;},\n;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :l", "end": 4544, "score": 0.9990545511245728, "start": 4540, "tag": "NAME", "value": "Anna" }, { "context": " 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; ", "end": 4577, "score": 0.995557427406311, "start": 4573, "tag": "NAME", "value": "Zach" }, { "context": ", :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;BOB&q", "end": 4614, "score": 0.9997060894966125, "start": 4609, "tag": "NAME", "value": "Smith" }, { "context": "Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;BOB&quot;,\n;;; :jobs {:main &quot;Barrista&quot;}}\n;", "end": 4662, "score": 0.9995086193084717, "start": 4659, "tag": "NAME", "value": "BOB" }, { "context": ";CA&quot;},\n;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :l", "end": 4891, "score": 0.9991389513015747, "start": 4887, "tag": "NAME", "value": "Anna" }, { "context": " 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; ", "end": 4924, "score": 0.996369481086731, "start": 4920, "tag": "NAME", "value": "Zach" }, { "context": ", :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; :age 45,\n;;; :first-name &quot;Bob&q", "end": 4961, "score": 0.9997295141220093, "start": 4956, "tag": "NAME", "value": "Smith" }, { "context": "Smith&quot;,\n;;; :age 45,\n;;; :first-name &quot;Bob&quot;,\n;;; :jobs {:main &quot;Barrista&quot;}}\n;", "end": 5009, "score": 0.9998010993003845, "start": 5006, "tag": "NAME", "value": "Bob" }, { "context": ";CA&quot;},\n;;; :children [{:age 11, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :l", "end": 5250, "score": 0.9995830059051514, "start": 5246, "tag": "NAME", "value": "Anna" }, { "context": " 11, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; ", "end": 5283, "score": 0.9994419813156128, "start": 5279, "tag": "NAME", "value": "Zach" }, { "context": ", :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&q", "end": 5320, "score": 0.9997183084487915, "start": 5315, "tag": "NAME", "value": "Smith" }, { "context": "Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&quot;,\n;;; :jobs {:main &quot;Barrista&quot;}}\n;", "end": 5368, "score": 0.9997206330299377, "start": 5365, "tag": "NAME", "value": "Bob" }, { "context": "rst-name &quot;Bob&quot;,\n;;; :jobs {:main &quot;Barrista&quot;}}\n;;; \n;; <-\n;; =>\n;;; {\"type\":\"html\",\"cont", "end": 5408, "score": 0.9917495846748352, "start": 5400, "tag": "NAME", "value": "Barrista" }, { "context": ";CA&quot;},\n;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :l", "end": 6751, "score": 0.9994620084762573, "start": 6747, "tag": "NAME", "value": "Anna" }, { "context": " 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; ", "end": 6784, "score": 0.9991809129714966, "start": 6780, "tag": "NAME", "value": "Zach" }, { "context": ", :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; :age 44,\n;;; :jobs {:main &quot;Barr", "end": 6821, "score": 0.9996707439422607, "start": 6816, "tag": "NAME", "value": "Smith" }, { "context": "mith&quot;,\n;;; :age 44,\n;;; :jobs {:main &quot;Barrista&quot;}}\n;;; &gt; (dissoc-in bob [:jobs :main])\n;;", "end": 6875, "score": 0.9885701537132263, "start": 6867, "tag": "NAME", "value": "Barrista" }, { "context": ";CA&quot;},\n;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :l", "end": 7067, "score": 0.9995373487472534, "start": 7063, "tag": "NAME", "value": "Anna" }, { "context": " 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; ", "end": 7100, "score": 0.998986005783081, "start": 7096, "tag": "NAME", "value": "Zach" }, { "context": ", :name &quot;Zach&quot;}],\n;;; :last-name &quot;Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&q", "end": 7137, "score": 0.999656617641449, "start": 7132, "tag": "NAME", "value": "Smith" }, { "context": "Smith&quot;,\n;;; :age 44,\n;;; :first-name &quot;Bob&quot;}\n;;; \n;; <-\n;; =>\n;;; {\"type\":\"html\",\"conte", "end": 7185, "score": 0.9996595978736877, "start": 7182, "tag": "NAME", "value": "Bob" } ]
ws/d08_maps2.clj
justone/cljplay
1
;; gorilla-repl.fileformat = 1 ;; ** ;;; # Maps 2 ;;; ;;; More on maps, focusing on nested maps. ;; ** ;; @@ (ns d08-maps2 (:require [cljplay.core :refer [show-examples]] [clojure.pprint :refer [pprint] :rename {pprint pp}] [clojure.string :refer [upper-case]])) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; @@ (def bob {:first-name "Bob" :last-name "Smith" :age 44 :children [{:age 10, :name "Anna"} {:age 6, :name "Zach"}] :jobs {:main "Barrista"} :address {:street1 "123 Anystreet" :city "Anytown" :state "CA"}}) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-var'>#&#x27;d08-maps2/bob</span>","value":"#'d08-maps2/bob"} ;; <= ;; @@ (pp bob) ;; @@ ;; -> ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}], ;;; :last-name &quot;Smith&quot;, ;;; :age 44, ;;; :first-name &quot;Bob&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; ** ;;; [assoc-in](http://clojuredocs.org/clojure.core/assoc-in) is used to set an arbitrarily nested field. ;; ** ;; @@ (show-examples (assoc-in bob [:last-name] "Jones") ; change a field, just like assoc (assoc-in bob [:address :zip] "91029") ; change nested map (assoc-in bob [:prefs :browser] "Firefox")) ; makes paths that don't exist ;; @@ ;; -> ;;; &gt; (assoc-in bob [:last-name] &quot;Jones&quot;) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}], ;;; :last-name &quot;Jones&quot;, ;;; :age 44, ;;; :first-name &quot;Bob&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (assoc-in bob [:address :zip] &quot;91029&quot;) ;;; {:address ;;; {:street1 &quot;123 Anystreet&quot;, ;;; :city &quot;Anytown&quot;, ;;; :state &quot;CA&quot;, ;;; :zip &quot;91029&quot;}, ;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}], ;;; :last-name &quot;Smith&quot;, ;;; :age 44, ;;; :first-name &quot;Bob&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (assoc-in bob [:prefs :browser] &quot;Firefox&quot;) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}], ;;; :last-name &quot;Smith&quot;, ;;; :age 44, ;;; :first-name &quot;Bob&quot;, ;;; :jobs {:main &quot;Barrista&quot;}, ;;; :prefs {:browser &quot;Firefox&quot;}} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; ** ;;; `assoc-in` also works with vectors. ;; ** ;; @@ (show-examples (assoc-in bob [:children 2] {:name "Jimmy" :age 0}) ; when vector already exists, an element is added (assoc-in bob [:friends 0] {:name "Jerry"})) ; when auto-creating paths, uses a map instead of a vector ;; @@ ;; -> ;;; &gt; (assoc-in bob [:children 2] {:name &quot;Jimmy&quot;, :age 0}) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children ;;; [{:age 10, :name &quot;Anna&quot;} ;;; {:age 6, :name &quot;Zach&quot;} ;;; {:age 0, :name &quot;Jimmy&quot;}], ;;; :last-name &quot;Smith&quot;, ;;; :age 44, ;;; :first-name &quot;Bob&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (assoc-in bob [:friends 0] {:name &quot;Jerry&quot;}) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}], ;;; :last-name &quot;Smith&quot;, ;;; :age 44, ;;; :first-name &quot;Bob&quot;, ;;; :jobs {:main &quot;Barrista&quot;}, ;;; :friends {0 {:name &quot;Jerry&quot;}}} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; ** ;;; To update an element with a function, use [update-in](http://clojuredocs.org/clojure.core/update-in): ;; ** ;; @@ (show-examples (update-in bob [:first-name] upper-case) (update-in bob [:age] inc) (update-in bob [:children 0 :age] inc)) ;; @@ ;; -> ;;; &gt; (update-in bob [:first-name] upper-case) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}], ;;; :last-name &quot;Smith&quot;, ;;; :age 44, ;;; :first-name &quot;BOB&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (update-in bob [:age] inc) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}], ;;; :last-name &quot;Smith&quot;, ;;; :age 45, ;;; :first-name &quot;Bob&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (update-in bob [:children 0 :age] inc) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 11, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}], ;;; :last-name &quot;Smith&quot;, ;;; :age 44, ;;; :first-name &quot;Bob&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; ** ;;; Curiously, there is no `dissoc-in` in the standard library. I found [one](https://github.com/clojure/core.incubator/blob/master/src/main/clojure/clojure/core/incubator.clj#L62) over in [core.incubator](https://github.com/clojure/core.incubator), which seems to be a place where experimental features are implemented and then merged into core when they mature. ;; ** ;; @@ (defn dissoc-in "Dissociates an entry from a nested associative structure returning a new nested structure. keys is a sequence of keys. Any empty maps that result will not be present in the new structure." [m [k & ks :as keys]] (if ks (if-let [nextmap (get m k)] (let [newmap (dissoc-in nextmap ks)] (if (seq newmap) (assoc m k newmap) (dissoc m k))) m) (dissoc m k))) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-var'>#&#x27;d08-maps2/dissoc-in</span>","value":"#'d08-maps2/dissoc-in"} ;; <= ;; @@ (show-examples (dissoc-in bob [:first-name]) (dissoc-in bob [:jobs :main])) ;; @@ ;; -> ;;; &gt; (dissoc-in bob [:first-name]) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}], ;;; :last-name &quot;Smith&quot;, ;;; :age 44, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (dissoc-in bob [:jobs :main]) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;Anna&quot;} {:age 6, :name &quot;Zach&quot;}], ;;; :last-name &quot;Smith&quot;, ;;; :age 44, ;;; :first-name &quot;Bob&quot;} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <=
534
;; gorilla-repl.fileformat = 1 ;; ** ;;; # Maps 2 ;;; ;;; More on maps, focusing on nested maps. ;; ** ;; @@ (ns d08-maps2 (:require [cljplay.core :refer [show-examples]] [clojure.pprint :refer [pprint] :rename {pprint pp}] [clojure.string :refer [upper-case]])) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; @@ (def bob {:first-name "<NAME>" :last-name "<NAME>" :age 44 :children [{:age 10, :name "<NAME>"} {:age 6, :name "<NAME>"}] :jobs {:main "Barrista"} :address {:street1 "123 Anystreet" :city "Anytown" :state "CA"}}) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-var'>#&#x27;d08-maps2/bob</span>","value":"#'d08-maps2/bob"} ;; <= ;; @@ (pp bob) ;; @@ ;; -> ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;<NAME>&quot;} {:age 6, :name &quot;<NAME>&quot;}], ;;; :last-name &quot;<NAME>&quot;, ;;; :age 44, ;;; :first-name &quot;<NAME>&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; ** ;;; [assoc-in](http://clojuredocs.org/clojure.core/assoc-in) is used to set an arbitrarily nested field. ;; ** ;; @@ (show-examples (assoc-in bob [:last-name] "<NAME>") ; change a field, just like assoc (assoc-in bob [:address :zip] "91029") ; change nested map (assoc-in bob [:prefs :browser] "Firefox")) ; makes paths that don't exist ;; @@ ;; -> ;;; &gt; (assoc-in bob [:last-name] &quot;<NAME>&quot;) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;<NAME>&quot;} {:age 6, :name &quot;<NAME>&quot;}], ;;; :last-name &quot;<NAME>&quot;, ;;; :age 44, ;;; :first-name &quot;<NAME>&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (assoc-in bob [:address :zip] &quot;91029&quot;) ;;; {:address ;;; {:street1 &quot;123 Anystreet&quot;, ;;; :city &quot;Anytown&quot;, ;;; :state &quot;CA&quot;, ;;; :zip &quot;91029&quot;}, ;;; :children [{:age 10, :name &quot;<NAME>&quot;} {:age 6, :name &quot;<NAME>&quot;}], ;;; :last-name &quot;<NAME>&quot;, ;;; :age 44, ;;; :first-name &quot;<NAME>&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (assoc-in bob [:prefs :browser] &quot;Firefox&quot;) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;<NAME>&quot;} {:age 6, :name &quot;<NAME>&quot;}], ;;; :last-name &quot;<NAME>&quot;, ;;; :age 44, ;;; :first-name &quot;<NAME>&quot;, ;;; :jobs {:main &quot;Barrista&quot;}, ;;; :prefs {:browser &quot;Firefox&quot;}} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; ** ;;; `assoc-in` also works with vectors. ;; ** ;; @@ (show-examples (assoc-in bob [:children 2] {:name "<NAME>" :age 0}) ; when vector already exists, an element is added (assoc-in bob [:friends 0] {:name "<NAME>"})) ; when auto-creating paths, uses a map instead of a vector ;; @@ ;; -> ;;; &gt; (assoc-in bob [:children 2] {:name &quot;<NAME>&quot;, :age 0}) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children ;;; [{:age 10, :name &quot;<NAME>&quot;} ;;; {:age 6, :name &quot;<NAME>&quot;} ;;; {:age 0, :name &quot;<NAME>&quot;}], ;;; :last-name &quot;<NAME>&quot;, ;;; :age 44, ;;; :first-name &quot;<NAME>&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (assoc-in bob [:friends 0] {:name &quot;<NAME>&quot;}) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;<NAME>&quot;} {:age 6, :name &quot;<NAME>&quot;}], ;;; :last-name &quot;<NAME>&quot;, ;;; :age 44, ;;; :first-name &quot;<NAME>&quot;, ;;; :jobs {:main &quot;Barrista&quot;}, ;;; :friends {0 {:name &quot;<NAME>&quot;}}} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; ** ;;; To update an element with a function, use [update-in](http://clojuredocs.org/clojure.core/update-in): ;; ** ;; @@ (show-examples (update-in bob [:first-name] upper-case) (update-in bob [:age] inc) (update-in bob [:children 0 :age] inc)) ;; @@ ;; -> ;;; &gt; (update-in bob [:first-name] upper-case) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;<NAME>&quot;} {:age 6, :name &quot;<NAME>&quot;}], ;;; :last-name &quot;<NAME>&quot;, ;;; :age 44, ;;; :first-name &quot;<NAME>&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (update-in bob [:age] inc) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;<NAME>&quot;} {:age 6, :name &quot;<NAME>&quot;}], ;;; :last-name &quot;<NAME>&quot;, ;;; :age 45, ;;; :first-name &quot;<NAME>&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (update-in bob [:children 0 :age] inc) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 11, :name &quot;<NAME>&quot;} {:age 6, :name &quot;<NAME>&quot;}], ;;; :last-name &quot;<NAME>&quot;, ;;; :age 44, ;;; :first-name &quot;<NAME>&quot;, ;;; :jobs {:main &quot;<NAME>&quot;}} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; ** ;;; Curiously, there is no `dissoc-in` in the standard library. I found [one](https://github.com/clojure/core.incubator/blob/master/src/main/clojure/clojure/core/incubator.clj#L62) over in [core.incubator](https://github.com/clojure/core.incubator), which seems to be a place where experimental features are implemented and then merged into core when they mature. ;; ** ;; @@ (defn dissoc-in "Dissociates an entry from a nested associative structure returning a new nested structure. keys is a sequence of keys. Any empty maps that result will not be present in the new structure." [m [k & ks :as keys]] (if ks (if-let [nextmap (get m k)] (let [newmap (dissoc-in nextmap ks)] (if (seq newmap) (assoc m k newmap) (dissoc m k))) m) (dissoc m k))) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-var'>#&#x27;d08-maps2/dissoc-in</span>","value":"#'d08-maps2/dissoc-in"} ;; <= ;; @@ (show-examples (dissoc-in bob [:first-name]) (dissoc-in bob [:jobs :main])) ;; @@ ;; -> ;;; &gt; (dissoc-in bob [:first-name]) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;<NAME>&quot;} {:age 6, :name &quot;<NAME>&quot;}], ;;; :last-name &quot;<NAME>&quot;, ;;; :age 44, ;;; :jobs {:main &quot;<NAME>&quot;}} ;;; &gt; (dissoc-in bob [:jobs :main]) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;<NAME>&quot;} {:age 6, :name &quot;<NAME>&quot;}], ;;; :last-name &quot;<NAME>&quot;, ;;; :age 44, ;;; :first-name &quot;<NAME>&quot;} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <=
true
;; gorilla-repl.fileformat = 1 ;; ** ;;; # Maps 2 ;;; ;;; More on maps, focusing on nested maps. ;; ** ;; @@ (ns d08-maps2 (:require [cljplay.core :refer [show-examples]] [clojure.pprint :refer [pprint] :rename {pprint pp}] [clojure.string :refer [upper-case]])) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; @@ (def bob {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age 44 :children [{:age 10, :name "PI:NAME:<NAME>END_PI"} {:age 6, :name "PI:NAME:<NAME>END_PI"}] :jobs {:main "Barrista"} :address {:street1 "123 Anystreet" :city "Anytown" :state "CA"}}) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-var'>#&#x27;d08-maps2/bob</span>","value":"#'d08-maps2/bob"} ;; <= ;; @@ (pp bob) ;; @@ ;; -> ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;PI:NAME:<NAME>END_PI&quot;} {:age 6, :name &quot;PI:NAME:<NAME>END_PI&quot;}], ;;; :last-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :age 44, ;;; :first-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; ** ;;; [assoc-in](http://clojuredocs.org/clojure.core/assoc-in) is used to set an arbitrarily nested field. ;; ** ;; @@ (show-examples (assoc-in bob [:last-name] "PI:NAME:<NAME>END_PI") ; change a field, just like assoc (assoc-in bob [:address :zip] "91029") ; change nested map (assoc-in bob [:prefs :browser] "Firefox")) ; makes paths that don't exist ;; @@ ;; -> ;;; &gt; (assoc-in bob [:last-name] &quot;PI:NAME:<NAME>END_PI&quot;) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;PI:NAME:<NAME>END_PI&quot;} {:age 6, :name &quot;PI:NAME:<NAME>END_PI&quot;}], ;;; :last-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :age 44, ;;; :first-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (assoc-in bob [:address :zip] &quot;91029&quot;) ;;; {:address ;;; {:street1 &quot;123 Anystreet&quot;, ;;; :city &quot;Anytown&quot;, ;;; :state &quot;CA&quot;, ;;; :zip &quot;91029&quot;}, ;;; :children [{:age 10, :name &quot;PI:NAME:<NAME>END_PI&quot;} {:age 6, :name &quot;PI:NAME:<NAME>END_PI&quot;}], ;;; :last-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :age 44, ;;; :first-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (assoc-in bob [:prefs :browser] &quot;Firefox&quot;) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;PI:NAME:<NAME>END_PI&quot;} {:age 6, :name &quot;PI:NAME:<NAME>END_PI&quot;}], ;;; :last-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :age 44, ;;; :first-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :jobs {:main &quot;Barrista&quot;}, ;;; :prefs {:browser &quot;Firefox&quot;}} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; ** ;;; `assoc-in` also works with vectors. ;; ** ;; @@ (show-examples (assoc-in bob [:children 2] {:name "PI:NAME:<NAME>END_PI" :age 0}) ; when vector already exists, an element is added (assoc-in bob [:friends 0] {:name "PI:NAME:<NAME>END_PI"})) ; when auto-creating paths, uses a map instead of a vector ;; @@ ;; -> ;;; &gt; (assoc-in bob [:children 2] {:name &quot;PI:NAME:<NAME>END_PI&quot;, :age 0}) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children ;;; [{:age 10, :name &quot;PI:NAME:<NAME>END_PI&quot;} ;;; {:age 6, :name &quot;PI:NAME:<NAME>END_PI&quot;} ;;; {:age 0, :name &quot;PI:NAME:<NAME>END_PI&quot;}], ;;; :last-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :age 44, ;;; :first-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (assoc-in bob [:friends 0] {:name &quot;PI:NAME:<NAME>END_PI&quot;}) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;PI:NAME:<NAME>END_PI&quot;} {:age 6, :name &quot;PI:NAME:<NAME>END_PI&quot;}], ;;; :last-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :age 44, ;;; :first-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :jobs {:main &quot;Barrista&quot;}, ;;; :friends {0 {:name &quot;PI:NAME:<NAME>END_PI&quot;}}} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; ** ;;; To update an element with a function, use [update-in](http://clojuredocs.org/clojure.core/update-in): ;; ** ;; @@ (show-examples (update-in bob [:first-name] upper-case) (update-in bob [:age] inc) (update-in bob [:children 0 :age] inc)) ;; @@ ;; -> ;;; &gt; (update-in bob [:first-name] upper-case) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;PI:NAME:<NAME>END_PI&quot;} {:age 6, :name &quot;PI:NAME:<NAME>END_PI&quot;}], ;;; :last-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :age 44, ;;; :first-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (update-in bob [:age] inc) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;PI:NAME:<NAME>END_PI&quot;} {:age 6, :name &quot;PI:NAME:<NAME>END_PI&quot;}], ;;; :last-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :age 45, ;;; :first-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :jobs {:main &quot;Barrista&quot;}} ;;; &gt; (update-in bob [:children 0 :age] inc) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 11, :name &quot;PI:NAME:<NAME>END_PI&quot;} {:age 6, :name &quot;PI:NAME:<NAME>END_PI&quot;}], ;;; :last-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :age 44, ;;; :first-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :jobs {:main &quot;PI:NAME:<NAME>END_PI&quot;}} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; ** ;;; Curiously, there is no `dissoc-in` in the standard library. I found [one](https://github.com/clojure/core.incubator/blob/master/src/main/clojure/clojure/core/incubator.clj#L62) over in [core.incubator](https://github.com/clojure/core.incubator), which seems to be a place where experimental features are implemented and then merged into core when they mature. ;; ** ;; @@ (defn dissoc-in "Dissociates an entry from a nested associative structure returning a new nested structure. keys is a sequence of keys. Any empty maps that result will not be present in the new structure." [m [k & ks :as keys]] (if ks (if-let [nextmap (get m k)] (let [newmap (dissoc-in nextmap ks)] (if (seq newmap) (assoc m k newmap) (dissoc m k))) m) (dissoc m k))) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-var'>#&#x27;d08-maps2/dissoc-in</span>","value":"#'d08-maps2/dissoc-in"} ;; <= ;; @@ (show-examples (dissoc-in bob [:first-name]) (dissoc-in bob [:jobs :main])) ;; @@ ;; -> ;;; &gt; (dissoc-in bob [:first-name]) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;PI:NAME:<NAME>END_PI&quot;} {:age 6, :name &quot;PI:NAME:<NAME>END_PI&quot;}], ;;; :last-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :age 44, ;;; :jobs {:main &quot;PI:NAME:<NAME>END_PI&quot;}} ;;; &gt; (dissoc-in bob [:jobs :main]) ;;; {:address {:street1 &quot;123 Anystreet&quot;, :city &quot;Anytown&quot;, :state &quot;CA&quot;}, ;;; :children [{:age 10, :name &quot;PI:NAME:<NAME>END_PI&quot;} {:age 6, :name &quot;PI:NAME:<NAME>END_PI&quot;}], ;;; :last-name &quot;PI:NAME:<NAME>END_PI&quot;, ;;; :age 44, ;;; :first-name &quot;PI:NAME:<NAME>END_PI&quot;} ;;; ;; <- ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <=
[ { "context": "s\n; Date: February 11, 2016.\n; Authors:\n; A01371743 Luis E. Ballinas Aguilar\n;-----------------------", "end": 153, "score": 0.9916777014732361, "start": 144, "tag": "USERNAME", "value": "A01371743" }, { "context": "February 11, 2016.\n; Authors:\n; A01371743 Luis E. Ballinas Aguilar\n;------------------------------------------------", "end": 178, "score": 0.9997313022613525, "start": 154, "tag": "NAME", "value": "Luis E. Ballinas Aguilar" } ]
higherorder.clj
lu15v/TC2006
0
;---------------------------------------------------------- ; Activity: Higher-Order Functions ; Date: February 11, 2016. ; Authors: ; A01371743 Luis E. Ballinas Aguilar ;---------------------------------------------------------- (use 'clojure.test) (defn my-map-indexed " It returns a list consisting of the result of applying f to 0 and the first item of lst, followed by applying f to 1 and the second item in lst, and so on until lst is exhausted. " [f lst] (loop [l1 lst result () x 0] (if (empty? l1) (reverse result) (recur (rest l1) (cons (f x (first l1))result)(inc x))))) (defn my-drop-while "akes two arguments: a function f and a list lst. It returns a list of items from lst dropping the initial items that evaluate to true when passed to f. Once a false value is encountered, the rest of the list is returned. Function f should accept one argument. Do not use the predefined drop-while function." [f lst] (loop [result () l1 lst] (if (empty? l1) result (if (f (first l1)) (recur () (rest l1)) (concat result l1))))) (defn aprox= "Checks if x is approximately equal to y. Returns true if |x - y| < epsilon, or false otherwise." [epsilon x y] (< (Math/abs (- x y)) epsilon)) (defn bisection "is a root-finding algorithm which works by repeatedly dividing an interval in half and then selecting the subinterval in which the root exists" [a b f] (loop [a a b b c (/(+ a b) 2.0)] (if (< (Math/abs (f c)) 1.0E-15) c (if (<(* (f a) (f c)) 0) (recur a c (/(+ a b) 2.0)) (recur c b (/(+ a b) 2.0)))))) (defn deriv "returns a new function that takes x as argument, and which represents the derivate of f given a certain value for h." [f h] (fn [x] (/(- (f (+ x h)) (f x)) h))) (defn integral "Calculates the Simpson's Rule" [a b n f] (loop [k 0 aprox 0] (let [ h (/(- b a)n) multEven 2 multOdd 4] (if (= k n) (/(*( + aprox (f (+ a (* k h))))h)3) (if(zero? k) (recur (inc k) (+ aprox (f (+ a (* k h))))) (if(even? k) (recur (inc k) (+ aprox (* (f (+ a (* k h))) multEven))) (recur (inc k) (+ aprox (* (f (+ a (* k h))) multOdd))))))))) (defn drops [lst n] (loop [l1 lst result () k 1] (if (empty? l1) result (if (not= k n) (recur (rest l1) (cons (first l1) result) (inc k)) (recur (rest l1) result 1))))) (deftest test-my-map-indexed (is (= () (my-map-indexed vector ()))) (is (= '([0 a] [1 b] [2 c] [3 d]) (my-map-indexed vector '(a b c d)))) (is (= '(10 4 -2 8 5 5 13) (my-map-indexed + '(10 3 -4 5 1 0 7)))) (is (= '(0 1 -4 3 1 0 6) (my-map-indexed min '(10 3 -4 5 1 0 7))))) (deftest test-my-drop-while (is (= () (my-drop-while neg? ()))) (is (= '(0 1 2 3 4) (my-drop-while neg? '(-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4)))) (is (= '(2 three 4 five) (my-drop-while symbol? '(zero one 2 three 4 five)))) (is (= '(0 one 2 three 4 five) (my-drop-while symbol? '(0 one 2 three 4 five))))) (deftest test-bisection (is (aprox= 0.0001 3.0 (bisection 1 4 (fn [x] (* (- x 3) (+ x 4)))))) (is (aprox= 0.0001 -4.0 (bisection -5 0 (fn [x] (* (- x 3) (+ x 4)))))) (is (aprox= 0.0001 Math/PI (bisection 1 4 (fn [x] (Math/sin x))))) (is (aprox= 0.0001 (* 2 Math/PI) (bisection 5 10 (fn [x] (Math/sin x))))) (is (aprox= 0.0001 1.618033988749895 (bisection 1 2 (fn [x] (- (* x x) x 1))))) (is (aprox= 0.0001 -0.6180339887498948 (bisection -10 1 (fn [x] (- (* x x) x 1)))))) (defn f [x] (* x x x)) (def df (deriv f 0.001)) (def ddf (deriv df 0.001)) (def dddf (deriv ddf 0.001)) (deftest test-deriv (is (aprox= 0.05 75 (df 5))) (is (aprox= 0.05 30 (ddf 5))) (is (aprox= 0.05 6 (dddf 5)))) (deftest test-integral (is (= 1/4 (integral 0 1 10 (fn [x] (* x x x))))) (is (= 21/4 (integral 1 2 10 (fn [x] (integral 3 4 10 (fn [y] (* x y)))))))) (run-tests)
99239
;---------------------------------------------------------- ; Activity: Higher-Order Functions ; Date: February 11, 2016. ; Authors: ; A01371743 <NAME> ;---------------------------------------------------------- (use 'clojure.test) (defn my-map-indexed " It returns a list consisting of the result of applying f to 0 and the first item of lst, followed by applying f to 1 and the second item in lst, and so on until lst is exhausted. " [f lst] (loop [l1 lst result () x 0] (if (empty? l1) (reverse result) (recur (rest l1) (cons (f x (first l1))result)(inc x))))) (defn my-drop-while "akes two arguments: a function f and a list lst. It returns a list of items from lst dropping the initial items that evaluate to true when passed to f. Once a false value is encountered, the rest of the list is returned. Function f should accept one argument. Do not use the predefined drop-while function." [f lst] (loop [result () l1 lst] (if (empty? l1) result (if (f (first l1)) (recur () (rest l1)) (concat result l1))))) (defn aprox= "Checks if x is approximately equal to y. Returns true if |x - y| < epsilon, or false otherwise." [epsilon x y] (< (Math/abs (- x y)) epsilon)) (defn bisection "is a root-finding algorithm which works by repeatedly dividing an interval in half and then selecting the subinterval in which the root exists" [a b f] (loop [a a b b c (/(+ a b) 2.0)] (if (< (Math/abs (f c)) 1.0E-15) c (if (<(* (f a) (f c)) 0) (recur a c (/(+ a b) 2.0)) (recur c b (/(+ a b) 2.0)))))) (defn deriv "returns a new function that takes x as argument, and which represents the derivate of f given a certain value for h." [f h] (fn [x] (/(- (f (+ x h)) (f x)) h))) (defn integral "Calculates the Simpson's Rule" [a b n f] (loop [k 0 aprox 0] (let [ h (/(- b a)n) multEven 2 multOdd 4] (if (= k n) (/(*( + aprox (f (+ a (* k h))))h)3) (if(zero? k) (recur (inc k) (+ aprox (f (+ a (* k h))))) (if(even? k) (recur (inc k) (+ aprox (* (f (+ a (* k h))) multEven))) (recur (inc k) (+ aprox (* (f (+ a (* k h))) multOdd))))))))) (defn drops [lst n] (loop [l1 lst result () k 1] (if (empty? l1) result (if (not= k n) (recur (rest l1) (cons (first l1) result) (inc k)) (recur (rest l1) result 1))))) (deftest test-my-map-indexed (is (= () (my-map-indexed vector ()))) (is (= '([0 a] [1 b] [2 c] [3 d]) (my-map-indexed vector '(a b c d)))) (is (= '(10 4 -2 8 5 5 13) (my-map-indexed + '(10 3 -4 5 1 0 7)))) (is (= '(0 1 -4 3 1 0 6) (my-map-indexed min '(10 3 -4 5 1 0 7))))) (deftest test-my-drop-while (is (= () (my-drop-while neg? ()))) (is (= '(0 1 2 3 4) (my-drop-while neg? '(-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4)))) (is (= '(2 three 4 five) (my-drop-while symbol? '(zero one 2 three 4 five)))) (is (= '(0 one 2 three 4 five) (my-drop-while symbol? '(0 one 2 three 4 five))))) (deftest test-bisection (is (aprox= 0.0001 3.0 (bisection 1 4 (fn [x] (* (- x 3) (+ x 4)))))) (is (aprox= 0.0001 -4.0 (bisection -5 0 (fn [x] (* (- x 3) (+ x 4)))))) (is (aprox= 0.0001 Math/PI (bisection 1 4 (fn [x] (Math/sin x))))) (is (aprox= 0.0001 (* 2 Math/PI) (bisection 5 10 (fn [x] (Math/sin x))))) (is (aprox= 0.0001 1.618033988749895 (bisection 1 2 (fn [x] (- (* x x) x 1))))) (is (aprox= 0.0001 -0.6180339887498948 (bisection -10 1 (fn [x] (- (* x x) x 1)))))) (defn f [x] (* x x x)) (def df (deriv f 0.001)) (def ddf (deriv df 0.001)) (def dddf (deriv ddf 0.001)) (deftest test-deriv (is (aprox= 0.05 75 (df 5))) (is (aprox= 0.05 30 (ddf 5))) (is (aprox= 0.05 6 (dddf 5)))) (deftest test-integral (is (= 1/4 (integral 0 1 10 (fn [x] (* x x x))))) (is (= 21/4 (integral 1 2 10 (fn [x] (integral 3 4 10 (fn [y] (* x y)))))))) (run-tests)
true
;---------------------------------------------------------- ; Activity: Higher-Order Functions ; Date: February 11, 2016. ; Authors: ; A01371743 PI:NAME:<NAME>END_PI ;---------------------------------------------------------- (use 'clojure.test) (defn my-map-indexed " It returns a list consisting of the result of applying f to 0 and the first item of lst, followed by applying f to 1 and the second item in lst, and so on until lst is exhausted. " [f lst] (loop [l1 lst result () x 0] (if (empty? l1) (reverse result) (recur (rest l1) (cons (f x (first l1))result)(inc x))))) (defn my-drop-while "akes two arguments: a function f and a list lst. It returns a list of items from lst dropping the initial items that evaluate to true when passed to f. Once a false value is encountered, the rest of the list is returned. Function f should accept one argument. Do not use the predefined drop-while function." [f lst] (loop [result () l1 lst] (if (empty? l1) result (if (f (first l1)) (recur () (rest l1)) (concat result l1))))) (defn aprox= "Checks if x is approximately equal to y. Returns true if |x - y| < epsilon, or false otherwise." [epsilon x y] (< (Math/abs (- x y)) epsilon)) (defn bisection "is a root-finding algorithm which works by repeatedly dividing an interval in half and then selecting the subinterval in which the root exists" [a b f] (loop [a a b b c (/(+ a b) 2.0)] (if (< (Math/abs (f c)) 1.0E-15) c (if (<(* (f a) (f c)) 0) (recur a c (/(+ a b) 2.0)) (recur c b (/(+ a b) 2.0)))))) (defn deriv "returns a new function that takes x as argument, and which represents the derivate of f given a certain value for h." [f h] (fn [x] (/(- (f (+ x h)) (f x)) h))) (defn integral "Calculates the Simpson's Rule" [a b n f] (loop [k 0 aprox 0] (let [ h (/(- b a)n) multEven 2 multOdd 4] (if (= k n) (/(*( + aprox (f (+ a (* k h))))h)3) (if(zero? k) (recur (inc k) (+ aprox (f (+ a (* k h))))) (if(even? k) (recur (inc k) (+ aprox (* (f (+ a (* k h))) multEven))) (recur (inc k) (+ aprox (* (f (+ a (* k h))) multOdd))))))))) (defn drops [lst n] (loop [l1 lst result () k 1] (if (empty? l1) result (if (not= k n) (recur (rest l1) (cons (first l1) result) (inc k)) (recur (rest l1) result 1))))) (deftest test-my-map-indexed (is (= () (my-map-indexed vector ()))) (is (= '([0 a] [1 b] [2 c] [3 d]) (my-map-indexed vector '(a b c d)))) (is (= '(10 4 -2 8 5 5 13) (my-map-indexed + '(10 3 -4 5 1 0 7)))) (is (= '(0 1 -4 3 1 0 6) (my-map-indexed min '(10 3 -4 5 1 0 7))))) (deftest test-my-drop-while (is (= () (my-drop-while neg? ()))) (is (= '(0 1 2 3 4) (my-drop-while neg? '(-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4)))) (is (= '(2 three 4 five) (my-drop-while symbol? '(zero one 2 three 4 five)))) (is (= '(0 one 2 three 4 five) (my-drop-while symbol? '(0 one 2 three 4 five))))) (deftest test-bisection (is (aprox= 0.0001 3.0 (bisection 1 4 (fn [x] (* (- x 3) (+ x 4)))))) (is (aprox= 0.0001 -4.0 (bisection -5 0 (fn [x] (* (- x 3) (+ x 4)))))) (is (aprox= 0.0001 Math/PI (bisection 1 4 (fn [x] (Math/sin x))))) (is (aprox= 0.0001 (* 2 Math/PI) (bisection 5 10 (fn [x] (Math/sin x))))) (is (aprox= 0.0001 1.618033988749895 (bisection 1 2 (fn [x] (- (* x x) x 1))))) (is (aprox= 0.0001 -0.6180339887498948 (bisection -10 1 (fn [x] (- (* x x) x 1)))))) (defn f [x] (* x x x)) (def df (deriv f 0.001)) (def ddf (deriv df 0.001)) (def dddf (deriv ddf 0.001)) (deftest test-deriv (is (aprox= 0.05 75 (df 5))) (is (aprox= 0.05 30 (ddf 5))) (is (aprox= 0.05 6 (dddf 5)))) (deftest test-integral (is (= 1/4 (integral 0 1 10 (fn [x] (* x x x))))) (is (= 21/4 (integral 1 2 10 (fn [x] (integral 3 4 10 (fn [y] (* x y)))))))) (run-tests)
[ { "context": "t test-update-delete-data\n (is (= [{:first_name \"Andre\"\n :height 180\n :id ", "end": 328, "score": 0.9996678233146667, "start": 323, "tag": "NAME", "value": "Andre" }, { "context": "\n :id 1\n :surname \"Agassi\"\n :weight 80}]\n (update-del", "end": 412, "score": 0.999676525592804, "start": 406, "tag": "NAME", "value": "Agassi" }, { "context": "-data/update-agassi *db*)\n (is (= [{:first_name \"Andre\"\n :height 180\n :id ", "end": 560, "score": 0.999637246131897, "start": 555, "tag": "NAME", "value": "Andre" }, { "context": "\n :id 1\n :surname \"Agassi\"\n :weight 78}]\n (update-del", "end": 644, "score": 0.999629557132721, "start": 638, "tag": "NAME", "value": "Agassi" } ]
chapter13/exercise13.7/test/packt_clj/exercises/test_update_delete_data.clj
TrainingByPackt/Clojure
0
(ns packt-clj.exercises.test-update-delete-data (:require [clojure.test :refer :all] [packt-clj.exercises.fixtures :as fixtures :refer [*db*]] [packt-clj.exercises.update-delete-data :as update-delete-data])) (use-fixtures :once fixtures/db-fixture) (deftest test-update-delete-data (is (= [{:first_name "Andre" :height 180 :id 1 :surname "Agassi" :weight 80}] (update-delete-data/all-users *db*))) (update-delete-data/update-agassi *db*) (is (= [{:first_name "Andre" :height 180 :id 1 :surname "Agassi" :weight 78}] (update-delete-data/all-users *db*))) (update-delete-data/delete-agassi *db*) (is (= [] (update-delete-data/all-users *db*))))
122388
(ns packt-clj.exercises.test-update-delete-data (:require [clojure.test :refer :all] [packt-clj.exercises.fixtures :as fixtures :refer [*db*]] [packt-clj.exercises.update-delete-data :as update-delete-data])) (use-fixtures :once fixtures/db-fixture) (deftest test-update-delete-data (is (= [{:first_name "<NAME>" :height 180 :id 1 :surname "<NAME>" :weight 80}] (update-delete-data/all-users *db*))) (update-delete-data/update-agassi *db*) (is (= [{:first_name "<NAME>" :height 180 :id 1 :surname "<NAME>" :weight 78}] (update-delete-data/all-users *db*))) (update-delete-data/delete-agassi *db*) (is (= [] (update-delete-data/all-users *db*))))
true
(ns packt-clj.exercises.test-update-delete-data (:require [clojure.test :refer :all] [packt-clj.exercises.fixtures :as fixtures :refer [*db*]] [packt-clj.exercises.update-delete-data :as update-delete-data])) (use-fixtures :once fixtures/db-fixture) (deftest test-update-delete-data (is (= [{:first_name "PI:NAME:<NAME>END_PI" :height 180 :id 1 :surname "PI:NAME:<NAME>END_PI" :weight 80}] (update-delete-data/all-users *db*))) (update-delete-data/update-agassi *db*) (is (= [{:first_name "PI:NAME:<NAME>END_PI" :height 180 :id 1 :surname "PI:NAME:<NAME>END_PI" :weight 78}] (update-delete-data/all-users *db*))) (update-delete-data/delete-agassi *db*) (is (= [] (update-delete-data/all-users *db*))))
[ { "context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License", "end": 49, "score": 0.9998814463615417, "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.8457209467887878, "start": 51, "tag": "EMAIL", "value": "narkisr.com" } ]
src/re_core/core.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 re-core.core) (defprotocol Vm "A VM/Machine base API, implement this in order to add a new provider into re-core" (create [this] "Creates a VM, the VM should be up and and ready to accept ssh sessions post this step") (delete [this] "Deletes a VM") (start [this] "Starts an existing VM only if its not running, ssh should be up") (stop [this] "Stops a VM only if it exists and running") (status [this] "Returns vm status (values defere between providers) false if it does not exists") (ip [this] "Instance IP address") ) (defprotocol Provision "A provisioner (puppet/chef) base API, implement this to add more provisioners" (apply- [this] "applies provisioner")) (defprotocol Remoter "Remote automation (capistrano, fabric and supernal) base api" (setup [this] "Sets up this remoter (pulling code, etc..)") (run [this ] "executes a task on remote hosts with") (cleanup [this] "Cleans up (deletes local source etc..)"))
55819
(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 re-core.core) (defprotocol Vm "A VM/Machine base API, implement this in order to add a new provider into re-core" (create [this] "Creates a VM, the VM should be up and and ready to accept ssh sessions post this step") (delete [this] "Deletes a VM") (start [this] "Starts an existing VM only if its not running, ssh should be up") (stop [this] "Stops a VM only if it exists and running") (status [this] "Returns vm status (values defere between providers) false if it does not exists") (ip [this] "Instance IP address") ) (defprotocol Provision "A provisioner (puppet/chef) base API, implement this to add more provisioners" (apply- [this] "applies provisioner")) (defprotocol Remoter "Remote automation (capistrano, fabric and supernal) base api" (setup [this] "Sets up this remoter (pulling code, etc..)") (run [this ] "executes a task on remote hosts with") (cleanup [this] "Cleans up (deletes local source etc..)"))
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 re-core.core) (defprotocol Vm "A VM/Machine base API, implement this in order to add a new provider into re-core" (create [this] "Creates a VM, the VM should be up and and ready to accept ssh sessions post this step") (delete [this] "Deletes a VM") (start [this] "Starts an existing VM only if its not running, ssh should be up") (stop [this] "Stops a VM only if it exists and running") (status [this] "Returns vm status (values defere between providers) false if it does not exists") (ip [this] "Instance IP address") ) (defprotocol Provision "A provisioner (puppet/chef) base API, implement this to add more provisioners" (apply- [this] "applies provisioner")) (defprotocol Remoter "Remote automation (capistrano, fabric and supernal) base api" (setup [this] "Sets up this remoter (pulling code, etc..)") (run [this ] "executes a task on remote hosts with") (cleanup [this] "Cleans up (deletes local source etc..)"))
[ { "context": "ge, London, All rights reserved.\n;\n; Contributors: Jony Hudson\n;\n; Released under the MIT license..\n;\n\n(ns algeb", "end": 137, "score": 0.9997768998146057, "start": 126, "tag": "NAME", "value": "Jony Hudson" } ]
src/algebolic/expression/render.clj
AlgorithmicScience/algebolic
19
; ; This file is part of algebolic. ; ; Copyright (C) 2014-, Imperial College, London, All rights reserved. ; ; Contributors: Jony Hudson ; ; Released under the MIT license.. ; (ns algebolic.expression.render "Gorilla REPL rendering support for algebolic expressions." (:require [algebolic.expression.core :as expression] [clojure.string :as str] [gorilla-renderable.core :as render])) (defn- latexify "Convert an expression to a LaTeX string. Uses a very simple algorithm, that doesn't generate terribly pretty results." [expr] (if (expression/non-terminal? expr) (case (first expr) :plus (str "(" (str/join " + " (map latexify (rest expr))) ")") :minus (str "(" (str/join " - " (map latexify (rest expr))) ")") :times (str/join " \\cdot " (map latexify (rest expr))) :div (str "\\frac{" (latexify (first (rest expr))) " }{ " (latexify (second (rest expr))) "}") :sin (str "\\sin(" (latexify (second expr)) ")") :cos (str "\\cos(" (latexify (second expr)) ")") :square (str "(" (latexify (second expr)) ")^2")) (if (float? expr) (format "%.3f" expr) (pr-str expr)))) (defrecord ExprLatexView [expr]) (defn mathematician-view "View an algebolic expression in more traditional mathematical notation." [expr] (ExprLatexView. expr)) (extend-type ExprLatexView render/Renderable (render [self] {:type :latex :content (latexify (:expr self)) :value (pr-str self)}))
22382
; ; This file is part of algebolic. ; ; Copyright (C) 2014-, Imperial College, London, All rights reserved. ; ; Contributors: <NAME> ; ; Released under the MIT license.. ; (ns algebolic.expression.render "Gorilla REPL rendering support for algebolic expressions." (:require [algebolic.expression.core :as expression] [clojure.string :as str] [gorilla-renderable.core :as render])) (defn- latexify "Convert an expression to a LaTeX string. Uses a very simple algorithm, that doesn't generate terribly pretty results." [expr] (if (expression/non-terminal? expr) (case (first expr) :plus (str "(" (str/join " + " (map latexify (rest expr))) ")") :minus (str "(" (str/join " - " (map latexify (rest expr))) ")") :times (str/join " \\cdot " (map latexify (rest expr))) :div (str "\\frac{" (latexify (first (rest expr))) " }{ " (latexify (second (rest expr))) "}") :sin (str "\\sin(" (latexify (second expr)) ")") :cos (str "\\cos(" (latexify (second expr)) ")") :square (str "(" (latexify (second expr)) ")^2")) (if (float? expr) (format "%.3f" expr) (pr-str expr)))) (defrecord ExprLatexView [expr]) (defn mathematician-view "View an algebolic expression in more traditional mathematical notation." [expr] (ExprLatexView. expr)) (extend-type ExprLatexView render/Renderable (render [self] {:type :latex :content (latexify (:expr self)) :value (pr-str self)}))
true
; ; This file is part of algebolic. ; ; Copyright (C) 2014-, Imperial College, London, All rights reserved. ; ; Contributors: PI:NAME:<NAME>END_PI ; ; Released under the MIT license.. ; (ns algebolic.expression.render "Gorilla REPL rendering support for algebolic expressions." (:require [algebolic.expression.core :as expression] [clojure.string :as str] [gorilla-renderable.core :as render])) (defn- latexify "Convert an expression to a LaTeX string. Uses a very simple algorithm, that doesn't generate terribly pretty results." [expr] (if (expression/non-terminal? expr) (case (first expr) :plus (str "(" (str/join " + " (map latexify (rest expr))) ")") :minus (str "(" (str/join " - " (map latexify (rest expr))) ")") :times (str/join " \\cdot " (map latexify (rest expr))) :div (str "\\frac{" (latexify (first (rest expr))) " }{ " (latexify (second (rest expr))) "}") :sin (str "\\sin(" (latexify (second expr)) ")") :cos (str "\\cos(" (latexify (second expr)) ")") :square (str "(" (latexify (second expr)) ")^2")) (if (float? expr) (format "%.3f" expr) (pr-str expr)))) (defrecord ExprLatexView [expr]) (defn mathematician-view "View an algebolic expression in more traditional mathematical notation." [expr] (ExprLatexView. expr)) (extend-type ExprLatexView render/Renderable (render [self] {:type :latex :content (latexify (:expr self)) :value (pr-str self)}))
[ { "context": "\n (:import (java.util.concurrent Executors)))\n\n;;N. King 5/3/2017\n;;Timing study on mergesort using concur", "end": 150, "score": 0.9990053176879883, "start": 143, "tag": "NAME", "value": "N. King" }, { "context": "erge sort algorithm from: https://gist.github.com/alco/2135276\n; multithreading: https://gist.github.com", "end": 3953, "score": 0.9992269277572632, "start": 3949, "tag": "USERNAME", "value": "alco" }, { "context": "2135276\n; multithreading: https://gist.github.com/ChrisWphoto/c6f86f34cd7ade5055aec743ec990765\n", "end": 4015, "score": 0.9996863603591919, "start": 4004, "tag": "USERNAME", "value": "ChrisWphoto" } ]
algorithms/sorting/mergesort.clj
CiganOliviu/clojure
13
(ns project2.core (:require [clojure.string :as str]) (:require [clojure.java.io :as io]) (:import (java.util.concurrent Executors))) ;;N. King 5/3/2017 ;;Timing study on mergesort using concurrency ;;added comments to show conceptual understanding (defn get-nums [file] ;;defines function "get-nums" which takes a file parameter (map read-string ;;returns lazy sequence of lines (numbers) (str/split-lines ;;splits collection by line (slurp file) ;;open file and read contents, returns string ) ) ) (defn split-2 [numSeq] ;;split into 2 (partition (/ (count numSeq) 2) numSeq)) ;count items in list, divide by two, partition the original list into lists ;containing (/ (count numSeq) 2) items each (defn split-4 [numSeq] ;;split into 4 (partition (/ (count numSeq) 4) numSeq)) (defn split-8 [numSeq] ;;split into 8 (partition (/ (count numSeq) 8) numSeq)) (defn split-16 [numSeq] ;;split into 16 (partition (/ (count numSeq) 16) numSeq)) (defn split-32 [numSeq] ;;split into 32 (partition (/ (count numSeq) 32) numSeq)) (defn merge-seqs "Merges two sorted sequences into a single sorted sequence" ([left right] ;;if parameter is two items (merge-seqs (list left right))) ;;merge them into a list ([[left right]] ;;if parameter is a list of two items (loop [l left, r right, result []] ;;loop through both lists (let [lhead (first l), rhead (first r)] ;;let the heads of the list be the first items (cond (nil? lhead) (concat result r) ;;if the lhead is null, append the rest of r to result (nil? rhead) (concat result l) ;;if the rhead is null, append the rest of l to result (<= lhead rhead) (recur (rest l) r (conj result lhead)) ;if the left head is less than the right head, continue loop with new parameters true (recur l (rest r) (conj result rhead)))))));if right head is less than left head, continue loop with new parameters (defn mergesort "Produces a sorted sequence from an input sequence. Works best with vectors (since it uses 'count' internally)." [xs] ((fn mergesort-counted [xs n] (if (<= n 1) ;if only 1 item remains xs ;return list (let [middle (bit-shift-right n 1)] ;set middle for the list to split (merge-seqs (map mergesort-counted ;call merge-seqs on two halves (split-at middle xs) ;two halves [middle (- n middle)]))))) ;count of each half xs (count xs))) (print "Single Thread mergesort: ") ;timing for simple mergesort --time results in milliseconds (time (mergesort (get-nums "src/project2/numbers_txt.txt"))) (print "2 Threads mergesort: ") ;timing for 2 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-2 (get-nums "src/project2/numbers_txt.txt"))))) ;; ;;pmap is similar to map, except mergesort is applied in parallel to all objects in collection ;; (print "4 Threads mergesort: ") ;timing for 4 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-4 (get-nums "src/project2/numbers_txt.txt"))))) (print "8 Threads mergesort: ") ;timing for 8 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-8 (get-nums "src/project2/numbers_txt.txt"))))) (print "16 Threads mergesort: ") ;timing for 16 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-16 (get-nums "src/project2/numbers_txt.txt"))))) (print "32 Threads mergesort: ") ;timing for 32 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-32 (get-nums "src/project2/numbers_txt.txt"))))) ;sources-- ; merge sort algorithm from: https://gist.github.com/alco/2135276 ; multithreading: https://gist.github.com/ChrisWphoto/c6f86f34cd7ade5055aec743ec990765
60059
(ns project2.core (:require [clojure.string :as str]) (:require [clojure.java.io :as io]) (:import (java.util.concurrent Executors))) ;;<NAME> 5/3/2017 ;;Timing study on mergesort using concurrency ;;added comments to show conceptual understanding (defn get-nums [file] ;;defines function "get-nums" which takes a file parameter (map read-string ;;returns lazy sequence of lines (numbers) (str/split-lines ;;splits collection by line (slurp file) ;;open file and read contents, returns string ) ) ) (defn split-2 [numSeq] ;;split into 2 (partition (/ (count numSeq) 2) numSeq)) ;count items in list, divide by two, partition the original list into lists ;containing (/ (count numSeq) 2) items each (defn split-4 [numSeq] ;;split into 4 (partition (/ (count numSeq) 4) numSeq)) (defn split-8 [numSeq] ;;split into 8 (partition (/ (count numSeq) 8) numSeq)) (defn split-16 [numSeq] ;;split into 16 (partition (/ (count numSeq) 16) numSeq)) (defn split-32 [numSeq] ;;split into 32 (partition (/ (count numSeq) 32) numSeq)) (defn merge-seqs "Merges two sorted sequences into a single sorted sequence" ([left right] ;;if parameter is two items (merge-seqs (list left right))) ;;merge them into a list ([[left right]] ;;if parameter is a list of two items (loop [l left, r right, result []] ;;loop through both lists (let [lhead (first l), rhead (first r)] ;;let the heads of the list be the first items (cond (nil? lhead) (concat result r) ;;if the lhead is null, append the rest of r to result (nil? rhead) (concat result l) ;;if the rhead is null, append the rest of l to result (<= lhead rhead) (recur (rest l) r (conj result lhead)) ;if the left head is less than the right head, continue loop with new parameters true (recur l (rest r) (conj result rhead)))))));if right head is less than left head, continue loop with new parameters (defn mergesort "Produces a sorted sequence from an input sequence. Works best with vectors (since it uses 'count' internally)." [xs] ((fn mergesort-counted [xs n] (if (<= n 1) ;if only 1 item remains xs ;return list (let [middle (bit-shift-right n 1)] ;set middle for the list to split (merge-seqs (map mergesort-counted ;call merge-seqs on two halves (split-at middle xs) ;two halves [middle (- n middle)]))))) ;count of each half xs (count xs))) (print "Single Thread mergesort: ") ;timing for simple mergesort --time results in milliseconds (time (mergesort (get-nums "src/project2/numbers_txt.txt"))) (print "2 Threads mergesort: ") ;timing for 2 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-2 (get-nums "src/project2/numbers_txt.txt"))))) ;; ;;pmap is similar to map, except mergesort is applied in parallel to all objects in collection ;; (print "4 Threads mergesort: ") ;timing for 4 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-4 (get-nums "src/project2/numbers_txt.txt"))))) (print "8 Threads mergesort: ") ;timing for 8 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-8 (get-nums "src/project2/numbers_txt.txt"))))) (print "16 Threads mergesort: ") ;timing for 16 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-16 (get-nums "src/project2/numbers_txt.txt"))))) (print "32 Threads mergesort: ") ;timing for 32 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-32 (get-nums "src/project2/numbers_txt.txt"))))) ;sources-- ; merge sort algorithm from: https://gist.github.com/alco/2135276 ; multithreading: https://gist.github.com/ChrisWphoto/c6f86f34cd7ade5055aec743ec990765
true
(ns project2.core (:require [clojure.string :as str]) (:require [clojure.java.io :as io]) (:import (java.util.concurrent Executors))) ;;PI:NAME:<NAME>END_PI 5/3/2017 ;;Timing study on mergesort using concurrency ;;added comments to show conceptual understanding (defn get-nums [file] ;;defines function "get-nums" which takes a file parameter (map read-string ;;returns lazy sequence of lines (numbers) (str/split-lines ;;splits collection by line (slurp file) ;;open file and read contents, returns string ) ) ) (defn split-2 [numSeq] ;;split into 2 (partition (/ (count numSeq) 2) numSeq)) ;count items in list, divide by two, partition the original list into lists ;containing (/ (count numSeq) 2) items each (defn split-4 [numSeq] ;;split into 4 (partition (/ (count numSeq) 4) numSeq)) (defn split-8 [numSeq] ;;split into 8 (partition (/ (count numSeq) 8) numSeq)) (defn split-16 [numSeq] ;;split into 16 (partition (/ (count numSeq) 16) numSeq)) (defn split-32 [numSeq] ;;split into 32 (partition (/ (count numSeq) 32) numSeq)) (defn merge-seqs "Merges two sorted sequences into a single sorted sequence" ([left right] ;;if parameter is two items (merge-seqs (list left right))) ;;merge them into a list ([[left right]] ;;if parameter is a list of two items (loop [l left, r right, result []] ;;loop through both lists (let [lhead (first l), rhead (first r)] ;;let the heads of the list be the first items (cond (nil? lhead) (concat result r) ;;if the lhead is null, append the rest of r to result (nil? rhead) (concat result l) ;;if the rhead is null, append the rest of l to result (<= lhead rhead) (recur (rest l) r (conj result lhead)) ;if the left head is less than the right head, continue loop with new parameters true (recur l (rest r) (conj result rhead)))))));if right head is less than left head, continue loop with new parameters (defn mergesort "Produces a sorted sequence from an input sequence. Works best with vectors (since it uses 'count' internally)." [xs] ((fn mergesort-counted [xs n] (if (<= n 1) ;if only 1 item remains xs ;return list (let [middle (bit-shift-right n 1)] ;set middle for the list to split (merge-seqs (map mergesort-counted ;call merge-seqs on two halves (split-at middle xs) ;two halves [middle (- n middle)]))))) ;count of each half xs (count xs))) (print "Single Thread mergesort: ") ;timing for simple mergesort --time results in milliseconds (time (mergesort (get-nums "src/project2/numbers_txt.txt"))) (print "2 Threads mergesort: ") ;timing for 2 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-2 (get-nums "src/project2/numbers_txt.txt"))))) ;; ;;pmap is similar to map, except mergesort is applied in parallel to all objects in collection ;; (print "4 Threads mergesort: ") ;timing for 4 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-4 (get-nums "src/project2/numbers_txt.txt"))))) (print "8 Threads mergesort: ") ;timing for 8 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-8 (get-nums "src/project2/numbers_txt.txt"))))) (print "16 Threads mergesort: ") ;timing for 16 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-16 (get-nums "src/project2/numbers_txt.txt"))))) (print "32 Threads mergesort: ") ;timing for 32 thread mergesort (time (reduce merge-seqs (pmap mergesort (split-32 (get-nums "src/project2/numbers_txt.txt"))))) ;sources-- ; merge sort algorithm from: https://gist.github.com/alco/2135276 ; multithreading: https://gist.github.com/ChrisWphoto/c6f86f34cd7ade5055aec743ec990765
[ { "context": "(ns template.config)\n\n(def firebase \n {:apiKey \"AIzaSyAaqFTPXPZmEGXKhpnRdVgAfqQX5q-7I00\"\n :authDomain \"jurko-fire.firebase", "end": 88, "score": 0.9997536540031433, "start": 49, "tag": "KEY", "value": "AIzaSyAaqFTPXPZmEGXKhpnRdVgAfqQX5q-7I00" } ]
src/template/config.cljs
jurkotroll/good-template
0
(ns template.config) (def firebase {:apiKey "AIzaSyAaqFTPXPZmEGXKhpnRdVgAfqQX5q-7I00" :authDomain "jurko-fire.firebaseapp.com" :databaseURL "https://jurko-fire.firebaseio.com" :projectId "jurko-fire" :storageBucket "jurko-fire.appspot.com" :messagingSenderId "264615085822"})
92919
(ns template.config) (def firebase {:apiKey "<KEY>" :authDomain "jurko-fire.firebaseapp.com" :databaseURL "https://jurko-fire.firebaseio.com" :projectId "jurko-fire" :storageBucket "jurko-fire.appspot.com" :messagingSenderId "264615085822"})
true
(ns template.config) (def firebase {:apiKey "PI:KEY:<KEY>END_PI" :authDomain "jurko-fire.firebaseapp.com" :databaseURL "https://jurko-fire.firebaseio.com" :projectId "jurko-fire" :storageBucket "jurko-fire.appspot.com" :messagingSenderId "264615085822"})
[ { "context": ";; Copyright © 2015-2020 Esko Luontola\n;; This software is released under the Apache Lic", "end": 38, "score": 0.9998846054077148, "start": 25, "tag": "NAME", "value": "Esko Luontola" } ]
src/territory_bro/infra/poller.clj
orfjackal/territory-bro
2
;; Copyright © 2015-2020 Esko Luontola ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.infra.poller (:refer-clojure :exclude [await]) (:require [territory-bro.infra.executors :as executors]) (:import (com.google.common.util.concurrent ThreadFactoryBuilder) (java.time Duration) (java.util Queue) (java.util.concurrent ExecutorService Executors TimeUnit ArrayBlockingQueue Future))) (defprotocol Poller (trigger! [this]) (await [this ^Duration timeout]) (shutdown! [this])) (defrecord AsyncPoller [^Queue available-tasks ^ExecutorService executor] Poller (trigger! [_] (when-let [task (.poll available-tasks)] (.execute executor (executors/safe-task (fn [] (.add available-tasks task) (task)))))) (await [_ timeout] (let [^Duration timeout timeout ^Future future (.submit executor ^Runnable (fn []))] (.get future (.toNanos timeout) TimeUnit/NANOSECONDS))) (shutdown! [_] (doto executor (.shutdown) (.awaitTermination 1 TimeUnit/MINUTES) (.shutdownNow)))) (defonce ^:private thread-factory (-> (ThreadFactoryBuilder.) (.setNameFormat "territory-bro.infra.poller/%d") (.setDaemon true) (.setUncaughtExceptionHandler executors/uncaught-exception-handler) (.build))) (defn create [task] (assert (fn? task) {:task task}) (AsyncPoller. (doto (ArrayBlockingQueue. 1) (.add task)) (Executors/newFixedThreadPool 1 thread-factory)))
10191
;; Copyright © 2015-2020 <NAME> ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.infra.poller (:refer-clojure :exclude [await]) (:require [territory-bro.infra.executors :as executors]) (:import (com.google.common.util.concurrent ThreadFactoryBuilder) (java.time Duration) (java.util Queue) (java.util.concurrent ExecutorService Executors TimeUnit ArrayBlockingQueue Future))) (defprotocol Poller (trigger! [this]) (await [this ^Duration timeout]) (shutdown! [this])) (defrecord AsyncPoller [^Queue available-tasks ^ExecutorService executor] Poller (trigger! [_] (when-let [task (.poll available-tasks)] (.execute executor (executors/safe-task (fn [] (.add available-tasks task) (task)))))) (await [_ timeout] (let [^Duration timeout timeout ^Future future (.submit executor ^Runnable (fn []))] (.get future (.toNanos timeout) TimeUnit/NANOSECONDS))) (shutdown! [_] (doto executor (.shutdown) (.awaitTermination 1 TimeUnit/MINUTES) (.shutdownNow)))) (defonce ^:private thread-factory (-> (ThreadFactoryBuilder.) (.setNameFormat "territory-bro.infra.poller/%d") (.setDaemon true) (.setUncaughtExceptionHandler executors/uncaught-exception-handler) (.build))) (defn create [task] (assert (fn? task) {:task task}) (AsyncPoller. (doto (ArrayBlockingQueue. 1) (.add task)) (Executors/newFixedThreadPool 1 thread-factory)))
true
;; Copyright © 2015-2020 PI:NAME:<NAME>END_PI ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.infra.poller (:refer-clojure :exclude [await]) (:require [territory-bro.infra.executors :as executors]) (:import (com.google.common.util.concurrent ThreadFactoryBuilder) (java.time Duration) (java.util Queue) (java.util.concurrent ExecutorService Executors TimeUnit ArrayBlockingQueue Future))) (defprotocol Poller (trigger! [this]) (await [this ^Duration timeout]) (shutdown! [this])) (defrecord AsyncPoller [^Queue available-tasks ^ExecutorService executor] Poller (trigger! [_] (when-let [task (.poll available-tasks)] (.execute executor (executors/safe-task (fn [] (.add available-tasks task) (task)))))) (await [_ timeout] (let [^Duration timeout timeout ^Future future (.submit executor ^Runnable (fn []))] (.get future (.toNanos timeout) TimeUnit/NANOSECONDS))) (shutdown! [_] (doto executor (.shutdown) (.awaitTermination 1 TimeUnit/MINUTES) (.shutdownNow)))) (defonce ^:private thread-factory (-> (ThreadFactoryBuilder.) (.setNameFormat "territory-bro.infra.poller/%d") (.setDaemon true) (.setUncaughtExceptionHandler executors/uncaught-exception-handler) (.build))) (defn create [task] (assert (fn? task) {:task task}) (AsyncPoller. (doto (ArrayBlockingQueue. 1) (.add task)) (Executors/newFixedThreadPool 1 thread-factory)))
[ { "context": ";\n; Copyright © 2020 Peter Monks\n;\n; Licensed under the Apache License, Version 2.", "end": 32, "score": 0.9996184706687927, "start": 21, "tag": "NAME", "value": "Peter Monks" } ]
src/futbot/source/dutch_referee_blog.clj
pmonks/futbot
3
; ; Copyright © 2020 Peter Monks ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns futbot.source.dutch-referee-blog (:require [clojure.string :as s] [java-time :as tm] [remus :as rss])) (def dutch-referee-blog-feed-url "http://www.dutchreferee.com/feed/atom") ; I prefer atom... (def quiz-title-substring "Laws of the Game Quiz") (defn quizzes "Returns a sequence of maps representing all of the quizzes in the Dutch Referee Blog's RSS feed, optionally since the given date, or nil if there aren't any." ([] (quizzes nil)) ([since] (seq (when-let [all-quizzes (filter #(s/index-of (:title %) quiz-title-substring) (:entries (:feed (rss/parse-url dutch-referee-blog-feed-url))))] (if since (filter #(tm/after? (tm/instant (:published-date %)) (tm/instant since)) all-quizzes) all-quizzes)))))
63528
; ; Copyright © 2020 <NAME> ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns futbot.source.dutch-referee-blog (:require [clojure.string :as s] [java-time :as tm] [remus :as rss])) (def dutch-referee-blog-feed-url "http://www.dutchreferee.com/feed/atom") ; I prefer atom... (def quiz-title-substring "Laws of the Game Quiz") (defn quizzes "Returns a sequence of maps representing all of the quizzes in the Dutch Referee Blog's RSS feed, optionally since the given date, or nil if there aren't any." ([] (quizzes nil)) ([since] (seq (when-let [all-quizzes (filter #(s/index-of (:title %) quiz-title-substring) (:entries (:feed (rss/parse-url dutch-referee-blog-feed-url))))] (if since (filter #(tm/after? (tm/instant (:published-date %)) (tm/instant since)) all-quizzes) all-quizzes)))))
true
; ; Copyright © 2020 PI:NAME:<NAME>END_PI ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns futbot.source.dutch-referee-blog (:require [clojure.string :as s] [java-time :as tm] [remus :as rss])) (def dutch-referee-blog-feed-url "http://www.dutchreferee.com/feed/atom") ; I prefer atom... (def quiz-title-substring "Laws of the Game Quiz") (defn quizzes "Returns a sequence of maps representing all of the quizzes in the Dutch Referee Blog's RSS feed, optionally since the given date, or nil if there aren't any." ([] (quizzes nil)) ([since] (seq (when-let [all-quizzes (filter #(s/index-of (:title %) quiz-title-substring) (:entries (:feed (rss/parse-url dutch-referee-blog-feed-url))))] (if since (filter #(tm/after? (tm/instant (:published-date %)) (tm/instant since)) all-quizzes) all-quizzes)))))
[ { "context": " :updated \"Candidato atualizado\"\n :fullname \"Nome completo\"\n :email \"E-mail\"\n :twitter \"Twitter\"\n :", "end": 982, "score": 0.940992534160614, "start": 969, "tag": "NAME", "value": "Nome completo" } ]
resources/pt_BR.clj
agile-alliance-brazil/election
1
{ :elections { :not-found "Eleição com ID %d não foi encontrada." :new-voters-registered "%d novo(s) eleitor(es) inscrito(s)." :some-voters-registered "%d novo(s) eleitor(es) inscrito(s) (existentes: %d, inválidos: %d)" :voter-registration-failed "Inscrição de eleitores falhou" :create "Criar eleição" :name "Nome da eleição" :description "Descrição" :startdate "Data de início da votação" :enddate "Data de fim da votação" :candidates-to-elect "Número de candidatos a serem eleitos" :candidates-to-vote-on "Número de candidatos a selecionar em um voto" :election-created "Eleição criada com sucesso!" :create-election-failed "Criação da eleição falhou. Tente novamente" } :candidates { :add "Adicionar novo candidato" :added "Candidato adicionado" :add-failed "Erro ao adicionar candidato" :edit "Editar detalhes" :update "Atualizar" :updated "Candidato atualizado" :fullname "Nome completo" :email "E-mail" :twitter "Twitter" :motivation "Motivação" :region "Região" :minibio "Minibio" :invalid-email "Email inválido" } :votes { :register "Inscrever eleitores" :partial-results "Resultados parciais" :final-results "Resultados finais" :count "Votos" :add-voters "Adicionar lista de eleitores" :instructions "Por favor, selecione %d candidato(a) a favor do(a) qual seu voto será contabilizado e pressione o botão 'Votar'." :place "Votar" :used-token "Seu token já foi utilizado" :recorded "Voto contabilizado! Obrigado." :invalid "Voto inválido. Por favor, verifique que selecionou a quantidade correta de candidatos." :confirm "Votos não podem ser alterados uma vez que forem enviados. Você tem certeza que deseja enviar seu voto?" :voter-count "Total de eleitores" :votes-count "Total de votos a receber" :casted-votes-count "Total de votos recebidos" :not-started "A eleição ainda não começou." :too-late "A eleição já encerrou." } :session { :new "Login" :destroy "Deslogar de %s" :destroyed "Deslogado com sucesso!" :invalid "Autenticação inválida. Tente novamente" :created "Logado com sucesso!" } :mailer { :token { :subject "Convite para votar na eleição de membros ao board de diretores da %s" :text! "Olá %s, Como participante do Agile Brazil 2016, 2017 ou 2018, você está habilitado a votar para a eleição de um membro ao board de diretoria da Agile Alliance Brazil para o período de 2020-2022. Para votar, acesse o link abaixo. Você poderá votar apenas uma vez e não poderá editar seu voto após o envio. Você deve votar em um(a) candidato(a) e tem até %s para submeter seu voto. %s Agradecemos a sua participação, Agile Alliance Brazil" :html* "Olá %s, Como participante do Agile Brazil 2016, 2017 ou 2018, você está habilitado a votar para a eleição de um membros ao board de diretoria da Agile Alliance Brazil para o período de 2020-2022. Para votar, acesse o link abaixo. Você poderá votar apenas uma vez e não poderá editar seu voto após o envio. Você deve votar em um(a) candidato(a) e tem até %s para submeter seu voto. [%s](%s) Agradecemos a sua participação, Agile Alliance Brazil" } :reminder { :subject "A eleição %s está quase terminando. Lembre-se de votar." :text! "Olá %s, A Agile Alliance Brazil está em mais um ciclo de renovação do board de diretoria da associação. Por meio de uma eleição entre o corpo de membros brasileiros da Agile Alliance, selecionaremos entre %d candidatos(as), o(a) novo(a) integrante do conselho de administração para o período de 2020-2022. Seu voto, como membro(a) da Agile Alliance Brazil, é muito importante para esse processo. Caso já tenha votado, não precisa fazer mais nada. Muito obrigado. Se ainda não tiver votado, conheça um pouco mais sobre cada candidato(a) participante dessa eleição (listados em ordem alfabética) abaixo. Para votar, procure em sua caixa de e-mail por um mensagem intitulada '%s'. Nela você encontrará um link único para fazer sua votação com a máxima segurança até %s. Se tiver dificuldades, responda este email descrevendo seu problema para lhe ajudarmos. Candidatos(as): %s Atenciosamente, Agile Alliance Brazil" :candidate-partial-text! "#%s Descreva um pouco sobre a sua motivação para participar do board da Agile Alliance Brazil no período 2020-2022. %s Região: %s %s --- " :candidate-social-text! " Rede Social: %s " :html* "Olá %s, A Agile Alliance Brazil está em mais um ciclo de renovação do board de diretoria da associação. Por meio de uma eleição entre o corpo de membros brasileiros da Agile Alliance, selecionaremos entre %d candidatos(as), o(a) novo(a) integrantes do conselho de administração para o período de 2020-2022. Seu voto, como membro(a) da Agile Alliance Brazil, é muito importante para esse processo. Caso já tenha votado, não precisa fazer mais nada. Muito obrigado. Se ainda não tiver votado, conheça um pouco mais sobre cada candidato(a) participante dessa eleição (listados em ordem alfabética) abaixo. Para votar, procure em sua caixa de e-mail por um mensagem intitulada **%s**. Nela você encontrará um link único para fazer sua votação com a máxima segurança até **%s**. Se tiver dificuldades, responda este email descrevendo seu problema para lhe ajudarmos. ##Candidatos(as): %s Atenciosamente, Agile Alliance Brazil" :candidate-partial-html* "#%s **Descreva um pouco sobre a sua motivação para participar do board da Agile Alliance Brazil no período 2020-2022.** %s **Região:** %s %s --- " :candidate-social-html* " **Rede Social:** [%s](%s) " } } :status { :up "A applicação está funcionando" :db-connection { :successful "Conexão com o BD operacional. A última migração foi: %s." :failed "Conexão com o BD falhou. Conexão/busca a %s falhou com: %s %s." } :connection { :successful "Conexão até '%s' respondeu com código %s em %d ms." :failed "Pedido HTTP falhou: %s" } } :forbidden "Acesso negado" :none "nenhum(a)" :pt-BR "Português do Brasil" :en-US "Inglês Americano" :cpf "Cadastro de Pessoa Física" :agile-alliance-logo "Logo da Agile Alliance" }
42622
{ :elections { :not-found "Eleição com ID %d não foi encontrada." :new-voters-registered "%d novo(s) eleitor(es) inscrito(s)." :some-voters-registered "%d novo(s) eleitor(es) inscrito(s) (existentes: %d, inválidos: %d)" :voter-registration-failed "Inscrição de eleitores falhou" :create "Criar eleição" :name "Nome da eleição" :description "Descrição" :startdate "Data de início da votação" :enddate "Data de fim da votação" :candidates-to-elect "Número de candidatos a serem eleitos" :candidates-to-vote-on "Número de candidatos a selecionar em um voto" :election-created "Eleição criada com sucesso!" :create-election-failed "Criação da eleição falhou. Tente novamente" } :candidates { :add "Adicionar novo candidato" :added "Candidato adicionado" :add-failed "Erro ao adicionar candidato" :edit "Editar detalhes" :update "Atualizar" :updated "Candidato atualizado" :fullname "<NAME>" :email "E-mail" :twitter "Twitter" :motivation "Motivação" :region "Região" :minibio "Minibio" :invalid-email "Email inválido" } :votes { :register "Inscrever eleitores" :partial-results "Resultados parciais" :final-results "Resultados finais" :count "Votos" :add-voters "Adicionar lista de eleitores" :instructions "Por favor, selecione %d candidato(a) a favor do(a) qual seu voto será contabilizado e pressione o botão 'Votar'." :place "Votar" :used-token "Seu token já foi utilizado" :recorded "Voto contabilizado! Obrigado." :invalid "Voto inválido. Por favor, verifique que selecionou a quantidade correta de candidatos." :confirm "Votos não podem ser alterados uma vez que forem enviados. Você tem certeza que deseja enviar seu voto?" :voter-count "Total de eleitores" :votes-count "Total de votos a receber" :casted-votes-count "Total de votos recebidos" :not-started "A eleição ainda não começou." :too-late "A eleição já encerrou." } :session { :new "Login" :destroy "Deslogar de %s" :destroyed "Deslogado com sucesso!" :invalid "Autenticação inválida. Tente novamente" :created "Logado com sucesso!" } :mailer { :token { :subject "Convite para votar na eleição de membros ao board de diretores da %s" :text! "Olá %s, Como participante do Agile Brazil 2016, 2017 ou 2018, você está habilitado a votar para a eleição de um membro ao board de diretoria da Agile Alliance Brazil para o período de 2020-2022. Para votar, acesse o link abaixo. Você poderá votar apenas uma vez e não poderá editar seu voto após o envio. Você deve votar em um(a) candidato(a) e tem até %s para submeter seu voto. %s Agradecemos a sua participação, Agile Alliance Brazil" :html* "Olá %s, Como participante do Agile Brazil 2016, 2017 ou 2018, você está habilitado a votar para a eleição de um membros ao board de diretoria da Agile Alliance Brazil para o período de 2020-2022. Para votar, acesse o link abaixo. Você poderá votar apenas uma vez e não poderá editar seu voto após o envio. Você deve votar em um(a) candidato(a) e tem até %s para submeter seu voto. [%s](%s) Agradecemos a sua participação, Agile Alliance Brazil" } :reminder { :subject "A eleição %s está quase terminando. Lembre-se de votar." :text! "Olá %s, A Agile Alliance Brazil está em mais um ciclo de renovação do board de diretoria da associação. Por meio de uma eleição entre o corpo de membros brasileiros da Agile Alliance, selecionaremos entre %d candidatos(as), o(a) novo(a) integrante do conselho de administração para o período de 2020-2022. Seu voto, como membro(a) da Agile Alliance Brazil, é muito importante para esse processo. Caso já tenha votado, não precisa fazer mais nada. Muito obrigado. Se ainda não tiver votado, conheça um pouco mais sobre cada candidato(a) participante dessa eleição (listados em ordem alfabética) abaixo. Para votar, procure em sua caixa de e-mail por um mensagem intitulada '%s'. Nela você encontrará um link único para fazer sua votação com a máxima segurança até %s. Se tiver dificuldades, responda este email descrevendo seu problema para lhe ajudarmos. Candidatos(as): %s Atenciosamente, Agile Alliance Brazil" :candidate-partial-text! "#%s Descreva um pouco sobre a sua motivação para participar do board da Agile Alliance Brazil no período 2020-2022. %s Região: %s %s --- " :candidate-social-text! " Rede Social: %s " :html* "Olá %s, A Agile Alliance Brazil está em mais um ciclo de renovação do board de diretoria da associação. Por meio de uma eleição entre o corpo de membros brasileiros da Agile Alliance, selecionaremos entre %d candidatos(as), o(a) novo(a) integrantes do conselho de administração para o período de 2020-2022. Seu voto, como membro(a) da Agile Alliance Brazil, é muito importante para esse processo. Caso já tenha votado, não precisa fazer mais nada. Muito obrigado. Se ainda não tiver votado, conheça um pouco mais sobre cada candidato(a) participante dessa eleição (listados em ordem alfabética) abaixo. Para votar, procure em sua caixa de e-mail por um mensagem intitulada **%s**. Nela você encontrará um link único para fazer sua votação com a máxima segurança até **%s**. Se tiver dificuldades, responda este email descrevendo seu problema para lhe ajudarmos. ##Candidatos(as): %s Atenciosamente, Agile Alliance Brazil" :candidate-partial-html* "#%s **Descreva um pouco sobre a sua motivação para participar do board da Agile Alliance Brazil no período 2020-2022.** %s **Região:** %s %s --- " :candidate-social-html* " **Rede Social:** [%s](%s) " } } :status { :up "A applicação está funcionando" :db-connection { :successful "Conexão com o BD operacional. A última migração foi: %s." :failed "Conexão com o BD falhou. Conexão/busca a %s falhou com: %s %s." } :connection { :successful "Conexão até '%s' respondeu com código %s em %d ms." :failed "Pedido HTTP falhou: %s" } } :forbidden "Acesso negado" :none "nenhum(a)" :pt-BR "Português do Brasil" :en-US "Inglês Americano" :cpf "Cadastro de Pessoa Física" :agile-alliance-logo "Logo da Agile Alliance" }
true
{ :elections { :not-found "Eleição com ID %d não foi encontrada." :new-voters-registered "%d novo(s) eleitor(es) inscrito(s)." :some-voters-registered "%d novo(s) eleitor(es) inscrito(s) (existentes: %d, inválidos: %d)" :voter-registration-failed "Inscrição de eleitores falhou" :create "Criar eleição" :name "Nome da eleição" :description "Descrição" :startdate "Data de início da votação" :enddate "Data de fim da votação" :candidates-to-elect "Número de candidatos a serem eleitos" :candidates-to-vote-on "Número de candidatos a selecionar em um voto" :election-created "Eleição criada com sucesso!" :create-election-failed "Criação da eleição falhou. Tente novamente" } :candidates { :add "Adicionar novo candidato" :added "Candidato adicionado" :add-failed "Erro ao adicionar candidato" :edit "Editar detalhes" :update "Atualizar" :updated "Candidato atualizado" :fullname "PI:NAME:<NAME>END_PI" :email "E-mail" :twitter "Twitter" :motivation "Motivação" :region "Região" :minibio "Minibio" :invalid-email "Email inválido" } :votes { :register "Inscrever eleitores" :partial-results "Resultados parciais" :final-results "Resultados finais" :count "Votos" :add-voters "Adicionar lista de eleitores" :instructions "Por favor, selecione %d candidato(a) a favor do(a) qual seu voto será contabilizado e pressione o botão 'Votar'." :place "Votar" :used-token "Seu token já foi utilizado" :recorded "Voto contabilizado! Obrigado." :invalid "Voto inválido. Por favor, verifique que selecionou a quantidade correta de candidatos." :confirm "Votos não podem ser alterados uma vez que forem enviados. Você tem certeza que deseja enviar seu voto?" :voter-count "Total de eleitores" :votes-count "Total de votos a receber" :casted-votes-count "Total de votos recebidos" :not-started "A eleição ainda não começou." :too-late "A eleição já encerrou." } :session { :new "Login" :destroy "Deslogar de %s" :destroyed "Deslogado com sucesso!" :invalid "Autenticação inválida. Tente novamente" :created "Logado com sucesso!" } :mailer { :token { :subject "Convite para votar na eleição de membros ao board de diretores da %s" :text! "Olá %s, Como participante do Agile Brazil 2016, 2017 ou 2018, você está habilitado a votar para a eleição de um membro ao board de diretoria da Agile Alliance Brazil para o período de 2020-2022. Para votar, acesse o link abaixo. Você poderá votar apenas uma vez e não poderá editar seu voto após o envio. Você deve votar em um(a) candidato(a) e tem até %s para submeter seu voto. %s Agradecemos a sua participação, Agile Alliance Brazil" :html* "Olá %s, Como participante do Agile Brazil 2016, 2017 ou 2018, você está habilitado a votar para a eleição de um membros ao board de diretoria da Agile Alliance Brazil para o período de 2020-2022. Para votar, acesse o link abaixo. Você poderá votar apenas uma vez e não poderá editar seu voto após o envio. Você deve votar em um(a) candidato(a) e tem até %s para submeter seu voto. [%s](%s) Agradecemos a sua participação, Agile Alliance Brazil" } :reminder { :subject "A eleição %s está quase terminando. Lembre-se de votar." :text! "Olá %s, A Agile Alliance Brazil está em mais um ciclo de renovação do board de diretoria da associação. Por meio de uma eleição entre o corpo de membros brasileiros da Agile Alliance, selecionaremos entre %d candidatos(as), o(a) novo(a) integrante do conselho de administração para o período de 2020-2022. Seu voto, como membro(a) da Agile Alliance Brazil, é muito importante para esse processo. Caso já tenha votado, não precisa fazer mais nada. Muito obrigado. Se ainda não tiver votado, conheça um pouco mais sobre cada candidato(a) participante dessa eleição (listados em ordem alfabética) abaixo. Para votar, procure em sua caixa de e-mail por um mensagem intitulada '%s'. Nela você encontrará um link único para fazer sua votação com a máxima segurança até %s. Se tiver dificuldades, responda este email descrevendo seu problema para lhe ajudarmos. Candidatos(as): %s Atenciosamente, Agile Alliance Brazil" :candidate-partial-text! "#%s Descreva um pouco sobre a sua motivação para participar do board da Agile Alliance Brazil no período 2020-2022. %s Região: %s %s --- " :candidate-social-text! " Rede Social: %s " :html* "Olá %s, A Agile Alliance Brazil está em mais um ciclo de renovação do board de diretoria da associação. Por meio de uma eleição entre o corpo de membros brasileiros da Agile Alliance, selecionaremos entre %d candidatos(as), o(a) novo(a) integrantes do conselho de administração para o período de 2020-2022. Seu voto, como membro(a) da Agile Alliance Brazil, é muito importante para esse processo. Caso já tenha votado, não precisa fazer mais nada. Muito obrigado. Se ainda não tiver votado, conheça um pouco mais sobre cada candidato(a) participante dessa eleição (listados em ordem alfabética) abaixo. Para votar, procure em sua caixa de e-mail por um mensagem intitulada **%s**. Nela você encontrará um link único para fazer sua votação com a máxima segurança até **%s**. Se tiver dificuldades, responda este email descrevendo seu problema para lhe ajudarmos. ##Candidatos(as): %s Atenciosamente, Agile Alliance Brazil" :candidate-partial-html* "#%s **Descreva um pouco sobre a sua motivação para participar do board da Agile Alliance Brazil no período 2020-2022.** %s **Região:** %s %s --- " :candidate-social-html* " **Rede Social:** [%s](%s) " } } :status { :up "A applicação está funcionando" :db-connection { :successful "Conexão com o BD operacional. A última migração foi: %s." :failed "Conexão com o BD falhou. Conexão/busca a %s falhou com: %s %s." } :connection { :successful "Conexão até '%s' respondeu com código %s em %d ms." :failed "Pedido HTTP falhou: %s" } } :forbidden "Acesso negado" :none "nenhum(a)" :pt-BR "Português do Brasil" :en-US "Inglês Americano" :cpf "Cadastro de Pessoa Física" :agile-alliance-logo "Logo da Agile Alliance" }
[ { "context": ";; Copyright 2016 Timothy Brooks\n;;\n;; Licensed under the Apache License, Version ", "end": 32, "score": 0.9998577237129211, "start": 18, "tag": "NAME", "value": "Timothy Brooks" } ]
src/beehive/back_pressure.clj
tbrooks8/fault
2
;; Copyright 2016 Timothy Brooks ;; ;; 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 beehive.back-pressure (:import (net.uncontended.precipice BackPressure))) (defn mechanism "This is experimental." [fn & {:keys [pass-nano-time?] :or {pass-nano-time? false}}] (if pass-nano-time? (with-meta (reify BackPressure (acquirePermit [this permit-count nano-time] (fn (:beehive (meta this)) permit-count nano-time)) (releasePermit [this permit-count nano-time] ) (releasePermit [this permit-count result nano-time] ) (registerGuardRail [this guard-rail])) {:clj? true}) (with-meta (reify BackPressure (acquirePermit [this permit-count nano-time] (fn (:beehive (meta this)) permit-count)) (releasePermit [this permit-count nano-time] ) (releasePermit [this permit-count result nano-time] ) (registerGuardRail [this guard-rail])) {:clj? true})))
21708
;; Copyright 2016 <NAME> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns beehive.back-pressure (:import (net.uncontended.precipice BackPressure))) (defn mechanism "This is experimental." [fn & {:keys [pass-nano-time?] :or {pass-nano-time? false}}] (if pass-nano-time? (with-meta (reify BackPressure (acquirePermit [this permit-count nano-time] (fn (:beehive (meta this)) permit-count nano-time)) (releasePermit [this permit-count nano-time] ) (releasePermit [this permit-count result nano-time] ) (registerGuardRail [this guard-rail])) {:clj? true}) (with-meta (reify BackPressure (acquirePermit [this permit-count nano-time] (fn (:beehive (meta this)) permit-count)) (releasePermit [this permit-count nano-time] ) (releasePermit [this permit-count result nano-time] ) (registerGuardRail [this guard-rail])) {:clj? true})))
true
;; Copyright 2016 PI:NAME:<NAME>END_PI ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns beehive.back-pressure (:import (net.uncontended.precipice BackPressure))) (defn mechanism "This is experimental." [fn & {:keys [pass-nano-time?] :or {pass-nano-time? false}}] (if pass-nano-time? (with-meta (reify BackPressure (acquirePermit [this permit-count nano-time] (fn (:beehive (meta this)) permit-count nano-time)) (releasePermit [this permit-count nano-time] ) (releasePermit [this permit-count result nano-time] ) (registerGuardRail [this guard-rail])) {:clj? true}) (with-meta (reify BackPressure (acquirePermit [this permit-count nano-time] (fn (:beehive (meta this)) permit-count)) (releasePermit [this permit-count nano-time] ) (releasePermit [this permit-count result nano-time] ) (registerGuardRail [this guard-rail])) {:clj? true})))
[ { "context": "rred to DARPA’s Public Release Center via email at prc@darpa.mil.\n\n(ns mbroker.util\n (:require [mbroker.rabbitmq ", "end": 172, "score": 0.9999170899391174, "start": 159, "tag": "EMAIL", "value": "prc@darpa.mil" }, { "context": " ex-info (@state exch)\n routing-key \"network_visualization\"\n channel (:channel ex-info)]\n\n (printl", "end": 839, "score": 0.9776161313056946, "start": 818, "tag": "KEY", "value": "network_visualization" } ]
src/mbroker/util.clj
paulratdollabs/drl007
0
;; DISTRIBUTION STATEMENT C: U.S. Government agencies and their contractors. ;; Other requests shall be referred to DARPA’s Public Release Center via email at prc@darpa.mil. (ns mbroker.util (:require [mbroker.rabbitmq :as q] [tpn.fromjson] [langohr.basic :as lb] [clojure.pprint :refer :all] [clojure.data.json :as json])) (defonce state (atom {})) (defn merge-state! [m] (swap! state merge m)) (defn setup [exch-name config] (if (@state exch-name) (println "Already have connection for " exch-name) (merge-state! {exch-name (q/make-channel exch-name config)}))) (defn send-msg-str [msg & exch-name] (let [exch (if (first exch-name) (first exch-name) "tpn-updates") ex-info (@state exch) routing-key "network_visualization" channel (:channel ex-info)] (println "to exchange" exch) (pprint ex-info) (lb/publish channel exch routing-key msg))) (defn send-msg [clj-data & exch] (send-msg-str (json/write-str clj-data) exch)) (defn payload-to-json [payload] (let [data (String. payload "UTF-8") js (tpn.fromjson/map-from-json-str data)] js))
17693
;; DISTRIBUTION STATEMENT C: U.S. Government agencies and their contractors. ;; Other requests shall be referred to DARPA’s Public Release Center via email at <EMAIL>. (ns mbroker.util (:require [mbroker.rabbitmq :as q] [tpn.fromjson] [langohr.basic :as lb] [clojure.pprint :refer :all] [clojure.data.json :as json])) (defonce state (atom {})) (defn merge-state! [m] (swap! state merge m)) (defn setup [exch-name config] (if (@state exch-name) (println "Already have connection for " exch-name) (merge-state! {exch-name (q/make-channel exch-name config)}))) (defn send-msg-str [msg & exch-name] (let [exch (if (first exch-name) (first exch-name) "tpn-updates") ex-info (@state exch) routing-key "<KEY>" channel (:channel ex-info)] (println "to exchange" exch) (pprint ex-info) (lb/publish channel exch routing-key msg))) (defn send-msg [clj-data & exch] (send-msg-str (json/write-str clj-data) exch)) (defn payload-to-json [payload] (let [data (String. payload "UTF-8") js (tpn.fromjson/map-from-json-str data)] js))
true
;; DISTRIBUTION STATEMENT C: U.S. Government agencies and their contractors. ;; Other requests shall be referred to DARPA’s Public Release Center via email at PI:EMAIL:<EMAIL>END_PI. (ns mbroker.util (:require [mbroker.rabbitmq :as q] [tpn.fromjson] [langohr.basic :as lb] [clojure.pprint :refer :all] [clojure.data.json :as json])) (defonce state (atom {})) (defn merge-state! [m] (swap! state merge m)) (defn setup [exch-name config] (if (@state exch-name) (println "Already have connection for " exch-name) (merge-state! {exch-name (q/make-channel exch-name config)}))) (defn send-msg-str [msg & exch-name] (let [exch (if (first exch-name) (first exch-name) "tpn-updates") ex-info (@state exch) routing-key "PI:KEY:<KEY>END_PI" channel (:channel ex-info)] (println "to exchange" exch) (pprint ex-info) (lb/publish channel exch routing-key msg))) (defn send-msg [clj-data & exch] (send-msg-str (json/write-str clj-data) exch)) (defn payload-to-json [payload] (let [data (String. payload "UTF-8") js (tpn.fromjson/map-from-json-str data)] js))
[ { "context": "tps://github.com/fnzc/jwt-verify-jwks\"\n :author \"Jeremy Farnault\"\n :license {:name \"MIT License\"\n :url", "end": 163, "score": 0.9998863339424133, "start": 148, "tag": "NAME", "value": "Jeremy Farnault" }, { "context": "\n :target-path \"target/%s\"\n :signing {:gpg-key \"02EEBEC3BBA039DDBE31A35C85759108682528DE\"}\n :profiles {:uberjar {:aot :all}})\n", "end": 727, "score": 0.9995217323303223, "start": 687, "tag": "KEY", "value": "02EEBEC3BBA039DDBE31A35C85759108682528DE" } ]
project.clj
fnzc/jwt-verify-jwks
3
(defproject jwt-verify-jwks "1.0.3" :description "Validate a JWT based on a JWKS url" :url "https://github.com/fnzc/jwt-verify-jwks" :author "Jeremy Farnault" :license {:name "MIT License" :url "https://github.com/fnzc/jwt-verify-jwks/blob/master/LICENSE"} :dependencies [[org.clojure/clojure "1.10.1"] [buddy/buddy-core "1.6.0"] [buddy/buddy-sign "3.1.0"] [clj-crypto "1.0.2" :exclusions [org.bouncycastle/bcprov-jdk15on]] [clj-http "3.10.0"]] :min-lein-version "2.0.0" :source-paths ["src"] :deploy-repositories [["releases" :clojars]] :target-path "target/%s" :signing {:gpg-key "02EEBEC3BBA039DDBE31A35C85759108682528DE"} :profiles {:uberjar {:aot :all}})
84932
(defproject jwt-verify-jwks "1.0.3" :description "Validate a JWT based on a JWKS url" :url "https://github.com/fnzc/jwt-verify-jwks" :author "<NAME>" :license {:name "MIT License" :url "https://github.com/fnzc/jwt-verify-jwks/blob/master/LICENSE"} :dependencies [[org.clojure/clojure "1.10.1"] [buddy/buddy-core "1.6.0"] [buddy/buddy-sign "3.1.0"] [clj-crypto "1.0.2" :exclusions [org.bouncycastle/bcprov-jdk15on]] [clj-http "3.10.0"]] :min-lein-version "2.0.0" :source-paths ["src"] :deploy-repositories [["releases" :clojars]] :target-path "target/%s" :signing {:gpg-key "<KEY>"} :profiles {:uberjar {:aot :all}})
true
(defproject jwt-verify-jwks "1.0.3" :description "Validate a JWT based on a JWKS url" :url "https://github.com/fnzc/jwt-verify-jwks" :author "PI:NAME:<NAME>END_PI" :license {:name "MIT License" :url "https://github.com/fnzc/jwt-verify-jwks/blob/master/LICENSE"} :dependencies [[org.clojure/clojure "1.10.1"] [buddy/buddy-core "1.6.0"] [buddy/buddy-sign "3.1.0"] [clj-crypto "1.0.2" :exclusions [org.bouncycastle/bcprov-jdk15on]] [clj-http "3.10.0"]] :min-lein-version "2.0.0" :source-paths ["src"] :deploy-repositories [["releases" :clojars]] :target-path "target/%s" :signing {:gpg-key "PI:KEY:<KEY>END_PI"} :profiles {:uberjar {:aot :all}})
[ { "context": "sword. With handlers\"\n (let [request {:password \"password\" :username \"test@test.no\" :email \"test@test.no\"}\n", "end": 750, "score": 0.998656153678894, "start": 742, "tag": "PASSWORD", "value": "password" }, { "context": "\n (let [request {:password \"password\" :username \"test@test.no\" :email \"test@test.no\"}\n user (handler/cre", "end": 775, "score": 0.9998955726623535, "start": 763, "tag": "EMAIL", "value": "test@test.no" }, { "context": "sword \"password\" :username \"test@test.no\" :email \"test@test.no\"}\n user (handler/create-user request)\n ", "end": 797, "score": 0.9999086260795593, "start": 785, "tag": "EMAIL", "value": "test@test.no" }, { "context": "ssword {:user_id (:id user) :password (:password \"e8ms2cu1fese7h8k6fcog\")})))))\n\n(deftest get-all-data\n \"Creates some da", "end": 1420, "score": 0.999483048915863, "start": 1399, "tag": "PASSWORD", "value": "e8ms2cu1fese7h8k6fcog" }, { "context": "nt\"\n (let [user (handler/create-user {:password \"password\" :username \"test@test.no\" :email \"test@test.no\"})", "end": 1577, "score": 0.9990339279174805, "start": 1569, "tag": "PASSWORD", "value": "password" }, { "context": "dler/create-user {:password \"password\" :username \"test@test.no\" :email \"test@test.no\"})\n r {:identity use", "end": 1602, "score": 0.9999220967292786, "start": 1590, "tag": "EMAIL", "value": "test@test.no" }, { "context": "sword \"password\" :username \"test@test.no\" :email \"test@test.no\"})\n r {:identity user}\n user2 (hand", "end": 1624, "score": 0.999916672706604, "start": 1612, "tag": "EMAIL", "value": "test@test.no" }, { "context": "r}\n user2 (handler/create-user {:password \"password\" :username \"test2@test.no\" :email \"test2@test.no\"", "end": 1710, "score": 0.9992207288742065, "start": 1702, "tag": "PASSWORD", "value": "password" }, { "context": "dler/create-user {:password \"password\" :username \"test2@test.no\" :email \"test2@test.no\"})\n r2 {:identity u", "end": 1736, "score": 0.9999229311943054, "start": 1723, "tag": "EMAIL", "value": "test2@test.no" }, { "context": "word \"password\" :username \"test2@test.no\" :email \"test2@test.no\"})\n r2 {:identity user2}\n activatio", "end": 1759, "score": 0.9999014735221863, "start": 1746, "tag": "EMAIL", "value": "test2@test.no" }, { "context": "ate-user activation-token)\n habit1 {:name \"piano\" :owner_id (parseLong (:id user))}\n habit2", "end": 1931, "score": 0.8038582801818848, "start": 1926, "tag": "USERNAME", "value": "piano" } ]
groove-api/test/groove/handlers/user_test.clj
MrLys/vicissitudes
1
(ns groove.handlers.user-test (:require [clojure.test :refer :all] [groove.util.utils :refer [parseLong create-activation-token]] [groove.util.validation :refer :all] [groove.bulwark :as blwrk] [groove.db-test-utils :refer :all] [groove.handlers.user :as handler] [groove.handlers.habit :as habit-handler] [groove.handlers.groove :as groove-handler] [groove.handlers.team :as team-handler] [groove.test-utils :refer :all] [groove.db :as db])) (deftest create-user-and-password-token "Test creation of a user, activation, forgot password password, then update password. With handlers" (let [request {:password "password" :username "test@test.no" :email "test@test.no"} user (handler/create-user request) activation-token (db/get-token-by-user-id (:id user)) token (handler/forgot-password-handler (:email request))] (and (is (nil? (:error user))) (is (> (:id user) 0)) (is (nil? (:error activation-token))) (is (valid-token? activation-token)) (is (blwrk/activate-user activation-token)) (is (nil? (:error token))) (is (valid-token? token)) (is (= (:user_id token) (:id user))) (is (not (:user token))) (is (handler/update-user-password {:user_id (:id user) :password (:password "e8ms2cu1fese7h8k6fcog")}))))) (deftest get-all-data "Creates some data, uses get-all-data to verify all data is present" (let [user (handler/create-user {:password "password" :username "test@test.no" :email "test@test.no"}) r {:identity user} user2 (handler/create-user {:password "password" :username "test2@test.no" :email "test2@test.no"}) r2 {:identity user2} activation-token (db/get-token-by-user-id (:id user)) _ (blwrk/activate-user activation-token) habit1 {:name "piano" :owner_id (parseLong (:id user))} habit2 {:name "exercise" :owner_id (parseLong (:id user))} habit3 {:name "exercise" :owner_id (parseLong (:id user2))} h1 (blwrk/create-habit habit1 r) h2 (blwrk/create-habit habit2 r) h3 (blwrk/create-habit habit3 r2) today (java.time.LocalDate/now java.time.ZoneOffset/UTC) g1 (create-groove r h1 today -5 "success") g2 (create-groove r h1 today -4 "success") g3 (create-groove r h2 today -3 "success") g4 (create-groove r h2 today 0 "fail") g5 (create-groove r h2 today -22 "success") g6 (create-groove r2 h3 today -1 "success") _ (groove-handler/update-groove g1 r) _ (groove-handler/update-groove g2 r) _ (groove-handler/update-groove g3 r) _ (groove-handler/update-groove g4 r) _ (groove-handler/update-groove g5 r) _ (groove-handler/update-groove g6 r2) t1 (team-handler/create-team r "Superteam") t2 (team-handler/create-team r2 "Not so good team") all-data (handler/get-all-data r)] (println all-data) (and (is (nil? (:error all-data))) (is (= (:id (:user all-data)) (:id user))) (is (= (:username (:user all-data) (:username user)))) (is (= (:email (:user all-data) (:email user)))) (is (= (count (:teams (:user all-data))) 1)) (is (= (:name (:teams (:user all-data))) (:name t1))) (is (= (count (:habits (:user all-data))) 2)) (is (= (:name ((keyword (:name habit1)) (:habits (:user all-data)))) (:name habit1))) (is (= (:name ((keyword (:name habit2)) (:habits (:user all-data)))) (:name habit2))) (is (= (count (:grooves ((keyword (:name habit1)) (:habits (:user all-data))))) 2)) (is (= (count (:grooves ((keyword (:name habit2)) (:habits (:user all-data))))) 3))))) (use-fixtures :once once-fixture) (use-fixtures :each each-fixture)
32799
(ns groove.handlers.user-test (:require [clojure.test :refer :all] [groove.util.utils :refer [parseLong create-activation-token]] [groove.util.validation :refer :all] [groove.bulwark :as blwrk] [groove.db-test-utils :refer :all] [groove.handlers.user :as handler] [groove.handlers.habit :as habit-handler] [groove.handlers.groove :as groove-handler] [groove.handlers.team :as team-handler] [groove.test-utils :refer :all] [groove.db :as db])) (deftest create-user-and-password-token "Test creation of a user, activation, forgot password password, then update password. With handlers" (let [request {:password "<PASSWORD>" :username "<EMAIL>" :email "<EMAIL>"} user (handler/create-user request) activation-token (db/get-token-by-user-id (:id user)) token (handler/forgot-password-handler (:email request))] (and (is (nil? (:error user))) (is (> (:id user) 0)) (is (nil? (:error activation-token))) (is (valid-token? activation-token)) (is (blwrk/activate-user activation-token)) (is (nil? (:error token))) (is (valid-token? token)) (is (= (:user_id token) (:id user))) (is (not (:user token))) (is (handler/update-user-password {:user_id (:id user) :password (:password "<PASSWORD>")}))))) (deftest get-all-data "Creates some data, uses get-all-data to verify all data is present" (let [user (handler/create-user {:password "<PASSWORD>" :username "<EMAIL>" :email "<EMAIL>"}) r {:identity user} user2 (handler/create-user {:password "<PASSWORD>" :username "<EMAIL>" :email "<EMAIL>"}) r2 {:identity user2} activation-token (db/get-token-by-user-id (:id user)) _ (blwrk/activate-user activation-token) habit1 {:name "piano" :owner_id (parseLong (:id user))} habit2 {:name "exercise" :owner_id (parseLong (:id user))} habit3 {:name "exercise" :owner_id (parseLong (:id user2))} h1 (blwrk/create-habit habit1 r) h2 (blwrk/create-habit habit2 r) h3 (blwrk/create-habit habit3 r2) today (java.time.LocalDate/now java.time.ZoneOffset/UTC) g1 (create-groove r h1 today -5 "success") g2 (create-groove r h1 today -4 "success") g3 (create-groove r h2 today -3 "success") g4 (create-groove r h2 today 0 "fail") g5 (create-groove r h2 today -22 "success") g6 (create-groove r2 h3 today -1 "success") _ (groove-handler/update-groove g1 r) _ (groove-handler/update-groove g2 r) _ (groove-handler/update-groove g3 r) _ (groove-handler/update-groove g4 r) _ (groove-handler/update-groove g5 r) _ (groove-handler/update-groove g6 r2) t1 (team-handler/create-team r "Superteam") t2 (team-handler/create-team r2 "Not so good team") all-data (handler/get-all-data r)] (println all-data) (and (is (nil? (:error all-data))) (is (= (:id (:user all-data)) (:id user))) (is (= (:username (:user all-data) (:username user)))) (is (= (:email (:user all-data) (:email user)))) (is (= (count (:teams (:user all-data))) 1)) (is (= (:name (:teams (:user all-data))) (:name t1))) (is (= (count (:habits (:user all-data))) 2)) (is (= (:name ((keyword (:name habit1)) (:habits (:user all-data)))) (:name habit1))) (is (= (:name ((keyword (:name habit2)) (:habits (:user all-data)))) (:name habit2))) (is (= (count (:grooves ((keyword (:name habit1)) (:habits (:user all-data))))) 2)) (is (= (count (:grooves ((keyword (:name habit2)) (:habits (:user all-data))))) 3))))) (use-fixtures :once once-fixture) (use-fixtures :each each-fixture)
true
(ns groove.handlers.user-test (:require [clojure.test :refer :all] [groove.util.utils :refer [parseLong create-activation-token]] [groove.util.validation :refer :all] [groove.bulwark :as blwrk] [groove.db-test-utils :refer :all] [groove.handlers.user :as handler] [groove.handlers.habit :as habit-handler] [groove.handlers.groove :as groove-handler] [groove.handlers.team :as team-handler] [groove.test-utils :refer :all] [groove.db :as db])) (deftest create-user-and-password-token "Test creation of a user, activation, forgot password password, then update password. With handlers" (let [request {:password "PI:PASSWORD:<PASSWORD>END_PI" :username "PI:EMAIL:<EMAIL>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"} user (handler/create-user request) activation-token (db/get-token-by-user-id (:id user)) token (handler/forgot-password-handler (:email request))] (and (is (nil? (:error user))) (is (> (:id user) 0)) (is (nil? (:error activation-token))) (is (valid-token? activation-token)) (is (blwrk/activate-user activation-token)) (is (nil? (:error token))) (is (valid-token? token)) (is (= (:user_id token) (:id user))) (is (not (:user token))) (is (handler/update-user-password {:user_id (:id user) :password (:password "PI:PASSWORD:<PASSWORD>END_PI")}))))) (deftest get-all-data "Creates some data, uses get-all-data to verify all data is present" (let [user (handler/create-user {:password "PI:PASSWORD:<PASSWORD>END_PI" :username "PI:EMAIL:<EMAIL>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}) r {:identity user} user2 (handler/create-user {:password "PI:PASSWORD:<PASSWORD>END_PI" :username "PI:EMAIL:<EMAIL>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}) r2 {:identity user2} activation-token (db/get-token-by-user-id (:id user)) _ (blwrk/activate-user activation-token) habit1 {:name "piano" :owner_id (parseLong (:id user))} habit2 {:name "exercise" :owner_id (parseLong (:id user))} habit3 {:name "exercise" :owner_id (parseLong (:id user2))} h1 (blwrk/create-habit habit1 r) h2 (blwrk/create-habit habit2 r) h3 (blwrk/create-habit habit3 r2) today (java.time.LocalDate/now java.time.ZoneOffset/UTC) g1 (create-groove r h1 today -5 "success") g2 (create-groove r h1 today -4 "success") g3 (create-groove r h2 today -3 "success") g4 (create-groove r h2 today 0 "fail") g5 (create-groove r h2 today -22 "success") g6 (create-groove r2 h3 today -1 "success") _ (groove-handler/update-groove g1 r) _ (groove-handler/update-groove g2 r) _ (groove-handler/update-groove g3 r) _ (groove-handler/update-groove g4 r) _ (groove-handler/update-groove g5 r) _ (groove-handler/update-groove g6 r2) t1 (team-handler/create-team r "Superteam") t2 (team-handler/create-team r2 "Not so good team") all-data (handler/get-all-data r)] (println all-data) (and (is (nil? (:error all-data))) (is (= (:id (:user all-data)) (:id user))) (is (= (:username (:user all-data) (:username user)))) (is (= (:email (:user all-data) (:email user)))) (is (= (count (:teams (:user all-data))) 1)) (is (= (:name (:teams (:user all-data))) (:name t1))) (is (= (count (:habits (:user all-data))) 2)) (is (= (:name ((keyword (:name habit1)) (:habits (:user all-data)))) (:name habit1))) (is (= (:name ((keyword (:name habit2)) (:habits (:user all-data)))) (:name habit2))) (is (= (count (:grooves ((keyword (:name habit1)) (:habits (:user all-data))))) 2)) (is (= (count (:grooves ((keyword (:name habit2)) (:habits (:user all-data))))) 3))))) (use-fixtures :once once-fixture) (use-fixtures :each each-fixture)
[ { "context": " tm\n :art art\n :name name}\n parent-id (insert! db-con :levels record", "end": 12616, "score": 0.9678080081939697, "start": 12612, "tag": "NAME", "value": "name" } ]
src/mincer/data.clj
elrippoblue/mincer
0
(ns mincer.data (:gen-class) (:require [clojure.java.jdbc :as jdbc] [clojure.java.jdbc :refer [with-db-connection]] [clojure.string :refer [join upper-case]] [clojure.tools.logging :as log])) (def mincer-version "0.1.0-SNAPSHOT") ; updated with bumpversion (defn setup-db [db-con] ; maybe use DDL for schema (jdbc/db-do-commands db-con (jdbc/create-table-ddl :info [:key :string "NOT NULL"] [:value :string "DEFAULT ''" "NOT NULL"]) "CREATE UNIQUE INDEX info_key ON info(key)" "PRAGMA foreign_keys = ON" (jdbc/create-table-ddl :levels [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:name :string "NOT NULL"] [:tm :string] [:art :string] [:min :integer] ; NOTE can be nil if tm and art are set [:max :integer] ; NOTE can be nil if tm and art are set [:parent_id :integer "REFERENCES levels"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX parent_level ON levels(parent_id)" (jdbc/create-table-ddl :courses [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:key :string "NOT NULL"] [:degree :string "NOT NULL"] [:short_name :string "NOT NULL"] [:name :string "NOT NULL"] [:kzfa :string "NOT NULL"] [:po :string] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX course_key ON courses(key)" (jdbc/create-table-ddl :course_levels [:course_id "NOT NULL" "REFERENCES courses"] [:level_id "NOT NULL" "REFERENCES levels"]) "CREATE INDEX course_level_course ON course_levels(course_id)" "CREATE INDEX course_level_level ON course_levels(level_id)" (jdbc/create-table-ddl :course_modules [:course_id "NOT NULL" "REFERENCES courses"] [:module_id "NOT NULL" "REFERENCES modules"]) "CREATE INDEX course_module_course ON course_modules(course_id)" "CREATE INDEX course_module_module ON course_modules(module_id)" (jdbc/create-table-ddl :modules [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:level_id :integer "REFERENCES levels"] [:key :string "NOT NULL"] ; XXX consider discarding one of both [:name :string "NOT NULL"] [:title :string] [:pordnr :integer] [:mandatory :boolean] ; XXX do we a direct link to the course? [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) (jdbc/create-table-ddl :abstract_units [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:key :string "NOT NULL"] [:title :string "NOT NULL"] [:type :string "NOT NULL"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX abstract_unit_key ON abstract_units(key)" (jdbc/create-table-ddl :modules_abstract_units_semesters [:abstract_unit_id :int "NOT NULL" "REFERENCES abstract_units"] [:module_id :int "NOT NULL" "REFERENCES modules"] [:semester :int "NOT NULL"]) "CREATE INDEX modules_abstract_units_semesters_au_id ON modules_abstract_units_semesters(abstract_unit_id)" "CREATE INDEX modules_abstract_units_semesters_module_id ON modules_abstract_units_semesters(module_id)" (jdbc/create-table-ddl :unit_abstract_unit_semester [:unit_id :int "NOT NULL" "REFERENCES unit"] [:abstract_unit_id :int "NOT NULL" "REFERENCES abstract_unit"] [:semester :int "NOT NULL"]) "CREATE INDEX unit_abstract_unit_semester_unit_id ON unit_abstract_unit_semester(unit_id)" "CREATE INDEX unit_abstract_unit_semester_abstract_unit_id ON unit_abstract_unit_semester(abstract_unit_id)" (jdbc/create-table-ddl :units [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:unit_key :string "NOT NULL"] [:title :string "NOT NULL"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX unit_key ON units(unit_key)" (jdbc/create-table-ddl :groups [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:unit_id :int "NOT NULL" "REFERENCES units"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX group_unit_id ON groups(unit_id)" (jdbc/create-table-ddl :sessions [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:group_id :integer "NOT NULL" "REFERENCES groups"] [:day :string "NOT NULL"] [:time :integer "NOT NULL"] [:duration :integer "NOT NULL"] [:rhythm :integer "NOT NULL"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX session_group_id ON sessions(group_id)" (jdbc/create-table-ddl :log [:session_id :integer "NOT NULL" "REFERENCES sessions"] [:src_day :string] [:src_time :integer] [:target_day :string] [:target_time :integer] [:created_at :datetime :default :current_timestamp]) "CREATE INDEX log_session_id ON log(session_id)") (jdbc/insert! db-con :info {:key "schema_version" :value (str "v3.0")}) (jdbc/insert! db-con :info {:key "generator" :value (str "mincer" "-" mincer-version)})) (defn insert! [db-con table col] (log/debug "Saving to" table col) ((keyword "last_insert_rowid()") (first (jdbc/insert! db-con table col)))) (defn run-on-db [func] (let [database (.getPath (java.io.File/createTempFile "mince" ".sqlite3")) db-spec {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname database}] (log/debug database) (with-db-connection [db-con db-spec] (setup-db db-con) (func db-con)) ; return path to generated DB database)) (declare persist-courses) (defn store-unit-abstract-unit-semester [db-con unit-id semesters abstract-unit-ref] (let [[{:keys [id]}] (jdbc/query db-con ["SELECT id FROM abstract_units WHERE key = ?" (:id abstract-unit-ref)])] (if-not (nil? id) (mapv (fn [s] (insert! db-con :unit_abstract_unit_semester {:unit_id unit-id :abstract_unit_id id :semester s})) semesters) (log/debug "No au for " (:id abstract-unit-ref))))) (defn store-refs [db-con unit-id refs semesters] (mapv (partial store-unit-abstract-unit-semester db-con unit-id semesters) refs)) (defn store-session [db-con group-id session] (assert (= :session (:type session))) (insert! db-con :sessions (assoc (dissoc session :type) :group_id group-id))) (defn store-group [db-con unit-id {:keys [type sessions]}] (assert (= :group type) type) (let [group-id (insert! db-con :groups {:unit_id unit-id})] (mapv (partial store-session db-con group-id) sessions))) (defn store-unit [db-con {:keys [type id title semester groups refs]}] (assert (= :unit type)) (let [record {:unit_key id :title title} unit-id (insert! db-con :units record)] (mapv (partial store-group db-con unit-id) groups) (store-refs db-con unit-id refs semester))) (defn persist-units [db-con units] (mapv (partial store-unit db-con) units)) (defn store-stuff [db-con levels modules units] (persist-courses db-con levels modules) (persist-units db-con units)) (defn store-abstract-unit [db-con module-id {:keys [id title type semester]}] (let [record {:key id :title title :type (name type) } au-id (insert! db-con :abstract_units record) merge-table-fn (fn [sem] (insert! db-con :modules_abstract_units_semesters {:abstract_unit_id au-id :module_id module-id :semester sem}))] (mapv merge-table-fn semester))) (defmulti store-child (fn [child & args] (:type child))) (defmethod store-child :level [{:keys [:min max name tm art children]} db-con parent-id course-id modules] "Insert node into level table in db-con. Returns id of created record." (let [record {:parent_id parent-id :min min :max max :tm tm :art art :name name} parent-id (insert! db-con :levels record)] (doall (map (fn [l] (store-child l db-con parent-id course-id modules)) children)) ; return the id of the created record parent-id)) (defmethod store-child :module [{:keys [name id pordnr mandatory]} db-con parent-id course-id modules] (let [{:keys [title abstract-units course key]} (get modules id) record {:level_id parent-id :mandatory mandatory :key key :name name}] (log/debug (type title)) (if-not (nil? title) ; NOTE or use something else ; merge both module records (let [extended-record (merge record {:pordnr pordnr :title title}) module-id (insert! db-con :modules extended-record)] (insert! db-con :course_modules {:course_id course-id :module_id module-id}) (mapv (partial store-abstract-unit db-con module-id) abstract-units) ; return the id of the created record module-id)))) (defmethod store-child :default [child & args] (throw (IllegalArgumentException. (str (:type child))))) (defn store-course [db-con idx {:keys [kzfa degree course name po children]} modules] (let [params {:degree degree :key (upper-case (join "-" [degree course kzfa po])) :short_name course :kzfa kzfa ; XXX find a propper name for this :name name :po po}] (let [parent-id (insert! db-con :courses params) levels (mapv (fn [l] (store-child l db-con nil parent-id modules)) children)] ; insert course-level/parent-id pairs into course_level table (mapv (fn [l] (insert! db-con :course_levels {:course_id parent-id :level_id l})) levels)))) (defn persist-courses [db-con levels modules] (reduce-kv (fn [_ k v] (store-course db-con k v modules)) nil levels)) (defn persist [levels modules units] (run-on-db #(store-stuff % levels modules units)))
36538
(ns mincer.data (:gen-class) (:require [clojure.java.jdbc :as jdbc] [clojure.java.jdbc :refer [with-db-connection]] [clojure.string :refer [join upper-case]] [clojure.tools.logging :as log])) (def mincer-version "0.1.0-SNAPSHOT") ; updated with bumpversion (defn setup-db [db-con] ; maybe use DDL for schema (jdbc/db-do-commands db-con (jdbc/create-table-ddl :info [:key :string "NOT NULL"] [:value :string "DEFAULT ''" "NOT NULL"]) "CREATE UNIQUE INDEX info_key ON info(key)" "PRAGMA foreign_keys = ON" (jdbc/create-table-ddl :levels [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:name :string "NOT NULL"] [:tm :string] [:art :string] [:min :integer] ; NOTE can be nil if tm and art are set [:max :integer] ; NOTE can be nil if tm and art are set [:parent_id :integer "REFERENCES levels"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX parent_level ON levels(parent_id)" (jdbc/create-table-ddl :courses [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:key :string "NOT NULL"] [:degree :string "NOT NULL"] [:short_name :string "NOT NULL"] [:name :string "NOT NULL"] [:kzfa :string "NOT NULL"] [:po :string] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX course_key ON courses(key)" (jdbc/create-table-ddl :course_levels [:course_id "NOT NULL" "REFERENCES courses"] [:level_id "NOT NULL" "REFERENCES levels"]) "CREATE INDEX course_level_course ON course_levels(course_id)" "CREATE INDEX course_level_level ON course_levels(level_id)" (jdbc/create-table-ddl :course_modules [:course_id "NOT NULL" "REFERENCES courses"] [:module_id "NOT NULL" "REFERENCES modules"]) "CREATE INDEX course_module_course ON course_modules(course_id)" "CREATE INDEX course_module_module ON course_modules(module_id)" (jdbc/create-table-ddl :modules [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:level_id :integer "REFERENCES levels"] [:key :string "NOT NULL"] ; XXX consider discarding one of both [:name :string "NOT NULL"] [:title :string] [:pordnr :integer] [:mandatory :boolean] ; XXX do we a direct link to the course? [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) (jdbc/create-table-ddl :abstract_units [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:key :string "NOT NULL"] [:title :string "NOT NULL"] [:type :string "NOT NULL"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX abstract_unit_key ON abstract_units(key)" (jdbc/create-table-ddl :modules_abstract_units_semesters [:abstract_unit_id :int "NOT NULL" "REFERENCES abstract_units"] [:module_id :int "NOT NULL" "REFERENCES modules"] [:semester :int "NOT NULL"]) "CREATE INDEX modules_abstract_units_semesters_au_id ON modules_abstract_units_semesters(abstract_unit_id)" "CREATE INDEX modules_abstract_units_semesters_module_id ON modules_abstract_units_semesters(module_id)" (jdbc/create-table-ddl :unit_abstract_unit_semester [:unit_id :int "NOT NULL" "REFERENCES unit"] [:abstract_unit_id :int "NOT NULL" "REFERENCES abstract_unit"] [:semester :int "NOT NULL"]) "CREATE INDEX unit_abstract_unit_semester_unit_id ON unit_abstract_unit_semester(unit_id)" "CREATE INDEX unit_abstract_unit_semester_abstract_unit_id ON unit_abstract_unit_semester(abstract_unit_id)" (jdbc/create-table-ddl :units [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:unit_key :string "NOT NULL"] [:title :string "NOT NULL"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX unit_key ON units(unit_key)" (jdbc/create-table-ddl :groups [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:unit_id :int "NOT NULL" "REFERENCES units"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX group_unit_id ON groups(unit_id)" (jdbc/create-table-ddl :sessions [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:group_id :integer "NOT NULL" "REFERENCES groups"] [:day :string "NOT NULL"] [:time :integer "NOT NULL"] [:duration :integer "NOT NULL"] [:rhythm :integer "NOT NULL"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX session_group_id ON sessions(group_id)" (jdbc/create-table-ddl :log [:session_id :integer "NOT NULL" "REFERENCES sessions"] [:src_day :string] [:src_time :integer] [:target_day :string] [:target_time :integer] [:created_at :datetime :default :current_timestamp]) "CREATE INDEX log_session_id ON log(session_id)") (jdbc/insert! db-con :info {:key "schema_version" :value (str "v3.0")}) (jdbc/insert! db-con :info {:key "generator" :value (str "mincer" "-" mincer-version)})) (defn insert! [db-con table col] (log/debug "Saving to" table col) ((keyword "last_insert_rowid()") (first (jdbc/insert! db-con table col)))) (defn run-on-db [func] (let [database (.getPath (java.io.File/createTempFile "mince" ".sqlite3")) db-spec {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname database}] (log/debug database) (with-db-connection [db-con db-spec] (setup-db db-con) (func db-con)) ; return path to generated DB database)) (declare persist-courses) (defn store-unit-abstract-unit-semester [db-con unit-id semesters abstract-unit-ref] (let [[{:keys [id]}] (jdbc/query db-con ["SELECT id FROM abstract_units WHERE key = ?" (:id abstract-unit-ref)])] (if-not (nil? id) (mapv (fn [s] (insert! db-con :unit_abstract_unit_semester {:unit_id unit-id :abstract_unit_id id :semester s})) semesters) (log/debug "No au for " (:id abstract-unit-ref))))) (defn store-refs [db-con unit-id refs semesters] (mapv (partial store-unit-abstract-unit-semester db-con unit-id semesters) refs)) (defn store-session [db-con group-id session] (assert (= :session (:type session))) (insert! db-con :sessions (assoc (dissoc session :type) :group_id group-id))) (defn store-group [db-con unit-id {:keys [type sessions]}] (assert (= :group type) type) (let [group-id (insert! db-con :groups {:unit_id unit-id})] (mapv (partial store-session db-con group-id) sessions))) (defn store-unit [db-con {:keys [type id title semester groups refs]}] (assert (= :unit type)) (let [record {:unit_key id :title title} unit-id (insert! db-con :units record)] (mapv (partial store-group db-con unit-id) groups) (store-refs db-con unit-id refs semester))) (defn persist-units [db-con units] (mapv (partial store-unit db-con) units)) (defn store-stuff [db-con levels modules units] (persist-courses db-con levels modules) (persist-units db-con units)) (defn store-abstract-unit [db-con module-id {:keys [id title type semester]}] (let [record {:key id :title title :type (name type) } au-id (insert! db-con :abstract_units record) merge-table-fn (fn [sem] (insert! db-con :modules_abstract_units_semesters {:abstract_unit_id au-id :module_id module-id :semester sem}))] (mapv merge-table-fn semester))) (defmulti store-child (fn [child & args] (:type child))) (defmethod store-child :level [{:keys [:min max name tm art children]} db-con parent-id course-id modules] "Insert node into level table in db-con. Returns id of created record." (let [record {:parent_id parent-id :min min :max max :tm tm :art art :name <NAME>} parent-id (insert! db-con :levels record)] (doall (map (fn [l] (store-child l db-con parent-id course-id modules)) children)) ; return the id of the created record parent-id)) (defmethod store-child :module [{:keys [name id pordnr mandatory]} db-con parent-id course-id modules] (let [{:keys [title abstract-units course key]} (get modules id) record {:level_id parent-id :mandatory mandatory :key key :name name}] (log/debug (type title)) (if-not (nil? title) ; NOTE or use something else ; merge both module records (let [extended-record (merge record {:pordnr pordnr :title title}) module-id (insert! db-con :modules extended-record)] (insert! db-con :course_modules {:course_id course-id :module_id module-id}) (mapv (partial store-abstract-unit db-con module-id) abstract-units) ; return the id of the created record module-id)))) (defmethod store-child :default [child & args] (throw (IllegalArgumentException. (str (:type child))))) (defn store-course [db-con idx {:keys [kzfa degree course name po children]} modules] (let [params {:degree degree :key (upper-case (join "-" [degree course kzfa po])) :short_name course :kzfa kzfa ; XXX find a propper name for this :name name :po po}] (let [parent-id (insert! db-con :courses params) levels (mapv (fn [l] (store-child l db-con nil parent-id modules)) children)] ; insert course-level/parent-id pairs into course_level table (mapv (fn [l] (insert! db-con :course_levels {:course_id parent-id :level_id l})) levels)))) (defn persist-courses [db-con levels modules] (reduce-kv (fn [_ k v] (store-course db-con k v modules)) nil levels)) (defn persist [levels modules units] (run-on-db #(store-stuff % levels modules units)))
true
(ns mincer.data (:gen-class) (:require [clojure.java.jdbc :as jdbc] [clojure.java.jdbc :refer [with-db-connection]] [clojure.string :refer [join upper-case]] [clojure.tools.logging :as log])) (def mincer-version "0.1.0-SNAPSHOT") ; updated with bumpversion (defn setup-db [db-con] ; maybe use DDL for schema (jdbc/db-do-commands db-con (jdbc/create-table-ddl :info [:key :string "NOT NULL"] [:value :string "DEFAULT ''" "NOT NULL"]) "CREATE UNIQUE INDEX info_key ON info(key)" "PRAGMA foreign_keys = ON" (jdbc/create-table-ddl :levels [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:name :string "NOT NULL"] [:tm :string] [:art :string] [:min :integer] ; NOTE can be nil if tm and art are set [:max :integer] ; NOTE can be nil if tm and art are set [:parent_id :integer "REFERENCES levels"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX parent_level ON levels(parent_id)" (jdbc/create-table-ddl :courses [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:key :string "NOT NULL"] [:degree :string "NOT NULL"] [:short_name :string "NOT NULL"] [:name :string "NOT NULL"] [:kzfa :string "NOT NULL"] [:po :string] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX course_key ON courses(key)" (jdbc/create-table-ddl :course_levels [:course_id "NOT NULL" "REFERENCES courses"] [:level_id "NOT NULL" "REFERENCES levels"]) "CREATE INDEX course_level_course ON course_levels(course_id)" "CREATE INDEX course_level_level ON course_levels(level_id)" (jdbc/create-table-ddl :course_modules [:course_id "NOT NULL" "REFERENCES courses"] [:module_id "NOT NULL" "REFERENCES modules"]) "CREATE INDEX course_module_course ON course_modules(course_id)" "CREATE INDEX course_module_module ON course_modules(module_id)" (jdbc/create-table-ddl :modules [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:level_id :integer "REFERENCES levels"] [:key :string "NOT NULL"] ; XXX consider discarding one of both [:name :string "NOT NULL"] [:title :string] [:pordnr :integer] [:mandatory :boolean] ; XXX do we a direct link to the course? [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) (jdbc/create-table-ddl :abstract_units [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:key :string "NOT NULL"] [:title :string "NOT NULL"] [:type :string "NOT NULL"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX abstract_unit_key ON abstract_units(key)" (jdbc/create-table-ddl :modules_abstract_units_semesters [:abstract_unit_id :int "NOT NULL" "REFERENCES abstract_units"] [:module_id :int "NOT NULL" "REFERENCES modules"] [:semester :int "NOT NULL"]) "CREATE INDEX modules_abstract_units_semesters_au_id ON modules_abstract_units_semesters(abstract_unit_id)" "CREATE INDEX modules_abstract_units_semesters_module_id ON modules_abstract_units_semesters(module_id)" (jdbc/create-table-ddl :unit_abstract_unit_semester [:unit_id :int "NOT NULL" "REFERENCES unit"] [:abstract_unit_id :int "NOT NULL" "REFERENCES abstract_unit"] [:semester :int "NOT NULL"]) "CREATE INDEX unit_abstract_unit_semester_unit_id ON unit_abstract_unit_semester(unit_id)" "CREATE INDEX unit_abstract_unit_semester_abstract_unit_id ON unit_abstract_unit_semester(abstract_unit_id)" (jdbc/create-table-ddl :units [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:unit_key :string "NOT NULL"] [:title :string "NOT NULL"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX unit_key ON units(unit_key)" (jdbc/create-table-ddl :groups [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:unit_id :int "NOT NULL" "REFERENCES units"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX group_unit_id ON groups(unit_id)" (jdbc/create-table-ddl :sessions [:id :integer "PRIMARY KEY" "AUTOINCREMENT"] [:group_id :integer "NOT NULL" "REFERENCES groups"] [:day :string "NOT NULL"] [:time :integer "NOT NULL"] [:duration :integer "NOT NULL"] [:rhythm :integer "NOT NULL"] [:created_at :datetime :default :current_timestamp] [:updated_at :datetime :default :current_timestamp]) "CREATE INDEX session_group_id ON sessions(group_id)" (jdbc/create-table-ddl :log [:session_id :integer "NOT NULL" "REFERENCES sessions"] [:src_day :string] [:src_time :integer] [:target_day :string] [:target_time :integer] [:created_at :datetime :default :current_timestamp]) "CREATE INDEX log_session_id ON log(session_id)") (jdbc/insert! db-con :info {:key "schema_version" :value (str "v3.0")}) (jdbc/insert! db-con :info {:key "generator" :value (str "mincer" "-" mincer-version)})) (defn insert! [db-con table col] (log/debug "Saving to" table col) ((keyword "last_insert_rowid()") (first (jdbc/insert! db-con table col)))) (defn run-on-db [func] (let [database (.getPath (java.io.File/createTempFile "mince" ".sqlite3")) db-spec {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname database}] (log/debug database) (with-db-connection [db-con db-spec] (setup-db db-con) (func db-con)) ; return path to generated DB database)) (declare persist-courses) (defn store-unit-abstract-unit-semester [db-con unit-id semesters abstract-unit-ref] (let [[{:keys [id]}] (jdbc/query db-con ["SELECT id FROM abstract_units WHERE key = ?" (:id abstract-unit-ref)])] (if-not (nil? id) (mapv (fn [s] (insert! db-con :unit_abstract_unit_semester {:unit_id unit-id :abstract_unit_id id :semester s})) semesters) (log/debug "No au for " (:id abstract-unit-ref))))) (defn store-refs [db-con unit-id refs semesters] (mapv (partial store-unit-abstract-unit-semester db-con unit-id semesters) refs)) (defn store-session [db-con group-id session] (assert (= :session (:type session))) (insert! db-con :sessions (assoc (dissoc session :type) :group_id group-id))) (defn store-group [db-con unit-id {:keys [type sessions]}] (assert (= :group type) type) (let [group-id (insert! db-con :groups {:unit_id unit-id})] (mapv (partial store-session db-con group-id) sessions))) (defn store-unit [db-con {:keys [type id title semester groups refs]}] (assert (= :unit type)) (let [record {:unit_key id :title title} unit-id (insert! db-con :units record)] (mapv (partial store-group db-con unit-id) groups) (store-refs db-con unit-id refs semester))) (defn persist-units [db-con units] (mapv (partial store-unit db-con) units)) (defn store-stuff [db-con levels modules units] (persist-courses db-con levels modules) (persist-units db-con units)) (defn store-abstract-unit [db-con module-id {:keys [id title type semester]}] (let [record {:key id :title title :type (name type) } au-id (insert! db-con :abstract_units record) merge-table-fn (fn [sem] (insert! db-con :modules_abstract_units_semesters {:abstract_unit_id au-id :module_id module-id :semester sem}))] (mapv merge-table-fn semester))) (defmulti store-child (fn [child & args] (:type child))) (defmethod store-child :level [{:keys [:min max name tm art children]} db-con parent-id course-id modules] "Insert node into level table in db-con. Returns id of created record." (let [record {:parent_id parent-id :min min :max max :tm tm :art art :name PI:NAME:<NAME>END_PI} parent-id (insert! db-con :levels record)] (doall (map (fn [l] (store-child l db-con parent-id course-id modules)) children)) ; return the id of the created record parent-id)) (defmethod store-child :module [{:keys [name id pordnr mandatory]} db-con parent-id course-id modules] (let [{:keys [title abstract-units course key]} (get modules id) record {:level_id parent-id :mandatory mandatory :key key :name name}] (log/debug (type title)) (if-not (nil? title) ; NOTE or use something else ; merge both module records (let [extended-record (merge record {:pordnr pordnr :title title}) module-id (insert! db-con :modules extended-record)] (insert! db-con :course_modules {:course_id course-id :module_id module-id}) (mapv (partial store-abstract-unit db-con module-id) abstract-units) ; return the id of the created record module-id)))) (defmethod store-child :default [child & args] (throw (IllegalArgumentException. (str (:type child))))) (defn store-course [db-con idx {:keys [kzfa degree course name po children]} modules] (let [params {:degree degree :key (upper-case (join "-" [degree course kzfa po])) :short_name course :kzfa kzfa ; XXX find a propper name for this :name name :po po}] (let [parent-id (insert! db-con :courses params) levels (mapv (fn [l] (store-child l db-con nil parent-id modules)) children)] ; insert course-level/parent-id pairs into course_level table (mapv (fn [l] (insert! db-con :course_levels {:course_id parent-id :level_id l})) levels)))) (defn persist-courses [db-con levels modules] (reduce-kv (fn [_ k v] (store-course db-con k v modules)) nil levels)) (defn persist [levels modules units] (run-on-db #(store-stuff % levels modules units)))
[ { "context": "co/defresolver dat-files->api-calls [{:keys [::dat-files]}]\n {::api-calls (api-calls-from-dat-files ", "end": 41620, "score": 0.6142687201499939, "start": 41620, "tag": "KEY", "value": "" }, { "context": "\n\n ())\n\n(comment\n\n (process {::har-path \"/Users/paulo.feodrippe/Downloads/www.notion.so.har\"}\n [::api-s", "end": 44830, "score": 0.9703245162963867, "start": 44815, "tag": "USERNAME", "value": "paulo.feodrippe" }, { "context": "spec-provider`.\n ;; - [ ] Use https://github.com/FudanSELab/train-ticket for testing.\n ;; - [x] Use some rea", "end": 47113, "score": 0.9994689226150513, "start": 47103, "tag": "USERNAME", "value": "FudanSELab" } ]
src/pitoco/core.clj
ikitommi/pitoco
0
(ns pitoco.core (:require [babashka.process :as sh] [cheshire.core :as json] [clojure.edn :as edn] [clojure.java.io :as io] [clojure.string :as str] [clojure.test.check.generators :as gen] [clojure.walk :as walk] [lambdaisland.deep-diff2 :as ddiff] [lambdaisland.uri :as uri] [malli.core :as m] [malli.generator :as mg] [malli.registry :as mr] [malli.swagger :as swagger] [malli.util :as mu] [pitoco.api-schema :as api-schema] [spec-provider.stats :as stats] [tick.core :as t] ;; Pathom. [com.wsscode.pathom3.cache :as p.cache] [com.wsscode.pathom3.connect.built-in.resolvers :as pbir] [com.wsscode.pathom3.connect.built-in.plugins :as pbip] [com.wsscode.pathom3.connect.foreign :as pcf] [com.wsscode.pathom3.connect.indexes :as pci] [com.wsscode.pathom3.connect.operation :as pco] [com.wsscode.pathom3.connect.operation.transit :as pcot] [com.wsscode.pathom3.connect.planner :as pcp] [com.wsscode.pathom3.connect.runner :as pcr] [com.wsscode.pathom3.error :as p.error] [com.wsscode.pathom3.format.eql :as pf.eql] [com.wsscode.pathom3.interface.async.eql :as p.a.eql] [com.wsscode.pathom3.interface.eql :as p.eql] [com.wsscode.pathom3.interface.smart-map :as psm] [com.wsscode.pathom3.path :as p.path] [com.wsscode.pathom3.plugin :as p.plugin]) (:import (java.time.format DateTimeFormatter) (java.time LocalDate Instant) (rawhttp.core RawHttp) (lambdaisland.deep_diff2.diff_impl Mismatch Deletion Insertion))) (defn uuid-str? [s] (boolean (try (java.util.UUID/fromString s) (catch Exception _)))) (def UUIDStr (m/schema (m/-simple-schema {:type `UUIDStr :pred uuid-str? :type-properties {:json-schema/type "string" :json-schema/description `UUIDStr :gen/gen (gen/fmap str gen/uuid)}}))) (defn iso-date? [s] (boolean (try (LocalDate/parse s DateTimeFormatter/ISO_DATE) (catch Exception _)))) (def IsoDate (m/schema (m/-simple-schema {:type `IsoDate :pred iso-date? :type-properties {:json-schema/type "string" :json-schema/description `IsoDate :gen/gen (gen/fmap #(str (t/date (t/instant %))) (mg/generator inst?))}}))) (defn iso-instant? [s] (boolean (try (Instant/parse s) (catch Exception _)))) (def IsoInstant (m/schema (m/-simple-schema {:type `IsoInstant :pred iso-instant? :type-properties {:json-schema/type "string" :json-schema/description `IsoInstant :gen/gen (gen/fmap #(str (t/instant %)) (mg/generator inst?))}}))) (def default-string-data-formats [UUIDStr IsoDate IsoInstant]) (def default-data-formats (concat default-string-data-formats [])) (defn- json-parse-string "Don't simply use `keyword`, some of the keys can be degenerated and really should be kept as string. E.g. uuids or names of people." [s] (json/parse-string s (fn [k-str] ;; If our key is one of the fomatted ones or if it has a space, do not ;; convert it to a keyword ;; TODO: This appears to have some non-neligible performance hit, let's ;; check it later. (if (or (str/includes? k-str " ") (str/includes? k-str "@") (some #(when (m/validate % k-str) k-str) default-string-data-formats)) k-str (keyword k-str))))) (def default-registry (mr/composite-registry (m/-registry) (->> default-data-formats (mapv (fn [df] [(m/type df) df])) (into {})))) (defn process-options [{:keys [::schemas]}] {:registry (if schemas (mr/composite-registry default-registry (->> schemas (mapv (fn [sch] [(m/type sch) sch])) (into {}))) default-registry)}) (defn generate-sample ([schema] (generate-sample schema {})) ([schema options] (mg/generate schema (process-options options)))) (def ^:private original-preds stats/preds) (defn value-schema "Create schema for a single value. The type is itself." [v] (m/schema (m/-simple-schema {:type v :pred #(= % v) :type-properties {::itself? true :gen/gen (gen/elements [v])}}))) (defn- new-data-formats [schemas] (->> default-data-formats (concat schemas) (reduce (fn [acc data-format] ;; Prioritize first validators if there is a tie, we do this ;; by putting a check in the lower priority validators ;; that it's not one of higher priorities. (->> (m/-simple-schema ;; We only use `:type` and `:pred` and `:type-properties` ;; to infer the schema, so we only care about these here. {:type (m/type data-format) :pred #(boolean (when-not (some (fn [df] (m/validate df %)) acc) (m/validate data-format %))) :type-properties (m/type-properties data-format)}) (conj acc))) []))) (defn collect-stats [samples {existing-data-formats ::data-formats existing-stats ::stats :as options}] (binding [stats/preds (concat original-preds (mapv m/validator existing-data-formats))] (reduce (fn [stats x] (stats/update-stats stats x options)) existing-stats samples))) ;; TODO: Maybe find hash map patterns by storing their hashes while we iterate ;; over `stats`? (defn infer-schema "Infer schema from a collection of samples. `:symbol-format?` is `true` by default, it makes all the schemas symbols. Set it to `falsy` if you want the output in the form of preds/schemas." ([samples] (infer-schema samples {})) ([samples {:keys [:symbol-format? :debug? ::schemas] existing-data-formats ::data-formats existing-stats ::stats :or {symbol-format? true schemas []} :as options}] ;; We cannot have `existing-stats` set and not have the `existing-data-formats` ;; are not serializable and each new evaluation here (from `new-data-formats`) ;; would return different values. We will try to deal with it in the future. (when (and existing-stats (not existing-data-formats)) (throw (ex-info (str "`existing-data-formats` should have a value when `existing-stats` " "is not `nil`.") {:existing-stats existing-stats :existing-data-formats existing-data-formats}))) (let [data-formats' (or existing-data-formats (new-data-formats schemas)) ;; `data-formats` needs to be exactly the same to match correctly as ;; they use the preds for matching, which are just functions which ;; are created on the fly (not equal as each evaluation returns a ;; different function). We could work in the future to make them ;; serializable using `malli` itself (with `sci`). stats (collect-stats samples (assoc options ::data-formats data-formats')) ;; `itself` data formats are the ones which check to themselves. They ;; are used to represent keys in a map so you can have a less generic ;; type if all of the map keys are `itself`. itself-value? (fn [v] (->> data-formats' (filter #(-> % m/type-properties ::itself?)) (mapv #(m/validate % v)) (some true?))) validators (set (mapv m/validator data-formats')) ;; TODO: Let's try to make this as deterministic as possible ;; so we can compare schema data directly without having to ;; define a powerful form of equivalence. schema (fn schema [stats] ;; `rs` is a function which checks if we want to output a symbol ;; or a resolved function (the last serves better for generation ;; of samples and for equality in tests without having to use a ;; registry). (let [rs (memoize (fn [v] (if symbol-format? (if debug? ;; Attach metadata to each element. (with-meta v {:stats stats}) v) (-> v resolve deref)))) ;; We remove the preds which have a lower hierarchy (custom ones ;; always are in a higher level). invalid-original-validators (->> (::stats/pred-map stats) (remove (comp (conj validators map? set? sequential?) first)) (filter (fn [[spec-type]] (->> (::stats/distinct-values stats) (filter spec-type) (every? #(some (fn [type] (m/validate type %)) data-formats'))))) set) types' (->> (::stats/pred-map stats) (remove invalid-original-validators) (mapv (fn [[spec-type]] (let [data-format (delay (->> data-formats' (filter (comp #{spec-type} m/validator)) first)) res (delay (condp = spec-type map? (if (and (or (some-> stats ::stats/map ::stats/non-keyword-sample-count pos?) (some-> stats ::stats/map ::stats/mixed-sample-count pos?)) ;; If all preds are part of ;; a schema which checks itself, ;; (ignoring keywords), then ;; we have a one to one mapping ;; and we can use these schemas ;; as keys (no need for `:map-of`. (->> (get-in stats [::stats/map ::stats/keys]) keys (remove keyword?) (every? itself-value?) not)) ;; If we have some non keyword key, ;; we move to a more generic map ;; using `:map-of`. [:map-of (infer-schema (->> (get-in stats [::stats/map ::stats/keys]) keys ;; Convert any keyword to string ;; to be in sync with the JSON ;; format. (mapv #(if (keyword? %) (name %) %))) ;; We remove `::stats` here as ;; we want a clean slate for these. (dissoc options ::stats)) (let [map-of-types (some->> (get-in stats [::stats/map ::stats/keys]) vals (mapv #(schema %)) set)] (if (> (count map-of-types) 1) ;; Here we could have nested `:or`s ;; which could be simplified, but ;; not a priority now. (into [:or] (sort-by str map-of-types)) (first map-of-types)))] (->> (get-in stats [::stats/map ::stats/keys]) (mapv (fn [[k nested-stats]] ;; If some key has less samples ;; than the count of maps, then ;; this is a optional key. (if (< (::stats/sample-count nested-stats) (get-in stats [::stats/map ::stats/sample-count])) [k {:optional true} (schema nested-stats)] [k (schema nested-stats)]))) (sort-by first) (into [:map]))) string? (rs 'string?) integer? (rs 'int?) set? [:set (schema (::stats/elements-set stats))] sequential? [:sequential (schema (::stats/elements-coll stats))] nil? (rs 'nil?) stats/float? (rs 'number?) stats/double? (rs 'number?) decimal? (rs 'decimal?) number? (rs 'number?) boolean? (rs 'boolean?) inst? (rs 'inst?) symbol? (rs 'symbol?) keyword? (rs 'keyword?) nil))] (cond @res @res @data-format (m/type @data-format) :else (rs 'any?)))))) types (remove #{(rs 'any?) (rs 'nil?)} types')] (cond (zero? (count types')) (rs 'any?) ;; Convert `nil?` to `any?` as ;; it's very likely that a parameter ;; is not really only `nil`, it's only ;; that we are not testing all the ;; possible cases. (= (set types') #{(rs 'nil?)}) (rs 'any?) (= (count types') 1) (first types') (= (set types') #{(rs 'any?) (rs 'nil?)}) (rs 'any?) (some #{(rs 'nil?)} types') [:maybe (if (= (count types) 1) ;; When there is some `any?` together some other types, we can ;; get rid of the any. (first types) (into [:or] (sort-by str types)))] :else (if (= (count types) 1) (first types) (into [:or] (sort-by str types))))))] (schema stats)))) ;; TODO: Remove this. (defn pprint "See https://docs.cider.mx/cider/usage/pretty_printing.html. Used for cider output so it does not hang emacs when trying to print a long line, should be used for debug only." [value writer options] (apply clojure.pprint/write (try (walk/prewalk (fn [v] (if (and (string? v) (> (count v) 97)) (str (subs v 0 97) "...") v)) value) (catch Exception _ value)) (mapcat identity (assoc options :stream writer)))) (def default-regexes {#"(?<=\/)([0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})(?=/|\z)" "PITOCO_UUID" #"(?<=\/)(\d+)(?=/|\z)" "PITOCO_INT"}) (defn normalize-api-call "Normalize a API call path to a regex format. E.g. if the path is `/api/resource/12`, we will have the pat converted to `/api/resource/PITOCO_INT` (check `default-regexes`) " ([api-call] (normalize-api-call api-call default-regexes)) ([api-call regexes] (update-in api-call [:request :path] #(loop [s % [[regex identifier] & rest-regexes] regexes] (if regex (recur (str/replace s regex (str identifier)) rest-regexes) s))))) (defn dat-files-from-pcap-path [pcap-path] (let [folder-path (str (java.nio.file.Files/createTempDirectory "pitoco" (into-array java.nio.file.attribute.FileAttribute [])))] ;; Run `tcptrace` to generate the dat files. (-> (conj '[sh -c] (str "tcptrace -el " (.getAbsolutePath (io/file pcap-path)))) (sh/process {:out :string :err :string :dir folder-path}) :out deref str/split-lines) ;; Return all the generated `.dat` files. (->> (io/file folder-path) file-seq (filter #(str/includes? % ".dat"))))) ;; TODO: Infer headers; ;; TODO: Infer query params. (defn api-schemas-from-api-calls "Receives a collection of a map with `:request` and `:response` data. You can pass a `:pitoco.core/regexes` map from regexes to identifiers which will be used to try to identify paths which are in reality the same endpoint. Example of input (try it by copying it!). [{:request {:body nil :path \"/api/myresource/1\" :method :get :host \"myexample.com\"} :response {:body {:a 10} :status 200}} {:request {:body {:b \"30\"} :path \"/api/other/1\" :method :post :host \"myexample.com\"} :response {:body {:a 10} :status 200}}]" ([api-calls] (api-schemas-from-api-calls api-calls {})) ([api-calls {:keys [::regexes ::api-schemas ::data-formats ::schemas] :as options}] (let [ ;; Assoc `::data-formats` so we "initialize" it here. options (if data-formats options (assoc options ::data-formats (or (-> (meta api-schemas) ::data-formats) (new-data-formats schemas)))) group->api-schema (->> api-schemas (mapv (juxt #(select-keys % [:path :method :host]) identity)) (into {}))] (with-meta (merge (->> api-calls ;; Infer path template. (mapv #(normalize-api-call % (or regexes default-regexes))) ;; Only success for now, it may change in the future. (filter #(when-let [status (some-> % :response :status)] (<= 200 status 299))) (group-by #(select-keys (:request %) [:path :method :host])) (mapv (fn [[k samples]] [k (let [{:keys [:request-schema :response-schema]} (group->api-schema k) request-samples (mapv #(-> % :request :body) samples) request-stats (collect-stats request-samples (assoc options ::stats (-> request-schema meta ::stats))) response-samples (mapv #(-> % :response :body) samples) response-stats (collect-stats response-samples (assoc options ::stats (-> response-schema meta ::stats)))] (-> (merge k ;; Assoc `::stats` into metadata. ;; TODO: We probably could make this a record so we ;; can store things more explicitly. {::api-schema/id (hash k) :request-schema (with-meta (infer-schema request-samples (assoc options ::stats request-stats)) {::stats request-stats}) :response-schema (with-meta (infer-schema response-samples (assoc options ::stats response-stats)) {::stats response-stats})}) (with-meta {::api-calls samples})))])) (into {}) ;; Merge existing api schemas, if any. (merge group->api-schema) (mapv last) (sort-by (juxt :host :path :method)) doall)) {::data-formats (::data-formats options)})))) (def ^:private string-method->keyword-method {"GET" :get "POST" :post "PUT" :put "HEAD" :head "DELETE" :delete "PATCH" :patch}) (defn- json-content-type? [api-call] (or (:json-content-type? (:request api-call)) (:json-content-type? (:response api-call)))) (defn api-calls-from-har-path [har-file-path'] (let [har-file-path (.getAbsolutePath (io/file har-file-path')) har-map (json/parse-string (slurp har-file-path) keyword)] (->> (get-in har-map [:log :entries]) (mapv (fn [entry] (let [{:keys [:host :path] :as uri} (uri/uri (-> entry :request :url)) request-headers (->> (-> entry :request :headers) (group-by :name) (mapv (fn [[name headers]] [(-> name str/lower-case keyword) (mapv :value headers)])) (into {})) response-headers (->> (-> entry :response :headers) (group-by :name) (mapv (fn [[name headers]] [(-> name str/lower-case keyword) (mapv :value headers)])) (into {}))] {:request {:file-origin har-file-path :body (try (-> entry :request :postData :text json-parse-string) (catch Exception _ (-> entry :request :postData :text))) :json-content-type? (some #(str/includes? % "json") (:content-type request-headers)) :headers request-headers :path path :method (string-method->keyword-method (-> entry :request :method)) :host host :uri uri} :response {:file-origin har-file-path :body (try (-> entry :response :content :text json-parse-string) (catch Exception _ (-> entry :response :content :text))) :json-content-type? (some #(str/includes? % "json") (:content-type response-headers)) :headers response-headers :status (-> entry :response :status)}}))) (filter json-content-type?)))) (defn api-calls-from-dat-files "`dat-files` are generated using `tcptrace`." [dat-files] (->> dat-files (group-by #(let [file-name (.getName %) identifier (-> file-name (str/split #"_") first) [client server] (str/split identifier #"2")] (sort [(io/file (str (.getParent %) "/" file-name)) (io/file (str (.getParent %) "/" (format "%s2%s_contents.dat" server client)))]))) keys (map-indexed vector) (pmap (fn [[idx [file-1 file-2]]] (let [read-stream (fn read-stream [file] ;; Return `nil` if file does not exist. (when (.exists file) (let [ ;; Try to read requests requests (with-open [is (io/input-stream file)] (try (let [raw-http (RawHttp.)] (loop [acc []] (if (pos? (.available is)) (let [request (.eagerly (.parseRequest raw-http is)) headers (->> (.getHeaders request) .asMap (mapv (fn [entry] [(-> (key entry) str/lower-case keyword) (val entry)])) (into {})) content-types (:content-type headers) ;; `body` is of type Optional<EagerBodyReader> body (.getBody request) json? (some #(str/includes? % "json") content-types) uri (uri/uri (.getUri request))] (->> {:file-origin (str file) :json-content-type? json? :body (cond (not (.isPresent body)) nil (and (seq content-types) (some #(str/includes? % "json") content-types)) (try (json-parse-string (str (.get body))) (catch Exception _ "")) :else "") :headers headers :method (string-method->keyword-method (.getMethod request)) :path (:path uri) :host (if (seq (:port uri)) (str (:host uri) ":" (:port uri)) (:host uri)) :uri uri} (conj acc) recur)) acc))) ;; If some exception happened, then it means that ;; this is a response. (catch Exception _ nil))) ;; Try to read response if `requests` is `nil`. responses (when-not requests ;; There are times where the response is incomplete, ;; so we will just ignore these cases. (try (with-open [is (io/input-stream file)] (let [raw-http (RawHttp.)] (loop [acc []] (if (pos? (.available is)) (let [response (.eagerly (.parseResponse raw-http is)) headers (->> (.getHeaders response) .asMap (mapv (fn [entry] [(-> (key entry) str/lower-case keyword) (val entry)])) (into {})) content-types (:content-type headers) ;; `body` is of type Optional<EagerBodyReader> body (.getBody response) json? (some #(str/includes? % "json") content-types)] (->> {:file-origin (str file) :json-content-type? json? :body (cond (not (.isPresent body)) nil (and (seq content-types) (some #(str/includes? % "json") content-types)) (try (json-parse-string (str (.get body))) (catch Exception _ "")) :else "") :headers headers :status (.getStatusCode response)} (conj acc) recur)) acc)))) (catch Exception _ nil)))] (or requests responses)))) file-1-results (read-stream file-1) file-2-results (read-stream file-2)] (when (zero? (mod idx 500)) (println :done (str idx "/" (count dat-files)) :file-path (str file-1))) ;; Find which is the request file. (if (:host (first file-1-results)) (mapv (fn [result-1 result-2] {:request result-1 :response result-2}) file-1-results file-2-results) (mapv (fn [result-1 result-2] {:request result-2 :response result-1}) file-1-results file-2-results))))) (apply concat) (filter json-content-type?) doall)) ;; TODO: Make default registry a dynamic variable (?). (defn openapi-3-from-api-schemas ([api-schemas] (openapi-3-from-api-schemas api-schemas {})) ([api-schemas {:keys [::regexes] :or {regexes default-regexes} :as options}] {:openapi "3.0.1" :info {:version "1.0.0" :title "My Schemas"} :servers [{:url "/"}] :paths (->> api-schemas (group-by #(select-keys % [:host :path])) (mapv (fn [[{:keys [:path]} schemas]] (let [pattern (->> regexes vals (str/join "|") re-pattern) splitted-str (str/split path pattern) path-params (->> (re-seq pattern path) (map-indexed (fn [idx v] {:in :path :name (format "arg%s" idx) :schema {:type :string} :description v :required true}))) path' (or (some->> path-params seq (mapv #(format "{%s}" (:name %))) (interleave splitted-str) (str/join "")) path) path' (if (and (> (count splitted-str) 1) (< (count path-params) (count splitted-str))) ;; Add last element of splitted str so we ;; don't have a bougs path. (str path' (last splitted-str)) path')] {path' (->> schemas (mapv (fn [{:keys [:method :request-schema :response-schema]}] {method (merge {:parameters path-params :responses {200 {:content {"*/*" {:schema (swagger/transform response-schema (process-options options))}} :description "Responses."}}} (when-not (contains? #{'nil? 'any?} request-schema) {:requestBody {:content {"*/*" {:schema (swagger/transform request-schema (process-options options))}} :required true}}))})) (apply merge))}))) (apply merge))})) (defn- contains-diff? [v] ;; If the key or the value contains a diff ;; instance, keep it. (or (instance? Mismatch v) (instance? Deletion v) (instance? Insertion v) (let [result-atom (atom false)] (walk/prewalk (fn [form] (when (or (instance? Mismatch form) (instance? Deletion form) (instance? Insertion form)) (reset! result-atom true)) form) v) @result-atom))) (defn- get-subschemas [schema options] (->> (mu/subschemas schema (process-options options)) (mu/distinct-by :id) pr-str edn/read-string (mapv #(select-keys % [:path :schema])) (mapv (juxt first identity)))) (defn api-request-subschemas-from-api-schema [api-schema options] (get-subschemas (:request-schema api-schema) options)) (defn api-response-subschemas-from-api-schema [api-schema options] (get-subschemas (:response-schema api-schema) options)) (defn diff-api-schemas ([base-api-schemas new-api-schemas] (diff-api-schemas base-api-schemas new-api-schemas {})) ([base-api-schemas new-api-schemas options] (let [removed-api-schemas (->> base-api-schemas (mapv (fn [original-api-schema] (when-not (->> new-api-schemas (filter #(= (select-keys % [:path :method :host]) (select-keys original-api-schema [:path :method :host]))) first) (-> original-api-schema (dissoc :response-schema :request-schema) (merge {:response-schema-diff ::api-schema/removed :request-schema-diff ::api-schema/removed}))))) (remove nil?))] (->> new-api-schemas (mapv (fn [new-api-schema] (if-let [original-api-schema (->> base-api-schemas (filter #(= (select-keys % [:path :method :host]) (select-keys new-api-schema [:path :method :host]))) first)] (-> new-api-schema (dissoc :response-schema :request-schema) (merge {:response-schema-diff (->> (ddiff/diff (get-subschemas (:response-schema original-api-schema) options) (get-subschemas (:response-schema new-api-schema) options)) (filter contains-diff?) seq) :request-schema-diff (->> (ddiff/diff (get-subschemas (:request-schema original-api-schema) options) (get-subschemas (:request-schema new-api-schema) options)) (filter contains-diff?) seq)})) (-> new-api-schema (dissoc :response-schema :request-schema) (merge {:response-schema-diff ::api-schema/new :request-schema-diff ::api-schema/new}))))) (concat removed-api-schemas) (sort-by (juxt :host :path :method)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;; PATHOM ;;;;;;;;;;;;;;;;;;;;;;;;; (pco/defresolver pcap-path->dat-files [{:keys [::pcap-path]}] {::dat-files (dat-files-from-pcap-path pcap-path)}) (pco/defresolver har-path->api-calls [{:keys [::har-path]}] {::api-calls (api-calls-from-har-path har-path)}) (pco/defresolver dat-files->api-calls [{:keys [::dat-files]}] {::api-calls (api-calls-from-dat-files dat-files)}) ;; TODO: Make these options come from the main query so we don't have to ;; repeat them everywhere! (pco/defresolver api-calls->api-schemas [env {:keys [::api-calls]}] {::api-schemas (api-schemas-from-api-calls api-calls (pco/params env))}) (pco/defresolver api-schema->api-calls [api-schema] {::pco/input [::api-schema/id]} {::api-calls (::api-calls (meta api-schema))}) (pco/defresolver api-schemas->openapi-3 [env {:keys [::api-schemas]}] {::openapi-3 (openapi-3-from-api-schemas api-schemas (pco/params env))}) (pco/defresolver api-schemas-diff-resolver [env {:keys [::base ::api-schemas]}] {::pco/input [{::base [::api-schemas]} ::api-schemas]} {::api-schemas-diff (diff-api-schemas (::api-schemas base) api-schemas (pco/params env))}) (pco/defresolver api-schema->api-request-subschemas [env api-schema] {::pco/input [::api-schema/id :request-schema]} {::request-subschemas (api-request-subschemas-from-api-schema api-schema (pco/params env))}) (pco/defresolver api-schema->api-response-subschemas [env api-schema] {::pco/input [::api-schema/id :response-schema]} {::response-subschemas (api-response-subschemas-from-api-schema api-schema (pco/params env))}) (def pathom-env (pci/register [pcap-path->dat-files har-path->api-calls dat-files->api-calls api-calls->api-schemas api-schemas->openapi-3 api-schema->api-calls api-schemas-diff-resolver api-schema->api-request-subschemas api-schema->api-response-subschemas])) (defn process ([tx] (p.eql/process pathom-env tx)) ([entity tx] (p.eql/process pathom-env entity tx))) (comment ;; We can get the schemas from a pcap path. (process {::pcap-path "resources-test/pcap-files/dump.pcap"} [::api-schemas]) (process [{[::pcap-path "resources-test/pcap-files/dump2.pcap"] [{::api-schemas ['* ::request-subschemas ::response-subschemas]}]}]) ;; But we also can get other info derived from a pcap path (e.g. openapi-3 ;; schema). (process {::pcap-path "resources-test/pcap-files/dump.pcap"} [::api-schemas ::openapi-3]) ;; Here we fetch the api schemas, then the api-calls and ;; open api 3 related to each api schema. Also we get open api 3 ;; for everyone. So we can mix and match things freely. (process {::pcap-path "resources-test/pcap-files/dump.pcap"} [{::api-schemas ['* ::api-calls ::openapi-3]} ::openapi-3]) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Diff ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (process {::pcap-path "resources-test/pcap-files/dump2.pcap" ::base {::pcap-path "resources-test/pcap-files/dump.pcap"}} [::api-schemas-diff]) (process [{'(:>/a {::pcap-path "resources-test/pcap-files/dump2.pcap" ::base {::pcap-path "resources-test/pcap-files/dump.pcap"}}) [::api-schemas-diff]}]) ()) (comment (process {::har-path "/Users/paulo.feodrippe/Downloads/www.notion.so.har"} [::api-schemas]) (def github-schemas (::api-schemas (process {::har-path "/Users/paulo.feodrippe/Downloads/github.com.har"} [::api-schemas]))) (->> (-> (process {::api-schemas github-schemas} [::openapi-3]) ::openapi-3 (json/generate-string {:pretty true})) (spit "github.json")) ()) (comment ;; TODO ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; CURRENT (in order!) ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; - [ ] Start web app. ;; - [ ] Give option to upload two files at FE. ;; - [ ] Show diffs at FE. ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; TBD or DONE ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; - [x] Group same method/path so it's added as a sample for the same ;; `mp/provide` call. ;; - [x] Improve grouping of API calls (EDIT: Let the user pass any regex). ;; - [ ] Separate query params from path and schematize it as well. ;; - [x] Accept HAR files. See https://support.zendesk.com/hc/en-us/articles/204410413-Generating-a-HAR-file-for-troubleshooting. ;; - [x] Generate OpenAPI 3 spec from REST endpoints. ;; - [x] Solve pipelined http requests. ;; - [x] Some data formats: ISO date format and UUID. ;; - [ ] See someway to do trace between multiple services. ;; - [ ] Parallelize inference(?). ;; - [x] Run `tcpdump` and `tcptrace` from Clojure. For `tcpdump`, maybe we ;; can even use some Java wrapper for `libpcap`. ;; - [ ] Use `libpcap` so we don't need `tcpdump` installed (?). ;; - [x] Group paths. ;; - [ ] Validate data (?). ;; - [ ] Create mock for `http-client-fake` so it can generate HAR files. ;; - [ ] Make it extensible? ;; - [ ] This is very much like integration tests + unit tests, while you ;; can unit test a method/function, the "real" usage (integr.) can create ;; a schema which can be used to check the data passed to unit tests. ;; - [ ] Create front end (not pretty, but also not ugly, please). ;; - [ ] Check what to show to the user. ;; - [ ] See other ways to output this data to the user (CLI, excel to an ;; email etc) (?). ;; - [x] Convert from clojure.spec to Malli (for schema generation with ;; `spec-provider`. ;; - [ ] Use https://github.com/FudanSELab/train-ticket for testing. ;; - [x] Use some real HTTP parser (or converter to HAR). ;; - [ ] Check if it's feasible to generate enums. ;; - [ ] Optimize some code. ;; - [ ] Add tests. ;; - [ ] Add zip code data format as if we were a user of the library. ;; - [ ] Recognize patterns (subschemas) and maybe add them dynamically ;; as new schemas. With it we can match patterns with other data and see ;; where they are used. ;; - [ ] Add timestamps to the request/response pairs (can we use ;; tcpdump/libpcap for it?). ;; - [ ] Refactor code of the schema parser in functions. ;; - [ ] Maybe add schema to our functions? ;; - [ ] Add some way to generate samples from our UI. ;; - [ ] Give options to store generated schema somewhere (S3 first?). ;; - [ ] Maybe show some possible values (`enum`) using a percentage over the ;; distinct samples. ;; - [ ] Show similar specs (e.g. one is a subset of another or how much this ;; this is like one another one). ;; - [ ] Maybe change the format of api-calls so it has more information and ;; it's more like the HAR file. ;; - [ ] Show schemas appearing in realtime in the FE. We can leverage the fact ;; that `stats/collect` returns a unique map which we can keep in some atom ;; and update it whenever some new file appears. We will keep track of the ;; .dat files created and create `api-calls` from it which will be "collected". ;; - [x] Give option to use existing api schemas stats. ;; - [ ] Accept `regal` so we can have automatic generators. ;; - [ ] Document public functions. ;; - [ ] Stream schemas? ;; - [ ] Create a library out of it only for the schemas (we have to be more ;; general about the types and NOT assume that the data is coming from ;; JSON. ;; - [x] Diff between schemas. ;; - [ ] Infer query params. ;; - [ ] Infer headers. ;; - [ ] Add origin so it's easy to know who called who. But there is no good ;; way to know it AFAIK with `tcptrace`. ;; - [x] Validate Cypress fixtures. Make it read schema from some source. ;; Better yet, we can generate HAR files using a Cypress plugin. ;; - [x] Generate Swagger API (low hanging fruit). Check if it's possible to ;; add metadata for custom formats. ;; - [ ] Add options to pass `options` using a dynamic var. ;; - [ ] Show diffs between two API schemas. ;; - [ ] Start FE. Show and search APIs (also in real time (?)). ;; - [ ] Show better validation error for Cypress fixtures (easier to understand). ;; - [ ] Suggest fix for Cypress fixtures (using generated data)? ;; - [ ] Measure other things like latency. ;; - [ ] Separate schemas per status code. Identify which ones are marked ;; as json and are not returning parseable json. ;; - [ ] User can create views with their own queries. ;; - [x] Call this library `Pitoco`. ;; - [x] Add Pathom so we don't need to create a lot of `-from` functions and ;; the data requested by the user can be just what he/she needs. ;; - [x] Create resolver to generate dat files from a pcap file. ;; - [ ] Add docker environment with non-usual dependencies (e.g. `tcptrace` ;; and `tcpdump`. ;; - [ ] Add possibilities of filtering data. E.g. get all with status from ;; 400 to 499, whoch one had schema changes (this is between two schemas), ;; by method, why is this content-type, but it's not parseable. Should ;; we query using `datascript`? ;; - [ ] Group api calls by status. ;; - [ ] Read file from S3. ;; - [ ] How can this tool be used for contract testing? ;; TODO - OTHERS: ;; - [ ] For `tla-edn`, make it convert empty domains to edn maps and empty ;; edn maps to empty domains. ;; - [ ] Add metadata to views so we can easily find the code for it. ;; - [ ] Make REPL for TLA+ with nRepl integration. ()) ;; Examples (to be used for testing).
58264
(ns pitoco.core (:require [babashka.process :as sh] [cheshire.core :as json] [clojure.edn :as edn] [clojure.java.io :as io] [clojure.string :as str] [clojure.test.check.generators :as gen] [clojure.walk :as walk] [lambdaisland.deep-diff2 :as ddiff] [lambdaisland.uri :as uri] [malli.core :as m] [malli.generator :as mg] [malli.registry :as mr] [malli.swagger :as swagger] [malli.util :as mu] [pitoco.api-schema :as api-schema] [spec-provider.stats :as stats] [tick.core :as t] ;; Pathom. [com.wsscode.pathom3.cache :as p.cache] [com.wsscode.pathom3.connect.built-in.resolvers :as pbir] [com.wsscode.pathom3.connect.built-in.plugins :as pbip] [com.wsscode.pathom3.connect.foreign :as pcf] [com.wsscode.pathom3.connect.indexes :as pci] [com.wsscode.pathom3.connect.operation :as pco] [com.wsscode.pathom3.connect.operation.transit :as pcot] [com.wsscode.pathom3.connect.planner :as pcp] [com.wsscode.pathom3.connect.runner :as pcr] [com.wsscode.pathom3.error :as p.error] [com.wsscode.pathom3.format.eql :as pf.eql] [com.wsscode.pathom3.interface.async.eql :as p.a.eql] [com.wsscode.pathom3.interface.eql :as p.eql] [com.wsscode.pathom3.interface.smart-map :as psm] [com.wsscode.pathom3.path :as p.path] [com.wsscode.pathom3.plugin :as p.plugin]) (:import (java.time.format DateTimeFormatter) (java.time LocalDate Instant) (rawhttp.core RawHttp) (lambdaisland.deep_diff2.diff_impl Mismatch Deletion Insertion))) (defn uuid-str? [s] (boolean (try (java.util.UUID/fromString s) (catch Exception _)))) (def UUIDStr (m/schema (m/-simple-schema {:type `UUIDStr :pred uuid-str? :type-properties {:json-schema/type "string" :json-schema/description `UUIDStr :gen/gen (gen/fmap str gen/uuid)}}))) (defn iso-date? [s] (boolean (try (LocalDate/parse s DateTimeFormatter/ISO_DATE) (catch Exception _)))) (def IsoDate (m/schema (m/-simple-schema {:type `IsoDate :pred iso-date? :type-properties {:json-schema/type "string" :json-schema/description `IsoDate :gen/gen (gen/fmap #(str (t/date (t/instant %))) (mg/generator inst?))}}))) (defn iso-instant? [s] (boolean (try (Instant/parse s) (catch Exception _)))) (def IsoInstant (m/schema (m/-simple-schema {:type `IsoInstant :pred iso-instant? :type-properties {:json-schema/type "string" :json-schema/description `IsoInstant :gen/gen (gen/fmap #(str (t/instant %)) (mg/generator inst?))}}))) (def default-string-data-formats [UUIDStr IsoDate IsoInstant]) (def default-data-formats (concat default-string-data-formats [])) (defn- json-parse-string "Don't simply use `keyword`, some of the keys can be degenerated and really should be kept as string. E.g. uuids or names of people." [s] (json/parse-string s (fn [k-str] ;; If our key is one of the fomatted ones or if it has a space, do not ;; convert it to a keyword ;; TODO: This appears to have some non-neligible performance hit, let's ;; check it later. (if (or (str/includes? k-str " ") (str/includes? k-str "@") (some #(when (m/validate % k-str) k-str) default-string-data-formats)) k-str (keyword k-str))))) (def default-registry (mr/composite-registry (m/-registry) (->> default-data-formats (mapv (fn [df] [(m/type df) df])) (into {})))) (defn process-options [{:keys [::schemas]}] {:registry (if schemas (mr/composite-registry default-registry (->> schemas (mapv (fn [sch] [(m/type sch) sch])) (into {}))) default-registry)}) (defn generate-sample ([schema] (generate-sample schema {})) ([schema options] (mg/generate schema (process-options options)))) (def ^:private original-preds stats/preds) (defn value-schema "Create schema for a single value. The type is itself." [v] (m/schema (m/-simple-schema {:type v :pred #(= % v) :type-properties {::itself? true :gen/gen (gen/elements [v])}}))) (defn- new-data-formats [schemas] (->> default-data-formats (concat schemas) (reduce (fn [acc data-format] ;; Prioritize first validators if there is a tie, we do this ;; by putting a check in the lower priority validators ;; that it's not one of higher priorities. (->> (m/-simple-schema ;; We only use `:type` and `:pred` and `:type-properties` ;; to infer the schema, so we only care about these here. {:type (m/type data-format) :pred #(boolean (when-not (some (fn [df] (m/validate df %)) acc) (m/validate data-format %))) :type-properties (m/type-properties data-format)}) (conj acc))) []))) (defn collect-stats [samples {existing-data-formats ::data-formats existing-stats ::stats :as options}] (binding [stats/preds (concat original-preds (mapv m/validator existing-data-formats))] (reduce (fn [stats x] (stats/update-stats stats x options)) existing-stats samples))) ;; TODO: Maybe find hash map patterns by storing their hashes while we iterate ;; over `stats`? (defn infer-schema "Infer schema from a collection of samples. `:symbol-format?` is `true` by default, it makes all the schemas symbols. Set it to `falsy` if you want the output in the form of preds/schemas." ([samples] (infer-schema samples {})) ([samples {:keys [:symbol-format? :debug? ::schemas] existing-data-formats ::data-formats existing-stats ::stats :or {symbol-format? true schemas []} :as options}] ;; We cannot have `existing-stats` set and not have the `existing-data-formats` ;; are not serializable and each new evaluation here (from `new-data-formats`) ;; would return different values. We will try to deal with it in the future. (when (and existing-stats (not existing-data-formats)) (throw (ex-info (str "`existing-data-formats` should have a value when `existing-stats` " "is not `nil`.") {:existing-stats existing-stats :existing-data-formats existing-data-formats}))) (let [data-formats' (or existing-data-formats (new-data-formats schemas)) ;; `data-formats` needs to be exactly the same to match correctly as ;; they use the preds for matching, which are just functions which ;; are created on the fly (not equal as each evaluation returns a ;; different function). We could work in the future to make them ;; serializable using `malli` itself (with `sci`). stats (collect-stats samples (assoc options ::data-formats data-formats')) ;; `itself` data formats are the ones which check to themselves. They ;; are used to represent keys in a map so you can have a less generic ;; type if all of the map keys are `itself`. itself-value? (fn [v] (->> data-formats' (filter #(-> % m/type-properties ::itself?)) (mapv #(m/validate % v)) (some true?))) validators (set (mapv m/validator data-formats')) ;; TODO: Let's try to make this as deterministic as possible ;; so we can compare schema data directly without having to ;; define a powerful form of equivalence. schema (fn schema [stats] ;; `rs` is a function which checks if we want to output a symbol ;; or a resolved function (the last serves better for generation ;; of samples and for equality in tests without having to use a ;; registry). (let [rs (memoize (fn [v] (if symbol-format? (if debug? ;; Attach metadata to each element. (with-meta v {:stats stats}) v) (-> v resolve deref)))) ;; We remove the preds which have a lower hierarchy (custom ones ;; always are in a higher level). invalid-original-validators (->> (::stats/pred-map stats) (remove (comp (conj validators map? set? sequential?) first)) (filter (fn [[spec-type]] (->> (::stats/distinct-values stats) (filter spec-type) (every? #(some (fn [type] (m/validate type %)) data-formats'))))) set) types' (->> (::stats/pred-map stats) (remove invalid-original-validators) (mapv (fn [[spec-type]] (let [data-format (delay (->> data-formats' (filter (comp #{spec-type} m/validator)) first)) res (delay (condp = spec-type map? (if (and (or (some-> stats ::stats/map ::stats/non-keyword-sample-count pos?) (some-> stats ::stats/map ::stats/mixed-sample-count pos?)) ;; If all preds are part of ;; a schema which checks itself, ;; (ignoring keywords), then ;; we have a one to one mapping ;; and we can use these schemas ;; as keys (no need for `:map-of`. (->> (get-in stats [::stats/map ::stats/keys]) keys (remove keyword?) (every? itself-value?) not)) ;; If we have some non keyword key, ;; we move to a more generic map ;; using `:map-of`. [:map-of (infer-schema (->> (get-in stats [::stats/map ::stats/keys]) keys ;; Convert any keyword to string ;; to be in sync with the JSON ;; format. (mapv #(if (keyword? %) (name %) %))) ;; We remove `::stats` here as ;; we want a clean slate for these. (dissoc options ::stats)) (let [map-of-types (some->> (get-in stats [::stats/map ::stats/keys]) vals (mapv #(schema %)) set)] (if (> (count map-of-types) 1) ;; Here we could have nested `:or`s ;; which could be simplified, but ;; not a priority now. (into [:or] (sort-by str map-of-types)) (first map-of-types)))] (->> (get-in stats [::stats/map ::stats/keys]) (mapv (fn [[k nested-stats]] ;; If some key has less samples ;; than the count of maps, then ;; this is a optional key. (if (< (::stats/sample-count nested-stats) (get-in stats [::stats/map ::stats/sample-count])) [k {:optional true} (schema nested-stats)] [k (schema nested-stats)]))) (sort-by first) (into [:map]))) string? (rs 'string?) integer? (rs 'int?) set? [:set (schema (::stats/elements-set stats))] sequential? [:sequential (schema (::stats/elements-coll stats))] nil? (rs 'nil?) stats/float? (rs 'number?) stats/double? (rs 'number?) decimal? (rs 'decimal?) number? (rs 'number?) boolean? (rs 'boolean?) inst? (rs 'inst?) symbol? (rs 'symbol?) keyword? (rs 'keyword?) nil))] (cond @res @res @data-format (m/type @data-format) :else (rs 'any?)))))) types (remove #{(rs 'any?) (rs 'nil?)} types')] (cond (zero? (count types')) (rs 'any?) ;; Convert `nil?` to `any?` as ;; it's very likely that a parameter ;; is not really only `nil`, it's only ;; that we are not testing all the ;; possible cases. (= (set types') #{(rs 'nil?)}) (rs 'any?) (= (count types') 1) (first types') (= (set types') #{(rs 'any?) (rs 'nil?)}) (rs 'any?) (some #{(rs 'nil?)} types') [:maybe (if (= (count types) 1) ;; When there is some `any?` together some other types, we can ;; get rid of the any. (first types) (into [:or] (sort-by str types)))] :else (if (= (count types) 1) (first types) (into [:or] (sort-by str types))))))] (schema stats)))) ;; TODO: Remove this. (defn pprint "See https://docs.cider.mx/cider/usage/pretty_printing.html. Used for cider output so it does not hang emacs when trying to print a long line, should be used for debug only." [value writer options] (apply clojure.pprint/write (try (walk/prewalk (fn [v] (if (and (string? v) (> (count v) 97)) (str (subs v 0 97) "...") v)) value) (catch Exception _ value)) (mapcat identity (assoc options :stream writer)))) (def default-regexes {#"(?<=\/)([0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})(?=/|\z)" "PITOCO_UUID" #"(?<=\/)(\d+)(?=/|\z)" "PITOCO_INT"}) (defn normalize-api-call "Normalize a API call path to a regex format. E.g. if the path is `/api/resource/12`, we will have the pat converted to `/api/resource/PITOCO_INT` (check `default-regexes`) " ([api-call] (normalize-api-call api-call default-regexes)) ([api-call regexes] (update-in api-call [:request :path] #(loop [s % [[regex identifier] & rest-regexes] regexes] (if regex (recur (str/replace s regex (str identifier)) rest-regexes) s))))) (defn dat-files-from-pcap-path [pcap-path] (let [folder-path (str (java.nio.file.Files/createTempDirectory "pitoco" (into-array java.nio.file.attribute.FileAttribute [])))] ;; Run `tcptrace` to generate the dat files. (-> (conj '[sh -c] (str "tcptrace -el " (.getAbsolutePath (io/file pcap-path)))) (sh/process {:out :string :err :string :dir folder-path}) :out deref str/split-lines) ;; Return all the generated `.dat` files. (->> (io/file folder-path) file-seq (filter #(str/includes? % ".dat"))))) ;; TODO: Infer headers; ;; TODO: Infer query params. (defn api-schemas-from-api-calls "Receives a collection of a map with `:request` and `:response` data. You can pass a `:pitoco.core/regexes` map from regexes to identifiers which will be used to try to identify paths which are in reality the same endpoint. Example of input (try it by copying it!). [{:request {:body nil :path \"/api/myresource/1\" :method :get :host \"myexample.com\"} :response {:body {:a 10} :status 200}} {:request {:body {:b \"30\"} :path \"/api/other/1\" :method :post :host \"myexample.com\"} :response {:body {:a 10} :status 200}}]" ([api-calls] (api-schemas-from-api-calls api-calls {})) ([api-calls {:keys [::regexes ::api-schemas ::data-formats ::schemas] :as options}] (let [ ;; Assoc `::data-formats` so we "initialize" it here. options (if data-formats options (assoc options ::data-formats (or (-> (meta api-schemas) ::data-formats) (new-data-formats schemas)))) group->api-schema (->> api-schemas (mapv (juxt #(select-keys % [:path :method :host]) identity)) (into {}))] (with-meta (merge (->> api-calls ;; Infer path template. (mapv #(normalize-api-call % (or regexes default-regexes))) ;; Only success for now, it may change in the future. (filter #(when-let [status (some-> % :response :status)] (<= 200 status 299))) (group-by #(select-keys (:request %) [:path :method :host])) (mapv (fn [[k samples]] [k (let [{:keys [:request-schema :response-schema]} (group->api-schema k) request-samples (mapv #(-> % :request :body) samples) request-stats (collect-stats request-samples (assoc options ::stats (-> request-schema meta ::stats))) response-samples (mapv #(-> % :response :body) samples) response-stats (collect-stats response-samples (assoc options ::stats (-> response-schema meta ::stats)))] (-> (merge k ;; Assoc `::stats` into metadata. ;; TODO: We probably could make this a record so we ;; can store things more explicitly. {::api-schema/id (hash k) :request-schema (with-meta (infer-schema request-samples (assoc options ::stats request-stats)) {::stats request-stats}) :response-schema (with-meta (infer-schema response-samples (assoc options ::stats response-stats)) {::stats response-stats})}) (with-meta {::api-calls samples})))])) (into {}) ;; Merge existing api schemas, if any. (merge group->api-schema) (mapv last) (sort-by (juxt :host :path :method)) doall)) {::data-formats (::data-formats options)})))) (def ^:private string-method->keyword-method {"GET" :get "POST" :post "PUT" :put "HEAD" :head "DELETE" :delete "PATCH" :patch}) (defn- json-content-type? [api-call] (or (:json-content-type? (:request api-call)) (:json-content-type? (:response api-call)))) (defn api-calls-from-har-path [har-file-path'] (let [har-file-path (.getAbsolutePath (io/file har-file-path')) har-map (json/parse-string (slurp har-file-path) keyword)] (->> (get-in har-map [:log :entries]) (mapv (fn [entry] (let [{:keys [:host :path] :as uri} (uri/uri (-> entry :request :url)) request-headers (->> (-> entry :request :headers) (group-by :name) (mapv (fn [[name headers]] [(-> name str/lower-case keyword) (mapv :value headers)])) (into {})) response-headers (->> (-> entry :response :headers) (group-by :name) (mapv (fn [[name headers]] [(-> name str/lower-case keyword) (mapv :value headers)])) (into {}))] {:request {:file-origin har-file-path :body (try (-> entry :request :postData :text json-parse-string) (catch Exception _ (-> entry :request :postData :text))) :json-content-type? (some #(str/includes? % "json") (:content-type request-headers)) :headers request-headers :path path :method (string-method->keyword-method (-> entry :request :method)) :host host :uri uri} :response {:file-origin har-file-path :body (try (-> entry :response :content :text json-parse-string) (catch Exception _ (-> entry :response :content :text))) :json-content-type? (some #(str/includes? % "json") (:content-type response-headers)) :headers response-headers :status (-> entry :response :status)}}))) (filter json-content-type?)))) (defn api-calls-from-dat-files "`dat-files` are generated using `tcptrace`." [dat-files] (->> dat-files (group-by #(let [file-name (.getName %) identifier (-> file-name (str/split #"_") first) [client server] (str/split identifier #"2")] (sort [(io/file (str (.getParent %) "/" file-name)) (io/file (str (.getParent %) "/" (format "%s2%s_contents.dat" server client)))]))) keys (map-indexed vector) (pmap (fn [[idx [file-1 file-2]]] (let [read-stream (fn read-stream [file] ;; Return `nil` if file does not exist. (when (.exists file) (let [ ;; Try to read requests requests (with-open [is (io/input-stream file)] (try (let [raw-http (RawHttp.)] (loop [acc []] (if (pos? (.available is)) (let [request (.eagerly (.parseRequest raw-http is)) headers (->> (.getHeaders request) .asMap (mapv (fn [entry] [(-> (key entry) str/lower-case keyword) (val entry)])) (into {})) content-types (:content-type headers) ;; `body` is of type Optional<EagerBodyReader> body (.getBody request) json? (some #(str/includes? % "json") content-types) uri (uri/uri (.getUri request))] (->> {:file-origin (str file) :json-content-type? json? :body (cond (not (.isPresent body)) nil (and (seq content-types) (some #(str/includes? % "json") content-types)) (try (json-parse-string (str (.get body))) (catch Exception _ "")) :else "") :headers headers :method (string-method->keyword-method (.getMethod request)) :path (:path uri) :host (if (seq (:port uri)) (str (:host uri) ":" (:port uri)) (:host uri)) :uri uri} (conj acc) recur)) acc))) ;; If some exception happened, then it means that ;; this is a response. (catch Exception _ nil))) ;; Try to read response if `requests` is `nil`. responses (when-not requests ;; There are times where the response is incomplete, ;; so we will just ignore these cases. (try (with-open [is (io/input-stream file)] (let [raw-http (RawHttp.)] (loop [acc []] (if (pos? (.available is)) (let [response (.eagerly (.parseResponse raw-http is)) headers (->> (.getHeaders response) .asMap (mapv (fn [entry] [(-> (key entry) str/lower-case keyword) (val entry)])) (into {})) content-types (:content-type headers) ;; `body` is of type Optional<EagerBodyReader> body (.getBody response) json? (some #(str/includes? % "json") content-types)] (->> {:file-origin (str file) :json-content-type? json? :body (cond (not (.isPresent body)) nil (and (seq content-types) (some #(str/includes? % "json") content-types)) (try (json-parse-string (str (.get body))) (catch Exception _ "")) :else "") :headers headers :status (.getStatusCode response)} (conj acc) recur)) acc)))) (catch Exception _ nil)))] (or requests responses)))) file-1-results (read-stream file-1) file-2-results (read-stream file-2)] (when (zero? (mod idx 500)) (println :done (str idx "/" (count dat-files)) :file-path (str file-1))) ;; Find which is the request file. (if (:host (first file-1-results)) (mapv (fn [result-1 result-2] {:request result-1 :response result-2}) file-1-results file-2-results) (mapv (fn [result-1 result-2] {:request result-2 :response result-1}) file-1-results file-2-results))))) (apply concat) (filter json-content-type?) doall)) ;; TODO: Make default registry a dynamic variable (?). (defn openapi-3-from-api-schemas ([api-schemas] (openapi-3-from-api-schemas api-schemas {})) ([api-schemas {:keys [::regexes] :or {regexes default-regexes} :as options}] {:openapi "3.0.1" :info {:version "1.0.0" :title "My Schemas"} :servers [{:url "/"}] :paths (->> api-schemas (group-by #(select-keys % [:host :path])) (mapv (fn [[{:keys [:path]} schemas]] (let [pattern (->> regexes vals (str/join "|") re-pattern) splitted-str (str/split path pattern) path-params (->> (re-seq pattern path) (map-indexed (fn [idx v] {:in :path :name (format "arg%s" idx) :schema {:type :string} :description v :required true}))) path' (or (some->> path-params seq (mapv #(format "{%s}" (:name %))) (interleave splitted-str) (str/join "")) path) path' (if (and (> (count splitted-str) 1) (< (count path-params) (count splitted-str))) ;; Add last element of splitted str so we ;; don't have a bougs path. (str path' (last splitted-str)) path')] {path' (->> schemas (mapv (fn [{:keys [:method :request-schema :response-schema]}] {method (merge {:parameters path-params :responses {200 {:content {"*/*" {:schema (swagger/transform response-schema (process-options options))}} :description "Responses."}}} (when-not (contains? #{'nil? 'any?} request-schema) {:requestBody {:content {"*/*" {:schema (swagger/transform request-schema (process-options options))}} :required true}}))})) (apply merge))}))) (apply merge))})) (defn- contains-diff? [v] ;; If the key or the value contains a diff ;; instance, keep it. (or (instance? Mismatch v) (instance? Deletion v) (instance? Insertion v) (let [result-atom (atom false)] (walk/prewalk (fn [form] (when (or (instance? Mismatch form) (instance? Deletion form) (instance? Insertion form)) (reset! result-atom true)) form) v) @result-atom))) (defn- get-subschemas [schema options] (->> (mu/subschemas schema (process-options options)) (mu/distinct-by :id) pr-str edn/read-string (mapv #(select-keys % [:path :schema])) (mapv (juxt first identity)))) (defn api-request-subschemas-from-api-schema [api-schema options] (get-subschemas (:request-schema api-schema) options)) (defn api-response-subschemas-from-api-schema [api-schema options] (get-subschemas (:response-schema api-schema) options)) (defn diff-api-schemas ([base-api-schemas new-api-schemas] (diff-api-schemas base-api-schemas new-api-schemas {})) ([base-api-schemas new-api-schemas options] (let [removed-api-schemas (->> base-api-schemas (mapv (fn [original-api-schema] (when-not (->> new-api-schemas (filter #(= (select-keys % [:path :method :host]) (select-keys original-api-schema [:path :method :host]))) first) (-> original-api-schema (dissoc :response-schema :request-schema) (merge {:response-schema-diff ::api-schema/removed :request-schema-diff ::api-schema/removed}))))) (remove nil?))] (->> new-api-schemas (mapv (fn [new-api-schema] (if-let [original-api-schema (->> base-api-schemas (filter #(= (select-keys % [:path :method :host]) (select-keys new-api-schema [:path :method :host]))) first)] (-> new-api-schema (dissoc :response-schema :request-schema) (merge {:response-schema-diff (->> (ddiff/diff (get-subschemas (:response-schema original-api-schema) options) (get-subschemas (:response-schema new-api-schema) options)) (filter contains-diff?) seq) :request-schema-diff (->> (ddiff/diff (get-subschemas (:request-schema original-api-schema) options) (get-subschemas (:request-schema new-api-schema) options)) (filter contains-diff?) seq)})) (-> new-api-schema (dissoc :response-schema :request-schema) (merge {:response-schema-diff ::api-schema/new :request-schema-diff ::api-schema/new}))))) (concat removed-api-schemas) (sort-by (juxt :host :path :method)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;; PATHOM ;;;;;;;;;;;;;;;;;;;;;;;;; (pco/defresolver pcap-path->dat-files [{:keys [::pcap-path]}] {::dat-files (dat-files-from-pcap-path pcap-path)}) (pco/defresolver har-path->api-calls [{:keys [::har-path]}] {::api-calls (api-calls-from-har-path har-path)}) (pco/defresolver dat-files->api-calls [{:keys [::dat<KEY>-files]}] {::api-calls (api-calls-from-dat-files dat-files)}) ;; TODO: Make these options come from the main query so we don't have to ;; repeat them everywhere! (pco/defresolver api-calls->api-schemas [env {:keys [::api-calls]}] {::api-schemas (api-schemas-from-api-calls api-calls (pco/params env))}) (pco/defresolver api-schema->api-calls [api-schema] {::pco/input [::api-schema/id]} {::api-calls (::api-calls (meta api-schema))}) (pco/defresolver api-schemas->openapi-3 [env {:keys [::api-schemas]}] {::openapi-3 (openapi-3-from-api-schemas api-schemas (pco/params env))}) (pco/defresolver api-schemas-diff-resolver [env {:keys [::base ::api-schemas]}] {::pco/input [{::base [::api-schemas]} ::api-schemas]} {::api-schemas-diff (diff-api-schemas (::api-schemas base) api-schemas (pco/params env))}) (pco/defresolver api-schema->api-request-subschemas [env api-schema] {::pco/input [::api-schema/id :request-schema]} {::request-subschemas (api-request-subschemas-from-api-schema api-schema (pco/params env))}) (pco/defresolver api-schema->api-response-subschemas [env api-schema] {::pco/input [::api-schema/id :response-schema]} {::response-subschemas (api-response-subschemas-from-api-schema api-schema (pco/params env))}) (def pathom-env (pci/register [pcap-path->dat-files har-path->api-calls dat-files->api-calls api-calls->api-schemas api-schemas->openapi-3 api-schema->api-calls api-schemas-diff-resolver api-schema->api-request-subschemas api-schema->api-response-subschemas])) (defn process ([tx] (p.eql/process pathom-env tx)) ([entity tx] (p.eql/process pathom-env entity tx))) (comment ;; We can get the schemas from a pcap path. (process {::pcap-path "resources-test/pcap-files/dump.pcap"} [::api-schemas]) (process [{[::pcap-path "resources-test/pcap-files/dump2.pcap"] [{::api-schemas ['* ::request-subschemas ::response-subschemas]}]}]) ;; But we also can get other info derived from a pcap path (e.g. openapi-3 ;; schema). (process {::pcap-path "resources-test/pcap-files/dump.pcap"} [::api-schemas ::openapi-3]) ;; Here we fetch the api schemas, then the api-calls and ;; open api 3 related to each api schema. Also we get open api 3 ;; for everyone. So we can mix and match things freely. (process {::pcap-path "resources-test/pcap-files/dump.pcap"} [{::api-schemas ['* ::api-calls ::openapi-3]} ::openapi-3]) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Diff ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (process {::pcap-path "resources-test/pcap-files/dump2.pcap" ::base {::pcap-path "resources-test/pcap-files/dump.pcap"}} [::api-schemas-diff]) (process [{'(:>/a {::pcap-path "resources-test/pcap-files/dump2.pcap" ::base {::pcap-path "resources-test/pcap-files/dump.pcap"}}) [::api-schemas-diff]}]) ()) (comment (process {::har-path "/Users/paulo.feodrippe/Downloads/www.notion.so.har"} [::api-schemas]) (def github-schemas (::api-schemas (process {::har-path "/Users/paulo.feodrippe/Downloads/github.com.har"} [::api-schemas]))) (->> (-> (process {::api-schemas github-schemas} [::openapi-3]) ::openapi-3 (json/generate-string {:pretty true})) (spit "github.json")) ()) (comment ;; TODO ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; CURRENT (in order!) ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; - [ ] Start web app. ;; - [ ] Give option to upload two files at FE. ;; - [ ] Show diffs at FE. ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; TBD or DONE ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; - [x] Group same method/path so it's added as a sample for the same ;; `mp/provide` call. ;; - [x] Improve grouping of API calls (EDIT: Let the user pass any regex). ;; - [ ] Separate query params from path and schematize it as well. ;; - [x] Accept HAR files. See https://support.zendesk.com/hc/en-us/articles/204410413-Generating-a-HAR-file-for-troubleshooting. ;; - [x] Generate OpenAPI 3 spec from REST endpoints. ;; - [x] Solve pipelined http requests. ;; - [x] Some data formats: ISO date format and UUID. ;; - [ ] See someway to do trace between multiple services. ;; - [ ] Parallelize inference(?). ;; - [x] Run `tcpdump` and `tcptrace` from Clojure. For `tcpdump`, maybe we ;; can even use some Java wrapper for `libpcap`. ;; - [ ] Use `libpcap` so we don't need `tcpdump` installed (?). ;; - [x] Group paths. ;; - [ ] Validate data (?). ;; - [ ] Create mock for `http-client-fake` so it can generate HAR files. ;; - [ ] Make it extensible? ;; - [ ] This is very much like integration tests + unit tests, while you ;; can unit test a method/function, the "real" usage (integr.) can create ;; a schema which can be used to check the data passed to unit tests. ;; - [ ] Create front end (not pretty, but also not ugly, please). ;; - [ ] Check what to show to the user. ;; - [ ] See other ways to output this data to the user (CLI, excel to an ;; email etc) (?). ;; - [x] Convert from clojure.spec to Malli (for schema generation with ;; `spec-provider`. ;; - [ ] Use https://github.com/FudanSELab/train-ticket for testing. ;; - [x] Use some real HTTP parser (or converter to HAR). ;; - [ ] Check if it's feasible to generate enums. ;; - [ ] Optimize some code. ;; - [ ] Add tests. ;; - [ ] Add zip code data format as if we were a user of the library. ;; - [ ] Recognize patterns (subschemas) and maybe add them dynamically ;; as new schemas. With it we can match patterns with other data and see ;; where they are used. ;; - [ ] Add timestamps to the request/response pairs (can we use ;; tcpdump/libpcap for it?). ;; - [ ] Refactor code of the schema parser in functions. ;; - [ ] Maybe add schema to our functions? ;; - [ ] Add some way to generate samples from our UI. ;; - [ ] Give options to store generated schema somewhere (S3 first?). ;; - [ ] Maybe show some possible values (`enum`) using a percentage over the ;; distinct samples. ;; - [ ] Show similar specs (e.g. one is a subset of another or how much this ;; this is like one another one). ;; - [ ] Maybe change the format of api-calls so it has more information and ;; it's more like the HAR file. ;; - [ ] Show schemas appearing in realtime in the FE. We can leverage the fact ;; that `stats/collect` returns a unique map which we can keep in some atom ;; and update it whenever some new file appears. We will keep track of the ;; .dat files created and create `api-calls` from it which will be "collected". ;; - [x] Give option to use existing api schemas stats. ;; - [ ] Accept `regal` so we can have automatic generators. ;; - [ ] Document public functions. ;; - [ ] Stream schemas? ;; - [ ] Create a library out of it only for the schemas (we have to be more ;; general about the types and NOT assume that the data is coming from ;; JSON. ;; - [x] Diff between schemas. ;; - [ ] Infer query params. ;; - [ ] Infer headers. ;; - [ ] Add origin so it's easy to know who called who. But there is no good ;; way to know it AFAIK with `tcptrace`. ;; - [x] Validate Cypress fixtures. Make it read schema from some source. ;; Better yet, we can generate HAR files using a Cypress plugin. ;; - [x] Generate Swagger API (low hanging fruit). Check if it's possible to ;; add metadata for custom formats. ;; - [ ] Add options to pass `options` using a dynamic var. ;; - [ ] Show diffs between two API schemas. ;; - [ ] Start FE. Show and search APIs (also in real time (?)). ;; - [ ] Show better validation error for Cypress fixtures (easier to understand). ;; - [ ] Suggest fix for Cypress fixtures (using generated data)? ;; - [ ] Measure other things like latency. ;; - [ ] Separate schemas per status code. Identify which ones are marked ;; as json and are not returning parseable json. ;; - [ ] User can create views with their own queries. ;; - [x] Call this library `Pitoco`. ;; - [x] Add Pathom so we don't need to create a lot of `-from` functions and ;; the data requested by the user can be just what he/she needs. ;; - [x] Create resolver to generate dat files from a pcap file. ;; - [ ] Add docker environment with non-usual dependencies (e.g. `tcptrace` ;; and `tcpdump`. ;; - [ ] Add possibilities of filtering data. E.g. get all with status from ;; 400 to 499, whoch one had schema changes (this is between two schemas), ;; by method, why is this content-type, but it's not parseable. Should ;; we query using `datascript`? ;; - [ ] Group api calls by status. ;; - [ ] Read file from S3. ;; - [ ] How can this tool be used for contract testing? ;; TODO - OTHERS: ;; - [ ] For `tla-edn`, make it convert empty domains to edn maps and empty ;; edn maps to empty domains. ;; - [ ] Add metadata to views so we can easily find the code for it. ;; - [ ] Make REPL for TLA+ with nRepl integration. ()) ;; Examples (to be used for testing).
true
(ns pitoco.core (:require [babashka.process :as sh] [cheshire.core :as json] [clojure.edn :as edn] [clojure.java.io :as io] [clojure.string :as str] [clojure.test.check.generators :as gen] [clojure.walk :as walk] [lambdaisland.deep-diff2 :as ddiff] [lambdaisland.uri :as uri] [malli.core :as m] [malli.generator :as mg] [malli.registry :as mr] [malli.swagger :as swagger] [malli.util :as mu] [pitoco.api-schema :as api-schema] [spec-provider.stats :as stats] [tick.core :as t] ;; Pathom. [com.wsscode.pathom3.cache :as p.cache] [com.wsscode.pathom3.connect.built-in.resolvers :as pbir] [com.wsscode.pathom3.connect.built-in.plugins :as pbip] [com.wsscode.pathom3.connect.foreign :as pcf] [com.wsscode.pathom3.connect.indexes :as pci] [com.wsscode.pathom3.connect.operation :as pco] [com.wsscode.pathom3.connect.operation.transit :as pcot] [com.wsscode.pathom3.connect.planner :as pcp] [com.wsscode.pathom3.connect.runner :as pcr] [com.wsscode.pathom3.error :as p.error] [com.wsscode.pathom3.format.eql :as pf.eql] [com.wsscode.pathom3.interface.async.eql :as p.a.eql] [com.wsscode.pathom3.interface.eql :as p.eql] [com.wsscode.pathom3.interface.smart-map :as psm] [com.wsscode.pathom3.path :as p.path] [com.wsscode.pathom3.plugin :as p.plugin]) (:import (java.time.format DateTimeFormatter) (java.time LocalDate Instant) (rawhttp.core RawHttp) (lambdaisland.deep_diff2.diff_impl Mismatch Deletion Insertion))) (defn uuid-str? [s] (boolean (try (java.util.UUID/fromString s) (catch Exception _)))) (def UUIDStr (m/schema (m/-simple-schema {:type `UUIDStr :pred uuid-str? :type-properties {:json-schema/type "string" :json-schema/description `UUIDStr :gen/gen (gen/fmap str gen/uuid)}}))) (defn iso-date? [s] (boolean (try (LocalDate/parse s DateTimeFormatter/ISO_DATE) (catch Exception _)))) (def IsoDate (m/schema (m/-simple-schema {:type `IsoDate :pred iso-date? :type-properties {:json-schema/type "string" :json-schema/description `IsoDate :gen/gen (gen/fmap #(str (t/date (t/instant %))) (mg/generator inst?))}}))) (defn iso-instant? [s] (boolean (try (Instant/parse s) (catch Exception _)))) (def IsoInstant (m/schema (m/-simple-schema {:type `IsoInstant :pred iso-instant? :type-properties {:json-schema/type "string" :json-schema/description `IsoInstant :gen/gen (gen/fmap #(str (t/instant %)) (mg/generator inst?))}}))) (def default-string-data-formats [UUIDStr IsoDate IsoInstant]) (def default-data-formats (concat default-string-data-formats [])) (defn- json-parse-string "Don't simply use `keyword`, some of the keys can be degenerated and really should be kept as string. E.g. uuids or names of people." [s] (json/parse-string s (fn [k-str] ;; If our key is one of the fomatted ones or if it has a space, do not ;; convert it to a keyword ;; TODO: This appears to have some non-neligible performance hit, let's ;; check it later. (if (or (str/includes? k-str " ") (str/includes? k-str "@") (some #(when (m/validate % k-str) k-str) default-string-data-formats)) k-str (keyword k-str))))) (def default-registry (mr/composite-registry (m/-registry) (->> default-data-formats (mapv (fn [df] [(m/type df) df])) (into {})))) (defn process-options [{:keys [::schemas]}] {:registry (if schemas (mr/composite-registry default-registry (->> schemas (mapv (fn [sch] [(m/type sch) sch])) (into {}))) default-registry)}) (defn generate-sample ([schema] (generate-sample schema {})) ([schema options] (mg/generate schema (process-options options)))) (def ^:private original-preds stats/preds) (defn value-schema "Create schema for a single value. The type is itself." [v] (m/schema (m/-simple-schema {:type v :pred #(= % v) :type-properties {::itself? true :gen/gen (gen/elements [v])}}))) (defn- new-data-formats [schemas] (->> default-data-formats (concat schemas) (reduce (fn [acc data-format] ;; Prioritize first validators if there is a tie, we do this ;; by putting a check in the lower priority validators ;; that it's not one of higher priorities. (->> (m/-simple-schema ;; We only use `:type` and `:pred` and `:type-properties` ;; to infer the schema, so we only care about these here. {:type (m/type data-format) :pred #(boolean (when-not (some (fn [df] (m/validate df %)) acc) (m/validate data-format %))) :type-properties (m/type-properties data-format)}) (conj acc))) []))) (defn collect-stats [samples {existing-data-formats ::data-formats existing-stats ::stats :as options}] (binding [stats/preds (concat original-preds (mapv m/validator existing-data-formats))] (reduce (fn [stats x] (stats/update-stats stats x options)) existing-stats samples))) ;; TODO: Maybe find hash map patterns by storing their hashes while we iterate ;; over `stats`? (defn infer-schema "Infer schema from a collection of samples. `:symbol-format?` is `true` by default, it makes all the schemas symbols. Set it to `falsy` if you want the output in the form of preds/schemas." ([samples] (infer-schema samples {})) ([samples {:keys [:symbol-format? :debug? ::schemas] existing-data-formats ::data-formats existing-stats ::stats :or {symbol-format? true schemas []} :as options}] ;; We cannot have `existing-stats` set and not have the `existing-data-formats` ;; are not serializable and each new evaluation here (from `new-data-formats`) ;; would return different values. We will try to deal with it in the future. (when (and existing-stats (not existing-data-formats)) (throw (ex-info (str "`existing-data-formats` should have a value when `existing-stats` " "is not `nil`.") {:existing-stats existing-stats :existing-data-formats existing-data-formats}))) (let [data-formats' (or existing-data-formats (new-data-formats schemas)) ;; `data-formats` needs to be exactly the same to match correctly as ;; they use the preds for matching, which are just functions which ;; are created on the fly (not equal as each evaluation returns a ;; different function). We could work in the future to make them ;; serializable using `malli` itself (with `sci`). stats (collect-stats samples (assoc options ::data-formats data-formats')) ;; `itself` data formats are the ones which check to themselves. They ;; are used to represent keys in a map so you can have a less generic ;; type if all of the map keys are `itself`. itself-value? (fn [v] (->> data-formats' (filter #(-> % m/type-properties ::itself?)) (mapv #(m/validate % v)) (some true?))) validators (set (mapv m/validator data-formats')) ;; TODO: Let's try to make this as deterministic as possible ;; so we can compare schema data directly without having to ;; define a powerful form of equivalence. schema (fn schema [stats] ;; `rs` is a function which checks if we want to output a symbol ;; or a resolved function (the last serves better for generation ;; of samples and for equality in tests without having to use a ;; registry). (let [rs (memoize (fn [v] (if symbol-format? (if debug? ;; Attach metadata to each element. (with-meta v {:stats stats}) v) (-> v resolve deref)))) ;; We remove the preds which have a lower hierarchy (custom ones ;; always are in a higher level). invalid-original-validators (->> (::stats/pred-map stats) (remove (comp (conj validators map? set? sequential?) first)) (filter (fn [[spec-type]] (->> (::stats/distinct-values stats) (filter spec-type) (every? #(some (fn [type] (m/validate type %)) data-formats'))))) set) types' (->> (::stats/pred-map stats) (remove invalid-original-validators) (mapv (fn [[spec-type]] (let [data-format (delay (->> data-formats' (filter (comp #{spec-type} m/validator)) first)) res (delay (condp = spec-type map? (if (and (or (some-> stats ::stats/map ::stats/non-keyword-sample-count pos?) (some-> stats ::stats/map ::stats/mixed-sample-count pos?)) ;; If all preds are part of ;; a schema which checks itself, ;; (ignoring keywords), then ;; we have a one to one mapping ;; and we can use these schemas ;; as keys (no need for `:map-of`. (->> (get-in stats [::stats/map ::stats/keys]) keys (remove keyword?) (every? itself-value?) not)) ;; If we have some non keyword key, ;; we move to a more generic map ;; using `:map-of`. [:map-of (infer-schema (->> (get-in stats [::stats/map ::stats/keys]) keys ;; Convert any keyword to string ;; to be in sync with the JSON ;; format. (mapv #(if (keyword? %) (name %) %))) ;; We remove `::stats` here as ;; we want a clean slate for these. (dissoc options ::stats)) (let [map-of-types (some->> (get-in stats [::stats/map ::stats/keys]) vals (mapv #(schema %)) set)] (if (> (count map-of-types) 1) ;; Here we could have nested `:or`s ;; which could be simplified, but ;; not a priority now. (into [:or] (sort-by str map-of-types)) (first map-of-types)))] (->> (get-in stats [::stats/map ::stats/keys]) (mapv (fn [[k nested-stats]] ;; If some key has less samples ;; than the count of maps, then ;; this is a optional key. (if (< (::stats/sample-count nested-stats) (get-in stats [::stats/map ::stats/sample-count])) [k {:optional true} (schema nested-stats)] [k (schema nested-stats)]))) (sort-by first) (into [:map]))) string? (rs 'string?) integer? (rs 'int?) set? [:set (schema (::stats/elements-set stats))] sequential? [:sequential (schema (::stats/elements-coll stats))] nil? (rs 'nil?) stats/float? (rs 'number?) stats/double? (rs 'number?) decimal? (rs 'decimal?) number? (rs 'number?) boolean? (rs 'boolean?) inst? (rs 'inst?) symbol? (rs 'symbol?) keyword? (rs 'keyword?) nil))] (cond @res @res @data-format (m/type @data-format) :else (rs 'any?)))))) types (remove #{(rs 'any?) (rs 'nil?)} types')] (cond (zero? (count types')) (rs 'any?) ;; Convert `nil?` to `any?` as ;; it's very likely that a parameter ;; is not really only `nil`, it's only ;; that we are not testing all the ;; possible cases. (= (set types') #{(rs 'nil?)}) (rs 'any?) (= (count types') 1) (first types') (= (set types') #{(rs 'any?) (rs 'nil?)}) (rs 'any?) (some #{(rs 'nil?)} types') [:maybe (if (= (count types) 1) ;; When there is some `any?` together some other types, we can ;; get rid of the any. (first types) (into [:or] (sort-by str types)))] :else (if (= (count types) 1) (first types) (into [:or] (sort-by str types))))))] (schema stats)))) ;; TODO: Remove this. (defn pprint "See https://docs.cider.mx/cider/usage/pretty_printing.html. Used for cider output so it does not hang emacs when trying to print a long line, should be used for debug only." [value writer options] (apply clojure.pprint/write (try (walk/prewalk (fn [v] (if (and (string? v) (> (count v) 97)) (str (subs v 0 97) "...") v)) value) (catch Exception _ value)) (mapcat identity (assoc options :stream writer)))) (def default-regexes {#"(?<=\/)([0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})(?=/|\z)" "PITOCO_UUID" #"(?<=\/)(\d+)(?=/|\z)" "PITOCO_INT"}) (defn normalize-api-call "Normalize a API call path to a regex format. E.g. if the path is `/api/resource/12`, we will have the pat converted to `/api/resource/PITOCO_INT` (check `default-regexes`) " ([api-call] (normalize-api-call api-call default-regexes)) ([api-call regexes] (update-in api-call [:request :path] #(loop [s % [[regex identifier] & rest-regexes] regexes] (if regex (recur (str/replace s regex (str identifier)) rest-regexes) s))))) (defn dat-files-from-pcap-path [pcap-path] (let [folder-path (str (java.nio.file.Files/createTempDirectory "pitoco" (into-array java.nio.file.attribute.FileAttribute [])))] ;; Run `tcptrace` to generate the dat files. (-> (conj '[sh -c] (str "tcptrace -el " (.getAbsolutePath (io/file pcap-path)))) (sh/process {:out :string :err :string :dir folder-path}) :out deref str/split-lines) ;; Return all the generated `.dat` files. (->> (io/file folder-path) file-seq (filter #(str/includes? % ".dat"))))) ;; TODO: Infer headers; ;; TODO: Infer query params. (defn api-schemas-from-api-calls "Receives a collection of a map with `:request` and `:response` data. You can pass a `:pitoco.core/regexes` map from regexes to identifiers which will be used to try to identify paths which are in reality the same endpoint. Example of input (try it by copying it!). [{:request {:body nil :path \"/api/myresource/1\" :method :get :host \"myexample.com\"} :response {:body {:a 10} :status 200}} {:request {:body {:b \"30\"} :path \"/api/other/1\" :method :post :host \"myexample.com\"} :response {:body {:a 10} :status 200}}]" ([api-calls] (api-schemas-from-api-calls api-calls {})) ([api-calls {:keys [::regexes ::api-schemas ::data-formats ::schemas] :as options}] (let [ ;; Assoc `::data-formats` so we "initialize" it here. options (if data-formats options (assoc options ::data-formats (or (-> (meta api-schemas) ::data-formats) (new-data-formats schemas)))) group->api-schema (->> api-schemas (mapv (juxt #(select-keys % [:path :method :host]) identity)) (into {}))] (with-meta (merge (->> api-calls ;; Infer path template. (mapv #(normalize-api-call % (or regexes default-regexes))) ;; Only success for now, it may change in the future. (filter #(when-let [status (some-> % :response :status)] (<= 200 status 299))) (group-by #(select-keys (:request %) [:path :method :host])) (mapv (fn [[k samples]] [k (let [{:keys [:request-schema :response-schema]} (group->api-schema k) request-samples (mapv #(-> % :request :body) samples) request-stats (collect-stats request-samples (assoc options ::stats (-> request-schema meta ::stats))) response-samples (mapv #(-> % :response :body) samples) response-stats (collect-stats response-samples (assoc options ::stats (-> response-schema meta ::stats)))] (-> (merge k ;; Assoc `::stats` into metadata. ;; TODO: We probably could make this a record so we ;; can store things more explicitly. {::api-schema/id (hash k) :request-schema (with-meta (infer-schema request-samples (assoc options ::stats request-stats)) {::stats request-stats}) :response-schema (with-meta (infer-schema response-samples (assoc options ::stats response-stats)) {::stats response-stats})}) (with-meta {::api-calls samples})))])) (into {}) ;; Merge existing api schemas, if any. (merge group->api-schema) (mapv last) (sort-by (juxt :host :path :method)) doall)) {::data-formats (::data-formats options)})))) (def ^:private string-method->keyword-method {"GET" :get "POST" :post "PUT" :put "HEAD" :head "DELETE" :delete "PATCH" :patch}) (defn- json-content-type? [api-call] (or (:json-content-type? (:request api-call)) (:json-content-type? (:response api-call)))) (defn api-calls-from-har-path [har-file-path'] (let [har-file-path (.getAbsolutePath (io/file har-file-path')) har-map (json/parse-string (slurp har-file-path) keyword)] (->> (get-in har-map [:log :entries]) (mapv (fn [entry] (let [{:keys [:host :path] :as uri} (uri/uri (-> entry :request :url)) request-headers (->> (-> entry :request :headers) (group-by :name) (mapv (fn [[name headers]] [(-> name str/lower-case keyword) (mapv :value headers)])) (into {})) response-headers (->> (-> entry :response :headers) (group-by :name) (mapv (fn [[name headers]] [(-> name str/lower-case keyword) (mapv :value headers)])) (into {}))] {:request {:file-origin har-file-path :body (try (-> entry :request :postData :text json-parse-string) (catch Exception _ (-> entry :request :postData :text))) :json-content-type? (some #(str/includes? % "json") (:content-type request-headers)) :headers request-headers :path path :method (string-method->keyword-method (-> entry :request :method)) :host host :uri uri} :response {:file-origin har-file-path :body (try (-> entry :response :content :text json-parse-string) (catch Exception _ (-> entry :response :content :text))) :json-content-type? (some #(str/includes? % "json") (:content-type response-headers)) :headers response-headers :status (-> entry :response :status)}}))) (filter json-content-type?)))) (defn api-calls-from-dat-files "`dat-files` are generated using `tcptrace`." [dat-files] (->> dat-files (group-by #(let [file-name (.getName %) identifier (-> file-name (str/split #"_") first) [client server] (str/split identifier #"2")] (sort [(io/file (str (.getParent %) "/" file-name)) (io/file (str (.getParent %) "/" (format "%s2%s_contents.dat" server client)))]))) keys (map-indexed vector) (pmap (fn [[idx [file-1 file-2]]] (let [read-stream (fn read-stream [file] ;; Return `nil` if file does not exist. (when (.exists file) (let [ ;; Try to read requests requests (with-open [is (io/input-stream file)] (try (let [raw-http (RawHttp.)] (loop [acc []] (if (pos? (.available is)) (let [request (.eagerly (.parseRequest raw-http is)) headers (->> (.getHeaders request) .asMap (mapv (fn [entry] [(-> (key entry) str/lower-case keyword) (val entry)])) (into {})) content-types (:content-type headers) ;; `body` is of type Optional<EagerBodyReader> body (.getBody request) json? (some #(str/includes? % "json") content-types) uri (uri/uri (.getUri request))] (->> {:file-origin (str file) :json-content-type? json? :body (cond (not (.isPresent body)) nil (and (seq content-types) (some #(str/includes? % "json") content-types)) (try (json-parse-string (str (.get body))) (catch Exception _ "")) :else "") :headers headers :method (string-method->keyword-method (.getMethod request)) :path (:path uri) :host (if (seq (:port uri)) (str (:host uri) ":" (:port uri)) (:host uri)) :uri uri} (conj acc) recur)) acc))) ;; If some exception happened, then it means that ;; this is a response. (catch Exception _ nil))) ;; Try to read response if `requests` is `nil`. responses (when-not requests ;; There are times where the response is incomplete, ;; so we will just ignore these cases. (try (with-open [is (io/input-stream file)] (let [raw-http (RawHttp.)] (loop [acc []] (if (pos? (.available is)) (let [response (.eagerly (.parseResponse raw-http is)) headers (->> (.getHeaders response) .asMap (mapv (fn [entry] [(-> (key entry) str/lower-case keyword) (val entry)])) (into {})) content-types (:content-type headers) ;; `body` is of type Optional<EagerBodyReader> body (.getBody response) json? (some #(str/includes? % "json") content-types)] (->> {:file-origin (str file) :json-content-type? json? :body (cond (not (.isPresent body)) nil (and (seq content-types) (some #(str/includes? % "json") content-types)) (try (json-parse-string (str (.get body))) (catch Exception _ "")) :else "") :headers headers :status (.getStatusCode response)} (conj acc) recur)) acc)))) (catch Exception _ nil)))] (or requests responses)))) file-1-results (read-stream file-1) file-2-results (read-stream file-2)] (when (zero? (mod idx 500)) (println :done (str idx "/" (count dat-files)) :file-path (str file-1))) ;; Find which is the request file. (if (:host (first file-1-results)) (mapv (fn [result-1 result-2] {:request result-1 :response result-2}) file-1-results file-2-results) (mapv (fn [result-1 result-2] {:request result-2 :response result-1}) file-1-results file-2-results))))) (apply concat) (filter json-content-type?) doall)) ;; TODO: Make default registry a dynamic variable (?). (defn openapi-3-from-api-schemas ([api-schemas] (openapi-3-from-api-schemas api-schemas {})) ([api-schemas {:keys [::regexes] :or {regexes default-regexes} :as options}] {:openapi "3.0.1" :info {:version "1.0.0" :title "My Schemas"} :servers [{:url "/"}] :paths (->> api-schemas (group-by #(select-keys % [:host :path])) (mapv (fn [[{:keys [:path]} schemas]] (let [pattern (->> regexes vals (str/join "|") re-pattern) splitted-str (str/split path pattern) path-params (->> (re-seq pattern path) (map-indexed (fn [idx v] {:in :path :name (format "arg%s" idx) :schema {:type :string} :description v :required true}))) path' (or (some->> path-params seq (mapv #(format "{%s}" (:name %))) (interleave splitted-str) (str/join "")) path) path' (if (and (> (count splitted-str) 1) (< (count path-params) (count splitted-str))) ;; Add last element of splitted str so we ;; don't have a bougs path. (str path' (last splitted-str)) path')] {path' (->> schemas (mapv (fn [{:keys [:method :request-schema :response-schema]}] {method (merge {:parameters path-params :responses {200 {:content {"*/*" {:schema (swagger/transform response-schema (process-options options))}} :description "Responses."}}} (when-not (contains? #{'nil? 'any?} request-schema) {:requestBody {:content {"*/*" {:schema (swagger/transform request-schema (process-options options))}} :required true}}))})) (apply merge))}))) (apply merge))})) (defn- contains-diff? [v] ;; If the key or the value contains a diff ;; instance, keep it. (or (instance? Mismatch v) (instance? Deletion v) (instance? Insertion v) (let [result-atom (atom false)] (walk/prewalk (fn [form] (when (or (instance? Mismatch form) (instance? Deletion form) (instance? Insertion form)) (reset! result-atom true)) form) v) @result-atom))) (defn- get-subschemas [schema options] (->> (mu/subschemas schema (process-options options)) (mu/distinct-by :id) pr-str edn/read-string (mapv #(select-keys % [:path :schema])) (mapv (juxt first identity)))) (defn api-request-subschemas-from-api-schema [api-schema options] (get-subschemas (:request-schema api-schema) options)) (defn api-response-subschemas-from-api-schema [api-schema options] (get-subschemas (:response-schema api-schema) options)) (defn diff-api-schemas ([base-api-schemas new-api-schemas] (diff-api-schemas base-api-schemas new-api-schemas {})) ([base-api-schemas new-api-schemas options] (let [removed-api-schemas (->> base-api-schemas (mapv (fn [original-api-schema] (when-not (->> new-api-schemas (filter #(= (select-keys % [:path :method :host]) (select-keys original-api-schema [:path :method :host]))) first) (-> original-api-schema (dissoc :response-schema :request-schema) (merge {:response-schema-diff ::api-schema/removed :request-schema-diff ::api-schema/removed}))))) (remove nil?))] (->> new-api-schemas (mapv (fn [new-api-schema] (if-let [original-api-schema (->> base-api-schemas (filter #(= (select-keys % [:path :method :host]) (select-keys new-api-schema [:path :method :host]))) first)] (-> new-api-schema (dissoc :response-schema :request-schema) (merge {:response-schema-diff (->> (ddiff/diff (get-subschemas (:response-schema original-api-schema) options) (get-subschemas (:response-schema new-api-schema) options)) (filter contains-diff?) seq) :request-schema-diff (->> (ddiff/diff (get-subschemas (:request-schema original-api-schema) options) (get-subschemas (:request-schema new-api-schema) options)) (filter contains-diff?) seq)})) (-> new-api-schema (dissoc :response-schema :request-schema) (merge {:response-schema-diff ::api-schema/new :request-schema-diff ::api-schema/new}))))) (concat removed-api-schemas) (sort-by (juxt :host :path :method)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;; PATHOM ;;;;;;;;;;;;;;;;;;;;;;;;; (pco/defresolver pcap-path->dat-files [{:keys [::pcap-path]}] {::dat-files (dat-files-from-pcap-path pcap-path)}) (pco/defresolver har-path->api-calls [{:keys [::har-path]}] {::api-calls (api-calls-from-har-path har-path)}) (pco/defresolver dat-files->api-calls [{:keys [::datPI:KEY:<KEY>END_PI-files]}] {::api-calls (api-calls-from-dat-files dat-files)}) ;; TODO: Make these options come from the main query so we don't have to ;; repeat them everywhere! (pco/defresolver api-calls->api-schemas [env {:keys [::api-calls]}] {::api-schemas (api-schemas-from-api-calls api-calls (pco/params env))}) (pco/defresolver api-schema->api-calls [api-schema] {::pco/input [::api-schema/id]} {::api-calls (::api-calls (meta api-schema))}) (pco/defresolver api-schemas->openapi-3 [env {:keys [::api-schemas]}] {::openapi-3 (openapi-3-from-api-schemas api-schemas (pco/params env))}) (pco/defresolver api-schemas-diff-resolver [env {:keys [::base ::api-schemas]}] {::pco/input [{::base [::api-schemas]} ::api-schemas]} {::api-schemas-diff (diff-api-schemas (::api-schemas base) api-schemas (pco/params env))}) (pco/defresolver api-schema->api-request-subschemas [env api-schema] {::pco/input [::api-schema/id :request-schema]} {::request-subschemas (api-request-subschemas-from-api-schema api-schema (pco/params env))}) (pco/defresolver api-schema->api-response-subschemas [env api-schema] {::pco/input [::api-schema/id :response-schema]} {::response-subschemas (api-response-subschemas-from-api-schema api-schema (pco/params env))}) (def pathom-env (pci/register [pcap-path->dat-files har-path->api-calls dat-files->api-calls api-calls->api-schemas api-schemas->openapi-3 api-schema->api-calls api-schemas-diff-resolver api-schema->api-request-subschemas api-schema->api-response-subschemas])) (defn process ([tx] (p.eql/process pathom-env tx)) ([entity tx] (p.eql/process pathom-env entity tx))) (comment ;; We can get the schemas from a pcap path. (process {::pcap-path "resources-test/pcap-files/dump.pcap"} [::api-schemas]) (process [{[::pcap-path "resources-test/pcap-files/dump2.pcap"] [{::api-schemas ['* ::request-subschemas ::response-subschemas]}]}]) ;; But we also can get other info derived from a pcap path (e.g. openapi-3 ;; schema). (process {::pcap-path "resources-test/pcap-files/dump.pcap"} [::api-schemas ::openapi-3]) ;; Here we fetch the api schemas, then the api-calls and ;; open api 3 related to each api schema. Also we get open api 3 ;; for everyone. So we can mix and match things freely. (process {::pcap-path "resources-test/pcap-files/dump.pcap"} [{::api-schemas ['* ::api-calls ::openapi-3]} ::openapi-3]) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Diff ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (process {::pcap-path "resources-test/pcap-files/dump2.pcap" ::base {::pcap-path "resources-test/pcap-files/dump.pcap"}} [::api-schemas-diff]) (process [{'(:>/a {::pcap-path "resources-test/pcap-files/dump2.pcap" ::base {::pcap-path "resources-test/pcap-files/dump.pcap"}}) [::api-schemas-diff]}]) ()) (comment (process {::har-path "/Users/paulo.feodrippe/Downloads/www.notion.so.har"} [::api-schemas]) (def github-schemas (::api-schemas (process {::har-path "/Users/paulo.feodrippe/Downloads/github.com.har"} [::api-schemas]))) (->> (-> (process {::api-schemas github-schemas} [::openapi-3]) ::openapi-3 (json/generate-string {:pretty true})) (spit "github.json")) ()) (comment ;; TODO ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; CURRENT (in order!) ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; - [ ] Start web app. ;; - [ ] Give option to upload two files at FE. ;; - [ ] Show diffs at FE. ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; TBD or DONE ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; - [x] Group same method/path so it's added as a sample for the same ;; `mp/provide` call. ;; - [x] Improve grouping of API calls (EDIT: Let the user pass any regex). ;; - [ ] Separate query params from path and schematize it as well. ;; - [x] Accept HAR files. See https://support.zendesk.com/hc/en-us/articles/204410413-Generating-a-HAR-file-for-troubleshooting. ;; - [x] Generate OpenAPI 3 spec from REST endpoints. ;; - [x] Solve pipelined http requests. ;; - [x] Some data formats: ISO date format and UUID. ;; - [ ] See someway to do trace between multiple services. ;; - [ ] Parallelize inference(?). ;; - [x] Run `tcpdump` and `tcptrace` from Clojure. For `tcpdump`, maybe we ;; can even use some Java wrapper for `libpcap`. ;; - [ ] Use `libpcap` so we don't need `tcpdump` installed (?). ;; - [x] Group paths. ;; - [ ] Validate data (?). ;; - [ ] Create mock for `http-client-fake` so it can generate HAR files. ;; - [ ] Make it extensible? ;; - [ ] This is very much like integration tests + unit tests, while you ;; can unit test a method/function, the "real" usage (integr.) can create ;; a schema which can be used to check the data passed to unit tests. ;; - [ ] Create front end (not pretty, but also not ugly, please). ;; - [ ] Check what to show to the user. ;; - [ ] See other ways to output this data to the user (CLI, excel to an ;; email etc) (?). ;; - [x] Convert from clojure.spec to Malli (for schema generation with ;; `spec-provider`. ;; - [ ] Use https://github.com/FudanSELab/train-ticket for testing. ;; - [x] Use some real HTTP parser (or converter to HAR). ;; - [ ] Check if it's feasible to generate enums. ;; - [ ] Optimize some code. ;; - [ ] Add tests. ;; - [ ] Add zip code data format as if we were a user of the library. ;; - [ ] Recognize patterns (subschemas) and maybe add them dynamically ;; as new schemas. With it we can match patterns with other data and see ;; where they are used. ;; - [ ] Add timestamps to the request/response pairs (can we use ;; tcpdump/libpcap for it?). ;; - [ ] Refactor code of the schema parser in functions. ;; - [ ] Maybe add schema to our functions? ;; - [ ] Add some way to generate samples from our UI. ;; - [ ] Give options to store generated schema somewhere (S3 first?). ;; - [ ] Maybe show some possible values (`enum`) using a percentage over the ;; distinct samples. ;; - [ ] Show similar specs (e.g. one is a subset of another or how much this ;; this is like one another one). ;; - [ ] Maybe change the format of api-calls so it has more information and ;; it's more like the HAR file. ;; - [ ] Show schemas appearing in realtime in the FE. We can leverage the fact ;; that `stats/collect` returns a unique map which we can keep in some atom ;; and update it whenever some new file appears. We will keep track of the ;; .dat files created and create `api-calls` from it which will be "collected". ;; - [x] Give option to use existing api schemas stats. ;; - [ ] Accept `regal` so we can have automatic generators. ;; - [ ] Document public functions. ;; - [ ] Stream schemas? ;; - [ ] Create a library out of it only for the schemas (we have to be more ;; general about the types and NOT assume that the data is coming from ;; JSON. ;; - [x] Diff between schemas. ;; - [ ] Infer query params. ;; - [ ] Infer headers. ;; - [ ] Add origin so it's easy to know who called who. But there is no good ;; way to know it AFAIK with `tcptrace`. ;; - [x] Validate Cypress fixtures. Make it read schema from some source. ;; Better yet, we can generate HAR files using a Cypress plugin. ;; - [x] Generate Swagger API (low hanging fruit). Check if it's possible to ;; add metadata for custom formats. ;; - [ ] Add options to pass `options` using a dynamic var. ;; - [ ] Show diffs between two API schemas. ;; - [ ] Start FE. Show and search APIs (also in real time (?)). ;; - [ ] Show better validation error for Cypress fixtures (easier to understand). ;; - [ ] Suggest fix for Cypress fixtures (using generated data)? ;; - [ ] Measure other things like latency. ;; - [ ] Separate schemas per status code. Identify which ones are marked ;; as json and are not returning parseable json. ;; - [ ] User can create views with their own queries. ;; - [x] Call this library `Pitoco`. ;; - [x] Add Pathom so we don't need to create a lot of `-from` functions and ;; the data requested by the user can be just what he/she needs. ;; - [x] Create resolver to generate dat files from a pcap file. ;; - [ ] Add docker environment with non-usual dependencies (e.g. `tcptrace` ;; and `tcpdump`. ;; - [ ] Add possibilities of filtering data. E.g. get all with status from ;; 400 to 499, whoch one had schema changes (this is between two schemas), ;; by method, why is this content-type, but it's not parseable. Should ;; we query using `datascript`? ;; - [ ] Group api calls by status. ;; - [ ] Read file from S3. ;; - [ ] How can this tool be used for contract testing? ;; TODO - OTHERS: ;; - [ ] For `tla-edn`, make it convert empty domains to edn maps and empty ;; edn maps to empty domains. ;; - [ ] Add metadata to views so we can easily find the code for it. ;; - [ ] Make REPL for TLA+ with nRepl integration. ()) ;; Examples (to be used for testing).
[ { "context": "c person :type))\n\n(let [data {:type :local :name \"chen\" :address \"Shanghai\"}]\n (if (s/valid? ::example ", "end": 438, "score": 0.982495129108429, "start": 434, "tag": "NAME", "value": "chen" }, { "context": "mple data))))\n\n(let [data {:type :stranger :name \"chen\"}]\n (if (s/valid? ::example data)\n (println (", "end": 616, "score": 0.9864175319671631, "start": 612, "tag": "NAME", "value": "chen" } ]
11-multi-spec.cljs
jiyinyiyong/spec-examples
1
(ns example.core (:require [cljs.spec.alpha :as s] [expound.alpha :refer [expound]])) (s/def ::type #{:local :stranger}) (s/def ::name string?) (s/def ::address string?) (defmulti person :type) (defmethod person :local [_] (s/keys :req-un [::type ::name ::address])) (defmethod person :stranger [_] (s/keys :req-un [::type ::name])) (s/def ::example (s/multi-spec person :type)) (let [data {:type :local :name "chen" :address "Shanghai"}] (if (s/valid? ::example data) (println (s/conform ::example data)) (println (expound ::example data)))) (let [data {:type :stranger :name "chen"}] (if (s/valid? ::example data) (println (s/conform ::example data)) (println (expound ::example data))))
79669
(ns example.core (:require [cljs.spec.alpha :as s] [expound.alpha :refer [expound]])) (s/def ::type #{:local :stranger}) (s/def ::name string?) (s/def ::address string?) (defmulti person :type) (defmethod person :local [_] (s/keys :req-un [::type ::name ::address])) (defmethod person :stranger [_] (s/keys :req-un [::type ::name])) (s/def ::example (s/multi-spec person :type)) (let [data {:type :local :name "<NAME>" :address "Shanghai"}] (if (s/valid? ::example data) (println (s/conform ::example data)) (println (expound ::example data)))) (let [data {:type :stranger :name "<NAME>"}] (if (s/valid? ::example data) (println (s/conform ::example data)) (println (expound ::example data))))
true
(ns example.core (:require [cljs.spec.alpha :as s] [expound.alpha :refer [expound]])) (s/def ::type #{:local :stranger}) (s/def ::name string?) (s/def ::address string?) (defmulti person :type) (defmethod person :local [_] (s/keys :req-un [::type ::name ::address])) (defmethod person :stranger [_] (s/keys :req-un [::type ::name])) (s/def ::example (s/multi-spec person :type)) (let [data {:type :local :name "PI:NAME:<NAME>END_PI" :address "Shanghai"}] (if (s/valid? ::example data) (println (s/conform ::example data)) (println (expound ::example data)))) (let [data {:type :stranger :name "PI:NAME:<NAME>END_PI"}] (if (s/valid? ::example data) (println (s/conform ::example data)) (println (expound ::example data))))
[ { "context": "(-> (test-db)\n (assoc :username 1234 :password 1234)\n (subject/poole", "end": 503, "score": 0.7799783945083618, "start": 499, "tag": "USERNAME", "value": "1234" }, { "context": " (assoc :username 1234 :password 1234)\n (subject/pooled-datasource))]", "end": 518, "score": 0.9992688894271851, "start": 514, "tag": "PASSWORD", "value": "1234" } ]
test/com/puppetlabs/test/jdbc.clj
atopian/puppetdb
0
(ns com.puppetlabs.test.jdbc (:require [com.puppetlabs.jdbc :as subject] [clojure.java.jdbc :as sql]) (:use [clojure.test] [com.puppetlabs.puppetdb.testutils :only [test-db]] [com.puppetlabs.testutils.db :only [antonym-data with-antonym-test-database]])) (use-fixtures :each with-antonym-test-database) (deftest pool-construction (testing "can construct pool with numeric usernames and passwords" (let [pool (-> (test-db) (assoc :username 1234 :password 1234) (subject/pooled-datasource))] (.close (:datasource pool))))) (deftest query-to-vec (testing "query string only" (is (= (set (subject/query-to-vec "SELECT key FROM test WHERE key LIKE 'ab%'")) (set (map #(hash-map :key (name %)) [:absence :abundant]))))) (testing "query with params" (doseq [[key value] antonym-data] (let [query ["SELECT key, value FROM test WHERE key = ?" key] result [{:key key :value value}]] (is (= (subject/query-to-vec query) result) (str query " => " result " with vector")) (is (= (apply subject/query-to-vec query) result) (str query " => " result " with multiple params")))))) (deftest limited-query-to-vec (testing "query does not exceed limit" (is (= (set (subject/limited-query-to-vec 100 "SELECT key FROM test WHERE key LIKE 'ab%'")) (set (map #(hash-map :key (name %)) [:absence :abundant]))))) (testing "query exceeds limit" (is (thrown-with-msg? IllegalStateException #"more than the maximum number of results" (subject/limited-query-to-vec 1 "SELECT key FROM test WHERE key LIKE 'ab%'"))))) (deftest order-by->sql (testing "should return an empty string if no order-by is provided" (is (= "" (subject/order-by->sql nil)))) (testing "should return an empty string if order-by list is empty" (is (= "" (subject/order-by->sql [])))) (testing "should generate a valid SQL 'ORDER BY' clause" (is (= " ORDER BY foo" (subject/order-by->sql [{:field "foo"}])))) (testing "should support ordering in descending order" (is (= " ORDER BY foo DESC" (subject/order-by->sql [{:field "foo" :order "desc"}])))) (testing "order specifier should be case insensitive" (is (= " ORDER BY foo DESC" (subject/order-by->sql [{:field "foo" :order "DESC"}])))) (testing "should support explicitly ordering in ascending order" (is (= " ORDER BY foo" (subject/order-by->sql [{:field "foo" :order "ASC"}])))) (testing "should raise an error if order is not ASC or DESC" (is (thrown-with-msg? IllegalArgumentException #"Unsupported value .* for :order; expected one of 'DESC' or 'ASC'" (subject/order-by->sql [{:field "foo" :order "foo"}])))) (testing "should support multiple order-by fields" (is (= " ORDER BY foo DESC, bar" (subject/order-by->sql [{:field "foo" :order "DESC"} {:field "bar"}])))))
105208
(ns com.puppetlabs.test.jdbc (:require [com.puppetlabs.jdbc :as subject] [clojure.java.jdbc :as sql]) (:use [clojure.test] [com.puppetlabs.puppetdb.testutils :only [test-db]] [com.puppetlabs.testutils.db :only [antonym-data with-antonym-test-database]])) (use-fixtures :each with-antonym-test-database) (deftest pool-construction (testing "can construct pool with numeric usernames and passwords" (let [pool (-> (test-db) (assoc :username 1234 :password <PASSWORD>) (subject/pooled-datasource))] (.close (:datasource pool))))) (deftest query-to-vec (testing "query string only" (is (= (set (subject/query-to-vec "SELECT key FROM test WHERE key LIKE 'ab%'")) (set (map #(hash-map :key (name %)) [:absence :abundant]))))) (testing "query with params" (doseq [[key value] antonym-data] (let [query ["SELECT key, value FROM test WHERE key = ?" key] result [{:key key :value value}]] (is (= (subject/query-to-vec query) result) (str query " => " result " with vector")) (is (= (apply subject/query-to-vec query) result) (str query " => " result " with multiple params")))))) (deftest limited-query-to-vec (testing "query does not exceed limit" (is (= (set (subject/limited-query-to-vec 100 "SELECT key FROM test WHERE key LIKE 'ab%'")) (set (map #(hash-map :key (name %)) [:absence :abundant]))))) (testing "query exceeds limit" (is (thrown-with-msg? IllegalStateException #"more than the maximum number of results" (subject/limited-query-to-vec 1 "SELECT key FROM test WHERE key LIKE 'ab%'"))))) (deftest order-by->sql (testing "should return an empty string if no order-by is provided" (is (= "" (subject/order-by->sql nil)))) (testing "should return an empty string if order-by list is empty" (is (= "" (subject/order-by->sql [])))) (testing "should generate a valid SQL 'ORDER BY' clause" (is (= " ORDER BY foo" (subject/order-by->sql [{:field "foo"}])))) (testing "should support ordering in descending order" (is (= " ORDER BY foo DESC" (subject/order-by->sql [{:field "foo" :order "desc"}])))) (testing "order specifier should be case insensitive" (is (= " ORDER BY foo DESC" (subject/order-by->sql [{:field "foo" :order "DESC"}])))) (testing "should support explicitly ordering in ascending order" (is (= " ORDER BY foo" (subject/order-by->sql [{:field "foo" :order "ASC"}])))) (testing "should raise an error if order is not ASC or DESC" (is (thrown-with-msg? IllegalArgumentException #"Unsupported value .* for :order; expected one of 'DESC' or 'ASC'" (subject/order-by->sql [{:field "foo" :order "foo"}])))) (testing "should support multiple order-by fields" (is (= " ORDER BY foo DESC, bar" (subject/order-by->sql [{:field "foo" :order "DESC"} {:field "bar"}])))))
true
(ns com.puppetlabs.test.jdbc (:require [com.puppetlabs.jdbc :as subject] [clojure.java.jdbc :as sql]) (:use [clojure.test] [com.puppetlabs.puppetdb.testutils :only [test-db]] [com.puppetlabs.testutils.db :only [antonym-data with-antonym-test-database]])) (use-fixtures :each with-antonym-test-database) (deftest pool-construction (testing "can construct pool with numeric usernames and passwords" (let [pool (-> (test-db) (assoc :username 1234 :password PI:PASSWORD:<PASSWORD>END_PI) (subject/pooled-datasource))] (.close (:datasource pool))))) (deftest query-to-vec (testing "query string only" (is (= (set (subject/query-to-vec "SELECT key FROM test WHERE key LIKE 'ab%'")) (set (map #(hash-map :key (name %)) [:absence :abundant]))))) (testing "query with params" (doseq [[key value] antonym-data] (let [query ["SELECT key, value FROM test WHERE key = ?" key] result [{:key key :value value}]] (is (= (subject/query-to-vec query) result) (str query " => " result " with vector")) (is (= (apply subject/query-to-vec query) result) (str query " => " result " with multiple params")))))) (deftest limited-query-to-vec (testing "query does not exceed limit" (is (= (set (subject/limited-query-to-vec 100 "SELECT key FROM test WHERE key LIKE 'ab%'")) (set (map #(hash-map :key (name %)) [:absence :abundant]))))) (testing "query exceeds limit" (is (thrown-with-msg? IllegalStateException #"more than the maximum number of results" (subject/limited-query-to-vec 1 "SELECT key FROM test WHERE key LIKE 'ab%'"))))) (deftest order-by->sql (testing "should return an empty string if no order-by is provided" (is (= "" (subject/order-by->sql nil)))) (testing "should return an empty string if order-by list is empty" (is (= "" (subject/order-by->sql [])))) (testing "should generate a valid SQL 'ORDER BY' clause" (is (= " ORDER BY foo" (subject/order-by->sql [{:field "foo"}])))) (testing "should support ordering in descending order" (is (= " ORDER BY foo DESC" (subject/order-by->sql [{:field "foo" :order "desc"}])))) (testing "order specifier should be case insensitive" (is (= " ORDER BY foo DESC" (subject/order-by->sql [{:field "foo" :order "DESC"}])))) (testing "should support explicitly ordering in ascending order" (is (= " ORDER BY foo" (subject/order-by->sql [{:field "foo" :order "ASC"}])))) (testing "should raise an error if order is not ASC or DESC" (is (thrown-with-msg? IllegalArgumentException #"Unsupported value .* for :order; expected one of 'DESC' or 'ASC'" (subject/order-by->sql [{:field "foo" :order "foo"}])))) (testing "should support multiple order-by fields" (is (= " ORDER BY foo DESC, bar" (subject/order-by->sql [{:field "foo" :order "DESC"} {:field "bar"}])))))
[ { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and dis", "end": 33, "score": 0.9998518824577332, "start": 19, "tag": "NAME", "value": "Nicola Mometto" }, { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and distribution ter", "end": 46, "score": 0.9998450875282288, "start": 35, "tag": "NAME", "value": "Rich Hickey" } ]
server/target/clojure/tools/analyzer/passes/cleanup.clj
OctavioBR/healthcheck
15
;; Copyright (c) Nicola Mometto, Rich Hickey & contributors. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns clojure.tools.analyzer.passes.cleanup) (defn cleanup {:pass-info {:walk :any :depends #{}}} [ast] (-> ast (update-in [:env] dissoc :loop-locals-casts) (update-in [:env :locals] #(reduce-kv (fn [m k l] (assoc m k (dissoc l :env :init))) {} %)) (dissoc :atom)))
14256
;; Copyright (c) <NAME>, <NAME> & contributors. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns clojure.tools.analyzer.passes.cleanup) (defn cleanup {:pass-info {:walk :any :depends #{}}} [ast] (-> ast (update-in [:env] dissoc :loop-locals-casts) (update-in [:env :locals] #(reduce-kv (fn [m k l] (assoc m k (dissoc l :env :init))) {} %)) (dissoc :atom)))
true
;; Copyright (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI & contributors. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns clojure.tools.analyzer.passes.cleanup) (defn cleanup {:pass-info {:walk :any :depends #{}}} [ast] (-> ast (update-in [:env] dissoc :loop-locals-casts) (update-in [:env :locals] #(reduce-kv (fn [m k l] (assoc m k (dissoc l :env :init))) {} %)) (dissoc :atom)))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998190999031067, "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.9998251795768738, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/test/editor/gviz_test.clj
cmarincia/defold
0
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 Ragnar Svensson, Christian Murray ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns editor.gviz-test (:require [clojure.java.io :as io] [clojure.test :refer :all] [editor.gviz :as gviz] [integration.test-util :as test-util] [dynamo.graph :as g] [support.test-support :refer [with-clean-system tx-nodes]])) (deftest installed [] (gviz/installed?)) (g/defnode SimpleNode (property prop g/Str) (input in g/Str) (output out g/Str (g/fnk [in] in))) (deftest simple [] (with-clean-system (let [g (g/make-graph!) nodes (tx-nodes (g/make-nodes g [n0 [SimpleNode :prop "test"] n1 [SimpleNode :prop "test2"]] (g/connect n0 :out n1 :in))) dot (gviz/subgraph->dot (g/now))] (is (re-find #"SimpleNode" dot))))) (deftest broken-graph [] (with-clean-system (let [g (g/make-graph!) nodes (tx-nodes (g/make-nodes g [n0 [SimpleNode :prop "test"] n1 [SimpleNode :prop "test2"]] (g/connect n0 :out n1 :in))) basis (update-in (g/now) [:graphs g :nodes] dissoc (first nodes)) dot (gviz/subgraph->dot basis)] (is (re-find #"red" dot))))) (deftest gui [] (with-clean-system (let [workspace (test-util/setup-workspace! world) project (test-util/setup-project! workspace) node-id (test-util/resource-node project "/logic/main.gui") basis (g/now) dot (gviz/subgraph->dot basis :root-id node-id :input-fn (fn [[s sl t tl]] (when-let [type (g/node-type* basis t)] ((g/cascade-deletes type) tl))))] (is (< 1000 (count dot))))))
27917
;; 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.gviz-test (:require [clojure.java.io :as io] [clojure.test :refer :all] [editor.gviz :as gviz] [integration.test-util :as test-util] [dynamo.graph :as g] [support.test-support :refer [with-clean-system tx-nodes]])) (deftest installed [] (gviz/installed?)) (g/defnode SimpleNode (property prop g/Str) (input in g/Str) (output out g/Str (g/fnk [in] in))) (deftest simple [] (with-clean-system (let [g (g/make-graph!) nodes (tx-nodes (g/make-nodes g [n0 [SimpleNode :prop "test"] n1 [SimpleNode :prop "test2"]] (g/connect n0 :out n1 :in))) dot (gviz/subgraph->dot (g/now))] (is (re-find #"SimpleNode" dot))))) (deftest broken-graph [] (with-clean-system (let [g (g/make-graph!) nodes (tx-nodes (g/make-nodes g [n0 [SimpleNode :prop "test"] n1 [SimpleNode :prop "test2"]] (g/connect n0 :out n1 :in))) basis (update-in (g/now) [:graphs g :nodes] dissoc (first nodes)) dot (gviz/subgraph->dot basis)] (is (re-find #"red" dot))))) (deftest gui [] (with-clean-system (let [workspace (test-util/setup-workspace! world) project (test-util/setup-project! workspace) node-id (test-util/resource-node project "/logic/main.gui") basis (g/now) dot (gviz/subgraph->dot basis :root-id node-id :input-fn (fn [[s sl t tl]] (when-let [type (g/node-type* basis t)] ((g/cascade-deletes type) tl))))] (is (< 1000 (count dot))))))
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.gviz-test (:require [clojure.java.io :as io] [clojure.test :refer :all] [editor.gviz :as gviz] [integration.test-util :as test-util] [dynamo.graph :as g] [support.test-support :refer [with-clean-system tx-nodes]])) (deftest installed [] (gviz/installed?)) (g/defnode SimpleNode (property prop g/Str) (input in g/Str) (output out g/Str (g/fnk [in] in))) (deftest simple [] (with-clean-system (let [g (g/make-graph!) nodes (tx-nodes (g/make-nodes g [n0 [SimpleNode :prop "test"] n1 [SimpleNode :prop "test2"]] (g/connect n0 :out n1 :in))) dot (gviz/subgraph->dot (g/now))] (is (re-find #"SimpleNode" dot))))) (deftest broken-graph [] (with-clean-system (let [g (g/make-graph!) nodes (tx-nodes (g/make-nodes g [n0 [SimpleNode :prop "test"] n1 [SimpleNode :prop "test2"]] (g/connect n0 :out n1 :in))) basis (update-in (g/now) [:graphs g :nodes] dissoc (first nodes)) dot (gviz/subgraph->dot basis)] (is (re-find #"red" dot))))) (deftest gui [] (with-clean-system (let [workspace (test-util/setup-workspace! world) project (test-util/setup-project! workspace) node-id (test-util/resource-node project "/logic/main.gui") basis (g/now) dot (gviz/subgraph->dot basis :root-id node-id :input-fn (fn [[s sl t tl]] (when-let [type (g/node-type* basis t)] ((g/cascade-deletes type) tl))))] (is (< 1000 (count dot))))))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998037815093994, "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.9998189806938171, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/src/clj/editor/code/util.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.util (:require [clojure.string :as string]) (:import [clojure.lang MapEntry] [java.util ArrayList Collections Comparator List] [java.util.regex Matcher Pattern])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn- comparisons-syntax [exp & rest-exps] (if (empty? rest-exps) exp (let [comparison-sym (gensym "comparison")] `(let [~comparison-sym ~exp] (if (zero? ~comparison-sym) ~(apply comparisons-syntax rest-exps) ~comparison-sym))))) (defmacro comparisons [& exps] (apply comparisons-syntax exps)) (defn- ->insert-index ^long [^long binary-search-result] ;; Collections/binarySearch returns a non-negative value if an exact match is ;; found. Otherwise it returns (-(insertion point) - 1). The insertion point ;; is defined as the point at which the key would be inserted into the list: ;; the index of the first element greater than the key, or list.size() if all ;; elements in the list are less than the specified key. (if (neg? binary-search-result) (Math/abs (inc binary-search-result)) (inc binary-search-result))) (defn find-insert-index "Finds the insertion index in an ordered collection. If the collection is not ordered, the result is undefined. New items will be inserted after exact matches, or between two non-exact matches that each compare differently to item using the supplied comparator." ([coll item] (find-insert-index coll item compare)) ([^List coll item ^Comparator comparator] (let [search-result (Collections/binarySearch coll item comparator)] (->insert-index search-result)))) (defn insert "Inserts an item at the specified position in a vector. Shifts the item currently at that position (if any) and any subsequent items to the right (adds one to their indices). Returns the new vector." [coll index item] (into (subvec coll 0 index) (cons item (subvec coll index)))) (defn insert-sort "Inserts an item into an ordered vector. If the collection is not ordered, the result is undefined. The insert index will be determined by comparing items. New items will be inserted after exact matches, or between two non-exact matches that each compare differently to item using the supplied comparator. Returns the new vector." ([coll item] (insert-sort coll item compare)) ([coll item comparator] (insert coll (find-insert-index coll item comparator) item))) (defn last-index-where "Returns the index of the last element in coll where pred returns true, or nil if there was no matching element. The coll must support addressing using nth." [pred coll] (loop [index (dec (count coll))] (when-not (neg? index) (if (pred (nth coll index)) index (recur (dec index)))))) (defn pair "Returns a two-element collection that implements IPersistentVector." [a b] (MapEntry/create a b)) (defn re-matcher-from "Returns an instance of java.util.regex.Matcher that starts at an offset." ^Matcher [re s start] (let [whole-string-matcher (re-matcher re s)] (if (> ^long start 0) (.region whole-string-matcher start (count s)) whole-string-matcher))) (defn re-match-result-seq "Returns a lazy sequence of successive MatchResults of the pattern in the specified string, using java.util.regex.Matcher.find(), with an optional start offset into the string." ([^Pattern re s] (re-match-result-seq re s 0)) ([^Pattern re s ^long start] (let [m (re-matcher-from re s start)] ((fn step [] (when (. m (find)) (cons (.toMatchResult m) (lazy-seq (step))))))))) (defn split-lines "Splits s on \\n or \\r\\n. Contrary to string/split-lines, keeps trailing newline at the end of a text." [^String text] ;; This is basically java code, for speed. This function is used a lot when ;; loading projects so it needs to be fast. String.split with regex is very ;; slow in comparison. I read that modern jvms are good at optimizing out the ;; .charAt call so this *should* be like a loop over a char array... (let [arr (ArrayList. 8192) len (.length text) sb (StringBuilder.)] (loop [i 0 last-index 0 last-char \x] (if (< i len) (let [c (.charAt text i) i (inc i)] (case c \newline (if-not (= last-char \return) (do (.add arr (.toString sb)) (.setLength sb 0) (recur i i c)) (recur i i c)) \return (do (.add arr (.toString sb)) (.setLength sb 0) (recur i i c)) ;; default (do (.append sb c) (recur i last-index c)))) ;; else branch (do (.add arr (.toString sb)) (into [] arr))))))
71694
;; 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.util (:require [clojure.string :as string]) (:import [clojure.lang MapEntry] [java.util ArrayList Collections Comparator List] [java.util.regex Matcher Pattern])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn- comparisons-syntax [exp & rest-exps] (if (empty? rest-exps) exp (let [comparison-sym (gensym "comparison")] `(let [~comparison-sym ~exp] (if (zero? ~comparison-sym) ~(apply comparisons-syntax rest-exps) ~comparison-sym))))) (defmacro comparisons [& exps] (apply comparisons-syntax exps)) (defn- ->insert-index ^long [^long binary-search-result] ;; Collections/binarySearch returns a non-negative value if an exact match is ;; found. Otherwise it returns (-(insertion point) - 1). The insertion point ;; is defined as the point at which the key would be inserted into the list: ;; the index of the first element greater than the key, or list.size() if all ;; elements in the list are less than the specified key. (if (neg? binary-search-result) (Math/abs (inc binary-search-result)) (inc binary-search-result))) (defn find-insert-index "Finds the insertion index in an ordered collection. If the collection is not ordered, the result is undefined. New items will be inserted after exact matches, or between two non-exact matches that each compare differently to item using the supplied comparator." ([coll item] (find-insert-index coll item compare)) ([^List coll item ^Comparator comparator] (let [search-result (Collections/binarySearch coll item comparator)] (->insert-index search-result)))) (defn insert "Inserts an item at the specified position in a vector. Shifts the item currently at that position (if any) and any subsequent items to the right (adds one to their indices). Returns the new vector." [coll index item] (into (subvec coll 0 index) (cons item (subvec coll index)))) (defn insert-sort "Inserts an item into an ordered vector. If the collection is not ordered, the result is undefined. The insert index will be determined by comparing items. New items will be inserted after exact matches, or between two non-exact matches that each compare differently to item using the supplied comparator. Returns the new vector." ([coll item] (insert-sort coll item compare)) ([coll item comparator] (insert coll (find-insert-index coll item comparator) item))) (defn last-index-where "Returns the index of the last element in coll where pred returns true, or nil if there was no matching element. The coll must support addressing using nth." [pred coll] (loop [index (dec (count coll))] (when-not (neg? index) (if (pred (nth coll index)) index (recur (dec index)))))) (defn pair "Returns a two-element collection that implements IPersistentVector." [a b] (MapEntry/create a b)) (defn re-matcher-from "Returns an instance of java.util.regex.Matcher that starts at an offset." ^Matcher [re s start] (let [whole-string-matcher (re-matcher re s)] (if (> ^long start 0) (.region whole-string-matcher start (count s)) whole-string-matcher))) (defn re-match-result-seq "Returns a lazy sequence of successive MatchResults of the pattern in the specified string, using java.util.regex.Matcher.find(), with an optional start offset into the string." ([^Pattern re s] (re-match-result-seq re s 0)) ([^Pattern re s ^long start] (let [m (re-matcher-from re s start)] ((fn step [] (when (. m (find)) (cons (.toMatchResult m) (lazy-seq (step))))))))) (defn split-lines "Splits s on \\n or \\r\\n. Contrary to string/split-lines, keeps trailing newline at the end of a text." [^String text] ;; This is basically java code, for speed. This function is used a lot when ;; loading projects so it needs to be fast. String.split with regex is very ;; slow in comparison. I read that modern jvms are good at optimizing out the ;; .charAt call so this *should* be like a loop over a char array... (let [arr (ArrayList. 8192) len (.length text) sb (StringBuilder.)] (loop [i 0 last-index 0 last-char \x] (if (< i len) (let [c (.charAt text i) i (inc i)] (case c \newline (if-not (= last-char \return) (do (.add arr (.toString sb)) (.setLength sb 0) (recur i i c)) (recur i i c)) \return (do (.add arr (.toString sb)) (.setLength sb 0) (recur i i c)) ;; default (do (.append sb c) (recur i last-index c)))) ;; else branch (do (.add arr (.toString sb)) (into [] arr))))))
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.util (:require [clojure.string :as string]) (:import [clojure.lang MapEntry] [java.util ArrayList Collections Comparator List] [java.util.regex Matcher Pattern])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn- comparisons-syntax [exp & rest-exps] (if (empty? rest-exps) exp (let [comparison-sym (gensym "comparison")] `(let [~comparison-sym ~exp] (if (zero? ~comparison-sym) ~(apply comparisons-syntax rest-exps) ~comparison-sym))))) (defmacro comparisons [& exps] (apply comparisons-syntax exps)) (defn- ->insert-index ^long [^long binary-search-result] ;; Collections/binarySearch returns a non-negative value if an exact match is ;; found. Otherwise it returns (-(insertion point) - 1). The insertion point ;; is defined as the point at which the key would be inserted into the list: ;; the index of the first element greater than the key, or list.size() if all ;; elements in the list are less than the specified key. (if (neg? binary-search-result) (Math/abs (inc binary-search-result)) (inc binary-search-result))) (defn find-insert-index "Finds the insertion index in an ordered collection. If the collection is not ordered, the result is undefined. New items will be inserted after exact matches, or between two non-exact matches that each compare differently to item using the supplied comparator." ([coll item] (find-insert-index coll item compare)) ([^List coll item ^Comparator comparator] (let [search-result (Collections/binarySearch coll item comparator)] (->insert-index search-result)))) (defn insert "Inserts an item at the specified position in a vector. Shifts the item currently at that position (if any) and any subsequent items to the right (adds one to their indices). Returns the new vector." [coll index item] (into (subvec coll 0 index) (cons item (subvec coll index)))) (defn insert-sort "Inserts an item into an ordered vector. If the collection is not ordered, the result is undefined. The insert index will be determined by comparing items. New items will be inserted after exact matches, or between two non-exact matches that each compare differently to item using the supplied comparator. Returns the new vector." ([coll item] (insert-sort coll item compare)) ([coll item comparator] (insert coll (find-insert-index coll item comparator) item))) (defn last-index-where "Returns the index of the last element in coll where pred returns true, or nil if there was no matching element. The coll must support addressing using nth." [pred coll] (loop [index (dec (count coll))] (when-not (neg? index) (if (pred (nth coll index)) index (recur (dec index)))))) (defn pair "Returns a two-element collection that implements IPersistentVector." [a b] (MapEntry/create a b)) (defn re-matcher-from "Returns an instance of java.util.regex.Matcher that starts at an offset." ^Matcher [re s start] (let [whole-string-matcher (re-matcher re s)] (if (> ^long start 0) (.region whole-string-matcher start (count s)) whole-string-matcher))) (defn re-match-result-seq "Returns a lazy sequence of successive MatchResults of the pattern in the specified string, using java.util.regex.Matcher.find(), with an optional start offset into the string." ([^Pattern re s] (re-match-result-seq re s 0)) ([^Pattern re s ^long start] (let [m (re-matcher-from re s start)] ((fn step [] (when (. m (find)) (cons (.toMatchResult m) (lazy-seq (step))))))))) (defn split-lines "Splits s on \\n or \\r\\n. Contrary to string/split-lines, keeps trailing newline at the end of a text." [^String text] ;; This is basically java code, for speed. This function is used a lot when ;; loading projects so it needs to be fast. String.split with regex is very ;; slow in comparison. I read that modern jvms are good at optimizing out the ;; .charAt call so this *should* be like a loop over a char array... (let [arr (ArrayList. 8192) len (.length text) sb (StringBuilder.)] (loop [i 0 last-index 0 last-char \x] (if (< i len) (let [c (.charAt text i) i (inc i)] (case c \newline (if-not (= last-char \return) (do (.add arr (.toString sb)) (.setLength sb 0) (recur i i c)) (recur i i c)) \return (do (.add arr (.toString sb)) (.setLength sb 0) (recur i i c)) ;; default (do (.append sb c) (recur i last-index c)))) ;; else branch (do (.add arr (.toString sb)) (into [] arr))))))
[ { "context": ";\n; Copyright © 2021 Peter Monks\n;\n; Licensed under the Apache License, Version 2.", "end": 32, "score": 0.9996914267539978, "start": 21, "tag": "NAME", "value": "Peter Monks" } ]
src/lice_comb/utils.clj
pmonks/lice-comb
3
; ; Copyright © 2021 Peter Monks ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns lice-comb.utils "General purpose utility fns that I seem to end up needing in every single project I write..." (:require [clojure.string :as s] [clojure.java.io :as io])) (defn clojurise-json-key "Converts JSON-style string keys (e.g. \"fullName\") to Clojure keyword keys (e.g. :full-name)." [k] (when k (keyword (s/replace (s/join "-" (map s/lower-case (s/split k #"(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"))) "_" "-")))) (defn mapfonk "Returns a new map where f has been applied to all of the keys of m." [f m] (when (and f m) (into {} (for [[k v] m] [(f k) v])))) (defn mapfonv "Returns a new map where f has been applied to all of the values of m." [f m] (when (and f m) (into {} (for [[k v] m] [k (f v)])))) (defn map-pad "Like map, but when presented with multiple collections of different lengths, 'pads out' the missing elements with nil rather than terminating early." [f & cs] (loop [result nil firsts (map first cs) rests (map rest cs)] (if-not (seq (keep identity firsts)) result (recur (cons (apply f firsts) result) (map first rests) (map rest rests))))) (defn strim "nil safe version of clojure.string/trim" [s] (when s (s/trim s))) (defn nset "nil preserving version of clojure.core/set" [coll] (when (seq coll) (set coll))) (defn escape-re "Escapes the given string for use in a regex." [s] (when s (s/escape s {\< "\\<" \( "\\(" \[ "\\[" \{ "\\{" \\ "\\\\" \^ "\\^" \- "\\-" \= "\\=" \$ "\\$" \! "\\!" \| "\\|" \] "\\]" \} "\\}" \) "\\)" \? "\\?" \* "\\*" \+ "\\+" \. "\\." \> "\\>" }))) (defn simplify-uri "Simplifies a URI (which can be a string, java.net.URL, or java.net.URI). Returns a string." [uri] (when uri (s/replace (s/replace (s/lower-case (s/trim (str uri))) "https://" "http://") "://www." "://"))) (defmulti filename "Returns just the name component of the given file or path string, excluding any parents." type) (defmethod filename nil [_]) (defmethod filename java.io.File [^java.io.File f] (.getName f)) (defmethod filename java.lang.String [s] (filename (io/file s))) (defmethod filename java.util.zip.ZipEntry [^java.util.zip.ZipEntry ze] (filename (.getName ze))) ; Note that Zip Entry names include the entire path (defmethod filename java.net.URI [^java.net.URI uri] (filename (.getPath uri))) (defmethod filename java.net.URL [^java.net.URL url] (filename (.getPath url))) (defn getenv "Obtain the given environment variable, returning default (or nil, if default is not provided) if it isn't set." ([var] (getenv var nil)) ([var default] (let [val (System/getenv var)] (if-not (s/blank? val) val default))))
123505
; ; Copyright © 2021 <NAME> ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns lice-comb.utils "General purpose utility fns that I seem to end up needing in every single project I write..." (:require [clojure.string :as s] [clojure.java.io :as io])) (defn clojurise-json-key "Converts JSON-style string keys (e.g. \"fullName\") to Clojure keyword keys (e.g. :full-name)." [k] (when k (keyword (s/replace (s/join "-" (map s/lower-case (s/split k #"(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"))) "_" "-")))) (defn mapfonk "Returns a new map where f has been applied to all of the keys of m." [f m] (when (and f m) (into {} (for [[k v] m] [(f k) v])))) (defn mapfonv "Returns a new map where f has been applied to all of the values of m." [f m] (when (and f m) (into {} (for [[k v] m] [k (f v)])))) (defn map-pad "Like map, but when presented with multiple collections of different lengths, 'pads out' the missing elements with nil rather than terminating early." [f & cs] (loop [result nil firsts (map first cs) rests (map rest cs)] (if-not (seq (keep identity firsts)) result (recur (cons (apply f firsts) result) (map first rests) (map rest rests))))) (defn strim "nil safe version of clojure.string/trim" [s] (when s (s/trim s))) (defn nset "nil preserving version of clojure.core/set" [coll] (when (seq coll) (set coll))) (defn escape-re "Escapes the given string for use in a regex." [s] (when s (s/escape s {\< "\\<" \( "\\(" \[ "\\[" \{ "\\{" \\ "\\\\" \^ "\\^" \- "\\-" \= "\\=" \$ "\\$" \! "\\!" \| "\\|" \] "\\]" \} "\\}" \) "\\)" \? "\\?" \* "\\*" \+ "\\+" \. "\\." \> "\\>" }))) (defn simplify-uri "Simplifies a URI (which can be a string, java.net.URL, or java.net.URI). Returns a string." [uri] (when uri (s/replace (s/replace (s/lower-case (s/trim (str uri))) "https://" "http://") "://www." "://"))) (defmulti filename "Returns just the name component of the given file or path string, excluding any parents." type) (defmethod filename nil [_]) (defmethod filename java.io.File [^java.io.File f] (.getName f)) (defmethod filename java.lang.String [s] (filename (io/file s))) (defmethod filename java.util.zip.ZipEntry [^java.util.zip.ZipEntry ze] (filename (.getName ze))) ; Note that Zip Entry names include the entire path (defmethod filename java.net.URI [^java.net.URI uri] (filename (.getPath uri))) (defmethod filename java.net.URL [^java.net.URL url] (filename (.getPath url))) (defn getenv "Obtain the given environment variable, returning default (or nil, if default is not provided) if it isn't set." ([var] (getenv var nil)) ([var default] (let [val (System/getenv var)] (if-not (s/blank? val) val default))))
true
; ; Copyright © 2021 PI:NAME:<NAME>END_PI ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns lice-comb.utils "General purpose utility fns that I seem to end up needing in every single project I write..." (:require [clojure.string :as s] [clojure.java.io :as io])) (defn clojurise-json-key "Converts JSON-style string keys (e.g. \"fullName\") to Clojure keyword keys (e.g. :full-name)." [k] (when k (keyword (s/replace (s/join "-" (map s/lower-case (s/split k #"(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"))) "_" "-")))) (defn mapfonk "Returns a new map where f has been applied to all of the keys of m." [f m] (when (and f m) (into {} (for [[k v] m] [(f k) v])))) (defn mapfonv "Returns a new map where f has been applied to all of the values of m." [f m] (when (and f m) (into {} (for [[k v] m] [k (f v)])))) (defn map-pad "Like map, but when presented with multiple collections of different lengths, 'pads out' the missing elements with nil rather than terminating early." [f & cs] (loop [result nil firsts (map first cs) rests (map rest cs)] (if-not (seq (keep identity firsts)) result (recur (cons (apply f firsts) result) (map first rests) (map rest rests))))) (defn strim "nil safe version of clojure.string/trim" [s] (when s (s/trim s))) (defn nset "nil preserving version of clojure.core/set" [coll] (when (seq coll) (set coll))) (defn escape-re "Escapes the given string for use in a regex." [s] (when s (s/escape s {\< "\\<" \( "\\(" \[ "\\[" \{ "\\{" \\ "\\\\" \^ "\\^" \- "\\-" \= "\\=" \$ "\\$" \! "\\!" \| "\\|" \] "\\]" \} "\\}" \) "\\)" \? "\\?" \* "\\*" \+ "\\+" \. "\\." \> "\\>" }))) (defn simplify-uri "Simplifies a URI (which can be a string, java.net.URL, or java.net.URI). Returns a string." [uri] (when uri (s/replace (s/replace (s/lower-case (s/trim (str uri))) "https://" "http://") "://www." "://"))) (defmulti filename "Returns just the name component of the given file or path string, excluding any parents." type) (defmethod filename nil [_]) (defmethod filename java.io.File [^java.io.File f] (.getName f)) (defmethod filename java.lang.String [s] (filename (io/file s))) (defmethod filename java.util.zip.ZipEntry [^java.util.zip.ZipEntry ze] (filename (.getName ze))) ; Note that Zip Entry names include the entire path (defmethod filename java.net.URI [^java.net.URI uri] (filename (.getPath uri))) (defmethod filename java.net.URL [^java.net.URL url] (filename (.getPath url))) (defn getenv "Obtain the given environment variable, returning default (or nil, if default is not provided) if it isn't set." ([var] (getenv var nil)) ([var default] (let [val (System/getenv var)] (if-not (s/blank? val) val default))))
[ { "context": "inally\n (unstrument)))))\n\n;; Copyright 2018 Frederic Merizen\n;;\n;; Licensed under the Apache License, Version ", "end": 512, "score": 0.9998747110366821, "start": 496, "tag": "NAME", "value": "Frederic Merizen" } ]
test/ferje/spec_test_utils.clj
chourave/clojyday
0
;; Copyright and license information at end of file (ns ferje.spec-test-utils (:require [clojure.spec.alpha :as s] [expound.alpha :as expound] [orchestra.spec.test :refer [instrument unstrument]])) (defn instrument-fixture "Fixture that runs tests, instrumenting specs with Orchestra, and producing clean spec diagnostics with Expoun" [f] (instrument) (binding [s/*explain-out* expound/printer] (try (f) (finally (unstrument))))) ;; Copyright 2018 Frederic Merizen ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express ;; or implied. See the License for the specific language governing ;; permissions and limitations under the License.
54064
;; Copyright and license information at end of file (ns ferje.spec-test-utils (:require [clojure.spec.alpha :as s] [expound.alpha :as expound] [orchestra.spec.test :refer [instrument unstrument]])) (defn instrument-fixture "Fixture that runs tests, instrumenting specs with Orchestra, and producing clean spec diagnostics with Expoun" [f] (instrument) (binding [s/*explain-out* expound/printer] (try (f) (finally (unstrument))))) ;; Copyright 2018 <NAME> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express ;; or implied. See the License for the specific language governing ;; permissions and limitations under the License.
true
;; Copyright and license information at end of file (ns ferje.spec-test-utils (:require [clojure.spec.alpha :as s] [expound.alpha :as expound] [orchestra.spec.test :refer [instrument unstrument]])) (defn instrument-fixture "Fixture that runs tests, instrumenting specs with Orchestra, and producing clean spec diagnostics with Expoun" [f] (instrument) (binding [s/*explain-out* expound/printer] (try (f) (finally (unstrument))))) ;; Copyright 2018 PI:NAME:<NAME>END_PI ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express ;; or implied. See the License for the specific language governing ;; permissions and limitations under the License.
[ { "context": ";; author: Mark W. Naylor\n;; file: day05.clj\n;; date: 2021-Jun-01\n(ns adv", "end": 25, "score": 0.9998754262924194, "start": 11, "tag": "NAME", "value": "Mark W. Naylor" }, { "context": "----\n;; BSD 3-Clause License\n\n;; Copyright © 2021, Mark W. Naylor\n;; All rights reserved.\n\n;; Redistribution and us", "end": 1618, "score": 0.9998778104782104, "start": 1604, "tag": "NAME", "value": "Mark W. Naylor" } ]
src/advent_2020/day05.clj
mark-naylor-1701/advent_2020
0
;; author: Mark W. Naylor ;; file: day05.clj ;; date: 2021-Jun-01 (ns advent-2020.day05 (:require [advent-2020.core :refer [input]] [clojure.string :as string] [clojure.set :refer [difference]])) (def input-file "day05.txt") (defn binary-code "Converts the seat code to a binary string." [seat-code] (->> seat-code (#(string/replace % #"[BR]" "1")) (#(string/replace % #"[FL]" "0")))) (defn binary-str->int "Converts a binary string to an decimal value." [bin-str] (->> bin-str (#(string/replace % #"[BR]" "1")) (#(string/replace % #"[FL]" "0")) (#(Integer/parseInt % 2)))) (defn seat-code->int "Converts the seat code to the equivalent decimal value." [seat-code] (-> seat-code binary-code binary-str->int)) (defn largest-seat-code [decimal-seat-codes] (apply max decimal-seat-codes)) (defn file->int-seat-codes "Transform from source file to usable decimal codes" [] (->> input-file input (map seat-code->int))) (defn largest-code-part1 "Find the largest decimal seat code in the data set." [] (->> (file->int-seat-codes) largest-seat-code)) (defn missing-seat "Find the only seat that does not have a boarding pass." [] (let [occupied-seats (set (file->int-seat-codes)) lowest (apply min occupied-seats) highest (apply max occupied-seats) all-seats (set (range lowest (inc highest)))] (first (difference all-seats occupied-seats)))) ;; ------------------------------------------------------------------------------ ;; BSD 3-Clause License ;; Copyright © 2021, Mark W. Naylor ;; 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. ;; 3. Neither the name of the copyright holder nor the names of its ;; contributors may be used to endorse or promote products derived from ;; this software without specific prior written permission. ;; 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.
32962
;; author: <NAME> ;; file: day05.clj ;; date: 2021-Jun-01 (ns advent-2020.day05 (:require [advent-2020.core :refer [input]] [clojure.string :as string] [clojure.set :refer [difference]])) (def input-file "day05.txt") (defn binary-code "Converts the seat code to a binary string." [seat-code] (->> seat-code (#(string/replace % #"[BR]" "1")) (#(string/replace % #"[FL]" "0")))) (defn binary-str->int "Converts a binary string to an decimal value." [bin-str] (->> bin-str (#(string/replace % #"[BR]" "1")) (#(string/replace % #"[FL]" "0")) (#(Integer/parseInt % 2)))) (defn seat-code->int "Converts the seat code to the equivalent decimal value." [seat-code] (-> seat-code binary-code binary-str->int)) (defn largest-seat-code [decimal-seat-codes] (apply max decimal-seat-codes)) (defn file->int-seat-codes "Transform from source file to usable decimal codes" [] (->> input-file input (map seat-code->int))) (defn largest-code-part1 "Find the largest decimal seat code in the data set." [] (->> (file->int-seat-codes) largest-seat-code)) (defn missing-seat "Find the only seat that does not have a boarding pass." [] (let [occupied-seats (set (file->int-seat-codes)) lowest (apply min occupied-seats) highest (apply max occupied-seats) all-seats (set (range lowest (inc highest)))] (first (difference all-seats occupied-seats)))) ;; ------------------------------------------------------------------------------ ;; BSD 3-Clause License ;; Copyright © 2021, <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. ;; 3. Neither the name of the copyright holder nor the names of its ;; contributors may be used to endorse or promote products derived from ;; this software without specific prior written permission. ;; 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.
true
;; author: PI:NAME:<NAME>END_PI ;; file: day05.clj ;; date: 2021-Jun-01 (ns advent-2020.day05 (:require [advent-2020.core :refer [input]] [clojure.string :as string] [clojure.set :refer [difference]])) (def input-file "day05.txt") (defn binary-code "Converts the seat code to a binary string." [seat-code] (->> seat-code (#(string/replace % #"[BR]" "1")) (#(string/replace % #"[FL]" "0")))) (defn binary-str->int "Converts a binary string to an decimal value." [bin-str] (->> bin-str (#(string/replace % #"[BR]" "1")) (#(string/replace % #"[FL]" "0")) (#(Integer/parseInt % 2)))) (defn seat-code->int "Converts the seat code to the equivalent decimal value." [seat-code] (-> seat-code binary-code binary-str->int)) (defn largest-seat-code [decimal-seat-codes] (apply max decimal-seat-codes)) (defn file->int-seat-codes "Transform from source file to usable decimal codes" [] (->> input-file input (map seat-code->int))) (defn largest-code-part1 "Find the largest decimal seat code in the data set." [] (->> (file->int-seat-codes) largest-seat-code)) (defn missing-seat "Find the only seat that does not have a boarding pass." [] (let [occupied-seats (set (file->int-seat-codes)) lowest (apply min occupied-seats) highest (apply max occupied-seats) all-seats (set (range lowest (inc highest)))] (first (difference all-seats occupied-seats)))) ;; ------------------------------------------------------------------------------ ;; BSD 3-Clause License ;; Copyright © 2021, 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. ;; 3. Neither the name of the copyright holder nor the names of its ;; contributors may be used to endorse or promote products derived from ;; this software without specific prior written permission. ;; 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.
[ { "context": ";; Copyright 2014 (c) Diego Souza <dsouza@c0d3.xxx>\n;; Copyright 2014 (c) Alexandre", "end": 33, "score": 0.9998762011528015, "start": 22, "tag": "NAME", "value": "Diego Souza" }, { "context": ";; Copyright 2014 (c) Diego Souza <dsouza@c0d3.xxx>\n;; Copyright 2014 (c) Alexandre Baaklini <abaakl", "end": 50, "score": 0.9998559951782227, "start": 35, "tag": "EMAIL", "value": "dsouza@c0d3.xxx" }, { "context": "iego Souza <dsouza@c0d3.xxx>\n;; Copyright 2014 (c) Alexandre Baaklini <abaaklini@gmail.com>\n;;\n;; Licensed under the Ap", "end": 92, "score": 0.9998741149902344, "start": 74, "tag": "NAME", "value": "Alexandre Baaklini" }, { "context": "d3.xxx>\n;; Copyright 2014 (c) Alexandre Baaklini <abaaklini@gmail.com>\n;;\n;; Licensed under the Apache License, Version", "end": 113, "score": 0.9999194741249084, "start": 94, "tag": "EMAIL", "value": "abaaklini@gmail.com" } ]
src/blackbox/src/leela/blackbox/storage/cassandra.clj
locaweb/leela
22
;; Copyright 2014 (c) Diego Souza <dsouza@c0d3.xxx> ;; Copyright 2014 (c) Alexandre Baaklini <abaaklini@gmail.com> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns leela.blackbox.storage.cassandra (:use [clj-time.core :only [date-time year month day]] [clj-time.coerce] [clojure.tools.logging :only [info warn]] [clojurewerkz.cassaforte.query] [clojurewerkz.cassaforte.cql]) (:require [clojure.string :as s] [leela.blackbox.f :as f] [clojurewerkz.cassaforte.policies :as policies] [clojurewerkz.cassaforte.client :as client])) (def +limit+ 32) (defn decode-time [time-in-sec] (let [time (from-long (* 1000 time-in-sec)) bucket (quot (to-long (date-time (year time) (month time) (day time))) 1000) slot (- time-in-sec bucket)] [(month time) bucket slot])) (defn encode-time [bucket slot] (+ bucket slot)) (defn t-attr-colfam [month] (keyword (format "t_attr_%02d" month))) (defn use-attr-schema [cluster keyspace] (when-not (describe-keyspace cluster keyspace) (warn (format "creating keyspace %s [simplestrategy, rf=1]" keyspace)) (create-keyspace cluster keyspace (if-not-exists) (with {:replication {:class "SimpleStrategy" :replication_factor 1}}))) (info (format "connecting to keyspace %s" keyspace)) (use-keyspace cluster keyspace) (dotimes [m 12] (let [colfam (t-attr-colfam (+ 1 m))] (when-not (describe-table cluster keyspace colfam) (warn (format "creating table %s" colfam) (create-table cluster colfam (if-not-exists) (column-definitions {:key :uuid :name :varchar :bucket :bigint :slot :int :data :blob :primary-key [[:key :name :bucket] :slot]}) (with {:compaction {:class "SizeTieredCompactionStrategy" :cold_reads_to_omit "0"}})))))) (when-not (describe-table cluster keyspace :k_attr) (warn "creating table k_attr") (create-table cluster :k_attr (if-not-exists) (column-definitions {:key :uuid :name :varchar :value :blob :primary-key [[:key :name]]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :k_index) (warn "creating table k_index") (create-table cluster :k_index (if-not-exists) (column-definitions {:key :uuid :name :varchar :primary-key [[:key] :name]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :t_index) (warn "creating table t_index") (create-table cluster :t_index (if-not-exists) (column-definitions {:key :uuid :name :varchar :primary-key [[:key] :name]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}})))) (defn use-graph-schema [cluster keyspace] (when-not (describe-keyspace cluster keyspace) (warn (format "creating keyspace %s [simplestrategy, rf=1]" keyspace)) (create-keyspace cluster keyspace (if-not-exists) (with {:replication {:class "SimpleStrategy" :replication_factor 1}}))) (info (format "connecting to keyspace %s" keyspace)) (use-keyspace cluster keyspace) (when-not (describe-table cluster keyspace :graph) (warn "creating table graph") (create-table cluster :graph (if-not-exists) (column-definitions {:a :uuid :l :varchar :b :uuid :primary-key [[:a :l] :b]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :n_naming) (warn "creating table n_naming") (create-table cluster :n_naming (if-not-exists) (column-definitions {:user :varchar :tree :varchar :kind :varchar :node :varchar :guid :uuid :primary-key [[:user :tree :kind] :node]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :g_naming) (warn "creating table g_naming") (create-table cluster :g_naming (if-not-exists) (column-definitions {:guid :uuid :user :varchar :tree :varchar :kind :varchar :node :varchar :primary-key [:guid]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :g_index) (warn "creating table g_index") (create-table cluster :g_index (if-not-exists) (column-definitions {:key :uuid :name :varchar :primary-key [[:key] :name]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}})))) (defmacro with-connection [[conn endpoint options] & body] `(let [~conn (.connect (client/build-cluster {:hosts ~endpoint :retry-policy (policies/logging-retry-policy (policies/retry-policy :fallthrough)) :credentials (:credentials ~options) :load-balancing-policy (policies/token-aware-policy (policies/round-robin-policy)) :connections-per-host (:connections ~options) :max-connections-per-host (:max-connections ~options)}))] (info (format "cassandra/with-connection %s" (dissoc ~options :credentials))) (try ~@body (finally (.close ~conn))))) (defmacro with-consistency [tag & body] `(policies/with-consistency-level (policies/consistency-level ~tag) ~@body)) (defmacro with-limit [lim & body] `(with-redefs [+limit+ (f/parse-int (or ~lim +limit+))] ~@body)) (defn truncate-all [cluster] (dotimes [m 12] (truncate cluster (t-attr-colfam (+ 1 m)))) (doseq [t [:graph :g_index :k_index :t_index :k_attr :n_naming :g_naming]] (truncate cluster t))) (defn fmt-put-index-opts [table data opts] (let [value (:name data)] (if (empty? opts) (insert-query table data) (insert-query table data (apply using opts))))) (defn fmt-put-index [table data] (fmt-put-index-opts table data [])) (defn fmt-del-index [table data] (let [value (:name data)] [(delete-query table (where [[= :key (:key data)] [= :name value]]))])) (defn fmt-put-link [data] (insert-query :graph data)) (defn fmt-del-link [data] (if-let [b (:b data)] (delete-query :graph (where [[= :a (:a data)] [= :l (:l data)] [= :b b]])) (delete-query :graph (where [[= :a (:a data)] [= :l (:l data)]])))) (defn fmt-put-kattr [[data opts0]] (let [opts (flatten (seq (dissoc opts0 :index))) idx (if (:index opts0) [(fmt-put-index-opts :k_index {:key (:key data) :name (:name data)} opts)] [])] (if (empty? opts) (cons (insert-query :k_attr data) idx) (cons (insert-query :k_attr data (apply using opts)) idx)))) (defn fmt-put-tattr [[data opts0]] (let [opts (flatten (seq (dissoc opts0 :index))) [month bucket slot] (decode-time (:time data)) idx (if (:index opts0) [(fmt-put-index-opts :t_index {:key (:key data) :name (:name data)} opts)] [])] (if (empty? opts) (cons (insert-query (t-attr-colfam month) {:data (:value data) :key (:key data) :name (:name data) :bucket bucket :slot slot}) idx) (cons (insert-query (t-attr-colfam month) {:data (:value data) :key (:key data) :name (:name data) :bucket bucket :slot slot} (apply using opts)) idx)))) (defn fmt-del-kattr [data] (cons (delete-query :k_attr (where [[= :key (:key data)] [= :name (:name data)]])) (fmt-del-index :k_index {:key (:key data) :name (:name data)}))) (defn fmt-del-tattr [data] (if (contains? data :time) (let [[month bucket slot] (decode-time (:time data))] [(delete-query (t-attr-colfam month) (where [[= :key (:key data)] [= :name (:name data)] [= :bucket bucket] [= :slot slot]]))]) (fmt-del-index :t_index {:key (:key data) :name (:name data)}))) (defn put-index [cluster table indexes] (doseq [query (map (partial fmt-put-index table) indexes)] (client/execute cluster (client/render-query query)))) (defn getguid0 [cluster user tree kind node] (map (fn [row] [(:guid row) (:node row)]) (select cluster :n_naming (columns :node :guid) (where [[= :user user] [= :tree tree] [= :kind kind] [= :node node]])))) (defn getguid [cluster user tree kind node] (with-limit 1 (if-let [[guid _] (first (getguid0 cluster user tree kind node))] guid))) (defn getname [cluster guid] (first (map (fn [row] [(:user row) (:tree row) (:kind row) (:node row)]) (select cluster :g_naming (columns :user :tree :kind :node) (where [[= :guid guid]]) (limit 1))))) (defn putguid [cluster user tree kind node] (if-let [guid (getguid cluster user tree kind node)] guid (let [guid (f/uuid-1)] (client/execute cluster (client/render-query (batch-query (queries (insert-query :n_naming {:user user :tree tree :kind kind :node node :guid guid}) (insert-query :g_naming {:user user :tree tree :kind kind :node node :guid guid}))))) guid))) (defn get-index [cluster table k & optional] (let [[start finish] optional] (map #(:name %) (select cluster table (columns :name) (case [(boolean start) (boolean finish)] [true true] (where [[= :key k] [>= :name start] [< :name finish]]) [true false] (where [[= :key k] [>= :name start]]) (where [[= :key k]])) (limit +limit+))))) (defn has-index [cluster table k name] (map #(:name %) (select cluster table (columns :name) (where [[= :key k] [= :name name]]) (limit 1)))) (defn putlink [cluster links] (doseq [query (map fmt-put-link links)] (client/execute cluster (client/render-query query)))) (defn dellink [cluster links] (doseq [query (map fmt-del-link links)] (client/execute cluster (client/render-query query)))) (defn getlink [cluster k l & page] (map #(:b %) (select cluster :graph (columns :b) (if (seq page) (where [[= :a k] [= :l l] [>= :b (first page)]]) (where [[= :a k] [= :l l]])) (limit +limit+)))) (defn put-tattr [cluster attrs] (doseq [query (mapcat fmt-put-tattr attrs)] (client/execute cluster (client/render-query query)))) (defn enum-tattr ([cluster t l] (let [[month _ _] (decode-time t) l (f/parse-int l)] (select cluster (t-attr-colfam month) (columns :key :name :bucket) (limit l)))) ([cluster t l & attrs] (let [[month _ _] (decode-time t) l (f/parse-int l) [k n b] attrs] (select cluster (t-attr-colfam month) (columns :key :name :bucket) (where [[> (token :key :name :bucket) (token k n b)]]) (limit l))))) (defn get-tattr [cluster k name time] (let [[month bucket slot] (decode-time time)] (map (fn [row] [(encode-time bucket (:slot row)) (f/binary-to-bytes (:data row))]) (select cluster (t-attr-colfam month) (columns :slot :data) (where [[= :key k] [= :name name] [= :bucket bucket] [>= :slot slot]]) (limit +limit+))))) (defn del-tattr [cluster attrs] (doseq [query (mapcat fmt-del-tattr attrs)] (client/execute cluster (client/render-query query)))) (defn put-kattr [cluster attrs] (doseq [query (mapcat fmt-put-kattr attrs)] (client/execute cluster (client/render-query query)))) (defn get-kattr [cluster k name] (first (map #(f/binary-to-bytes (:value %)) (select cluster :k_attr (columns :value) (where [[= :key k] [= :name name]]) (limit 1))))) (defn del-kattr [cluster attrs] (doseq [query (mapcat fmt-del-kattr attrs)] (client/execute cluster (client/render-query query))))
11301
;; Copyright 2014 (c) <NAME> <<EMAIL>> ;; Copyright 2014 (c) <NAME> <<EMAIL>> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns leela.blackbox.storage.cassandra (:use [clj-time.core :only [date-time year month day]] [clj-time.coerce] [clojure.tools.logging :only [info warn]] [clojurewerkz.cassaforte.query] [clojurewerkz.cassaforte.cql]) (:require [clojure.string :as s] [leela.blackbox.f :as f] [clojurewerkz.cassaforte.policies :as policies] [clojurewerkz.cassaforte.client :as client])) (def +limit+ 32) (defn decode-time [time-in-sec] (let [time (from-long (* 1000 time-in-sec)) bucket (quot (to-long (date-time (year time) (month time) (day time))) 1000) slot (- time-in-sec bucket)] [(month time) bucket slot])) (defn encode-time [bucket slot] (+ bucket slot)) (defn t-attr-colfam [month] (keyword (format "t_attr_%02d" month))) (defn use-attr-schema [cluster keyspace] (when-not (describe-keyspace cluster keyspace) (warn (format "creating keyspace %s [simplestrategy, rf=1]" keyspace)) (create-keyspace cluster keyspace (if-not-exists) (with {:replication {:class "SimpleStrategy" :replication_factor 1}}))) (info (format "connecting to keyspace %s" keyspace)) (use-keyspace cluster keyspace) (dotimes [m 12] (let [colfam (t-attr-colfam (+ 1 m))] (when-not (describe-table cluster keyspace colfam) (warn (format "creating table %s" colfam) (create-table cluster colfam (if-not-exists) (column-definitions {:key :uuid :name :varchar :bucket :bigint :slot :int :data :blob :primary-key [[:key :name :bucket] :slot]}) (with {:compaction {:class "SizeTieredCompactionStrategy" :cold_reads_to_omit "0"}})))))) (when-not (describe-table cluster keyspace :k_attr) (warn "creating table k_attr") (create-table cluster :k_attr (if-not-exists) (column-definitions {:key :uuid :name :varchar :value :blob :primary-key [[:key :name]]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :k_index) (warn "creating table k_index") (create-table cluster :k_index (if-not-exists) (column-definitions {:key :uuid :name :varchar :primary-key [[:key] :name]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :t_index) (warn "creating table t_index") (create-table cluster :t_index (if-not-exists) (column-definitions {:key :uuid :name :varchar :primary-key [[:key] :name]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}})))) (defn use-graph-schema [cluster keyspace] (when-not (describe-keyspace cluster keyspace) (warn (format "creating keyspace %s [simplestrategy, rf=1]" keyspace)) (create-keyspace cluster keyspace (if-not-exists) (with {:replication {:class "SimpleStrategy" :replication_factor 1}}))) (info (format "connecting to keyspace %s" keyspace)) (use-keyspace cluster keyspace) (when-not (describe-table cluster keyspace :graph) (warn "creating table graph") (create-table cluster :graph (if-not-exists) (column-definitions {:a :uuid :l :varchar :b :uuid :primary-key [[:a :l] :b]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :n_naming) (warn "creating table n_naming") (create-table cluster :n_naming (if-not-exists) (column-definitions {:user :varchar :tree :varchar :kind :varchar :node :varchar :guid :uuid :primary-key [[:user :tree :kind] :node]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :g_naming) (warn "creating table g_naming") (create-table cluster :g_naming (if-not-exists) (column-definitions {:guid :uuid :user :varchar :tree :varchar :kind :varchar :node :varchar :primary-key [:guid]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :g_index) (warn "creating table g_index") (create-table cluster :g_index (if-not-exists) (column-definitions {:key :uuid :name :varchar :primary-key [[:key] :name]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}})))) (defmacro with-connection [[conn endpoint options] & body] `(let [~conn (.connect (client/build-cluster {:hosts ~endpoint :retry-policy (policies/logging-retry-policy (policies/retry-policy :fallthrough)) :credentials (:credentials ~options) :load-balancing-policy (policies/token-aware-policy (policies/round-robin-policy)) :connections-per-host (:connections ~options) :max-connections-per-host (:max-connections ~options)}))] (info (format "cassandra/with-connection %s" (dissoc ~options :credentials))) (try ~@body (finally (.close ~conn))))) (defmacro with-consistency [tag & body] `(policies/with-consistency-level (policies/consistency-level ~tag) ~@body)) (defmacro with-limit [lim & body] `(with-redefs [+limit+ (f/parse-int (or ~lim +limit+))] ~@body)) (defn truncate-all [cluster] (dotimes [m 12] (truncate cluster (t-attr-colfam (+ 1 m)))) (doseq [t [:graph :g_index :k_index :t_index :k_attr :n_naming :g_naming]] (truncate cluster t))) (defn fmt-put-index-opts [table data opts] (let [value (:name data)] (if (empty? opts) (insert-query table data) (insert-query table data (apply using opts))))) (defn fmt-put-index [table data] (fmt-put-index-opts table data [])) (defn fmt-del-index [table data] (let [value (:name data)] [(delete-query table (where [[= :key (:key data)] [= :name value]]))])) (defn fmt-put-link [data] (insert-query :graph data)) (defn fmt-del-link [data] (if-let [b (:b data)] (delete-query :graph (where [[= :a (:a data)] [= :l (:l data)] [= :b b]])) (delete-query :graph (where [[= :a (:a data)] [= :l (:l data)]])))) (defn fmt-put-kattr [[data opts0]] (let [opts (flatten (seq (dissoc opts0 :index))) idx (if (:index opts0) [(fmt-put-index-opts :k_index {:key (:key data) :name (:name data)} opts)] [])] (if (empty? opts) (cons (insert-query :k_attr data) idx) (cons (insert-query :k_attr data (apply using opts)) idx)))) (defn fmt-put-tattr [[data opts0]] (let [opts (flatten (seq (dissoc opts0 :index))) [month bucket slot] (decode-time (:time data)) idx (if (:index opts0) [(fmt-put-index-opts :t_index {:key (:key data) :name (:name data)} opts)] [])] (if (empty? opts) (cons (insert-query (t-attr-colfam month) {:data (:value data) :key (:key data) :name (:name data) :bucket bucket :slot slot}) idx) (cons (insert-query (t-attr-colfam month) {:data (:value data) :key (:key data) :name (:name data) :bucket bucket :slot slot} (apply using opts)) idx)))) (defn fmt-del-kattr [data] (cons (delete-query :k_attr (where [[= :key (:key data)] [= :name (:name data)]])) (fmt-del-index :k_index {:key (:key data) :name (:name data)}))) (defn fmt-del-tattr [data] (if (contains? data :time) (let [[month bucket slot] (decode-time (:time data))] [(delete-query (t-attr-colfam month) (where [[= :key (:key data)] [= :name (:name data)] [= :bucket bucket] [= :slot slot]]))]) (fmt-del-index :t_index {:key (:key data) :name (:name data)}))) (defn put-index [cluster table indexes] (doseq [query (map (partial fmt-put-index table) indexes)] (client/execute cluster (client/render-query query)))) (defn getguid0 [cluster user tree kind node] (map (fn [row] [(:guid row) (:node row)]) (select cluster :n_naming (columns :node :guid) (where [[= :user user] [= :tree tree] [= :kind kind] [= :node node]])))) (defn getguid [cluster user tree kind node] (with-limit 1 (if-let [[guid _] (first (getguid0 cluster user tree kind node))] guid))) (defn getname [cluster guid] (first (map (fn [row] [(:user row) (:tree row) (:kind row) (:node row)]) (select cluster :g_naming (columns :user :tree :kind :node) (where [[= :guid guid]]) (limit 1))))) (defn putguid [cluster user tree kind node] (if-let [guid (getguid cluster user tree kind node)] guid (let [guid (f/uuid-1)] (client/execute cluster (client/render-query (batch-query (queries (insert-query :n_naming {:user user :tree tree :kind kind :node node :guid guid}) (insert-query :g_naming {:user user :tree tree :kind kind :node node :guid guid}))))) guid))) (defn get-index [cluster table k & optional] (let [[start finish] optional] (map #(:name %) (select cluster table (columns :name) (case [(boolean start) (boolean finish)] [true true] (where [[= :key k] [>= :name start] [< :name finish]]) [true false] (where [[= :key k] [>= :name start]]) (where [[= :key k]])) (limit +limit+))))) (defn has-index [cluster table k name] (map #(:name %) (select cluster table (columns :name) (where [[= :key k] [= :name name]]) (limit 1)))) (defn putlink [cluster links] (doseq [query (map fmt-put-link links)] (client/execute cluster (client/render-query query)))) (defn dellink [cluster links] (doseq [query (map fmt-del-link links)] (client/execute cluster (client/render-query query)))) (defn getlink [cluster k l & page] (map #(:b %) (select cluster :graph (columns :b) (if (seq page) (where [[= :a k] [= :l l] [>= :b (first page)]]) (where [[= :a k] [= :l l]])) (limit +limit+)))) (defn put-tattr [cluster attrs] (doseq [query (mapcat fmt-put-tattr attrs)] (client/execute cluster (client/render-query query)))) (defn enum-tattr ([cluster t l] (let [[month _ _] (decode-time t) l (f/parse-int l)] (select cluster (t-attr-colfam month) (columns :key :name :bucket) (limit l)))) ([cluster t l & attrs] (let [[month _ _] (decode-time t) l (f/parse-int l) [k n b] attrs] (select cluster (t-attr-colfam month) (columns :key :name :bucket) (where [[> (token :key :name :bucket) (token k n b)]]) (limit l))))) (defn get-tattr [cluster k name time] (let [[month bucket slot] (decode-time time)] (map (fn [row] [(encode-time bucket (:slot row)) (f/binary-to-bytes (:data row))]) (select cluster (t-attr-colfam month) (columns :slot :data) (where [[= :key k] [= :name name] [= :bucket bucket] [>= :slot slot]]) (limit +limit+))))) (defn del-tattr [cluster attrs] (doseq [query (mapcat fmt-del-tattr attrs)] (client/execute cluster (client/render-query query)))) (defn put-kattr [cluster attrs] (doseq [query (mapcat fmt-put-kattr attrs)] (client/execute cluster (client/render-query query)))) (defn get-kattr [cluster k name] (first (map #(f/binary-to-bytes (:value %)) (select cluster :k_attr (columns :value) (where [[= :key k] [= :name name]]) (limit 1))))) (defn del-kattr [cluster attrs] (doseq [query (mapcat fmt-del-kattr attrs)] (client/execute cluster (client/render-query query))))
true
;; Copyright 2014 (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; Copyright 2014 (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns leela.blackbox.storage.cassandra (:use [clj-time.core :only [date-time year month day]] [clj-time.coerce] [clojure.tools.logging :only [info warn]] [clojurewerkz.cassaforte.query] [clojurewerkz.cassaforte.cql]) (:require [clojure.string :as s] [leela.blackbox.f :as f] [clojurewerkz.cassaforte.policies :as policies] [clojurewerkz.cassaforte.client :as client])) (def +limit+ 32) (defn decode-time [time-in-sec] (let [time (from-long (* 1000 time-in-sec)) bucket (quot (to-long (date-time (year time) (month time) (day time))) 1000) slot (- time-in-sec bucket)] [(month time) bucket slot])) (defn encode-time [bucket slot] (+ bucket slot)) (defn t-attr-colfam [month] (keyword (format "t_attr_%02d" month))) (defn use-attr-schema [cluster keyspace] (when-not (describe-keyspace cluster keyspace) (warn (format "creating keyspace %s [simplestrategy, rf=1]" keyspace)) (create-keyspace cluster keyspace (if-not-exists) (with {:replication {:class "SimpleStrategy" :replication_factor 1}}))) (info (format "connecting to keyspace %s" keyspace)) (use-keyspace cluster keyspace) (dotimes [m 12] (let [colfam (t-attr-colfam (+ 1 m))] (when-not (describe-table cluster keyspace colfam) (warn (format "creating table %s" colfam) (create-table cluster colfam (if-not-exists) (column-definitions {:key :uuid :name :varchar :bucket :bigint :slot :int :data :blob :primary-key [[:key :name :bucket] :slot]}) (with {:compaction {:class "SizeTieredCompactionStrategy" :cold_reads_to_omit "0"}})))))) (when-not (describe-table cluster keyspace :k_attr) (warn "creating table k_attr") (create-table cluster :k_attr (if-not-exists) (column-definitions {:key :uuid :name :varchar :value :blob :primary-key [[:key :name]]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :k_index) (warn "creating table k_index") (create-table cluster :k_index (if-not-exists) (column-definitions {:key :uuid :name :varchar :primary-key [[:key] :name]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :t_index) (warn "creating table t_index") (create-table cluster :t_index (if-not-exists) (column-definitions {:key :uuid :name :varchar :primary-key [[:key] :name]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}})))) (defn use-graph-schema [cluster keyspace] (when-not (describe-keyspace cluster keyspace) (warn (format "creating keyspace %s [simplestrategy, rf=1]" keyspace)) (create-keyspace cluster keyspace (if-not-exists) (with {:replication {:class "SimpleStrategy" :replication_factor 1}}))) (info (format "connecting to keyspace %s" keyspace)) (use-keyspace cluster keyspace) (when-not (describe-table cluster keyspace :graph) (warn "creating table graph") (create-table cluster :graph (if-not-exists) (column-definitions {:a :uuid :l :varchar :b :uuid :primary-key [[:a :l] :b]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :n_naming) (warn "creating table n_naming") (create-table cluster :n_naming (if-not-exists) (column-definitions {:user :varchar :tree :varchar :kind :varchar :node :varchar :guid :uuid :primary-key [[:user :tree :kind] :node]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :g_naming) (warn "creating table g_naming") (create-table cluster :g_naming (if-not-exists) (column-definitions {:guid :uuid :user :varchar :tree :varchar :kind :varchar :node :varchar :primary-key [:guid]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}}))) (when-not (describe-table cluster keyspace :g_index) (warn "creating table g_index") (create-table cluster :g_index (if-not-exists) (column-definitions {:key :uuid :name :varchar :primary-key [[:key] :name]}) (with {:compaction {:class "LeveledCompactionStrategy" :sstable_size_in_mb "256"}})))) (defmacro with-connection [[conn endpoint options] & body] `(let [~conn (.connect (client/build-cluster {:hosts ~endpoint :retry-policy (policies/logging-retry-policy (policies/retry-policy :fallthrough)) :credentials (:credentials ~options) :load-balancing-policy (policies/token-aware-policy (policies/round-robin-policy)) :connections-per-host (:connections ~options) :max-connections-per-host (:max-connections ~options)}))] (info (format "cassandra/with-connection %s" (dissoc ~options :credentials))) (try ~@body (finally (.close ~conn))))) (defmacro with-consistency [tag & body] `(policies/with-consistency-level (policies/consistency-level ~tag) ~@body)) (defmacro with-limit [lim & body] `(with-redefs [+limit+ (f/parse-int (or ~lim +limit+))] ~@body)) (defn truncate-all [cluster] (dotimes [m 12] (truncate cluster (t-attr-colfam (+ 1 m)))) (doseq [t [:graph :g_index :k_index :t_index :k_attr :n_naming :g_naming]] (truncate cluster t))) (defn fmt-put-index-opts [table data opts] (let [value (:name data)] (if (empty? opts) (insert-query table data) (insert-query table data (apply using opts))))) (defn fmt-put-index [table data] (fmt-put-index-opts table data [])) (defn fmt-del-index [table data] (let [value (:name data)] [(delete-query table (where [[= :key (:key data)] [= :name value]]))])) (defn fmt-put-link [data] (insert-query :graph data)) (defn fmt-del-link [data] (if-let [b (:b data)] (delete-query :graph (where [[= :a (:a data)] [= :l (:l data)] [= :b b]])) (delete-query :graph (where [[= :a (:a data)] [= :l (:l data)]])))) (defn fmt-put-kattr [[data opts0]] (let [opts (flatten (seq (dissoc opts0 :index))) idx (if (:index opts0) [(fmt-put-index-opts :k_index {:key (:key data) :name (:name data)} opts)] [])] (if (empty? opts) (cons (insert-query :k_attr data) idx) (cons (insert-query :k_attr data (apply using opts)) idx)))) (defn fmt-put-tattr [[data opts0]] (let [opts (flatten (seq (dissoc opts0 :index))) [month bucket slot] (decode-time (:time data)) idx (if (:index opts0) [(fmt-put-index-opts :t_index {:key (:key data) :name (:name data)} opts)] [])] (if (empty? opts) (cons (insert-query (t-attr-colfam month) {:data (:value data) :key (:key data) :name (:name data) :bucket bucket :slot slot}) idx) (cons (insert-query (t-attr-colfam month) {:data (:value data) :key (:key data) :name (:name data) :bucket bucket :slot slot} (apply using opts)) idx)))) (defn fmt-del-kattr [data] (cons (delete-query :k_attr (where [[= :key (:key data)] [= :name (:name data)]])) (fmt-del-index :k_index {:key (:key data) :name (:name data)}))) (defn fmt-del-tattr [data] (if (contains? data :time) (let [[month bucket slot] (decode-time (:time data))] [(delete-query (t-attr-colfam month) (where [[= :key (:key data)] [= :name (:name data)] [= :bucket bucket] [= :slot slot]]))]) (fmt-del-index :t_index {:key (:key data) :name (:name data)}))) (defn put-index [cluster table indexes] (doseq [query (map (partial fmt-put-index table) indexes)] (client/execute cluster (client/render-query query)))) (defn getguid0 [cluster user tree kind node] (map (fn [row] [(:guid row) (:node row)]) (select cluster :n_naming (columns :node :guid) (where [[= :user user] [= :tree tree] [= :kind kind] [= :node node]])))) (defn getguid [cluster user tree kind node] (with-limit 1 (if-let [[guid _] (first (getguid0 cluster user tree kind node))] guid))) (defn getname [cluster guid] (first (map (fn [row] [(:user row) (:tree row) (:kind row) (:node row)]) (select cluster :g_naming (columns :user :tree :kind :node) (where [[= :guid guid]]) (limit 1))))) (defn putguid [cluster user tree kind node] (if-let [guid (getguid cluster user tree kind node)] guid (let [guid (f/uuid-1)] (client/execute cluster (client/render-query (batch-query (queries (insert-query :n_naming {:user user :tree tree :kind kind :node node :guid guid}) (insert-query :g_naming {:user user :tree tree :kind kind :node node :guid guid}))))) guid))) (defn get-index [cluster table k & optional] (let [[start finish] optional] (map #(:name %) (select cluster table (columns :name) (case [(boolean start) (boolean finish)] [true true] (where [[= :key k] [>= :name start] [< :name finish]]) [true false] (where [[= :key k] [>= :name start]]) (where [[= :key k]])) (limit +limit+))))) (defn has-index [cluster table k name] (map #(:name %) (select cluster table (columns :name) (where [[= :key k] [= :name name]]) (limit 1)))) (defn putlink [cluster links] (doseq [query (map fmt-put-link links)] (client/execute cluster (client/render-query query)))) (defn dellink [cluster links] (doseq [query (map fmt-del-link links)] (client/execute cluster (client/render-query query)))) (defn getlink [cluster k l & page] (map #(:b %) (select cluster :graph (columns :b) (if (seq page) (where [[= :a k] [= :l l] [>= :b (first page)]]) (where [[= :a k] [= :l l]])) (limit +limit+)))) (defn put-tattr [cluster attrs] (doseq [query (mapcat fmt-put-tattr attrs)] (client/execute cluster (client/render-query query)))) (defn enum-tattr ([cluster t l] (let [[month _ _] (decode-time t) l (f/parse-int l)] (select cluster (t-attr-colfam month) (columns :key :name :bucket) (limit l)))) ([cluster t l & attrs] (let [[month _ _] (decode-time t) l (f/parse-int l) [k n b] attrs] (select cluster (t-attr-colfam month) (columns :key :name :bucket) (where [[> (token :key :name :bucket) (token k n b)]]) (limit l))))) (defn get-tattr [cluster k name time] (let [[month bucket slot] (decode-time time)] (map (fn [row] [(encode-time bucket (:slot row)) (f/binary-to-bytes (:data row))]) (select cluster (t-attr-colfam month) (columns :slot :data) (where [[= :key k] [= :name name] [= :bucket bucket] [>= :slot slot]]) (limit +limit+))))) (defn del-tattr [cluster attrs] (doseq [query (mapcat fmt-del-tattr attrs)] (client/execute cluster (client/render-query query)))) (defn put-kattr [cluster attrs] (doseq [query (mapcat fmt-put-kattr attrs)] (client/execute cluster (client/render-query query)))) (defn get-kattr [cluster k name] (first (map #(f/binary-to-bytes (:value %)) (select cluster :k_attr (columns :value) (where [[= :key k] [= :name name]]) (limit 1))))) (defn del-kattr [cluster attrs] (doseq [query (mapcat fmt-del-kattr attrs)] (client/execute cluster (client/render-query query))))
[ { "context": "ile\n;;; Activity: Macros\n;;; Authors:\n;;; A01371743 Luis E. Ballinas Aguilar\n(ns macros)\n\n(defmacro m", "end": 111, "score": 0.9931868314743042, "start": 102, "tag": "USERNAME", "value": "A01371743" }, { "context": "tivity: Macros\n;;; Authors:\n;;; A01371743 Luis E. Ballinas Aguilar\n(ns macros)\n\n(defmacro my-or\n \"Evaluates its exp", "end": 136, "score": 0.9911301732063293, "start": 112, "tag": "NAME", "value": "Luis E. Ballinas Aguilar" } ]
macros.clj
lu15v/TC2006
0
;;; ITESM CEM, April 14, 2016. ;;; Clojure Source File ;;; Activity: Macros ;;; Authors: ;;; A01371743 Luis E. Ballinas Aguilar (ns macros) (defmacro my-or "Evaluates its expressions one at a time, from left to right. If a form returns a logical true value, it returns that value and doesn't evaluate any of the other expressions, otherwise it returns the value of the last expression. (or) returns nil." ([] nil) ([x] x) ([x & y] `(let [temp# ~x] (if-not temp# (my-or ~@y) temp#)))) (defmacro do-loop "Implements the do-loop functionality, if in the condition (last argument of the body), specify :while, the body of the loop is repeated while the condition holds true, :until, repeat the body while the conditon holds false, another expression returns nil" [& body] `(let [condition# ~(first (last body))] (if (= :while condition#) (do-while ~@body) (if (= :until condition#) (not-do-while ~@body) nil)))) (defmacro do-while [& body] `(loop [] ~@(butlast body) (when ~(last (last body)) (recur)))) (defmacro not-do-while [& body] `(loop [] ~@(butlast body) (when-not ~(last (last body)) (recur)))) (defmacro def-pred "Takes a name, an arg vector, and a body of one or more expressions, and creates two functions, the first one with the specified name and body and the second with the prefix 'not-' with the opposite logic of the first one" [name vectr & body] `(do (defn ~name ~vectr ~@body) (defn ~(symbol (str "not-" name)) ~vectr (not (do ~@body))))) (defmacro create-function ([lst x] `(fn [~x] (do ~@lst))) ([lst x & args] `(fn [~x] (create-function ~lst ~@args)))) (defmacro defn-curry "Perfomrs a currying transformation to a function definition. It Takes as parameters a name, an args vector and a body of one of more expressions." [name vectr & body] (let [fst (first vectr) res (rest vectr)] (cond (> (count vectr) 1) `(defn ~name [~fst] (create-function ~body ~@res)) (= (count vectr) 1) `(defn ~name [~fst] (do ~@body)) :else `(defn ~name [] (do ~@body)))))
34611
;;; ITESM CEM, April 14, 2016. ;;; Clojure Source File ;;; Activity: Macros ;;; Authors: ;;; A01371743 <NAME> (ns macros) (defmacro my-or "Evaluates its expressions one at a time, from left to right. If a form returns a logical true value, it returns that value and doesn't evaluate any of the other expressions, otherwise it returns the value of the last expression. (or) returns nil." ([] nil) ([x] x) ([x & y] `(let [temp# ~x] (if-not temp# (my-or ~@y) temp#)))) (defmacro do-loop "Implements the do-loop functionality, if in the condition (last argument of the body), specify :while, the body of the loop is repeated while the condition holds true, :until, repeat the body while the conditon holds false, another expression returns nil" [& body] `(let [condition# ~(first (last body))] (if (= :while condition#) (do-while ~@body) (if (= :until condition#) (not-do-while ~@body) nil)))) (defmacro do-while [& body] `(loop [] ~@(butlast body) (when ~(last (last body)) (recur)))) (defmacro not-do-while [& body] `(loop [] ~@(butlast body) (when-not ~(last (last body)) (recur)))) (defmacro def-pred "Takes a name, an arg vector, and a body of one or more expressions, and creates two functions, the first one with the specified name and body and the second with the prefix 'not-' with the opposite logic of the first one" [name vectr & body] `(do (defn ~name ~vectr ~@body) (defn ~(symbol (str "not-" name)) ~vectr (not (do ~@body))))) (defmacro create-function ([lst x] `(fn [~x] (do ~@lst))) ([lst x & args] `(fn [~x] (create-function ~lst ~@args)))) (defmacro defn-curry "Perfomrs a currying transformation to a function definition. It Takes as parameters a name, an args vector and a body of one of more expressions." [name vectr & body] (let [fst (first vectr) res (rest vectr)] (cond (> (count vectr) 1) `(defn ~name [~fst] (create-function ~body ~@res)) (= (count vectr) 1) `(defn ~name [~fst] (do ~@body)) :else `(defn ~name [] (do ~@body)))))
true
;;; ITESM CEM, April 14, 2016. ;;; Clojure Source File ;;; Activity: Macros ;;; Authors: ;;; A01371743 PI:NAME:<NAME>END_PI (ns macros) (defmacro my-or "Evaluates its expressions one at a time, from left to right. If a form returns a logical true value, it returns that value and doesn't evaluate any of the other expressions, otherwise it returns the value of the last expression. (or) returns nil." ([] nil) ([x] x) ([x & y] `(let [temp# ~x] (if-not temp# (my-or ~@y) temp#)))) (defmacro do-loop "Implements the do-loop functionality, if in the condition (last argument of the body), specify :while, the body of the loop is repeated while the condition holds true, :until, repeat the body while the conditon holds false, another expression returns nil" [& body] `(let [condition# ~(first (last body))] (if (= :while condition#) (do-while ~@body) (if (= :until condition#) (not-do-while ~@body) nil)))) (defmacro do-while [& body] `(loop [] ~@(butlast body) (when ~(last (last body)) (recur)))) (defmacro not-do-while [& body] `(loop [] ~@(butlast body) (when-not ~(last (last body)) (recur)))) (defmacro def-pred "Takes a name, an arg vector, and a body of one or more expressions, and creates two functions, the first one with the specified name and body and the second with the prefix 'not-' with the opposite logic of the first one" [name vectr & body] `(do (defn ~name ~vectr ~@body) (defn ~(symbol (str "not-" name)) ~vectr (not (do ~@body))))) (defmacro create-function ([lst x] `(fn [~x] (do ~@lst))) ([lst x & args] `(fn [~x] (create-function ~lst ~@args)))) (defmacro defn-curry "Perfomrs a currying transformation to a function definition. It Takes as parameters a name, an args vector and a body of one of more expressions." [name vectr & body] (let [fst (first vectr) res (rest vectr)] (cond (> (count vectr) 1) `(defn ~name [~fst] (create-function ~body ~@res)) (= (count vectr) 1) `(defn ~name [~fst] (do ~@body)) :else `(defn ~name [] (do ~@body)))))
[ { "context": "eate-spike \"obilnitrh\"\n \"Obilni trh\"\n 49.199569, 16.597069\n ", "end": 2001, "score": 0.5149679183959961, "start": 2000, "tag": "NAME", "value": "h" } ]
src/gss/db.clj
bbktsk/green-spike
0
(ns gss.db (:require [monger.core :as mg] [monger.collection :as mc] [monger.operators :refer :all] [slingshot.slingshot :refer [throw+ try+]] [gss.m2x :as m2x])) (defonce db (atom nil)) (defonce conn (atom nil)) (def spikes "spikes") (defn connect [uri] (let [uri' (or uri "mongodb://127.0.0.1/green-spike") m (mg/connect-via-uri uri')] (reset! db (:db m)) (reset! conn (:conn m)))) (defn create-spike [id name lat lng dev eth state] (mc/insert @db spikes {:_id id :name name :lat lat :lng lng :dev dev :eth eth :state state})) (defn get-spike [id] (if-let [spike (mc/find-one-as-map @db spikes {:_id id})] spike (throw+ (format "Spike %s not found" id)))) (defn get-spikes [] (->> spikes (mc/find-maps @db) (map #(merge {:balance 0 :bounty 0 :wallet ""} %)))) (defn update-spike-wetness [spike] (let [{:keys [dev _id]} (get-spike spike) wetness (m2x/device-wetness dev)] (mc/update-by-id @db spikes _id {$set {:wetness wetness}}))) (defn update-spike-request [spike address] (let [{:keys [_id]} (get-spike spike)] (mc/update-by-id @db spikes _id {$set {:requestor address}}))) (defn create-testing [] (try+ (create-spike "holin" "Bush next to Holiday Inn" 49.184635 16.580268 "0904d16113289ea7b0f7d0dcbf8167ed" "02652bfde2ff7f3264138cdb2117021c202ebbe2" "red") (catch Object _ nil)) (try+ (create-spike "spilberk" "Spilberk" 49.193982 16.601023 "0904d16113289ea7b0f7d0dcbf8167ed" "50e339de78eb57ed8724107e044eb8d0a54b48a8" "yellow") (catch Object _ nil)) (try+ (create-spike "obilnitrh" "Obilni trh" 49.199569, 16.597069 "0904d16113289ea7b0f7d0dcbf8167ed" "9f97d33281649c7b38b73ead0c12ccef8f70a2b6" "green") (catch Object _ nil)))
57246
(ns gss.db (:require [monger.core :as mg] [monger.collection :as mc] [monger.operators :refer :all] [slingshot.slingshot :refer [throw+ try+]] [gss.m2x :as m2x])) (defonce db (atom nil)) (defonce conn (atom nil)) (def spikes "spikes") (defn connect [uri] (let [uri' (or uri "mongodb://127.0.0.1/green-spike") m (mg/connect-via-uri uri')] (reset! db (:db m)) (reset! conn (:conn m)))) (defn create-spike [id name lat lng dev eth state] (mc/insert @db spikes {:_id id :name name :lat lat :lng lng :dev dev :eth eth :state state})) (defn get-spike [id] (if-let [spike (mc/find-one-as-map @db spikes {:_id id})] spike (throw+ (format "Spike %s not found" id)))) (defn get-spikes [] (->> spikes (mc/find-maps @db) (map #(merge {:balance 0 :bounty 0 :wallet ""} %)))) (defn update-spike-wetness [spike] (let [{:keys [dev _id]} (get-spike spike) wetness (m2x/device-wetness dev)] (mc/update-by-id @db spikes _id {$set {:wetness wetness}}))) (defn update-spike-request [spike address] (let [{:keys [_id]} (get-spike spike)] (mc/update-by-id @db spikes _id {$set {:requestor address}}))) (defn create-testing [] (try+ (create-spike "holin" "Bush next to Holiday Inn" 49.184635 16.580268 "0904d16113289ea7b0f7d0dcbf8167ed" "02652bfde2ff7f3264138cdb2117021c202ebbe2" "red") (catch Object _ nil)) (try+ (create-spike "spilberk" "Spilberk" 49.193982 16.601023 "0904d16113289ea7b0f7d0dcbf8167ed" "50e339de78eb57ed8724107e044eb8d0a54b48a8" "yellow") (catch Object _ nil)) (try+ (create-spike "obilnitrh" "Obilni tr<NAME>" 49.199569, 16.597069 "0904d16113289ea7b0f7d0dcbf8167ed" "9f97d33281649c7b38b73ead0c12ccef8f70a2b6" "green") (catch Object _ nil)))
true
(ns gss.db (:require [monger.core :as mg] [monger.collection :as mc] [monger.operators :refer :all] [slingshot.slingshot :refer [throw+ try+]] [gss.m2x :as m2x])) (defonce db (atom nil)) (defonce conn (atom nil)) (def spikes "spikes") (defn connect [uri] (let [uri' (or uri "mongodb://127.0.0.1/green-spike") m (mg/connect-via-uri uri')] (reset! db (:db m)) (reset! conn (:conn m)))) (defn create-spike [id name lat lng dev eth state] (mc/insert @db spikes {:_id id :name name :lat lat :lng lng :dev dev :eth eth :state state})) (defn get-spike [id] (if-let [spike (mc/find-one-as-map @db spikes {:_id id})] spike (throw+ (format "Spike %s not found" id)))) (defn get-spikes [] (->> spikes (mc/find-maps @db) (map #(merge {:balance 0 :bounty 0 :wallet ""} %)))) (defn update-spike-wetness [spike] (let [{:keys [dev _id]} (get-spike spike) wetness (m2x/device-wetness dev)] (mc/update-by-id @db spikes _id {$set {:wetness wetness}}))) (defn update-spike-request [spike address] (let [{:keys [_id]} (get-spike spike)] (mc/update-by-id @db spikes _id {$set {:requestor address}}))) (defn create-testing [] (try+ (create-spike "holin" "Bush next to Holiday Inn" 49.184635 16.580268 "0904d16113289ea7b0f7d0dcbf8167ed" "02652bfde2ff7f3264138cdb2117021c202ebbe2" "red") (catch Object _ nil)) (try+ (create-spike "spilberk" "Spilberk" 49.193982 16.601023 "0904d16113289ea7b0f7d0dcbf8167ed" "50e339de78eb57ed8724107e044eb8d0a54b48a8" "yellow") (catch Object _ nil)) (try+ (create-spike "obilnitrh" "Obilni trPI:NAME:<NAME>END_PI" 49.199569, 16.597069 "0904d16113289ea7b0f7d0dcbf8167ed" "9f97d33281649c7b38b73ead0c12ccef8f70a2b6" "green") (catch Object _ nil)))
[ { "context": "is props]\n (dom/div\n (ui-person {:person/name \"Joe\" :person/age 22})))", "end": 387, "score": 0.999409556388855, "start": 384, "tag": "NAME", "value": "Joe" } ]
src/datomic/com/example/fulcro_comps_v1.cljc
justin-wallander/fulcro-rad-demo
0
(ns com.example.components.fulcro-comps-v1 (:require #?(:clj [com.fulcrologic.fulcro.dom-server :as dom] :cljs [com.fulcrologic.fulcro.dom :as dom]))) (defsc Person [this {:person/keys [name age]}] (dom/div (dom/p "Name: " name) (dom/p "Age: " age))) (def ui-person (comp/factory Person)) (defsc Root [this props] (dom/div (ui-person {:person/name "Joe" :person/age 22})))
11207
(ns com.example.components.fulcro-comps-v1 (:require #?(:clj [com.fulcrologic.fulcro.dom-server :as dom] :cljs [com.fulcrologic.fulcro.dom :as dom]))) (defsc Person [this {:person/keys [name age]}] (dom/div (dom/p "Name: " name) (dom/p "Age: " age))) (def ui-person (comp/factory Person)) (defsc Root [this props] (dom/div (ui-person {:person/name "<NAME>" :person/age 22})))
true
(ns com.example.components.fulcro-comps-v1 (:require #?(:clj [com.fulcrologic.fulcro.dom-server :as dom] :cljs [com.fulcrologic.fulcro.dom :as dom]))) (defsc Person [this {:person/keys [name age]}] (dom/div (dom/p "Name: " name) (dom/p "Age: " age))) (def ui-person (comp/factory Person)) (defsc Root [this props] (dom/div (ui-person {:person/name "PI:NAME:<NAME>END_PI" :person/age 22})))
[ { "context": ";; Authors: Sung Pae <self@sungpae.com>\n;; Joel Holdbrooks <c", "end": 20, "score": 0.9998849630355835, "start": 12, "tag": "NAME", "value": "Sung Pae" }, { "context": ";; Authors: Sung Pae <self@sungpae.com>\n;; Joel Holdbrooks <cjholdbrooks@gmail.", "end": 38, "score": 0.9999345541000366, "start": 22, "tag": "EMAIL", "value": "self@sungpae.com" }, { "context": "; Authors: Sung Pae <self@sungpae.com>\n;; Joel Holdbrooks <cjholdbrooks@gmail.com>\n\n(ns vim-clojure-static.", "end": 67, "score": 0.9998717308044434, "start": 52, "tag": "NAME", "value": "Joel Holdbrooks" }, { "context": "e <self@sungpae.com>\n;; Joel Holdbrooks <cjholdbrooks@gmail.com>\n\n(ns vim-clojure-static.generate\n (:require [cl", "end": 91, "score": 0.9999340772628784, "start": 69, "tag": "EMAIL", "value": "cjholdbrooks@gmail.com" }, { "context": "n-comment\n \"\\\" Generated from https://github.com/clojure-vim/clojure.vim/blob/%%RELEASE_TAG%%/clj/src/vim_cloj", "end": 2226, "score": 0.9974238872528076, "start": 2215, "tag": "USERNAME", "value": "clojure-vim" }, { "context": "util/regex/Pattern.html\n;; [5] https://github.com/openjdk/jdk/blob/4d13bf33d4932cc210a29c4e3a68f848db18575b", "end": 5501, "score": 0.9802474975585938, "start": 5494, "tag": "USERNAME", "value": "openjdk" }, { "context": "2920f43191ae48084cea2c641a42ca8d34381f5\n Author: guns <self@sungpae.com>\n Date: Sat Jan 26 06:53:14", "end": 8292, "score": 0.9996999502182007, "start": 8288, "tag": "USERNAME", "value": "guns" }, { "context": "191ae48084cea2c641a42ca8d34381f5\n Author: guns <self@sungpae.com>\n Date: Sat Jan 26 06:53:14 2013 -0600\n\n ", "end": 8310, "score": 0.9999266862869263, "start": 8294, "tag": "EMAIL", "value": "self@sungpae.com" } ]
clj/src/vim_clojure_static/generate.clj
lucascebertin/clojure.vim
0
;; Authors: Sung Pae <self@sungpae.com> ;; Joel Holdbrooks <cjholdbrooks@gmail.com> (ns vim-clojure-static.generate (:require [clojure.java.io :as io] [clojure.java.shell :refer [sh]] [clojure.set :as set] [clojure.string :as string] [clojure.data.csv :as csv] [frak :as f]) (:import [clojure.lang MultiFn Compiler] java.text.SimpleDateFormat java.util.Date)) ;; ;; Helpers ;; (defn- vim-frak-pattern "Create a non-capturing regular expression pattern compatible with Vim." [strs] (-> (f/string-pattern strs {:escape-chars :vim}) (string/replace #"\(\?:" "\\%\\("))) (defn- property-pattern "Vimscript very magic pattern for a character property class." ([s] (property-pattern s true)) ([s braces?] (if braces? (format "\\v\\\\[pP]\\{%s\\}" s) (format "\\v\\\\[pP]%s" s)))) (defn- syntax-match-properties "Vimscript literal `syntax match` for a character property class." ([group fmt props] (syntax-match-properties group fmt props true)) ([group fmt props braces?] (format "syntax match %s \"%s\" contained display\n" (name group) (property-pattern (format fmt (vim-frak-pattern props)) braces?)))) (defn- map-keyword-names "Add non fully-qualified versions of the clojure.core functions and stringify everything." [coll] (let [stringified (into #{} (map #(if (nil? %) "nil" (str %))) coll) bare-symbols (into #{} (map #(string/replace-first % #"^clojure\.core/(?!import\*$)" "")) stringified)] (set/union stringified bare-symbols))) (defn- vim-top-cluster "Generate a Vimscript literal `syntax cluster` statement for `groups` and all top-level syntax groups in the given syntax buffer." [groups syntax-buf] (->> syntax-buf (re-seq #"syntax\s+(?:keyword|match|region)\s+(\S+)(?!.*\bcontained\b)") (map peek) (concat groups) sort distinct (string/join \,) (format "syntax cluster clojureTop contains=@Spell,%s\n"))) ;; ;; Definitions ;; (def generation-comment "\" Generated from https://github.com/clojure-vim/clojure.vim/blob/%%RELEASE_TAG%%/clj/src/vim_clojure_static/generate.clj\n") (def clojure-version-comment (format "\" Clojure version %s\n" (clojure-version))) (def java-version-comment (format "\" Java version %s\n" (System/getProperty "java.version"))) (defn vars-in-ns [ns] (->> ns ns-publics (map (fn [[_ var]] (assoc (meta var) :var var :fqs (symbol var)))))) (defn ->fqs [vars] (into #{} (map :fqs) vars)) (defn multi-fn? [v] (instance? MultiFn (var-get (:var v)))) (defn function? [v] (or (and (nil? (:macro v)) (contains? v :arglists)) (multi-fn? v))) (defn variable? [v] (nil? (or (:macro v) (:special-form v) (:arglists v) (:inline v)))) (defn define? [v] (re-find #"([^/]*/)?\Af?def(?!ault)" (str (if (map? v) (:name v) v)))) (def keyword-groups "Special forms, constants, and every public var in clojure.core keyed by syntax group name." (let [vars (vars-in-ns 'clojure.core) compiler-specials (set (keys Compiler/specials)) exceptions '#{throw try catch finally} repeat '#{recur loop* clojure.core/loop clojure.core/doseq clojure.core/dotimes clojure.core/while} conditionals '#{case* clojure.core/case if clojure.core/if-not clojure.core/if-let clojure.core/if-some clojure.core/cond clojure.core/cond-> clojure.core/cond->> clojure.core/condp clojure.core/when clojure.core/when-first clojure.core/when-let clojure.core/when-not clojure.core/when-some} define (set/union (->fqs (filter define? vars)) (set (filter define? compiler-specials))) macros (->fqs (filter :macro vars)) functions (->fqs (filter function? vars)) variables (->fqs (filter variable? vars)) special (set/union (->fqs (filter :special-form vars)) compiler-specials)] {"clojureBoolean" '#{true false} "clojureConstant" '#{nil} "clojureException" exceptions "clojureRepeat" repeat "clojureCond" conditionals "clojureDefine" define "clojureVariable" variables "clojureFunc" functions "clojureSpecial" (set/difference special define repeat conditionals exceptions) "clojureMacro" (set/difference macros define repeat conditionals special)})) ;; Java 8 Character class implements Unicode standard 6.2 from 2012 [1], ;; Java 15 implements Unicode standard 13 from 2020 [2], ;; the latter standard includes a few more scripts and removes some. ;; Unicode Technical Standard #18 [3] describes Unicode Regular Expressions. ;; java.util.regex.Pattern [4] describes which parts of Unicode standard are supported. ;; Some values which aren't mentioned in Unicode or Javadoc, are also supported [5]. ;; ;; [1] https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html ;; [2] https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/Character.html ;; [3] https://unicode.org/reports/tr18/ ;; [4] https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/regex/Pattern.html ;; [5] https://github.com/openjdk/jdk/blob/4d13bf33d4932cc210a29c4e3a68f848db18575b/src/java.base/share/classes/java/util/regex/CharPredicates.java (def unicode-property-value-aliases (with-open [f (io/reader (io/resource "unicode/PropertyValueAliases.txt"))] (->> (csv/read-csv f :separator \;) (map (fn [row] (mapv string/trim row))) doall))) (def unicode-blocks (with-open [f (io/reader (io/resource "unicode/Blocks.txt"))] (->> (csv/read-csv f :separator \;) (map (fn [row] (mapv string/trim row))) doall))) (defn- block-alt-names [block-name] (let [n (string/upper-case block-name)] [n (string/replace n #"[ -]" "_") (string/replace n #" " "")])) (def character-properties {:posix #{"Lower" "Space" "XDigit" "Alnum" "Cntrl" "Graph" "Alpha" "Print" "Blank" "Digit" "Upper" "Punct" "ASCII"} :java #{"javaSpaceChar" "javaUnicodeIdentifierPart" "javaLetterOrDigit" "javaTitleCase" "javaLowerCase" "javaDefined" "javaAlphabetic" "javaIdentifierIgnorable" "javaJavaIdentifierStart" "javaIdeographic" "javaWhitespace" "javaMirrored" "javaUnicodeIdentifierStart" "javaISOControl" "javaUpperCase" "javaDigit" "javaLetter" "javaJavaIdentifierPart"} :binary #{"IDEOGRAPHIC" "HEX_DIGIT" "ALPHABETIC" "NONCHARACTERCODEPOINT" "GRAPH" "PUNCTUATION" "WORD" "LETTER" "TITLECASE" "JOIN_CONTROL" "CONTROL" "HEXDIGIT" "LOWERCASE" "NONCHARACTER_CODE_POINT" "JOINCONTROL" "BLANK" "WHITESPACE" "ALNUM" "DIGIT" "WHITE_SPACE" "ASSIGNED" "UPPERCASE" "PRINT"} ;; https://www.unicode.org/reports/tr44/#General_Category_Values :category (->> unicode-property-value-aliases (filter #(= "gc" (first %))) (map second) ;; Supported by Java but not in standard or docs. (concat ["LD"]) set) :script (->> unicode-property-value-aliases (filter #(= "sc" (first %))) (mapcat #(subvec % 1 3)) (map string/upper-case) set) :block (->> unicode-blocks (filter (fn [row] (and (seq (first row)) (not (string/starts-with? (first row) "#"))))) (map second) ;; Old names supported by Java (concat ["GREEK" "COMBINING MARKS FOR SYMBOLS" "CYRILLIC SUPPLEMENTARY"]) (mapcat block-alt-names) set)}) (def lispwords "Specially indented symbols in clojure.core and clojure.test. The following commit message (tag `lispwords-guidelines`) outlines a convention: commit c2920f43191ae48084cea2c641a42ca8d34381f5 Author: guns <self@sungpae.com> Date: Sat Jan 26 06:53:14 2013 -0600 Update lispwords Besides expanding the definitions into an easily maintainable style, we update the set of words for Clojure 1.5 using a simple rule: A function should only be indented specially if its first argument is special. This generally includes: * Definitions * Binding forms * Constructs that branch from a predicate What it does not include are functions/macros that accept a flat list of arguments (arglist: [& body]). Omissions include: clojure.core/dosync [& exprs] clojure.core/future [& body] clojure.core/gen-class [& options] clojure.core/gen-interface [& options] clojure.core/with-out-str [& body] Also added some symbols from clojure.test, since this namespace is present in many projects. Interestingly, clojure-mode.el includes \"assoc\" and \"struct-map\" in the special indent list, which makes a good deal of sense: (assoc my-map :foo \"foo\" :bar \"bar\") If we were to include this in lispwords, the following functions/macros should also be considered since they also take optional key value pairs at the end of the arglist: clojure.core/agent [state & options] clojure.core/assoc … [map key val & kvs] clojure.core/assoc! … [coll key val & kvs] clojure.core/atom … [x & options] clojure.core/ref [x] [x & options] clojure.core/refer [ns-sym & filters] clojure.core/restart-agent [a new-state & options] clojure.core/slurp [f & opts] clojure.core/sorted-map-by [comparator & keyvals] clojure.core/spit [f content & options] clojure.core/struct-map [s & inits]" (set/union ;; Definitions '#{bound-fn def definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol defrecord defstruct deftest deftest- deftype extend extend-protocol extend-type fn ns proxy reify set-test} ;; Binding forms '#{as-> binding doseq dotimes doto for if-let if-some let letfn locking loop testing when-first when-let when-some with-bindings with-in-str with-local-vars with-open with-precision with-redefs with-redefs-fn with-test} ;; Conditional branching '#{case cond-> cond->> condp if if-not when when-not while} ;; Exception handling '#{catch})) ;; ;; Vimscript literals ;; (def vim-keywords "Vimscript literal dictionary of important identifiers." (->> keyword-groups sort (map (fn [[group keywords]] (->> keywords map-keyword-names sort (map pr-str) (string/join \,) (format "'%s': [%s]" group)))) (string/join ",\n\t\\ ") (format "let s:clojure_syntax_keywords = {\n\t\\ %s\n\t\\ }\n"))) (def vim-completion-words "Vimscript literal list of words for omnifunc completion." (->> keyword-groups vals (reduce set/union) map-keyword-names sort (remove #(re-find #"^clojure\.core/" %)) (map pr-str) (string/join \,) (format "let s:words = [%s]\n"))) (def vim-posix-char-classes "Vimscript literal `syntax match` for POSIX character classes." ;; `IsPosix` works, but is undefined. (syntax-match-properties :clojureRegexpPosixCharClass "%s" (:posix character-properties))) (def vim-java-char-classes "Vimscript literal `syntax match` for \\p{javaMethod} property classes." ;; `IsjavaMethod` works, but is undefined. (syntax-match-properties :clojureRegexpJavaCharClass "java%s" (map #(string/replace % #"\Ajava" "") (:java character-properties)))) (def vim-unicode-binary-char-classes "Vimscript literal `syntax match` for Unicode Binary properties." ;; Though the docs do not mention it, the property name is matched case ;; insensitively like the other Unicode properties. (syntax-match-properties :clojureRegexpUnicodeCharClass "\\cIs%s" (map string/lower-case (:binary character-properties)))) (def vim-unicode-category-char-classes "Vimscript literal `syntax match` for Unicode General Category classes." (let [cats (sort (:category character-properties)) chrs (->> (map seq cats) (group-by first) (keys) (map str) (sort))] ;; gc= and general_category= can be case insensitive, but this is behavior ;; is undefined. (str (syntax-match-properties :clojureRegexpUnicodeCharClass "%s" chrs false) (syntax-match-properties :clojureRegexpUnicodeCharClass "%s" cats) (syntax-match-properties :clojureRegexpUnicodeCharClass "%%(Is|gc\\=|general_category\\=)?%s" cats)))) (def vim-unicode-script-char-classes "Vimscript literal `syntax match` for Unicode Script properties." ;; Script names are matched case insensitively, but Is, sc=, and script= ;; should be matched exactly. In this case, only Is is matched exactly, but ;; this is an acceptable trade-off. ;; ;; InScriptName works, but is undefined. (syntax-match-properties :clojureRegexpUnicodeCharClass "\\c%%(Is|sc\\=|script\\=)%s" (map string/lower-case (:script character-properties)))) (def vim-unicode-block-char-classes "Vimscript literal `syntax match` for Unicode Block properties." ;; Block names work like Script names, except the In prefix is used in place ;; of Is. (syntax-match-properties :clojureRegexpUnicodeCharClass "\\c%%(In|blk\\=|block\\=)%s" (map string/lower-case (:block character-properties)))) (def vim-lispwords "Vimscript literal `setlocal lispwords=` statement." (str "setlocal lispwords=" (string/join \, (sort lispwords)) "\n")) (defn- comprehensive-clojure-character-property-regexps "A string representing a Clojure literal vector of regular expressions containing all possible property character classes. For testing Vimscript syntax matching optimizations." [] (let [fmt (fn [prefix prop-key] (let [props (map (partial format "\\p{%s%s}" prefix) (sort (get character-properties prop-key)))] (format "#\"%s\"" (string/join props))))] (string/join \newline [(fmt "" :posix) (fmt "" :java) (fmt "Is" :binary) (fmt "general_category=" :category) (fmt "script=" :script) (fmt "block=" :block)]))) ;; ;; Update functions ;; (def ^:private CLOJURE-SECTION #"(?ms)^CLOJURE.*?(?=^[\p{Lu} ]+\t*\*)") (defn- fjoin [& args] (string/join \/ args)) (defn- qstr [& xs] (string/replace (string/join xs) "\\" "\\\\")) (defn- update-doc! [first-line-pattern src-file dst-file] (let [sbuf (with-open [rdr (io/reader src-file)] (->> rdr line-seq (drop-while #(not (re-find first-line-pattern %))) (string/join \newline))) dbuf (slurp dst-file) dmatch (re-find CLOJURE-SECTION dbuf) hunk (re-find CLOJURE-SECTION sbuf)] (spit dst-file (string/replace-first dbuf dmatch hunk)))) (defn- copy-runtime-files! [src dst & opts] (let [{:keys [tag date paths]} (apply hash-map opts)] (doseq [path paths :let [buf (-> (fjoin src path) slurp (string/replace "%%RELEASE_TAG%%" tag) (string/replace "%%RELEASE_DATE%%" date))]] (spit (fjoin dst "runtime" path) buf)))) (defn- project-replacements [dir] {(fjoin dir "syntax/clojure.vim") {"-*- KEYWORDS -*-" (qstr generation-comment clojure-version-comment vim-keywords) "-*- CHARACTER PROPERTY CLASSES -*-" (qstr generation-comment java-version-comment vim-posix-char-classes vim-java-char-classes vim-unicode-binary-char-classes vim-unicode-category-char-classes vim-unicode-script-char-classes vim-unicode-block-char-classes) "-*- TOP CLUSTER -*-" (qstr generation-comment (vim-top-cluster (keys keyword-groups) (slurp (fjoin dir "syntax/clojure.vim"))))} (fjoin dir "ftplugin/clojure.vim") {"-*- LISPWORDS -*-" (qstr generation-comment vim-lispwords)} (fjoin dir "autoload/clojurecomplete.vim") {"-*- COMPLETION WORDS -*-" (qstr generation-comment clojure-version-comment vim-completion-words)}}) (defn- update-project! "Update project runtime files in the given directory." [dir] (doseq [[file replacements] (project-replacements dir)] (doseq [[magic-comment replacement] replacements] (let [buf (slurp file) pat (re-pattern (str "(?s)\\Q" magic-comment "\\E\\n.*?\\n\\n")) rep (str magic-comment "\n" replacement "\n") buf' (string/replace buf pat rep)] (if (= buf buf') (printf "No changes: %s\n" magic-comment) (do (printf "Updating %s\n" magic-comment) (spit file buf'))))))) (defn- update-vim! "Update Vim repository runtime files in dst/runtime" [src dst] (let [current-tag (string/trim-newline (:out (sh "git" "rev-parse" "HEAD"))) current-date (.format (SimpleDateFormat. "YYYY-MM-dd") (Date.))] (assert (seq current-tag) "Git HEAD doesn't appear to have a commit hash.") (update-doc! #"CLOJURE\t*\*ft-clojure-indent\*" (fjoin src "doc/clojure.txt") (fjoin dst "runtime/doc/indent.txt")) (update-doc! #"CLOJURE\t*\*ft-clojure-syntax\*" (fjoin src "doc/clojure.txt") (fjoin dst "runtime/doc/syntax.txt")) (copy-runtime-files! src dst :tag current-tag :date current-date :paths ["autoload/clojurecomplete.vim" "ftplugin/clojure.vim" "indent/clojure.vim" "syntax/clojure.vim"]))) (comment ;; Run this to update the project files (update-project! "..") ;; Run this to update a vim repository (update-vim! ".." "../../vim") ;; Generate an example file with all possible character property literals. (spit "tmp/all-char-props.clj" (comprehensive-clojure-character-property-regexps)) (require 'vim-clojure-static.test) ;; Performance test: `syntax keyword` vs `syntax match` (vim-clojure-static.test/benchmark 1000 "tmp/bench.clj" (str keyword-groups) ;; `syntax keyword` (->> keyword-groups (map (fn [[group keywords]] (format "syntax keyword clojure%s %s\n" group (string/join \space (sort (map-keyword-names keywords)))))) (map string/trim-newline) (string/join " | ")) ;; Naive `syntax match` (->> keyword-groups (map (fn [[group keywords]] (format "syntax match clojure%s \"\\V\\<%s\\>\"\n" group (string/join "\\|" (map-keyword-names keywords))))) (map string/trim-newline) (string/join " | ")) ;; Frak-optimized `syntax match` (->> keyword-groups (map (fn [[group keywords]] (format "syntax match clojure%s \"\\v<%s>\"\n" group (vim-frak-pattern (map-keyword-names keywords))))) (map string/trim-newline) (string/join " | "))) )
115588
;; Authors: <NAME> <<EMAIL>> ;; <NAME> <<EMAIL>> (ns vim-clojure-static.generate (:require [clojure.java.io :as io] [clojure.java.shell :refer [sh]] [clojure.set :as set] [clojure.string :as string] [clojure.data.csv :as csv] [frak :as f]) (:import [clojure.lang MultiFn Compiler] java.text.SimpleDateFormat java.util.Date)) ;; ;; Helpers ;; (defn- vim-frak-pattern "Create a non-capturing regular expression pattern compatible with Vim." [strs] (-> (f/string-pattern strs {:escape-chars :vim}) (string/replace #"\(\?:" "\\%\\("))) (defn- property-pattern "Vimscript very magic pattern for a character property class." ([s] (property-pattern s true)) ([s braces?] (if braces? (format "\\v\\\\[pP]\\{%s\\}" s) (format "\\v\\\\[pP]%s" s)))) (defn- syntax-match-properties "Vimscript literal `syntax match` for a character property class." ([group fmt props] (syntax-match-properties group fmt props true)) ([group fmt props braces?] (format "syntax match %s \"%s\" contained display\n" (name group) (property-pattern (format fmt (vim-frak-pattern props)) braces?)))) (defn- map-keyword-names "Add non fully-qualified versions of the clojure.core functions and stringify everything." [coll] (let [stringified (into #{} (map #(if (nil? %) "nil" (str %))) coll) bare-symbols (into #{} (map #(string/replace-first % #"^clojure\.core/(?!import\*$)" "")) stringified)] (set/union stringified bare-symbols))) (defn- vim-top-cluster "Generate a Vimscript literal `syntax cluster` statement for `groups` and all top-level syntax groups in the given syntax buffer." [groups syntax-buf] (->> syntax-buf (re-seq #"syntax\s+(?:keyword|match|region)\s+(\S+)(?!.*\bcontained\b)") (map peek) (concat groups) sort distinct (string/join \,) (format "syntax cluster clojureTop contains=@Spell,%s\n"))) ;; ;; Definitions ;; (def generation-comment "\" Generated from https://github.com/clojure-vim/clojure.vim/blob/%%RELEASE_TAG%%/clj/src/vim_clojure_static/generate.clj\n") (def clojure-version-comment (format "\" Clojure version %s\n" (clojure-version))) (def java-version-comment (format "\" Java version %s\n" (System/getProperty "java.version"))) (defn vars-in-ns [ns] (->> ns ns-publics (map (fn [[_ var]] (assoc (meta var) :var var :fqs (symbol var)))))) (defn ->fqs [vars] (into #{} (map :fqs) vars)) (defn multi-fn? [v] (instance? MultiFn (var-get (:var v)))) (defn function? [v] (or (and (nil? (:macro v)) (contains? v :arglists)) (multi-fn? v))) (defn variable? [v] (nil? (or (:macro v) (:special-form v) (:arglists v) (:inline v)))) (defn define? [v] (re-find #"([^/]*/)?\Af?def(?!ault)" (str (if (map? v) (:name v) v)))) (def keyword-groups "Special forms, constants, and every public var in clojure.core keyed by syntax group name." (let [vars (vars-in-ns 'clojure.core) compiler-specials (set (keys Compiler/specials)) exceptions '#{throw try catch finally} repeat '#{recur loop* clojure.core/loop clojure.core/doseq clojure.core/dotimes clojure.core/while} conditionals '#{case* clojure.core/case if clojure.core/if-not clojure.core/if-let clojure.core/if-some clojure.core/cond clojure.core/cond-> clojure.core/cond->> clojure.core/condp clojure.core/when clojure.core/when-first clojure.core/when-let clojure.core/when-not clojure.core/when-some} define (set/union (->fqs (filter define? vars)) (set (filter define? compiler-specials))) macros (->fqs (filter :macro vars)) functions (->fqs (filter function? vars)) variables (->fqs (filter variable? vars)) special (set/union (->fqs (filter :special-form vars)) compiler-specials)] {"clojureBoolean" '#{true false} "clojureConstant" '#{nil} "clojureException" exceptions "clojureRepeat" repeat "clojureCond" conditionals "clojureDefine" define "clojureVariable" variables "clojureFunc" functions "clojureSpecial" (set/difference special define repeat conditionals exceptions) "clojureMacro" (set/difference macros define repeat conditionals special)})) ;; Java 8 Character class implements Unicode standard 6.2 from 2012 [1], ;; Java 15 implements Unicode standard 13 from 2020 [2], ;; the latter standard includes a few more scripts and removes some. ;; Unicode Technical Standard #18 [3] describes Unicode Regular Expressions. ;; java.util.regex.Pattern [4] describes which parts of Unicode standard are supported. ;; Some values which aren't mentioned in Unicode or Javadoc, are also supported [5]. ;; ;; [1] https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html ;; [2] https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/Character.html ;; [3] https://unicode.org/reports/tr18/ ;; [4] https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/regex/Pattern.html ;; [5] https://github.com/openjdk/jdk/blob/4d13bf33d4932cc210a29c4e3a68f848db18575b/src/java.base/share/classes/java/util/regex/CharPredicates.java (def unicode-property-value-aliases (with-open [f (io/reader (io/resource "unicode/PropertyValueAliases.txt"))] (->> (csv/read-csv f :separator \;) (map (fn [row] (mapv string/trim row))) doall))) (def unicode-blocks (with-open [f (io/reader (io/resource "unicode/Blocks.txt"))] (->> (csv/read-csv f :separator \;) (map (fn [row] (mapv string/trim row))) doall))) (defn- block-alt-names [block-name] (let [n (string/upper-case block-name)] [n (string/replace n #"[ -]" "_") (string/replace n #" " "")])) (def character-properties {:posix #{"Lower" "Space" "XDigit" "Alnum" "Cntrl" "Graph" "Alpha" "Print" "Blank" "Digit" "Upper" "Punct" "ASCII"} :java #{"javaSpaceChar" "javaUnicodeIdentifierPart" "javaLetterOrDigit" "javaTitleCase" "javaLowerCase" "javaDefined" "javaAlphabetic" "javaIdentifierIgnorable" "javaJavaIdentifierStart" "javaIdeographic" "javaWhitespace" "javaMirrored" "javaUnicodeIdentifierStart" "javaISOControl" "javaUpperCase" "javaDigit" "javaLetter" "javaJavaIdentifierPart"} :binary #{"IDEOGRAPHIC" "HEX_DIGIT" "ALPHABETIC" "NONCHARACTERCODEPOINT" "GRAPH" "PUNCTUATION" "WORD" "LETTER" "TITLECASE" "JOIN_CONTROL" "CONTROL" "HEXDIGIT" "LOWERCASE" "NONCHARACTER_CODE_POINT" "JOINCONTROL" "BLANK" "WHITESPACE" "ALNUM" "DIGIT" "WHITE_SPACE" "ASSIGNED" "UPPERCASE" "PRINT"} ;; https://www.unicode.org/reports/tr44/#General_Category_Values :category (->> unicode-property-value-aliases (filter #(= "gc" (first %))) (map second) ;; Supported by Java but not in standard or docs. (concat ["LD"]) set) :script (->> unicode-property-value-aliases (filter #(= "sc" (first %))) (mapcat #(subvec % 1 3)) (map string/upper-case) set) :block (->> unicode-blocks (filter (fn [row] (and (seq (first row)) (not (string/starts-with? (first row) "#"))))) (map second) ;; Old names supported by Java (concat ["GREEK" "COMBINING MARKS FOR SYMBOLS" "CYRILLIC SUPPLEMENTARY"]) (mapcat block-alt-names) set)}) (def lispwords "Specially indented symbols in clojure.core and clojure.test. The following commit message (tag `lispwords-guidelines`) outlines a convention: commit c2920f43191ae48084cea2c641a42ca8d34381f5 Author: guns <<EMAIL>> Date: Sat Jan 26 06:53:14 2013 -0600 Update lispwords Besides expanding the definitions into an easily maintainable style, we update the set of words for Clojure 1.5 using a simple rule: A function should only be indented specially if its first argument is special. This generally includes: * Definitions * Binding forms * Constructs that branch from a predicate What it does not include are functions/macros that accept a flat list of arguments (arglist: [& body]). Omissions include: clojure.core/dosync [& exprs] clojure.core/future [& body] clojure.core/gen-class [& options] clojure.core/gen-interface [& options] clojure.core/with-out-str [& body] Also added some symbols from clojure.test, since this namespace is present in many projects. Interestingly, clojure-mode.el includes \"assoc\" and \"struct-map\" in the special indent list, which makes a good deal of sense: (assoc my-map :foo \"foo\" :bar \"bar\") If we were to include this in lispwords, the following functions/macros should also be considered since they also take optional key value pairs at the end of the arglist: clojure.core/agent [state & options] clojure.core/assoc … [map key val & kvs] clojure.core/assoc! … [coll key val & kvs] clojure.core/atom … [x & options] clojure.core/ref [x] [x & options] clojure.core/refer [ns-sym & filters] clojure.core/restart-agent [a new-state & options] clojure.core/slurp [f & opts] clojure.core/sorted-map-by [comparator & keyvals] clojure.core/spit [f content & options] clojure.core/struct-map [s & inits]" (set/union ;; Definitions '#{bound-fn def definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol defrecord defstruct deftest deftest- deftype extend extend-protocol extend-type fn ns proxy reify set-test} ;; Binding forms '#{as-> binding doseq dotimes doto for if-let if-some let letfn locking loop testing when-first when-let when-some with-bindings with-in-str with-local-vars with-open with-precision with-redefs with-redefs-fn with-test} ;; Conditional branching '#{case cond-> cond->> condp if if-not when when-not while} ;; Exception handling '#{catch})) ;; ;; Vimscript literals ;; (def vim-keywords "Vimscript literal dictionary of important identifiers." (->> keyword-groups sort (map (fn [[group keywords]] (->> keywords map-keyword-names sort (map pr-str) (string/join \,) (format "'%s': [%s]" group)))) (string/join ",\n\t\\ ") (format "let s:clojure_syntax_keywords = {\n\t\\ %s\n\t\\ }\n"))) (def vim-completion-words "Vimscript literal list of words for omnifunc completion." (->> keyword-groups vals (reduce set/union) map-keyword-names sort (remove #(re-find #"^clojure\.core/" %)) (map pr-str) (string/join \,) (format "let s:words = [%s]\n"))) (def vim-posix-char-classes "Vimscript literal `syntax match` for POSIX character classes." ;; `IsPosix` works, but is undefined. (syntax-match-properties :clojureRegexpPosixCharClass "%s" (:posix character-properties))) (def vim-java-char-classes "Vimscript literal `syntax match` for \\p{javaMethod} property classes." ;; `IsjavaMethod` works, but is undefined. (syntax-match-properties :clojureRegexpJavaCharClass "java%s" (map #(string/replace % #"\Ajava" "") (:java character-properties)))) (def vim-unicode-binary-char-classes "Vimscript literal `syntax match` for Unicode Binary properties." ;; Though the docs do not mention it, the property name is matched case ;; insensitively like the other Unicode properties. (syntax-match-properties :clojureRegexpUnicodeCharClass "\\cIs%s" (map string/lower-case (:binary character-properties)))) (def vim-unicode-category-char-classes "Vimscript literal `syntax match` for Unicode General Category classes." (let [cats (sort (:category character-properties)) chrs (->> (map seq cats) (group-by first) (keys) (map str) (sort))] ;; gc= and general_category= can be case insensitive, but this is behavior ;; is undefined. (str (syntax-match-properties :clojureRegexpUnicodeCharClass "%s" chrs false) (syntax-match-properties :clojureRegexpUnicodeCharClass "%s" cats) (syntax-match-properties :clojureRegexpUnicodeCharClass "%%(Is|gc\\=|general_category\\=)?%s" cats)))) (def vim-unicode-script-char-classes "Vimscript literal `syntax match` for Unicode Script properties." ;; Script names are matched case insensitively, but Is, sc=, and script= ;; should be matched exactly. In this case, only Is is matched exactly, but ;; this is an acceptable trade-off. ;; ;; InScriptName works, but is undefined. (syntax-match-properties :clojureRegexpUnicodeCharClass "\\c%%(Is|sc\\=|script\\=)%s" (map string/lower-case (:script character-properties)))) (def vim-unicode-block-char-classes "Vimscript literal `syntax match` for Unicode Block properties." ;; Block names work like Script names, except the In prefix is used in place ;; of Is. (syntax-match-properties :clojureRegexpUnicodeCharClass "\\c%%(In|blk\\=|block\\=)%s" (map string/lower-case (:block character-properties)))) (def vim-lispwords "Vimscript literal `setlocal lispwords=` statement." (str "setlocal lispwords=" (string/join \, (sort lispwords)) "\n")) (defn- comprehensive-clojure-character-property-regexps "A string representing a Clojure literal vector of regular expressions containing all possible property character classes. For testing Vimscript syntax matching optimizations." [] (let [fmt (fn [prefix prop-key] (let [props (map (partial format "\\p{%s%s}" prefix) (sort (get character-properties prop-key)))] (format "#\"%s\"" (string/join props))))] (string/join \newline [(fmt "" :posix) (fmt "" :java) (fmt "Is" :binary) (fmt "general_category=" :category) (fmt "script=" :script) (fmt "block=" :block)]))) ;; ;; Update functions ;; (def ^:private CLOJURE-SECTION #"(?ms)^CLOJURE.*?(?=^[\p{Lu} ]+\t*\*)") (defn- fjoin [& args] (string/join \/ args)) (defn- qstr [& xs] (string/replace (string/join xs) "\\" "\\\\")) (defn- update-doc! [first-line-pattern src-file dst-file] (let [sbuf (with-open [rdr (io/reader src-file)] (->> rdr line-seq (drop-while #(not (re-find first-line-pattern %))) (string/join \newline))) dbuf (slurp dst-file) dmatch (re-find CLOJURE-SECTION dbuf) hunk (re-find CLOJURE-SECTION sbuf)] (spit dst-file (string/replace-first dbuf dmatch hunk)))) (defn- copy-runtime-files! [src dst & opts] (let [{:keys [tag date paths]} (apply hash-map opts)] (doseq [path paths :let [buf (-> (fjoin src path) slurp (string/replace "%%RELEASE_TAG%%" tag) (string/replace "%%RELEASE_DATE%%" date))]] (spit (fjoin dst "runtime" path) buf)))) (defn- project-replacements [dir] {(fjoin dir "syntax/clojure.vim") {"-*- KEYWORDS -*-" (qstr generation-comment clojure-version-comment vim-keywords) "-*- CHARACTER PROPERTY CLASSES -*-" (qstr generation-comment java-version-comment vim-posix-char-classes vim-java-char-classes vim-unicode-binary-char-classes vim-unicode-category-char-classes vim-unicode-script-char-classes vim-unicode-block-char-classes) "-*- TOP CLUSTER -*-" (qstr generation-comment (vim-top-cluster (keys keyword-groups) (slurp (fjoin dir "syntax/clojure.vim"))))} (fjoin dir "ftplugin/clojure.vim") {"-*- LISPWORDS -*-" (qstr generation-comment vim-lispwords)} (fjoin dir "autoload/clojurecomplete.vim") {"-*- COMPLETION WORDS -*-" (qstr generation-comment clojure-version-comment vim-completion-words)}}) (defn- update-project! "Update project runtime files in the given directory." [dir] (doseq [[file replacements] (project-replacements dir)] (doseq [[magic-comment replacement] replacements] (let [buf (slurp file) pat (re-pattern (str "(?s)\\Q" magic-comment "\\E\\n.*?\\n\\n")) rep (str magic-comment "\n" replacement "\n") buf' (string/replace buf pat rep)] (if (= buf buf') (printf "No changes: %s\n" magic-comment) (do (printf "Updating %s\n" magic-comment) (spit file buf'))))))) (defn- update-vim! "Update Vim repository runtime files in dst/runtime" [src dst] (let [current-tag (string/trim-newline (:out (sh "git" "rev-parse" "HEAD"))) current-date (.format (SimpleDateFormat. "YYYY-MM-dd") (Date.))] (assert (seq current-tag) "Git HEAD doesn't appear to have a commit hash.") (update-doc! #"CLOJURE\t*\*ft-clojure-indent\*" (fjoin src "doc/clojure.txt") (fjoin dst "runtime/doc/indent.txt")) (update-doc! #"CLOJURE\t*\*ft-clojure-syntax\*" (fjoin src "doc/clojure.txt") (fjoin dst "runtime/doc/syntax.txt")) (copy-runtime-files! src dst :tag current-tag :date current-date :paths ["autoload/clojurecomplete.vim" "ftplugin/clojure.vim" "indent/clojure.vim" "syntax/clojure.vim"]))) (comment ;; Run this to update the project files (update-project! "..") ;; Run this to update a vim repository (update-vim! ".." "../../vim") ;; Generate an example file with all possible character property literals. (spit "tmp/all-char-props.clj" (comprehensive-clojure-character-property-regexps)) (require 'vim-clojure-static.test) ;; Performance test: `syntax keyword` vs `syntax match` (vim-clojure-static.test/benchmark 1000 "tmp/bench.clj" (str keyword-groups) ;; `syntax keyword` (->> keyword-groups (map (fn [[group keywords]] (format "syntax keyword clojure%s %s\n" group (string/join \space (sort (map-keyword-names keywords)))))) (map string/trim-newline) (string/join " | ")) ;; Naive `syntax match` (->> keyword-groups (map (fn [[group keywords]] (format "syntax match clojure%s \"\\V\\<%s\\>\"\n" group (string/join "\\|" (map-keyword-names keywords))))) (map string/trim-newline) (string/join " | ")) ;; Frak-optimized `syntax match` (->> keyword-groups (map (fn [[group keywords]] (format "syntax match clojure%s \"\\v<%s>\"\n" group (vim-frak-pattern (map-keyword-names keywords))))) (map string/trim-newline) (string/join " | "))) )
true
;; Authors: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (ns vim-clojure-static.generate (:require [clojure.java.io :as io] [clojure.java.shell :refer [sh]] [clojure.set :as set] [clojure.string :as string] [clojure.data.csv :as csv] [frak :as f]) (:import [clojure.lang MultiFn Compiler] java.text.SimpleDateFormat java.util.Date)) ;; ;; Helpers ;; (defn- vim-frak-pattern "Create a non-capturing regular expression pattern compatible with Vim." [strs] (-> (f/string-pattern strs {:escape-chars :vim}) (string/replace #"\(\?:" "\\%\\("))) (defn- property-pattern "Vimscript very magic pattern for a character property class." ([s] (property-pattern s true)) ([s braces?] (if braces? (format "\\v\\\\[pP]\\{%s\\}" s) (format "\\v\\\\[pP]%s" s)))) (defn- syntax-match-properties "Vimscript literal `syntax match` for a character property class." ([group fmt props] (syntax-match-properties group fmt props true)) ([group fmt props braces?] (format "syntax match %s \"%s\" contained display\n" (name group) (property-pattern (format fmt (vim-frak-pattern props)) braces?)))) (defn- map-keyword-names "Add non fully-qualified versions of the clojure.core functions and stringify everything." [coll] (let [stringified (into #{} (map #(if (nil? %) "nil" (str %))) coll) bare-symbols (into #{} (map #(string/replace-first % #"^clojure\.core/(?!import\*$)" "")) stringified)] (set/union stringified bare-symbols))) (defn- vim-top-cluster "Generate a Vimscript literal `syntax cluster` statement for `groups` and all top-level syntax groups in the given syntax buffer." [groups syntax-buf] (->> syntax-buf (re-seq #"syntax\s+(?:keyword|match|region)\s+(\S+)(?!.*\bcontained\b)") (map peek) (concat groups) sort distinct (string/join \,) (format "syntax cluster clojureTop contains=@Spell,%s\n"))) ;; ;; Definitions ;; (def generation-comment "\" Generated from https://github.com/clojure-vim/clojure.vim/blob/%%RELEASE_TAG%%/clj/src/vim_clojure_static/generate.clj\n") (def clojure-version-comment (format "\" Clojure version %s\n" (clojure-version))) (def java-version-comment (format "\" Java version %s\n" (System/getProperty "java.version"))) (defn vars-in-ns [ns] (->> ns ns-publics (map (fn [[_ var]] (assoc (meta var) :var var :fqs (symbol var)))))) (defn ->fqs [vars] (into #{} (map :fqs) vars)) (defn multi-fn? [v] (instance? MultiFn (var-get (:var v)))) (defn function? [v] (or (and (nil? (:macro v)) (contains? v :arglists)) (multi-fn? v))) (defn variable? [v] (nil? (or (:macro v) (:special-form v) (:arglists v) (:inline v)))) (defn define? [v] (re-find #"([^/]*/)?\Af?def(?!ault)" (str (if (map? v) (:name v) v)))) (def keyword-groups "Special forms, constants, and every public var in clojure.core keyed by syntax group name." (let [vars (vars-in-ns 'clojure.core) compiler-specials (set (keys Compiler/specials)) exceptions '#{throw try catch finally} repeat '#{recur loop* clojure.core/loop clojure.core/doseq clojure.core/dotimes clojure.core/while} conditionals '#{case* clojure.core/case if clojure.core/if-not clojure.core/if-let clojure.core/if-some clojure.core/cond clojure.core/cond-> clojure.core/cond->> clojure.core/condp clojure.core/when clojure.core/when-first clojure.core/when-let clojure.core/when-not clojure.core/when-some} define (set/union (->fqs (filter define? vars)) (set (filter define? compiler-specials))) macros (->fqs (filter :macro vars)) functions (->fqs (filter function? vars)) variables (->fqs (filter variable? vars)) special (set/union (->fqs (filter :special-form vars)) compiler-specials)] {"clojureBoolean" '#{true false} "clojureConstant" '#{nil} "clojureException" exceptions "clojureRepeat" repeat "clojureCond" conditionals "clojureDefine" define "clojureVariable" variables "clojureFunc" functions "clojureSpecial" (set/difference special define repeat conditionals exceptions) "clojureMacro" (set/difference macros define repeat conditionals special)})) ;; Java 8 Character class implements Unicode standard 6.2 from 2012 [1], ;; Java 15 implements Unicode standard 13 from 2020 [2], ;; the latter standard includes a few more scripts and removes some. ;; Unicode Technical Standard #18 [3] describes Unicode Regular Expressions. ;; java.util.regex.Pattern [4] describes which parts of Unicode standard are supported. ;; Some values which aren't mentioned in Unicode or Javadoc, are also supported [5]. ;; ;; [1] https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html ;; [2] https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/Character.html ;; [3] https://unicode.org/reports/tr18/ ;; [4] https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/regex/Pattern.html ;; [5] https://github.com/openjdk/jdk/blob/4d13bf33d4932cc210a29c4e3a68f848db18575b/src/java.base/share/classes/java/util/regex/CharPredicates.java (def unicode-property-value-aliases (with-open [f (io/reader (io/resource "unicode/PropertyValueAliases.txt"))] (->> (csv/read-csv f :separator \;) (map (fn [row] (mapv string/trim row))) doall))) (def unicode-blocks (with-open [f (io/reader (io/resource "unicode/Blocks.txt"))] (->> (csv/read-csv f :separator \;) (map (fn [row] (mapv string/trim row))) doall))) (defn- block-alt-names [block-name] (let [n (string/upper-case block-name)] [n (string/replace n #"[ -]" "_") (string/replace n #" " "")])) (def character-properties {:posix #{"Lower" "Space" "XDigit" "Alnum" "Cntrl" "Graph" "Alpha" "Print" "Blank" "Digit" "Upper" "Punct" "ASCII"} :java #{"javaSpaceChar" "javaUnicodeIdentifierPart" "javaLetterOrDigit" "javaTitleCase" "javaLowerCase" "javaDefined" "javaAlphabetic" "javaIdentifierIgnorable" "javaJavaIdentifierStart" "javaIdeographic" "javaWhitespace" "javaMirrored" "javaUnicodeIdentifierStart" "javaISOControl" "javaUpperCase" "javaDigit" "javaLetter" "javaJavaIdentifierPart"} :binary #{"IDEOGRAPHIC" "HEX_DIGIT" "ALPHABETIC" "NONCHARACTERCODEPOINT" "GRAPH" "PUNCTUATION" "WORD" "LETTER" "TITLECASE" "JOIN_CONTROL" "CONTROL" "HEXDIGIT" "LOWERCASE" "NONCHARACTER_CODE_POINT" "JOINCONTROL" "BLANK" "WHITESPACE" "ALNUM" "DIGIT" "WHITE_SPACE" "ASSIGNED" "UPPERCASE" "PRINT"} ;; https://www.unicode.org/reports/tr44/#General_Category_Values :category (->> unicode-property-value-aliases (filter #(= "gc" (first %))) (map second) ;; Supported by Java but not in standard or docs. (concat ["LD"]) set) :script (->> unicode-property-value-aliases (filter #(= "sc" (first %))) (mapcat #(subvec % 1 3)) (map string/upper-case) set) :block (->> unicode-blocks (filter (fn [row] (and (seq (first row)) (not (string/starts-with? (first row) "#"))))) (map second) ;; Old names supported by Java (concat ["GREEK" "COMBINING MARKS FOR SYMBOLS" "CYRILLIC SUPPLEMENTARY"]) (mapcat block-alt-names) set)}) (def lispwords "Specially indented symbols in clojure.core and clojure.test. The following commit message (tag `lispwords-guidelines`) outlines a convention: commit c2920f43191ae48084cea2c641a42ca8d34381f5 Author: guns <PI:EMAIL:<EMAIL>END_PI> Date: Sat Jan 26 06:53:14 2013 -0600 Update lispwords Besides expanding the definitions into an easily maintainable style, we update the set of words for Clojure 1.5 using a simple rule: A function should only be indented specially if its first argument is special. This generally includes: * Definitions * Binding forms * Constructs that branch from a predicate What it does not include are functions/macros that accept a flat list of arguments (arglist: [& body]). Omissions include: clojure.core/dosync [& exprs] clojure.core/future [& body] clojure.core/gen-class [& options] clojure.core/gen-interface [& options] clojure.core/with-out-str [& body] Also added some symbols from clojure.test, since this namespace is present in many projects. Interestingly, clojure-mode.el includes \"assoc\" and \"struct-map\" in the special indent list, which makes a good deal of sense: (assoc my-map :foo \"foo\" :bar \"bar\") If we were to include this in lispwords, the following functions/macros should also be considered since they also take optional key value pairs at the end of the arglist: clojure.core/agent [state & options] clojure.core/assoc … [map key val & kvs] clojure.core/assoc! … [coll key val & kvs] clojure.core/atom … [x & options] clojure.core/ref [x] [x & options] clojure.core/refer [ns-sym & filters] clojure.core/restart-agent [a new-state & options] clojure.core/slurp [f & opts] clojure.core/sorted-map-by [comparator & keyvals] clojure.core/spit [f content & options] clojure.core/struct-map [s & inits]" (set/union ;; Definitions '#{bound-fn def definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol defrecord defstruct deftest deftest- deftype extend extend-protocol extend-type fn ns proxy reify set-test} ;; Binding forms '#{as-> binding doseq dotimes doto for if-let if-some let letfn locking loop testing when-first when-let when-some with-bindings with-in-str with-local-vars with-open with-precision with-redefs with-redefs-fn with-test} ;; Conditional branching '#{case cond-> cond->> condp if if-not when when-not while} ;; Exception handling '#{catch})) ;; ;; Vimscript literals ;; (def vim-keywords "Vimscript literal dictionary of important identifiers." (->> keyword-groups sort (map (fn [[group keywords]] (->> keywords map-keyword-names sort (map pr-str) (string/join \,) (format "'%s': [%s]" group)))) (string/join ",\n\t\\ ") (format "let s:clojure_syntax_keywords = {\n\t\\ %s\n\t\\ }\n"))) (def vim-completion-words "Vimscript literal list of words for omnifunc completion." (->> keyword-groups vals (reduce set/union) map-keyword-names sort (remove #(re-find #"^clojure\.core/" %)) (map pr-str) (string/join \,) (format "let s:words = [%s]\n"))) (def vim-posix-char-classes "Vimscript literal `syntax match` for POSIX character classes." ;; `IsPosix` works, but is undefined. (syntax-match-properties :clojureRegexpPosixCharClass "%s" (:posix character-properties))) (def vim-java-char-classes "Vimscript literal `syntax match` for \\p{javaMethod} property classes." ;; `IsjavaMethod` works, but is undefined. (syntax-match-properties :clojureRegexpJavaCharClass "java%s" (map #(string/replace % #"\Ajava" "") (:java character-properties)))) (def vim-unicode-binary-char-classes "Vimscript literal `syntax match` for Unicode Binary properties." ;; Though the docs do not mention it, the property name is matched case ;; insensitively like the other Unicode properties. (syntax-match-properties :clojureRegexpUnicodeCharClass "\\cIs%s" (map string/lower-case (:binary character-properties)))) (def vim-unicode-category-char-classes "Vimscript literal `syntax match` for Unicode General Category classes." (let [cats (sort (:category character-properties)) chrs (->> (map seq cats) (group-by first) (keys) (map str) (sort))] ;; gc= and general_category= can be case insensitive, but this is behavior ;; is undefined. (str (syntax-match-properties :clojureRegexpUnicodeCharClass "%s" chrs false) (syntax-match-properties :clojureRegexpUnicodeCharClass "%s" cats) (syntax-match-properties :clojureRegexpUnicodeCharClass "%%(Is|gc\\=|general_category\\=)?%s" cats)))) (def vim-unicode-script-char-classes "Vimscript literal `syntax match` for Unicode Script properties." ;; Script names are matched case insensitively, but Is, sc=, and script= ;; should be matched exactly. In this case, only Is is matched exactly, but ;; this is an acceptable trade-off. ;; ;; InScriptName works, but is undefined. (syntax-match-properties :clojureRegexpUnicodeCharClass "\\c%%(Is|sc\\=|script\\=)%s" (map string/lower-case (:script character-properties)))) (def vim-unicode-block-char-classes "Vimscript literal `syntax match` for Unicode Block properties." ;; Block names work like Script names, except the In prefix is used in place ;; of Is. (syntax-match-properties :clojureRegexpUnicodeCharClass "\\c%%(In|blk\\=|block\\=)%s" (map string/lower-case (:block character-properties)))) (def vim-lispwords "Vimscript literal `setlocal lispwords=` statement." (str "setlocal lispwords=" (string/join \, (sort lispwords)) "\n")) (defn- comprehensive-clojure-character-property-regexps "A string representing a Clojure literal vector of regular expressions containing all possible property character classes. For testing Vimscript syntax matching optimizations." [] (let [fmt (fn [prefix prop-key] (let [props (map (partial format "\\p{%s%s}" prefix) (sort (get character-properties prop-key)))] (format "#\"%s\"" (string/join props))))] (string/join \newline [(fmt "" :posix) (fmt "" :java) (fmt "Is" :binary) (fmt "general_category=" :category) (fmt "script=" :script) (fmt "block=" :block)]))) ;; ;; Update functions ;; (def ^:private CLOJURE-SECTION #"(?ms)^CLOJURE.*?(?=^[\p{Lu} ]+\t*\*)") (defn- fjoin [& args] (string/join \/ args)) (defn- qstr [& xs] (string/replace (string/join xs) "\\" "\\\\")) (defn- update-doc! [first-line-pattern src-file dst-file] (let [sbuf (with-open [rdr (io/reader src-file)] (->> rdr line-seq (drop-while #(not (re-find first-line-pattern %))) (string/join \newline))) dbuf (slurp dst-file) dmatch (re-find CLOJURE-SECTION dbuf) hunk (re-find CLOJURE-SECTION sbuf)] (spit dst-file (string/replace-first dbuf dmatch hunk)))) (defn- copy-runtime-files! [src dst & opts] (let [{:keys [tag date paths]} (apply hash-map opts)] (doseq [path paths :let [buf (-> (fjoin src path) slurp (string/replace "%%RELEASE_TAG%%" tag) (string/replace "%%RELEASE_DATE%%" date))]] (spit (fjoin dst "runtime" path) buf)))) (defn- project-replacements [dir] {(fjoin dir "syntax/clojure.vim") {"-*- KEYWORDS -*-" (qstr generation-comment clojure-version-comment vim-keywords) "-*- CHARACTER PROPERTY CLASSES -*-" (qstr generation-comment java-version-comment vim-posix-char-classes vim-java-char-classes vim-unicode-binary-char-classes vim-unicode-category-char-classes vim-unicode-script-char-classes vim-unicode-block-char-classes) "-*- TOP CLUSTER -*-" (qstr generation-comment (vim-top-cluster (keys keyword-groups) (slurp (fjoin dir "syntax/clojure.vim"))))} (fjoin dir "ftplugin/clojure.vim") {"-*- LISPWORDS -*-" (qstr generation-comment vim-lispwords)} (fjoin dir "autoload/clojurecomplete.vim") {"-*- COMPLETION WORDS -*-" (qstr generation-comment clojure-version-comment vim-completion-words)}}) (defn- update-project! "Update project runtime files in the given directory." [dir] (doseq [[file replacements] (project-replacements dir)] (doseq [[magic-comment replacement] replacements] (let [buf (slurp file) pat (re-pattern (str "(?s)\\Q" magic-comment "\\E\\n.*?\\n\\n")) rep (str magic-comment "\n" replacement "\n") buf' (string/replace buf pat rep)] (if (= buf buf') (printf "No changes: %s\n" magic-comment) (do (printf "Updating %s\n" magic-comment) (spit file buf'))))))) (defn- update-vim! "Update Vim repository runtime files in dst/runtime" [src dst] (let [current-tag (string/trim-newline (:out (sh "git" "rev-parse" "HEAD"))) current-date (.format (SimpleDateFormat. "YYYY-MM-dd") (Date.))] (assert (seq current-tag) "Git HEAD doesn't appear to have a commit hash.") (update-doc! #"CLOJURE\t*\*ft-clojure-indent\*" (fjoin src "doc/clojure.txt") (fjoin dst "runtime/doc/indent.txt")) (update-doc! #"CLOJURE\t*\*ft-clojure-syntax\*" (fjoin src "doc/clojure.txt") (fjoin dst "runtime/doc/syntax.txt")) (copy-runtime-files! src dst :tag current-tag :date current-date :paths ["autoload/clojurecomplete.vim" "ftplugin/clojure.vim" "indent/clojure.vim" "syntax/clojure.vim"]))) (comment ;; Run this to update the project files (update-project! "..") ;; Run this to update a vim repository (update-vim! ".." "../../vim") ;; Generate an example file with all possible character property literals. (spit "tmp/all-char-props.clj" (comprehensive-clojure-character-property-regexps)) (require 'vim-clojure-static.test) ;; Performance test: `syntax keyword` vs `syntax match` (vim-clojure-static.test/benchmark 1000 "tmp/bench.clj" (str keyword-groups) ;; `syntax keyword` (->> keyword-groups (map (fn [[group keywords]] (format "syntax keyword clojure%s %s\n" group (string/join \space (sort (map-keyword-names keywords)))))) (map string/trim-newline) (string/join " | ")) ;; Naive `syntax match` (->> keyword-groups (map (fn [[group keywords]] (format "syntax match clojure%s \"\\V\\<%s\\>\"\n" group (string/join "\\|" (map-keyword-names keywords))))) (map string/trim-newline) (string/join " | ")) ;; Frak-optimized `syntax match` (->> keyword-groups (map (fn [[group keywords]] (format "syntax match clojure%s \"\\v<%s>\"\n" group (vim-frak-pattern (map-keyword-names keywords))))) (map string/trim-newline) (string/join " | "))) )
[ { "context": "\n :body (generate-string {:username username\n :password", "end": 479, "score": 0.9832232594490051, "start": 471, "tag": "USERNAME", "value": "username" }, { "context": "\n :password password})})\n [:headers\n :set-cookie]))\n\n(defn get\n ", "end": 538, "score": 0.9899634718894958, "start": 530, "tag": "PASSWORD", "value": "password" } ]
src/obelisk_log/api.clj
Akeboshiwind/obelisk-log
0
(ns obelisk-log.api (:require [org.httpkit.client :as http] [cheshire.core :refer [generate-string parse-string]])) (defn make-address [server-address endpoint] (str server-address "/api" endpoint)) (defn login [username password {:keys [server-address basic-auth]}] (get-in @(http/post (make-address server-address "/login") {:basic-auth basic-auth :body (generate-string {:username username :password password})}) [:headers :set-cookie])) (defn get [endpoint {:keys [server-address basic-auth cookie]}] (let [response @(http/get (make-address server-address endpoint) {:basic-auth basic-auth :keep-alive 3000 :headers {"Cookie" cookie}})] (if (not= (:status response) 200) :failed ;; Don't like, what would be a better solution? (-> response :body (parse-string true))))) (defn curr-user [opts] (get "/currUser" opts)) (defn versions [opts] (get "/inventory/versions" opts)) (defn dashboard [opts] (get "/status/dashboard" opts))
25745
(ns obelisk-log.api (:require [org.httpkit.client :as http] [cheshire.core :refer [generate-string parse-string]])) (defn make-address [server-address endpoint] (str server-address "/api" endpoint)) (defn login [username password {:keys [server-address basic-auth]}] (get-in @(http/post (make-address server-address "/login") {:basic-auth basic-auth :body (generate-string {:username username :password <PASSWORD>})}) [:headers :set-cookie])) (defn get [endpoint {:keys [server-address basic-auth cookie]}] (let [response @(http/get (make-address server-address endpoint) {:basic-auth basic-auth :keep-alive 3000 :headers {"Cookie" cookie}})] (if (not= (:status response) 200) :failed ;; Don't like, what would be a better solution? (-> response :body (parse-string true))))) (defn curr-user [opts] (get "/currUser" opts)) (defn versions [opts] (get "/inventory/versions" opts)) (defn dashboard [opts] (get "/status/dashboard" opts))
true
(ns obelisk-log.api (:require [org.httpkit.client :as http] [cheshire.core :refer [generate-string parse-string]])) (defn make-address [server-address endpoint] (str server-address "/api" endpoint)) (defn login [username password {:keys [server-address basic-auth]}] (get-in @(http/post (make-address server-address "/login") {:basic-auth basic-auth :body (generate-string {:username username :password PI:PASSWORD:<PASSWORD>END_PI})}) [:headers :set-cookie])) (defn get [endpoint {:keys [server-address basic-auth cookie]}] (let [response @(http/get (make-address server-address endpoint) {:basic-auth basic-auth :keep-alive 3000 :headers {"Cookie" cookie}})] (if (not= (:status response) 200) :failed ;; Don't like, what would be a better solution? (-> response :body (parse-string true))))) (defn curr-user [opts] (get "/currUser" opts)) (defn versions [opts] (get "/inventory/versions" opts)) (defn dashboard [opts] (get "/status/dashboard" opts))
[ { "context": "(member.name = ? and member.email = ?)\\nlimit 1\" \"test\" \"test@test.com\"]\n (q/sql-vec '[:select", "end": 2196, "score": 0.9990255832672119, "start": 2192, "tag": "USERNAME", "value": "test" }, { "context": ".name = ? and member.email = ?)\\nlimit 1\" \"test\" \"test@test.com\"]\n (q/sql-vec '[:select member/name mem", "end": 2212, "score": 0.9999071359634399, "start": 2199, "tag": "EMAIL", "value": "test@test.com" }, { "context": "mail\n :where [member/name \"test\"]\n [member/email \"t", "end": 2321, "score": 0.987022340297699, "start": 2317, "tag": "USERNAME", "value": "test" }, { "context": "t\"]\n [member/email \"test@test.com\"]\n :limit 1]))))\n\n (testi", "end": 2383, "score": 0.9998983144760132, "start": 2370, "tag": "EMAIL", "value": "test@test.com" }, { "context": "\n [member/email \"test@test.com\"]\n and [member/name", "end": 2644, "score": 0.9998635053634644, "start": 2631, "tag": "EMAIL", "value": "test@test.com" }, { "context": "r.name is not null and member.id != ?)\\nlimit 1\" \"test\" \"test@test.com\" 1])))\n\n (testing \"a sql-vec tha", "end": 2989, "score": 0.9979665279388428, "start": 2985, "tag": "USERNAME", "value": "test" }, { "context": "is not null and member.id != ?)\\nlimit 1\" \"test\" \"test@test.com\" 1])))\n\n (testing \"a sql-vec that tries out most", "end": 3005, "score": 0.9998825192451477, "start": 2992, "tag": "EMAIL", "value": "test@test.com" } ]
test/coast/db/query_test.clj
Biserkov/coast
0
(ns coast.db.query-test (:require [coast.db.query :as q] [coast.db.schema] [clojure.test :refer [deftest testing is]])) (deftest vec->map (testing "vec->map turns query vec into map" (is (= '{:select [todo/name]} (q/vec->map '[:select todo/name]))) (is (= '{:select [todo/name todo/id]} (q/vec->map '[:select todo/name todo/id]))) (is (= '{:where [member/active true] :group [member/name] :limit [10] :offset [0] :joins [member/todos] :order [todo/id desc] :select [todo/id todo/name]}) (q/vec->map '[:select todo/id todo/name :joins member/todos :where [member/active true] :order todo/id desc :limit 10 :offset 0 :group member/name])))) (deftest where-test (testing "where with and, not" (is (= (q/where '[and [member/name != ""] [member/id 1]]) {:where "where (member.name != ? and member.id = ?)" :args '("" 1)}))) (testing "where not and implicit and" (is (= (q/where '[[member/name != ""] [member/id ""]]) {:where "where (member.name != ? and member.id = ?)" :args '("" "")}))) (testing "where or" (is (= (q/where '[or [member/name ""] [member/id 1] [member/active != false]]) {:where "where (member.name = ? or member.id = ? or member.active != ?)" :args '("" 1 false)}))) (testing "where and & or" (is (= (q/where '[or [member/name "test"] [member/id 1] and [member/id 2] [member/active != false]]) {:where "where (member.name = ? or member.id = ?) and (member.id = ? and member.active != ?)" :args '("test" 1 2 false)})))) (deftest sql-vec (testing "sql-vec with select, limit and where clause" (is (= ["select member.name as member_name, member.email as member_email\nfrom member\nwhere (member.name = ? and member.email = ?)\nlimit 1" "test" "test@test.com"] (q/sql-vec '[:select member/name member/email :where [member/name "test"] [member/email "test@test.com"] :limit 1])))) (testing "sql-vec with an or where clause" (is (= (q/sql-vec '[:select member/name member/email :where or [member/name "test"] [member/email "test@test.com"] and [member/name != nil] [member/id != 1] :limit 1]) ["select member.name as member_name, member.email as member_email\nfrom member\nwhere (member.name = ? or member.email = ?) and (member.name is not null and member.id != ?)\nlimit 1" "test" "test@test.com" 1]))) (testing "a sql-vec that tries out most of the stuff" (is (= ["select member.id as member_id, member.name as member_name, member.email as member_email, todo.name as todo_name, todo.id as todo_id\nfrom member\nwhere (member.id != ? and todo.name != ?)\norder by todo.name desc, member.name asc\noffset 10\nlimit 1" 1 "hello"] (q/sql-vec '[:select member/id member/name member/email todo/name todo/id :where and [member/id != 1] [todo/name != "hello"] :limit 1 :offset 10 :order todo/name desc member/name])))) (testing "a join with a select statement that doesn't include the main table" (with-redefs [coast.db.schema/fetch (fn [] {:member/todos {:db/joins :todo/member :db/type :many}})] (is (= ["select todo.name as todo_name\nfrom member\njoin todo on todo.member_id = member.id\nwhere (todo.name is not null)"] (q/sql-vec '[:select todo/name :joins member/todos :where [todo/name != nil]]))))) (testing "variable parameters" (let [ids [1 2 3]] (is (= ["select todo.name as todo_name\nfrom todo\nwhere (todo.id in (?, ?, ?))" 1 2 3] (q/sql-vec '[:select todo/name :where [todo/id ?ids]] {:ids ids})))))) (deftest from (testing "from with a select without the main table" (is (= "from member" (q/from '[todo/name] '[todo/member])))))
88494
(ns coast.db.query-test (:require [coast.db.query :as q] [coast.db.schema] [clojure.test :refer [deftest testing is]])) (deftest vec->map (testing "vec->map turns query vec into map" (is (= '{:select [todo/name]} (q/vec->map '[:select todo/name]))) (is (= '{:select [todo/name todo/id]} (q/vec->map '[:select todo/name todo/id]))) (is (= '{:where [member/active true] :group [member/name] :limit [10] :offset [0] :joins [member/todos] :order [todo/id desc] :select [todo/id todo/name]}) (q/vec->map '[:select todo/id todo/name :joins member/todos :where [member/active true] :order todo/id desc :limit 10 :offset 0 :group member/name])))) (deftest where-test (testing "where with and, not" (is (= (q/where '[and [member/name != ""] [member/id 1]]) {:where "where (member.name != ? and member.id = ?)" :args '("" 1)}))) (testing "where not and implicit and" (is (= (q/where '[[member/name != ""] [member/id ""]]) {:where "where (member.name != ? and member.id = ?)" :args '("" "")}))) (testing "where or" (is (= (q/where '[or [member/name ""] [member/id 1] [member/active != false]]) {:where "where (member.name = ? or member.id = ? or member.active != ?)" :args '("" 1 false)}))) (testing "where and & or" (is (= (q/where '[or [member/name "test"] [member/id 1] and [member/id 2] [member/active != false]]) {:where "where (member.name = ? or member.id = ?) and (member.id = ? and member.active != ?)" :args '("test" 1 2 false)})))) (deftest sql-vec (testing "sql-vec with select, limit and where clause" (is (= ["select member.name as member_name, member.email as member_email\nfrom member\nwhere (member.name = ? and member.email = ?)\nlimit 1" "test" "<EMAIL>"] (q/sql-vec '[:select member/name member/email :where [member/name "test"] [member/email "<EMAIL>"] :limit 1])))) (testing "sql-vec with an or where clause" (is (= (q/sql-vec '[:select member/name member/email :where or [member/name "test"] [member/email "<EMAIL>"] and [member/name != nil] [member/id != 1] :limit 1]) ["select member.name as member_name, member.email as member_email\nfrom member\nwhere (member.name = ? or member.email = ?) and (member.name is not null and member.id != ?)\nlimit 1" "test" "<EMAIL>" 1]))) (testing "a sql-vec that tries out most of the stuff" (is (= ["select member.id as member_id, member.name as member_name, member.email as member_email, todo.name as todo_name, todo.id as todo_id\nfrom member\nwhere (member.id != ? and todo.name != ?)\norder by todo.name desc, member.name asc\noffset 10\nlimit 1" 1 "hello"] (q/sql-vec '[:select member/id member/name member/email todo/name todo/id :where and [member/id != 1] [todo/name != "hello"] :limit 1 :offset 10 :order todo/name desc member/name])))) (testing "a join with a select statement that doesn't include the main table" (with-redefs [coast.db.schema/fetch (fn [] {:member/todos {:db/joins :todo/member :db/type :many}})] (is (= ["select todo.name as todo_name\nfrom member\njoin todo on todo.member_id = member.id\nwhere (todo.name is not null)"] (q/sql-vec '[:select todo/name :joins member/todos :where [todo/name != nil]]))))) (testing "variable parameters" (let [ids [1 2 3]] (is (= ["select todo.name as todo_name\nfrom todo\nwhere (todo.id in (?, ?, ?))" 1 2 3] (q/sql-vec '[:select todo/name :where [todo/id ?ids]] {:ids ids})))))) (deftest from (testing "from with a select without the main table" (is (= "from member" (q/from '[todo/name] '[todo/member])))))
true
(ns coast.db.query-test (:require [coast.db.query :as q] [coast.db.schema] [clojure.test :refer [deftest testing is]])) (deftest vec->map (testing "vec->map turns query vec into map" (is (= '{:select [todo/name]} (q/vec->map '[:select todo/name]))) (is (= '{:select [todo/name todo/id]} (q/vec->map '[:select todo/name todo/id]))) (is (= '{:where [member/active true] :group [member/name] :limit [10] :offset [0] :joins [member/todos] :order [todo/id desc] :select [todo/id todo/name]}) (q/vec->map '[:select todo/id todo/name :joins member/todos :where [member/active true] :order todo/id desc :limit 10 :offset 0 :group member/name])))) (deftest where-test (testing "where with and, not" (is (= (q/where '[and [member/name != ""] [member/id 1]]) {:where "where (member.name != ? and member.id = ?)" :args '("" 1)}))) (testing "where not and implicit and" (is (= (q/where '[[member/name != ""] [member/id ""]]) {:where "where (member.name != ? and member.id = ?)" :args '("" "")}))) (testing "where or" (is (= (q/where '[or [member/name ""] [member/id 1] [member/active != false]]) {:where "where (member.name = ? or member.id = ? or member.active != ?)" :args '("" 1 false)}))) (testing "where and & or" (is (= (q/where '[or [member/name "test"] [member/id 1] and [member/id 2] [member/active != false]]) {:where "where (member.name = ? or member.id = ?) and (member.id = ? and member.active != ?)" :args '("test" 1 2 false)})))) (deftest sql-vec (testing "sql-vec with select, limit and where clause" (is (= ["select member.name as member_name, member.email as member_email\nfrom member\nwhere (member.name = ? and member.email = ?)\nlimit 1" "test" "PI:EMAIL:<EMAIL>END_PI"] (q/sql-vec '[:select member/name member/email :where [member/name "test"] [member/email "PI:EMAIL:<EMAIL>END_PI"] :limit 1])))) (testing "sql-vec with an or where clause" (is (= (q/sql-vec '[:select member/name member/email :where or [member/name "test"] [member/email "PI:EMAIL:<EMAIL>END_PI"] and [member/name != nil] [member/id != 1] :limit 1]) ["select member.name as member_name, member.email as member_email\nfrom member\nwhere (member.name = ? or member.email = ?) and (member.name is not null and member.id != ?)\nlimit 1" "test" "PI:EMAIL:<EMAIL>END_PI" 1]))) (testing "a sql-vec that tries out most of the stuff" (is (= ["select member.id as member_id, member.name as member_name, member.email as member_email, todo.name as todo_name, todo.id as todo_id\nfrom member\nwhere (member.id != ? and todo.name != ?)\norder by todo.name desc, member.name asc\noffset 10\nlimit 1" 1 "hello"] (q/sql-vec '[:select member/id member/name member/email todo/name todo/id :where and [member/id != 1] [todo/name != "hello"] :limit 1 :offset 10 :order todo/name desc member/name])))) (testing "a join with a select statement that doesn't include the main table" (with-redefs [coast.db.schema/fetch (fn [] {:member/todos {:db/joins :todo/member :db/type :many}})] (is (= ["select todo.name as todo_name\nfrom member\njoin todo on todo.member_id = member.id\nwhere (todo.name is not null)"] (q/sql-vec '[:select todo/name :joins member/todos :where [todo/name != nil]]))))) (testing "variable parameters" (let [ids [1 2 3]] (is (= ["select todo.name as todo_name\nfrom todo\nwhere (todo.id in (?, ?, ?))" 1 2 3] (q/sql-vec '[:select todo/name :where [todo/id ?ids]] {:ids ids})))))) (deftest from (testing "from with a select without the main table" (is (= "from member" (q/from '[todo/name] '[todo/member])))))
[ { "context": "target-username\" [target-username :as {{username :username} :identity}]\n (store/delete target-usern", "end": 665, "score": 0.9923595786094666, "start": 657, "tag": "USERNAME", "value": "username" }, { "context": "routes user-api-routes\n (GET \"/data\" {{username :username} :identity}\n (ring-response/response (store", "end": 835, "score": 0.9969115853309631, "start": 827, "tag": "USERNAME", "value": "username" }, { "context": " username)))\n (GET \"/data/:k\" [k :as {{username :username} :identity}]\n (nil-to-response (store/get-v", "end": 952, "score": 0.9926342368125916, "start": 944, "tag": "USERNAME", "value": "username" }, { "context": "ername k)))\n (POST \"/data/:k\" [k :as {{username :username} :identity} :as {{value :value} :body}]\n (", "end": 1067, "score": 0.9973474740982056, "start": 1059, "tag": "USERNAME", "value": "username" }, { "context": "s \"ok\"}))\n (DELETE \"/data/:k\" [k :as {{username :username} :identity}]\n (store/delete username k)\n", "end": 1249, "score": 0.9825793504714966, "start": 1241, "tag": "USERNAME", "value": "username" }, { "context": "ite #\"^/user($|/.*)\"}\n :session {:session-key \"KEEP-KEY-SECRET!\"\n :cookie-name \"comrade-examples-sess", "end": 2268, "score": 0.8203719258308411, "start": 2251, "tag": "KEY", "value": "KEEP-KEY-SECRET!\"" } ]
src/comrade_examples/handler.clj
gandalfhz/comrade-examples
0
(ns comrade-examples.handler (:require [compojure.core :refer [defroutes routes context GET POST PUT DELETE HEAD]] [compojure.route :as route] [ring.util.response :as ring-response] [ring.middleware.defaults :as ring-defaults] [comrade.app :as comrade-app] [comrade-examples.store :as store])) (defn- nil-to-response [response] (if-not (nil? response) (ring-response/response response) (ring-response/not-found ""))) (defroutes admin-api-routes (GET "/users" [] (ring-response/response (store/get-users))) (DELETE "/data/:target-username" [target-username :as {{username :username} :identity}] (store/delete target-username) (ring-response/response {:status "ok"}))) (defroutes user-api-routes (GET "/data" {{username :username} :identity} (ring-response/response (store/get-keys username))) (GET "/data/:k" [k :as {{username :username} :identity}] (nil-to-response (store/get-value username k))) (POST "/data/:k" [k :as {{username :username} :identity} :as {{value :value} :body}] (store/add-value! username k value) (ring-response/response {:status "ok"})) (DELETE "/data/:k" [k :as {{username :username} :identity}] (store/delete username k) (ring-response/response {:status "ok"}))) (defroutes api-routes (POST "/login" request (comrade-app/login request store/authenticate)) (GET "/logout" [] comrade-app/logout) (context "/admin" [] admin-api-routes) (context "/user" [] user-api-routes) (route/not-found {:body {:error "Not found"}})) ;; User and admin pages are served as protected resources. (defroutes site-routes (GET "/" [] (ring-response/resource-response "index" {:root "public"})) (route/not-found "Not Found")) (defn allow-access? [{{username :username session-id :session-id} :identity}] (store/valid-session? username session-id)) (def app (comrade-app/define-app :api-routes api-routes :site-routes site-routes :restrictions {:admin-api #"^/api/admin($|/.*)" :user-api #"^/api/user($|/.*)" :admin-site #"^/admin($|/.*)" :user-site #"^/user($|/.*)"} :session {:session-key "KEEP-KEY-SECRET!" :cookie-name "comrade-examples-session" :max-age (* 60 60 24 30)} :allow-access-fn? allow-access? ;; Update the defaults so that requests for resources ;; with no extension are tagged as Content-Type: text/html. :site-defaults (assoc-in ring-defaults/site-defaults [:responses :content-types] {:mime-types {nil "text/html"}})))
90390
(ns comrade-examples.handler (:require [compojure.core :refer [defroutes routes context GET POST PUT DELETE HEAD]] [compojure.route :as route] [ring.util.response :as ring-response] [ring.middleware.defaults :as ring-defaults] [comrade.app :as comrade-app] [comrade-examples.store :as store])) (defn- nil-to-response [response] (if-not (nil? response) (ring-response/response response) (ring-response/not-found ""))) (defroutes admin-api-routes (GET "/users" [] (ring-response/response (store/get-users))) (DELETE "/data/:target-username" [target-username :as {{username :username} :identity}] (store/delete target-username) (ring-response/response {:status "ok"}))) (defroutes user-api-routes (GET "/data" {{username :username} :identity} (ring-response/response (store/get-keys username))) (GET "/data/:k" [k :as {{username :username} :identity}] (nil-to-response (store/get-value username k))) (POST "/data/:k" [k :as {{username :username} :identity} :as {{value :value} :body}] (store/add-value! username k value) (ring-response/response {:status "ok"})) (DELETE "/data/:k" [k :as {{username :username} :identity}] (store/delete username k) (ring-response/response {:status "ok"}))) (defroutes api-routes (POST "/login" request (comrade-app/login request store/authenticate)) (GET "/logout" [] comrade-app/logout) (context "/admin" [] admin-api-routes) (context "/user" [] user-api-routes) (route/not-found {:body {:error "Not found"}})) ;; User and admin pages are served as protected resources. (defroutes site-routes (GET "/" [] (ring-response/resource-response "index" {:root "public"})) (route/not-found "Not Found")) (defn allow-access? [{{username :username session-id :session-id} :identity}] (store/valid-session? username session-id)) (def app (comrade-app/define-app :api-routes api-routes :site-routes site-routes :restrictions {:admin-api #"^/api/admin($|/.*)" :user-api #"^/api/user($|/.*)" :admin-site #"^/admin($|/.*)" :user-site #"^/user($|/.*)"} :session {:session-key "<KEY> :cookie-name "comrade-examples-session" :max-age (* 60 60 24 30)} :allow-access-fn? allow-access? ;; Update the defaults so that requests for resources ;; with no extension are tagged as Content-Type: text/html. :site-defaults (assoc-in ring-defaults/site-defaults [:responses :content-types] {:mime-types {nil "text/html"}})))
true
(ns comrade-examples.handler (:require [compojure.core :refer [defroutes routes context GET POST PUT DELETE HEAD]] [compojure.route :as route] [ring.util.response :as ring-response] [ring.middleware.defaults :as ring-defaults] [comrade.app :as comrade-app] [comrade-examples.store :as store])) (defn- nil-to-response [response] (if-not (nil? response) (ring-response/response response) (ring-response/not-found ""))) (defroutes admin-api-routes (GET "/users" [] (ring-response/response (store/get-users))) (DELETE "/data/:target-username" [target-username :as {{username :username} :identity}] (store/delete target-username) (ring-response/response {:status "ok"}))) (defroutes user-api-routes (GET "/data" {{username :username} :identity} (ring-response/response (store/get-keys username))) (GET "/data/:k" [k :as {{username :username} :identity}] (nil-to-response (store/get-value username k))) (POST "/data/:k" [k :as {{username :username} :identity} :as {{value :value} :body}] (store/add-value! username k value) (ring-response/response {:status "ok"})) (DELETE "/data/:k" [k :as {{username :username} :identity}] (store/delete username k) (ring-response/response {:status "ok"}))) (defroutes api-routes (POST "/login" request (comrade-app/login request store/authenticate)) (GET "/logout" [] comrade-app/logout) (context "/admin" [] admin-api-routes) (context "/user" [] user-api-routes) (route/not-found {:body {:error "Not found"}})) ;; User and admin pages are served as protected resources. (defroutes site-routes (GET "/" [] (ring-response/resource-response "index" {:root "public"})) (route/not-found "Not Found")) (defn allow-access? [{{username :username session-id :session-id} :identity}] (store/valid-session? username session-id)) (def app (comrade-app/define-app :api-routes api-routes :site-routes site-routes :restrictions {:admin-api #"^/api/admin($|/.*)" :user-api #"^/api/user($|/.*)" :admin-site #"^/admin($|/.*)" :user-site #"^/user($|/.*)"} :session {:session-key "PI:KEY:<KEY>END_PI :cookie-name "comrade-examples-session" :max-age (* 60 60 24 30)} :allow-access-fn? allow-access? ;; Update the defaults so that requests for resources ;; with no extension are tagged as Content-Type: text/html. :site-defaults (assoc-in ring-defaults/site-defaults [:responses :content-types] {:mime-types {nil "text/html"}})))
[ { "context": "; Copyright 2018-2021 Rahul De\n;\n; Use of this source code is governed by an MIT", "end": 30, "score": 0.9998617172241211, "start": 22, "tag": "NAME", "value": "Rahul De" } ]
entities/src/entities/pipeline.clj
bob-cd/bob
88
; Copyright 2018-2021 Rahul De ; ; Use of this source code is governed by an MIT-style ; license that can be found in the LICENSE file or at ; https://opensource.org/licenses/MIT. (ns entities.pipeline (:require [failjure.core :as f] [taoensso.timbre :as log] [xtdb.api :as xt] [common.errors :as err])) (defn create "Creates a new pipeline. Takes a map of the following: - group - name - a list of steps - a map of environment vars - a list of resources - a starting Docker image. The group defines a logical grouping of pipelines like dev or staging and the name is the name of the pipeline like build or test. Returns Ok or the error if any." [db-client queue-chan pipeline] (let [id (keyword (format "bob.pipeline.%s/%s" (:group pipeline) (:name pipeline))) data (-> pipeline (assoc :xt/id id) (assoc :type :pipeline)) result (f/try* (xt/submit-tx db-client [[::xt/put data]]))] (if (f/failed? result) (err/publish-error queue-chan (format "Pipeline creation failed: %s" (f/message result))) "Ok"))) (defn delete "Deletes a pipeline" [db-client _queue-chan pipeline] (let [id (keyword (format "bob.pipeline.%s/%s" (:group pipeline) (:name pipeline)))] (log/debugf "Deleting pipeline %s" pipeline) (f/try* (xt/submit-tx db-client [[::xt/delete id]])) "Ok"))
16994
; Copyright 2018-2021 <NAME> ; ; Use of this source code is governed by an MIT-style ; license that can be found in the LICENSE file or at ; https://opensource.org/licenses/MIT. (ns entities.pipeline (:require [failjure.core :as f] [taoensso.timbre :as log] [xtdb.api :as xt] [common.errors :as err])) (defn create "Creates a new pipeline. Takes a map of the following: - group - name - a list of steps - a map of environment vars - a list of resources - a starting Docker image. The group defines a logical grouping of pipelines like dev or staging and the name is the name of the pipeline like build or test. Returns Ok or the error if any." [db-client queue-chan pipeline] (let [id (keyword (format "bob.pipeline.%s/%s" (:group pipeline) (:name pipeline))) data (-> pipeline (assoc :xt/id id) (assoc :type :pipeline)) result (f/try* (xt/submit-tx db-client [[::xt/put data]]))] (if (f/failed? result) (err/publish-error queue-chan (format "Pipeline creation failed: %s" (f/message result))) "Ok"))) (defn delete "Deletes a pipeline" [db-client _queue-chan pipeline] (let [id (keyword (format "bob.pipeline.%s/%s" (:group pipeline) (:name pipeline)))] (log/debugf "Deleting pipeline %s" pipeline) (f/try* (xt/submit-tx db-client [[::xt/delete id]])) "Ok"))
true
; Copyright 2018-2021 PI:NAME:<NAME>END_PI ; ; Use of this source code is governed by an MIT-style ; license that can be found in the LICENSE file or at ; https://opensource.org/licenses/MIT. (ns entities.pipeline (:require [failjure.core :as f] [taoensso.timbre :as log] [xtdb.api :as xt] [common.errors :as err])) (defn create "Creates a new pipeline. Takes a map of the following: - group - name - a list of steps - a map of environment vars - a list of resources - a starting Docker image. The group defines a logical grouping of pipelines like dev or staging and the name is the name of the pipeline like build or test. Returns Ok or the error if any." [db-client queue-chan pipeline] (let [id (keyword (format "bob.pipeline.%s/%s" (:group pipeline) (:name pipeline))) data (-> pipeline (assoc :xt/id id) (assoc :type :pipeline)) result (f/try* (xt/submit-tx db-client [[::xt/put data]]))] (if (f/failed? result) (err/publish-error queue-chan (format "Pipeline creation failed: %s" (f/message result))) "Ok"))) (defn delete "Deletes a pipeline" [db-client _queue-chan pipeline] (let [id (keyword (format "bob.pipeline.%s/%s" (:group pipeline) (:name pipeline)))] (log/debugf "Deleting pipeline %s" pipeline) (f/try* (xt/submit-tx db-client [[::xt/delete id]])) "Ok"))
[ { "context": "rest.users \"The Foursquare Users API\"\n {:author \"William Lee (birryree)\"}\n (:require [mochify.hiroba.rest :as", "end": 80, "score": 0.9998876452445984, "start": 69, "tag": "NAME", "value": "William Lee" }, { "context": "he Foursquare Users API\"\n {:author \"William Lee (birryree)\"}\n (:require [mochify.hiroba.rest :as rest]))\n\n", "end": 90, "score": 0.9995482563972473, "start": 82, "tag": "USERNAME", "value": "birryree" } ]
src/mochify/hiroba/rest/users.clj
mochify/hiroba
0
(ns mochify.hiroba.rest.users "The Foursquare Users API" {:author "William Lee (birryree)"} (:require [mochify.hiroba.rest :as rest])) (defn user "Returns information for a user. Required Parameters: * oauth-token (string) - An OAuth2 token for an authenticated user. Optional Parameters: * user (string) - A user to get. If not supplied, defaults to 'self'. " ([user oauth-token] (rest/get (rest/authenticated-uri "users" user) :query-params {:oauth_token oauth-token})) ([oauth-token] (user "self" oauth-token))) (defn leaderboard "hits the leaderboard endpoint" ([&{:as params}] (rest/get (rest/authenticated-uri "users" "leaderboard") :query-params params))) (defn requests "Endpoint for the list of friend requests a user has" ([&{:as params}] (rest/get (rest/authenticated-uri "users" "requests") :query-params params))) (defn search "Locate friends with a bunch of parameters against the endpoint users/search Parameters: * :phone seq(string) - a list of phone numbers to search by. * :email seq(string) - a list of email addresses to search by. * :twitter seq(string) - a list of Twitter handles to search. * :twitterSource (string) - a single Twitter handle. Will return users that the handle follows on Twitter, who also use * :fbid (seq(string)) - A list of Facebook user IDs to search * :name (string) - A name to search for * :oauth_token (string) - OAuth2 token for the user " ([& {:as params}] (rest/get (rest/authenticated-uri "users" "search") :query-params params))) (defn badges "Returns a user's badges" ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "badges") :query-params params))) (defn checkins "Returns a history of checkins for a user. Parameters: * :limit (int) - number of results to return, up to 250 (default 100) * :offset (int) - number of results to return, up to 250 (default 100) * :sort (string) - sort the returned checkins, valid values are 'newestfirst' or 'oldestfirst' (default 'newestfirst') * :afterTimestamp - retrieve the first results that follow this value. The value is seconds after epoch. * :beforeTimestamp - retrieve the first results before this epoch time. " ([& {:as params}] (rest/get (rest/authenticated-uri "users" "self" "checkins") :query-params params))) (defn friends "Returns an array of a user's friends Parameters: * :limit (int) - number of results to return, up to 500 * :offset (int) - Used to page through results. " ([user & {:as params}] (rest/get (rest/authenticated-uri "users" user "friends") :query-params params))) (defn lists "Returns lists associated with a user. Parameters: * :group (string) - Can be one of the following, 'created', 'edited', 'followed', 'friends', or 'suggested' * :ll (geographic coordinate) - Location of the user. Necessary if you specify :group 'suggested' " ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "lists") :query-params params))) (defn mayorships "Returns a user's mayorships" ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "mayorships") :query-params params))) (defn photos "Returns photos a user has uploaded. Parameters: * :limit (int) - Number of results to return. Default 100, max 500. * :offset (int) - Used to page through results. Default 100. " ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "photos") :query-params params))) (defn venuehistory "Returns a list of venues visited by a user, including count and last visit. Parameters: * :beforeTimestamp (int) - Seconds since epoch. * :afterTimestamp (int) - Seconds after epoch. * :categoryId (string) - Limits returned venues to this category. If a top-level category is specified, all sub-categories will match. " ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "venuehistory") :query-params params))) (defn approve "Approve a friend request from another user." ([user oauth-token] (rest/post (rest/authenticated-uri "users" user "approve") :query-params {:oauth_token oauth-token}))) (defn deny "Denies a pending friend request from another user." ([user oauth-token] (rest/post (rest/authenticated-uri "users" user "deny") :query-params {:oauth_token oauth-token}))) (defn setpings "Changes whether a user will receive pings (phone notifications) when a specified user checks in. Required Parameters: * user (string) - A User ID for a friend. * oauth-token (string) - The OAuth token of an authenticated user. * receive-pings (bool) - True if you should receive pings from the specified user, False otherwise. " ([user oauth-token receive-pings] (rest/post (rest/authenticated-uri "users" user "setpings") :query-params {:oauth_token oauth-token :value receive-pings}))) (defn unfriend "Cancels a relationship between the acting user and a specified user. Removes a friend, unfollows a celebrity, or rejects a pending friend request. Required Parameters: * user (string) - The User ID to unfriend * oauth-token (string) - The Acting User's OAuth token " ([user oauth-token] (rest/post (rest/authenticated-uri "users" user "unfriend") :query-params {:oauth_token oauth-token})))
34181
(ns mochify.hiroba.rest.users "The Foursquare Users API" {:author "<NAME> (birryree)"} (:require [mochify.hiroba.rest :as rest])) (defn user "Returns information for a user. Required Parameters: * oauth-token (string) - An OAuth2 token for an authenticated user. Optional Parameters: * user (string) - A user to get. If not supplied, defaults to 'self'. " ([user oauth-token] (rest/get (rest/authenticated-uri "users" user) :query-params {:oauth_token oauth-token})) ([oauth-token] (user "self" oauth-token))) (defn leaderboard "hits the leaderboard endpoint" ([&{:as params}] (rest/get (rest/authenticated-uri "users" "leaderboard") :query-params params))) (defn requests "Endpoint for the list of friend requests a user has" ([&{:as params}] (rest/get (rest/authenticated-uri "users" "requests") :query-params params))) (defn search "Locate friends with a bunch of parameters against the endpoint users/search Parameters: * :phone seq(string) - a list of phone numbers to search by. * :email seq(string) - a list of email addresses to search by. * :twitter seq(string) - a list of Twitter handles to search. * :twitterSource (string) - a single Twitter handle. Will return users that the handle follows on Twitter, who also use * :fbid (seq(string)) - A list of Facebook user IDs to search * :name (string) - A name to search for * :oauth_token (string) - OAuth2 token for the user " ([& {:as params}] (rest/get (rest/authenticated-uri "users" "search") :query-params params))) (defn badges "Returns a user's badges" ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "badges") :query-params params))) (defn checkins "Returns a history of checkins for a user. Parameters: * :limit (int) - number of results to return, up to 250 (default 100) * :offset (int) - number of results to return, up to 250 (default 100) * :sort (string) - sort the returned checkins, valid values are 'newestfirst' or 'oldestfirst' (default 'newestfirst') * :afterTimestamp - retrieve the first results that follow this value. The value is seconds after epoch. * :beforeTimestamp - retrieve the first results before this epoch time. " ([& {:as params}] (rest/get (rest/authenticated-uri "users" "self" "checkins") :query-params params))) (defn friends "Returns an array of a user's friends Parameters: * :limit (int) - number of results to return, up to 500 * :offset (int) - Used to page through results. " ([user & {:as params}] (rest/get (rest/authenticated-uri "users" user "friends") :query-params params))) (defn lists "Returns lists associated with a user. Parameters: * :group (string) - Can be one of the following, 'created', 'edited', 'followed', 'friends', or 'suggested' * :ll (geographic coordinate) - Location of the user. Necessary if you specify :group 'suggested' " ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "lists") :query-params params))) (defn mayorships "Returns a user's mayorships" ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "mayorships") :query-params params))) (defn photos "Returns photos a user has uploaded. Parameters: * :limit (int) - Number of results to return. Default 100, max 500. * :offset (int) - Used to page through results. Default 100. " ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "photos") :query-params params))) (defn venuehistory "Returns a list of venues visited by a user, including count and last visit. Parameters: * :beforeTimestamp (int) - Seconds since epoch. * :afterTimestamp (int) - Seconds after epoch. * :categoryId (string) - Limits returned venues to this category. If a top-level category is specified, all sub-categories will match. " ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "venuehistory") :query-params params))) (defn approve "Approve a friend request from another user." ([user oauth-token] (rest/post (rest/authenticated-uri "users" user "approve") :query-params {:oauth_token oauth-token}))) (defn deny "Denies a pending friend request from another user." ([user oauth-token] (rest/post (rest/authenticated-uri "users" user "deny") :query-params {:oauth_token oauth-token}))) (defn setpings "Changes whether a user will receive pings (phone notifications) when a specified user checks in. Required Parameters: * user (string) - A User ID for a friend. * oauth-token (string) - The OAuth token of an authenticated user. * receive-pings (bool) - True if you should receive pings from the specified user, False otherwise. " ([user oauth-token receive-pings] (rest/post (rest/authenticated-uri "users" user "setpings") :query-params {:oauth_token oauth-token :value receive-pings}))) (defn unfriend "Cancels a relationship between the acting user and a specified user. Removes a friend, unfollows a celebrity, or rejects a pending friend request. Required Parameters: * user (string) - The User ID to unfriend * oauth-token (string) - The Acting User's OAuth token " ([user oauth-token] (rest/post (rest/authenticated-uri "users" user "unfriend") :query-params {:oauth_token oauth-token})))
true
(ns mochify.hiroba.rest.users "The Foursquare Users API" {:author "PI:NAME:<NAME>END_PI (birryree)"} (:require [mochify.hiroba.rest :as rest])) (defn user "Returns information for a user. Required Parameters: * oauth-token (string) - An OAuth2 token for an authenticated user. Optional Parameters: * user (string) - A user to get. If not supplied, defaults to 'self'. " ([user oauth-token] (rest/get (rest/authenticated-uri "users" user) :query-params {:oauth_token oauth-token})) ([oauth-token] (user "self" oauth-token))) (defn leaderboard "hits the leaderboard endpoint" ([&{:as params}] (rest/get (rest/authenticated-uri "users" "leaderboard") :query-params params))) (defn requests "Endpoint for the list of friend requests a user has" ([&{:as params}] (rest/get (rest/authenticated-uri "users" "requests") :query-params params))) (defn search "Locate friends with a bunch of parameters against the endpoint users/search Parameters: * :phone seq(string) - a list of phone numbers to search by. * :email seq(string) - a list of email addresses to search by. * :twitter seq(string) - a list of Twitter handles to search. * :twitterSource (string) - a single Twitter handle. Will return users that the handle follows on Twitter, who also use * :fbid (seq(string)) - A list of Facebook user IDs to search * :name (string) - A name to search for * :oauth_token (string) - OAuth2 token for the user " ([& {:as params}] (rest/get (rest/authenticated-uri "users" "search") :query-params params))) (defn badges "Returns a user's badges" ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "badges") :query-params params))) (defn checkins "Returns a history of checkins for a user. Parameters: * :limit (int) - number of results to return, up to 250 (default 100) * :offset (int) - number of results to return, up to 250 (default 100) * :sort (string) - sort the returned checkins, valid values are 'newestfirst' or 'oldestfirst' (default 'newestfirst') * :afterTimestamp - retrieve the first results that follow this value. The value is seconds after epoch. * :beforeTimestamp - retrieve the first results before this epoch time. " ([& {:as params}] (rest/get (rest/authenticated-uri "users" "self" "checkins") :query-params params))) (defn friends "Returns an array of a user's friends Parameters: * :limit (int) - number of results to return, up to 500 * :offset (int) - Used to page through results. " ([user & {:as params}] (rest/get (rest/authenticated-uri "users" user "friends") :query-params params))) (defn lists "Returns lists associated with a user. Parameters: * :group (string) - Can be one of the following, 'created', 'edited', 'followed', 'friends', or 'suggested' * :ll (geographic coordinate) - Location of the user. Necessary if you specify :group 'suggested' " ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "lists") :query-params params))) (defn mayorships "Returns a user's mayorships" ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "mayorships") :query-params params))) (defn photos "Returns photos a user has uploaded. Parameters: * :limit (int) - Number of results to return. Default 100, max 500. * :offset (int) - Used to page through results. Default 100. " ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "photos") :query-params params))) (defn venuehistory "Returns a list of venues visited by a user, including count and last visit. Parameters: * :beforeTimestamp (int) - Seconds since epoch. * :afterTimestamp (int) - Seconds after epoch. * :categoryId (string) - Limits returned venues to this category. If a top-level category is specified, all sub-categories will match. " ([user &{:as params}] (rest/get (rest/authenticated-uri "users" user "venuehistory") :query-params params))) (defn approve "Approve a friend request from another user." ([user oauth-token] (rest/post (rest/authenticated-uri "users" user "approve") :query-params {:oauth_token oauth-token}))) (defn deny "Denies a pending friend request from another user." ([user oauth-token] (rest/post (rest/authenticated-uri "users" user "deny") :query-params {:oauth_token oauth-token}))) (defn setpings "Changes whether a user will receive pings (phone notifications) when a specified user checks in. Required Parameters: * user (string) - A User ID for a friend. * oauth-token (string) - The OAuth token of an authenticated user. * receive-pings (bool) - True if you should receive pings from the specified user, False otherwise. " ([user oauth-token receive-pings] (rest/post (rest/authenticated-uri "users" user "setpings") :query-params {:oauth_token oauth-token :value receive-pings}))) (defn unfriend "Cancels a relationship between the acting user and a specified user. Removes a friend, unfollows a celebrity, or rejects a pending friend request. Required Parameters: * user (string) - The User ID to unfriend * oauth-token (string) - The Acting User's OAuth token " ([user oauth-token] (rest/post (rest/authenticated-uri "users" user "unfriend") :query-params {:oauth_token oauth-token})))
[ { "context": "(-> {:connection-uri jdbc-url :user user :password password}\n (jdbc/execute! [statement]))))\n\n(defn- g", "end": 7799, "score": 0.9967088103294373, "start": 7791, "tag": "PASSWORD", "value": "password" } ]
tools/scalar-schema/src/scalar_schema/jdbc.clj
y-taka-23/scalardb
0
(ns scalar-schema.jdbc (:require [clojure.tools.logging :as log] [clojure.string :as string] [scalar-schema.common :as common] [scalar-schema.protocols :as proto] [clojure.java.jdbc :as jdbc]) (:import (java.sql SQLException))) (def ^:private data-type-mapping {:mysql {"INT" "INT" "BIGINT" "BIGINT" "TEXT" "LONGTEXT" "FLOAT" "FLOAT" "DOUBLE" "DOUBLE" "BOOLEAN" "BOOLEAN" "BLOB" "LONGBLOB"} :postgresql {"INT" "INT" "BIGINT" "BIGINT" "TEXT" "TEXT" "FLOAT" "FLOAT" "DOUBLE" "DOUBLE PRECISION" "BOOLEAN" "BOOLEAN" "BLOB" "BYTEA"} :oracle {"INT" "INT" "BIGINT" "NUMBER(19)" "TEXT" "VARCHAR(4000)" "FLOAT" "BINARY_FLOAT" "DOUBLE" "BINARY_DOUBLE" "BOOLEAN" "NUMBER(1)" "BLOB" "BLOB"} :sql-server {"INT" "INT" "BIGINT" "BIGINT" "TEXT" "VARCHAR(8000)" "FLOAT" "FLOAT(24)" "DOUBLE" "FLOAT" "BOOLEAN" "BIT" "BLOB" "VARBINARY(8000)"}}) (def ^:private data-type-mapping-for-key {:mysql {"TEXT" "VARCHAR(64)" "BLOB" "VARBINARY(64)"} :postgresql {"TEXT" "VARCHAR(10485760)"} :oracle {"BLOB" "RAW(2000)"} :sql-server {}}) (defn- key? [column key] (if key (.contains key column) false)) (defn- get-table-name ([database table] (str database \. table)) ([database table {:keys [enclosure-fn]}] (str (enclosure-fn database) \. (enclosure-fn table)))) (defn- get-metadata-table-name [{:keys [prefix] :as opts}] (let [database common/METADATA_DATABASE table common/METADATA_TABLE] (get-table-name (if prefix (str prefix \_ database) database) table opts))) (defn- get-metadata-schema [{:keys [boolean-type]}] {"full_table_name" "VARCHAR(128)" "column_name" "VARCHAR(128)" "data_type" "VARCHAR(20) NOT NULL" "key_type" "VARCHAR(20)" "clustering_order" "VARCHAR(10)" "indexed" (str boolean-type \ "NOT NULL") "index_order" "VARCHAR(10)" "ordinal_position" "INTEGER NOT NULL"}) (defn- make-create-metadata-statement [{:keys [enclosure-fn] :as opts}] (str "CREATE TABLE " (get-metadata-table-name opts) \( (->> (map #(str (enclosure-fn (key %)) \ (val %)) (get-metadata-schema opts)) (string/join \,)) ", PRIMARY KEY (" (->> (map enclosure-fn ["full_table_name" "column_name"]) (string/join \,)) "))")) (defn- create-metadata-table [{:keys [execution-fn] :as opts}] (try (execution-fn (make-create-metadata-statement opts)) (log/info "metatable table is created successfully.") (catch SQLException e (when-not (string/includes? (.getMessage e) "already") (throw e))))) (defn- make-create-database-statement [database {:keys [enclosure-fn]}] (str "CREATE SCHEMA " (enclosure-fn database))) (defn- create-database [database {:keys [rdb-engine execution-fn] :as opts}] (when-not (= rdb-engine :oracle) (try (execution-fn (make-create-database-statement database opts)) (log/info "The database" database "is created successfully.") (catch SQLException e (when-not (or (string/includes? (.getMessage e) "already") (string/includes? (.getMessage e) "database exists")) (throw e)))))) (defn- create-metadata-database [{:keys [prefix] :as opts}] (let [meta-database common/METADATA_DATABASE database (if prefix (str prefix \_ meta-database) meta-database)] (create-database database opts))) (defn- make-create-table-statement [{:keys [database table partition-key clustering-key reordered-columns]} {:keys [enclosure-fn data-type-fn] :as opts}] (let [primary-key (concat partition-key clustering-key)] (str "CREATE TABLE " (get-table-name database table opts) \( (->> (map #(let [column (enclosure-fn (first %)) data-type (data-type-fn (first %) (second %))] (str column \ data-type)) reordered-columns) (string/join \,)) ", PRIMARY KEY (" (->> (map enclosure-fn primary-key) (string/join \,)) "))"))) (defn- create-table [schema {:keys [execution-fn] :as opts}] (execution-fn (make-create-table-statement schema opts))) (defn- make-create-index-statement [{:keys [database table]} {:keys [enclosure-fn] :as opts} indexed-column] (let [index-name (str common/INDEX_NAME_PREFIX \_ database \_ table \_ indexed-column)] (str "CREATE INDEX " (enclosure-fn index-name) " ON " (get-table-name database table opts) \( (enclosure-fn indexed-column) \)))) (defn- create-index [{:keys [secondary-index] :as schema} {:keys [execution-fn] :as opts}] (doall (map #(execution-fn (make-create-index-statement schema opts %)) secondary-index))) (defn- get-key-type [column partition-key clustering-key] (cond (key? column partition-key) "PARTITION" (key? column clustering-key) "CLUSTERING" :else nil)) (defn- secondary-indexed? [column secondary-index] (key? column secondary-index)) (defn- make-insert-metadata-statement [{:keys [database table partition-key clustering-key secondary-index]} {:keys [boolean-value-fn] :as opts} column data-type ordinal-position] (let [key-type (get-key-type column partition-key clustering-key) key-order (if (key? column clustering-key) "'ASC'" "NULL") indexed (boolean-value-fn (secondary-indexed? column secondary-index)) index-order (if (key? column secondary-index) "'ASC'" "NULL")] (str "INSERT INTO " (get-metadata-table-name opts) " VALUES (" "'" (get-table-name database table) "'," "'" column "'," "'" data-type "'," (if key-type (str "'" key-type "'") "NULL") "," key-order "," indexed "," index-order "," ordinal-position ")"))) (defn- insert-metadata [{:keys [reordered-columns] :as schema} {:keys [execution-fn] :as opts}] (loop [[[column data-type] & rest] reordered-columns pos 1] (when column (execution-fn (make-insert-metadata-statement schema opts column (string/upper-case data-type) pos)) (recur rest (inc pos))))) (defn- make-drop-table-statement [{:keys [database table]} opts] (str "DROP TABLE " (get-table-name database table opts))) (defn- drop-table [schema {:keys [execution-fn] :as opts}] (execution-fn (make-drop-table-statement schema opts))) (defn- make-delete-metadata-statement [{:keys [database table]} {:keys [enclosure-fn] :as opts}] (str "DELETE FROM " (get-metadata-table-name opts) " WHERE " (enclosure-fn "full_table_name") " = " "'" (get-table-name database table) "'")) (defn- delete-metadata [schema {:keys [execution-fn] :as opts}] (execution-fn (make-delete-metadata-statement schema opts))) (defn- reorder-columns [{:keys [columns partition-key clustering-key]}] (concat (map #(vector % (get columns %)) partition-key) (map #(vector % (get columns %)) clustering-key) (filter #(not (key? (first %) (concat partition-key clustering-key))) (apply list columns)))) (defn- get-execution-fn [{:keys [jdbc-url user password]}] (fn [statement] (log/debug "Executing" statement) (-> {:connection-uri jdbc-url :user user :password password} (jdbc/execute! [statement])))) (defn- get-rdb-engine [{:keys [jdbc-url]}] (condp #(string/starts-with? %2 %1) jdbc-url "jdbc:mysql:" :mysql "jdbc:postgresql:" :postgresql "jdbc:oracle:" :oracle "jdbc:sqlserver:" :sql-server (throw (ex-info "unknown rdb engine" {})))) (defn- get-enclosure-fn [rdb-engine] #(cond (= rdb-engine :mysql) (str "`" % "`") (= rdb-engine :sql-server) (str "[" % "]") :else (str "\"" % "\""))) (defn- get-boolean-type [rdb-engine] (get (get data-type-mapping rdb-engine) "BOOLEAN")) (defn- get-boolean-value-fn [rdb-engine] #(if (or (= rdb-engine :oracle) (= rdb-engine :sql-server)) (if % "1" "0") (if % "true" "false"))) (defn- get-data-type-fn [rdb-engine {:keys [partition-key clustering-key secondary-index]}] #(let [data-type (string/upper-case %2) mapping (get data-type-mapping rdb-engine) mapping-for-key (get data-type-mapping-for-key rdb-engine)] (if (key? %1 (concat partition-key clustering-key secondary-index)) (get mapping-for-key data-type (get mapping data-type)) (get mapping data-type)))) (defn make-jdbc-operator [opts] (let [rdb-engine (get-rdb-engine opts) opts (assoc opts :execution-fn (get-execution-fn opts) :rdb-engine rdb-engine :enclosure-fn (get-enclosure-fn rdb-engine) :boolean-type (get-boolean-type rdb-engine) :boolean-value-fn (get-boolean-value-fn rdb-engine))] (reify proto/IOperator (create-table [_ {:keys [database table] :as schema} _] (let [schema (assoc schema :reordered-columns (reorder-columns schema)) opts (assoc opts :data-type-fn (get-data-type-fn rdb-engine schema)) table-name (get-table-name database table)] (try (create-metadata-database opts) (create-metadata-table opts) (create-database database opts) (create-table schema opts) (create-index schema opts) (insert-metadata schema opts) (log/info table-name "is created successfully.") (catch SQLException e (if (string/includes? (.getMessage e) "already") (log/warn table-name "already exists.") (throw e)))))) (delete-table [_ {:keys [database table] :as schema} _] (let [table-name (get-table-name database table)] (try (create-metadata-database opts) (create-metadata-table opts) (delete-metadata schema opts) (drop-table schema opts) (log/info table-name "is deleted successfully.") (catch SQLException e (if (or (string/includes? (.getMessage e) "Unknown table") (string/includes? (.getMessage e) "does not exist")) (log/warn table-name "does not exist.") (throw e)))))) (close [_ _]))))
100608
(ns scalar-schema.jdbc (:require [clojure.tools.logging :as log] [clojure.string :as string] [scalar-schema.common :as common] [scalar-schema.protocols :as proto] [clojure.java.jdbc :as jdbc]) (:import (java.sql SQLException))) (def ^:private data-type-mapping {:mysql {"INT" "INT" "BIGINT" "BIGINT" "TEXT" "LONGTEXT" "FLOAT" "FLOAT" "DOUBLE" "DOUBLE" "BOOLEAN" "BOOLEAN" "BLOB" "LONGBLOB"} :postgresql {"INT" "INT" "BIGINT" "BIGINT" "TEXT" "TEXT" "FLOAT" "FLOAT" "DOUBLE" "DOUBLE PRECISION" "BOOLEAN" "BOOLEAN" "BLOB" "BYTEA"} :oracle {"INT" "INT" "BIGINT" "NUMBER(19)" "TEXT" "VARCHAR(4000)" "FLOAT" "BINARY_FLOAT" "DOUBLE" "BINARY_DOUBLE" "BOOLEAN" "NUMBER(1)" "BLOB" "BLOB"} :sql-server {"INT" "INT" "BIGINT" "BIGINT" "TEXT" "VARCHAR(8000)" "FLOAT" "FLOAT(24)" "DOUBLE" "FLOAT" "BOOLEAN" "BIT" "BLOB" "VARBINARY(8000)"}}) (def ^:private data-type-mapping-for-key {:mysql {"TEXT" "VARCHAR(64)" "BLOB" "VARBINARY(64)"} :postgresql {"TEXT" "VARCHAR(10485760)"} :oracle {"BLOB" "RAW(2000)"} :sql-server {}}) (defn- key? [column key] (if key (.contains key column) false)) (defn- get-table-name ([database table] (str database \. table)) ([database table {:keys [enclosure-fn]}] (str (enclosure-fn database) \. (enclosure-fn table)))) (defn- get-metadata-table-name [{:keys [prefix] :as opts}] (let [database common/METADATA_DATABASE table common/METADATA_TABLE] (get-table-name (if prefix (str prefix \_ database) database) table opts))) (defn- get-metadata-schema [{:keys [boolean-type]}] {"full_table_name" "VARCHAR(128)" "column_name" "VARCHAR(128)" "data_type" "VARCHAR(20) NOT NULL" "key_type" "VARCHAR(20)" "clustering_order" "VARCHAR(10)" "indexed" (str boolean-type \ "NOT NULL") "index_order" "VARCHAR(10)" "ordinal_position" "INTEGER NOT NULL"}) (defn- make-create-metadata-statement [{:keys [enclosure-fn] :as opts}] (str "CREATE TABLE " (get-metadata-table-name opts) \( (->> (map #(str (enclosure-fn (key %)) \ (val %)) (get-metadata-schema opts)) (string/join \,)) ", PRIMARY KEY (" (->> (map enclosure-fn ["full_table_name" "column_name"]) (string/join \,)) "))")) (defn- create-metadata-table [{:keys [execution-fn] :as opts}] (try (execution-fn (make-create-metadata-statement opts)) (log/info "metatable table is created successfully.") (catch SQLException e (when-not (string/includes? (.getMessage e) "already") (throw e))))) (defn- make-create-database-statement [database {:keys [enclosure-fn]}] (str "CREATE SCHEMA " (enclosure-fn database))) (defn- create-database [database {:keys [rdb-engine execution-fn] :as opts}] (when-not (= rdb-engine :oracle) (try (execution-fn (make-create-database-statement database opts)) (log/info "The database" database "is created successfully.") (catch SQLException e (when-not (or (string/includes? (.getMessage e) "already") (string/includes? (.getMessage e) "database exists")) (throw e)))))) (defn- create-metadata-database [{:keys [prefix] :as opts}] (let [meta-database common/METADATA_DATABASE database (if prefix (str prefix \_ meta-database) meta-database)] (create-database database opts))) (defn- make-create-table-statement [{:keys [database table partition-key clustering-key reordered-columns]} {:keys [enclosure-fn data-type-fn] :as opts}] (let [primary-key (concat partition-key clustering-key)] (str "CREATE TABLE " (get-table-name database table opts) \( (->> (map #(let [column (enclosure-fn (first %)) data-type (data-type-fn (first %) (second %))] (str column \ data-type)) reordered-columns) (string/join \,)) ", PRIMARY KEY (" (->> (map enclosure-fn primary-key) (string/join \,)) "))"))) (defn- create-table [schema {:keys [execution-fn] :as opts}] (execution-fn (make-create-table-statement schema opts))) (defn- make-create-index-statement [{:keys [database table]} {:keys [enclosure-fn] :as opts} indexed-column] (let [index-name (str common/INDEX_NAME_PREFIX \_ database \_ table \_ indexed-column)] (str "CREATE INDEX " (enclosure-fn index-name) " ON " (get-table-name database table opts) \( (enclosure-fn indexed-column) \)))) (defn- create-index [{:keys [secondary-index] :as schema} {:keys [execution-fn] :as opts}] (doall (map #(execution-fn (make-create-index-statement schema opts %)) secondary-index))) (defn- get-key-type [column partition-key clustering-key] (cond (key? column partition-key) "PARTITION" (key? column clustering-key) "CLUSTERING" :else nil)) (defn- secondary-indexed? [column secondary-index] (key? column secondary-index)) (defn- make-insert-metadata-statement [{:keys [database table partition-key clustering-key secondary-index]} {:keys [boolean-value-fn] :as opts} column data-type ordinal-position] (let [key-type (get-key-type column partition-key clustering-key) key-order (if (key? column clustering-key) "'ASC'" "NULL") indexed (boolean-value-fn (secondary-indexed? column secondary-index)) index-order (if (key? column secondary-index) "'ASC'" "NULL")] (str "INSERT INTO " (get-metadata-table-name opts) " VALUES (" "'" (get-table-name database table) "'," "'" column "'," "'" data-type "'," (if key-type (str "'" key-type "'") "NULL") "," key-order "," indexed "," index-order "," ordinal-position ")"))) (defn- insert-metadata [{:keys [reordered-columns] :as schema} {:keys [execution-fn] :as opts}] (loop [[[column data-type] & rest] reordered-columns pos 1] (when column (execution-fn (make-insert-metadata-statement schema opts column (string/upper-case data-type) pos)) (recur rest (inc pos))))) (defn- make-drop-table-statement [{:keys [database table]} opts] (str "DROP TABLE " (get-table-name database table opts))) (defn- drop-table [schema {:keys [execution-fn] :as opts}] (execution-fn (make-drop-table-statement schema opts))) (defn- make-delete-metadata-statement [{:keys [database table]} {:keys [enclosure-fn] :as opts}] (str "DELETE FROM " (get-metadata-table-name opts) " WHERE " (enclosure-fn "full_table_name") " = " "'" (get-table-name database table) "'")) (defn- delete-metadata [schema {:keys [execution-fn] :as opts}] (execution-fn (make-delete-metadata-statement schema opts))) (defn- reorder-columns [{:keys [columns partition-key clustering-key]}] (concat (map #(vector % (get columns %)) partition-key) (map #(vector % (get columns %)) clustering-key) (filter #(not (key? (first %) (concat partition-key clustering-key))) (apply list columns)))) (defn- get-execution-fn [{:keys [jdbc-url user password]}] (fn [statement] (log/debug "Executing" statement) (-> {:connection-uri jdbc-url :user user :password <PASSWORD>} (jdbc/execute! [statement])))) (defn- get-rdb-engine [{:keys [jdbc-url]}] (condp #(string/starts-with? %2 %1) jdbc-url "jdbc:mysql:" :mysql "jdbc:postgresql:" :postgresql "jdbc:oracle:" :oracle "jdbc:sqlserver:" :sql-server (throw (ex-info "unknown rdb engine" {})))) (defn- get-enclosure-fn [rdb-engine] #(cond (= rdb-engine :mysql) (str "`" % "`") (= rdb-engine :sql-server) (str "[" % "]") :else (str "\"" % "\""))) (defn- get-boolean-type [rdb-engine] (get (get data-type-mapping rdb-engine) "BOOLEAN")) (defn- get-boolean-value-fn [rdb-engine] #(if (or (= rdb-engine :oracle) (= rdb-engine :sql-server)) (if % "1" "0") (if % "true" "false"))) (defn- get-data-type-fn [rdb-engine {:keys [partition-key clustering-key secondary-index]}] #(let [data-type (string/upper-case %2) mapping (get data-type-mapping rdb-engine) mapping-for-key (get data-type-mapping-for-key rdb-engine)] (if (key? %1 (concat partition-key clustering-key secondary-index)) (get mapping-for-key data-type (get mapping data-type)) (get mapping data-type)))) (defn make-jdbc-operator [opts] (let [rdb-engine (get-rdb-engine opts) opts (assoc opts :execution-fn (get-execution-fn opts) :rdb-engine rdb-engine :enclosure-fn (get-enclosure-fn rdb-engine) :boolean-type (get-boolean-type rdb-engine) :boolean-value-fn (get-boolean-value-fn rdb-engine))] (reify proto/IOperator (create-table [_ {:keys [database table] :as schema} _] (let [schema (assoc schema :reordered-columns (reorder-columns schema)) opts (assoc opts :data-type-fn (get-data-type-fn rdb-engine schema)) table-name (get-table-name database table)] (try (create-metadata-database opts) (create-metadata-table opts) (create-database database opts) (create-table schema opts) (create-index schema opts) (insert-metadata schema opts) (log/info table-name "is created successfully.") (catch SQLException e (if (string/includes? (.getMessage e) "already") (log/warn table-name "already exists.") (throw e)))))) (delete-table [_ {:keys [database table] :as schema} _] (let [table-name (get-table-name database table)] (try (create-metadata-database opts) (create-metadata-table opts) (delete-metadata schema opts) (drop-table schema opts) (log/info table-name "is deleted successfully.") (catch SQLException e (if (or (string/includes? (.getMessage e) "Unknown table") (string/includes? (.getMessage e) "does not exist")) (log/warn table-name "does not exist.") (throw e)))))) (close [_ _]))))
true
(ns scalar-schema.jdbc (:require [clojure.tools.logging :as log] [clojure.string :as string] [scalar-schema.common :as common] [scalar-schema.protocols :as proto] [clojure.java.jdbc :as jdbc]) (:import (java.sql SQLException))) (def ^:private data-type-mapping {:mysql {"INT" "INT" "BIGINT" "BIGINT" "TEXT" "LONGTEXT" "FLOAT" "FLOAT" "DOUBLE" "DOUBLE" "BOOLEAN" "BOOLEAN" "BLOB" "LONGBLOB"} :postgresql {"INT" "INT" "BIGINT" "BIGINT" "TEXT" "TEXT" "FLOAT" "FLOAT" "DOUBLE" "DOUBLE PRECISION" "BOOLEAN" "BOOLEAN" "BLOB" "BYTEA"} :oracle {"INT" "INT" "BIGINT" "NUMBER(19)" "TEXT" "VARCHAR(4000)" "FLOAT" "BINARY_FLOAT" "DOUBLE" "BINARY_DOUBLE" "BOOLEAN" "NUMBER(1)" "BLOB" "BLOB"} :sql-server {"INT" "INT" "BIGINT" "BIGINT" "TEXT" "VARCHAR(8000)" "FLOAT" "FLOAT(24)" "DOUBLE" "FLOAT" "BOOLEAN" "BIT" "BLOB" "VARBINARY(8000)"}}) (def ^:private data-type-mapping-for-key {:mysql {"TEXT" "VARCHAR(64)" "BLOB" "VARBINARY(64)"} :postgresql {"TEXT" "VARCHAR(10485760)"} :oracle {"BLOB" "RAW(2000)"} :sql-server {}}) (defn- key? [column key] (if key (.contains key column) false)) (defn- get-table-name ([database table] (str database \. table)) ([database table {:keys [enclosure-fn]}] (str (enclosure-fn database) \. (enclosure-fn table)))) (defn- get-metadata-table-name [{:keys [prefix] :as opts}] (let [database common/METADATA_DATABASE table common/METADATA_TABLE] (get-table-name (if prefix (str prefix \_ database) database) table opts))) (defn- get-metadata-schema [{:keys [boolean-type]}] {"full_table_name" "VARCHAR(128)" "column_name" "VARCHAR(128)" "data_type" "VARCHAR(20) NOT NULL" "key_type" "VARCHAR(20)" "clustering_order" "VARCHAR(10)" "indexed" (str boolean-type \ "NOT NULL") "index_order" "VARCHAR(10)" "ordinal_position" "INTEGER NOT NULL"}) (defn- make-create-metadata-statement [{:keys [enclosure-fn] :as opts}] (str "CREATE TABLE " (get-metadata-table-name opts) \( (->> (map #(str (enclosure-fn (key %)) \ (val %)) (get-metadata-schema opts)) (string/join \,)) ", PRIMARY KEY (" (->> (map enclosure-fn ["full_table_name" "column_name"]) (string/join \,)) "))")) (defn- create-metadata-table [{:keys [execution-fn] :as opts}] (try (execution-fn (make-create-metadata-statement opts)) (log/info "metatable table is created successfully.") (catch SQLException e (when-not (string/includes? (.getMessage e) "already") (throw e))))) (defn- make-create-database-statement [database {:keys [enclosure-fn]}] (str "CREATE SCHEMA " (enclosure-fn database))) (defn- create-database [database {:keys [rdb-engine execution-fn] :as opts}] (when-not (= rdb-engine :oracle) (try (execution-fn (make-create-database-statement database opts)) (log/info "The database" database "is created successfully.") (catch SQLException e (when-not (or (string/includes? (.getMessage e) "already") (string/includes? (.getMessage e) "database exists")) (throw e)))))) (defn- create-metadata-database [{:keys [prefix] :as opts}] (let [meta-database common/METADATA_DATABASE database (if prefix (str prefix \_ meta-database) meta-database)] (create-database database opts))) (defn- make-create-table-statement [{:keys [database table partition-key clustering-key reordered-columns]} {:keys [enclosure-fn data-type-fn] :as opts}] (let [primary-key (concat partition-key clustering-key)] (str "CREATE TABLE " (get-table-name database table opts) \( (->> (map #(let [column (enclosure-fn (first %)) data-type (data-type-fn (first %) (second %))] (str column \ data-type)) reordered-columns) (string/join \,)) ", PRIMARY KEY (" (->> (map enclosure-fn primary-key) (string/join \,)) "))"))) (defn- create-table [schema {:keys [execution-fn] :as opts}] (execution-fn (make-create-table-statement schema opts))) (defn- make-create-index-statement [{:keys [database table]} {:keys [enclosure-fn] :as opts} indexed-column] (let [index-name (str common/INDEX_NAME_PREFIX \_ database \_ table \_ indexed-column)] (str "CREATE INDEX " (enclosure-fn index-name) " ON " (get-table-name database table opts) \( (enclosure-fn indexed-column) \)))) (defn- create-index [{:keys [secondary-index] :as schema} {:keys [execution-fn] :as opts}] (doall (map #(execution-fn (make-create-index-statement schema opts %)) secondary-index))) (defn- get-key-type [column partition-key clustering-key] (cond (key? column partition-key) "PARTITION" (key? column clustering-key) "CLUSTERING" :else nil)) (defn- secondary-indexed? [column secondary-index] (key? column secondary-index)) (defn- make-insert-metadata-statement [{:keys [database table partition-key clustering-key secondary-index]} {:keys [boolean-value-fn] :as opts} column data-type ordinal-position] (let [key-type (get-key-type column partition-key clustering-key) key-order (if (key? column clustering-key) "'ASC'" "NULL") indexed (boolean-value-fn (secondary-indexed? column secondary-index)) index-order (if (key? column secondary-index) "'ASC'" "NULL")] (str "INSERT INTO " (get-metadata-table-name opts) " VALUES (" "'" (get-table-name database table) "'," "'" column "'," "'" data-type "'," (if key-type (str "'" key-type "'") "NULL") "," key-order "," indexed "," index-order "," ordinal-position ")"))) (defn- insert-metadata [{:keys [reordered-columns] :as schema} {:keys [execution-fn] :as opts}] (loop [[[column data-type] & rest] reordered-columns pos 1] (when column (execution-fn (make-insert-metadata-statement schema opts column (string/upper-case data-type) pos)) (recur rest (inc pos))))) (defn- make-drop-table-statement [{:keys [database table]} opts] (str "DROP TABLE " (get-table-name database table opts))) (defn- drop-table [schema {:keys [execution-fn] :as opts}] (execution-fn (make-drop-table-statement schema opts))) (defn- make-delete-metadata-statement [{:keys [database table]} {:keys [enclosure-fn] :as opts}] (str "DELETE FROM " (get-metadata-table-name opts) " WHERE " (enclosure-fn "full_table_name") " = " "'" (get-table-name database table) "'")) (defn- delete-metadata [schema {:keys [execution-fn] :as opts}] (execution-fn (make-delete-metadata-statement schema opts))) (defn- reorder-columns [{:keys [columns partition-key clustering-key]}] (concat (map #(vector % (get columns %)) partition-key) (map #(vector % (get columns %)) clustering-key) (filter #(not (key? (first %) (concat partition-key clustering-key))) (apply list columns)))) (defn- get-execution-fn [{:keys [jdbc-url user password]}] (fn [statement] (log/debug "Executing" statement) (-> {:connection-uri jdbc-url :user user :password PI:PASSWORD:<PASSWORD>END_PI} (jdbc/execute! [statement])))) (defn- get-rdb-engine [{:keys [jdbc-url]}] (condp #(string/starts-with? %2 %1) jdbc-url "jdbc:mysql:" :mysql "jdbc:postgresql:" :postgresql "jdbc:oracle:" :oracle "jdbc:sqlserver:" :sql-server (throw (ex-info "unknown rdb engine" {})))) (defn- get-enclosure-fn [rdb-engine] #(cond (= rdb-engine :mysql) (str "`" % "`") (= rdb-engine :sql-server) (str "[" % "]") :else (str "\"" % "\""))) (defn- get-boolean-type [rdb-engine] (get (get data-type-mapping rdb-engine) "BOOLEAN")) (defn- get-boolean-value-fn [rdb-engine] #(if (or (= rdb-engine :oracle) (= rdb-engine :sql-server)) (if % "1" "0") (if % "true" "false"))) (defn- get-data-type-fn [rdb-engine {:keys [partition-key clustering-key secondary-index]}] #(let [data-type (string/upper-case %2) mapping (get data-type-mapping rdb-engine) mapping-for-key (get data-type-mapping-for-key rdb-engine)] (if (key? %1 (concat partition-key clustering-key secondary-index)) (get mapping-for-key data-type (get mapping data-type)) (get mapping data-type)))) (defn make-jdbc-operator [opts] (let [rdb-engine (get-rdb-engine opts) opts (assoc opts :execution-fn (get-execution-fn opts) :rdb-engine rdb-engine :enclosure-fn (get-enclosure-fn rdb-engine) :boolean-type (get-boolean-type rdb-engine) :boolean-value-fn (get-boolean-value-fn rdb-engine))] (reify proto/IOperator (create-table [_ {:keys [database table] :as schema} _] (let [schema (assoc schema :reordered-columns (reorder-columns schema)) opts (assoc opts :data-type-fn (get-data-type-fn rdb-engine schema)) table-name (get-table-name database table)] (try (create-metadata-database opts) (create-metadata-table opts) (create-database database opts) (create-table schema opts) (create-index schema opts) (insert-metadata schema opts) (log/info table-name "is created successfully.") (catch SQLException e (if (string/includes? (.getMessage e) "already") (log/warn table-name "already exists.") (throw e)))))) (delete-table [_ {:keys [database table] :as schema} _] (let [table-name (get-table-name database table)] (try (create-metadata-database opts) (create-metadata-table opts) (delete-metadata schema opts) (drop-table schema opts) (log/info table-name "is deleted successfully.") (catch SQLException e (if (or (string/includes? (.getMessage e) "Unknown table") (string/includes? (.getMessage e) "does not exist")) (log/warn table-name "does not exist.") (throw e)))))) (close [_ _]))))
[ { "context": "(is (= {:form/fields {0 {:field/options {0 {:key :t.form.validation/required}}}}}\n (validat", "end": 12131, "score": 0.8008944988250732, "start": 12124, "tag": "KEY", "value": "t.form." }, { "context": " {:key \"bacon\"\n ", "end": 13719, "score": 0.6173669099807739, "start": 13714, "tag": "KEY", "value": "bacon" } ]
src/cljc/rems/common/form.cljc
juholehtonen/rems
0
(ns rems.common.form "Common form utilities shared between UI and API. Includes functions for both forms and form templates." (:require [clojure.string :as str] [clojure.test :refer [deftest is testing]] [medley.core :refer [find-first]] [rems.common.util :refer [getx-in parse-int remove-empty-keys]])) (defn supports-optional? [field] (not (contains? #{:label :header} (:field/type field)))) (defn supports-placeholder? [field] (contains? #{:text :texta :description} (:field/type field))) (defn supports-max-length? [field] (contains? #{:description :text :texta} (:field/type field))) (defn supports-options? [field] (contains? #{:option :multiselect} (:field/type field))) (defn supports-privacy? [field] (not (contains? #{:label :header} (:field/type field)))) (defn supports-visibility? [field] true) ; at the moment all field types (defn- generate-field-ids "Generate a set of unique field ids taking into account what have been given already. Returns in the format [{:field/id \"fld1\"} ...], same as the fields." [fields] (let [generated-ids (map #(str "fld" %) (iterate inc 1)) default-ids (for [id (->> generated-ids (remove (set (map :field/id fields))))] {:field/id id})] default-ids)) (def generate-field-id "Generate a single unique field id taking into account what have been given already. Returns in the format [{:field/id \"fld1\"} ...], same as the fields." (comp first generate-field-ids)) (defn assign-field-ids "Go through the given fields and assign each a unique `:field/id` if it's missing." [fields] (mapv merge (generate-field-ids fields) fields)) (deftest test-assign-field-ids (is (= [] (assign-field-ids []))) (is (= [{:field/id "fld1"} {:field/id "fld2"}] (assign-field-ids [{} {}]))) (is (= [{:field/id "abc"}] (assign-field-ids [{:field/id "abc"}]))) (is (= [{:field/id "abc"} {:field/id "fld2"}] (assign-field-ids [{:field/id "abc"} {}]))) (is (= [{:field/id "fld2"} {:field/id "fld3"}] (assign-field-ids [{:field/id "fld2"} {}]))) (is (= [{:field/id "fld2"} {:field/id "fld1"}] (assign-field-ids [{} {:field/id "fld1"}]))) (is (= [{:field/id "fld2"} {:field/id "fld4"} {:field/id "fld3"}] (assign-field-ids [{:field/id "fld2"} {} {:field/id "fld3"}])))) (defn field-visible? [field values] (let [visibility (:field/visibility field)] (or (nil? visibility) (= :always (:visibility/type visibility)) (and (= :only-if (:visibility/type visibility)) (contains? (set (:visibility/values visibility)) (get values (:field/id (:visibility/field visibility)))))))) (deftest test-field-visible? (is (true? (field-visible? nil nil))) (is (true? (field-visible? {:field/visibility {:visibility/type :always}} nil))) (is (false? (field-visible? {:field/visibility {:visibility/type :only-if :visibility/field {:field/id "1"} :visibility/values ["yes"]}} nil))) (is (false? (field-visible? {:field/visibility {:visibility/type :only-if :visibility/field {:field/id "1"} :visibility/values ["yes"]}} {"1" "no"}))) (is (true? (field-visible? {:field/visibility {:visibility/type :only-if :visibility/field {:field/id "1"} :visibility/values ["yes"]}} {"1" "yes"}))) (is (true? (field-visible? {:field/visibility {:visibility/type :only-if :visibility/field {:field/id "1"} :visibility/values ["yes" "definitely"]}} {"1" "definitely"})))) (defn- validate-text-field [m key] (when (str/blank? (get m key)) {key :t.form.validation/required})) (def field-types #{:attachment :date :description :email :header :label :multiselect :option :text :texta}) (defn- validate-field-type [m] (let [type (keyword (get m :field/type))] (cond (not type) {:field/type :t.form.validation/required} (not (contains? field-types type)) {:field/type :t.form.validation/invalid-value}))) (defn- validate-localized-text-field [m key languages] {key (apply merge (mapv #(validate-text-field (get m key) %) languages))}) (defn- validate-optional-localized-field [m key languages] (let [validated (mapv #(validate-text-field (get m key) %) languages)] ;; partial translations are not allowed (when (not-empty (remove identity validated)) {key (apply merge validated)}))) (def ^:private max-length-range [0 32767]) (defn- validate-max-length [max-length] {:field/max-length (let [parsed (if (int? max-length) max-length (parse-int max-length))] (cond (nil? max-length) nil ; providing max-length is optional (nil? parsed) :t.form.validation/invalid-value (not (<= (first max-length-range) parsed (second max-length-range))) :t.form.validation/invalid-value))}) (defn- validate-option [option id languages] {id (merge (validate-text-field option :key) (validate-localized-text-field option :label languages))}) (defn- validate-options [options languages] {:field/options (apply merge (mapv #(validate-option %1 %2 languages) options (range)))}) (defn- field-option-keys [field] (set (map :key (:field/options field)))) (defn- validate-privacy [field fields] (let [privacy (get :field/privacy field :public)] (when-not (contains? #{:public :private} privacy) {:field/privacy {:privacy/type :t.form.validation/invalid-value}}))) (defn- validate-only-if-visibility [visibility fields] (let [referred-id (get-in visibility [:visibility/field :field/id]) referred-field (find-first (comp #{referred-id} :field/id) fields)] (cond (not (:visibility/field visibility)) {:field/visibility {:visibility/field :t.form.validation/required}} (empty? referred-id) {:field/visibility {:visibility/field :t.form.validation/required}} (not referred-field) {:field/visibility {:visibility/field :t.form.validation/invalid-value}} (not (supports-options? referred-field)) {:field/visibility {:visibility/field :t.form.validation/invalid-value}} (empty? (:visibility/values visibility)) {:field/visibility {:visibility/values :t.form.validation/required}} (some #(not (contains? (field-option-keys referred-field) %)) (:visibility/values visibility)) {:field/visibility {:visibility/values :t.form.validation/invalid-value}}))) (defn- validate-visibility [field fields] (when-let [visibility (:field/visibility field)] (case (:visibility/type visibility) :always nil :only-if (validate-only-if-visibility visibility fields) nil {:field/visibility {:visibility/type :t.form.validation/required}} {:field/visibility {:visibility/type :t.form.validation/invalid-value}}))) (defn- validate-fields [fields languages] (letfn [(validate-field [index field] {index (merge (validate-field-type field) (validate-localized-text-field field :field/title languages) (when (supports-placeholder? field) (validate-optional-localized-field field :field/placeholder languages)) (when (supports-max-length? field) (validate-max-length (:field/max-length field))) (when (supports-options? field) (validate-options (:field/options field) languages)) (when (supports-privacy? field) (validate-privacy field fields)) (when (supports-visibility? field) (validate-visibility field fields)))})] (apply merge (map-indexed validate-field fields)))) (defn- nil-if-empty [m] (when-not (empty? m) m)) (defn validate-form-template [form languages] (-> (merge (validate-text-field form :form/organization) (validate-text-field form :form/title) {:form/fields (validate-fields (:form/fields form) languages)}) remove-empty-keys nil-if-empty)) (deftest validate-form-template-test (let [form {:form/organization "abc" :form/title "the title" :form/fields [{:field/id "fld1" :field/title {:en "en title" :fi "fi title"} :field/optional true :field/type :text :field/max-length "12" :field/placeholder {:en "en placeholder" :fi "fi placeholder"}}]} languages [:en :fi]] (testing "valid form" (is (empty? (validate-form-template form languages)))) (testing "missing organization" (is (= (:form/organization (validate-form-template (assoc-in form [:form/organization] "") languages)) :t.form.validation/required))) (testing "missing title" (is (= (:form/title (validate-form-template (assoc-in form [:form/title] "") languages)) :t.form.validation/required))) (testing "zero fields is ok" (is (empty? (validate-form-template (assoc-in form [:form/fields] []) languages)))) (testing "missing field title" (is (= {:form/fields {0 {:field/title {:en :t.form.validation/required}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/title :en] "") languages) (validate-form-template (update-in form [:form/fields 0 :field/title] dissoc :en) languages))) (is (= {:form/fields {0 {:field/title {:en :t.form.validation/required :fi :t.form.validation/required}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/title] nil) languages)))) (testing "missing field type" (is (= {:form/fields {0 {:field/type :t.form.validation/required}}} (validate-form-template (assoc-in form [:form/fields 0 :field/type] nil) languages)))) (testing "if you use a placeholder, you must fill in all the languages" (is (= {:form/fields {0 {:field/placeholder {:fi :t.form.validation/required}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/placeholder] {:en "en placeholder" :fi ""}) languages) (validate-form-template (assoc-in form [:form/fields 0 :field/placeholder] {:en "en placeholder"}) languages)))) (testing "placeholder is not validated if it is not used" (let [form (-> form (assoc-in [:form/fields 0 :field/type] :label) (assoc-in [:form/fields 0 :field/placeholder :fi] ""))] (is (empty? (validate-form-template form languages))))) (testing "option fields" (let [form (-> form (assoc-in [:form/fields 0 :field/type] :option) (assoc-in [:form/fields 0 :field/options] [{:key "yes" :label {:en "en yes" :fi "fi yes"}} {:key "no" :label {:en "en no" :fi "fi no"}}]))] (testing "valid form" (is (empty? (validate-form-template form languages)))) (testing "missing option key" (is (= {:form/fields {0 {:field/options {0 {:key :t.form.validation/required}}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :key] "") languages) (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :key] nil) languages)))) (testing "... are not validated when options are not used" (let [form (-> form (assoc-in [:form/fields 0 :field/options 0 :key] "") (assoc-in [:form/fields 0 :field/type] :texta))] (is (empty? (validate-form-template form languages))))) (testing "missing option label" (let [empty-label (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :label] {:en "" :fi ""}) languages) nil-label (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :label] nil) languages)] (is (= {:form/fields {0 {:field/options {0 {:label {:en :t.form.validation/required :fi :t.form.validation/required}}}}}} empty-label nil-label)))))) (testing "multiselect fields" (let [form (-> form (assoc-in [:form/fields 0 :field/type] :multiselect) (assoc-in [:form/fields 0 :field/options] [{:key "egg" :label {:en "Egg" :fi "Munaa"}} {:key "bacon" :label {:en "Bacon" :fi "Pekonia"}}]))] (testing "valid form" (is (empty? (validate-form-template form languages)))) (testing "missing option key" (is (= {:form/fields {0 {:field/options {0 {:key :t.form.validation/required}}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :key] "") languages) (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :key] nil) languages)))) (testing "missing option label" (let [empty-label (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :label] {:en "" :fi ""}) languages) nil-label (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :label] nil) languages)] (is (= {:form/fields {0 {:field/options {0 {:label {:en :t.form.validation/required :fi :t.form.validation/required}}}}}} empty-label nil-label)))))) (testing "visible" (let [form (-> form (assoc-in [:form/fields 0 :field/id] "fld1") (assoc-in [:form/fields 0 :field/type] :option) (assoc-in [:form/fields 0 :field/options] [{:key "yes" :label {:en "en yes" :fi "fi yes"}} {:key "no" :label {:en "en no" :fi "fi no"}}]) (assoc-in [:form/fields 1] {:field/id "fld2" :field/title {:en "en title additional" :fi "fi title additional"} :field/optional false :field/type :text :field/max-length "12" :field/placeholder {:en "en placeholder" :fi "fi placeholder"}})) validate-visible (fn [visible] (validate-form-template (assoc-in form [:form/fields 1 :field/visibility] visible) languages))] (testing "invalid type" (is (= {:form/fields {1 {:field/visibility {:visibility/type :t.form.validation/required}}}} (validate-visible {:visibility/type nil}))) (is (= {:form/fields {1 {:field/visibility {:visibility/type :t.form.validation/invalid-value}}}} (validate-visible {:visibility/type :does-not-exist})))) (testing "invalid field" (is (= {:form/fields {1 {:field/visibility {:visibility/field :t.form.validation/required}}}} (validate-visible {:visibility/type :only-if}) (validate-visible {:visibility/type :only-if :visibility/field nil}) (validate-visible {:visibility/type :only-if :visibility/field {}}))) (is (= {:form/fields {1 {:field/visibility {:visibility/field :t.form.validation/invalid-value}}}} (validate-visible {:visibility/type :only-if :visibility/field {:field/id "does-not-exist"}})))) (testing "invalid value" (is (= {:form/fields {1 {:field/visibility {:visibility/values :t.form.validation/required}}}} (validate-visible {:visibility/type :only-if :visibility/field {:field/id "fld1"}}))) (is (= {:form/fields {1 {:field/visibility {:visibility/values :t.form.validation/invalid-value}}}} (validate-visible {:visibility/type :only-if :visibility/field {:field/id "fld1"} :visibility/values ["does-not-exist"]}) (validate-visible {:visibility/type :only-if :visibility/field {:field/id "fld1"} :visibility/values ["yes" "does-not-exist"]})))) (testing "correct data" (is (empty? (validate-visible {:visibility/type :always}))) (is (empty? (validate-visible {:visibility/type :only-if :visibility/field {:field/id "fld1"} :visibility/values ["yes"]}))))))))
69096
(ns rems.common.form "Common form utilities shared between UI and API. Includes functions for both forms and form templates." (:require [clojure.string :as str] [clojure.test :refer [deftest is testing]] [medley.core :refer [find-first]] [rems.common.util :refer [getx-in parse-int remove-empty-keys]])) (defn supports-optional? [field] (not (contains? #{:label :header} (:field/type field)))) (defn supports-placeholder? [field] (contains? #{:text :texta :description} (:field/type field))) (defn supports-max-length? [field] (contains? #{:description :text :texta} (:field/type field))) (defn supports-options? [field] (contains? #{:option :multiselect} (:field/type field))) (defn supports-privacy? [field] (not (contains? #{:label :header} (:field/type field)))) (defn supports-visibility? [field] true) ; at the moment all field types (defn- generate-field-ids "Generate a set of unique field ids taking into account what have been given already. Returns in the format [{:field/id \"fld1\"} ...], same as the fields." [fields] (let [generated-ids (map #(str "fld" %) (iterate inc 1)) default-ids (for [id (->> generated-ids (remove (set (map :field/id fields))))] {:field/id id})] default-ids)) (def generate-field-id "Generate a single unique field id taking into account what have been given already. Returns in the format [{:field/id \"fld1\"} ...], same as the fields." (comp first generate-field-ids)) (defn assign-field-ids "Go through the given fields and assign each a unique `:field/id` if it's missing." [fields] (mapv merge (generate-field-ids fields) fields)) (deftest test-assign-field-ids (is (= [] (assign-field-ids []))) (is (= [{:field/id "fld1"} {:field/id "fld2"}] (assign-field-ids [{} {}]))) (is (= [{:field/id "abc"}] (assign-field-ids [{:field/id "abc"}]))) (is (= [{:field/id "abc"} {:field/id "fld2"}] (assign-field-ids [{:field/id "abc"} {}]))) (is (= [{:field/id "fld2"} {:field/id "fld3"}] (assign-field-ids [{:field/id "fld2"} {}]))) (is (= [{:field/id "fld2"} {:field/id "fld1"}] (assign-field-ids [{} {:field/id "fld1"}]))) (is (= [{:field/id "fld2"} {:field/id "fld4"} {:field/id "fld3"}] (assign-field-ids [{:field/id "fld2"} {} {:field/id "fld3"}])))) (defn field-visible? [field values] (let [visibility (:field/visibility field)] (or (nil? visibility) (= :always (:visibility/type visibility)) (and (= :only-if (:visibility/type visibility)) (contains? (set (:visibility/values visibility)) (get values (:field/id (:visibility/field visibility)))))))) (deftest test-field-visible? (is (true? (field-visible? nil nil))) (is (true? (field-visible? {:field/visibility {:visibility/type :always}} nil))) (is (false? (field-visible? {:field/visibility {:visibility/type :only-if :visibility/field {:field/id "1"} :visibility/values ["yes"]}} nil))) (is (false? (field-visible? {:field/visibility {:visibility/type :only-if :visibility/field {:field/id "1"} :visibility/values ["yes"]}} {"1" "no"}))) (is (true? (field-visible? {:field/visibility {:visibility/type :only-if :visibility/field {:field/id "1"} :visibility/values ["yes"]}} {"1" "yes"}))) (is (true? (field-visible? {:field/visibility {:visibility/type :only-if :visibility/field {:field/id "1"} :visibility/values ["yes" "definitely"]}} {"1" "definitely"})))) (defn- validate-text-field [m key] (when (str/blank? (get m key)) {key :t.form.validation/required})) (def field-types #{:attachment :date :description :email :header :label :multiselect :option :text :texta}) (defn- validate-field-type [m] (let [type (keyword (get m :field/type))] (cond (not type) {:field/type :t.form.validation/required} (not (contains? field-types type)) {:field/type :t.form.validation/invalid-value}))) (defn- validate-localized-text-field [m key languages] {key (apply merge (mapv #(validate-text-field (get m key) %) languages))}) (defn- validate-optional-localized-field [m key languages] (let [validated (mapv #(validate-text-field (get m key) %) languages)] ;; partial translations are not allowed (when (not-empty (remove identity validated)) {key (apply merge validated)}))) (def ^:private max-length-range [0 32767]) (defn- validate-max-length [max-length] {:field/max-length (let [parsed (if (int? max-length) max-length (parse-int max-length))] (cond (nil? max-length) nil ; providing max-length is optional (nil? parsed) :t.form.validation/invalid-value (not (<= (first max-length-range) parsed (second max-length-range))) :t.form.validation/invalid-value))}) (defn- validate-option [option id languages] {id (merge (validate-text-field option :key) (validate-localized-text-field option :label languages))}) (defn- validate-options [options languages] {:field/options (apply merge (mapv #(validate-option %1 %2 languages) options (range)))}) (defn- field-option-keys [field] (set (map :key (:field/options field)))) (defn- validate-privacy [field fields] (let [privacy (get :field/privacy field :public)] (when-not (contains? #{:public :private} privacy) {:field/privacy {:privacy/type :t.form.validation/invalid-value}}))) (defn- validate-only-if-visibility [visibility fields] (let [referred-id (get-in visibility [:visibility/field :field/id]) referred-field (find-first (comp #{referred-id} :field/id) fields)] (cond (not (:visibility/field visibility)) {:field/visibility {:visibility/field :t.form.validation/required}} (empty? referred-id) {:field/visibility {:visibility/field :t.form.validation/required}} (not referred-field) {:field/visibility {:visibility/field :t.form.validation/invalid-value}} (not (supports-options? referred-field)) {:field/visibility {:visibility/field :t.form.validation/invalid-value}} (empty? (:visibility/values visibility)) {:field/visibility {:visibility/values :t.form.validation/required}} (some #(not (contains? (field-option-keys referred-field) %)) (:visibility/values visibility)) {:field/visibility {:visibility/values :t.form.validation/invalid-value}}))) (defn- validate-visibility [field fields] (when-let [visibility (:field/visibility field)] (case (:visibility/type visibility) :always nil :only-if (validate-only-if-visibility visibility fields) nil {:field/visibility {:visibility/type :t.form.validation/required}} {:field/visibility {:visibility/type :t.form.validation/invalid-value}}))) (defn- validate-fields [fields languages] (letfn [(validate-field [index field] {index (merge (validate-field-type field) (validate-localized-text-field field :field/title languages) (when (supports-placeholder? field) (validate-optional-localized-field field :field/placeholder languages)) (when (supports-max-length? field) (validate-max-length (:field/max-length field))) (when (supports-options? field) (validate-options (:field/options field) languages)) (when (supports-privacy? field) (validate-privacy field fields)) (when (supports-visibility? field) (validate-visibility field fields)))})] (apply merge (map-indexed validate-field fields)))) (defn- nil-if-empty [m] (when-not (empty? m) m)) (defn validate-form-template [form languages] (-> (merge (validate-text-field form :form/organization) (validate-text-field form :form/title) {:form/fields (validate-fields (:form/fields form) languages)}) remove-empty-keys nil-if-empty)) (deftest validate-form-template-test (let [form {:form/organization "abc" :form/title "the title" :form/fields [{:field/id "fld1" :field/title {:en "en title" :fi "fi title"} :field/optional true :field/type :text :field/max-length "12" :field/placeholder {:en "en placeholder" :fi "fi placeholder"}}]} languages [:en :fi]] (testing "valid form" (is (empty? (validate-form-template form languages)))) (testing "missing organization" (is (= (:form/organization (validate-form-template (assoc-in form [:form/organization] "") languages)) :t.form.validation/required))) (testing "missing title" (is (= (:form/title (validate-form-template (assoc-in form [:form/title] "") languages)) :t.form.validation/required))) (testing "zero fields is ok" (is (empty? (validate-form-template (assoc-in form [:form/fields] []) languages)))) (testing "missing field title" (is (= {:form/fields {0 {:field/title {:en :t.form.validation/required}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/title :en] "") languages) (validate-form-template (update-in form [:form/fields 0 :field/title] dissoc :en) languages))) (is (= {:form/fields {0 {:field/title {:en :t.form.validation/required :fi :t.form.validation/required}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/title] nil) languages)))) (testing "missing field type" (is (= {:form/fields {0 {:field/type :t.form.validation/required}}} (validate-form-template (assoc-in form [:form/fields 0 :field/type] nil) languages)))) (testing "if you use a placeholder, you must fill in all the languages" (is (= {:form/fields {0 {:field/placeholder {:fi :t.form.validation/required}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/placeholder] {:en "en placeholder" :fi ""}) languages) (validate-form-template (assoc-in form [:form/fields 0 :field/placeholder] {:en "en placeholder"}) languages)))) (testing "placeholder is not validated if it is not used" (let [form (-> form (assoc-in [:form/fields 0 :field/type] :label) (assoc-in [:form/fields 0 :field/placeholder :fi] ""))] (is (empty? (validate-form-template form languages))))) (testing "option fields" (let [form (-> form (assoc-in [:form/fields 0 :field/type] :option) (assoc-in [:form/fields 0 :field/options] [{:key "yes" :label {:en "en yes" :fi "fi yes"}} {:key "no" :label {:en "en no" :fi "fi no"}}]))] (testing "valid form" (is (empty? (validate-form-template form languages)))) (testing "missing option key" (is (= {:form/fields {0 {:field/options {0 {:key :<KEY>validation/required}}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :key] "") languages) (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :key] nil) languages)))) (testing "... are not validated when options are not used" (let [form (-> form (assoc-in [:form/fields 0 :field/options 0 :key] "") (assoc-in [:form/fields 0 :field/type] :texta))] (is (empty? (validate-form-template form languages))))) (testing "missing option label" (let [empty-label (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :label] {:en "" :fi ""}) languages) nil-label (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :label] nil) languages)] (is (= {:form/fields {0 {:field/options {0 {:label {:en :t.form.validation/required :fi :t.form.validation/required}}}}}} empty-label nil-label)))))) (testing "multiselect fields" (let [form (-> form (assoc-in [:form/fields 0 :field/type] :multiselect) (assoc-in [:form/fields 0 :field/options] [{:key "egg" :label {:en "Egg" :fi "Munaa"}} {:key "<KEY>" :label {:en "Bacon" :fi "Pekonia"}}]))] (testing "valid form" (is (empty? (validate-form-template form languages)))) (testing "missing option key" (is (= {:form/fields {0 {:field/options {0 {:key :t.form.validation/required}}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :key] "") languages) (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :key] nil) languages)))) (testing "missing option label" (let [empty-label (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :label] {:en "" :fi ""}) languages) nil-label (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :label] nil) languages)] (is (= {:form/fields {0 {:field/options {0 {:label {:en :t.form.validation/required :fi :t.form.validation/required}}}}}} empty-label nil-label)))))) (testing "visible" (let [form (-> form (assoc-in [:form/fields 0 :field/id] "fld1") (assoc-in [:form/fields 0 :field/type] :option) (assoc-in [:form/fields 0 :field/options] [{:key "yes" :label {:en "en yes" :fi "fi yes"}} {:key "no" :label {:en "en no" :fi "fi no"}}]) (assoc-in [:form/fields 1] {:field/id "fld2" :field/title {:en "en title additional" :fi "fi title additional"} :field/optional false :field/type :text :field/max-length "12" :field/placeholder {:en "en placeholder" :fi "fi placeholder"}})) validate-visible (fn [visible] (validate-form-template (assoc-in form [:form/fields 1 :field/visibility] visible) languages))] (testing "invalid type" (is (= {:form/fields {1 {:field/visibility {:visibility/type :t.form.validation/required}}}} (validate-visible {:visibility/type nil}))) (is (= {:form/fields {1 {:field/visibility {:visibility/type :t.form.validation/invalid-value}}}} (validate-visible {:visibility/type :does-not-exist})))) (testing "invalid field" (is (= {:form/fields {1 {:field/visibility {:visibility/field :t.form.validation/required}}}} (validate-visible {:visibility/type :only-if}) (validate-visible {:visibility/type :only-if :visibility/field nil}) (validate-visible {:visibility/type :only-if :visibility/field {}}))) (is (= {:form/fields {1 {:field/visibility {:visibility/field :t.form.validation/invalid-value}}}} (validate-visible {:visibility/type :only-if :visibility/field {:field/id "does-not-exist"}})))) (testing "invalid value" (is (= {:form/fields {1 {:field/visibility {:visibility/values :t.form.validation/required}}}} (validate-visible {:visibility/type :only-if :visibility/field {:field/id "fld1"}}))) (is (= {:form/fields {1 {:field/visibility {:visibility/values :t.form.validation/invalid-value}}}} (validate-visible {:visibility/type :only-if :visibility/field {:field/id "fld1"} :visibility/values ["does-not-exist"]}) (validate-visible {:visibility/type :only-if :visibility/field {:field/id "fld1"} :visibility/values ["yes" "does-not-exist"]})))) (testing "correct data" (is (empty? (validate-visible {:visibility/type :always}))) (is (empty? (validate-visible {:visibility/type :only-if :visibility/field {:field/id "fld1"} :visibility/values ["yes"]}))))))))
true
(ns rems.common.form "Common form utilities shared between UI and API. Includes functions for both forms and form templates." (:require [clojure.string :as str] [clojure.test :refer [deftest is testing]] [medley.core :refer [find-first]] [rems.common.util :refer [getx-in parse-int remove-empty-keys]])) (defn supports-optional? [field] (not (contains? #{:label :header} (:field/type field)))) (defn supports-placeholder? [field] (contains? #{:text :texta :description} (:field/type field))) (defn supports-max-length? [field] (contains? #{:description :text :texta} (:field/type field))) (defn supports-options? [field] (contains? #{:option :multiselect} (:field/type field))) (defn supports-privacy? [field] (not (contains? #{:label :header} (:field/type field)))) (defn supports-visibility? [field] true) ; at the moment all field types (defn- generate-field-ids "Generate a set of unique field ids taking into account what have been given already. Returns in the format [{:field/id \"fld1\"} ...], same as the fields." [fields] (let [generated-ids (map #(str "fld" %) (iterate inc 1)) default-ids (for [id (->> generated-ids (remove (set (map :field/id fields))))] {:field/id id})] default-ids)) (def generate-field-id "Generate a single unique field id taking into account what have been given already. Returns in the format [{:field/id \"fld1\"} ...], same as the fields." (comp first generate-field-ids)) (defn assign-field-ids "Go through the given fields and assign each a unique `:field/id` if it's missing." [fields] (mapv merge (generate-field-ids fields) fields)) (deftest test-assign-field-ids (is (= [] (assign-field-ids []))) (is (= [{:field/id "fld1"} {:field/id "fld2"}] (assign-field-ids [{} {}]))) (is (= [{:field/id "abc"}] (assign-field-ids [{:field/id "abc"}]))) (is (= [{:field/id "abc"} {:field/id "fld2"}] (assign-field-ids [{:field/id "abc"} {}]))) (is (= [{:field/id "fld2"} {:field/id "fld3"}] (assign-field-ids [{:field/id "fld2"} {}]))) (is (= [{:field/id "fld2"} {:field/id "fld1"}] (assign-field-ids [{} {:field/id "fld1"}]))) (is (= [{:field/id "fld2"} {:field/id "fld4"} {:field/id "fld3"}] (assign-field-ids [{:field/id "fld2"} {} {:field/id "fld3"}])))) (defn field-visible? [field values] (let [visibility (:field/visibility field)] (or (nil? visibility) (= :always (:visibility/type visibility)) (and (= :only-if (:visibility/type visibility)) (contains? (set (:visibility/values visibility)) (get values (:field/id (:visibility/field visibility)))))))) (deftest test-field-visible? (is (true? (field-visible? nil nil))) (is (true? (field-visible? {:field/visibility {:visibility/type :always}} nil))) (is (false? (field-visible? {:field/visibility {:visibility/type :only-if :visibility/field {:field/id "1"} :visibility/values ["yes"]}} nil))) (is (false? (field-visible? {:field/visibility {:visibility/type :only-if :visibility/field {:field/id "1"} :visibility/values ["yes"]}} {"1" "no"}))) (is (true? (field-visible? {:field/visibility {:visibility/type :only-if :visibility/field {:field/id "1"} :visibility/values ["yes"]}} {"1" "yes"}))) (is (true? (field-visible? {:field/visibility {:visibility/type :only-if :visibility/field {:field/id "1"} :visibility/values ["yes" "definitely"]}} {"1" "definitely"})))) (defn- validate-text-field [m key] (when (str/blank? (get m key)) {key :t.form.validation/required})) (def field-types #{:attachment :date :description :email :header :label :multiselect :option :text :texta}) (defn- validate-field-type [m] (let [type (keyword (get m :field/type))] (cond (not type) {:field/type :t.form.validation/required} (not (contains? field-types type)) {:field/type :t.form.validation/invalid-value}))) (defn- validate-localized-text-field [m key languages] {key (apply merge (mapv #(validate-text-field (get m key) %) languages))}) (defn- validate-optional-localized-field [m key languages] (let [validated (mapv #(validate-text-field (get m key) %) languages)] ;; partial translations are not allowed (when (not-empty (remove identity validated)) {key (apply merge validated)}))) (def ^:private max-length-range [0 32767]) (defn- validate-max-length [max-length] {:field/max-length (let [parsed (if (int? max-length) max-length (parse-int max-length))] (cond (nil? max-length) nil ; providing max-length is optional (nil? parsed) :t.form.validation/invalid-value (not (<= (first max-length-range) parsed (second max-length-range))) :t.form.validation/invalid-value))}) (defn- validate-option [option id languages] {id (merge (validate-text-field option :key) (validate-localized-text-field option :label languages))}) (defn- validate-options [options languages] {:field/options (apply merge (mapv #(validate-option %1 %2 languages) options (range)))}) (defn- field-option-keys [field] (set (map :key (:field/options field)))) (defn- validate-privacy [field fields] (let [privacy (get :field/privacy field :public)] (when-not (contains? #{:public :private} privacy) {:field/privacy {:privacy/type :t.form.validation/invalid-value}}))) (defn- validate-only-if-visibility [visibility fields] (let [referred-id (get-in visibility [:visibility/field :field/id]) referred-field (find-first (comp #{referred-id} :field/id) fields)] (cond (not (:visibility/field visibility)) {:field/visibility {:visibility/field :t.form.validation/required}} (empty? referred-id) {:field/visibility {:visibility/field :t.form.validation/required}} (not referred-field) {:field/visibility {:visibility/field :t.form.validation/invalid-value}} (not (supports-options? referred-field)) {:field/visibility {:visibility/field :t.form.validation/invalid-value}} (empty? (:visibility/values visibility)) {:field/visibility {:visibility/values :t.form.validation/required}} (some #(not (contains? (field-option-keys referred-field) %)) (:visibility/values visibility)) {:field/visibility {:visibility/values :t.form.validation/invalid-value}}))) (defn- validate-visibility [field fields] (when-let [visibility (:field/visibility field)] (case (:visibility/type visibility) :always nil :only-if (validate-only-if-visibility visibility fields) nil {:field/visibility {:visibility/type :t.form.validation/required}} {:field/visibility {:visibility/type :t.form.validation/invalid-value}}))) (defn- validate-fields [fields languages] (letfn [(validate-field [index field] {index (merge (validate-field-type field) (validate-localized-text-field field :field/title languages) (when (supports-placeholder? field) (validate-optional-localized-field field :field/placeholder languages)) (when (supports-max-length? field) (validate-max-length (:field/max-length field))) (when (supports-options? field) (validate-options (:field/options field) languages)) (when (supports-privacy? field) (validate-privacy field fields)) (when (supports-visibility? field) (validate-visibility field fields)))})] (apply merge (map-indexed validate-field fields)))) (defn- nil-if-empty [m] (when-not (empty? m) m)) (defn validate-form-template [form languages] (-> (merge (validate-text-field form :form/organization) (validate-text-field form :form/title) {:form/fields (validate-fields (:form/fields form) languages)}) remove-empty-keys nil-if-empty)) (deftest validate-form-template-test (let [form {:form/organization "abc" :form/title "the title" :form/fields [{:field/id "fld1" :field/title {:en "en title" :fi "fi title"} :field/optional true :field/type :text :field/max-length "12" :field/placeholder {:en "en placeholder" :fi "fi placeholder"}}]} languages [:en :fi]] (testing "valid form" (is (empty? (validate-form-template form languages)))) (testing "missing organization" (is (= (:form/organization (validate-form-template (assoc-in form [:form/organization] "") languages)) :t.form.validation/required))) (testing "missing title" (is (= (:form/title (validate-form-template (assoc-in form [:form/title] "") languages)) :t.form.validation/required))) (testing "zero fields is ok" (is (empty? (validate-form-template (assoc-in form [:form/fields] []) languages)))) (testing "missing field title" (is (= {:form/fields {0 {:field/title {:en :t.form.validation/required}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/title :en] "") languages) (validate-form-template (update-in form [:form/fields 0 :field/title] dissoc :en) languages))) (is (= {:form/fields {0 {:field/title {:en :t.form.validation/required :fi :t.form.validation/required}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/title] nil) languages)))) (testing "missing field type" (is (= {:form/fields {0 {:field/type :t.form.validation/required}}} (validate-form-template (assoc-in form [:form/fields 0 :field/type] nil) languages)))) (testing "if you use a placeholder, you must fill in all the languages" (is (= {:form/fields {0 {:field/placeholder {:fi :t.form.validation/required}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/placeholder] {:en "en placeholder" :fi ""}) languages) (validate-form-template (assoc-in form [:form/fields 0 :field/placeholder] {:en "en placeholder"}) languages)))) (testing "placeholder is not validated if it is not used" (let [form (-> form (assoc-in [:form/fields 0 :field/type] :label) (assoc-in [:form/fields 0 :field/placeholder :fi] ""))] (is (empty? (validate-form-template form languages))))) (testing "option fields" (let [form (-> form (assoc-in [:form/fields 0 :field/type] :option) (assoc-in [:form/fields 0 :field/options] [{:key "yes" :label {:en "en yes" :fi "fi yes"}} {:key "no" :label {:en "en no" :fi "fi no"}}]))] (testing "valid form" (is (empty? (validate-form-template form languages)))) (testing "missing option key" (is (= {:form/fields {0 {:field/options {0 {:key :PI:KEY:<KEY>END_PIvalidation/required}}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :key] "") languages) (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :key] nil) languages)))) (testing "... are not validated when options are not used" (let [form (-> form (assoc-in [:form/fields 0 :field/options 0 :key] "") (assoc-in [:form/fields 0 :field/type] :texta))] (is (empty? (validate-form-template form languages))))) (testing "missing option label" (let [empty-label (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :label] {:en "" :fi ""}) languages) nil-label (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :label] nil) languages)] (is (= {:form/fields {0 {:field/options {0 {:label {:en :t.form.validation/required :fi :t.form.validation/required}}}}}} empty-label nil-label)))))) (testing "multiselect fields" (let [form (-> form (assoc-in [:form/fields 0 :field/type] :multiselect) (assoc-in [:form/fields 0 :field/options] [{:key "egg" :label {:en "Egg" :fi "Munaa"}} {:key "PI:KEY:<KEY>END_PI" :label {:en "Bacon" :fi "Pekonia"}}]))] (testing "valid form" (is (empty? (validate-form-template form languages)))) (testing "missing option key" (is (= {:form/fields {0 {:field/options {0 {:key :t.form.validation/required}}}}} (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :key] "") languages) (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :key] nil) languages)))) (testing "missing option label" (let [empty-label (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :label] {:en "" :fi ""}) languages) nil-label (validate-form-template (assoc-in form [:form/fields 0 :field/options 0 :label] nil) languages)] (is (= {:form/fields {0 {:field/options {0 {:label {:en :t.form.validation/required :fi :t.form.validation/required}}}}}} empty-label nil-label)))))) (testing "visible" (let [form (-> form (assoc-in [:form/fields 0 :field/id] "fld1") (assoc-in [:form/fields 0 :field/type] :option) (assoc-in [:form/fields 0 :field/options] [{:key "yes" :label {:en "en yes" :fi "fi yes"}} {:key "no" :label {:en "en no" :fi "fi no"}}]) (assoc-in [:form/fields 1] {:field/id "fld2" :field/title {:en "en title additional" :fi "fi title additional"} :field/optional false :field/type :text :field/max-length "12" :field/placeholder {:en "en placeholder" :fi "fi placeholder"}})) validate-visible (fn [visible] (validate-form-template (assoc-in form [:form/fields 1 :field/visibility] visible) languages))] (testing "invalid type" (is (= {:form/fields {1 {:field/visibility {:visibility/type :t.form.validation/required}}}} (validate-visible {:visibility/type nil}))) (is (= {:form/fields {1 {:field/visibility {:visibility/type :t.form.validation/invalid-value}}}} (validate-visible {:visibility/type :does-not-exist})))) (testing "invalid field" (is (= {:form/fields {1 {:field/visibility {:visibility/field :t.form.validation/required}}}} (validate-visible {:visibility/type :only-if}) (validate-visible {:visibility/type :only-if :visibility/field nil}) (validate-visible {:visibility/type :only-if :visibility/field {}}))) (is (= {:form/fields {1 {:field/visibility {:visibility/field :t.form.validation/invalid-value}}}} (validate-visible {:visibility/type :only-if :visibility/field {:field/id "does-not-exist"}})))) (testing "invalid value" (is (= {:form/fields {1 {:field/visibility {:visibility/values :t.form.validation/required}}}} (validate-visible {:visibility/type :only-if :visibility/field {:field/id "fld1"}}))) (is (= {:form/fields {1 {:field/visibility {:visibility/values :t.form.validation/invalid-value}}}} (validate-visible {:visibility/type :only-if :visibility/field {:field/id "fld1"} :visibility/values ["does-not-exist"]}) (validate-visible {:visibility/type :only-if :visibility/field {:field/id "fld1"} :visibility/values ["yes" "does-not-exist"]})))) (testing "correct data" (is (empty? (validate-visible {:visibility/type :always}))) (is (empty? (validate-visible {:visibility/type :only-if :visibility/field {:field/id "fld1"} :visibility/values ["yes"]}))))))))
[ { "context": ";;\n;;\n;; Copyright 2014-2015 Netflix, Inc.\n;;\n;; Licensed under the Apache License", "end": 37, "score": 0.7334020137786865, "start": 30, "tag": "NAME", "value": "Netflix" } ]
pigpen-parquet/src/main/clojure/pigpen/local/parquet.clj
ombagus/Netflix
327
;; ;; ;; Copyright 2014-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.local.parquet (:require [pigpen.local] [pigpen.hadoop] [pigpen.parquet.core :as pq]) (:import [parquet.tools.read SimpleRecord SimpleRecord$NameValue] [pigpen.hadoop InputFormatLoader OutputFormatStorage] [parquet.hadoop ParquetInputFormat ParquetOutputFormat])) (defmethod pigpen.local/load :parquet [{:keys [location fields]}] (let [field-names (into {} (map (juxt name identity) fields))] (InputFormatLoader. (ParquetInputFormat.) {ParquetInputFormat/READ_SUPPORT_CLASS "parquet.tools.read.SimpleReadSupport"} location (fn [^SimpleRecord value] (->> value (.getValues) (map (fn [^SimpleRecord$NameValue nv] [(field-names (.getName nv)) (.getValue nv)])) (into {})))))) (defmethod pigpen.local/store :parquet [{:keys [location opts]}] (OutputFormatStorage. (ParquetOutputFormat.) {ParquetOutputFormat/WRITE_SUPPORT_CLASS "pigpen.parquet.PigPenParquetWriteSupport" "schema" (str (:schema opts))} location))
106011
;; ;; ;; Copyright 2014-2015 <NAME>, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.local.parquet (:require [pigpen.local] [pigpen.hadoop] [pigpen.parquet.core :as pq]) (:import [parquet.tools.read SimpleRecord SimpleRecord$NameValue] [pigpen.hadoop InputFormatLoader OutputFormatStorage] [parquet.hadoop ParquetInputFormat ParquetOutputFormat])) (defmethod pigpen.local/load :parquet [{:keys [location fields]}] (let [field-names (into {} (map (juxt name identity) fields))] (InputFormatLoader. (ParquetInputFormat.) {ParquetInputFormat/READ_SUPPORT_CLASS "parquet.tools.read.SimpleReadSupport"} location (fn [^SimpleRecord value] (->> value (.getValues) (map (fn [^SimpleRecord$NameValue nv] [(field-names (.getName nv)) (.getValue nv)])) (into {})))))) (defmethod pigpen.local/store :parquet [{:keys [location opts]}] (OutputFormatStorage. (ParquetOutputFormat.) {ParquetOutputFormat/WRITE_SUPPORT_CLASS "pigpen.parquet.PigPenParquetWriteSupport" "schema" (str (:schema opts))} location))
true
;; ;; ;; Copyright 2014-2015 PI:NAME:<NAME>END_PI, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.local.parquet (:require [pigpen.local] [pigpen.hadoop] [pigpen.parquet.core :as pq]) (:import [parquet.tools.read SimpleRecord SimpleRecord$NameValue] [pigpen.hadoop InputFormatLoader OutputFormatStorage] [parquet.hadoop ParquetInputFormat ParquetOutputFormat])) (defmethod pigpen.local/load :parquet [{:keys [location fields]}] (let [field-names (into {} (map (juxt name identity) fields))] (InputFormatLoader. (ParquetInputFormat.) {ParquetInputFormat/READ_SUPPORT_CLASS "parquet.tools.read.SimpleReadSupport"} location (fn [^SimpleRecord value] (->> value (.getValues) (map (fn [^SimpleRecord$NameValue nv] [(field-names (.getName nv)) (.getValue nv)])) (into {})))))) (defmethod pigpen.local/store :parquet [{:keys [location opts]}] (OutputFormatStorage. (ParquetOutputFormat.) {ParquetOutputFormat/WRITE_SUPPORT_CLASS "pigpen.parquet.PigPenParquetWriteSupport" "schema" (str (:schema opts))} location))
[ { "context": ";; Copyright (c) 2015-2018 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redi", "end": 40, "score": 0.999883770942688, "start": 27, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright (c) 2015-2018 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redistribution and", "end": 54, "score": 0.9999322891235352, "start": 42, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
src/octet/spec/reference.cljc
allumbra/octet
0
;; Copyright (c) 2015-2018 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 octet.spec.reference "Spec types for arbitrary length byte arrays/strings with a length reference." (:require [octet.buffer :as buffer] [octet.spec :as spec] [octet.spec.basic :as basic-spec] [octet.spec.string :as string-spec])) (defn- ref-size [type data] (cond (satisfies? spec/ISpecDynamicSize type) (spec/size* type data) (satisfies? spec/ISpecSize type) (spec/size type) :else (throw (ex-info "Unexpected type" {:type type})))) (defn- coerce-types "to make it terser to handle both maps (assoc spec) and seq/vector (indexed spec), we coerce the seq/vector types to maps where the keys are indexes" [types] (cond (map? types) types (or (seq? types) (vector? types)) (apply array-map (interleave (range) types)) :else (throw (ex-info "invalid type structure, not map, seq or vector" {:type-structure types})))) (defn- ref-len-offset "for ref-xxxx specs, calculate the byte offset of the spec containing the length, i.e. (spec :a (int16) :b (int16) c: (ref-string* :b)) would cause this method to be called with :b (since the ref-string has a :b reference as its length) and should then return 2 as the second int16 is at byte offset 2" [ref-kw-or-index types data] (reduce-kv (fn [acc kw-or-index type] (if (= ref-kw-or-index kw-or-index) (reduced acc) (+ acc (ref-size type (get data kw-or-index))))) 0 types)) (defn- ref-write-length [type buff offset length] (cond (identical? basic-spec/int16 type) (buffer/write-short buff offset length) (identical? basic-spec/int32 type) (buffer/write-int buff offset length) (identical? basic-spec/int64 type) (buffer/write-long buff offset length) (identical? basic-spec/int64 type) (buffer/write-long buff offset length) (identical? basic-spec/uint16 type) (buffer/write-ushort buff offset length) (identical? basic-spec/uint32 type) (buffer/write-uint buff offset length) (identical? basic-spec/uint64 type) (buffer/write-ulong buff offset length) (identical? basic-spec/byte type) (buffer/write-byte buff offset length) :else (throw (ex-info "Invalid reference type: should be int16, int32, int64 and unsigned variants" {})))) (defn- ref-write "write a ref spec, will also write the length to the length spec" [ref-kw-or-index buff pos value types data] (let [input (if (string? value) (string-spec/string->bytes value) value) length (count input) types (coerce-types types) len-offset (ref-len-offset ref-kw-or-index types data) len-type (get types ref-kw-or-index)] (ref-write-length len-type buff len-offset length) (buffer/write-bytes buff pos length input) (+ length))) (defn- ref-read "read ref spec, will read the length from the length spec" [ref-kw-or-index buff pos parent] (let [datasize (cond (map? parent) (ref-kw-or-index parent) (or (seq? parent) (vector? parent)) (get parent ref-kw-or-index) :else (throw (ex-info (str "bad ref-string/ref-bytes length reference - " ref-kw-or-index) {:length-kw ref-kw-or-index :data-read parent}))) ;; _ (println "FOFOFO:" parent ref-kw-or-index) data (buffer/read-bytes buff pos datasize)] [datasize data])) (defn ref-bytes "create a dynamic length byte array where the length of the byte array is stored in another spec within the containing indexed spec or associative spec. Example usages: (spec (int16) (int16) (ref-bytes* 1)) (spec :a (int16) :b (int32) (ref-bytes* :b)) where the first example would store the length of the byte array in the second int16 and the second example would store the length of the byte array in the int32 at key :b." [ref-kw-or-index] (reify #?@(:clj [clojure.lang.IFn (invoke [s] s)] :cljs [cljs.core/IFn (-invoke [s] s)]) spec/ISpecDynamicSize (size* [_ data] (count data)) spec/ISpecWithRef (read* [_ buff pos parent] (ref-read ref-kw-or-index buff pos parent)) (write* [_ buff pos value types data] (ref-write ref-kw-or-index buff pos value types data)))) (defn ref-string "create a dynamic length string where the length of the string is stored in another spec within the containing indexed spec or associative spec. Example usages: (spec (int16) (int16) (ref-string* 1)) (spec :a (int16) :b (int32) (ref-string* :b)) where the first example would store the length of the string in the second int16 and the second example would store the length of the string in the int32 at key :b." [ref-kw-or-index] (reify #?@(:clj [clojure.lang.IFn (invoke [s] s)] :cljs [cljs.core/IFn (-invoke [s] s)]) spec/ISpecDynamicSize (size* [_ data] (let [data (string-spec/string->bytes data)] (count data))) spec/ISpecWithRef (read* [_ buff pos parent] (let [[datasize bytes] (ref-read ref-kw-or-index buff pos parent)] [datasize (string-spec/bytes->string bytes datasize)])) (write* [_ buff pos value types data] (ref-write ref-kw-or-index buff pos value types data))))
31851
;; Copyright (c) 2015-2018 <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 octet.spec.reference "Spec types for arbitrary length byte arrays/strings with a length reference." (:require [octet.buffer :as buffer] [octet.spec :as spec] [octet.spec.basic :as basic-spec] [octet.spec.string :as string-spec])) (defn- ref-size [type data] (cond (satisfies? spec/ISpecDynamicSize type) (spec/size* type data) (satisfies? spec/ISpecSize type) (spec/size type) :else (throw (ex-info "Unexpected type" {:type type})))) (defn- coerce-types "to make it terser to handle both maps (assoc spec) and seq/vector (indexed spec), we coerce the seq/vector types to maps where the keys are indexes" [types] (cond (map? types) types (or (seq? types) (vector? types)) (apply array-map (interleave (range) types)) :else (throw (ex-info "invalid type structure, not map, seq or vector" {:type-structure types})))) (defn- ref-len-offset "for ref-xxxx specs, calculate the byte offset of the spec containing the length, i.e. (spec :a (int16) :b (int16) c: (ref-string* :b)) would cause this method to be called with :b (since the ref-string has a :b reference as its length) and should then return 2 as the second int16 is at byte offset 2" [ref-kw-or-index types data] (reduce-kv (fn [acc kw-or-index type] (if (= ref-kw-or-index kw-or-index) (reduced acc) (+ acc (ref-size type (get data kw-or-index))))) 0 types)) (defn- ref-write-length [type buff offset length] (cond (identical? basic-spec/int16 type) (buffer/write-short buff offset length) (identical? basic-spec/int32 type) (buffer/write-int buff offset length) (identical? basic-spec/int64 type) (buffer/write-long buff offset length) (identical? basic-spec/int64 type) (buffer/write-long buff offset length) (identical? basic-spec/uint16 type) (buffer/write-ushort buff offset length) (identical? basic-spec/uint32 type) (buffer/write-uint buff offset length) (identical? basic-spec/uint64 type) (buffer/write-ulong buff offset length) (identical? basic-spec/byte type) (buffer/write-byte buff offset length) :else (throw (ex-info "Invalid reference type: should be int16, int32, int64 and unsigned variants" {})))) (defn- ref-write "write a ref spec, will also write the length to the length spec" [ref-kw-or-index buff pos value types data] (let [input (if (string? value) (string-spec/string->bytes value) value) length (count input) types (coerce-types types) len-offset (ref-len-offset ref-kw-or-index types data) len-type (get types ref-kw-or-index)] (ref-write-length len-type buff len-offset length) (buffer/write-bytes buff pos length input) (+ length))) (defn- ref-read "read ref spec, will read the length from the length spec" [ref-kw-or-index buff pos parent] (let [datasize (cond (map? parent) (ref-kw-or-index parent) (or (seq? parent) (vector? parent)) (get parent ref-kw-or-index) :else (throw (ex-info (str "bad ref-string/ref-bytes length reference - " ref-kw-or-index) {:length-kw ref-kw-or-index :data-read parent}))) ;; _ (println "FOFOFO:" parent ref-kw-or-index) data (buffer/read-bytes buff pos datasize)] [datasize data])) (defn ref-bytes "create a dynamic length byte array where the length of the byte array is stored in another spec within the containing indexed spec or associative spec. Example usages: (spec (int16) (int16) (ref-bytes* 1)) (spec :a (int16) :b (int32) (ref-bytes* :b)) where the first example would store the length of the byte array in the second int16 and the second example would store the length of the byte array in the int32 at key :b." [ref-kw-or-index] (reify #?@(:clj [clojure.lang.IFn (invoke [s] s)] :cljs [cljs.core/IFn (-invoke [s] s)]) spec/ISpecDynamicSize (size* [_ data] (count data)) spec/ISpecWithRef (read* [_ buff pos parent] (ref-read ref-kw-or-index buff pos parent)) (write* [_ buff pos value types data] (ref-write ref-kw-or-index buff pos value types data)))) (defn ref-string "create a dynamic length string where the length of the string is stored in another spec within the containing indexed spec or associative spec. Example usages: (spec (int16) (int16) (ref-string* 1)) (spec :a (int16) :b (int32) (ref-string* :b)) where the first example would store the length of the string in the second int16 and the second example would store the length of the string in the int32 at key :b." [ref-kw-or-index] (reify #?@(:clj [clojure.lang.IFn (invoke [s] s)] :cljs [cljs.core/IFn (-invoke [s] s)]) spec/ISpecDynamicSize (size* [_ data] (let [data (string-spec/string->bytes data)] (count data))) spec/ISpecWithRef (read* [_ buff pos parent] (let [[datasize bytes] (ref-read ref-kw-or-index buff pos parent)] [datasize (string-spec/bytes->string bytes datasize)])) (write* [_ buff pos value types data] (ref-write ref-kw-or-index buff pos value types data))))
true
;; Copyright (c) 2015-2018 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 octet.spec.reference "Spec types for arbitrary length byte arrays/strings with a length reference." (:require [octet.buffer :as buffer] [octet.spec :as spec] [octet.spec.basic :as basic-spec] [octet.spec.string :as string-spec])) (defn- ref-size [type data] (cond (satisfies? spec/ISpecDynamicSize type) (spec/size* type data) (satisfies? spec/ISpecSize type) (spec/size type) :else (throw (ex-info "Unexpected type" {:type type})))) (defn- coerce-types "to make it terser to handle both maps (assoc spec) and seq/vector (indexed spec), we coerce the seq/vector types to maps where the keys are indexes" [types] (cond (map? types) types (or (seq? types) (vector? types)) (apply array-map (interleave (range) types)) :else (throw (ex-info "invalid type structure, not map, seq or vector" {:type-structure types})))) (defn- ref-len-offset "for ref-xxxx specs, calculate the byte offset of the spec containing the length, i.e. (spec :a (int16) :b (int16) c: (ref-string* :b)) would cause this method to be called with :b (since the ref-string has a :b reference as its length) and should then return 2 as the second int16 is at byte offset 2" [ref-kw-or-index types data] (reduce-kv (fn [acc kw-or-index type] (if (= ref-kw-or-index kw-or-index) (reduced acc) (+ acc (ref-size type (get data kw-or-index))))) 0 types)) (defn- ref-write-length [type buff offset length] (cond (identical? basic-spec/int16 type) (buffer/write-short buff offset length) (identical? basic-spec/int32 type) (buffer/write-int buff offset length) (identical? basic-spec/int64 type) (buffer/write-long buff offset length) (identical? basic-spec/int64 type) (buffer/write-long buff offset length) (identical? basic-spec/uint16 type) (buffer/write-ushort buff offset length) (identical? basic-spec/uint32 type) (buffer/write-uint buff offset length) (identical? basic-spec/uint64 type) (buffer/write-ulong buff offset length) (identical? basic-spec/byte type) (buffer/write-byte buff offset length) :else (throw (ex-info "Invalid reference type: should be int16, int32, int64 and unsigned variants" {})))) (defn- ref-write "write a ref spec, will also write the length to the length spec" [ref-kw-or-index buff pos value types data] (let [input (if (string? value) (string-spec/string->bytes value) value) length (count input) types (coerce-types types) len-offset (ref-len-offset ref-kw-or-index types data) len-type (get types ref-kw-or-index)] (ref-write-length len-type buff len-offset length) (buffer/write-bytes buff pos length input) (+ length))) (defn- ref-read "read ref spec, will read the length from the length spec" [ref-kw-or-index buff pos parent] (let [datasize (cond (map? parent) (ref-kw-or-index parent) (or (seq? parent) (vector? parent)) (get parent ref-kw-or-index) :else (throw (ex-info (str "bad ref-string/ref-bytes length reference - " ref-kw-or-index) {:length-kw ref-kw-or-index :data-read parent}))) ;; _ (println "FOFOFO:" parent ref-kw-or-index) data (buffer/read-bytes buff pos datasize)] [datasize data])) (defn ref-bytes "create a dynamic length byte array where the length of the byte array is stored in another spec within the containing indexed spec or associative spec. Example usages: (spec (int16) (int16) (ref-bytes* 1)) (spec :a (int16) :b (int32) (ref-bytes* :b)) where the first example would store the length of the byte array in the second int16 and the second example would store the length of the byte array in the int32 at key :b." [ref-kw-or-index] (reify #?@(:clj [clojure.lang.IFn (invoke [s] s)] :cljs [cljs.core/IFn (-invoke [s] s)]) spec/ISpecDynamicSize (size* [_ data] (count data)) spec/ISpecWithRef (read* [_ buff pos parent] (ref-read ref-kw-or-index buff pos parent)) (write* [_ buff pos value types data] (ref-write ref-kw-or-index buff pos value types data)))) (defn ref-string "create a dynamic length string where the length of the string is stored in another spec within the containing indexed spec or associative spec. Example usages: (spec (int16) (int16) (ref-string* 1)) (spec :a (int16) :b (int32) (ref-string* :b)) where the first example would store the length of the string in the second int16 and the second example would store the length of the string in the int32 at key :b." [ref-kw-or-index] (reify #?@(:clj [clojure.lang.IFn (invoke [s] s)] :cljs [cljs.core/IFn (-invoke [s] s)]) spec/ISpecDynamicSize (size* [_ data] (let [data (string-spec/string->bytes data)] (count data))) spec/ISpecWithRef (read* [_ buff pos parent] (let [[datasize bytes] (ref-read ref-kw-or-index buff pos parent)] [datasize (string-spec/bytes->string bytes datasize)])) (write* [_ buff pos value types data] (ref-write ref-kw-or-index buff pos value types data))))
[ { "context": ";; Original author Hirokuni Kim\n;; Modifications by Kevin Kredit\n;; Licensed unde", "end": 31, "score": 0.999680757522583, "start": 19, "tag": "NAME", "value": "Hirokuni Kim" }, { "context": "; Original author Hirokuni Kim\n;; Modifications by Kevin Kredit\n;; Licensed under https://www.apache.org/licenses", "end": 64, "score": 0.9998758435249329, "start": 52, "tag": "NAME", "value": "Kevin Kredit" } ]
clojure/p21-recur/src/p21_recur/core.clj
kkredit/pl-study
0
;; Original author Hirokuni Kim ;; Modifications by Kevin Kredit ;; Licensed under https://www.apache.org/licenses/LICENSE-2.0 ;; See https://kimh.github.io/clojure-by-example/#recur (ns p21-recur.core) (defn fibo-recursive [n] (if (or (= n 0) (= n 1)) n (+ (fibo-recursive (- n 1)) (fibo-recursive (- n 2))))) (defn fibo-recur [iteration] (let [fibo (fn [one two n] (if (= iteration n) one (recur two (+ one two) (inc n))))] ;; 0N 1N are bigint literals. See Bigint section ;; We need to use bigint to avoid StackOverflow to do the addition of big Fibonacci numbers ;; demonstrated below. (fibo 0N 1N 0))) ; (defn fibo-loop-recur [current next iteration] ; (if (= 0 iteration) ; current ; (+ 0 ; (recur next (+ current next) (dec iteration))))) ; ^^ CompilerException java.lang.UnsupportedOperationException: Can only recur from tail position (defn count-down [result n] (if (= n 0) result (recur (conj result n) (dec n)))) (defn -main "Main" [] (println (fibo-recursive 0)) (println (fibo-recursive 6)) (println (fibo-recur 6)) ; (println (fibo-recursive 100000)) ; StackOverflowError (println (fibo-recur 100000)) ; no stack overflow, just slow (println (count-down [] 5)) )
111114
;; Original author <NAME> ;; Modifications by <NAME> ;; Licensed under https://www.apache.org/licenses/LICENSE-2.0 ;; See https://kimh.github.io/clojure-by-example/#recur (ns p21-recur.core) (defn fibo-recursive [n] (if (or (= n 0) (= n 1)) n (+ (fibo-recursive (- n 1)) (fibo-recursive (- n 2))))) (defn fibo-recur [iteration] (let [fibo (fn [one two n] (if (= iteration n) one (recur two (+ one two) (inc n))))] ;; 0N 1N are bigint literals. See Bigint section ;; We need to use bigint to avoid StackOverflow to do the addition of big Fibonacci numbers ;; demonstrated below. (fibo 0N 1N 0))) ; (defn fibo-loop-recur [current next iteration] ; (if (= 0 iteration) ; current ; (+ 0 ; (recur next (+ current next) (dec iteration))))) ; ^^ CompilerException java.lang.UnsupportedOperationException: Can only recur from tail position (defn count-down [result n] (if (= n 0) result (recur (conj result n) (dec n)))) (defn -main "Main" [] (println (fibo-recursive 0)) (println (fibo-recursive 6)) (println (fibo-recur 6)) ; (println (fibo-recursive 100000)) ; StackOverflowError (println (fibo-recur 100000)) ; no stack overflow, just slow (println (count-down [] 5)) )
true
;; Original author PI:NAME:<NAME>END_PI ;; Modifications by PI:NAME:<NAME>END_PI ;; Licensed under https://www.apache.org/licenses/LICENSE-2.0 ;; See https://kimh.github.io/clojure-by-example/#recur (ns p21-recur.core) (defn fibo-recursive [n] (if (or (= n 0) (= n 1)) n (+ (fibo-recursive (- n 1)) (fibo-recursive (- n 2))))) (defn fibo-recur [iteration] (let [fibo (fn [one two n] (if (= iteration n) one (recur two (+ one two) (inc n))))] ;; 0N 1N are bigint literals. See Bigint section ;; We need to use bigint to avoid StackOverflow to do the addition of big Fibonacci numbers ;; demonstrated below. (fibo 0N 1N 0))) ; (defn fibo-loop-recur [current next iteration] ; (if (= 0 iteration) ; current ; (+ 0 ; (recur next (+ current next) (dec iteration))))) ; ^^ CompilerException java.lang.UnsupportedOperationException: Can only recur from tail position (defn count-down [result n] (if (= n 0) result (recur (conj result n) (dec n)))) (defn -main "Main" [] (println (fibo-recursive 0)) (println (fibo-recursive 6)) (println (fibo-recur 6)) ; (println (fibo-recursive 100000)) ; StackOverflowError (println (fibo-recur 100000)) ; no stack overflow, just slow (println (count-down [] 5)) )
[ { "context": "re)\n\n(deftest catalogue-api-test\n (let [api-key \"42\"\n user-id \"alice\"]\n (let [data (-> (req", "end": 330, "score": 0.9990160465240479, "start": 328, "tag": "KEY", "value": "42" }, { "context": "ue-api-test\n (let [api-key \"42\"\n user-id \"alice\"]\n (let [data (-> (request :get \"/api/catalogu", "end": 354, "score": 0.9993407130241394, "start": 349, "tag": "USERNAME", "value": "alice" } ]
test/clj/rems/test/api/catalogue.clj
secureb2share/secureb2share-rems
0
(ns ^:integration rems.test.api.catalogue (:require [clojure.string :as str] [clojure.test :refer :all] [rems.handler :refer [app]] [rems.test.api :refer :all] [ring.mock.request :refer :all])) (use-fixtures :once api-fixture) (deftest catalogue-api-test (let [api-key "42" user-id "alice"] (let [data (-> (request :get "/api/catalogue/") (authenticate api-key user-id) app read-body) item (first data)] (is (str/starts-with? (:resid item) "urn:"))))) (deftest catalogue-api-security-test (testing "listing without authentication" (let [response (-> (request :get (str "/api/catalogue")) app) body (read-body response)] (is (response-is-unauthorized? response)) (is (= "unauthorized" body)))) (testing "listing with wrong API-Key" (is (= "invalid api key" (-> (request :get (str "/api/catalogue")) (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") app (read-body))))))
106093
(ns ^:integration rems.test.api.catalogue (:require [clojure.string :as str] [clojure.test :refer :all] [rems.handler :refer [app]] [rems.test.api :refer :all] [ring.mock.request :refer :all])) (use-fixtures :once api-fixture) (deftest catalogue-api-test (let [api-key "<KEY>" user-id "alice"] (let [data (-> (request :get "/api/catalogue/") (authenticate api-key user-id) app read-body) item (first data)] (is (str/starts-with? (:resid item) "urn:"))))) (deftest catalogue-api-security-test (testing "listing without authentication" (let [response (-> (request :get (str "/api/catalogue")) app) body (read-body response)] (is (response-is-unauthorized? response)) (is (= "unauthorized" body)))) (testing "listing with wrong API-Key" (is (= "invalid api key" (-> (request :get (str "/api/catalogue")) (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") app (read-body))))))
true
(ns ^:integration rems.test.api.catalogue (:require [clojure.string :as str] [clojure.test :refer :all] [rems.handler :refer [app]] [rems.test.api :refer :all] [ring.mock.request :refer :all])) (use-fixtures :once api-fixture) (deftest catalogue-api-test (let [api-key "PI:KEY:<KEY>END_PI" user-id "alice"] (let [data (-> (request :get "/api/catalogue/") (authenticate api-key user-id) app read-body) item (first data)] (is (str/starts-with? (:resid item) "urn:"))))) (deftest catalogue-api-security-test (testing "listing without authentication" (let [response (-> (request :get (str "/api/catalogue")) app) body (read-body response)] (is (response-is-unauthorized? response)) (is (= "unauthorized" body)))) (testing "listing with wrong API-Key" (is (= "invalid api key" (-> (request :get (str "/api/catalogue")) (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") app (read-body))))))
[ { "context": ";; Copyright 2014 Pellucid Analytics\n;;\n;; Licensed under the Apache License, Versio", "end": 38, "score": 0.9990689158439636, "start": 20, "tag": "NAME", "value": "Pellucid Analytics" } ]
src/datomic_list/core.clj
dwhjames/datomic-linklist
15
;; Copyright 2014 Pellucid Analytics ;; ;; 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 datomic-list.core (:require [datomic.api :as d])) (defn is-list-empty "Test if list is empty" [db list-id] (-> db (d/entity list-id) (get :linklist/first) keyword?)) (defn nodes "Get list nodes" [list-entity] (loop [n (:linklist/first list-entity) l []] (if (keyword? n) l (recur (:linknode/next n) (conj l n)))))
60465
;; Copyright 2014 <NAME> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns datomic-list.core (:require [datomic.api :as d])) (defn is-list-empty "Test if list is empty" [db list-id] (-> db (d/entity list-id) (get :linklist/first) keyword?)) (defn nodes "Get list nodes" [list-entity] (loop [n (:linklist/first list-entity) l []] (if (keyword? n) l (recur (:linknode/next n) (conj l n)))))
true
;; Copyright 2014 PI:NAME:<NAME>END_PI ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns datomic-list.core (:require [datomic.api :as d])) (defn is-list-empty "Test if list is empty" [db list-id] (-> db (d/entity list-id) (get :linklist/first) keyword?)) (defn nodes "Get list nodes" [list-entity] (loop [n (:linklist/first list-entity) l []] (if (keyword? n) l (recur (:linknode/next n) (conj l n)))))
[ { "context": "\n(def config\n {:gin.ioc/http {:jetty-spec {:host \"127.0.0.1\"\n :port 8080}\n ", "end": 1330, "score": 0.9996941089630127, "start": 1321, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " :gin.ioc/hdfs {:hadoop-spec {:namenodes [{:host \"192.168.7.111\"\n :fs-", "end": 1633, "score": 0.9997748136520386, "start": 1620, "tag": "IP_ADDRESS", "value": "192.168.7.111" }, { "context": " {:host \"192.168.7.112\"\n :fs-", "end": 1830, "score": 0.9996400475502014, "start": 1817, "tag": "IP_ADDRESS", "value": "192.168.7.112" }, { "context": "ort 50070}]\n :user \"pmp\"\n :props {\"fs.permi", "end": 2005, "score": 0.9925167560577393, "start": 2002, "tag": "USERNAME", "value": "pmp" }, { "context": "e \"hive\"\n :host \"192.168.7.111\"\n :port 5432\n ", "end": 2240, "score": 0.9995707869529724, "start": 2227, "tag": "IP_ADDRESS", "value": "192.168.7.111" }, { "context": "ive\"\n :password \"IOzC8S0lubO1H3T6TBbr2c5GtGKK62V5\"}\n :hikari-spec {:minimumIdl", "end": 2411, "score": 0.9936143159866333, "start": 2379, "tag": "PASSWORD", "value": "IOzC8S0lubO1H3T6TBbr2c5GtGKK62V5" }, { "context": "btype \"hive2\"\n :host \"192.168.7.112\"\n :port 10000\n ", "end": 2635, "score": 0.9995761513710022, "start": 2622, "tag": "IP_ADDRESS", "value": "192.168.7.112" }, { "context": " :port 10000\n :user \"pmp\"\n :password \"pmp\"}\n ", "end": 2717, "score": 0.7297013998031616, "start": 2714, "tag": "USERNAME", "value": "pmp" }, { "context": "ser \"pmp\"\n :password \"pmp\"}\n :hikari-spec {:minimumIdle 1}}", "end": 2762, "score": 0.9993190765380859, "start": 2759, "tag": "PASSWORD", "value": "pmp" }, { "context": "BL_ID) 248\n #_(PART_KEY_VAL_STR) [\"2021\" \"08\" \"09\" \"15\"])\n\n(partition-parent #_(TBL_ID) 5", "end": 4622, "score": 0.9986281394958496, "start": 4618, "tag": "KEY", "value": "2021" }, { "context": "248\n #_(PART_KEY_VAL_STR) [\"2021\" \"08\" \"09\" \"15\"])\n\n(partition-parent #_(TBL_ID) 59\n ", "end": 4627, "score": 0.9706315398216248, "start": 4625, "tag": "KEY", "value": "08" }, { "context": " #_(PART_KEY_VAL_STR) [\"2021\" \"08\" \"09\" \"15\"])\n\n(partition-parent #_(TBL_ID) 59\n ", "end": 4632, "score": 0.9979695081710815, "start": 4631, "tag": "KEY", "value": "9" }, { "context": " #_(PART_KEY_VAL_STR) [\"2021\" \"08\" \"09\" \"15\"])\n\n(partition-parent #_(TBL_ID) 59\n ", "end": 4637, "score": 0.7394396066665649, "start": 4636, "tag": "KEY", "value": "5" }, { "context": "L_ID) 261\n #_(PART_KEY_VALS) [\"2019-11-23\" \"moscow\" 13]\n #_(DATA_LOCATIO", "end": 5067, "score": 0.999282956123352, "start": 5057, "tag": "KEY", "value": "2019-11-23" }, { "context": " #_(PART_KEY_VALS) [\"2019-11-23\" \"moscow\" 13]\n #_(DATA_LOCATION) \"/user", "end": 5076, "score": 0.9986016154289246, "start": 5070, "tag": "KEY", "value": "moscow" }, { "context": " #_(PART_KEY_VALS) [\"2019-11-23\" \"moscow\" 13]\n #_(DATA_LOCATION) \"/user/pmp", "end": 5080, "score": 0.8587931394577026, "start": 5078, "tag": "KEY", "value": "13" }, { "context": "TBL_ID) 261\n #_(PART_KEY_VALS) [\"2019-11-23\" \"moscow\" 13])\n\n;(echo\n; (gin.rpc.metastore/parti", "end": 5337, "score": 0.9966397285461426, "start": 5327, "tag": "KEY", "value": "2019-11-23" }, { "context": " #_(PART_KEY_VALS) [\"2019-11-23\" \"moscow\" 13])\n\n;(echo\n; (gin.rpc.metastore/partition-desc", "end": 5346, "score": 0.9872463941574097, "start": 5340, "tag": "KEY", "value": "moscow" }, { "context": " #_(PART_KEY_VALS) [\"2019-11-23\" \"moscow\" 13])\n\n;(echo\n; (gin.rpc.metastore/partition-describe", "end": 5350, "score": 0.9866267442703247, "start": 5349, "tag": "KEY", "value": "3" } ]
dev/user.clj
kornev/kornev-gin-app
0
(ns user (:require [clojure.string :as str] [clojure.edn :as edn] [integrant.core :as ig] [integrant.repl :as stage] [farseer.client :as client] [next.jdbc :as jdbc] [next.jdbc.result-set :as result-set] [honey.sql :as sql] [fipp.edn :refer [pprint] :rename {pprint echo}] [gin.rpc :as rpc] [gin.ioc.jmx :as jmx] [gin.rpc.hdfs :as hdfs]) (:import (org.apache.hadoop.fs FileSystem Path))) ;;; GENERAL ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn make-system [m] (integrant.repl/set-prep! #(ig/prep m)) (ig/load-namespaces m)) (defn find-node [k] (second (ig/find-derived-1 integrant.repl.state/system k))) ;;; JSON-RPC CLIENT ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private call nil) (defn make-client [m] (let [{:keys [host port]} (-> m :gin.ioc/http :jetty-spec) client (client/make-client {:http/url (str "http://" host ":" port "/rpc")})] (alter-var-root #'call (constantly (partial client/call client))))) ;;; APP ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def config {:gin.ioc/http {:jetty-spec {:host "127.0.0.1" :port 8080} :handler (ig/ref :gin.ioc/rpc)} :gin.ioc/rpc {:metastore (ig/ref :gin.ioc/metastore) :hive (ig/ref :gin.ioc/hive) :hdfs (ig/ref :gin.ioc/hdfs)} :gin.ioc/hdfs {:hadoop-spec {:namenodes [{:host "192.168.7.111" :fs-metadata-port 8020 :web-ui-port 50070} {:host "192.168.7.112" :fs-metadata-port 8020 :web-ui-port 50070}] :user "pmp" :props {"fs.permissions.umask-mode" "0002"}}} :gin.ioc/metastore {:jdbc-spec {:dbtype "postgres" :dbname "hive" :host "192.168.7.111" :port 5432 :user "hive" :password "IOzC8S0lubO1H3T6TBbr2c5GtGKK62V5"} :hikari-spec {:minimumIdle 1}} :gin.ioc/hive {:jdbc-spec {:classname "org.apache.hive.jdbc.HiveDriver" :dbtype "hive2" :host "192.168.7.112" :port 10000 :user "pmp" :password "pmp"} :hikari-spec {:minimumIdle 1}}}) (defn start [m] (make-system m) (make-client m) (stage/go)) (defn metastore! [q & [p & r]] (jdbc/execute! (find-node :gin.ioc/metastore) (sql/format q {:quoted true :params p}) {:builder-fn result-set/as-unqualified-maps})) (defn hive! [& more] (jdbc/execute! (find-node :gin.ioc/hive) more {:builder-fn result-set/as-unqualified-maps})) (defn file [path data] (let [fs (jmx/active-fs (find-node :gin.ioc/hdfs)) path (Path. path)] (when (. fs exists path) (. fs delete path)) (doto (. fs create path true) (.writeBytes data) (.close)))) ;;; TEST ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn table-describe-rpc [& r] (echo (rpc/table-describe-rpc {:metastore-ds (find-node :gin.ioc/metastore) :hive-ds (find-node :gin.ioc/hive) :hadoop-ctx (find-node :gin.ioc/hdfs)} r))) (defn table-describe [& r] (echo (call :table/describe r))) (defn partition-list [& r] (echo (call :partition/list r))) (defn partition-find [& r] (echo (call :partition/find r))) (defn partition-parent [& r] (echo (call :partition/parent r))) (defn partition-attach [& r] (echo (call :partition/attach r))) (defn partition-detach [& r] (echo (call :partition/detach r))) ;;; RUN ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (start config) (table-describe-rpc #_(DB_NAME) "processing" #_(TBL_NAME) "test01") (partition-list #_(TBL_ID) 198 #_(LIMIT) 2) (partition-find #_(TBL_ID) 248 #_(PART_KEY_VAL_STR) ["2021" "08" "09" "15"]) (partition-parent #_(TBL_ID) 59 #_(CREATE_TIME) 1626746198) ;curl -s -X POST 'http://127.0.0.1:8080/rpc' \ ; -d '{"id": 61966, "jsonrpc": "2.0", "method": "partition/attach", "params": [248, ["2021", "08", "09", "15"]]}' \ ; -H 'content-type: application/json' (do (file "/user/pmp/input/data.csv" "3,omar\n4,lory") (partition-attach #_(TBL_ID) 261 #_(PART_KEY_VALS) ["2019-11-23" "moscow" 13] #_(DATA_LOCATION) "/user/pmp/input")) (echo (hive! "show partitions processing.test01")) (echo (hive! "select * from processing.test01 where num=13")) (partition-detach #_(TBL_ID) 261 #_(PART_KEY_VALS) ["2019-11-23" "moscow" 13]) ;(echo ; (gin.rpc.metastore/partition-describe ; (find-node :gin.ioc/metastore) ; {:TBL_ID 261})) ;(echo ; (metastore! {:select [:datname] ; :from [[:pg_database :d]] ; :where [:= :d/datistemplate false]})) ;(echo ; (metastore! {:select [:table_schema ; :table_name] ; :from [:information_schema.tables] ; :order-by [:table_schema :table_name]})) ;(echo ; (metastore! {:select [:*] :from [:DBS] :limit 3}))
91866
(ns user (:require [clojure.string :as str] [clojure.edn :as edn] [integrant.core :as ig] [integrant.repl :as stage] [farseer.client :as client] [next.jdbc :as jdbc] [next.jdbc.result-set :as result-set] [honey.sql :as sql] [fipp.edn :refer [pprint] :rename {pprint echo}] [gin.rpc :as rpc] [gin.ioc.jmx :as jmx] [gin.rpc.hdfs :as hdfs]) (:import (org.apache.hadoop.fs FileSystem Path))) ;;; GENERAL ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn make-system [m] (integrant.repl/set-prep! #(ig/prep m)) (ig/load-namespaces m)) (defn find-node [k] (second (ig/find-derived-1 integrant.repl.state/system k))) ;;; JSON-RPC CLIENT ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private call nil) (defn make-client [m] (let [{:keys [host port]} (-> m :gin.ioc/http :jetty-spec) client (client/make-client {:http/url (str "http://" host ":" port "/rpc")})] (alter-var-root #'call (constantly (partial client/call client))))) ;;; APP ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def config {:gin.ioc/http {:jetty-spec {:host "127.0.0.1" :port 8080} :handler (ig/ref :gin.ioc/rpc)} :gin.ioc/rpc {:metastore (ig/ref :gin.ioc/metastore) :hive (ig/ref :gin.ioc/hive) :hdfs (ig/ref :gin.ioc/hdfs)} :gin.ioc/hdfs {:hadoop-spec {:namenodes [{:host "192.168.7.111" :fs-metadata-port 8020 :web-ui-port 50070} {:host "192.168.7.112" :fs-metadata-port 8020 :web-ui-port 50070}] :user "pmp" :props {"fs.permissions.umask-mode" "0002"}}} :gin.ioc/metastore {:jdbc-spec {:dbtype "postgres" :dbname "hive" :host "192.168.7.111" :port 5432 :user "hive" :password "<PASSWORD>"} :hikari-spec {:minimumIdle 1}} :gin.ioc/hive {:jdbc-spec {:classname "org.apache.hive.jdbc.HiveDriver" :dbtype "hive2" :host "192.168.7.112" :port 10000 :user "pmp" :password "<PASSWORD>"} :hikari-spec {:minimumIdle 1}}}) (defn start [m] (make-system m) (make-client m) (stage/go)) (defn metastore! [q & [p & r]] (jdbc/execute! (find-node :gin.ioc/metastore) (sql/format q {:quoted true :params p}) {:builder-fn result-set/as-unqualified-maps})) (defn hive! [& more] (jdbc/execute! (find-node :gin.ioc/hive) more {:builder-fn result-set/as-unqualified-maps})) (defn file [path data] (let [fs (jmx/active-fs (find-node :gin.ioc/hdfs)) path (Path. path)] (when (. fs exists path) (. fs delete path)) (doto (. fs create path true) (.writeBytes data) (.close)))) ;;; TEST ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn table-describe-rpc [& r] (echo (rpc/table-describe-rpc {:metastore-ds (find-node :gin.ioc/metastore) :hive-ds (find-node :gin.ioc/hive) :hadoop-ctx (find-node :gin.ioc/hdfs)} r))) (defn table-describe [& r] (echo (call :table/describe r))) (defn partition-list [& r] (echo (call :partition/list r))) (defn partition-find [& r] (echo (call :partition/find r))) (defn partition-parent [& r] (echo (call :partition/parent r))) (defn partition-attach [& r] (echo (call :partition/attach r))) (defn partition-detach [& r] (echo (call :partition/detach r))) ;;; RUN ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (start config) (table-describe-rpc #_(DB_NAME) "processing" #_(TBL_NAME) "test01") (partition-list #_(TBL_ID) 198 #_(LIMIT) 2) (partition-find #_(TBL_ID) 248 #_(PART_KEY_VAL_STR) ["<KEY>" "<KEY>" "0<KEY>" "1<KEY>"]) (partition-parent #_(TBL_ID) 59 #_(CREATE_TIME) 1626746198) ;curl -s -X POST 'http://127.0.0.1:8080/rpc' \ ; -d '{"id": 61966, "jsonrpc": "2.0", "method": "partition/attach", "params": [248, ["2021", "08", "09", "15"]]}' \ ; -H 'content-type: application/json' (do (file "/user/pmp/input/data.csv" "3,omar\n4,lory") (partition-attach #_(TBL_ID) 261 #_(PART_KEY_VALS) ["<KEY>" "<KEY>" <KEY>] #_(DATA_LOCATION) "/user/pmp/input")) (echo (hive! "show partitions processing.test01")) (echo (hive! "select * from processing.test01 where num=13")) (partition-detach #_(TBL_ID) 261 #_(PART_KEY_VALS) ["<KEY>" "<KEY>" 1<KEY>]) ;(echo ; (gin.rpc.metastore/partition-describe ; (find-node :gin.ioc/metastore) ; {:TBL_ID 261})) ;(echo ; (metastore! {:select [:datname] ; :from [[:pg_database :d]] ; :where [:= :d/datistemplate false]})) ;(echo ; (metastore! {:select [:table_schema ; :table_name] ; :from [:information_schema.tables] ; :order-by [:table_schema :table_name]})) ;(echo ; (metastore! {:select [:*] :from [:DBS] :limit 3}))
true
(ns user (:require [clojure.string :as str] [clojure.edn :as edn] [integrant.core :as ig] [integrant.repl :as stage] [farseer.client :as client] [next.jdbc :as jdbc] [next.jdbc.result-set :as result-set] [honey.sql :as sql] [fipp.edn :refer [pprint] :rename {pprint echo}] [gin.rpc :as rpc] [gin.ioc.jmx :as jmx] [gin.rpc.hdfs :as hdfs]) (:import (org.apache.hadoop.fs FileSystem Path))) ;;; GENERAL ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn make-system [m] (integrant.repl/set-prep! #(ig/prep m)) (ig/load-namespaces m)) (defn find-node [k] (second (ig/find-derived-1 integrant.repl.state/system k))) ;;; JSON-RPC CLIENT ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private call nil) (defn make-client [m] (let [{:keys [host port]} (-> m :gin.ioc/http :jetty-spec) client (client/make-client {:http/url (str "http://" host ":" port "/rpc")})] (alter-var-root #'call (constantly (partial client/call client))))) ;;; APP ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def config {:gin.ioc/http {:jetty-spec {:host "127.0.0.1" :port 8080} :handler (ig/ref :gin.ioc/rpc)} :gin.ioc/rpc {:metastore (ig/ref :gin.ioc/metastore) :hive (ig/ref :gin.ioc/hive) :hdfs (ig/ref :gin.ioc/hdfs)} :gin.ioc/hdfs {:hadoop-spec {:namenodes [{:host "192.168.7.111" :fs-metadata-port 8020 :web-ui-port 50070} {:host "192.168.7.112" :fs-metadata-port 8020 :web-ui-port 50070}] :user "pmp" :props {"fs.permissions.umask-mode" "0002"}}} :gin.ioc/metastore {:jdbc-spec {:dbtype "postgres" :dbname "hive" :host "192.168.7.111" :port 5432 :user "hive" :password "PI:PASSWORD:<PASSWORD>END_PI"} :hikari-spec {:minimumIdle 1}} :gin.ioc/hive {:jdbc-spec {:classname "org.apache.hive.jdbc.HiveDriver" :dbtype "hive2" :host "192.168.7.112" :port 10000 :user "pmp" :password "PI:PASSWORD:<PASSWORD>END_PI"} :hikari-spec {:minimumIdle 1}}}) (defn start [m] (make-system m) (make-client m) (stage/go)) (defn metastore! [q & [p & r]] (jdbc/execute! (find-node :gin.ioc/metastore) (sql/format q {:quoted true :params p}) {:builder-fn result-set/as-unqualified-maps})) (defn hive! [& more] (jdbc/execute! (find-node :gin.ioc/hive) more {:builder-fn result-set/as-unqualified-maps})) (defn file [path data] (let [fs (jmx/active-fs (find-node :gin.ioc/hdfs)) path (Path. path)] (when (. fs exists path) (. fs delete path)) (doto (. fs create path true) (.writeBytes data) (.close)))) ;;; TEST ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn table-describe-rpc [& r] (echo (rpc/table-describe-rpc {:metastore-ds (find-node :gin.ioc/metastore) :hive-ds (find-node :gin.ioc/hive) :hadoop-ctx (find-node :gin.ioc/hdfs)} r))) (defn table-describe [& r] (echo (call :table/describe r))) (defn partition-list [& r] (echo (call :partition/list r))) (defn partition-find [& r] (echo (call :partition/find r))) (defn partition-parent [& r] (echo (call :partition/parent r))) (defn partition-attach [& r] (echo (call :partition/attach r))) (defn partition-detach [& r] (echo (call :partition/detach r))) ;;; RUN ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (start config) (table-describe-rpc #_(DB_NAME) "processing" #_(TBL_NAME) "test01") (partition-list #_(TBL_ID) 198 #_(LIMIT) 2) (partition-find #_(TBL_ID) 248 #_(PART_KEY_VAL_STR) ["PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" "0PI:KEY:<KEY>END_PI" "1PI:KEY:<KEY>END_PI"]) (partition-parent #_(TBL_ID) 59 #_(CREATE_TIME) 1626746198) ;curl -s -X POST 'http://127.0.0.1:8080/rpc' \ ; -d '{"id": 61966, "jsonrpc": "2.0", "method": "partition/attach", "params": [248, ["2021", "08", "09", "15"]]}' \ ; -H 'content-type: application/json' (do (file "/user/pmp/input/data.csv" "3,omar\n4,lory") (partition-attach #_(TBL_ID) 261 #_(PART_KEY_VALS) ["PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" PI:KEY:<KEY>END_PI] #_(DATA_LOCATION) "/user/pmp/input")) (echo (hive! "show partitions processing.test01")) (echo (hive! "select * from processing.test01 where num=13")) (partition-detach #_(TBL_ID) 261 #_(PART_KEY_VALS) ["PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" 1PI:KEY:<KEY>END_PI]) ;(echo ; (gin.rpc.metastore/partition-describe ; (find-node :gin.ioc/metastore) ; {:TBL_ID 261})) ;(echo ; (metastore! {:select [:datname] ; :from [[:pg_database :d]] ; :where [:= :d/datistemplate false]})) ;(echo ; (metastore! {:select [:table_schema ; :table_name] ; :from [:information_schema.tables] ; :order-by [:table_schema :table_name]})) ;(echo ; (metastore! {:select [:*] :from [:DBS] :limit 3}))
[ { "context": "x that represents literal values.\"\n :author \"Sean Dawson\"}\n nanoweave.ast.literals\n (:require [schema.cor", "end": 78, "score": 0.999858021736145, "start": 67, "tag": "NAME", "value": "Sean Dawson" } ]
src/nanoweave/ast/literals.clj
NoxHarmonium/nanoweave
0
(ns ^{:doc "Syntax that represents literal values." :author "Sean Dawson"} nanoweave.ast.literals (:require [schema.core :as s] [nanoweave.ast.base :refer [Resolvable]])) (s/defrecord IdentiferLit [value :- s/Str]) (s/defrecord StringLit [value :- s/Str]) (s/defrecord FloatLit [value :- s/Num]) (s/defrecord BoolLit [value :- s/Bool]) (s/defrecord NilLit []) (s/defrecord ArrayLit [value :- [Resolvable]])
18502
(ns ^{:doc "Syntax that represents literal values." :author "<NAME>"} nanoweave.ast.literals (:require [schema.core :as s] [nanoweave.ast.base :refer [Resolvable]])) (s/defrecord IdentiferLit [value :- s/Str]) (s/defrecord StringLit [value :- s/Str]) (s/defrecord FloatLit [value :- s/Num]) (s/defrecord BoolLit [value :- s/Bool]) (s/defrecord NilLit []) (s/defrecord ArrayLit [value :- [Resolvable]])
true
(ns ^{:doc "Syntax that represents literal values." :author "PI:NAME:<NAME>END_PI"} nanoweave.ast.literals (:require [schema.core :as s] [nanoweave.ast.base :refer [Resolvable]])) (s/defrecord IdentiferLit [value :- s/Str]) (s/defrecord StringLit [value :- s/Str]) (s/defrecord FloatLit [value :- s/Num]) (s/defrecord BoolLit [value :- s/Bool]) (s/defrecord NilLit []) (s/defrecord ArrayLit [value :- [Resolvable]])
[ { "context": " (when (some? auth-entity)\n {:username (:username auth-entity)\n :password (:password auth-", "end": 460, "score": 0.5339869856834412, "start": 452, "tag": "USERNAME", "value": "username" }, { "context": "(some? auth-entity)\n {:username (:username auth-entity)\n :password (:password auth-entity)\n ", "end": 472, "score": 0.7942410111427307, "start": 461, "tag": "USERNAME", "value": "auth-entity" }, { "context": " (:username auth-entity)\n :password (:password auth-entity)\n :serveraddress (:url auth-entit", "end": 504, "score": 0.7740702629089355, "start": 496, "tag": "PASSWORD", "value": "password" }, { "context": "ername auth-entity)\n :password (:password auth-entity)\n :serveraddress (:url auth-entity)}))\n\n(defn", "end": 516, "score": 0.7445794939994812, "start": 505, "tag": "PASSWORD", "value": "auth-entity" } ]
ch16/swarmpit/src/clj/swarmpit/docker/engine/mapper/outbound.clj
vincestorm/Docker-on-Amazon-Web-Services
0
(ns swarmpit.docker.engine.mapper.outbound "Map swarmpit domain to docker domain" (:require [clojure.string :as str] [swarmpit.docker.engine.mapper.inbound :refer [autoredeploy-label]] [swarmpit.utils :refer [name-value->map ->nano]])) (defn- as-bytes [megabytes] (* megabytes (* 1024 1024))) (defn ->auth-config "Pass registry or dockeruser entity" [auth-entity] (when (some? auth-entity) {:username (:username auth-entity) :password (:password auth-entity) :serveraddress (:url auth-entity)})) (defn ->service-mode [service] (if (= (:mode service) "global") {:Global {}} {:Replicated {:Replicas (:replicas service)}})) (defn ->service-ports [service] (->> (:ports service) (filter #(and (some? (:containerPort %)) (some? (:hostPort %)) (> (:containerPort %) 0) (> (:hostPort %) 0))) (map (fn [p] {:Protocol (:protocol p) :PublishMode (:mode p) :PublishedPort (:hostPort p) :TargetPort (:containerPort p)})) (into []))) (defn- ->service-networks [service] (->> (:networks service) (map #(hash-map :Target (:networkName %) :Aliases (:serviceAliases %))) (into []))) (defn ->service-variables [service] (->> (:variables service) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (map (fn [p] (str (:name p) "=" (:value p)))) (into []))) (defn ->service-labels [service] (->> (:labels service) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (name-value->map))) (defn ->service-log-options [service] (->> (get-in service [:logdriver :opts]) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (name-value->map))) (defn ->service-volume-options [service-volume] (when (some? service-volume) {:Labels (:labels service-volume) :DriverConfig {:Name (get-in service-volume [:driver :name]) :Options (name-value->map (get-in service-volume [:driver :options]))}})) (defn ->service-mounts [service] (->> (:mounts service) (map (fn [v] {:ReadOnly (:readOnly v) :Source (:host v) :Target (:containerPath v) :Type (:type v) :VolumeOptions (->service-volume-options (:volumeOptions v))})) (into []))) (defn- ->service-placement-contraints [service] (->> (get-in service [:deployment :placement]) (map (fn [p] (:rule p))) (into []))) (defn- ->secret-id [secret-name secrets] (->> secrets (filter #(= secret-name (:secretName %))) (first) :id)) (defn ->secret-target [secret] (let [secret-target (:secretTarget secret)] (if (str/blank? secret-target) (:secretName secret) secret-target))) (defn ->service-secrets [service secrets] (->> (:secrets service) (map (fn [s] {:SecretName (:secretName s) :SecretID (->secret-id (:secretName s) secrets) :File {:GID "0" :Mode 292 :Name (->secret-target s) :UID "0"}})) (into []))) (defn- ->config-id [config-name configs] (->> configs (filter #(= config-name (:configName %))) (first) :id)) (defn ->config-target [config] (let [config-target (:configTarget config)] (if (str/blank? config-target) (:configName config) config-target))) (defn ->service-configs [service configs] (->> (:configs service) (map (fn [c] {:ConfigName (:configName c) :ConfigID (->config-id (:configName c) configs) :File {:GID "0" :Mode 292 :Name (->config-target c) :UID "0"}})) (into []))) (defn ->service-resource [service-resource] (let [cpu (:cpu service-resource) memory (:memory service-resource)] {:NanoCPUs (when (some? cpu) (-> cpu (->nano) (long))) :MemoryBytes (when (some? memory) (as-bytes memory))})) (defn ->service-update-config [service] (let [update (get-in service [:deployment :update])] {:Parallelism (:parallelism update) :Delay (->nano (:delay update)) :Order (:order update) :FailureAction (:failureAction update)})) (defn ->service-rollback-config [service] (let [rollback (get-in service [:deployment :rollback])] {:Parallelism (:parallelism rollback) :Delay (->nano (:delay rollback)) :Order (:order rollback) :FailureAction (:failureAction rollback)})) (defn ->service-restart-policy [service] (let [policy (get-in service [:deployment :restartPolicy])] {:Condition (:condition policy) :Delay (->nano (:delay policy)) :Window (->nano (:window policy)) :MaxAttempts (:attempts policy)})) (defn ->service-image [service digest?] (let [repository (get-in service [:repository :name]) tag (get-in service [:repository :tag]) digest (get-in service [:repository :imageDigest])] (if digest? (str repository ":" tag "@" digest) (str repository ":" tag)))) (defn ->service-metadata [service image] (let [autoredeploy (get-in service [:deployment :autoredeploy]) stack (:stack service)] (merge {} (when (some? stack) {:com.docker.stack.namespace stack :com.docker.stack.image image}) (when (some? autoredeploy) {autoredeploy-label (str autoredeploy)})))) (defn ->service-container-metadata [service] (let [stack (:stack service)] (merge {} (when (some? stack) {:com.docker.stack.namespace stack})))) (defn ->service [service] {:Name (:serviceName service) :Labels (merge (->service-labels service) (->service-metadata service (->service-image service false))) :TaskTemplate {:ContainerSpec {:Image (->service-image service true) :Labels (->service-container-metadata service) :Mounts (->service-mounts service) :Secrets (:secrets service) :Configs (:configs service) :Args (:command service) :Env (->service-variables service)} :LogDriver {:Name (get-in service [:logdriver :name]) :Options (->service-log-options service)} :Resources {:Limits (->service-resource (get-in service [:resources :limit])) :Reservations (->service-resource (get-in service [:resources :reservation]))} :RestartPolicy (->service-restart-policy service) :Placement {:Constraints (->service-placement-contraints service)} :ForceUpdate (get-in service [:deployment :forceUpdate]) :Networks (->service-networks service)} :Mode (->service-mode service) :UpdateConfig (->service-update-config service) :RollbackConfig (->service-rollback-config service) :EndpointSpec {:Ports (->service-ports service)}}) (defn ->network-ipam-config [network] (let [ipam (:ipam network) gateway (:gateway ipam) subnet (:subnet ipam)] (if (not (str/blank? subnet)) {:Config [{:Subnet subnet :Gateway gateway}]} {:Config []}))) (defn ->network [network] {:Name (:networkName network) :Driver (:driver network) :Internal (:internal network) :Options (name-value->map (:options network)) :Attachable (:attachable network) :Ingress (:ingress network) :EnableIPv6 (:enableIPv6 network) :IPAM (merge {:Driver "default"} (->network-ipam-config network))}) (defn ->volume [volume] {:Name (:volumeName volume) :Driver (:driver volume) :DriverOpts (name-value->map (:options volume)) :Labels (:labels volume)}) (defn ->secret [secret] {:Name (:secretName secret) :Data (:data secret)}) (defn ->config [config] {:Name (:configName config) :Data (:data config)}) (defn ->node [node] {:Availability (:availability node) :Role (:role node) :Labels (name-value->map (:labels node))})
33432
(ns swarmpit.docker.engine.mapper.outbound "Map swarmpit domain to docker domain" (:require [clojure.string :as str] [swarmpit.docker.engine.mapper.inbound :refer [autoredeploy-label]] [swarmpit.utils :refer [name-value->map ->nano]])) (defn- as-bytes [megabytes] (* megabytes (* 1024 1024))) (defn ->auth-config "Pass registry or dockeruser entity" [auth-entity] (when (some? auth-entity) {:username (:username auth-entity) :password (:<PASSWORD> <PASSWORD>) :serveraddress (:url auth-entity)})) (defn ->service-mode [service] (if (= (:mode service) "global") {:Global {}} {:Replicated {:Replicas (:replicas service)}})) (defn ->service-ports [service] (->> (:ports service) (filter #(and (some? (:containerPort %)) (some? (:hostPort %)) (> (:containerPort %) 0) (> (:hostPort %) 0))) (map (fn [p] {:Protocol (:protocol p) :PublishMode (:mode p) :PublishedPort (:hostPort p) :TargetPort (:containerPort p)})) (into []))) (defn- ->service-networks [service] (->> (:networks service) (map #(hash-map :Target (:networkName %) :Aliases (:serviceAliases %))) (into []))) (defn ->service-variables [service] (->> (:variables service) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (map (fn [p] (str (:name p) "=" (:value p)))) (into []))) (defn ->service-labels [service] (->> (:labels service) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (name-value->map))) (defn ->service-log-options [service] (->> (get-in service [:logdriver :opts]) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (name-value->map))) (defn ->service-volume-options [service-volume] (when (some? service-volume) {:Labels (:labels service-volume) :DriverConfig {:Name (get-in service-volume [:driver :name]) :Options (name-value->map (get-in service-volume [:driver :options]))}})) (defn ->service-mounts [service] (->> (:mounts service) (map (fn [v] {:ReadOnly (:readOnly v) :Source (:host v) :Target (:containerPath v) :Type (:type v) :VolumeOptions (->service-volume-options (:volumeOptions v))})) (into []))) (defn- ->service-placement-contraints [service] (->> (get-in service [:deployment :placement]) (map (fn [p] (:rule p))) (into []))) (defn- ->secret-id [secret-name secrets] (->> secrets (filter #(= secret-name (:secretName %))) (first) :id)) (defn ->secret-target [secret] (let [secret-target (:secretTarget secret)] (if (str/blank? secret-target) (:secretName secret) secret-target))) (defn ->service-secrets [service secrets] (->> (:secrets service) (map (fn [s] {:SecretName (:secretName s) :SecretID (->secret-id (:secretName s) secrets) :File {:GID "0" :Mode 292 :Name (->secret-target s) :UID "0"}})) (into []))) (defn- ->config-id [config-name configs] (->> configs (filter #(= config-name (:configName %))) (first) :id)) (defn ->config-target [config] (let [config-target (:configTarget config)] (if (str/blank? config-target) (:configName config) config-target))) (defn ->service-configs [service configs] (->> (:configs service) (map (fn [c] {:ConfigName (:configName c) :ConfigID (->config-id (:configName c) configs) :File {:GID "0" :Mode 292 :Name (->config-target c) :UID "0"}})) (into []))) (defn ->service-resource [service-resource] (let [cpu (:cpu service-resource) memory (:memory service-resource)] {:NanoCPUs (when (some? cpu) (-> cpu (->nano) (long))) :MemoryBytes (when (some? memory) (as-bytes memory))})) (defn ->service-update-config [service] (let [update (get-in service [:deployment :update])] {:Parallelism (:parallelism update) :Delay (->nano (:delay update)) :Order (:order update) :FailureAction (:failureAction update)})) (defn ->service-rollback-config [service] (let [rollback (get-in service [:deployment :rollback])] {:Parallelism (:parallelism rollback) :Delay (->nano (:delay rollback)) :Order (:order rollback) :FailureAction (:failureAction rollback)})) (defn ->service-restart-policy [service] (let [policy (get-in service [:deployment :restartPolicy])] {:Condition (:condition policy) :Delay (->nano (:delay policy)) :Window (->nano (:window policy)) :MaxAttempts (:attempts policy)})) (defn ->service-image [service digest?] (let [repository (get-in service [:repository :name]) tag (get-in service [:repository :tag]) digest (get-in service [:repository :imageDigest])] (if digest? (str repository ":" tag "@" digest) (str repository ":" tag)))) (defn ->service-metadata [service image] (let [autoredeploy (get-in service [:deployment :autoredeploy]) stack (:stack service)] (merge {} (when (some? stack) {:com.docker.stack.namespace stack :com.docker.stack.image image}) (when (some? autoredeploy) {autoredeploy-label (str autoredeploy)})))) (defn ->service-container-metadata [service] (let [stack (:stack service)] (merge {} (when (some? stack) {:com.docker.stack.namespace stack})))) (defn ->service [service] {:Name (:serviceName service) :Labels (merge (->service-labels service) (->service-metadata service (->service-image service false))) :TaskTemplate {:ContainerSpec {:Image (->service-image service true) :Labels (->service-container-metadata service) :Mounts (->service-mounts service) :Secrets (:secrets service) :Configs (:configs service) :Args (:command service) :Env (->service-variables service)} :LogDriver {:Name (get-in service [:logdriver :name]) :Options (->service-log-options service)} :Resources {:Limits (->service-resource (get-in service [:resources :limit])) :Reservations (->service-resource (get-in service [:resources :reservation]))} :RestartPolicy (->service-restart-policy service) :Placement {:Constraints (->service-placement-contraints service)} :ForceUpdate (get-in service [:deployment :forceUpdate]) :Networks (->service-networks service)} :Mode (->service-mode service) :UpdateConfig (->service-update-config service) :RollbackConfig (->service-rollback-config service) :EndpointSpec {:Ports (->service-ports service)}}) (defn ->network-ipam-config [network] (let [ipam (:ipam network) gateway (:gateway ipam) subnet (:subnet ipam)] (if (not (str/blank? subnet)) {:Config [{:Subnet subnet :Gateway gateway}]} {:Config []}))) (defn ->network [network] {:Name (:networkName network) :Driver (:driver network) :Internal (:internal network) :Options (name-value->map (:options network)) :Attachable (:attachable network) :Ingress (:ingress network) :EnableIPv6 (:enableIPv6 network) :IPAM (merge {:Driver "default"} (->network-ipam-config network))}) (defn ->volume [volume] {:Name (:volumeName volume) :Driver (:driver volume) :DriverOpts (name-value->map (:options volume)) :Labels (:labels volume)}) (defn ->secret [secret] {:Name (:secretName secret) :Data (:data secret)}) (defn ->config [config] {:Name (:configName config) :Data (:data config)}) (defn ->node [node] {:Availability (:availability node) :Role (:role node) :Labels (name-value->map (:labels node))})
true
(ns swarmpit.docker.engine.mapper.outbound "Map swarmpit domain to docker domain" (:require [clojure.string :as str] [swarmpit.docker.engine.mapper.inbound :refer [autoredeploy-label]] [swarmpit.utils :refer [name-value->map ->nano]])) (defn- as-bytes [megabytes] (* megabytes (* 1024 1024))) (defn ->auth-config "Pass registry or dockeruser entity" [auth-entity] (when (some? auth-entity) {:username (:username auth-entity) :password (:PI:PASSWORD:<PASSWORD>END_PI PI:PASSWORD:<PASSWORD>END_PI) :serveraddress (:url auth-entity)})) (defn ->service-mode [service] (if (= (:mode service) "global") {:Global {}} {:Replicated {:Replicas (:replicas service)}})) (defn ->service-ports [service] (->> (:ports service) (filter #(and (some? (:containerPort %)) (some? (:hostPort %)) (> (:containerPort %) 0) (> (:hostPort %) 0))) (map (fn [p] {:Protocol (:protocol p) :PublishMode (:mode p) :PublishedPort (:hostPort p) :TargetPort (:containerPort p)})) (into []))) (defn- ->service-networks [service] (->> (:networks service) (map #(hash-map :Target (:networkName %) :Aliases (:serviceAliases %))) (into []))) (defn ->service-variables [service] (->> (:variables service) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (map (fn [p] (str (:name p) "=" (:value p)))) (into []))) (defn ->service-labels [service] (->> (:labels service) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (name-value->map))) (defn ->service-log-options [service] (->> (get-in service [:logdriver :opts]) (filter #(not (and (str/blank? (:name %)) (str/blank? (:value %))))) (name-value->map))) (defn ->service-volume-options [service-volume] (when (some? service-volume) {:Labels (:labels service-volume) :DriverConfig {:Name (get-in service-volume [:driver :name]) :Options (name-value->map (get-in service-volume [:driver :options]))}})) (defn ->service-mounts [service] (->> (:mounts service) (map (fn [v] {:ReadOnly (:readOnly v) :Source (:host v) :Target (:containerPath v) :Type (:type v) :VolumeOptions (->service-volume-options (:volumeOptions v))})) (into []))) (defn- ->service-placement-contraints [service] (->> (get-in service [:deployment :placement]) (map (fn [p] (:rule p))) (into []))) (defn- ->secret-id [secret-name secrets] (->> secrets (filter #(= secret-name (:secretName %))) (first) :id)) (defn ->secret-target [secret] (let [secret-target (:secretTarget secret)] (if (str/blank? secret-target) (:secretName secret) secret-target))) (defn ->service-secrets [service secrets] (->> (:secrets service) (map (fn [s] {:SecretName (:secretName s) :SecretID (->secret-id (:secretName s) secrets) :File {:GID "0" :Mode 292 :Name (->secret-target s) :UID "0"}})) (into []))) (defn- ->config-id [config-name configs] (->> configs (filter #(= config-name (:configName %))) (first) :id)) (defn ->config-target [config] (let [config-target (:configTarget config)] (if (str/blank? config-target) (:configName config) config-target))) (defn ->service-configs [service configs] (->> (:configs service) (map (fn [c] {:ConfigName (:configName c) :ConfigID (->config-id (:configName c) configs) :File {:GID "0" :Mode 292 :Name (->config-target c) :UID "0"}})) (into []))) (defn ->service-resource [service-resource] (let [cpu (:cpu service-resource) memory (:memory service-resource)] {:NanoCPUs (when (some? cpu) (-> cpu (->nano) (long))) :MemoryBytes (when (some? memory) (as-bytes memory))})) (defn ->service-update-config [service] (let [update (get-in service [:deployment :update])] {:Parallelism (:parallelism update) :Delay (->nano (:delay update)) :Order (:order update) :FailureAction (:failureAction update)})) (defn ->service-rollback-config [service] (let [rollback (get-in service [:deployment :rollback])] {:Parallelism (:parallelism rollback) :Delay (->nano (:delay rollback)) :Order (:order rollback) :FailureAction (:failureAction rollback)})) (defn ->service-restart-policy [service] (let [policy (get-in service [:deployment :restartPolicy])] {:Condition (:condition policy) :Delay (->nano (:delay policy)) :Window (->nano (:window policy)) :MaxAttempts (:attempts policy)})) (defn ->service-image [service digest?] (let [repository (get-in service [:repository :name]) tag (get-in service [:repository :tag]) digest (get-in service [:repository :imageDigest])] (if digest? (str repository ":" tag "@" digest) (str repository ":" tag)))) (defn ->service-metadata [service image] (let [autoredeploy (get-in service [:deployment :autoredeploy]) stack (:stack service)] (merge {} (when (some? stack) {:com.docker.stack.namespace stack :com.docker.stack.image image}) (when (some? autoredeploy) {autoredeploy-label (str autoredeploy)})))) (defn ->service-container-metadata [service] (let [stack (:stack service)] (merge {} (when (some? stack) {:com.docker.stack.namespace stack})))) (defn ->service [service] {:Name (:serviceName service) :Labels (merge (->service-labels service) (->service-metadata service (->service-image service false))) :TaskTemplate {:ContainerSpec {:Image (->service-image service true) :Labels (->service-container-metadata service) :Mounts (->service-mounts service) :Secrets (:secrets service) :Configs (:configs service) :Args (:command service) :Env (->service-variables service)} :LogDriver {:Name (get-in service [:logdriver :name]) :Options (->service-log-options service)} :Resources {:Limits (->service-resource (get-in service [:resources :limit])) :Reservations (->service-resource (get-in service [:resources :reservation]))} :RestartPolicy (->service-restart-policy service) :Placement {:Constraints (->service-placement-contraints service)} :ForceUpdate (get-in service [:deployment :forceUpdate]) :Networks (->service-networks service)} :Mode (->service-mode service) :UpdateConfig (->service-update-config service) :RollbackConfig (->service-rollback-config service) :EndpointSpec {:Ports (->service-ports service)}}) (defn ->network-ipam-config [network] (let [ipam (:ipam network) gateway (:gateway ipam) subnet (:subnet ipam)] (if (not (str/blank? subnet)) {:Config [{:Subnet subnet :Gateway gateway}]} {:Config []}))) (defn ->network [network] {:Name (:networkName network) :Driver (:driver network) :Internal (:internal network) :Options (name-value->map (:options network)) :Attachable (:attachable network) :Ingress (:ingress network) :EnableIPv6 (:enableIPv6 network) :IPAM (merge {:Driver "default"} (->network-ipam-config network))}) (defn ->volume [volume] {:Name (:volumeName volume) :Driver (:driver volume) :DriverOpts (name-value->map (:options volume)) :Labels (:labels volume)}) (defn ->secret [secret] {:Name (:secretName secret) :Data (:data secret)}) (defn ->config [config] {:Name (:configName config) :Data (:data config)}) (defn ->node [node] {:Availability (:availability node) :Role (:role node) :Labels (name-value->map (:labels node))})
[ { "context": "he clojure world:\n\n - [at-at](https://github.com/overtone/at-at)\n - [chime](https://github.com/james-hende", "end": 1190, "score": 0.9708515405654907, "start": 1182, "tag": "USERNAME", "value": "overtone" }, { "context": "om/overtone/at-at)\n - [chime](https://github.com/james-henderson/chime)\n - [clj-cronlike](https://github.com/kogn", "end": 1244, "score": 0.997260332107544, "start": 1229, "tag": "USERNAME", "value": "james-henderson" }, { "context": "rson/chime)\n - [clj-cronlike](https://github.com/kognate/clj-cronlike)\n - [cron4j](http://www.sauronsoftw", "end": 1297, "score": 0.9521465301513672, "start": 1290, "tag": "USERNAME", "value": "kognate" }, { "context": "rojects/cron4j)\n - [monotony](https://github.com/aredington/monotony)\n - [quartzite](https://github.com/mich", "end": 1415, "score": 0.9987038969993591, "start": 1405, "tag": "USERNAME", "value": "aredington" }, { "context": "gton/monotony)\n - [quartzite](https://github.com/michaelklishin/quartzite)\n - [schejulure](https://github.com/Ad", "end": 1475, "score": 0.9985194206237793, "start": 1461, "tag": "USERNAME", "value": "michaelklishin" }, { "context": "in/quartzite)\n - [schejulure](https://github.com/AdamClements/schejulure)\n\nWith so many options, and so many di", "end": 1535, "score": 0.9977449774742126, "start": 1523, "tag": "USERNAME", "value": "AdamClements" }, { "context": "lodge an issue on github or contact me directly.\n\nChris.\n\"\n", "end": 16111, "score": 0.9513189792633057, "start": 16106, "tag": "NAME", "value": "Chris" } ]
test/midje_doc/cronj_guide.clj
zcaudate/cronj
52
(ns midje-doc.cronj-guide (:require [cronj.core :refer :all] [midje.sweet :refer :all])) [[:chapter {:title "Installation"}]] "Add to `project.clj` dependencies: `[im.chit/cronj `\"`{{PROJECT.version}}`\"`]`" "All functions are in the `cronj.core` namespace." [[{:numbered false}]] (comment (use 'cronj.core)) [[:chapter {:title "Background"}]] " `cronj` was built for a project of mine back in 2012. The system needed to record video footage from multiple ip-cameras in fifteen minute blocks, as well as to save pictures from each camera (one picture every second). All saved files needed a timestamp allowing for easy file management and retrieval. At that time, `quartzite`, `at-at` and `monotony` were the most popular options. After coming up with a list of design features and weighing up all options, I decided to write my own instead. As a core component of the original project, `cronj` has been operational now since October 2012. A couple of major rewrites and api rejuggling were done, but the api has been very stable from version `0.6` onwards. There are now many more scheduling libraries in the clojure world: - [at-at](https://github.com/overtone/at-at) - [chime](https://github.com/james-henderson/chime) - [clj-cronlike](https://github.com/kognate/clj-cronlike) - [cron4j](http://www.sauronsoftware.it/projects/cron4j) - [monotony](https://github.com/aredington/monotony) - [quartzite](https://github.com/michaelklishin/quartzite) - [schejulure](https://github.com/AdamClements/schejulure) With so many options, and so many different ways to define task schedules, why choose `cronj`? I have listed a number of [design](#design) decisions that make it beneficial. However, for those that are impatient, cut to the chase, by skipping to the [simulations](#running-simulations) section. " [[:chapter {:title "Design"}]] "`cronj` was built around a concept of a **task**. A task has two components: - A `handler` (what is to be done) - A `schedule` (when it should be done) Tasks are *triggered* by a `scheduler` who in-turn is notified of the current time by a `timer`. If a task was scheduled to run at that time, it's `handler` would be run in a seperate thread. " [[{:numbered false}]] (comment ; cronj schedule ; -------------- +-------------------------+ ; scheduler watches | '* 8 /2 7-9 2,3 * *' | ; the timer and +-------------------------+ ; triggers tasks | :sec [:*] | ; to execute at | :min [:# 8] | ; the scheduled time | :hour [:| 2] | ; | :dayw [:- 7 9] | ; | :daym [:# 2] [:# 3] | ; | :month [:*] | ; | :year [:*] | ; +-----------+-------------+ ; task | XXXXXXXXX ; +-----------------+ +-----------+-----+ XX XX ; |:id | | | |\ XX timer XX ; |:desc +---+-+:task | | \ X X ; |:handler | | :schedule+ | \ X :start-time X ; |:pre-hook | | :enabled | entry X :thread X+----+ ; |:post-hook | | :opts | `. X :last-check X | ; |:enabled | | | \ X :interval X | ; |:args | _-------._--------, \ XX XX | ; |:running | `-._ `.. `. \ XX XX + ; |:last-exec | `-._ `-._ `. \ XXXXXXXXX watch ; |:last-successful | `-._ `-._ `. `. + ; +----------+------+ `-._ `-. `. \ | ; +----+----+----`-._-+-`-.`.--->----+----+----+----+----+----+ ; | | | | `-.. | `. | | | | | | | ; +----+----+----+----+--`-.---'+----+----+----+----+----+----+ ; scheduler ) [[:section {:title "Seperation of Concerns"}]] " A task handler is just a function taking two arguments: " [[{:numbered false}]] (comment (fn [t opts] (... perform a task ...))) " **`t`** represents the time at which the handler was called. This solves the problem of *time synchronisation*. For example, I may have three tasks scheduled to run at a same time: - perform a calculation and write the result to the database - perform a http call and write result to the database - load some files, write to single output then store file location to the database. All these tasks will end at different times. To retrospectively reasoning about how all three tasks were synced, each handler is required to accept the triggred time `t` as an argument. **`opts`** is a hashmap, for example `{:path '/app/videos'}`. It has been found that user customisations such as server addresses and filenames, along with job schedules are usually specified at the top-most tier of the application whilst handler logic is usually in the middle-tier. Having an extra `opts` argument allow for better seperation of concerns and more readable code. " [[:section {:title "Thread Management"}]] " In reviewing other scheduling libraries, it was found that fully-featured thread management capabilities were lacking. `cronj` was designed with these features in mind: - tasks can be triggered to start manually at any time. - tasks can start at the next scheduled time before the previous thread has finished running so that multiple threads can be running simultaneously for a single task. - *pre-* and *post-* hooks can be defined for better seperation of setup/notification/cleanup code from handler body. - running threads can be listed. - normal and abnormal termination: - kill a running thread - kill all running threads in a task - kill all threads - disable task but let running threads finish - stop timer but let running threads finish - shutdown timer, kill all running threads " [[:section {:title "Simulation Testing"}]] " Because the `timer` and the `scheduler` modules have been completely decoupled, it was very easy to add a simulation component into `cronj`. Simulation has some very handy features: - Simulate how the entire system would behave over a long periods of time - Generating test inputs for other applications. - Both single and multi-threaded execution strategies are supported. " [[:chapter {:title "Walkthrough"}]] "In this section all the important and novel features and use cases for `cronj` will be shown. Interesting examples include: [simulation](#running-simulations), [task management](#task-management) and [hooks](#hooks)." [[:section {:title "Creating a Task"}]] "`print-handler` outputs the value of `{:output opts}` and the time `t`." [[{:numbered false}]] (defn print-handler [t opts] (println (:output opts) ": " t)) "`print-task` defines the actual task to be run. Note that it is just a map. - `:handler` set to `print-handler` - `:schedule` set for task to run every `2` seconds - `:opts` can be customised " [[{:numbered false}]] (def print-task {:id "print-task" :handler print-handler :schedule "/2 * * * * * *" :opts {:output "Hello There"}}) [[:section {:title "Running Tasks"}]] "Once the task is defined, `cronj` is called to create the task-scheduler (`cj`)." [[{:numbered false}]] (def cj (cronj :entries [print-task])) "Calling `start!` on `cj` will start the timer and `print-handler` will be triggered every two seconds. Calling `stop!` on `cj` will stop all outputs" [[{:numbered false}]] (comment (start! cj) ;; > Hello There : #<DateTime 2013-09-29T14:42:54.000+10:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2013-09-29T14:42:56.000+10:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2013-09-29T14:42:58.000+10:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2013-09-29T14:43:00.000+10:00> (stop! cj)) [[:section {:title "Running Simulations"}]] "Simulations are a great way to check your application for errors as they provide constant time inputs. This allows an entire system to be tested for correctness. How `simulate` works is that it decouples the `timer` from the `scheduler` and tricks the `scheduler` to trigger on the range of date inputs provided." [[:subsection {:title "Y2K Revisited"}]] "For instance, we wish to test that our `print-handler` method was not affected by the Y2K Bug. `T1` and `T2` are defined as start and end times:" [[{:numbered false}]] (def T1 (local-time 1999 12 31 23 59 58)) (def T2 (local-time 2000 1 1 0 0 2)) "We can simulate events by calling `simulate` on `cj` with a start and end time. The function will trigger registered tasks to run beginning at T1, incrementing by 1 sec each time until T2. Note that in this example, there are three threads created for `print-handler`. The printed output may be out of order because of indeterminancy of threads (we can fix this later)." [[{:numbered false}]] (comment (simulate cj T1 T2) .... instantly ... ;; > Hello There : #<DateTime 1999-12-31T23:59:58.000+11:00> ;; > Hello There : #<DateTime 2000-01-01T00:00:02.000+11:00> ;; out of order ;; > Hello There : #<DateTime 2000-01-01T00:00:00.000+11:00> ) [[:subsection {:title "Single Threaded"}]] "To keep ordering of the `println` outputs, `simulate-st` can be used. This will run `print-handler` calls on a single thread and so will keep order of outputs. Because of the sequential nature of this type of simulation, it is advised that `simulate-st` be used only if there are no significant pauses or thread blocking in the tasks." [[{:numbered false}]] (comment (simulate-st cj T1 T2) .... instantly ... ;; > Hello There : #<DateTime 1999-12-31T23:59:58.000+11:00> ;; > Hello There : #<DateTime 2000-01-01T00:00:00.000+11:00> ;; > Hello There : #<DateTime 2000-01-01T00:00:02.000+11:00> ) [[:subsection {:title "Interval and Pause"}]] "Two other arguments for `simulate` and `simulate-st` are: - the time interval `(in secs)` between the current time-point and the next time-point (the default is 1) - the pause `(in ms)` to take in triggering the next time-point (the default is 0) It can be seen that we can simulate the actual speed of outputs by keeping the interval as 1 and increasing the pause time to 1000ms" [[{:numbered false}]] (comment (simulate cj T1 T2 1 1000) ;; > Hello There : #<DateTime 1999-12-31T23:59:58.000+11:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2000-01-01T00:00:00.000+11:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2000-01-01T00:00:02.000+11:00> ) [[:subsection {:title "Speeding Up"}]] "In the following example, the interval has been increased to 2 seconds whilst the pause time has decreased to 100ms. This results in a 20x increase in the speed of outputs." [[{:numbered false}]] (comment (simulate cj T1 T2 2 100) ;; > Hello There : #<DateTime 1999-12-31T23:59:58.000+11:00> .... wait 100 msecs ... ;; > Hello There : #<DateTime 2000-01-01T00:00:00.000+11:00> .... wait 100 msecs ... ;; > Hello There : #<DateTime 2000-01-01T00:00:02.000+11:00> ) "Being able to adjust these simulation parameters are really powerful testing tools and saves an incredible amount of time in development. For example, we can quickly test the year long output of a task that is scheduled to run once an hour very quickly by making the interval 3600 seconds and the pause time to the same length of time that the task takes to finish. Through simulations, task-scheduling can now be tested and entire systems just got easier to manage and reason about!" [[:section {:title "Task Management"}]] "Task management capabilities of `cronj` will be demonstrated by first creating a `cronj` object with two task entries labeled `l1` and `l2` doing nothing but sleeping for a long time:" [[{:numbered false}]] (def cj (cronj :entries [{:id :l1 :handler (fn [dt opts] (Thread/sleep 30000000000000)) :schedule "/2 * * * * * *" :opts {:data "foo"}} {:id :l2 :handler (fn [dt opts] (Thread/sleep 30000000000000)) :schedule "0-2 * * * * * *" :opts {:data "bar"}}])) [[:subsection {:title "Showing Threads"}]] " The task will be triggered using the `exec!` command. This is done for play purposes. Normal use would involve calling `get-threads` after `start!` has been called." [[{:numbered false}]] (fact (get-threads cj :l1) ;; See that there are no threads running => [] ;; - :l1 is empty (get-threads cj :l2) => [] ;; - :l2 is empty (exec! cj :l1 T1) ;; Launch :l1 with time of T1 (get-threads cj :l1) => [{:tid T1 :opts {:data "foo"}}] ;; l1 now has one running thread (exec! cj :l1 T2) ;; Launch :l2 with time of T2 (get-threads cj :l1) => [{:tid T1 :opts {:data "foo"}} ;; l1 now has two running threads {:tid T2 :opts {:data "foo"}}] (exec! cj :l2 T2 {:data "new"}) ;; Launch :l2 with time of T2 (get-threads cj :l2) => [{:tid T2 :opts {:data "new"}}] ;; l2 now has one running thread (get-threads cj) ;; if no id is given, all running threads can be seen => [{:id :l1, :running [{:tid T1 :opts {:data "foo"}} {:tid T2 :opts {:data "foo"}}]} {:id :l2, :running [{:tid T2 :opts {:data "new"}}]}]) [[:subsection {:title "Killing Threads"}]] [[{:numbered false}]] (fact (kill! cj :l1 T1) ;; Kill :l1 thread starting at time T1 (get-threads cj :l1) => [{:opts {:data "foo"}, :tid T2}] ;; l1 now has one running thread (kill! cj :l1) ;; Kill all :l1 threads (get-threads cj :l1) => [] ;; l1 now has no threads (kill! cj) ;; Kill everything in cj (get-threads cj) => [{:id :l1, :running []} ;; All threads have been killed {:id :l2, :running []}]) [[:section {:title "Pre and Post Hooks" :tag "hooks"}]] "Having pre- and post- hook entries allow additional processing to be done outside of the handler. They also have the same function signature as the task handler. An example below can be seen where data is passed from one handler to another:" [[{:numbered false}]] (comment (def cj (cronj :entries [{:id :hook :desc "This is showing how a hook example should work" :handler (fn [dt opts] (println "In handle, opts:" opts) (Thread/sleep 1000) ;; Do Something :handler-result) :pre-hook (fn [dt opts] (println "In pre-hook," "opts:" opts) (assoc opts :pre-hook :pre-hook-data)) :post-hook (fn [dt opts] (println "In post-hook, opts: " opts)) :opts {:data "stuff"} :schedule "* * * * * * *"}])) (exec! cj :hook T1) ;; > In pre-hook, opts: {:data stuff} ;; > In handle, opts: {:data stuff, :pre-hook :pre-hook-data} .... wait 1000 msecs .... ;; > In post-hook, opts: {:data stuff, :pre-hook :pre-hook-data, :result :handler-result} ) "As could be seen, the `:pre-hook` function can modify opts for use in the handler function while `:pre-hook` can take the result of the main handler and do something with it. I use it mostly for logging purposes." [[:file {:src "test/midje_doc/cronj_api.clj"}]] [[:chapter {:title "End Notes"}]] "For any feedback, requests and comments, please feel free to lodge an issue on github or contact me directly. Chris. "
19679
(ns midje-doc.cronj-guide (:require [cronj.core :refer :all] [midje.sweet :refer :all])) [[:chapter {:title "Installation"}]] "Add to `project.clj` dependencies: `[im.chit/cronj `\"`{{PROJECT.version}}`\"`]`" "All functions are in the `cronj.core` namespace." [[{:numbered false}]] (comment (use 'cronj.core)) [[:chapter {:title "Background"}]] " `cronj` was built for a project of mine back in 2012. The system needed to record video footage from multiple ip-cameras in fifteen minute blocks, as well as to save pictures from each camera (one picture every second). All saved files needed a timestamp allowing for easy file management and retrieval. At that time, `quartzite`, `at-at` and `monotony` were the most popular options. After coming up with a list of design features and weighing up all options, I decided to write my own instead. As a core component of the original project, `cronj` has been operational now since October 2012. A couple of major rewrites and api rejuggling were done, but the api has been very stable from version `0.6` onwards. There are now many more scheduling libraries in the clojure world: - [at-at](https://github.com/overtone/at-at) - [chime](https://github.com/james-henderson/chime) - [clj-cronlike](https://github.com/kognate/clj-cronlike) - [cron4j](http://www.sauronsoftware.it/projects/cron4j) - [monotony](https://github.com/aredington/monotony) - [quartzite](https://github.com/michaelklishin/quartzite) - [schejulure](https://github.com/AdamClements/schejulure) With so many options, and so many different ways to define task schedules, why choose `cronj`? I have listed a number of [design](#design) decisions that make it beneficial. However, for those that are impatient, cut to the chase, by skipping to the [simulations](#running-simulations) section. " [[:chapter {:title "Design"}]] "`cronj` was built around a concept of a **task**. A task has two components: - A `handler` (what is to be done) - A `schedule` (when it should be done) Tasks are *triggered* by a `scheduler` who in-turn is notified of the current time by a `timer`. If a task was scheduled to run at that time, it's `handler` would be run in a seperate thread. " [[{:numbered false}]] (comment ; cronj schedule ; -------------- +-------------------------+ ; scheduler watches | '* 8 /2 7-9 2,3 * *' | ; the timer and +-------------------------+ ; triggers tasks | :sec [:*] | ; to execute at | :min [:# 8] | ; the scheduled time | :hour [:| 2] | ; | :dayw [:- 7 9] | ; | :daym [:# 2] [:# 3] | ; | :month [:*] | ; | :year [:*] | ; +-----------+-------------+ ; task | XXXXXXXXX ; +-----------------+ +-----------+-----+ XX XX ; |:id | | | |\ XX timer XX ; |:desc +---+-+:task | | \ X X ; |:handler | | :schedule+ | \ X :start-time X ; |:pre-hook | | :enabled | entry X :thread X+----+ ; |:post-hook | | :opts | `. X :last-check X | ; |:enabled | | | \ X :interval X | ; |:args | _-------._--------, \ XX XX | ; |:running | `-._ `.. `. \ XX XX + ; |:last-exec | `-._ `-._ `. \ XXXXXXXXX watch ; |:last-successful | `-._ `-._ `. `. + ; +----------+------+ `-._ `-. `. \ | ; +----+----+----`-._-+-`-.`.--->----+----+----+----+----+----+ ; | | | | `-.. | `. | | | | | | | ; +----+----+----+----+--`-.---'+----+----+----+----+----+----+ ; scheduler ) [[:section {:title "Seperation of Concerns"}]] " A task handler is just a function taking two arguments: " [[{:numbered false}]] (comment (fn [t opts] (... perform a task ...))) " **`t`** represents the time at which the handler was called. This solves the problem of *time synchronisation*. For example, I may have three tasks scheduled to run at a same time: - perform a calculation and write the result to the database - perform a http call and write result to the database - load some files, write to single output then store file location to the database. All these tasks will end at different times. To retrospectively reasoning about how all three tasks were synced, each handler is required to accept the triggred time `t` as an argument. **`opts`** is a hashmap, for example `{:path '/app/videos'}`. It has been found that user customisations such as server addresses and filenames, along with job schedules are usually specified at the top-most tier of the application whilst handler logic is usually in the middle-tier. Having an extra `opts` argument allow for better seperation of concerns and more readable code. " [[:section {:title "Thread Management"}]] " In reviewing other scheduling libraries, it was found that fully-featured thread management capabilities were lacking. `cronj` was designed with these features in mind: - tasks can be triggered to start manually at any time. - tasks can start at the next scheduled time before the previous thread has finished running so that multiple threads can be running simultaneously for a single task. - *pre-* and *post-* hooks can be defined for better seperation of setup/notification/cleanup code from handler body. - running threads can be listed. - normal and abnormal termination: - kill a running thread - kill all running threads in a task - kill all threads - disable task but let running threads finish - stop timer but let running threads finish - shutdown timer, kill all running threads " [[:section {:title "Simulation Testing"}]] " Because the `timer` and the `scheduler` modules have been completely decoupled, it was very easy to add a simulation component into `cronj`. Simulation has some very handy features: - Simulate how the entire system would behave over a long periods of time - Generating test inputs for other applications. - Both single and multi-threaded execution strategies are supported. " [[:chapter {:title "Walkthrough"}]] "In this section all the important and novel features and use cases for `cronj` will be shown. Interesting examples include: [simulation](#running-simulations), [task management](#task-management) and [hooks](#hooks)." [[:section {:title "Creating a Task"}]] "`print-handler` outputs the value of `{:output opts}` and the time `t`." [[{:numbered false}]] (defn print-handler [t opts] (println (:output opts) ": " t)) "`print-task` defines the actual task to be run. Note that it is just a map. - `:handler` set to `print-handler` - `:schedule` set for task to run every `2` seconds - `:opts` can be customised " [[{:numbered false}]] (def print-task {:id "print-task" :handler print-handler :schedule "/2 * * * * * *" :opts {:output "Hello There"}}) [[:section {:title "Running Tasks"}]] "Once the task is defined, `cronj` is called to create the task-scheduler (`cj`)." [[{:numbered false}]] (def cj (cronj :entries [print-task])) "Calling `start!` on `cj` will start the timer and `print-handler` will be triggered every two seconds. Calling `stop!` on `cj` will stop all outputs" [[{:numbered false}]] (comment (start! cj) ;; > Hello There : #<DateTime 2013-09-29T14:42:54.000+10:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2013-09-29T14:42:56.000+10:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2013-09-29T14:42:58.000+10:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2013-09-29T14:43:00.000+10:00> (stop! cj)) [[:section {:title "Running Simulations"}]] "Simulations are a great way to check your application for errors as they provide constant time inputs. This allows an entire system to be tested for correctness. How `simulate` works is that it decouples the `timer` from the `scheduler` and tricks the `scheduler` to trigger on the range of date inputs provided." [[:subsection {:title "Y2K Revisited"}]] "For instance, we wish to test that our `print-handler` method was not affected by the Y2K Bug. `T1` and `T2` are defined as start and end times:" [[{:numbered false}]] (def T1 (local-time 1999 12 31 23 59 58)) (def T2 (local-time 2000 1 1 0 0 2)) "We can simulate events by calling `simulate` on `cj` with a start and end time. The function will trigger registered tasks to run beginning at T1, incrementing by 1 sec each time until T2. Note that in this example, there are three threads created for `print-handler`. The printed output may be out of order because of indeterminancy of threads (we can fix this later)." [[{:numbered false}]] (comment (simulate cj T1 T2) .... instantly ... ;; > Hello There : #<DateTime 1999-12-31T23:59:58.000+11:00> ;; > Hello There : #<DateTime 2000-01-01T00:00:02.000+11:00> ;; out of order ;; > Hello There : #<DateTime 2000-01-01T00:00:00.000+11:00> ) [[:subsection {:title "Single Threaded"}]] "To keep ordering of the `println` outputs, `simulate-st` can be used. This will run `print-handler` calls on a single thread and so will keep order of outputs. Because of the sequential nature of this type of simulation, it is advised that `simulate-st` be used only if there are no significant pauses or thread blocking in the tasks." [[{:numbered false}]] (comment (simulate-st cj T1 T2) .... instantly ... ;; > Hello There : #<DateTime 1999-12-31T23:59:58.000+11:00> ;; > Hello There : #<DateTime 2000-01-01T00:00:00.000+11:00> ;; > Hello There : #<DateTime 2000-01-01T00:00:02.000+11:00> ) [[:subsection {:title "Interval and Pause"}]] "Two other arguments for `simulate` and `simulate-st` are: - the time interval `(in secs)` between the current time-point and the next time-point (the default is 1) - the pause `(in ms)` to take in triggering the next time-point (the default is 0) It can be seen that we can simulate the actual speed of outputs by keeping the interval as 1 and increasing the pause time to 1000ms" [[{:numbered false}]] (comment (simulate cj T1 T2 1 1000) ;; > Hello There : #<DateTime 1999-12-31T23:59:58.000+11:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2000-01-01T00:00:00.000+11:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2000-01-01T00:00:02.000+11:00> ) [[:subsection {:title "Speeding Up"}]] "In the following example, the interval has been increased to 2 seconds whilst the pause time has decreased to 100ms. This results in a 20x increase in the speed of outputs." [[{:numbered false}]] (comment (simulate cj T1 T2 2 100) ;; > Hello There : #<DateTime 1999-12-31T23:59:58.000+11:00> .... wait 100 msecs ... ;; > Hello There : #<DateTime 2000-01-01T00:00:00.000+11:00> .... wait 100 msecs ... ;; > Hello There : #<DateTime 2000-01-01T00:00:02.000+11:00> ) "Being able to adjust these simulation parameters are really powerful testing tools and saves an incredible amount of time in development. For example, we can quickly test the year long output of a task that is scheduled to run once an hour very quickly by making the interval 3600 seconds and the pause time to the same length of time that the task takes to finish. Through simulations, task-scheduling can now be tested and entire systems just got easier to manage and reason about!" [[:section {:title "Task Management"}]] "Task management capabilities of `cronj` will be demonstrated by first creating a `cronj` object with two task entries labeled `l1` and `l2` doing nothing but sleeping for a long time:" [[{:numbered false}]] (def cj (cronj :entries [{:id :l1 :handler (fn [dt opts] (Thread/sleep 30000000000000)) :schedule "/2 * * * * * *" :opts {:data "foo"}} {:id :l2 :handler (fn [dt opts] (Thread/sleep 30000000000000)) :schedule "0-2 * * * * * *" :opts {:data "bar"}}])) [[:subsection {:title "Showing Threads"}]] " The task will be triggered using the `exec!` command. This is done for play purposes. Normal use would involve calling `get-threads` after `start!` has been called." [[{:numbered false}]] (fact (get-threads cj :l1) ;; See that there are no threads running => [] ;; - :l1 is empty (get-threads cj :l2) => [] ;; - :l2 is empty (exec! cj :l1 T1) ;; Launch :l1 with time of T1 (get-threads cj :l1) => [{:tid T1 :opts {:data "foo"}}] ;; l1 now has one running thread (exec! cj :l1 T2) ;; Launch :l2 with time of T2 (get-threads cj :l1) => [{:tid T1 :opts {:data "foo"}} ;; l1 now has two running threads {:tid T2 :opts {:data "foo"}}] (exec! cj :l2 T2 {:data "new"}) ;; Launch :l2 with time of T2 (get-threads cj :l2) => [{:tid T2 :opts {:data "new"}}] ;; l2 now has one running thread (get-threads cj) ;; if no id is given, all running threads can be seen => [{:id :l1, :running [{:tid T1 :opts {:data "foo"}} {:tid T2 :opts {:data "foo"}}]} {:id :l2, :running [{:tid T2 :opts {:data "new"}}]}]) [[:subsection {:title "Killing Threads"}]] [[{:numbered false}]] (fact (kill! cj :l1 T1) ;; Kill :l1 thread starting at time T1 (get-threads cj :l1) => [{:opts {:data "foo"}, :tid T2}] ;; l1 now has one running thread (kill! cj :l1) ;; Kill all :l1 threads (get-threads cj :l1) => [] ;; l1 now has no threads (kill! cj) ;; Kill everything in cj (get-threads cj) => [{:id :l1, :running []} ;; All threads have been killed {:id :l2, :running []}]) [[:section {:title "Pre and Post Hooks" :tag "hooks"}]] "Having pre- and post- hook entries allow additional processing to be done outside of the handler. They also have the same function signature as the task handler. An example below can be seen where data is passed from one handler to another:" [[{:numbered false}]] (comment (def cj (cronj :entries [{:id :hook :desc "This is showing how a hook example should work" :handler (fn [dt opts] (println "In handle, opts:" opts) (Thread/sleep 1000) ;; Do Something :handler-result) :pre-hook (fn [dt opts] (println "In pre-hook," "opts:" opts) (assoc opts :pre-hook :pre-hook-data)) :post-hook (fn [dt opts] (println "In post-hook, opts: " opts)) :opts {:data "stuff"} :schedule "* * * * * * *"}])) (exec! cj :hook T1) ;; > In pre-hook, opts: {:data stuff} ;; > In handle, opts: {:data stuff, :pre-hook :pre-hook-data} .... wait 1000 msecs .... ;; > In post-hook, opts: {:data stuff, :pre-hook :pre-hook-data, :result :handler-result} ) "As could be seen, the `:pre-hook` function can modify opts for use in the handler function while `:pre-hook` can take the result of the main handler and do something with it. I use it mostly for logging purposes." [[:file {:src "test/midje_doc/cronj_api.clj"}]] [[:chapter {:title "End Notes"}]] "For any feedback, requests and comments, please feel free to lodge an issue on github or contact me directly. <NAME>. "
true
(ns midje-doc.cronj-guide (:require [cronj.core :refer :all] [midje.sweet :refer :all])) [[:chapter {:title "Installation"}]] "Add to `project.clj` dependencies: `[im.chit/cronj `\"`{{PROJECT.version}}`\"`]`" "All functions are in the `cronj.core` namespace." [[{:numbered false}]] (comment (use 'cronj.core)) [[:chapter {:title "Background"}]] " `cronj` was built for a project of mine back in 2012. The system needed to record video footage from multiple ip-cameras in fifteen minute blocks, as well as to save pictures from each camera (one picture every second). All saved files needed a timestamp allowing for easy file management and retrieval. At that time, `quartzite`, `at-at` and `monotony` were the most popular options. After coming up with a list of design features and weighing up all options, I decided to write my own instead. As a core component of the original project, `cronj` has been operational now since October 2012. A couple of major rewrites and api rejuggling were done, but the api has been very stable from version `0.6` onwards. There are now many more scheduling libraries in the clojure world: - [at-at](https://github.com/overtone/at-at) - [chime](https://github.com/james-henderson/chime) - [clj-cronlike](https://github.com/kognate/clj-cronlike) - [cron4j](http://www.sauronsoftware.it/projects/cron4j) - [monotony](https://github.com/aredington/monotony) - [quartzite](https://github.com/michaelklishin/quartzite) - [schejulure](https://github.com/AdamClements/schejulure) With so many options, and so many different ways to define task schedules, why choose `cronj`? I have listed a number of [design](#design) decisions that make it beneficial. However, for those that are impatient, cut to the chase, by skipping to the [simulations](#running-simulations) section. " [[:chapter {:title "Design"}]] "`cronj` was built around a concept of a **task**. A task has two components: - A `handler` (what is to be done) - A `schedule` (when it should be done) Tasks are *triggered* by a `scheduler` who in-turn is notified of the current time by a `timer`. If a task was scheduled to run at that time, it's `handler` would be run in a seperate thread. " [[{:numbered false}]] (comment ; cronj schedule ; -------------- +-------------------------+ ; scheduler watches | '* 8 /2 7-9 2,3 * *' | ; the timer and +-------------------------+ ; triggers tasks | :sec [:*] | ; to execute at | :min [:# 8] | ; the scheduled time | :hour [:| 2] | ; | :dayw [:- 7 9] | ; | :daym [:# 2] [:# 3] | ; | :month [:*] | ; | :year [:*] | ; +-----------+-------------+ ; task | XXXXXXXXX ; +-----------------+ +-----------+-----+ XX XX ; |:id | | | |\ XX timer XX ; |:desc +---+-+:task | | \ X X ; |:handler | | :schedule+ | \ X :start-time X ; |:pre-hook | | :enabled | entry X :thread X+----+ ; |:post-hook | | :opts | `. X :last-check X | ; |:enabled | | | \ X :interval X | ; |:args | _-------._--------, \ XX XX | ; |:running | `-._ `.. `. \ XX XX + ; |:last-exec | `-._ `-._ `. \ XXXXXXXXX watch ; |:last-successful | `-._ `-._ `. `. + ; +----------+------+ `-._ `-. `. \ | ; +----+----+----`-._-+-`-.`.--->----+----+----+----+----+----+ ; | | | | `-.. | `. | | | | | | | ; +----+----+----+----+--`-.---'+----+----+----+----+----+----+ ; scheduler ) [[:section {:title "Seperation of Concerns"}]] " A task handler is just a function taking two arguments: " [[{:numbered false}]] (comment (fn [t opts] (... perform a task ...))) " **`t`** represents the time at which the handler was called. This solves the problem of *time synchronisation*. For example, I may have three tasks scheduled to run at a same time: - perform a calculation and write the result to the database - perform a http call and write result to the database - load some files, write to single output then store file location to the database. All these tasks will end at different times. To retrospectively reasoning about how all three tasks were synced, each handler is required to accept the triggred time `t` as an argument. **`opts`** is a hashmap, for example `{:path '/app/videos'}`. It has been found that user customisations such as server addresses and filenames, along with job schedules are usually specified at the top-most tier of the application whilst handler logic is usually in the middle-tier. Having an extra `opts` argument allow for better seperation of concerns and more readable code. " [[:section {:title "Thread Management"}]] " In reviewing other scheduling libraries, it was found that fully-featured thread management capabilities were lacking. `cronj` was designed with these features in mind: - tasks can be triggered to start manually at any time. - tasks can start at the next scheduled time before the previous thread has finished running so that multiple threads can be running simultaneously for a single task. - *pre-* and *post-* hooks can be defined for better seperation of setup/notification/cleanup code from handler body. - running threads can be listed. - normal and abnormal termination: - kill a running thread - kill all running threads in a task - kill all threads - disable task but let running threads finish - stop timer but let running threads finish - shutdown timer, kill all running threads " [[:section {:title "Simulation Testing"}]] " Because the `timer` and the `scheduler` modules have been completely decoupled, it was very easy to add a simulation component into `cronj`. Simulation has some very handy features: - Simulate how the entire system would behave over a long periods of time - Generating test inputs for other applications. - Both single and multi-threaded execution strategies are supported. " [[:chapter {:title "Walkthrough"}]] "In this section all the important and novel features and use cases for `cronj` will be shown. Interesting examples include: [simulation](#running-simulations), [task management](#task-management) and [hooks](#hooks)." [[:section {:title "Creating a Task"}]] "`print-handler` outputs the value of `{:output opts}` and the time `t`." [[{:numbered false}]] (defn print-handler [t opts] (println (:output opts) ": " t)) "`print-task` defines the actual task to be run. Note that it is just a map. - `:handler` set to `print-handler` - `:schedule` set for task to run every `2` seconds - `:opts` can be customised " [[{:numbered false}]] (def print-task {:id "print-task" :handler print-handler :schedule "/2 * * * * * *" :opts {:output "Hello There"}}) [[:section {:title "Running Tasks"}]] "Once the task is defined, `cronj` is called to create the task-scheduler (`cj`)." [[{:numbered false}]] (def cj (cronj :entries [print-task])) "Calling `start!` on `cj` will start the timer and `print-handler` will be triggered every two seconds. Calling `stop!` on `cj` will stop all outputs" [[{:numbered false}]] (comment (start! cj) ;; > Hello There : #<DateTime 2013-09-29T14:42:54.000+10:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2013-09-29T14:42:56.000+10:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2013-09-29T14:42:58.000+10:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2013-09-29T14:43:00.000+10:00> (stop! cj)) [[:section {:title "Running Simulations"}]] "Simulations are a great way to check your application for errors as they provide constant time inputs. This allows an entire system to be tested for correctness. How `simulate` works is that it decouples the `timer` from the `scheduler` and tricks the `scheduler` to trigger on the range of date inputs provided." [[:subsection {:title "Y2K Revisited"}]] "For instance, we wish to test that our `print-handler` method was not affected by the Y2K Bug. `T1` and `T2` are defined as start and end times:" [[{:numbered false}]] (def T1 (local-time 1999 12 31 23 59 58)) (def T2 (local-time 2000 1 1 0 0 2)) "We can simulate events by calling `simulate` on `cj` with a start and end time. The function will trigger registered tasks to run beginning at T1, incrementing by 1 sec each time until T2. Note that in this example, there are three threads created for `print-handler`. The printed output may be out of order because of indeterminancy of threads (we can fix this later)." [[{:numbered false}]] (comment (simulate cj T1 T2) .... instantly ... ;; > Hello There : #<DateTime 1999-12-31T23:59:58.000+11:00> ;; > Hello There : #<DateTime 2000-01-01T00:00:02.000+11:00> ;; out of order ;; > Hello There : #<DateTime 2000-01-01T00:00:00.000+11:00> ) [[:subsection {:title "Single Threaded"}]] "To keep ordering of the `println` outputs, `simulate-st` can be used. This will run `print-handler` calls on a single thread and so will keep order of outputs. Because of the sequential nature of this type of simulation, it is advised that `simulate-st` be used only if there are no significant pauses or thread blocking in the tasks." [[{:numbered false}]] (comment (simulate-st cj T1 T2) .... instantly ... ;; > Hello There : #<DateTime 1999-12-31T23:59:58.000+11:00> ;; > Hello There : #<DateTime 2000-01-01T00:00:00.000+11:00> ;; > Hello There : #<DateTime 2000-01-01T00:00:02.000+11:00> ) [[:subsection {:title "Interval and Pause"}]] "Two other arguments for `simulate` and `simulate-st` are: - the time interval `(in secs)` between the current time-point and the next time-point (the default is 1) - the pause `(in ms)` to take in triggering the next time-point (the default is 0) It can be seen that we can simulate the actual speed of outputs by keeping the interval as 1 and increasing the pause time to 1000ms" [[{:numbered false}]] (comment (simulate cj T1 T2 1 1000) ;; > Hello There : #<DateTime 1999-12-31T23:59:58.000+11:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2000-01-01T00:00:00.000+11:00> .... wait 2 secs ... ;; > Hello There : #<DateTime 2000-01-01T00:00:02.000+11:00> ) [[:subsection {:title "Speeding Up"}]] "In the following example, the interval has been increased to 2 seconds whilst the pause time has decreased to 100ms. This results in a 20x increase in the speed of outputs." [[{:numbered false}]] (comment (simulate cj T1 T2 2 100) ;; > Hello There : #<DateTime 1999-12-31T23:59:58.000+11:00> .... wait 100 msecs ... ;; > Hello There : #<DateTime 2000-01-01T00:00:00.000+11:00> .... wait 100 msecs ... ;; > Hello There : #<DateTime 2000-01-01T00:00:02.000+11:00> ) "Being able to adjust these simulation parameters are really powerful testing tools and saves an incredible amount of time in development. For example, we can quickly test the year long output of a task that is scheduled to run once an hour very quickly by making the interval 3600 seconds and the pause time to the same length of time that the task takes to finish. Through simulations, task-scheduling can now be tested and entire systems just got easier to manage and reason about!" [[:section {:title "Task Management"}]] "Task management capabilities of `cronj` will be demonstrated by first creating a `cronj` object with two task entries labeled `l1` and `l2` doing nothing but sleeping for a long time:" [[{:numbered false}]] (def cj (cronj :entries [{:id :l1 :handler (fn [dt opts] (Thread/sleep 30000000000000)) :schedule "/2 * * * * * *" :opts {:data "foo"}} {:id :l2 :handler (fn [dt opts] (Thread/sleep 30000000000000)) :schedule "0-2 * * * * * *" :opts {:data "bar"}}])) [[:subsection {:title "Showing Threads"}]] " The task will be triggered using the `exec!` command. This is done for play purposes. Normal use would involve calling `get-threads` after `start!` has been called." [[{:numbered false}]] (fact (get-threads cj :l1) ;; See that there are no threads running => [] ;; - :l1 is empty (get-threads cj :l2) => [] ;; - :l2 is empty (exec! cj :l1 T1) ;; Launch :l1 with time of T1 (get-threads cj :l1) => [{:tid T1 :opts {:data "foo"}}] ;; l1 now has one running thread (exec! cj :l1 T2) ;; Launch :l2 with time of T2 (get-threads cj :l1) => [{:tid T1 :opts {:data "foo"}} ;; l1 now has two running threads {:tid T2 :opts {:data "foo"}}] (exec! cj :l2 T2 {:data "new"}) ;; Launch :l2 with time of T2 (get-threads cj :l2) => [{:tid T2 :opts {:data "new"}}] ;; l2 now has one running thread (get-threads cj) ;; if no id is given, all running threads can be seen => [{:id :l1, :running [{:tid T1 :opts {:data "foo"}} {:tid T2 :opts {:data "foo"}}]} {:id :l2, :running [{:tid T2 :opts {:data "new"}}]}]) [[:subsection {:title "Killing Threads"}]] [[{:numbered false}]] (fact (kill! cj :l1 T1) ;; Kill :l1 thread starting at time T1 (get-threads cj :l1) => [{:opts {:data "foo"}, :tid T2}] ;; l1 now has one running thread (kill! cj :l1) ;; Kill all :l1 threads (get-threads cj :l1) => [] ;; l1 now has no threads (kill! cj) ;; Kill everything in cj (get-threads cj) => [{:id :l1, :running []} ;; All threads have been killed {:id :l2, :running []}]) [[:section {:title "Pre and Post Hooks" :tag "hooks"}]] "Having pre- and post- hook entries allow additional processing to be done outside of the handler. They also have the same function signature as the task handler. An example below can be seen where data is passed from one handler to another:" [[{:numbered false}]] (comment (def cj (cronj :entries [{:id :hook :desc "This is showing how a hook example should work" :handler (fn [dt opts] (println "In handle, opts:" opts) (Thread/sleep 1000) ;; Do Something :handler-result) :pre-hook (fn [dt opts] (println "In pre-hook," "opts:" opts) (assoc opts :pre-hook :pre-hook-data)) :post-hook (fn [dt opts] (println "In post-hook, opts: " opts)) :opts {:data "stuff"} :schedule "* * * * * * *"}])) (exec! cj :hook T1) ;; > In pre-hook, opts: {:data stuff} ;; > In handle, opts: {:data stuff, :pre-hook :pre-hook-data} .... wait 1000 msecs .... ;; > In post-hook, opts: {:data stuff, :pre-hook :pre-hook-data, :result :handler-result} ) "As could be seen, the `:pre-hook` function can modify opts for use in the handler function while `:pre-hook` can take the result of the main handler and do something with it. I use it mostly for logging purposes." [[:file {:src "test/midje_doc/cronj_api.clj"}]] [[:chapter {:title "End Notes"}]] "For any feedback, requests and comments, please feel free to lodge an issue on github or contact me directly. PI:NAME:<NAME>END_PI. "
[ { "context": " dhs-config)\n :headers {\"apikey\" \"testuser\"}\n :as :json}]\n (fn [rest-path", "end": 1447, "score": 0.901634156703949, "start": 1439, "tag": "KEY", "value": "testuser" } ]
src/main/clojure/seazme/sources/datahub.clj
paypal/seazme-sources
7
(ns seazme.sources.datahub (:require [clojure.data.json :as json] [clj-http.client :as chc] [seazme.sources.twiki :as t] [seazme.sources.confluence :as c] [seazme.sources.jira-api :as jira-api] [seazme.sources.jira :as j] [seazme.sources.snow :as s] [clj-time.format :as tf] [clj-time.core :as tr] [clj-time.coerce :as te] [clojure.tools.logging :as log]) (:use seazme.common.common)) ;;TODO replace conf->confluence everywhere ;;TODO check datahub status prior starting sessions ;; ;; common ;; (def continue-default 40) ;;depends on hub's time-span and find-periods (defn make-sure[] ;;TODO automate this (println "Please delete a few last entries/days from cache dir, as they contain unnecessary data") (println "Warning: it might take a while to see results as all entries in the cache have to be verified")) (defn- wrap-with-counter[f] (let [counter (atom 0)] [counter (fn[& args] (swap! counter inc) (apply f args))])) (defn- jts-to-str[jts] (->> jts te/from-long (tf/unparse (tf/formatters :mysql)))) ;;TODO move insecure to config ;;combine get and post ;;TODO handle 413 > than client_max_body_size 64M; (defn mk-datahub-post-api[dhs-config] (let [url (str (:host dhs-config) "/v1/datahub/") options {:insecure? true :throw-exceptions true :basic-auth (:basic-auth dhs-config) :headers {"apikey" "testuser"} :as :json}] (fn [rest-path body] (select-keys (chc/post (str url rest-path) (if body (merge options {:content-type :json :body body}) options)) [:body :status] )))) #_(chc/post "https://*/v1/datahub/intake-sessions/20171110003823\\7506ad50-c5af-11e7-9dee-4f6e83cbd595/document" {:content-type :json :body (json/write-str content) :insecure? true :throw-exceptions false :basic-auth ["*" "*"] :as :json}) (defn mk-datahub-get-api[dhs-config] (let [url (str (:host dhs-config) "/v1/datahub/") options {:insecure? true :throw-exceptions true :basic-auth (:basic-auth dhs-config)}] (fn [rest-path] (:body (chc/get (str url rest-path) options))))) ;; ;; Twiki ;; (defn twiki-scan![{:keys [app-id index kind path]} d {:keys [path]}] #_(prn "DEBUG" index kind d s) (println "STARTING twiki-scan:"app-id index kind path(str "@"(tr/now))) (let [p (mk-datahub-post-api d) {:keys [body status]} (p (format "intake-sessions?app-id=%s&description=twiki full scan&command=scan" app-id) nil) session-id (:key body) [counter cb] (wrap-with-counter #(p (format "intake-sessions/%s/document" session-id) (json/write-str %))) ret1 (->> path t/find-topics #_(take 10) ;;TODO do partitions (remove nil?) (map t/read-topic!) (remove nil?) (map cb) frequencies) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil) ] (println "SUCCEEDED:" (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) ) ) ;; ;; Confluence ;; (defn confluence-scan![{:keys [app-id index kind]} d s] #_(prn "DEBUG" index kind d s) (println "STARTING confluence-scan:"app-id index kind(str "@"(tr/now))) (let [p (mk-datahub-post-api d) {:keys [body status]} (p (format "intake-sessions?app-id=%s&description=Confluence full scan&command=scan" app-id) nil) session-id (:key body) [counter cb] (wrap-with-counter #(p (format "intake-sessions/%s/document" session-id) (json/write-str %))) ret1 (->> s c/find-spaces ;;(drop 1) (take 1);;TODO (map (partial c/save-space-from-search2 s cb)) flatten frequencies) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil) ] (println "SUCCEEDED:" (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) ) ) (defn confluence-update![{:keys [app-id index kind]} d s continue] #_(prn "DEBUG" index kind d s continue) (println "STARTING confluence-update:"app-id index kind(str "@"(tr/now))) (let [p (mk-datahub-post-api d)] (loop [limit continue-default] (when (pos? limit) (let [{:keys [body status]} (p (format "intake-sessions?app-id=%s&description=Confluence update&command=update" app-id) nil)] (condp = status 200 (let [session-id (:key body) {{:keys [from to]} :range} body [counter cb] (wrap-with-counter #(p (format "intake-sessions/%s/document" session-id) (json/write-str %))) ret1 (->> (c/pull-confl-incr2 s cb from to) frequencies) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil)] (println "SUCCEEDED:" (jts-to-str from) (jts-to-str to) status (pr-str body) (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) (when continue (recur (dec limit)))) 202 (println "FINISHED:" status (pr-str body)(str "@"(tr/now))) (log/error "FAILED" status body))))))) ;; ;; JIRA ;; (def scanned-jira-keys (atom {})) (defn- to-datahub[p payload] (let [jira-key (-> payload :key) jira-id (-> payload :id) updated (-> payload :fields :updated)] (locking (.intern jira-key) (let [old-updated (@scanned-jira-keys jira-key)] (if (neg? (compare old-updated updated)) (do (swap! scanned-jira-keys assoc jira-key updated) (sync-println "\tposting:" jira-key jira-id updated old-updated) (and p (p payload))) (sync-println "\tskipping:" jira-key jira-id updated old-updated)))))) (defn jira-scan![context d s] #_(prn "DEBUG" context d s) (println "STARTING jira-scan:"context(str "@"(tr/now))) (make-sure) (let [{:keys [app-id index kind]} context pf (get s :parallel-factor 1) p (mk-datahub-post-api d) {:keys [body status]} (p (format "intake-sessions?app-id=%s&description=JIRA full scan&command=scan" app-id) nil) session-id (:key body) pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s)) [counter cb] (wrap-with-counter (partial to-datahub #(p (format "intake-sessions/%s/document" session-id) (json/write-str %)))) ret1 (->> (j/find-periods) (pmapr pf (partial j/upload-period context (:cache s) false pja-search-api cb)) flatten frequencies) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil)] (println "SUCCEEDED:" (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) )) (defn jira-patch![context d s jql] #_(prn "DEBUG" context d s jql) (println "STARTING jira-patch:"context(str "@"(tr/now))) (println "WARNINIG: please suspend update due to slight risk of overwriting issues") (let [{:keys [app-id index kind]} context p (mk-datahub-post-api d) {:keys [body status]} (p (format "intake-sessions?app-id=%s&description=JIRA patch&command=patch" app-id) nil);;TODO for parameters #_ (prn "DEBUG" body) session-id (:key body) pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s)) [counter cb] (wrap-with-counter (partial to-datahub #(p (format "intake-sessions/%s/document" session-id) (json/write-str %)))) ret1 (j/upload-by-jql context pja-search-api cb jql) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil)] (println "SUCCEEDED:" (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) )) (defn jira-update![context d s continue] #_(prn "DEBUG" context d s continue) (println "STARTING jira-update:"context(str "@"(tr/now))) (let [{:keys [app-id index kind]} context p (mk-datahub-post-api d) pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s))] (loop [limit continue-default] (when (pos? limit) (let [{:keys [body status]} (p (format "intake-sessions?app-id=%s&description=JIRA update&command=update" app-id) nil)] (condp = status 200 (let [session-id (:key body) {{:keys [from to]} :range} body [counter cb] (wrap-with-counter (partial to-datahub #(p (format "intake-sessions/%s/document" session-id) (json/write-str %)))) ret1 (j/upload-period context (:cache s) false pja-search-api cb (list from to)) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil)] (println "SUCCEEDED:" (jts-to-str from) (jts-to-str to) status (pr-str body) (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) (when continue (recur (dec limit)))) 202 (println "FINISHED:" status (pr-str body)(str "@"(tr/now))) (log/error "FAILED" status body))))))) (defn jira-scan-to-cache![context s] #_(prn "DEBUG" context s) (println "STARTING jira-scan-to-cache:"context(str "@"(tr/now))) (make-sure) (let [pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s)) pf (get s :parallel-factor 1)] (->> (j/find-periods) (pmapr pf (partial j/upload-period context true true pja-search-api #(sync-println "\tposting:" (:key %) (:id %) (-> % :fields :updated)))) flatten frequencies) )) (defn jira-patch-to-cache![context d s jql] #_(prn "DEBUG" context d s jql) (println "STARTING jira-patch-to-cache:"context(str "@"(tr/now))) (let [pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s))] (->> (j/upload-by-jql context pja-search-api (constantly "done") jql) frequencies) )) ;; ;; SNOW ;; (defn- print-and-pass[a] (println (frequencies a)) a) (defn snow-scan![{:keys [index kind]} d s] (let [p (mk-datahub-post-api d) api (:basic-auth s) in-se (p "intake-sessions?app-id=4&description=this is snow test&command=scan" nil);;TODO appid from config cb #(p (format "intake-sessions/%s/document" (:key in-se)) (json/write-str %))] (->> (s/find-periods) (map (partial s/upload-period (s/mk-snow-api api) cb)) (map print-and-pass) flatten frequencies) ) )
44572
(ns seazme.sources.datahub (:require [clojure.data.json :as json] [clj-http.client :as chc] [seazme.sources.twiki :as t] [seazme.sources.confluence :as c] [seazme.sources.jira-api :as jira-api] [seazme.sources.jira :as j] [seazme.sources.snow :as s] [clj-time.format :as tf] [clj-time.core :as tr] [clj-time.coerce :as te] [clojure.tools.logging :as log]) (:use seazme.common.common)) ;;TODO replace conf->confluence everywhere ;;TODO check datahub status prior starting sessions ;; ;; common ;; (def continue-default 40) ;;depends on hub's time-span and find-periods (defn make-sure[] ;;TODO automate this (println "Please delete a few last entries/days from cache dir, as they contain unnecessary data") (println "Warning: it might take a while to see results as all entries in the cache have to be verified")) (defn- wrap-with-counter[f] (let [counter (atom 0)] [counter (fn[& args] (swap! counter inc) (apply f args))])) (defn- jts-to-str[jts] (->> jts te/from-long (tf/unparse (tf/formatters :mysql)))) ;;TODO move insecure to config ;;combine get and post ;;TODO handle 413 > than client_max_body_size 64M; (defn mk-datahub-post-api[dhs-config] (let [url (str (:host dhs-config) "/v1/datahub/") options {:insecure? true :throw-exceptions true :basic-auth (:basic-auth dhs-config) :headers {"apikey" "<KEY>"} :as :json}] (fn [rest-path body] (select-keys (chc/post (str url rest-path) (if body (merge options {:content-type :json :body body}) options)) [:body :status] )))) #_(chc/post "https://*/v1/datahub/intake-sessions/20171110003823\\7506ad50-c5af-11e7-9dee-4f6e83cbd595/document" {:content-type :json :body (json/write-str content) :insecure? true :throw-exceptions false :basic-auth ["*" "*"] :as :json}) (defn mk-datahub-get-api[dhs-config] (let [url (str (:host dhs-config) "/v1/datahub/") options {:insecure? true :throw-exceptions true :basic-auth (:basic-auth dhs-config)}] (fn [rest-path] (:body (chc/get (str url rest-path) options))))) ;; ;; Twiki ;; (defn twiki-scan![{:keys [app-id index kind path]} d {:keys [path]}] #_(prn "DEBUG" index kind d s) (println "STARTING twiki-scan:"app-id index kind path(str "@"(tr/now))) (let [p (mk-datahub-post-api d) {:keys [body status]} (p (format "intake-sessions?app-id=%s&description=twiki full scan&command=scan" app-id) nil) session-id (:key body) [counter cb] (wrap-with-counter #(p (format "intake-sessions/%s/document" session-id) (json/write-str %))) ret1 (->> path t/find-topics #_(take 10) ;;TODO do partitions (remove nil?) (map t/read-topic!) (remove nil?) (map cb) frequencies) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil) ] (println "SUCCEEDED:" (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) ) ) ;; ;; Confluence ;; (defn confluence-scan![{:keys [app-id index kind]} d s] #_(prn "DEBUG" index kind d s) (println "STARTING confluence-scan:"app-id index kind(str "@"(tr/now))) (let [p (mk-datahub-post-api d) {:keys [body status]} (p (format "intake-sessions?app-id=%s&description=Confluence full scan&command=scan" app-id) nil) session-id (:key body) [counter cb] (wrap-with-counter #(p (format "intake-sessions/%s/document" session-id) (json/write-str %))) ret1 (->> s c/find-spaces ;;(drop 1) (take 1);;TODO (map (partial c/save-space-from-search2 s cb)) flatten frequencies) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil) ] (println "SUCCEEDED:" (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) ) ) (defn confluence-update![{:keys [app-id index kind]} d s continue] #_(prn "DEBUG" index kind d s continue) (println "STARTING confluence-update:"app-id index kind(str "@"(tr/now))) (let [p (mk-datahub-post-api d)] (loop [limit continue-default] (when (pos? limit) (let [{:keys [body status]} (p (format "intake-sessions?app-id=%s&description=Confluence update&command=update" app-id) nil)] (condp = status 200 (let [session-id (:key body) {{:keys [from to]} :range} body [counter cb] (wrap-with-counter #(p (format "intake-sessions/%s/document" session-id) (json/write-str %))) ret1 (->> (c/pull-confl-incr2 s cb from to) frequencies) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil)] (println "SUCCEEDED:" (jts-to-str from) (jts-to-str to) status (pr-str body) (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) (when continue (recur (dec limit)))) 202 (println "FINISHED:" status (pr-str body)(str "@"(tr/now))) (log/error "FAILED" status body))))))) ;; ;; JIRA ;; (def scanned-jira-keys (atom {})) (defn- to-datahub[p payload] (let [jira-key (-> payload :key) jira-id (-> payload :id) updated (-> payload :fields :updated)] (locking (.intern jira-key) (let [old-updated (@scanned-jira-keys jira-key)] (if (neg? (compare old-updated updated)) (do (swap! scanned-jira-keys assoc jira-key updated) (sync-println "\tposting:" jira-key jira-id updated old-updated) (and p (p payload))) (sync-println "\tskipping:" jira-key jira-id updated old-updated)))))) (defn jira-scan![context d s] #_(prn "DEBUG" context d s) (println "STARTING jira-scan:"context(str "@"(tr/now))) (make-sure) (let [{:keys [app-id index kind]} context pf (get s :parallel-factor 1) p (mk-datahub-post-api d) {:keys [body status]} (p (format "intake-sessions?app-id=%s&description=JIRA full scan&command=scan" app-id) nil) session-id (:key body) pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s)) [counter cb] (wrap-with-counter (partial to-datahub #(p (format "intake-sessions/%s/document" session-id) (json/write-str %)))) ret1 (->> (j/find-periods) (pmapr pf (partial j/upload-period context (:cache s) false pja-search-api cb)) flatten frequencies) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil)] (println "SUCCEEDED:" (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) )) (defn jira-patch![context d s jql] #_(prn "DEBUG" context d s jql) (println "STARTING jira-patch:"context(str "@"(tr/now))) (println "WARNINIG: please suspend update due to slight risk of overwriting issues") (let [{:keys [app-id index kind]} context p (mk-datahub-post-api d) {:keys [body status]} (p (format "intake-sessions?app-id=%s&description=JIRA patch&command=patch" app-id) nil);;TODO for parameters #_ (prn "DEBUG" body) session-id (:key body) pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s)) [counter cb] (wrap-with-counter (partial to-datahub #(p (format "intake-sessions/%s/document" session-id) (json/write-str %)))) ret1 (j/upload-by-jql context pja-search-api cb jql) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil)] (println "SUCCEEDED:" (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) )) (defn jira-update![context d s continue] #_(prn "DEBUG" context d s continue) (println "STARTING jira-update:"context(str "@"(tr/now))) (let [{:keys [app-id index kind]} context p (mk-datahub-post-api d) pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s))] (loop [limit continue-default] (when (pos? limit) (let [{:keys [body status]} (p (format "intake-sessions?app-id=%s&description=JIRA update&command=update" app-id) nil)] (condp = status 200 (let [session-id (:key body) {{:keys [from to]} :range} body [counter cb] (wrap-with-counter (partial to-datahub #(p (format "intake-sessions/%s/document" session-id) (json/write-str %)))) ret1 (j/upload-period context (:cache s) false pja-search-api cb (list from to)) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil)] (println "SUCCEEDED:" (jts-to-str from) (jts-to-str to) status (pr-str body) (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) (when continue (recur (dec limit)))) 202 (println "FINISHED:" status (pr-str body)(str "@"(tr/now))) (log/error "FAILED" status body))))))) (defn jira-scan-to-cache![context s] #_(prn "DEBUG" context s) (println "STARTING jira-scan-to-cache:"context(str "@"(tr/now))) (make-sure) (let [pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s)) pf (get s :parallel-factor 1)] (->> (j/find-periods) (pmapr pf (partial j/upload-period context true true pja-search-api #(sync-println "\tposting:" (:key %) (:id %) (-> % :fields :updated)))) flatten frequencies) )) (defn jira-patch-to-cache![context d s jql] #_(prn "DEBUG" context d s jql) (println "STARTING jira-patch-to-cache:"context(str "@"(tr/now))) (let [pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s))] (->> (j/upload-by-jql context pja-search-api (constantly "done") jql) frequencies) )) ;; ;; SNOW ;; (defn- print-and-pass[a] (println (frequencies a)) a) (defn snow-scan![{:keys [index kind]} d s] (let [p (mk-datahub-post-api d) api (:basic-auth s) in-se (p "intake-sessions?app-id=4&description=this is snow test&command=scan" nil);;TODO appid from config cb #(p (format "intake-sessions/%s/document" (:key in-se)) (json/write-str %))] (->> (s/find-periods) (map (partial s/upload-period (s/mk-snow-api api) cb)) (map print-and-pass) flatten frequencies) ) )
true
(ns seazme.sources.datahub (:require [clojure.data.json :as json] [clj-http.client :as chc] [seazme.sources.twiki :as t] [seazme.sources.confluence :as c] [seazme.sources.jira-api :as jira-api] [seazme.sources.jira :as j] [seazme.sources.snow :as s] [clj-time.format :as tf] [clj-time.core :as tr] [clj-time.coerce :as te] [clojure.tools.logging :as log]) (:use seazme.common.common)) ;;TODO replace conf->confluence everywhere ;;TODO check datahub status prior starting sessions ;; ;; common ;; (def continue-default 40) ;;depends on hub's time-span and find-periods (defn make-sure[] ;;TODO automate this (println "Please delete a few last entries/days from cache dir, as they contain unnecessary data") (println "Warning: it might take a while to see results as all entries in the cache have to be verified")) (defn- wrap-with-counter[f] (let [counter (atom 0)] [counter (fn[& args] (swap! counter inc) (apply f args))])) (defn- jts-to-str[jts] (->> jts te/from-long (tf/unparse (tf/formatters :mysql)))) ;;TODO move insecure to config ;;combine get and post ;;TODO handle 413 > than client_max_body_size 64M; (defn mk-datahub-post-api[dhs-config] (let [url (str (:host dhs-config) "/v1/datahub/") options {:insecure? true :throw-exceptions true :basic-auth (:basic-auth dhs-config) :headers {"apikey" "PI:KEY:<KEY>END_PI"} :as :json}] (fn [rest-path body] (select-keys (chc/post (str url rest-path) (if body (merge options {:content-type :json :body body}) options)) [:body :status] )))) #_(chc/post "https://*/v1/datahub/intake-sessions/20171110003823\\7506ad50-c5af-11e7-9dee-4f6e83cbd595/document" {:content-type :json :body (json/write-str content) :insecure? true :throw-exceptions false :basic-auth ["*" "*"] :as :json}) (defn mk-datahub-get-api[dhs-config] (let [url (str (:host dhs-config) "/v1/datahub/") options {:insecure? true :throw-exceptions true :basic-auth (:basic-auth dhs-config)}] (fn [rest-path] (:body (chc/get (str url rest-path) options))))) ;; ;; Twiki ;; (defn twiki-scan![{:keys [app-id index kind path]} d {:keys [path]}] #_(prn "DEBUG" index kind d s) (println "STARTING twiki-scan:"app-id index kind path(str "@"(tr/now))) (let [p (mk-datahub-post-api d) {:keys [body status]} (p (format "intake-sessions?app-id=%s&description=twiki full scan&command=scan" app-id) nil) session-id (:key body) [counter cb] (wrap-with-counter #(p (format "intake-sessions/%s/document" session-id) (json/write-str %))) ret1 (->> path t/find-topics #_(take 10) ;;TODO do partitions (remove nil?) (map t/read-topic!) (remove nil?) (map cb) frequencies) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil) ] (println "SUCCEEDED:" (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) ) ) ;; ;; Confluence ;; (defn confluence-scan![{:keys [app-id index kind]} d s] #_(prn "DEBUG" index kind d s) (println "STARTING confluence-scan:"app-id index kind(str "@"(tr/now))) (let [p (mk-datahub-post-api d) {:keys [body status]} (p (format "intake-sessions?app-id=%s&description=Confluence full scan&command=scan" app-id) nil) session-id (:key body) [counter cb] (wrap-with-counter #(p (format "intake-sessions/%s/document" session-id) (json/write-str %))) ret1 (->> s c/find-spaces ;;(drop 1) (take 1);;TODO (map (partial c/save-space-from-search2 s cb)) flatten frequencies) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil) ] (println "SUCCEEDED:" (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) ) ) (defn confluence-update![{:keys [app-id index kind]} d s continue] #_(prn "DEBUG" index kind d s continue) (println "STARTING confluence-update:"app-id index kind(str "@"(tr/now))) (let [p (mk-datahub-post-api d)] (loop [limit continue-default] (when (pos? limit) (let [{:keys [body status]} (p (format "intake-sessions?app-id=%s&description=Confluence update&command=update" app-id) nil)] (condp = status 200 (let [session-id (:key body) {{:keys [from to]} :range} body [counter cb] (wrap-with-counter #(p (format "intake-sessions/%s/document" session-id) (json/write-str %))) ret1 (->> (c/pull-confl-incr2 s cb from to) frequencies) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil)] (println "SUCCEEDED:" (jts-to-str from) (jts-to-str to) status (pr-str body) (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) (when continue (recur (dec limit)))) 202 (println "FINISHED:" status (pr-str body)(str "@"(tr/now))) (log/error "FAILED" status body))))))) ;; ;; JIRA ;; (def scanned-jira-keys (atom {})) (defn- to-datahub[p payload] (let [jira-key (-> payload :key) jira-id (-> payload :id) updated (-> payload :fields :updated)] (locking (.intern jira-key) (let [old-updated (@scanned-jira-keys jira-key)] (if (neg? (compare old-updated updated)) (do (swap! scanned-jira-keys assoc jira-key updated) (sync-println "\tposting:" jira-key jira-id updated old-updated) (and p (p payload))) (sync-println "\tskipping:" jira-key jira-id updated old-updated)))))) (defn jira-scan![context d s] #_(prn "DEBUG" context d s) (println "STARTING jira-scan:"context(str "@"(tr/now))) (make-sure) (let [{:keys [app-id index kind]} context pf (get s :parallel-factor 1) p (mk-datahub-post-api d) {:keys [body status]} (p (format "intake-sessions?app-id=%s&description=JIRA full scan&command=scan" app-id) nil) session-id (:key body) pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s)) [counter cb] (wrap-with-counter (partial to-datahub #(p (format "intake-sessions/%s/document" session-id) (json/write-str %)))) ret1 (->> (j/find-periods) (pmapr pf (partial j/upload-period context (:cache s) false pja-search-api cb)) flatten frequencies) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil)] (println "SUCCEEDED:" (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) )) (defn jira-patch![context d s jql] #_(prn "DEBUG" context d s jql) (println "STARTING jira-patch:"context(str "@"(tr/now))) (println "WARNINIG: please suspend update due to slight risk of overwriting issues") (let [{:keys [app-id index kind]} context p (mk-datahub-post-api d) {:keys [body status]} (p (format "intake-sessions?app-id=%s&description=JIRA patch&command=patch" app-id) nil);;TODO for parameters #_ (prn "DEBUG" body) session-id (:key body) pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s)) [counter cb] (wrap-with-counter (partial to-datahub #(p (format "intake-sessions/%s/document" session-id) (json/write-str %)))) ret1 (j/upload-by-jql context pja-search-api cb jql) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil)] (println "SUCCEEDED:" (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) )) (defn jira-update![context d s continue] #_(prn "DEBUG" context d s continue) (println "STARTING jira-update:"context(str "@"(tr/now))) (let [{:keys [app-id index kind]} context p (mk-datahub-post-api d) pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s))] (loop [limit continue-default] (when (pos? limit) (let [{:keys [body status]} (p (format "intake-sessions?app-id=%s&description=JIRA update&command=update" app-id) nil)] (condp = status 200 (let [session-id (:key body) {{:keys [from to]} :range} body [counter cb] (wrap-with-counter (partial to-datahub #(p (format "intake-sessions/%s/document" session-id) (json/write-str %)))) ret1 (j/upload-period context (:cache s) false pja-search-api cb (list from to)) ret2 (p (format "intake-sessions/%s/submit?count=%d" session-id @counter) nil)] (println "SUCCEEDED:" (jts-to-str from) (jts-to-str to) status (pr-str body) (pr-str ret1) (pr-str ret2)(str "@"(tr/now))) (when continue (recur (dec limit)))) 202 (println "FINISHED:" status (pr-str body)(str "@"(tr/now))) (log/error "FAILED" status body))))))) (defn jira-scan-to-cache![context s] #_(prn "DEBUG" context s) (println "STARTING jira-scan-to-cache:"context(str "@"(tr/now))) (make-sure) (let [pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s)) pf (get s :parallel-factor 1)] (->> (j/find-periods) (pmapr pf (partial j/upload-period context true true pja-search-api #(sync-println "\tposting:" (:key %) (:id %) (-> % :fields :updated)))) flatten frequencies) )) (defn jira-patch-to-cache![context d s jql] #_(prn "DEBUG" context d s jql) (println "STARTING jira-patch-to-cache:"context(str "@"(tr/now))) (let [pja-search-api (jira-api/mk-pja-search-api (:url s) (:credentials s) (:debug s))] (->> (j/upload-by-jql context pja-search-api (constantly "done") jql) frequencies) )) ;; ;; SNOW ;; (defn- print-and-pass[a] (println (frequencies a)) a) (defn snow-scan![{:keys [index kind]} d s] (let [p (mk-datahub-post-api d) api (:basic-auth s) in-se (p "intake-sessions?app-id=4&description=this is snow test&command=scan" nil);;TODO appid from config cb #(p (format "intake-sessions/%s/document" (:key in-se)) (json/write-str %))] (->> (s/find-periods) (map (partial s/upload-period (s/mk-snow-api api) cb)) (map print-and-pass) flatten frequencies) ) )
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998817443847656, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": "functions that pre-evaluate sub-expressions\n\n;; By Stuart Sierra\n;; June 23, 2009\n\n;; CHANGE LOG\n;;\n;; June 23, 20", "end": 557, "score": 0.9998962879180908, "start": 544, "tag": "NAME", "value": "Stuart Sierra" }, { "context": "copies of a template expression.\"\n :author \"Stuart Sierra\"}\n clojure.template\n (:require [clojure.walk :a", "end": 904, "score": 0.9998871684074402, "start": 891, "tag": "NAME", "value": "Stuart Sierra" } ]
Neptune/bin/Debug/clojure/template.clj
yasir2000/Neptune-
14
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ;;; template.clj - anonymous functions that pre-evaluate sub-expressions ;; By Stuart Sierra ;; June 23, 2009 ;; CHANGE LOG ;; ;; June 23, 2009: complete rewrite, eliminated _1,_2,... argument ;; syntax ;; ;; January 20, 2009: added "template?" and checks for valid template ;; expressions. ;; ;; December 15, 2008: first version (ns ^{:doc "Macros that expand to repeated copies of a template expression." :author "Stuart Sierra"} clojure.template (:require [clojure.walk :as walk])) (defn apply-template "For use in macros. argv is an argument list, as in defn. expr is a quoted expression using the symbols in argv. values is a sequence of values to be used for the arguments. apply-template will recursively replace argument symbols in expr with their corresponding values, returning a modified expr. Example: (apply-template '[x] '(+ x x) '[2]) ;=> (+ 2 2)" [argv expr values] (assert (vector? argv)) (assert (every? symbol? argv)) (walk/prewalk-replace (zipmap argv values) expr)) (defmacro do-template "Repeatedly copies expr (in a do block) for each group of arguments in values. values are automatically partitioned by the number of arguments in argv, an argument vector as in defn. Example: (macroexpand '(do-template [x y] (+ y x) 2 4 3 5)) ;=> (do (+ 4 2) (+ 5 3))" [argv expr & values] (let [c (count argv)] `(do ~@(map (fn [a] (apply-template argv expr a)) (partition c values)))))
71187
; 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. ;;; template.clj - anonymous functions that pre-evaluate sub-expressions ;; By <NAME> ;; June 23, 2009 ;; CHANGE LOG ;; ;; June 23, 2009: complete rewrite, eliminated _1,_2,... argument ;; syntax ;; ;; January 20, 2009: added "template?" and checks for valid template ;; expressions. ;; ;; December 15, 2008: first version (ns ^{:doc "Macros that expand to repeated copies of a template expression." :author "<NAME>"} clojure.template (:require [clojure.walk :as walk])) (defn apply-template "For use in macros. argv is an argument list, as in defn. expr is a quoted expression using the symbols in argv. values is a sequence of values to be used for the arguments. apply-template will recursively replace argument symbols in expr with their corresponding values, returning a modified expr. Example: (apply-template '[x] '(+ x x) '[2]) ;=> (+ 2 2)" [argv expr values] (assert (vector? argv)) (assert (every? symbol? argv)) (walk/prewalk-replace (zipmap argv values) expr)) (defmacro do-template "Repeatedly copies expr (in a do block) for each group of arguments in values. values are automatically partitioned by the number of arguments in argv, an argument vector as in defn. Example: (macroexpand '(do-template [x y] (+ y x) 2 4 3 5)) ;=> (do (+ 4 2) (+ 5 3))" [argv expr & values] (let [c (count argv)] `(do ~@(map (fn [a] (apply-template argv expr a)) (partition c values)))))
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. ;;; template.clj - anonymous functions that pre-evaluate sub-expressions ;; By PI:NAME:<NAME>END_PI ;; June 23, 2009 ;; CHANGE LOG ;; ;; June 23, 2009: complete rewrite, eliminated _1,_2,... argument ;; syntax ;; ;; January 20, 2009: added "template?" and checks for valid template ;; expressions. ;; ;; December 15, 2008: first version (ns ^{:doc "Macros that expand to repeated copies of a template expression." :author "PI:NAME:<NAME>END_PI"} clojure.template (:require [clojure.walk :as walk])) (defn apply-template "For use in macros. argv is an argument list, as in defn. expr is a quoted expression using the symbols in argv. values is a sequence of values to be used for the arguments. apply-template will recursively replace argument symbols in expr with their corresponding values, returning a modified expr. Example: (apply-template '[x] '(+ x x) '[2]) ;=> (+ 2 2)" [argv expr values] (assert (vector? argv)) (assert (every? symbol? argv)) (walk/prewalk-replace (zipmap argv values) expr)) (defmacro do-template "Repeatedly copies expr (in a do block) for each group of arguments in values. values are automatically partitioned by the number of arguments in argv, an argument vector as in defn. Example: (macroexpand '(do-template [x y] (+ y x) 2 4 3 5)) ;=> (do (+ 4 2) (+ 5 3))" [argv expr & values] (let [c (count argv)] `(do ~@(map (fn [a] (apply-template argv expr a)) (partition c values)))))
[ { "context": "TING\" callback-id))\n\n(def auth-pubkey\n (str\n \"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA835H7CQt2oOmlj6GoZp+\"\n \"dFLE6k43Ybi3ku/yuuzatlnet95xVibbyD+DWBz8owRx", "end": 2024, "score": 0.9982130527496338, "start": 1959, "tag": "KEY", "value": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA835H7CQt2oOmlj6GoZp+\"" }, { "context": "QEFAAOCAQ8AMIIBCgKCAQEA835H7CQt2oOmlj6GoZp+\"\n \"dFLE6k43Ybi3ku/yuuzatlnet95xVibbyD+DWBz8owRx5F7dZKbFuJPD7KNZWnxD\"\n \"P4hSO6p7xg6xOjWrU2naMW8SaWs8cbU7rssRKbEmCc3", "end": 2094, "score": 0.9982203245162964, "start": 2030, "tag": "KEY", "value": "dFLE6k43Ybi3ku/yuuzatlnet95xVibbyD+DWBz8owRx5F7dZKbFuJPD7KNZWnxD" }, { "context": "lnet95xVibbyD+DWBz8owRx5F7dZKbFuJPD7KNZWnxD\"\n \"P4hSO6p7xg6xOjWrU2naMW8SaWs8cbU7rssRKbEmCc39888pgNi6/VgZiHXmVeUR\"\n \"eWbxlrppIhIrRiHwf8LHA0LzGn0UAS4K0dMPdRR02vW", "end": 2165, "score": 0.9924585819244385, "start": 2101, "tag": "KEY", "value": "P4hSO6p7xg6xOjWrU2naMW8SaWs8cbU7rssRKbEmCc39888pgNi6/VgZiHXmVeUR" }, { "context": "W8SaWs8cbU7rssRKbEmCc39888pgNi6/VgZiHXmVeUR\"\n \"eWbxlrppIhIrRiHwf8LHA0LzGn0UAS4K0dMPdRR02vWs5hRw8yOAr0hXU2LUb7AO\"\n \"uP73cumiWDqkmJBhKa1PYN7vixkud1Gb1UhJ77N+W32", "end": 2236, "score": 0.9908178448677063, "start": 2172, "tag": "KEY", "value": "eWbxlrppIhIrRiHwf8LHA0LzGn0UAS4K0dMPdRR02vWs5hRw8yOAr0hXU2LUb7AO" }, { "context": "0LzGn0UAS4K0dMPdRR02vWs5hRw8yOAr0hXU2LUb7AO\"\n \"uP73cumiWDqkmJBhKa1PYN7vixkud1Gb1UhJ77N+W32VdOOXbiS4cophQkfdNhjk\"\n \"jVunw8YkO7dsBhVP/8bqLDLw/8NsSAKwlzsoNKbrjVQ", "end": 2307, "score": 0.9868462085723877, "start": 2243, "tag": "KEY", "value": "uP73cumiWDqkmJBhKa1PYN7vixkud1Gb1UhJ77N+W32VdOOXbiS4cophQkfdNhjk" }, { "context": "N7vixkud1Gb1UhJ77N+W32VdOOXbiS4cophQkfdNhjk\"\n \"jVunw8YkO7dsBhVP/8bqLDLw/8NsSAKwlzsoNKbrjVQ/NmHMJ88QkiKwv+E6lidy\"\n \"3wIDAQAB\"))\n\n(def configuration-session-oid", "end": 2378, "score": 0.9799529314041138, "start": 2314, "tag": "KEY", "value": "jVunw8YkO7dsBhVP/8bqLDLw/8NsSAKwlzsoNKbrjVQ/NmHMJ88QkiKwv+E6lidy" }, { "context": "-user (header session-anon authn-info-header \"user USER ANON\")\n session-anon-form (-> session-anon", "end": 3419, "score": 0.48667439818382263, "start": 3415, "tag": "NAME", "value": "USER" }, { "context": " (header session-anon authn-info-header \"user USER ANON\")\n session-anon-form (-> session-anon\n ", "end": 3424, "score": 0.6561378836631775, "start": 3420, "tag": "NAME", "value": "ANON" }, { "context": "OIDC_USER\"\n :email \"user@oidc.example.com\"\n :entitlement [\"alpha-en", "end": 6182, "score": 0.9998931884765625, "start": 6161, "tag": "EMAIL", "value": "user@oidc.example.com" }, { "context": " (header authn-info-header (str \"user USER ANON \" id2))\n (request abs-uri2)\n ", "end": 10163, "score": 0.7139037847518921, "start": 10159, "tag": "NAME", "value": "USER" }, { "context": " (header authn-info-header (str \"user USER ANON \" id2))\n (request abs-uri2)\n ", "end": 10168, "score": 0.8060932159423828, "start": 10164, "tag": "NAME", "value": "ANON" }, { "context": " (header authn-info-header (str \"user USER ANON \" id3))\n (request abs-uri3)\n ", "end": 10484, "score": 0.8399773836135864, "start": 10480, "tag": "NAME", "value": "USER" }, { "context": " (header authn-info-header (str \"user USER ANON \" id3))\n (request abs-uri3)\n ", "end": 10489, "score": 0.824559211730957, "start": 10485, "tag": "NAME", "value": "ANON" }, { "context": " (header authn-info-header (str \"user USER ANON \" id))\n (request base-uri)\n ", "end": 11663, "score": 0.7136679291725159, "start": 11659, "tag": "NAME", "value": "USER" }, { "context": " (header authn-info-header (str \"user USER ANON \" id))\n (request base-uri)\n ", "end": 11668, "score": 0.8059984445571899, "start": 11664, "tag": "NAME", "value": "ANON" }, { "context": " (header authn-info-header (str \"user USER ANON \" id2))\n (request base-uri)\n ", "end": 11887, "score": 0.5397341251373291, "start": 11883, "tag": "NAME", "value": "USER" }, { "context": " (header authn-info-header (str \"user USER ANON \" id2))\n (request base-uri)\n ", "end": 11892, "score": 0.7658106684684753, "start": 11888, "tag": "NAME", "value": "ANON" }, { "context": " (header authn-info-header (str \"user USER ANON \" id3))\n (request base-uri)\n ", "end": 12117, "score": 0.7344149947166443, "start": 12113, "tag": "NAME", "value": "ANON" }, { "context": " (header authn-info-header (str \"user USER ANON \" id2))\n (request abs-uri2\n ", "end": 21595, "score": 0.8630309104919434, "start": 21591, "tag": "NAME", "value": "ANON" }, { "context": " (header authn-info-header (str \"user USER ANON \" id3))\n (request abs-uri3\n ", "end": 21867, "score": 0.5098648071289062, "start": 21863, "tag": "NAME", "value": "USER" }, { "context": " (header authn-info-header (str \"user USER ANON \" id3))\n (request abs-uri3\n ", "end": 21872, "score": 0.8521479368209839, "start": 21868, "tag": "NAME", "value": "ANON" } ]
cimi/test/com/sixsq/slipstream/ssclj/resources/session_oidc_lifecycle_test.clj
slipstream/SlipStreamServer
6
(ns com.sixsq.slipstream.ssclj.resources.session-oidc-lifecycle-test (:require [clojure.data.json :as json] [clojure.test :refer [deftest is use-fixtures]] [com.sixsq.slipstream.auth.oidc :as auth-oidc] [com.sixsq.slipstream.auth.utils.db :as db] [com.sixsq.slipstream.auth.utils.sign :as sign] [com.sixsq.slipstream.ssclj.app.params :as p] [com.sixsq.slipstream.ssclj.middleware.authn-info-header :refer [authn-info-header]] [com.sixsq.slipstream.ssclj.resources.callback.utils :as cbu] [com.sixsq.slipstream.ssclj.resources.common.utils :as u] [com.sixsq.slipstream.ssclj.resources.configuration :as configuration] [com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu] [com.sixsq.slipstream.ssclj.resources.session :as session] [com.sixsq.slipstream.ssclj.resources.session-template :as ct] [com.sixsq.slipstream.ssclj.resources.session-template :as st] [com.sixsq.slipstream.ssclj.resources.session-template-oidc :as oidc] [peridot.core :refer :all] [ring.util.codec :as codec])) (use-fixtures :each ltu/with-test-server-fixture) (def base-uri (str p/service-context (u/de-camelcase session/resource-name))) (def configuration-base-uri (str p/service-context (u/de-camelcase configuration/resource-name))) (def session-template-base-uri (str p/service-context (u/de-camelcase ct/resource-name))) (def instance "test-oidc") (def session-template-oidc {:method oidc/authn-method :instance instance :name "OpenID Connect" :description "External Authentication via OpenID Connect Protocol" :acl st/resource-acl}) (def ^:const callback-pattern #".*/api/callback/.*/execute") ;; callback state reset between tests (defn reset-callback! [callback-id] (cbu/update-callback-state! "WAITING" callback-id)) (def auth-pubkey (str "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA835H7CQt2oOmlj6GoZp+" "dFLE6k43Ybi3ku/yuuzatlnet95xVibbyD+DWBz8owRx5F7dZKbFuJPD7KNZWnxD" "P4hSO6p7xg6xOjWrU2naMW8SaWs8cbU7rssRKbEmCc39888pgNi6/VgZiHXmVeUR" "eWbxlrppIhIrRiHwf8LHA0LzGn0UAS4K0dMPdRR02vWs5hRw8yOAr0hXU2LUb7AO" "uP73cumiWDqkmJBhKa1PYN7vixkud1Gb1UhJ77N+W32VdOOXbiS4cophQkfdNhjk" "jVunw8YkO7dsBhVP/8bqLDLw/8NsSAKwlzsoNKbrjVQ/NmHMJ88QkiKwv+E6lidy" "3wIDAQAB")) (def configuration-session-oidc {:configurationTemplate {:service "session-oidc" :instance instance :clientID "FAKE_CLIENT_ID" :clientSecret "MyOIDCClientSecret" :authorizeURL "https://authorize.oidc.com/authorize" :tokenURL "https://token.oidc.com/token" :publicKey auth-pubkey}}) (deftest lifecycle (let [session-anon (-> (ltu/ring-app) session (content-type "application/json") (header authn-info-header "unknown ANON")) session-admin (header session-anon authn-info-header "admin ADMIN USER ANON") session-user (header session-anon authn-info-header "user USER ANON") session-anon-form (-> session-anon (content-type u/form-urlencoded)) redirect-uri "https://example.com/webui"] ;; get session template so that session resources can be tested (let [ ;; ;; create the session template to use for these tests ;; href (-> session-admin (request session-template-base-uri :request-method :post :body (json/write-str session-template-oidc)) (ltu/body->edn) (ltu/is-status 201) (ltu/location)) template-url (str p/service-context href) resp (-> session-anon (request template-url) (ltu/body->edn) (ltu/is-status 200)) name-attr "name" description-attr "description" properties-attr {:a "one", :b "two"} ;;valid-create {:sessionTemplate (ltu/strip-unwanted-attrs template)} href-create {:name name-attr :description description-attr :properties properties-attr :sessionTemplate {:href href}} href-create-redirect {:sessionTemplate {:href href :redirectURI redirect-uri}} invalid-create (assoc-in href-create [:sessionTemplate :invalid] "BAD")] ;; anonymous query should succeed but have no entries (-> session-anon (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?)) ;; configuration must have OIDC client id and base URL, if not should get 500 (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status 500)) ;; anonymous create must succeed (let [ ;; ;; create the session-oidc configuration to use for these tests ;; cfg-href (-> session-admin (request configuration-base-uri :request-method :post :body (json/write-str configuration-session-oidc)) (ltu/body->edn) (ltu/is-status 201) (ltu/location)) public-key (:auth-public-key environ.core/env) good-claims {:sub "OIDC_USER" :email "user@oidc.example.com" :entitlement ["alpha-entitlement"] :groups ["/organization/group-1"] :realm "my-realm"} good-token (sign/sign-claims good-claims) bad-claims {} bad-token (sign/sign-claims bad-claims)] (is (= cfg-href (str "configuration/session-oidc-" instance))) (let [resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 303)) id (get-in resp [:response :body :resource-id]) uri (-> resp (ltu/location)) abs-uri (str p/service-context id) resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create-redirect)) (ltu/body->edn) (ltu/is-status 303)) id2 (get-in resp [:response :body :resource-id]) uri2 (-> resp (ltu/location)) abs-uri2 (str p/service-context id2) resp (-> session-anon-form (request base-uri :request-method :post :body (codec/form-encode {:href href :redirectURI redirect-uri})) (ltu/body->edn) (ltu/is-status 303)) id3 (get-in resp [:response :body :resource-id]) uri3 (-> resp (ltu/location)) abs-uri3 (str p/service-context id3)] ;; redirect URLs in location header should contain the client ID and resource id (is (re-matches #".*FAKE_CLIENT_ID.*" (or uri ""))) (is (re-matches callback-pattern (or uri ""))) (is (re-matches #".*FAKE_CLIENT_ID.*" (or uri2 ""))) (is (re-matches callback-pattern (or uri2 ""))) (is (re-matches #".*FAKE_CLIENT_ID.*" (or uri3 ""))) (is (re-matches callback-pattern (or uri3 ""))) ;; user should not be able to see session without session role (-> session-user (request abs-uri) (ltu/body->edn) (ltu/is-status 403)) (-> session-user (request abs-uri2) (ltu/body->edn) (ltu/is-status 403)) (-> session-user (request abs-uri3) (ltu/body->edn) (ltu/is-status 403)) ;; anonymous query should succeed but still have no entries (-> session-anon (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?)) ;; user query should succeed but have no entries because of missing session role (-> session-user (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?)) ;; admin query should succeed, but see no sessions without the correct session role (-> session-admin (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 0)) ;; user should be able to see session with session role (-> session-user (header authn-info-header (str "user USER ANON " id)) (request abs-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) (-> session-user (header authn-info-header (str "user USER ANON " id2)) (request abs-uri2) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id2) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) (-> session-user (header authn-info-header (str "user USER ANON " id3)) (request abs-uri3) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id3) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) ;; check contents of session resource (let [{:keys [name description properties] :as body} (-> (ltu/ring-app) session (header authn-info-header (str "user USER " id)) (request abs-uri) (ltu/body->edn) :response :body)] (is (= name name-attr)) (is (= description description-attr)) (is (= properties properties-attr))) ;; user query with session role should succeed but and have one entry (-> session-user (header authn-info-header (str "user USER ANON " id)) (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) (-> session-user (header authn-info-header (str "user USER ANON " id2)) (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) (-> session-user (header authn-info-header (str "user USER ANON " id3)) (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) ;; ;; test validation callback ;; (let [get-redirect-uri (fn [u] (let [r #".*redirect_uri=(.*)$"] (second (re-matches r u)))) get-callback-id (fn [u] (let [r #".*(callback.*)/execute$"] (second (re-matches r u)))) validate-url (get-redirect-uri uri) validate-url2 (get-redirect-uri uri2) validate-url3 (get-redirect-uri uri3) callback-id (get-callback-id validate-url) callback-id2 (get-callback-id validate-url2) callback-id3 (get-callback-id validate-url3)] (-> session-admin (request (str p/service-context callback-id)) (ltu/body->edn) (ltu/is-status 200)) (-> session-admin (request (str p/service-context callback-id2)) (ltu/body->edn) (ltu/is-status 200)) (-> session-admin (request (str p/service-context callback-id3)) (ltu/body->edn) (ltu/is-status 200)) ;; remove the authentication configurations (-> session-admin (request (str p/service-context cfg-href) :request-method :delete) (ltu/body->edn) (ltu/is-status 200)) ;; try hitting the callback with an invalid server configuration (-> session-anon (request validate-url :request-method :get) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status 500)) (-> session-anon (request validate-url2 :request-method :get) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status 303)) ;; always expect redirect when redirectURI is provided (-> session-anon (request validate-url3 :request-method :get) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status 303)) ;; always expect redirect when redirectURI is provided ;; add the configurations back again (-> session-admin (request configuration-base-uri :request-method :post :body (json/write-str configuration-session-oidc)) (ltu/body->edn) (ltu/is-status 201)) ;; try hitting the callback without the OIDC code parameter (reset-callback! callback-id) (-> session-anon (request validate-url :request-method :get) (ltu/body->edn) (ltu/message-matches #".*not contain required code.*") (ltu/is-status 400)) (reset-callback! callback-id2) (-> session-anon (request validate-url2 :request-method :get) (ltu/body->edn) (ltu/message-matches #".*not contain required code.*") (ltu/is-status 303)) ;; always expect redirect when redirectURI is provided (reset-callback! callback-id3) (-> session-anon (request validate-url3 :request-method :get) (ltu/body->edn) (ltu/message-matches #".*not contain required code.*") (ltu/is-status 303)) ;; always expect redirect when redirectURI is provided ;; try now with a fake code (with-redefs [auth-oidc/get-access-token (fn [client-id client-secret token-url oauth-code redirect-url] (case oauth-code "GOOD" good-token "BAD" bad-token nil)) db/find-roles-for-username (fn [username] "USER ANON alpha") db/user-exists? (constantly true)] (reset-callback! callback-id) (-> session-anon (request (str validate-url "?code=NONE") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*unable to retrieve OIDC/MITREid access token.*") (ltu/is-status 400)) (reset-callback! callback-id) (-> session-anon (request (str validate-url "?code=BAD") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*OIDC/MITREid token is missing subject.*") (ltu/is-status 400)) (let [_ (reset-callback! callback-id) ring-info (-> session-anon (request (str validate-url "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/is-status 400))]) ;; inactive account (let [_ (reset-callback! callback-id2) ring-info (-> session-anon (request (str validate-url2 "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/is-status 303)) location (ltu/location ring-info) token (get-in ring-info [:response :cookies "com.sixsq.slipstream.cookie" :value :token]) claims (if token (sign/unsign-claims token) {})] #_(is (clojure.string/starts-with? location redirect-uri)) (is (empty? claims))) (let [_ (reset-callback! callback-id3) ring-info (-> session-anon (request (str validate-url3 "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/is-status 303)) location (ltu/location ring-info) token (get-in ring-info [:response :cookies "com.sixsq.slipstream.cookie" :value :token]) claims (if token (sign/unsign-claims token) {})] #_(is (clojure.string/starts-with? location redirect-uri)) (is (empty? claims))))) (let [ring-info (-> session-user (header authn-info-header (str "user USER ANON " id)) (request abs-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) session (get-in ring-info [:response :body])] (is (nil? (:username session))) (is (= (:created session) (:updated session)))) (let [ring-info (-> session-user (header authn-info-header (str "user USER ANON " id2)) (request abs-uri2) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id2) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) session (get-in ring-info [:response :body])] (is (nil? (:username session))) (is (= (:created session) (:updated session)))) (let [ring-info (-> session-user (header authn-info-header (str "user USER ANON " id3)) (request abs-uri3) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id3) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) session (get-in ring-info [:response :body])] (is (nil? (:username session))) (is (= (:created session) (:updated session)))) ;; user with session role can delete resource (-> session-user (header authn-info-header (str "user USER ANON " id)) (request abs-uri :request-method :delete) (ltu/is-unset-cookie) (ltu/body->edn) (ltu/is-status 200)) (-> session-user (header authn-info-header (str "user USER ANON " id2)) (request abs-uri2 :request-method :delete) (ltu/is-unset-cookie) (ltu/body->edn) (ltu/is-status 200)) (-> session-user (header authn-info-header (str "user USER ANON " id3)) (request abs-uri3 :request-method :delete) (ltu/is-unset-cookie) (ltu/body->edn) (ltu/is-status 200)) ;; create with invalid template fails (-> session-anon (request base-uri :request-method :post :body (json/write-str invalid-create)) (ltu/body->edn) (ltu/is-status 400))))))) (deftest bad-methods (let [resource-uri (str p/service-context (u/new-resource-id session/resource-name))] (ltu/verify-405-status [[base-uri :options] [base-uri :delete] [resource-uri :options] [resource-uri :put] [resource-uri :post]])))
6954
(ns com.sixsq.slipstream.ssclj.resources.session-oidc-lifecycle-test (:require [clojure.data.json :as json] [clojure.test :refer [deftest is use-fixtures]] [com.sixsq.slipstream.auth.oidc :as auth-oidc] [com.sixsq.slipstream.auth.utils.db :as db] [com.sixsq.slipstream.auth.utils.sign :as sign] [com.sixsq.slipstream.ssclj.app.params :as p] [com.sixsq.slipstream.ssclj.middleware.authn-info-header :refer [authn-info-header]] [com.sixsq.slipstream.ssclj.resources.callback.utils :as cbu] [com.sixsq.slipstream.ssclj.resources.common.utils :as u] [com.sixsq.slipstream.ssclj.resources.configuration :as configuration] [com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu] [com.sixsq.slipstream.ssclj.resources.session :as session] [com.sixsq.slipstream.ssclj.resources.session-template :as ct] [com.sixsq.slipstream.ssclj.resources.session-template :as st] [com.sixsq.slipstream.ssclj.resources.session-template-oidc :as oidc] [peridot.core :refer :all] [ring.util.codec :as codec])) (use-fixtures :each ltu/with-test-server-fixture) (def base-uri (str p/service-context (u/de-camelcase session/resource-name))) (def configuration-base-uri (str p/service-context (u/de-camelcase configuration/resource-name))) (def session-template-base-uri (str p/service-context (u/de-camelcase ct/resource-name))) (def instance "test-oidc") (def session-template-oidc {:method oidc/authn-method :instance instance :name "OpenID Connect" :description "External Authentication via OpenID Connect Protocol" :acl st/resource-acl}) (def ^:const callback-pattern #".*/api/callback/.*/execute") ;; callback state reset between tests (defn reset-callback! [callback-id] (cbu/update-callback-state! "WAITING" callback-id)) (def auth-pubkey (str "<KEY> "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "3wIDAQAB")) (def configuration-session-oidc {:configurationTemplate {:service "session-oidc" :instance instance :clientID "FAKE_CLIENT_ID" :clientSecret "MyOIDCClientSecret" :authorizeURL "https://authorize.oidc.com/authorize" :tokenURL "https://token.oidc.com/token" :publicKey auth-pubkey}}) (deftest lifecycle (let [session-anon (-> (ltu/ring-app) session (content-type "application/json") (header authn-info-header "unknown ANON")) session-admin (header session-anon authn-info-header "admin ADMIN USER ANON") session-user (header session-anon authn-info-header "user <NAME> <NAME>") session-anon-form (-> session-anon (content-type u/form-urlencoded)) redirect-uri "https://example.com/webui"] ;; get session template so that session resources can be tested (let [ ;; ;; create the session template to use for these tests ;; href (-> session-admin (request session-template-base-uri :request-method :post :body (json/write-str session-template-oidc)) (ltu/body->edn) (ltu/is-status 201) (ltu/location)) template-url (str p/service-context href) resp (-> session-anon (request template-url) (ltu/body->edn) (ltu/is-status 200)) name-attr "name" description-attr "description" properties-attr {:a "one", :b "two"} ;;valid-create {:sessionTemplate (ltu/strip-unwanted-attrs template)} href-create {:name name-attr :description description-attr :properties properties-attr :sessionTemplate {:href href}} href-create-redirect {:sessionTemplate {:href href :redirectURI redirect-uri}} invalid-create (assoc-in href-create [:sessionTemplate :invalid] "BAD")] ;; anonymous query should succeed but have no entries (-> session-anon (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?)) ;; configuration must have OIDC client id and base URL, if not should get 500 (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status 500)) ;; anonymous create must succeed (let [ ;; ;; create the session-oidc configuration to use for these tests ;; cfg-href (-> session-admin (request configuration-base-uri :request-method :post :body (json/write-str configuration-session-oidc)) (ltu/body->edn) (ltu/is-status 201) (ltu/location)) public-key (:auth-public-key environ.core/env) good-claims {:sub "OIDC_USER" :email "<EMAIL>" :entitlement ["alpha-entitlement"] :groups ["/organization/group-1"] :realm "my-realm"} good-token (sign/sign-claims good-claims) bad-claims {} bad-token (sign/sign-claims bad-claims)] (is (= cfg-href (str "configuration/session-oidc-" instance))) (let [resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 303)) id (get-in resp [:response :body :resource-id]) uri (-> resp (ltu/location)) abs-uri (str p/service-context id) resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create-redirect)) (ltu/body->edn) (ltu/is-status 303)) id2 (get-in resp [:response :body :resource-id]) uri2 (-> resp (ltu/location)) abs-uri2 (str p/service-context id2) resp (-> session-anon-form (request base-uri :request-method :post :body (codec/form-encode {:href href :redirectURI redirect-uri})) (ltu/body->edn) (ltu/is-status 303)) id3 (get-in resp [:response :body :resource-id]) uri3 (-> resp (ltu/location)) abs-uri3 (str p/service-context id3)] ;; redirect URLs in location header should contain the client ID and resource id (is (re-matches #".*FAKE_CLIENT_ID.*" (or uri ""))) (is (re-matches callback-pattern (or uri ""))) (is (re-matches #".*FAKE_CLIENT_ID.*" (or uri2 ""))) (is (re-matches callback-pattern (or uri2 ""))) (is (re-matches #".*FAKE_CLIENT_ID.*" (or uri3 ""))) (is (re-matches callback-pattern (or uri3 ""))) ;; user should not be able to see session without session role (-> session-user (request abs-uri) (ltu/body->edn) (ltu/is-status 403)) (-> session-user (request abs-uri2) (ltu/body->edn) (ltu/is-status 403)) (-> session-user (request abs-uri3) (ltu/body->edn) (ltu/is-status 403)) ;; anonymous query should succeed but still have no entries (-> session-anon (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?)) ;; user query should succeed but have no entries because of missing session role (-> session-user (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?)) ;; admin query should succeed, but see no sessions without the correct session role (-> session-admin (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 0)) ;; user should be able to see session with session role (-> session-user (header authn-info-header (str "user USER ANON " id)) (request abs-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) (-> session-user (header authn-info-header (str "user <NAME> <NAME> " id2)) (request abs-uri2) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id2) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) (-> session-user (header authn-info-header (str "user <NAME> <NAME> " id3)) (request abs-uri3) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id3) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) ;; check contents of session resource (let [{:keys [name description properties] :as body} (-> (ltu/ring-app) session (header authn-info-header (str "user USER " id)) (request abs-uri) (ltu/body->edn) :response :body)] (is (= name name-attr)) (is (= description description-attr)) (is (= properties properties-attr))) ;; user query with session role should succeed but and have one entry (-> session-user (header authn-info-header (str "user <NAME> <NAME> " id)) (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) (-> session-user (header authn-info-header (str "user <NAME> <NAME> " id2)) (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) (-> session-user (header authn-info-header (str "user USER <NAME> " id3)) (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) ;; ;; test validation callback ;; (let [get-redirect-uri (fn [u] (let [r #".*redirect_uri=(.*)$"] (second (re-matches r u)))) get-callback-id (fn [u] (let [r #".*(callback.*)/execute$"] (second (re-matches r u)))) validate-url (get-redirect-uri uri) validate-url2 (get-redirect-uri uri2) validate-url3 (get-redirect-uri uri3) callback-id (get-callback-id validate-url) callback-id2 (get-callback-id validate-url2) callback-id3 (get-callback-id validate-url3)] (-> session-admin (request (str p/service-context callback-id)) (ltu/body->edn) (ltu/is-status 200)) (-> session-admin (request (str p/service-context callback-id2)) (ltu/body->edn) (ltu/is-status 200)) (-> session-admin (request (str p/service-context callback-id3)) (ltu/body->edn) (ltu/is-status 200)) ;; remove the authentication configurations (-> session-admin (request (str p/service-context cfg-href) :request-method :delete) (ltu/body->edn) (ltu/is-status 200)) ;; try hitting the callback with an invalid server configuration (-> session-anon (request validate-url :request-method :get) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status 500)) (-> session-anon (request validate-url2 :request-method :get) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status 303)) ;; always expect redirect when redirectURI is provided (-> session-anon (request validate-url3 :request-method :get) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status 303)) ;; always expect redirect when redirectURI is provided ;; add the configurations back again (-> session-admin (request configuration-base-uri :request-method :post :body (json/write-str configuration-session-oidc)) (ltu/body->edn) (ltu/is-status 201)) ;; try hitting the callback without the OIDC code parameter (reset-callback! callback-id) (-> session-anon (request validate-url :request-method :get) (ltu/body->edn) (ltu/message-matches #".*not contain required code.*") (ltu/is-status 400)) (reset-callback! callback-id2) (-> session-anon (request validate-url2 :request-method :get) (ltu/body->edn) (ltu/message-matches #".*not contain required code.*") (ltu/is-status 303)) ;; always expect redirect when redirectURI is provided (reset-callback! callback-id3) (-> session-anon (request validate-url3 :request-method :get) (ltu/body->edn) (ltu/message-matches #".*not contain required code.*") (ltu/is-status 303)) ;; always expect redirect when redirectURI is provided ;; try now with a fake code (with-redefs [auth-oidc/get-access-token (fn [client-id client-secret token-url oauth-code redirect-url] (case oauth-code "GOOD" good-token "BAD" bad-token nil)) db/find-roles-for-username (fn [username] "USER ANON alpha") db/user-exists? (constantly true)] (reset-callback! callback-id) (-> session-anon (request (str validate-url "?code=NONE") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*unable to retrieve OIDC/MITREid access token.*") (ltu/is-status 400)) (reset-callback! callback-id) (-> session-anon (request (str validate-url "?code=BAD") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*OIDC/MITREid token is missing subject.*") (ltu/is-status 400)) (let [_ (reset-callback! callback-id) ring-info (-> session-anon (request (str validate-url "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/is-status 400))]) ;; inactive account (let [_ (reset-callback! callback-id2) ring-info (-> session-anon (request (str validate-url2 "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/is-status 303)) location (ltu/location ring-info) token (get-in ring-info [:response :cookies "com.sixsq.slipstream.cookie" :value :token]) claims (if token (sign/unsign-claims token) {})] #_(is (clojure.string/starts-with? location redirect-uri)) (is (empty? claims))) (let [_ (reset-callback! callback-id3) ring-info (-> session-anon (request (str validate-url3 "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/is-status 303)) location (ltu/location ring-info) token (get-in ring-info [:response :cookies "com.sixsq.slipstream.cookie" :value :token]) claims (if token (sign/unsign-claims token) {})] #_(is (clojure.string/starts-with? location redirect-uri)) (is (empty? claims))))) (let [ring-info (-> session-user (header authn-info-header (str "user USER ANON " id)) (request abs-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) session (get-in ring-info [:response :body])] (is (nil? (:username session))) (is (= (:created session) (:updated session)))) (let [ring-info (-> session-user (header authn-info-header (str "user USER ANON " id2)) (request abs-uri2) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id2) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) session (get-in ring-info [:response :body])] (is (nil? (:username session))) (is (= (:created session) (:updated session)))) (let [ring-info (-> session-user (header authn-info-header (str "user USER ANON " id3)) (request abs-uri3) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id3) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) session (get-in ring-info [:response :body])] (is (nil? (:username session))) (is (= (:created session) (:updated session)))) ;; user with session role can delete resource (-> session-user (header authn-info-header (str "user USER ANON " id)) (request abs-uri :request-method :delete) (ltu/is-unset-cookie) (ltu/body->edn) (ltu/is-status 200)) (-> session-user (header authn-info-header (str "user USER <NAME> " id2)) (request abs-uri2 :request-method :delete) (ltu/is-unset-cookie) (ltu/body->edn) (ltu/is-status 200)) (-> session-user (header authn-info-header (str "user <NAME> <NAME> " id3)) (request abs-uri3 :request-method :delete) (ltu/is-unset-cookie) (ltu/body->edn) (ltu/is-status 200)) ;; create with invalid template fails (-> session-anon (request base-uri :request-method :post :body (json/write-str invalid-create)) (ltu/body->edn) (ltu/is-status 400))))))) (deftest bad-methods (let [resource-uri (str p/service-context (u/new-resource-id session/resource-name))] (ltu/verify-405-status [[base-uri :options] [base-uri :delete] [resource-uri :options] [resource-uri :put] [resource-uri :post]])))
true
(ns com.sixsq.slipstream.ssclj.resources.session-oidc-lifecycle-test (:require [clojure.data.json :as json] [clojure.test :refer [deftest is use-fixtures]] [com.sixsq.slipstream.auth.oidc :as auth-oidc] [com.sixsq.slipstream.auth.utils.db :as db] [com.sixsq.slipstream.auth.utils.sign :as sign] [com.sixsq.slipstream.ssclj.app.params :as p] [com.sixsq.slipstream.ssclj.middleware.authn-info-header :refer [authn-info-header]] [com.sixsq.slipstream.ssclj.resources.callback.utils :as cbu] [com.sixsq.slipstream.ssclj.resources.common.utils :as u] [com.sixsq.slipstream.ssclj.resources.configuration :as configuration] [com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu] [com.sixsq.slipstream.ssclj.resources.session :as session] [com.sixsq.slipstream.ssclj.resources.session-template :as ct] [com.sixsq.slipstream.ssclj.resources.session-template :as st] [com.sixsq.slipstream.ssclj.resources.session-template-oidc :as oidc] [peridot.core :refer :all] [ring.util.codec :as codec])) (use-fixtures :each ltu/with-test-server-fixture) (def base-uri (str p/service-context (u/de-camelcase session/resource-name))) (def configuration-base-uri (str p/service-context (u/de-camelcase configuration/resource-name))) (def session-template-base-uri (str p/service-context (u/de-camelcase ct/resource-name))) (def instance "test-oidc") (def session-template-oidc {:method oidc/authn-method :instance instance :name "OpenID Connect" :description "External Authentication via OpenID Connect Protocol" :acl st/resource-acl}) (def ^:const callback-pattern #".*/api/callback/.*/execute") ;; callback state reset between tests (defn reset-callback! [callback-id] (cbu/update-callback-state! "WAITING" callback-id)) (def auth-pubkey (str "PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" "3wIDAQAB")) (def configuration-session-oidc {:configurationTemplate {:service "session-oidc" :instance instance :clientID "FAKE_CLIENT_ID" :clientSecret "MyOIDCClientSecret" :authorizeURL "https://authorize.oidc.com/authorize" :tokenURL "https://token.oidc.com/token" :publicKey auth-pubkey}}) (deftest lifecycle (let [session-anon (-> (ltu/ring-app) session (content-type "application/json") (header authn-info-header "unknown ANON")) session-admin (header session-anon authn-info-header "admin ADMIN USER ANON") session-user (header session-anon authn-info-header "user PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI") session-anon-form (-> session-anon (content-type u/form-urlencoded)) redirect-uri "https://example.com/webui"] ;; get session template so that session resources can be tested (let [ ;; ;; create the session template to use for these tests ;; href (-> session-admin (request session-template-base-uri :request-method :post :body (json/write-str session-template-oidc)) (ltu/body->edn) (ltu/is-status 201) (ltu/location)) template-url (str p/service-context href) resp (-> session-anon (request template-url) (ltu/body->edn) (ltu/is-status 200)) name-attr "name" description-attr "description" properties-attr {:a "one", :b "two"} ;;valid-create {:sessionTemplate (ltu/strip-unwanted-attrs template)} href-create {:name name-attr :description description-attr :properties properties-attr :sessionTemplate {:href href}} href-create-redirect {:sessionTemplate {:href href :redirectURI redirect-uri}} invalid-create (assoc-in href-create [:sessionTemplate :invalid] "BAD")] ;; anonymous query should succeed but have no entries (-> session-anon (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?)) ;; configuration must have OIDC client id and base URL, if not should get 500 (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status 500)) ;; anonymous create must succeed (let [ ;; ;; create the session-oidc configuration to use for these tests ;; cfg-href (-> session-admin (request configuration-base-uri :request-method :post :body (json/write-str configuration-session-oidc)) (ltu/body->edn) (ltu/is-status 201) (ltu/location)) public-key (:auth-public-key environ.core/env) good-claims {:sub "OIDC_USER" :email "PI:EMAIL:<EMAIL>END_PI" :entitlement ["alpha-entitlement"] :groups ["/organization/group-1"] :realm "my-realm"} good-token (sign/sign-claims good-claims) bad-claims {} bad-token (sign/sign-claims bad-claims)] (is (= cfg-href (str "configuration/session-oidc-" instance))) (let [resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 303)) id (get-in resp [:response :body :resource-id]) uri (-> resp (ltu/location)) abs-uri (str p/service-context id) resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create-redirect)) (ltu/body->edn) (ltu/is-status 303)) id2 (get-in resp [:response :body :resource-id]) uri2 (-> resp (ltu/location)) abs-uri2 (str p/service-context id2) resp (-> session-anon-form (request base-uri :request-method :post :body (codec/form-encode {:href href :redirectURI redirect-uri})) (ltu/body->edn) (ltu/is-status 303)) id3 (get-in resp [:response :body :resource-id]) uri3 (-> resp (ltu/location)) abs-uri3 (str p/service-context id3)] ;; redirect URLs in location header should contain the client ID and resource id (is (re-matches #".*FAKE_CLIENT_ID.*" (or uri ""))) (is (re-matches callback-pattern (or uri ""))) (is (re-matches #".*FAKE_CLIENT_ID.*" (or uri2 ""))) (is (re-matches callback-pattern (or uri2 ""))) (is (re-matches #".*FAKE_CLIENT_ID.*" (or uri3 ""))) (is (re-matches callback-pattern (or uri3 ""))) ;; user should not be able to see session without session role (-> session-user (request abs-uri) (ltu/body->edn) (ltu/is-status 403)) (-> session-user (request abs-uri2) (ltu/body->edn) (ltu/is-status 403)) (-> session-user (request abs-uri3) (ltu/body->edn) (ltu/is-status 403)) ;; anonymous query should succeed but still have no entries (-> session-anon (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?)) ;; user query should succeed but have no entries because of missing session role (-> session-user (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?)) ;; admin query should succeed, but see no sessions without the correct session role (-> session-admin (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 0)) ;; user should be able to see session with session role (-> session-user (header authn-info-header (str "user USER ANON " id)) (request abs-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) (-> session-user (header authn-info-header (str "user PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI " id2)) (request abs-uri2) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id2) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) (-> session-user (header authn-info-header (str "user PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI " id3)) (request abs-uri3) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id3) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) ;; check contents of session resource (let [{:keys [name description properties] :as body} (-> (ltu/ring-app) session (header authn-info-header (str "user USER " id)) (request abs-uri) (ltu/body->edn) :response :body)] (is (= name name-attr)) (is (= description description-attr)) (is (= properties properties-attr))) ;; user query with session role should succeed but and have one entry (-> session-user (header authn-info-header (str "user PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI " id)) (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) (-> session-user (header authn-info-header (str "user PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI " id2)) (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) (-> session-user (header authn-info-header (str "user USER PI:NAME:<NAME>END_PI " id3)) (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count 1)) ;; ;; test validation callback ;; (let [get-redirect-uri (fn [u] (let [r #".*redirect_uri=(.*)$"] (second (re-matches r u)))) get-callback-id (fn [u] (let [r #".*(callback.*)/execute$"] (second (re-matches r u)))) validate-url (get-redirect-uri uri) validate-url2 (get-redirect-uri uri2) validate-url3 (get-redirect-uri uri3) callback-id (get-callback-id validate-url) callback-id2 (get-callback-id validate-url2) callback-id3 (get-callback-id validate-url3)] (-> session-admin (request (str p/service-context callback-id)) (ltu/body->edn) (ltu/is-status 200)) (-> session-admin (request (str p/service-context callback-id2)) (ltu/body->edn) (ltu/is-status 200)) (-> session-admin (request (str p/service-context callback-id3)) (ltu/body->edn) (ltu/is-status 200)) ;; remove the authentication configurations (-> session-admin (request (str p/service-context cfg-href) :request-method :delete) (ltu/body->edn) (ltu/is-status 200)) ;; try hitting the callback with an invalid server configuration (-> session-anon (request validate-url :request-method :get) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status 500)) (-> session-anon (request validate-url2 :request-method :get) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status 303)) ;; always expect redirect when redirectURI is provided (-> session-anon (request validate-url3 :request-method :get) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status 303)) ;; always expect redirect when redirectURI is provided ;; add the configurations back again (-> session-admin (request configuration-base-uri :request-method :post :body (json/write-str configuration-session-oidc)) (ltu/body->edn) (ltu/is-status 201)) ;; try hitting the callback without the OIDC code parameter (reset-callback! callback-id) (-> session-anon (request validate-url :request-method :get) (ltu/body->edn) (ltu/message-matches #".*not contain required code.*") (ltu/is-status 400)) (reset-callback! callback-id2) (-> session-anon (request validate-url2 :request-method :get) (ltu/body->edn) (ltu/message-matches #".*not contain required code.*") (ltu/is-status 303)) ;; always expect redirect when redirectURI is provided (reset-callback! callback-id3) (-> session-anon (request validate-url3 :request-method :get) (ltu/body->edn) (ltu/message-matches #".*not contain required code.*") (ltu/is-status 303)) ;; always expect redirect when redirectURI is provided ;; try now with a fake code (with-redefs [auth-oidc/get-access-token (fn [client-id client-secret token-url oauth-code redirect-url] (case oauth-code "GOOD" good-token "BAD" bad-token nil)) db/find-roles-for-username (fn [username] "USER ANON alpha") db/user-exists? (constantly true)] (reset-callback! callback-id) (-> session-anon (request (str validate-url "?code=NONE") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*unable to retrieve OIDC/MITREid access token.*") (ltu/is-status 400)) (reset-callback! callback-id) (-> session-anon (request (str validate-url "?code=BAD") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*OIDC/MITREid token is missing subject.*") (ltu/is-status 400)) (let [_ (reset-callback! callback-id) ring-info (-> session-anon (request (str validate-url "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/is-status 400))]) ;; inactive account (let [_ (reset-callback! callback-id2) ring-info (-> session-anon (request (str validate-url2 "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/is-status 303)) location (ltu/location ring-info) token (get-in ring-info [:response :cookies "com.sixsq.slipstream.cookie" :value :token]) claims (if token (sign/unsign-claims token) {})] #_(is (clojure.string/starts-with? location redirect-uri)) (is (empty? claims))) (let [_ (reset-callback! callback-id3) ring-info (-> session-anon (request (str validate-url3 "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/is-status 303)) location (ltu/location ring-info) token (get-in ring-info [:response :cookies "com.sixsq.slipstream.cookie" :value :token]) claims (if token (sign/unsign-claims token) {})] #_(is (clojure.string/starts-with? location redirect-uri)) (is (empty? claims))))) (let [ring-info (-> session-user (header authn-info-header (str "user USER ANON " id)) (request abs-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) session (get-in ring-info [:response :body])] (is (nil? (:username session))) (is (= (:created session) (:updated session)))) (let [ring-info (-> session-user (header authn-info-header (str "user USER ANON " id2)) (request abs-uri2) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id2) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) session (get-in ring-info [:response :body])] (is (nil? (:username session))) (is (= (:created session) (:updated session)))) (let [ring-info (-> session-user (header authn-info-header (str "user USER ANON " id3)) (request abs-uri3) (ltu/body->edn) (ltu/is-status 200) (ltu/is-id id3) (ltu/is-operation-present "delete") (ltu/is-operation-absent "edit")) session (get-in ring-info [:response :body])] (is (nil? (:username session))) (is (= (:created session) (:updated session)))) ;; user with session role can delete resource (-> session-user (header authn-info-header (str "user USER ANON " id)) (request abs-uri :request-method :delete) (ltu/is-unset-cookie) (ltu/body->edn) (ltu/is-status 200)) (-> session-user (header authn-info-header (str "user USER PI:NAME:<NAME>END_PI " id2)) (request abs-uri2 :request-method :delete) (ltu/is-unset-cookie) (ltu/body->edn) (ltu/is-status 200)) (-> session-user (header authn-info-header (str "user PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI " id3)) (request abs-uri3 :request-method :delete) (ltu/is-unset-cookie) (ltu/body->edn) (ltu/is-status 200)) ;; create with invalid template fails (-> session-anon (request base-uri :request-method :post :body (json/write-str invalid-create)) (ltu/body->edn) (ltu/is-status 400))))))) (deftest bad-methods (let [resource-uri (str p/service-context (u/new-resource-id session/resource-name))] (ltu/verify-405-status [[base-uri :options] [base-uri :delete] [resource-uri :options] [resource-uri :put] [resource-uri :post]])))
[ { "context": "e to provide\n(def users (atom {\"root\" {:username \"root\"\n :password (creds/hash-bcryp", "end": 182, "score": 0.9723027348518372, "start": 178, "tag": "USERNAME", "value": "root" }, { "context": " :password (creds/hash-bcrypt \"admin_password\")\n :roles #{::admin}}\n ", "end": 249, "score": 0.9984682202339172, "start": 235, "tag": "PASSWORD", "value": "admin_password" }, { "context": " :roles #{::admin}}\n \"jane\" {:username \"jane\"\n :password", "end": 310, "score": 0.9883818626403809, "start": 306, "tag": "USERNAME", "value": "jane" }, { "context": "roles #{::admin}}\n \"jane\" {:username \"jane\"\n :password (creds/hash-bcryp", "end": 328, "score": 0.9992111921310425, "start": 324, "tag": "USERNAME", "value": "jane" }, { "context": " :password (creds/hash-bcrypt \"user_password\")\n :roles #{::user}}}))\n\n", "end": 394, "score": 0.9992820620536804, "start": 381, "tag": "PASSWORD", "value": "user_password" } ]
src/ofdb/login.clj
kremers/clojurewebtemplate
2
(ns ofdb.login (:require [cemerick.friend.credentials :as creds])) ; User map according to friend. Use your favourite datasource to provide (def users (atom {"root" {:username "root" :password (creds/hash-bcrypt "admin_password") :roles #{::admin}} "jane" {:username "jane" :password (creds/hash-bcrypt "user_password") :roles #{::user}}}))
105953
(ns ofdb.login (:require [cemerick.friend.credentials :as creds])) ; User map according to friend. Use your favourite datasource to provide (def users (atom {"root" {:username "root" :password (creds/hash-bcrypt "<PASSWORD>") :roles #{::admin}} "jane" {:username "jane" :password (creds/hash-bcrypt "<PASSWORD>") :roles #{::user}}}))
true
(ns ofdb.login (:require [cemerick.friend.credentials :as creds])) ; User map according to friend. Use your favourite datasource to provide (def users (atom {"root" {:username "root" :password (creds/hash-bcrypt "PI:PASSWORD:<PASSWORD>END_PI") :roles #{::admin}} "jane" {:username "jane" :password (creds/hash-bcrypt "PI:PASSWORD:<PASSWORD>END_PI") :roles #{::user}}}))
[ { "context": "h2\"\n :user \"sa\"\n :password \"sa\"\n :subname \"mem:ruuvi_server\"}\n :serve", "end": 172, "score": 0.9995235204696655, "start": 170, "tag": "PASSWORD", "value": "sa" } ]
test/server-test-config.clj
RuuviTracker/ruuvitracker_server
1
{ ;; Configuration for unit tests :environment :test :database {:classname "org.h2.Driver" :subprotocol "h2" :user "sa" :password "sa" :subname "mem:ruuvi_server"} :server { :type :standalone :port 8080 :max-threads 10 } :tracker-api { :require-authentication true } :client-api { :max-search-results 50 } }
4641
{ ;; Configuration for unit tests :environment :test :database {:classname "org.h2.Driver" :subprotocol "h2" :user "sa" :password "<PASSWORD>" :subname "mem:ruuvi_server"} :server { :type :standalone :port 8080 :max-threads 10 } :tracker-api { :require-authentication true } :client-api { :max-search-results 50 } }
true
{ ;; Configuration for unit tests :environment :test :database {:classname "org.h2.Driver" :subprotocol "h2" :user "sa" :password "PI:PASSWORD:<PASSWORD>END_PI" :subname "mem:ruuvi_server"} :server { :type :standalone :port 8080 :max-threads 10 } :tracker-api { :require-authentication true } :client-api { :max-search-results 50 } }
[ { "context": "s [data]\n [:form {:id \"login\"}\n [c/text-input \"Username\" :username \"Enter your username\" data false]\n [", "end": 623, "score": 0.6557304263114929, "start": 615, "tag": "USERNAME", "value": "Username" }, { "context": " your username\" data false]\n [c/password-input \"Password\" :password \"Enter your password\" data false]])\n\n(", "end": 699, "score": 0.6197949051856995, "start": 691, "tag": "PASSWORD", "value": "Password" }, { "context": "false]\n [c/password-input \"Password\" :password \"Enter your password\" data false]])\n\n(defn login-form [e! close-fn]\n ", "end": 731, "score": 0.9965569376945496, "start": 712, "tag": "PASSWORD", "value": "Enter your password" } ]
src/cljs/my_money/views/login.cljs
Juholei/my-money
1
(ns my-money.views.login (:require [my-money.components.common :as c] [my-money.components.button :refer [button]] [my-money.app.controller.authentication :as ac] [reagent.core :as r])) (defn login! [e! data event-handler] (.preventDefault event-handler) (e! (ac/->Login data))) (defn- buttons [e! data close-fn] [:div [button {:type :primary :form "login" :on-click (r/partial login! e! @data)} "Login"] [button {:type :danger :on-click close-fn} "Cancel"]]) (defn- fields [data] [:form {:id "login"} [c/text-input "Username" :username "Enter your username" data false] [c/password-input "Password" :password "Enter your password" data false]]) (defn login-form [e! close-fn] (r/with-let [data (r/atom {})] [c/modal "Login" [fields data] [buttons e! data close-fn] close-fn]))
94050
(ns my-money.views.login (:require [my-money.components.common :as c] [my-money.components.button :refer [button]] [my-money.app.controller.authentication :as ac] [reagent.core :as r])) (defn login! [e! data event-handler] (.preventDefault event-handler) (e! (ac/->Login data))) (defn- buttons [e! data close-fn] [:div [button {:type :primary :form "login" :on-click (r/partial login! e! @data)} "Login"] [button {:type :danger :on-click close-fn} "Cancel"]]) (defn- fields [data] [:form {:id "login"} [c/text-input "Username" :username "Enter your username" data false] [c/password-input "<PASSWORD>" :password "<PASSWORD>" data false]]) (defn login-form [e! close-fn] (r/with-let [data (r/atom {})] [c/modal "Login" [fields data] [buttons e! data close-fn] close-fn]))
true
(ns my-money.views.login (:require [my-money.components.common :as c] [my-money.components.button :refer [button]] [my-money.app.controller.authentication :as ac] [reagent.core :as r])) (defn login! [e! data event-handler] (.preventDefault event-handler) (e! (ac/->Login data))) (defn- buttons [e! data close-fn] [:div [button {:type :primary :form "login" :on-click (r/partial login! e! @data)} "Login"] [button {:type :danger :on-click close-fn} "Cancel"]]) (defn- fields [data] [:form {:id "login"} [c/text-input "Username" :username "Enter your username" data false] [c/password-input "PI:PASSWORD:<PASSWORD>END_PI" :password "PI:PASSWORD:<PASSWORD>END_PI" data false]]) (defn login-form [e! close-fn] (r/with-let [data (r/atom {})] [c/modal "Login" [fields data] [buttons e! data close-fn] close-fn]))
[ { "context": "le/config config }\n exp-serialized {:name \"Name\"\n :config {:page 1\n ", "end": 775, "score": 0.9190553426742554, "start": 771, "tag": "NAME", "value": "Name" } ]
test/ohmycards/web/services/cards_grid_profile_manager/impl/helpers_test.cljs
vitorqb/oh-my-cards-web
1
(ns ohmycards.web.services.cards-grid-profile-manager.impl.helpers-test (:require [cljs.test :refer-macros [are async deftest is testing use-fixtures]] [ohmycards.web.kws.cards-grid.config.core :as kws.config] [ohmycards.web.kws.cards-grid.profile.core :as kws.profile] [ohmycards.web.services.cards-grid-profile-manager.impl.helpers :as sut])) (deftest test-serialize-profile (let [config {kws.config/page 1 kws.config/page-size 2 kws.config/include-tags ["A"] kws.config/exclude-tags ["B"] kws.config/tags-filter-query "((tags CONTAINS 'foo'))"} profile {kws.profile/name "Name" kws.profile/config config } exp-serialized {:name "Name" :config {:page 1 :pageSize 2 :includeTags ["A"] :excludeTags ["B"] :query "((tags CONTAINS 'foo'))"}}] (is (= exp-serialized (sut/serialize-profile profile)))))
121333
(ns ohmycards.web.services.cards-grid-profile-manager.impl.helpers-test (:require [cljs.test :refer-macros [are async deftest is testing use-fixtures]] [ohmycards.web.kws.cards-grid.config.core :as kws.config] [ohmycards.web.kws.cards-grid.profile.core :as kws.profile] [ohmycards.web.services.cards-grid-profile-manager.impl.helpers :as sut])) (deftest test-serialize-profile (let [config {kws.config/page 1 kws.config/page-size 2 kws.config/include-tags ["A"] kws.config/exclude-tags ["B"] kws.config/tags-filter-query "((tags CONTAINS 'foo'))"} profile {kws.profile/name "Name" kws.profile/config config } exp-serialized {:name "<NAME>" :config {:page 1 :pageSize 2 :includeTags ["A"] :excludeTags ["B"] :query "((tags CONTAINS 'foo'))"}}] (is (= exp-serialized (sut/serialize-profile profile)))))
true
(ns ohmycards.web.services.cards-grid-profile-manager.impl.helpers-test (:require [cljs.test :refer-macros [are async deftest is testing use-fixtures]] [ohmycards.web.kws.cards-grid.config.core :as kws.config] [ohmycards.web.kws.cards-grid.profile.core :as kws.profile] [ohmycards.web.services.cards-grid-profile-manager.impl.helpers :as sut])) (deftest test-serialize-profile (let [config {kws.config/page 1 kws.config/page-size 2 kws.config/include-tags ["A"] kws.config/exclude-tags ["B"] kws.config/tags-filter-query "((tags CONTAINS 'foo'))"} profile {kws.profile/name "Name" kws.profile/config config } exp-serialized {:name "PI:NAME:<NAME>END_PI" :config {:page 1 :pageSize 2 :includeTags ["A"] :excludeTags ["B"] :query "((tags CONTAINS 'foo'))"}}] (is (= exp-serialized (sut/serialize-profile profile)))))
[ { "context": ";; Copyright (c) 2014-2016 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache Li", "end": 40, "score": 0.9998842477798462, "start": 27, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright (c) 2014-2016 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache License, Version", "end": 54, "score": 0.9999300241470337, "start": 42, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
src/buddy/util/deflate.clj
shilder/buddy-core
121
;; Copyright (c) 2014-2016 Andrey Antukh <niwi@niwi.nz> ;; ;; 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. ;; Links to rfcs: ;; - https://tools.ietf.org/html/rfc1951 (ns buddy.util.deflate "Interface to DEFLATE compression algorithm." (:import java.io.ByteArrayInputStream java.io.ByteArrayOutputStream java.util.zip.Deflater java.util.zip.DeflaterOutputStream java.util.zip.InflaterInputStream java.util.zip.Inflater java.util.zip.ZipException)) (defn compress "Given a plain byte array, compress it and return an other byte array." ([^bytes input] (compress input nil)) ([^bytes input {:keys [nowrap] :or {nowrap true}}] (let [os (ByteArrayOutputStream.) defl (Deflater. Deflater/DEFLATED nowrap)] (with-open [dos (DeflaterOutputStream. os defl)] (.write dos input)) (.toByteArray os)))) (defn uncompress "Given a compressed data as byte-array, uncompress it and return as an other byte array." ([^bytes input] (uncompress input nil)) ([^bytes input {:keys [nowrap buffer-size] :or {nowrap true buffer-size 2048} :as opts}] (let [buf (byte-array (int buffer-size)) os (ByteArrayOutputStream.) inf (Inflater. ^Boolean nowrap)] (try (with-open [is (ByteArrayInputStream. input) iis (InflaterInputStream. is inf)] (loop [] (let [readed (.read iis buf)] (when (pos? readed) (.write os buf 0 readed) (recur))))) (.toByteArray os) (catch ZipException e (if nowrap (uncompress input (assoc opts :nowrap false)) (throw e)))))))
75273
;; Copyright (c) 2014-2016 <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. ;; Links to rfcs: ;; - https://tools.ietf.org/html/rfc1951 (ns buddy.util.deflate "Interface to DEFLATE compression algorithm." (:import java.io.ByteArrayInputStream java.io.ByteArrayOutputStream java.util.zip.Deflater java.util.zip.DeflaterOutputStream java.util.zip.InflaterInputStream java.util.zip.Inflater java.util.zip.ZipException)) (defn compress "Given a plain byte array, compress it and return an other byte array." ([^bytes input] (compress input nil)) ([^bytes input {:keys [nowrap] :or {nowrap true}}] (let [os (ByteArrayOutputStream.) defl (Deflater. Deflater/DEFLATED nowrap)] (with-open [dos (DeflaterOutputStream. os defl)] (.write dos input)) (.toByteArray os)))) (defn uncompress "Given a compressed data as byte-array, uncompress it and return as an other byte array." ([^bytes input] (uncompress input nil)) ([^bytes input {:keys [nowrap buffer-size] :or {nowrap true buffer-size 2048} :as opts}] (let [buf (byte-array (int buffer-size)) os (ByteArrayOutputStream.) inf (Inflater. ^Boolean nowrap)] (try (with-open [is (ByteArrayInputStream. input) iis (InflaterInputStream. is inf)] (loop [] (let [readed (.read iis buf)] (when (pos? readed) (.write os buf 0 readed) (recur))))) (.toByteArray os) (catch ZipException e (if nowrap (uncompress input (assoc opts :nowrap false)) (throw e)))))))
true
;; Copyright (c) 2014-2016 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. ;; Links to rfcs: ;; - https://tools.ietf.org/html/rfc1951 (ns buddy.util.deflate "Interface to DEFLATE compression algorithm." (:import java.io.ByteArrayInputStream java.io.ByteArrayOutputStream java.util.zip.Deflater java.util.zip.DeflaterOutputStream java.util.zip.InflaterInputStream java.util.zip.Inflater java.util.zip.ZipException)) (defn compress "Given a plain byte array, compress it and return an other byte array." ([^bytes input] (compress input nil)) ([^bytes input {:keys [nowrap] :or {nowrap true}}] (let [os (ByteArrayOutputStream.) defl (Deflater. Deflater/DEFLATED nowrap)] (with-open [dos (DeflaterOutputStream. os defl)] (.write dos input)) (.toByteArray os)))) (defn uncompress "Given a compressed data as byte-array, uncompress it and return as an other byte array." ([^bytes input] (uncompress input nil)) ([^bytes input {:keys [nowrap buffer-size] :or {nowrap true buffer-size 2048} :as opts}] (let [buf (byte-array (int buffer-size)) os (ByteArrayOutputStream.) inf (Inflater. ^Boolean nowrap)] (try (with-open [is (ByteArrayInputStream. input) iis (InflaterInputStream. is inf)] (loop [] (let [readed (.read iis buf)] (when (pos? readed) (.write os buf 0 readed) (recur))))) (.toByteArray os) (catch ZipException e (if nowrap (uncompress input (assoc opts :nowrap false)) (throw e)))))))
[ { "context": "x \"foo\"} {:x (email)})\n nil (validate {:x \"foo@bar.com\"} {:x (email)})\n nil (validate {:x nil} {:", "end": 2422, "score": 0.9992759823799133, "start": 2411, "tag": "EMAIL", "value": "foo@bar.com" } ]
test/cljs/shevek/lib/validation_test.cljs
eeng/shevek
6
(ns shevek.lib.validation-test (:require-macros [cljs.test :refer [deftest testing is are]]) (:require [shevek.lib.validation :refer [validate pred required regex email confirmation]])) (deftest validation-tests (testing "general rules" (testing "single validator per field" (are [ee vr] (= ee (:errors vr)) {:x ["pos"]} (validate {:x 0} {:x (pred pos? {:msg "pos"})}) nil (validate {:x 1} {:x (pred pos? {:msg "pos"})}))) (testing "multiple validators per field" (are [ee vr] (= ee (:errors vr)) {:x ["> 0" "> 1"]} (validate {:x 0} {:x [(pred #(> % 0) {:msg "> 0"}) (pred #(> % 1) {:msg "> 1"})]}))) (testing "validators are not optional by default" (are [ee vr] (= ee (:errors vr)) {:x ["pos"]} (validate {:x nil} {:x (pred pos? {:msg "pos"})}) nil (validate {:x nil} {:x (pred pos? {:msg "pos" :optional? true})}))) (testing "option :when (fn of state) can be used to validate only on some cases" (are [ee vr] (= ee (:errors vr)) {:x ["oops"]} (validate {:x nil :id 1} {:x (required {:when :id :msg "oops"})}) nil (validate {:x nil :id nil} {:x (required {:when :id})}))) (testing "value interpolation in the message" (are [ee vr] (= ee (:errors vr)) {:x ["val 'foo' is invalid"]} (validate {:x "foo"} {:x (pred #(= % "bar") {:msg "val '%s' is invalid"})})))) (testing "validators" (testing "required validator" (are [ee vr] (= ee (:errors vr)) {:x ["can't be blank"]} (validate {} {:x (required)}) {:x ["can't be blank"]} (validate {:x " "} {:x (required)}) nil (validate {:x "..."} {:x (required)}))) (testing "regex validator" (are [ee vr] (= ee (:errors vr)) nil (validate {:x "foo"} {:x (regex #"foo")}) {:x ["doesn't match pattern"]} (validate {:x "bar"} {:x (regex #"foo")}) {:x ["oops"]} (validate {:x "bar"} {:x (regex #"foo" {:msg "oops"})}) {:x ["doesn't match pattern"]} (validate {:x nil} {:x (regex #"foo")}) {:x ["doesn't match pattern"]} (validate {:x ""} {:x (regex #"foo")}) nil (validate {} {:x (regex #"foo" {:optional? true})}))) (testing "email validator" (are [ee vr] (= ee (:errors vr)) {:x ["is not a valid email address"]} (validate {:x "foo"} {:x (email)}) nil (validate {:x "foo@bar.com"} {:x (email)}) nil (validate {:x nil} {:x (email {:optional? true})}) nil (validate {:x ""} {:x (email {:optional? true})}))) (testing "confirmation validator" (are [ee vr] (= ee (:errors vr)) {:y ["doesn't match the previous value"]} (validate {:x "foo" :y "foO"} {:y (confirmation :x)}) nil (validate {:x "foo" :y "foo"} {:y (confirmation :x)}) {:y ["not optional by default"]} (validate {:x "foo" :y nil} {:y (confirmation :x {:msg "not optional by default"})})))))
78909
(ns shevek.lib.validation-test (:require-macros [cljs.test :refer [deftest testing is are]]) (:require [shevek.lib.validation :refer [validate pred required regex email confirmation]])) (deftest validation-tests (testing "general rules" (testing "single validator per field" (are [ee vr] (= ee (:errors vr)) {:x ["pos"]} (validate {:x 0} {:x (pred pos? {:msg "pos"})}) nil (validate {:x 1} {:x (pred pos? {:msg "pos"})}))) (testing "multiple validators per field" (are [ee vr] (= ee (:errors vr)) {:x ["> 0" "> 1"]} (validate {:x 0} {:x [(pred #(> % 0) {:msg "> 0"}) (pred #(> % 1) {:msg "> 1"})]}))) (testing "validators are not optional by default" (are [ee vr] (= ee (:errors vr)) {:x ["pos"]} (validate {:x nil} {:x (pred pos? {:msg "pos"})}) nil (validate {:x nil} {:x (pred pos? {:msg "pos" :optional? true})}))) (testing "option :when (fn of state) can be used to validate only on some cases" (are [ee vr] (= ee (:errors vr)) {:x ["oops"]} (validate {:x nil :id 1} {:x (required {:when :id :msg "oops"})}) nil (validate {:x nil :id nil} {:x (required {:when :id})}))) (testing "value interpolation in the message" (are [ee vr] (= ee (:errors vr)) {:x ["val 'foo' is invalid"]} (validate {:x "foo"} {:x (pred #(= % "bar") {:msg "val '%s' is invalid"})})))) (testing "validators" (testing "required validator" (are [ee vr] (= ee (:errors vr)) {:x ["can't be blank"]} (validate {} {:x (required)}) {:x ["can't be blank"]} (validate {:x " "} {:x (required)}) nil (validate {:x "..."} {:x (required)}))) (testing "regex validator" (are [ee vr] (= ee (:errors vr)) nil (validate {:x "foo"} {:x (regex #"foo")}) {:x ["doesn't match pattern"]} (validate {:x "bar"} {:x (regex #"foo")}) {:x ["oops"]} (validate {:x "bar"} {:x (regex #"foo" {:msg "oops"})}) {:x ["doesn't match pattern"]} (validate {:x nil} {:x (regex #"foo")}) {:x ["doesn't match pattern"]} (validate {:x ""} {:x (regex #"foo")}) nil (validate {} {:x (regex #"foo" {:optional? true})}))) (testing "email validator" (are [ee vr] (= ee (:errors vr)) {:x ["is not a valid email address"]} (validate {:x "foo"} {:x (email)}) nil (validate {:x "<EMAIL>"} {:x (email)}) nil (validate {:x nil} {:x (email {:optional? true})}) nil (validate {:x ""} {:x (email {:optional? true})}))) (testing "confirmation validator" (are [ee vr] (= ee (:errors vr)) {:y ["doesn't match the previous value"]} (validate {:x "foo" :y "foO"} {:y (confirmation :x)}) nil (validate {:x "foo" :y "foo"} {:y (confirmation :x)}) {:y ["not optional by default"]} (validate {:x "foo" :y nil} {:y (confirmation :x {:msg "not optional by default"})})))))
true
(ns shevek.lib.validation-test (:require-macros [cljs.test :refer [deftest testing is are]]) (:require [shevek.lib.validation :refer [validate pred required regex email confirmation]])) (deftest validation-tests (testing "general rules" (testing "single validator per field" (are [ee vr] (= ee (:errors vr)) {:x ["pos"]} (validate {:x 0} {:x (pred pos? {:msg "pos"})}) nil (validate {:x 1} {:x (pred pos? {:msg "pos"})}))) (testing "multiple validators per field" (are [ee vr] (= ee (:errors vr)) {:x ["> 0" "> 1"]} (validate {:x 0} {:x [(pred #(> % 0) {:msg "> 0"}) (pred #(> % 1) {:msg "> 1"})]}))) (testing "validators are not optional by default" (are [ee vr] (= ee (:errors vr)) {:x ["pos"]} (validate {:x nil} {:x (pred pos? {:msg "pos"})}) nil (validate {:x nil} {:x (pred pos? {:msg "pos" :optional? true})}))) (testing "option :when (fn of state) can be used to validate only on some cases" (are [ee vr] (= ee (:errors vr)) {:x ["oops"]} (validate {:x nil :id 1} {:x (required {:when :id :msg "oops"})}) nil (validate {:x nil :id nil} {:x (required {:when :id})}))) (testing "value interpolation in the message" (are [ee vr] (= ee (:errors vr)) {:x ["val 'foo' is invalid"]} (validate {:x "foo"} {:x (pred #(= % "bar") {:msg "val '%s' is invalid"})})))) (testing "validators" (testing "required validator" (are [ee vr] (= ee (:errors vr)) {:x ["can't be blank"]} (validate {} {:x (required)}) {:x ["can't be blank"]} (validate {:x " "} {:x (required)}) nil (validate {:x "..."} {:x (required)}))) (testing "regex validator" (are [ee vr] (= ee (:errors vr)) nil (validate {:x "foo"} {:x (regex #"foo")}) {:x ["doesn't match pattern"]} (validate {:x "bar"} {:x (regex #"foo")}) {:x ["oops"]} (validate {:x "bar"} {:x (regex #"foo" {:msg "oops"})}) {:x ["doesn't match pattern"]} (validate {:x nil} {:x (regex #"foo")}) {:x ["doesn't match pattern"]} (validate {:x ""} {:x (regex #"foo")}) nil (validate {} {:x (regex #"foo" {:optional? true})}))) (testing "email validator" (are [ee vr] (= ee (:errors vr)) {:x ["is not a valid email address"]} (validate {:x "foo"} {:x (email)}) nil (validate {:x "PI:EMAIL:<EMAIL>END_PI"} {:x (email)}) nil (validate {:x nil} {:x (email {:optional? true})}) nil (validate {:x ""} {:x (email {:optional? true})}))) (testing "confirmation validator" (are [ee vr] (= ee (:errors vr)) {:y ["doesn't match the previous value"]} (validate {:x "foo" :y "foO"} {:y (confirmation :x)}) nil (validate {:x "foo" :y "foo"} {:y (confirmation :x)}) {:y ["not optional by default"]} (validate {:x "foo" :y nil} {:y (confirmation :x {:msg "not optional by default"})})))))
[ { "context": " (runtime/connect extension-id #js {:name \"Dirac Marionettist\"})))))\n\n", "end": 4016, "score": 0.9998244643211365, "start": 3998, "tag": "NAME", "value": "Dirac Marionettist" } ]
test/marion/src/background/marion/background/helpers.cljs
pvinis/dirac
0
(ns marion.background.helpers (:require-macros [cljs.core.async.macros :refer [go go-loop]] [marion.background.logging :refer [log info warn error]]) (:require [cljs.core.async :refer [<! chan timeout]] [oops.core :refer [oget ocall oapply]] [chromex.ext.tabs :as tabs] [chromex.ext.runtime :as runtime] [chromex.ext.management :as management] [chromex.ext.windows :as windows] [dirac.settings :refer-macros [get-dirac-scenario-window-top get-dirac-scenario-window-left get-dirac-scenario-window-width get-dirac-scenario-window-height get-dirac-runner-window-top get-dirac-runner-window-left get-dirac-runner-window-width get-dirac-runner-window-height]] [dirac.sugar :as sugar])) (defn find-extension [pred] (go (let [[extension-infos] (<! (management/get-all)) match? (fn [extension-info] (if (pred extension-info) extension-info))] (some match? extension-infos)))) (defn find-extension-by-name [name] (find-extension (fn [extension-info] (= (oget extension-info "name") name)))) (defn create-tab-with-url! [url] (go (if-let [[tab] (<! (tabs/create #js {:url url}))] (sugar/get-tab-id tab)))) (defn create-scenario-with-url! [url] {:pre [(string? url)]} (go ; during development we may want to override standard "cascading" of new windows and position the window explicitely (let [window-params (sugar/set-window-params-dimensions! #js {:url url} (get-dirac-scenario-window-left) (get-dirac-scenario-window-top) (get-dirac-scenario-window-width) (get-dirac-scenario-window-height)) [_window tab-id] (<! (sugar/create-window-and-wait-for-first-tab-completed! window-params))] tab-id))) (defn focus-window-with-tab-id! [tab-id] (go (if-let [window-id (<! (sugar/fetch-tab-window-id tab-id))] (<! (windows/update window-id #js {"focused" true "drawAttention" true}))))) (defn activate-tab! [tab-id] (tabs/update tab-id #js {"active" true})) (defn find-runner-tab! [] (go (let [[tabs] (<! (tabs/query #js {:title "TASK RUNNER"}))] (if-let [tab (first tabs)] tab (warn "no TASK RUNNER tab?"))))) (defn find-runner-tab-id! [] (go (if-let [tab (<! (find-runner-tab!))] (sugar/get-tab-id tab)))) (defn reposition-runner-window! [] (go (if-let [tab-id (<! (find-runner-tab-id!))] (if-let [window-id (<! (sugar/fetch-tab-window-id tab-id))] (<! (windows/update window-id (sugar/set-window-params-dimensions! #js {} (get-dirac-runner-window-left) (get-dirac-runner-window-top) (get-dirac-runner-window-width) (get-dirac-runner-window-height)))))))) (defn close-tab-with-id! [tab-id] (tabs/remove tab-id)) (defn close-all-scenario-tabs! [] (go (let [[tabs] (<! (tabs/query #js {:url "http://*/scenarios/*"}))] (doseq [tab tabs] (<! (close-tab-with-id! (sugar/get-tab-id tab))))))) (defn connect-to-dirac-extension! [] (go (if-let [extension-info (<! (find-extension-by-name "Dirac DevTools"))] (let [extension-id (oget extension-info "id")] (log (str "found dirac extension id: '" extension-id "'")) (runtime/connect extension-id #js {:name "Dirac Marionettist"})))))
102439
(ns marion.background.helpers (:require-macros [cljs.core.async.macros :refer [go go-loop]] [marion.background.logging :refer [log info warn error]]) (:require [cljs.core.async :refer [<! chan timeout]] [oops.core :refer [oget ocall oapply]] [chromex.ext.tabs :as tabs] [chromex.ext.runtime :as runtime] [chromex.ext.management :as management] [chromex.ext.windows :as windows] [dirac.settings :refer-macros [get-dirac-scenario-window-top get-dirac-scenario-window-left get-dirac-scenario-window-width get-dirac-scenario-window-height get-dirac-runner-window-top get-dirac-runner-window-left get-dirac-runner-window-width get-dirac-runner-window-height]] [dirac.sugar :as sugar])) (defn find-extension [pred] (go (let [[extension-infos] (<! (management/get-all)) match? (fn [extension-info] (if (pred extension-info) extension-info))] (some match? extension-infos)))) (defn find-extension-by-name [name] (find-extension (fn [extension-info] (= (oget extension-info "name") name)))) (defn create-tab-with-url! [url] (go (if-let [[tab] (<! (tabs/create #js {:url url}))] (sugar/get-tab-id tab)))) (defn create-scenario-with-url! [url] {:pre [(string? url)]} (go ; during development we may want to override standard "cascading" of new windows and position the window explicitely (let [window-params (sugar/set-window-params-dimensions! #js {:url url} (get-dirac-scenario-window-left) (get-dirac-scenario-window-top) (get-dirac-scenario-window-width) (get-dirac-scenario-window-height)) [_window tab-id] (<! (sugar/create-window-and-wait-for-first-tab-completed! window-params))] tab-id))) (defn focus-window-with-tab-id! [tab-id] (go (if-let [window-id (<! (sugar/fetch-tab-window-id tab-id))] (<! (windows/update window-id #js {"focused" true "drawAttention" true}))))) (defn activate-tab! [tab-id] (tabs/update tab-id #js {"active" true})) (defn find-runner-tab! [] (go (let [[tabs] (<! (tabs/query #js {:title "TASK RUNNER"}))] (if-let [tab (first tabs)] tab (warn "no TASK RUNNER tab?"))))) (defn find-runner-tab-id! [] (go (if-let [tab (<! (find-runner-tab!))] (sugar/get-tab-id tab)))) (defn reposition-runner-window! [] (go (if-let [tab-id (<! (find-runner-tab-id!))] (if-let [window-id (<! (sugar/fetch-tab-window-id tab-id))] (<! (windows/update window-id (sugar/set-window-params-dimensions! #js {} (get-dirac-runner-window-left) (get-dirac-runner-window-top) (get-dirac-runner-window-width) (get-dirac-runner-window-height)))))))) (defn close-tab-with-id! [tab-id] (tabs/remove tab-id)) (defn close-all-scenario-tabs! [] (go (let [[tabs] (<! (tabs/query #js {:url "http://*/scenarios/*"}))] (doseq [tab tabs] (<! (close-tab-with-id! (sugar/get-tab-id tab))))))) (defn connect-to-dirac-extension! [] (go (if-let [extension-info (<! (find-extension-by-name "Dirac DevTools"))] (let [extension-id (oget extension-info "id")] (log (str "found dirac extension id: '" extension-id "'")) (runtime/connect extension-id #js {:name "<NAME>"})))))
true
(ns marion.background.helpers (:require-macros [cljs.core.async.macros :refer [go go-loop]] [marion.background.logging :refer [log info warn error]]) (:require [cljs.core.async :refer [<! chan timeout]] [oops.core :refer [oget ocall oapply]] [chromex.ext.tabs :as tabs] [chromex.ext.runtime :as runtime] [chromex.ext.management :as management] [chromex.ext.windows :as windows] [dirac.settings :refer-macros [get-dirac-scenario-window-top get-dirac-scenario-window-left get-dirac-scenario-window-width get-dirac-scenario-window-height get-dirac-runner-window-top get-dirac-runner-window-left get-dirac-runner-window-width get-dirac-runner-window-height]] [dirac.sugar :as sugar])) (defn find-extension [pred] (go (let [[extension-infos] (<! (management/get-all)) match? (fn [extension-info] (if (pred extension-info) extension-info))] (some match? extension-infos)))) (defn find-extension-by-name [name] (find-extension (fn [extension-info] (= (oget extension-info "name") name)))) (defn create-tab-with-url! [url] (go (if-let [[tab] (<! (tabs/create #js {:url url}))] (sugar/get-tab-id tab)))) (defn create-scenario-with-url! [url] {:pre [(string? url)]} (go ; during development we may want to override standard "cascading" of new windows and position the window explicitely (let [window-params (sugar/set-window-params-dimensions! #js {:url url} (get-dirac-scenario-window-left) (get-dirac-scenario-window-top) (get-dirac-scenario-window-width) (get-dirac-scenario-window-height)) [_window tab-id] (<! (sugar/create-window-and-wait-for-first-tab-completed! window-params))] tab-id))) (defn focus-window-with-tab-id! [tab-id] (go (if-let [window-id (<! (sugar/fetch-tab-window-id tab-id))] (<! (windows/update window-id #js {"focused" true "drawAttention" true}))))) (defn activate-tab! [tab-id] (tabs/update tab-id #js {"active" true})) (defn find-runner-tab! [] (go (let [[tabs] (<! (tabs/query #js {:title "TASK RUNNER"}))] (if-let [tab (first tabs)] tab (warn "no TASK RUNNER tab?"))))) (defn find-runner-tab-id! [] (go (if-let [tab (<! (find-runner-tab!))] (sugar/get-tab-id tab)))) (defn reposition-runner-window! [] (go (if-let [tab-id (<! (find-runner-tab-id!))] (if-let [window-id (<! (sugar/fetch-tab-window-id tab-id))] (<! (windows/update window-id (sugar/set-window-params-dimensions! #js {} (get-dirac-runner-window-left) (get-dirac-runner-window-top) (get-dirac-runner-window-width) (get-dirac-runner-window-height)))))))) (defn close-tab-with-id! [tab-id] (tabs/remove tab-id)) (defn close-all-scenario-tabs! [] (go (let [[tabs] (<! (tabs/query #js {:url "http://*/scenarios/*"}))] (doseq [tab tabs] (<! (close-tab-with-id! (sugar/get-tab-id tab))))))) (defn connect-to-dirac-extension! [] (go (if-let [extension-info (<! (find-extension-by-name "Dirac DevTools"))] (let [extension-id (oget extension-info "id")] (log (str "found dirac extension id: '" extension-id "'")) (runtime/connect extension-id #js {:name "PI:NAME:<NAME>END_PI"})))))
[ { "context": "TRUST_STORE_PASSWORD\")\n \"changeit\"))\n (System/setProperty \"javax.net.ssl.keyStore\"", "end": 3439, "score": 0.9876017570495605, "start": 3431, "tag": "PASSWORD", "value": "changeit" }, { "context": " \"KEY_STORE_PASSWORD\")\n \"somepass\"))\n (component/start-system\n (make-signal-serv", "end": 3896, "score": 0.9979182481765747, "start": 3888, "tag": "PASSWORD", "value": "somepass" }, { "context": "TRUST_STORE_PASSWORD\")\n \"changeit\"))\n (System/setProperty \"javax.net.ssl.keyStore\"", "end": 4559, "score": 0.9981817007064819, "start": 4551, "tag": "PASSWORD", "value": "changeit" }, { "context": " \"KEY_STORE_PASSWORD\")\n \"somepass\"))\n (make-signal-server {:http-config {:env ", "end": 5016, "score": 0.9991071224212646, "start": 5008, "tag": "PASSWORD", "value": "somepass" } ]
src/signal/server.clj
boundlessgeo/signal
6
;; Copyright 2016-2017 Boundless, http://boundlessgeo.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 signal.server (:gen-class) ; for -main method in uberjar (:require [io.pedestal.http :as server] [signal.components.http.core :as http] [com.stuartsierra.component :as component] [signal.components.processor :as processor] [signal.components.input-manager :as input] [signal.components.notification :as notification] [clojure.tools.logging :as log])) (defrecord SignalServer [http-service] component/Lifecycle (start [component] (log/info "Starting SignalServer Component") (let [server (server/create-server (:service-def http-service))] (server/start server) (assoc component :http-server server))) (stop [component] (log/info "Stopping SignalServer Component") (update-in component [:http-server] server/stop))) (defn new-signal-server [] (map->SignalServer {})) (defn make-signal-server "Returns a new instance of the system" [config-options] (log/debug "Making server config with these options" config-options) (let [{:keys [http-config]} config-options] (component/system-map :notify (component/using (notification/make-signal-notification-component) []) :processor (component/using (processor/make-processor-component) [:notify]) :input (component/using (input/make-input-manager-component) [:processor]) :http-service (component/using (http/make-http-service-component http-config) [:processor :notify :input]) :server (component/using (new-signal-server) [:http-service])))) (defn -main "The entry-point for 'lein run'" [& _] (log/info "Configuring Signal server...") (if (get-in signal.config/config [:app :auto-migrate]) (signal.components.database/migrate)) (let [email (get-in signal.config/config [:app :admin-email]) pass (get-in signal.config/config [:app :admin-pass])] (if (and (some? email) (some? pass)) (do (signal.components.database/create-user {:name "admin" :email email :password pass})))) ;; create global uncaught exception handler so threads don't silently die (Thread/setDefaultUncaughtExceptionHandler (reify Thread$UncaughtExceptionHandler (uncaughtException [_ thread ex] (log/error ex "Uncaught exception on thread" (.getName thread))))) (System/setProperty "javax.net.ssl.trustStore" (or (System/getenv "TRUST_STORE") "tls/test-cacerts.jks")) (System/setProperty "javax.net.ssl.trustStoreType" (or (System/getenv "TRUST_STORE_TYPE") "JKS")) (System/setProperty "javax.net.ssl.trustStorePassword" (or (System/getenv "TRUST_STORE_PASSWORD") "changeit")) (System/setProperty "javax.net.ssl.keyStore" (or (System/getenv "KEY_STORE") "tls/test-keystore.p12")) (System/setProperty "javax.net.ssl.keyStoreType" (or (System/getenv "KEY_STORE_TYPE") "pkcs12")) (System/setProperty "javax.net.ssl.keyStorePassword" (or (System/getenv "KEY_STORE_PASSWORD") "somepass")) (component/start-system (make-signal-server {:http-config {}}))) (def system-val nil) (defn init-dev [] (log/info "Initializing dev system for repl") (signal.components.database/migrate) (System/setProperty "javax.net.ssl.trustStore" (or (System/getenv "TRUST_STORE") "tls/test-cacerts.jks")) (System/setProperty "javax.net.ssl.trustStoreType" (or (System/getenv "TRUST_STORE_TYPE") "JKS")) (System/setProperty "javax.net.ssl.trustStorePassword" (or (System/getenv "TRUST_STORE_PASSWORD") "changeit")) (System/setProperty "javax.net.ssl.keyStore" (or (System/getenv "KEY_STORE") "tls/test-keystore.p12")) (System/setProperty "javax.net.ssl.keyStoreType" (or (System/getenv "KEY_STORE_TYPE") "pkcs12")) (System/setProperty "javax.net.ssl.keyStorePassword" (or (System/getenv "KEY_STORE_PASSWORD") "somepass")) (make-signal-server {:http-config {:env :dev ::server/join? false ::server/allowed-origins ["localhost:8084"]}})) ;::server/allowed-origins {:creds true ; :allowed-origins (constantly true)}})) (defn init [] (alter-var-root #'system-val (constantly (init-dev)))) (defn start [] (alter-var-root #'system-val component/start-system)) (defn stop [] (alter-var-root #'system-val (fn [s] (when s (component/stop-system s))))) (defn go [] (init) (start)) (defn reset [] (stop) (go))
8054
;; Copyright 2016-2017 Boundless, http://boundlessgeo.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 signal.server (:gen-class) ; for -main method in uberjar (:require [io.pedestal.http :as server] [signal.components.http.core :as http] [com.stuartsierra.component :as component] [signal.components.processor :as processor] [signal.components.input-manager :as input] [signal.components.notification :as notification] [clojure.tools.logging :as log])) (defrecord SignalServer [http-service] component/Lifecycle (start [component] (log/info "Starting SignalServer Component") (let [server (server/create-server (:service-def http-service))] (server/start server) (assoc component :http-server server))) (stop [component] (log/info "Stopping SignalServer Component") (update-in component [:http-server] server/stop))) (defn new-signal-server [] (map->SignalServer {})) (defn make-signal-server "Returns a new instance of the system" [config-options] (log/debug "Making server config with these options" config-options) (let [{:keys [http-config]} config-options] (component/system-map :notify (component/using (notification/make-signal-notification-component) []) :processor (component/using (processor/make-processor-component) [:notify]) :input (component/using (input/make-input-manager-component) [:processor]) :http-service (component/using (http/make-http-service-component http-config) [:processor :notify :input]) :server (component/using (new-signal-server) [:http-service])))) (defn -main "The entry-point for 'lein run'" [& _] (log/info "Configuring Signal server...") (if (get-in signal.config/config [:app :auto-migrate]) (signal.components.database/migrate)) (let [email (get-in signal.config/config [:app :admin-email]) pass (get-in signal.config/config [:app :admin-pass])] (if (and (some? email) (some? pass)) (do (signal.components.database/create-user {:name "admin" :email email :password pass})))) ;; create global uncaught exception handler so threads don't silently die (Thread/setDefaultUncaughtExceptionHandler (reify Thread$UncaughtExceptionHandler (uncaughtException [_ thread ex] (log/error ex "Uncaught exception on thread" (.getName thread))))) (System/setProperty "javax.net.ssl.trustStore" (or (System/getenv "TRUST_STORE") "tls/test-cacerts.jks")) (System/setProperty "javax.net.ssl.trustStoreType" (or (System/getenv "TRUST_STORE_TYPE") "JKS")) (System/setProperty "javax.net.ssl.trustStorePassword" (or (System/getenv "TRUST_STORE_PASSWORD") "<PASSWORD>")) (System/setProperty "javax.net.ssl.keyStore" (or (System/getenv "KEY_STORE") "tls/test-keystore.p12")) (System/setProperty "javax.net.ssl.keyStoreType" (or (System/getenv "KEY_STORE_TYPE") "pkcs12")) (System/setProperty "javax.net.ssl.keyStorePassword" (or (System/getenv "KEY_STORE_PASSWORD") "<PASSWORD>")) (component/start-system (make-signal-server {:http-config {}}))) (def system-val nil) (defn init-dev [] (log/info "Initializing dev system for repl") (signal.components.database/migrate) (System/setProperty "javax.net.ssl.trustStore" (or (System/getenv "TRUST_STORE") "tls/test-cacerts.jks")) (System/setProperty "javax.net.ssl.trustStoreType" (or (System/getenv "TRUST_STORE_TYPE") "JKS")) (System/setProperty "javax.net.ssl.trustStorePassword" (or (System/getenv "TRUST_STORE_PASSWORD") "<PASSWORD>")) (System/setProperty "javax.net.ssl.keyStore" (or (System/getenv "KEY_STORE") "tls/test-keystore.p12")) (System/setProperty "javax.net.ssl.keyStoreType" (or (System/getenv "KEY_STORE_TYPE") "pkcs12")) (System/setProperty "javax.net.ssl.keyStorePassword" (or (System/getenv "KEY_STORE_PASSWORD") "<PASSWORD>")) (make-signal-server {:http-config {:env :dev ::server/join? false ::server/allowed-origins ["localhost:8084"]}})) ;::server/allowed-origins {:creds true ; :allowed-origins (constantly true)}})) (defn init [] (alter-var-root #'system-val (constantly (init-dev)))) (defn start [] (alter-var-root #'system-val component/start-system)) (defn stop [] (alter-var-root #'system-val (fn [s] (when s (component/stop-system s))))) (defn go [] (init) (start)) (defn reset [] (stop) (go))
true
;; Copyright 2016-2017 Boundless, http://boundlessgeo.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 signal.server (:gen-class) ; for -main method in uberjar (:require [io.pedestal.http :as server] [signal.components.http.core :as http] [com.stuartsierra.component :as component] [signal.components.processor :as processor] [signal.components.input-manager :as input] [signal.components.notification :as notification] [clojure.tools.logging :as log])) (defrecord SignalServer [http-service] component/Lifecycle (start [component] (log/info "Starting SignalServer Component") (let [server (server/create-server (:service-def http-service))] (server/start server) (assoc component :http-server server))) (stop [component] (log/info "Stopping SignalServer Component") (update-in component [:http-server] server/stop))) (defn new-signal-server [] (map->SignalServer {})) (defn make-signal-server "Returns a new instance of the system" [config-options] (log/debug "Making server config with these options" config-options) (let [{:keys [http-config]} config-options] (component/system-map :notify (component/using (notification/make-signal-notification-component) []) :processor (component/using (processor/make-processor-component) [:notify]) :input (component/using (input/make-input-manager-component) [:processor]) :http-service (component/using (http/make-http-service-component http-config) [:processor :notify :input]) :server (component/using (new-signal-server) [:http-service])))) (defn -main "The entry-point for 'lein run'" [& _] (log/info "Configuring Signal server...") (if (get-in signal.config/config [:app :auto-migrate]) (signal.components.database/migrate)) (let [email (get-in signal.config/config [:app :admin-email]) pass (get-in signal.config/config [:app :admin-pass])] (if (and (some? email) (some? pass)) (do (signal.components.database/create-user {:name "admin" :email email :password pass})))) ;; create global uncaught exception handler so threads don't silently die (Thread/setDefaultUncaughtExceptionHandler (reify Thread$UncaughtExceptionHandler (uncaughtException [_ thread ex] (log/error ex "Uncaught exception on thread" (.getName thread))))) (System/setProperty "javax.net.ssl.trustStore" (or (System/getenv "TRUST_STORE") "tls/test-cacerts.jks")) (System/setProperty "javax.net.ssl.trustStoreType" (or (System/getenv "TRUST_STORE_TYPE") "JKS")) (System/setProperty "javax.net.ssl.trustStorePassword" (or (System/getenv "TRUST_STORE_PASSWORD") "PI:PASSWORD:<PASSWORD>END_PI")) (System/setProperty "javax.net.ssl.keyStore" (or (System/getenv "KEY_STORE") "tls/test-keystore.p12")) (System/setProperty "javax.net.ssl.keyStoreType" (or (System/getenv "KEY_STORE_TYPE") "pkcs12")) (System/setProperty "javax.net.ssl.keyStorePassword" (or (System/getenv "KEY_STORE_PASSWORD") "PI:PASSWORD:<PASSWORD>END_PI")) (component/start-system (make-signal-server {:http-config {}}))) (def system-val nil) (defn init-dev [] (log/info "Initializing dev system for repl") (signal.components.database/migrate) (System/setProperty "javax.net.ssl.trustStore" (or (System/getenv "TRUST_STORE") "tls/test-cacerts.jks")) (System/setProperty "javax.net.ssl.trustStoreType" (or (System/getenv "TRUST_STORE_TYPE") "JKS")) (System/setProperty "javax.net.ssl.trustStorePassword" (or (System/getenv "TRUST_STORE_PASSWORD") "PI:PASSWORD:<PASSWORD>END_PI")) (System/setProperty "javax.net.ssl.keyStore" (or (System/getenv "KEY_STORE") "tls/test-keystore.p12")) (System/setProperty "javax.net.ssl.keyStoreType" (or (System/getenv "KEY_STORE_TYPE") "pkcs12")) (System/setProperty "javax.net.ssl.keyStorePassword" (or (System/getenv "KEY_STORE_PASSWORD") "PI:PASSWORD:<PASSWORD>END_PI")) (make-signal-server {:http-config {:env :dev ::server/join? false ::server/allowed-origins ["localhost:8084"]}})) ;::server/allowed-origins {:creds true ; :allowed-origins (constantly true)}})) (defn init [] (alter-var-root #'system-val (constantly (init-dev)))) (defn start [] (alter-var-root #'system-val component/start-system)) (defn stop [] (alter-var-root #'system-val (fn [s] (when s (component/stop-system s))))) (defn go [] (init) (start)) (defn reset [] (stop) (go))
[ { "context": "oat\n \n {:doc \"Apfloat experiments.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-05-24\"\n :version \"2017-05-24\"}", "end": 276, "score": 0.9413903951644897, "start": 240, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/scripts/clojure/palisades/lakes/elements/scripts/numbers/apfloat.clj
palisades-lakes/les-elemens
0
(set! *warn-on-reflection* true) ;;(set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.scripts.numbers.apfloat {:doc "Apfloat experiments." :author "palisades dot lakes at gmail dot com" :since "2017-05-24" :version "2017-05-24"} #_(:require [palisades.lakes.elements.api :as mc]) (:import [org.apfloat Apfloat ApfloatMath])) ;;---------------------------------------------------------------- (println "round trip (Apfloat. d)") (loop [d (double (Math/nextUp (/ 1.0 Math/E)))] (let [a (Apfloat. d) da (.doubleValue a)] (if (== d da) (recur (Math/nextUp d)) (do (println d) (println a) (println da) (println))))) ;;---------------------------------------------------------------- (println "round trip 'binary128' (Apfloat. d)") (loop [i 0 d (double (Math/nextUp (/ 1.0 Math/E)))] (let [a (Apfloat. d (long 113) (int 2)) da (.doubleValue a)] (if (and (< i 1000000) (== d da)) (recur (Math/nextUp d)) (do (println i) (println d) (println a) (println da) (println))))) ;;----------------------------------------------------------------
62257
(set! *warn-on-reflection* true) ;;(set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.scripts.numbers.apfloat {:doc "Apfloat experiments." :author "<EMAIL>" :since "2017-05-24" :version "2017-05-24"} #_(:require [palisades.lakes.elements.api :as mc]) (:import [org.apfloat Apfloat ApfloatMath])) ;;---------------------------------------------------------------- (println "round trip (Apfloat. d)") (loop [d (double (Math/nextUp (/ 1.0 Math/E)))] (let [a (Apfloat. d) da (.doubleValue a)] (if (== d da) (recur (Math/nextUp d)) (do (println d) (println a) (println da) (println))))) ;;---------------------------------------------------------------- (println "round trip 'binary128' (Apfloat. d)") (loop [i 0 d (double (Math/nextUp (/ 1.0 Math/E)))] (let [a (Apfloat. d (long 113) (int 2)) da (.doubleValue a)] (if (and (< i 1000000) (== d da)) (recur (Math/nextUp d)) (do (println i) (println d) (println a) (println da) (println))))) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) ;;(set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.scripts.numbers.apfloat {:doc "Apfloat experiments." :author "PI:EMAIL:<EMAIL>END_PI" :since "2017-05-24" :version "2017-05-24"} #_(:require [palisades.lakes.elements.api :as mc]) (:import [org.apfloat Apfloat ApfloatMath])) ;;---------------------------------------------------------------- (println "round trip (Apfloat. d)") (loop [d (double (Math/nextUp (/ 1.0 Math/E)))] (let [a (Apfloat. d) da (.doubleValue a)] (if (== d da) (recur (Math/nextUp d)) (do (println d) (println a) (println da) (println))))) ;;---------------------------------------------------------------- (println "round trip 'binary128' (Apfloat. d)") (loop [i 0 d (double (Math/nextUp (/ 1.0 Math/E)))] (let [a (Apfloat. d (long 113) (int 2)) da (.doubleValue a)] (if (and (< i 1000000) (== d da)) (recur (Math/nextUp d)) (do (println i) (println d) (println a) (println da) (println))))) ;;----------------------------------------------------------------
[ { "context": "s users-schema]])\n data {:users {1 {:name \"Bo\" :nickname \"B\"}}}\n encoded (l/serialize st", "end": 6962, "score": 0.5588579773902893, "start": 6960, "tag": "NAME", "value": "Bo" } ]
test/deercreeklabs/unit/lt_test.cljc
GriffinScribe-LLC/lancaster
42
(ns deercreeklabs.unit.lt-test (:require [clojure.test :refer [deftest is use-fixtures]] [deercreeklabs.baracus :as ba] [deercreeklabs.lancaster :as l] [deercreeklabs.lancaster.utils :as u] [deercreeklabs.unit.lancaster-test :as lt] [schema.core :as s :include-macros true]) #?(:clj (:import (clojure.lang ExceptionInfo)))) ;; Use this instead of fixtures, which are hard to make work w/ async testing. (s/set-fn-validation! true) (l/def-int-map-schema sku-to-qty-schema l/int-schema) (def sku-to-qty-v2-schema (l/int-map-schema ::sku-to-qty l/long-schema)) (l/def-int-map-schema im-schema l/string-schema) (l/def-fixed-map-schema fm-schema 16 l/string-schema) (l/def-union-schema im-or-fm-schema im-schema fm-schema) (l/def-union-schema lt-union-schema l/keyword-schema l/string-schema l/int-schema) (deftest test-int-map-schema (is (= {:name :deercreeklabs.unit.lt-test/sku-to-qty :type :record :fields [{:name :deercreeklabs-unit-lt-test-sku-to-qty/ks :type {:type :array :items :int} :default []} {:name :deercreeklabs-unit-lt-test-sku-to-qty/vs :type {:type :array :items :int} :default []}]} (u/strip-lt-attrs (l/edn sku-to-qty-schema)))) #?(:clj (is (lt/fp-matches? sku-to-qty-schema))) (is (= (str "{\"name\":\"deercreeklabs.unit.lt_test.SkuToQty\",\"type\":" "\"record\",\"fields\":[{\"name\":" "\"deercreeklabsUnitLtTestSkuToQtyKs\",\"type\":{\"type\":\"array\"," "\"items\":\"int\"}},{\"name\":\"deercreeklabsUnitLtTestSkuToQtyVs\"," "\"type\":{\"type\":\"array\",\"items\":\"int\"}}]}") (l/pcf sku-to-qty-schema))) (is (= (str "{\"name\":\"deercreeklabs.unit.lt_test.SkuToQty\",\"fields\":" "[{\"name\":\"deercreeklabsUnitLtTestSkuToQtyKs\",\"type\":{\"type\":" "\"array\",\"items\":\"int\"},\"default\":[]},{\"name\":" "\"deercreeklabsUnitLtTestSkuToQtyVs\",\"type\":{\"type\":\"array\"," "\"items\":\"int\"},\"default\":[]}],\"type\":\"record\"," "\"logicalType\":\"int-map\"}") (l/json sku-to-qty-schema))) (is (= "-7668463894600081969" (u/long->str (l/fingerprint64 sku-to-qty-schema))))) (deftest test-embedded-int-map-pcf (let [fms (l/int-map-schema ::my-map l/int-schema) rs (l/record-schema :r [[:fm fms]])] (is (= (str "{\"name\":\"R\",\"type\":\"record\",\"fields\":[{\"name\":\"fm\"," "\"type\":[\"null\",{\"name\":\"deercreeklabs.unit.lt_test.MyMap\"" ",\"type\":\"record\",\"fields\":[{\"name\":" "\"deercreeklabsUnitLtTestMyMapKs\",\"type\":{\"type\":\"array\"," "\"items\":\"int\"}},{\"name\":\"deercreeklabsUnitLtTestMyMapVs\"," "\"type\":{\"type\":\"array\",\"items\":\"int\"}}]}]}]}") (l/pcf rs))))) (deftest test-int-map-schema-serdes (let [data {123 10 456 100 789 2} encoded (l/serialize sku-to-qty-schema data) decoded (l/deserialize-same sku-to-qty-schema encoded)] (is (ba/equivalent-byte-arrays? (ba/byte-array [6 -10 1 -112 7 -86 12 0 6 20 -56 1 4 0]) encoded)) (is (= data decoded)))) (deftest test-int-map-serdes-empty-map (let [data {} encoded (l/serialize sku-to-qty-schema data) decoded (l/deserialize-same sku-to-qty-schema encoded)] (is (= data decoded)))) (deftest test-maybe-int-map (let [int-map-schema (l/int-map-schema ::im l/int-schema) maybe-schema (l/maybe int-map-schema) data1 {1 1} data2 nil] (is (lt/round-trip? maybe-schema data1)) (is (lt/round-trip? maybe-schema data2)))) (deftest test-bad-fixed-map-size (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Second argument to fixed-map-schema must be a positive integer" (l/fixed-map-schema ::x -1 l/string-schema)))) (deftest test-int-map-evolution (let [data {123 10 456 100 789 2} encoded (l/serialize sku-to-qty-schema data) decoded (l/deserialize sku-to-qty-v2-schema sku-to-qty-schema encoded)] (is (= data decoded)))) (deftest test-schema-at-path-int-map (let [path [1] ret (-> (l/schema-at-path sku-to-qty-schema path) (u/edn-schema) (u/edn-schema->name-kw))] (is (= :int ret)))) (deftest test-schema-at-path-int-map-bad-key (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Key `a` is not a valid key for logical type `int-map`" (l/schema-at-path sku-to-qty-schema ["a"])))) (deftest test-schema-at-path-int-map-empty-path (let [path [] ret (-> (l/schema-at-path sku-to-qty-schema path) (u/edn-schema) (u/edn-schema->name-kw))] (is (= :deercreeklabs.unit.lt-test/sku-to-qty ret)))) (deftest test-flex-map-union (let [data1 {(ba/byte-array (range 16)) "name1"} data2 {1 "str2"} enc1 (l/serialize im-or-fm-schema data1) enc2 (l/serialize im-or-fm-schema data2) rt1 (l/deserialize-same im-or-fm-schema enc1) rt2 (l/deserialize-same im-or-fm-schema enc2)] (is (ba/equivalent-byte-arrays? (ffirst data1) (ffirst rt1))) (is (= (nfirst data1) (nfirst rt1))) (is (= data2 rt2)))) (deftest test-keyword-schema (let [data1 :a-simple-kw data2 ::a-namespaced-kw] (is (lt/round-trip? l/keyword-schema data1)) (is (lt/round-trip? l/keyword-schema data2)))) (deftest test-keyword-union-schema (let [data1 :a-simple-kw data2 ::a-namespaced-kw data3 123] (is (lt/round-trip? lt-union-schema data1)) (is (lt/round-trip? lt-union-schema data2)) (is (lt/round-trip? lt-union-schema data3)))) (deftest test-lt-schema-at-path (let [sch (l/map-schema lt-union-schema) child-sch (l/schema-at-path sch ["a"]) data :kw1] (is (lt/round-trip? child-sch data)))) (deftest test-name-kw-lt (let [sch (l/record-schema ::sch [[:foo/a l/keyword-schema] [:bar/b l/keyword-schema]]) data1 {:foo/a :a :bar/b :an-ns/b}] (is (lt/round-trip? sch data1)))) (deftest test-default-data-lt (let [sch (l/int-map-schema ::test l/string-schema) data (l/default-data sch)] (is (= {} data)))) (deftest test-lt-in-record (let [user-schema (l/record-schema ::user [[:name l/string-schema] [:nickname l/string-schema]]) users-schema (l/int-map-schema ::users user-schema) state-schema (l/record-schema ::state [[:users users-schema]]) data {:users {1 {:name "Bo" :nickname "B"}}} encoded (l/serialize state-schema data) decoded (l/deserialize-same state-schema encoded)] (is (= data decoded)))) (deftest test-lt-in-record-from-json (let [schema (l/int-map-schema ::im l/string-schema) rt-schema (l/json->schema (l/pcf schema)) data {1 "yyy"} encoded (l/serialize schema data) decoded (l/deserialize schema rt-schema encoded)] (is (= data decoded))))
122034
(ns deercreeklabs.unit.lt-test (:require [clojure.test :refer [deftest is use-fixtures]] [deercreeklabs.baracus :as ba] [deercreeklabs.lancaster :as l] [deercreeklabs.lancaster.utils :as u] [deercreeklabs.unit.lancaster-test :as lt] [schema.core :as s :include-macros true]) #?(:clj (:import (clojure.lang ExceptionInfo)))) ;; Use this instead of fixtures, which are hard to make work w/ async testing. (s/set-fn-validation! true) (l/def-int-map-schema sku-to-qty-schema l/int-schema) (def sku-to-qty-v2-schema (l/int-map-schema ::sku-to-qty l/long-schema)) (l/def-int-map-schema im-schema l/string-schema) (l/def-fixed-map-schema fm-schema 16 l/string-schema) (l/def-union-schema im-or-fm-schema im-schema fm-schema) (l/def-union-schema lt-union-schema l/keyword-schema l/string-schema l/int-schema) (deftest test-int-map-schema (is (= {:name :deercreeklabs.unit.lt-test/sku-to-qty :type :record :fields [{:name :deercreeklabs-unit-lt-test-sku-to-qty/ks :type {:type :array :items :int} :default []} {:name :deercreeklabs-unit-lt-test-sku-to-qty/vs :type {:type :array :items :int} :default []}]} (u/strip-lt-attrs (l/edn sku-to-qty-schema)))) #?(:clj (is (lt/fp-matches? sku-to-qty-schema))) (is (= (str "{\"name\":\"deercreeklabs.unit.lt_test.SkuToQty\",\"type\":" "\"record\",\"fields\":[{\"name\":" "\"deercreeklabsUnitLtTestSkuToQtyKs\",\"type\":{\"type\":\"array\"," "\"items\":\"int\"}},{\"name\":\"deercreeklabsUnitLtTestSkuToQtyVs\"," "\"type\":{\"type\":\"array\",\"items\":\"int\"}}]}") (l/pcf sku-to-qty-schema))) (is (= (str "{\"name\":\"deercreeklabs.unit.lt_test.SkuToQty\",\"fields\":" "[{\"name\":\"deercreeklabsUnitLtTestSkuToQtyKs\",\"type\":{\"type\":" "\"array\",\"items\":\"int\"},\"default\":[]},{\"name\":" "\"deercreeklabsUnitLtTestSkuToQtyVs\",\"type\":{\"type\":\"array\"," "\"items\":\"int\"},\"default\":[]}],\"type\":\"record\"," "\"logicalType\":\"int-map\"}") (l/json sku-to-qty-schema))) (is (= "-7668463894600081969" (u/long->str (l/fingerprint64 sku-to-qty-schema))))) (deftest test-embedded-int-map-pcf (let [fms (l/int-map-schema ::my-map l/int-schema) rs (l/record-schema :r [[:fm fms]])] (is (= (str "{\"name\":\"R\",\"type\":\"record\",\"fields\":[{\"name\":\"fm\"," "\"type\":[\"null\",{\"name\":\"deercreeklabs.unit.lt_test.MyMap\"" ",\"type\":\"record\",\"fields\":[{\"name\":" "\"deercreeklabsUnitLtTestMyMapKs\",\"type\":{\"type\":\"array\"," "\"items\":\"int\"}},{\"name\":\"deercreeklabsUnitLtTestMyMapVs\"," "\"type\":{\"type\":\"array\",\"items\":\"int\"}}]}]}]}") (l/pcf rs))))) (deftest test-int-map-schema-serdes (let [data {123 10 456 100 789 2} encoded (l/serialize sku-to-qty-schema data) decoded (l/deserialize-same sku-to-qty-schema encoded)] (is (ba/equivalent-byte-arrays? (ba/byte-array [6 -10 1 -112 7 -86 12 0 6 20 -56 1 4 0]) encoded)) (is (= data decoded)))) (deftest test-int-map-serdes-empty-map (let [data {} encoded (l/serialize sku-to-qty-schema data) decoded (l/deserialize-same sku-to-qty-schema encoded)] (is (= data decoded)))) (deftest test-maybe-int-map (let [int-map-schema (l/int-map-schema ::im l/int-schema) maybe-schema (l/maybe int-map-schema) data1 {1 1} data2 nil] (is (lt/round-trip? maybe-schema data1)) (is (lt/round-trip? maybe-schema data2)))) (deftest test-bad-fixed-map-size (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Second argument to fixed-map-schema must be a positive integer" (l/fixed-map-schema ::x -1 l/string-schema)))) (deftest test-int-map-evolution (let [data {123 10 456 100 789 2} encoded (l/serialize sku-to-qty-schema data) decoded (l/deserialize sku-to-qty-v2-schema sku-to-qty-schema encoded)] (is (= data decoded)))) (deftest test-schema-at-path-int-map (let [path [1] ret (-> (l/schema-at-path sku-to-qty-schema path) (u/edn-schema) (u/edn-schema->name-kw))] (is (= :int ret)))) (deftest test-schema-at-path-int-map-bad-key (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Key `a` is not a valid key for logical type `int-map`" (l/schema-at-path sku-to-qty-schema ["a"])))) (deftest test-schema-at-path-int-map-empty-path (let [path [] ret (-> (l/schema-at-path sku-to-qty-schema path) (u/edn-schema) (u/edn-schema->name-kw))] (is (= :deercreeklabs.unit.lt-test/sku-to-qty ret)))) (deftest test-flex-map-union (let [data1 {(ba/byte-array (range 16)) "name1"} data2 {1 "str2"} enc1 (l/serialize im-or-fm-schema data1) enc2 (l/serialize im-or-fm-schema data2) rt1 (l/deserialize-same im-or-fm-schema enc1) rt2 (l/deserialize-same im-or-fm-schema enc2)] (is (ba/equivalent-byte-arrays? (ffirst data1) (ffirst rt1))) (is (= (nfirst data1) (nfirst rt1))) (is (= data2 rt2)))) (deftest test-keyword-schema (let [data1 :a-simple-kw data2 ::a-namespaced-kw] (is (lt/round-trip? l/keyword-schema data1)) (is (lt/round-trip? l/keyword-schema data2)))) (deftest test-keyword-union-schema (let [data1 :a-simple-kw data2 ::a-namespaced-kw data3 123] (is (lt/round-trip? lt-union-schema data1)) (is (lt/round-trip? lt-union-schema data2)) (is (lt/round-trip? lt-union-schema data3)))) (deftest test-lt-schema-at-path (let [sch (l/map-schema lt-union-schema) child-sch (l/schema-at-path sch ["a"]) data :kw1] (is (lt/round-trip? child-sch data)))) (deftest test-name-kw-lt (let [sch (l/record-schema ::sch [[:foo/a l/keyword-schema] [:bar/b l/keyword-schema]]) data1 {:foo/a :a :bar/b :an-ns/b}] (is (lt/round-trip? sch data1)))) (deftest test-default-data-lt (let [sch (l/int-map-schema ::test l/string-schema) data (l/default-data sch)] (is (= {} data)))) (deftest test-lt-in-record (let [user-schema (l/record-schema ::user [[:name l/string-schema] [:nickname l/string-schema]]) users-schema (l/int-map-schema ::users user-schema) state-schema (l/record-schema ::state [[:users users-schema]]) data {:users {1 {:name "<NAME>" :nickname "B"}}} encoded (l/serialize state-schema data) decoded (l/deserialize-same state-schema encoded)] (is (= data decoded)))) (deftest test-lt-in-record-from-json (let [schema (l/int-map-schema ::im l/string-schema) rt-schema (l/json->schema (l/pcf schema)) data {1 "yyy"} encoded (l/serialize schema data) decoded (l/deserialize schema rt-schema encoded)] (is (= data decoded))))
true
(ns deercreeklabs.unit.lt-test (:require [clojure.test :refer [deftest is use-fixtures]] [deercreeklabs.baracus :as ba] [deercreeklabs.lancaster :as l] [deercreeklabs.lancaster.utils :as u] [deercreeklabs.unit.lancaster-test :as lt] [schema.core :as s :include-macros true]) #?(:clj (:import (clojure.lang ExceptionInfo)))) ;; Use this instead of fixtures, which are hard to make work w/ async testing. (s/set-fn-validation! true) (l/def-int-map-schema sku-to-qty-schema l/int-schema) (def sku-to-qty-v2-schema (l/int-map-schema ::sku-to-qty l/long-schema)) (l/def-int-map-schema im-schema l/string-schema) (l/def-fixed-map-schema fm-schema 16 l/string-schema) (l/def-union-schema im-or-fm-schema im-schema fm-schema) (l/def-union-schema lt-union-schema l/keyword-schema l/string-schema l/int-schema) (deftest test-int-map-schema (is (= {:name :deercreeklabs.unit.lt-test/sku-to-qty :type :record :fields [{:name :deercreeklabs-unit-lt-test-sku-to-qty/ks :type {:type :array :items :int} :default []} {:name :deercreeklabs-unit-lt-test-sku-to-qty/vs :type {:type :array :items :int} :default []}]} (u/strip-lt-attrs (l/edn sku-to-qty-schema)))) #?(:clj (is (lt/fp-matches? sku-to-qty-schema))) (is (= (str "{\"name\":\"deercreeklabs.unit.lt_test.SkuToQty\",\"type\":" "\"record\",\"fields\":[{\"name\":" "\"deercreeklabsUnitLtTestSkuToQtyKs\",\"type\":{\"type\":\"array\"," "\"items\":\"int\"}},{\"name\":\"deercreeklabsUnitLtTestSkuToQtyVs\"," "\"type\":{\"type\":\"array\",\"items\":\"int\"}}]}") (l/pcf sku-to-qty-schema))) (is (= (str "{\"name\":\"deercreeklabs.unit.lt_test.SkuToQty\",\"fields\":" "[{\"name\":\"deercreeklabsUnitLtTestSkuToQtyKs\",\"type\":{\"type\":" "\"array\",\"items\":\"int\"},\"default\":[]},{\"name\":" "\"deercreeklabsUnitLtTestSkuToQtyVs\",\"type\":{\"type\":\"array\"," "\"items\":\"int\"},\"default\":[]}],\"type\":\"record\"," "\"logicalType\":\"int-map\"}") (l/json sku-to-qty-schema))) (is (= "-7668463894600081969" (u/long->str (l/fingerprint64 sku-to-qty-schema))))) (deftest test-embedded-int-map-pcf (let [fms (l/int-map-schema ::my-map l/int-schema) rs (l/record-schema :r [[:fm fms]])] (is (= (str "{\"name\":\"R\",\"type\":\"record\",\"fields\":[{\"name\":\"fm\"," "\"type\":[\"null\",{\"name\":\"deercreeklabs.unit.lt_test.MyMap\"" ",\"type\":\"record\",\"fields\":[{\"name\":" "\"deercreeklabsUnitLtTestMyMapKs\",\"type\":{\"type\":\"array\"," "\"items\":\"int\"}},{\"name\":\"deercreeklabsUnitLtTestMyMapVs\"," "\"type\":{\"type\":\"array\",\"items\":\"int\"}}]}]}]}") (l/pcf rs))))) (deftest test-int-map-schema-serdes (let [data {123 10 456 100 789 2} encoded (l/serialize sku-to-qty-schema data) decoded (l/deserialize-same sku-to-qty-schema encoded)] (is (ba/equivalent-byte-arrays? (ba/byte-array [6 -10 1 -112 7 -86 12 0 6 20 -56 1 4 0]) encoded)) (is (= data decoded)))) (deftest test-int-map-serdes-empty-map (let [data {} encoded (l/serialize sku-to-qty-schema data) decoded (l/deserialize-same sku-to-qty-schema encoded)] (is (= data decoded)))) (deftest test-maybe-int-map (let [int-map-schema (l/int-map-schema ::im l/int-schema) maybe-schema (l/maybe int-map-schema) data1 {1 1} data2 nil] (is (lt/round-trip? maybe-schema data1)) (is (lt/round-trip? maybe-schema data2)))) (deftest test-bad-fixed-map-size (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Second argument to fixed-map-schema must be a positive integer" (l/fixed-map-schema ::x -1 l/string-schema)))) (deftest test-int-map-evolution (let [data {123 10 456 100 789 2} encoded (l/serialize sku-to-qty-schema data) decoded (l/deserialize sku-to-qty-v2-schema sku-to-qty-schema encoded)] (is (= data decoded)))) (deftest test-schema-at-path-int-map (let [path [1] ret (-> (l/schema-at-path sku-to-qty-schema path) (u/edn-schema) (u/edn-schema->name-kw))] (is (= :int ret)))) (deftest test-schema-at-path-int-map-bad-key (is (thrown-with-msg? #?(:clj ExceptionInfo :cljs js/Error) #"Key `a` is not a valid key for logical type `int-map`" (l/schema-at-path sku-to-qty-schema ["a"])))) (deftest test-schema-at-path-int-map-empty-path (let [path [] ret (-> (l/schema-at-path sku-to-qty-schema path) (u/edn-schema) (u/edn-schema->name-kw))] (is (= :deercreeklabs.unit.lt-test/sku-to-qty ret)))) (deftest test-flex-map-union (let [data1 {(ba/byte-array (range 16)) "name1"} data2 {1 "str2"} enc1 (l/serialize im-or-fm-schema data1) enc2 (l/serialize im-or-fm-schema data2) rt1 (l/deserialize-same im-or-fm-schema enc1) rt2 (l/deserialize-same im-or-fm-schema enc2)] (is (ba/equivalent-byte-arrays? (ffirst data1) (ffirst rt1))) (is (= (nfirst data1) (nfirst rt1))) (is (= data2 rt2)))) (deftest test-keyword-schema (let [data1 :a-simple-kw data2 ::a-namespaced-kw] (is (lt/round-trip? l/keyword-schema data1)) (is (lt/round-trip? l/keyword-schema data2)))) (deftest test-keyword-union-schema (let [data1 :a-simple-kw data2 ::a-namespaced-kw data3 123] (is (lt/round-trip? lt-union-schema data1)) (is (lt/round-trip? lt-union-schema data2)) (is (lt/round-trip? lt-union-schema data3)))) (deftest test-lt-schema-at-path (let [sch (l/map-schema lt-union-schema) child-sch (l/schema-at-path sch ["a"]) data :kw1] (is (lt/round-trip? child-sch data)))) (deftest test-name-kw-lt (let [sch (l/record-schema ::sch [[:foo/a l/keyword-schema] [:bar/b l/keyword-schema]]) data1 {:foo/a :a :bar/b :an-ns/b}] (is (lt/round-trip? sch data1)))) (deftest test-default-data-lt (let [sch (l/int-map-schema ::test l/string-schema) data (l/default-data sch)] (is (= {} data)))) (deftest test-lt-in-record (let [user-schema (l/record-schema ::user [[:name l/string-schema] [:nickname l/string-schema]]) users-schema (l/int-map-schema ::users user-schema) state-schema (l/record-schema ::state [[:users users-schema]]) data {:users {1 {:name "PI:NAME:<NAME>END_PI" :nickname "B"}}} encoded (l/serialize state-schema data) decoded (l/deserialize-same state-schema encoded)] (is (= data decoded)))) (deftest test-lt-in-record-from-json (let [schema (l/int-map-schema ::im l/string-schema) rt-schema (l/json->schema (l/pcf schema)) data {1 "yyy"} encoded (l/serialize schema data) decoded (l/deserialize schema rt-schema encoded)] (is (= data decoded))))
[ { "context": " (->> [{:id \"1000\"\n :name \"Luke Skywalker\"\n :friends [\"1002\", \"1003\", \"2000\", \"2", "end": 672, "score": 0.9998710751533508, "start": 658, "tag": "NAME", "value": "Luke Skywalker" }, { "context": " {:id \"1001\"\n :name \"Darth Vader\"\n :friends [\"1004\"]\n :enemes ", "end": 927, "score": 0.9998209476470947, "start": 916, "tag": "NAME", "value": "Darth Vader" }, { "context": " {:id \"1003\"\n :name \"Leia Organa\"\n :friends [\"1000\", \"1002\", \"2000\", \"2", "end": 1158, "score": 0.9998793601989746, "start": 1147, "tag": "NAME", "value": "Leia Organa" }, { "context": " {:id \"1002\"\n :name \"Han Solo\"\n :friends [\"1000\", \"1003\", \"2001\"]\n ", "end": 1410, "score": 0.9998583197593689, "start": 1402, "tag": "NAME", "value": "Han Solo" }, { "context": " {:id \"1004\"\n :name \"Wilhuff Tarkin\"\n :friends [\"1001\"]\n :enemies ", "end": 1628, "score": 0.9998811483383179, "start": 1614, "tag": "NAME", "value": "Wilhuff Tarkin" }, { "context": " \"2000\"\n :name \"C-3PO\"\n :friends [\"1000\", \"1002\", \"1", "end": 2128, "score": 0.6109061241149902, "start": 2127, "tag": "USERNAME", "value": "3" } ]
dev-resources/com/walmartlabs/test_schema.clj
gusbicalho/lacinia
0
(ns com.walmartlabs.test-schema (:require [com.walmartlabs.lacinia.schema :as schema ] [com.walmartlabs.lacinia.internal-utils :refer [ map-vals]] [clojure.spec.alpha :as s])) ;; ————————————————————————————————————————————————————————————————————————————— ;; ## Helpers (defn ^:private hash-map-by "Constructs a hash map from the supplied values. key-fn : Passed a value and extracts the key for that value. values : Seq of values from which map keys and values will be extracted." [key-fn values] (into {} (map (juxt key-fn identity)) values)) (def humans-data (->> [{:id "1000" :name "Luke Skywalker" :friends ["1002", "1003", "2000", "2001"] :enemies ["1002"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :homePlanet "Tatooine" :force-side "3001"} {:id "1001" :name "Darth Vader" :friends ["1004"] :enemes ["1000"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :homePlanet "Tatooine" :force-side "3000"} {:id "1003" :name "Leia Organa" :friends ["1000", "1002", "2000", "2001"] :enemies ["1001"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :homePlanet "Alderaan" :force-side "3001"} {:id "1002" :name "Han Solo" :friends ["1000", "1003", "2001"] :enemies ["1001"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :force-side "3001"} {:id "1004" :name "Wilhuff Tarkin" :friends ["1001"] :enemies ["1000"] :appears-in [:NEWHOPE] :force-side "3000"} ] (hash-map-by :id) (map-vals #(assoc % ::type :human)))) (def droids-data (->> [{:id "2001" :name "R2-D2" :friends ["1000", "1002", "1003"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :primary-function "ASTROMECH"} {:id "2000" :name "C-3PO" :friends ["1000", "1002", "1003", "2001"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :primary-function "PROTOCOL"} ] (hash-map-by :id) (map-vals #(assoc % ::type :droid)))) (def force-data (->> [{:id "3000" :name "dark" :members ["1001" "1004"]} {:id "3001" :name "light" :members ["1000" "1003" "1002"]}] (hash-map-by :id) (map-vals #(assoc % ::type :force)))) (defn with-tag [v] (if-let [type (::type v)] (schema/tag-with-type v type) v)) (defn get-character "Gets a character." [k] (with-tag (or (get humans-data k) (get droids-data k)))) (defn find-by-name [n] (->> (concat (vals humans-data) (vals droids-data)) (filter #(= n (:name %))) first)) (defn get-friends "Gets the friends of a character." [friends-coll] (mapv get-character friends-coll)) (defn get-enemies "Gets the enemie of a character." [enemies-coll] (mapv get-character enemies-coll)) (defn get-force-data "Gets side of the force that character is on." [k] (with-tag (get force-data k))) (defn get-force-members "Gets the members of a force side." [force-id] (let [members (get force-data force-id)] (mapv get-character members))) (defn get-hero "Usually retrieves the undisputed hero of the Star Wars trilogy, R2-D2." [episode] (get-character (if (= :NEWHOPE episode) "1000" ; luke "2001" ; r2d2 ))) ;; ————————————————————————————————————————————————————————————————————————————— ;; ## Schema (def date-formatter "Used by custom scalar :Date" (java.text.SimpleDateFormat. "yyyy-MM-dd")) (def test-schema {:enums {:episode {:description "The episodes of the original Star Wars trilogy." :values [:NEWHOPE :EMPIRE :JEDI]}} :scalars {:Date {:parse (s/conformer #(.parse date-formatter %)) :serialize (s/conformer (constantly "A long time ago"))}} :interfaces {:character {:fields {:id {:type 'String} :name {:type 'String} :appears_in {:type '(list :episode)} :friends {:type '(list :character)} :enemies {:type '(list (non-null :character))} :family {:type '(non-null (list :character))} :droids {:type '(non-null (list (non-null :character)))} :forceSide {:type :force} :foo {:type '(non-null String)} :bar {:type :character} :best_friend {:type :character} :arch_enemy {:type '(non-null :character)}}}} :input-objects {:nestedInputObject ;; used for testing argument coercion and validation {:fields {:integerArray {:type '(list Int)} :name {:type 'String} :date {:type :Date}}} :testInputObject ;; used for testing argument coercion and validation {:fields {:integer {:type 'Int} :string {:type 'String} :nestedInputObject {:type :nestedInputObject}}}} :objects {:force {:fields {:id {:type 'String} :name {:type 'String} :members {:type '(list :character) :resolve (fn [ctx args v] (let [{:keys [members]} v] (get-force-members members)))}}} ;; used for testing argument coercion and validation :echoArgs {:fields {:integer {:type 'Int} :integerArray {:type '(list Int)} :inputObject {:type :testInputObject}}} :galaxy_date {:fields {:date {:type :Date}}} :droid {:implements [:character] :fields {:id {:type 'String} :name {:type 'String} :appears_in {:type '(list :episode)} :friends {:type '(list :character) :resolve (fn [ctx args v] (let [{:keys [friends]} v] (get-friends friends)))} :enemies {:type '(list (non-null :character)) :resolve (fn [ctx args v] (let [{:keys [enemies]} v] (get-enemies enemies)))} :family {:type '(non-null (list :character)) :resolve (fn [ctx args v] (let [{:keys [friends]} v] (get-friends friends)))} :droids {:type '(non-null (list (non-null :character))) :resolve (fn [ctx args v] [])} :forceSide {:type :force :resolve (fn [ctx args v] (let [{:keys [force-side]} v] (get-force-data force-side)))} :foo {:type '(non-null String)} :bar {:type :character} :best_friend {:type :character :resolve (fn [ctx args v] (let [{:keys [friends]} v] (first (get-friends friends))))} :arch_enemy {:type '(non-null :character) :resolve (fn [ctx args v] nil)} :primary_function {:type '(list String)} :incept_date {:type 'Int ;; This will cause a failure, since expecting single: :resolve (fn [_ _ _] [1 2 3])} :accessories {:type '(list String) ;; This will cause a failure, since expecting multiple: :resolve (fn [_ _ _] "<Single Value>")}}} :human {:implements [:character] :fields {:id {:type 'String} :name {:type 'String} :appears_in {:type '(list :episode)} :friends {:type '(list :character) :resolve (fn [ctx args v] (let [{:keys [friends]} v] (get-friends friends)))} :enemies {:type '(list (non-null :character)) :resolve (fn [ctx args v] (let [{:keys [enemies]} v] (get-enemies enemies)))} :family {:type '(non-null (list :character)) :resolve (fn [ctx args v] (let [{:keys [friends]} v] (get-friends friends)))} :droids {:type '(non-null (list (non-null :character))) :resolve (fn [ctx args v] [])} :forceSide {:type :force :resolve (fn [ctx args v] (let [{:keys [force-side]} v] (get-force-data force-side)))} :foo {:type '(non-null String)} :bar {:type :character} :best_friend {:type :character :resolve (fn [ctx args v] (let [{:keys [friends]} v] (first (get-friends friends))))} :arch_enemy {:type '(non-null :character) :resolve (fn [ctx args v] nil)} :primary_function {:type '(list String)} :homePlanet {:type 'String}}}} :mutations {:changeHeroName {:type :character :args {:from {:type 'String} :to {:type 'String :default-value "Rey"}} :resolve (fn [ctx args v] (let [{:keys [from to]} args] (-> (find-by-name from) (assoc :name to) with-tag)))} :addHeroEpisodes {:type :character :args {:id {:type '(non-null String)} :episodes {:type '(non-null (list :episode))} :does_nothing {:type 'String}} :resolve (fn [ctx args v] (with-tag (let [{:keys [id episodes]} args hero (get humans-data id)] (update hero :appears-in concat episodes))))} :changeHeroHomePlanet {:type :human :args {:id {:type '(non-null String)} :newHomePlanet {:type 'String}} :resolve (fn [ctx args v] (with-tag (let [hero (get humans-data (:id args))] (if (contains? args :newHomePlanet) (assoc hero :homePlanet (:newHomePlanet args)) hero))))}} :queries {:hero {:type '(non-null :character) :args {:episode {:type :episode}} :resolve (fn [ctx args v] (let [{:keys [episode]} args] (get-hero episode)))} :echoArgs {:type :echoArgs :args {:integer {:type 'Int} :integerArray {:type '(list Int)} :inputObject {:type :testInputObject}} :resolve (fn [ctx args v] args)} :now {:type :galaxy_date :resolve (fn [ctx args v] {:date (java.util.Date.)})} :human {:type '(non-null :human) :args {:id {:type 'String :default-value "1001"}} :resolve (fn [ctx args v] (let [{:keys [id]} args] (get humans-data id)))} :droid {:type :droid :args {:id {:type 'String :default-value "2001"}} :resolve (fn [ctx args v] (get droids-data (:id args)))}}})
52660
(ns com.walmartlabs.test-schema (:require [com.walmartlabs.lacinia.schema :as schema ] [com.walmartlabs.lacinia.internal-utils :refer [ map-vals]] [clojure.spec.alpha :as s])) ;; ————————————————————————————————————————————————————————————————————————————— ;; ## Helpers (defn ^:private hash-map-by "Constructs a hash map from the supplied values. key-fn : Passed a value and extracts the key for that value. values : Seq of values from which map keys and values will be extracted." [key-fn values] (into {} (map (juxt key-fn identity)) values)) (def humans-data (->> [{:id "1000" :name "<NAME>" :friends ["1002", "1003", "2000", "2001"] :enemies ["1002"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :homePlanet "Tatooine" :force-side "3001"} {:id "1001" :name "<NAME>" :friends ["1004"] :enemes ["1000"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :homePlanet "Tatooine" :force-side "3000"} {:id "1003" :name "<NAME>" :friends ["1000", "1002", "2000", "2001"] :enemies ["1001"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :homePlanet "Alderaan" :force-side "3001"} {:id "1002" :name "<NAME>" :friends ["1000", "1003", "2001"] :enemies ["1001"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :force-side "3001"} {:id "1004" :name "<NAME>" :friends ["1001"] :enemies ["1000"] :appears-in [:NEWHOPE] :force-side "3000"} ] (hash-map-by :id) (map-vals #(assoc % ::type :human)))) (def droids-data (->> [{:id "2001" :name "R2-D2" :friends ["1000", "1002", "1003"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :primary-function "ASTROMECH"} {:id "2000" :name "C-3PO" :friends ["1000", "1002", "1003", "2001"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :primary-function "PROTOCOL"} ] (hash-map-by :id) (map-vals #(assoc % ::type :droid)))) (def force-data (->> [{:id "3000" :name "dark" :members ["1001" "1004"]} {:id "3001" :name "light" :members ["1000" "1003" "1002"]}] (hash-map-by :id) (map-vals #(assoc % ::type :force)))) (defn with-tag [v] (if-let [type (::type v)] (schema/tag-with-type v type) v)) (defn get-character "Gets a character." [k] (with-tag (or (get humans-data k) (get droids-data k)))) (defn find-by-name [n] (->> (concat (vals humans-data) (vals droids-data)) (filter #(= n (:name %))) first)) (defn get-friends "Gets the friends of a character." [friends-coll] (mapv get-character friends-coll)) (defn get-enemies "Gets the enemie of a character." [enemies-coll] (mapv get-character enemies-coll)) (defn get-force-data "Gets side of the force that character is on." [k] (with-tag (get force-data k))) (defn get-force-members "Gets the members of a force side." [force-id] (let [members (get force-data force-id)] (mapv get-character members))) (defn get-hero "Usually retrieves the undisputed hero of the Star Wars trilogy, R2-D2." [episode] (get-character (if (= :NEWHOPE episode) "1000" ; luke "2001" ; r2d2 ))) ;; ————————————————————————————————————————————————————————————————————————————— ;; ## Schema (def date-formatter "Used by custom scalar :Date" (java.text.SimpleDateFormat. "yyyy-MM-dd")) (def test-schema {:enums {:episode {:description "The episodes of the original Star Wars trilogy." :values [:NEWHOPE :EMPIRE :JEDI]}} :scalars {:Date {:parse (s/conformer #(.parse date-formatter %)) :serialize (s/conformer (constantly "A long time ago"))}} :interfaces {:character {:fields {:id {:type 'String} :name {:type 'String} :appears_in {:type '(list :episode)} :friends {:type '(list :character)} :enemies {:type '(list (non-null :character))} :family {:type '(non-null (list :character))} :droids {:type '(non-null (list (non-null :character)))} :forceSide {:type :force} :foo {:type '(non-null String)} :bar {:type :character} :best_friend {:type :character} :arch_enemy {:type '(non-null :character)}}}} :input-objects {:nestedInputObject ;; used for testing argument coercion and validation {:fields {:integerArray {:type '(list Int)} :name {:type 'String} :date {:type :Date}}} :testInputObject ;; used for testing argument coercion and validation {:fields {:integer {:type 'Int} :string {:type 'String} :nestedInputObject {:type :nestedInputObject}}}} :objects {:force {:fields {:id {:type 'String} :name {:type 'String} :members {:type '(list :character) :resolve (fn [ctx args v] (let [{:keys [members]} v] (get-force-members members)))}}} ;; used for testing argument coercion and validation :echoArgs {:fields {:integer {:type 'Int} :integerArray {:type '(list Int)} :inputObject {:type :testInputObject}}} :galaxy_date {:fields {:date {:type :Date}}} :droid {:implements [:character] :fields {:id {:type 'String} :name {:type 'String} :appears_in {:type '(list :episode)} :friends {:type '(list :character) :resolve (fn [ctx args v] (let [{:keys [friends]} v] (get-friends friends)))} :enemies {:type '(list (non-null :character)) :resolve (fn [ctx args v] (let [{:keys [enemies]} v] (get-enemies enemies)))} :family {:type '(non-null (list :character)) :resolve (fn [ctx args v] (let [{:keys [friends]} v] (get-friends friends)))} :droids {:type '(non-null (list (non-null :character))) :resolve (fn [ctx args v] [])} :forceSide {:type :force :resolve (fn [ctx args v] (let [{:keys [force-side]} v] (get-force-data force-side)))} :foo {:type '(non-null String)} :bar {:type :character} :best_friend {:type :character :resolve (fn [ctx args v] (let [{:keys [friends]} v] (first (get-friends friends))))} :arch_enemy {:type '(non-null :character) :resolve (fn [ctx args v] nil)} :primary_function {:type '(list String)} :incept_date {:type 'Int ;; This will cause a failure, since expecting single: :resolve (fn [_ _ _] [1 2 3])} :accessories {:type '(list String) ;; This will cause a failure, since expecting multiple: :resolve (fn [_ _ _] "<Single Value>")}}} :human {:implements [:character] :fields {:id {:type 'String} :name {:type 'String} :appears_in {:type '(list :episode)} :friends {:type '(list :character) :resolve (fn [ctx args v] (let [{:keys [friends]} v] (get-friends friends)))} :enemies {:type '(list (non-null :character)) :resolve (fn [ctx args v] (let [{:keys [enemies]} v] (get-enemies enemies)))} :family {:type '(non-null (list :character)) :resolve (fn [ctx args v] (let [{:keys [friends]} v] (get-friends friends)))} :droids {:type '(non-null (list (non-null :character))) :resolve (fn [ctx args v] [])} :forceSide {:type :force :resolve (fn [ctx args v] (let [{:keys [force-side]} v] (get-force-data force-side)))} :foo {:type '(non-null String)} :bar {:type :character} :best_friend {:type :character :resolve (fn [ctx args v] (let [{:keys [friends]} v] (first (get-friends friends))))} :arch_enemy {:type '(non-null :character) :resolve (fn [ctx args v] nil)} :primary_function {:type '(list String)} :homePlanet {:type 'String}}}} :mutations {:changeHeroName {:type :character :args {:from {:type 'String} :to {:type 'String :default-value "Rey"}} :resolve (fn [ctx args v] (let [{:keys [from to]} args] (-> (find-by-name from) (assoc :name to) with-tag)))} :addHeroEpisodes {:type :character :args {:id {:type '(non-null String)} :episodes {:type '(non-null (list :episode))} :does_nothing {:type 'String}} :resolve (fn [ctx args v] (with-tag (let [{:keys [id episodes]} args hero (get humans-data id)] (update hero :appears-in concat episodes))))} :changeHeroHomePlanet {:type :human :args {:id {:type '(non-null String)} :newHomePlanet {:type 'String}} :resolve (fn [ctx args v] (with-tag (let [hero (get humans-data (:id args))] (if (contains? args :newHomePlanet) (assoc hero :homePlanet (:newHomePlanet args)) hero))))}} :queries {:hero {:type '(non-null :character) :args {:episode {:type :episode}} :resolve (fn [ctx args v] (let [{:keys [episode]} args] (get-hero episode)))} :echoArgs {:type :echoArgs :args {:integer {:type 'Int} :integerArray {:type '(list Int)} :inputObject {:type :testInputObject}} :resolve (fn [ctx args v] args)} :now {:type :galaxy_date :resolve (fn [ctx args v] {:date (java.util.Date.)})} :human {:type '(non-null :human) :args {:id {:type 'String :default-value "1001"}} :resolve (fn [ctx args v] (let [{:keys [id]} args] (get humans-data id)))} :droid {:type :droid :args {:id {:type 'String :default-value "2001"}} :resolve (fn [ctx args v] (get droids-data (:id args)))}}})
true
(ns com.walmartlabs.test-schema (:require [com.walmartlabs.lacinia.schema :as schema ] [com.walmartlabs.lacinia.internal-utils :refer [ map-vals]] [clojure.spec.alpha :as s])) ;; ————————————————————————————————————————————————————————————————————————————— ;; ## Helpers (defn ^:private hash-map-by "Constructs a hash map from the supplied values. key-fn : Passed a value and extracts the key for that value. values : Seq of values from which map keys and values will be extracted." [key-fn values] (into {} (map (juxt key-fn identity)) values)) (def humans-data (->> [{:id "1000" :name "PI:NAME:<NAME>END_PI" :friends ["1002", "1003", "2000", "2001"] :enemies ["1002"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :homePlanet "Tatooine" :force-side "3001"} {:id "1001" :name "PI:NAME:<NAME>END_PI" :friends ["1004"] :enemes ["1000"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :homePlanet "Tatooine" :force-side "3000"} {:id "1003" :name "PI:NAME:<NAME>END_PI" :friends ["1000", "1002", "2000", "2001"] :enemies ["1001"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :homePlanet "Alderaan" :force-side "3001"} {:id "1002" :name "PI:NAME:<NAME>END_PI" :friends ["1000", "1003", "2001"] :enemies ["1001"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :force-side "3001"} {:id "1004" :name "PI:NAME:<NAME>END_PI" :friends ["1001"] :enemies ["1000"] :appears-in [:NEWHOPE] :force-side "3000"} ] (hash-map-by :id) (map-vals #(assoc % ::type :human)))) (def droids-data (->> [{:id "2001" :name "R2-D2" :friends ["1000", "1002", "1003"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :primary-function "ASTROMECH"} {:id "2000" :name "C-3PO" :friends ["1000", "1002", "1003", "2001"] :appears-in [:NEWHOPE :EMPIRE :JEDI] :primary-function "PROTOCOL"} ] (hash-map-by :id) (map-vals #(assoc % ::type :droid)))) (def force-data (->> [{:id "3000" :name "dark" :members ["1001" "1004"]} {:id "3001" :name "light" :members ["1000" "1003" "1002"]}] (hash-map-by :id) (map-vals #(assoc % ::type :force)))) (defn with-tag [v] (if-let [type (::type v)] (schema/tag-with-type v type) v)) (defn get-character "Gets a character." [k] (with-tag (or (get humans-data k) (get droids-data k)))) (defn find-by-name [n] (->> (concat (vals humans-data) (vals droids-data)) (filter #(= n (:name %))) first)) (defn get-friends "Gets the friends of a character." [friends-coll] (mapv get-character friends-coll)) (defn get-enemies "Gets the enemie of a character." [enemies-coll] (mapv get-character enemies-coll)) (defn get-force-data "Gets side of the force that character is on." [k] (with-tag (get force-data k))) (defn get-force-members "Gets the members of a force side." [force-id] (let [members (get force-data force-id)] (mapv get-character members))) (defn get-hero "Usually retrieves the undisputed hero of the Star Wars trilogy, R2-D2." [episode] (get-character (if (= :NEWHOPE episode) "1000" ; luke "2001" ; r2d2 ))) ;; ————————————————————————————————————————————————————————————————————————————— ;; ## Schema (def date-formatter "Used by custom scalar :Date" (java.text.SimpleDateFormat. "yyyy-MM-dd")) (def test-schema {:enums {:episode {:description "The episodes of the original Star Wars trilogy." :values [:NEWHOPE :EMPIRE :JEDI]}} :scalars {:Date {:parse (s/conformer #(.parse date-formatter %)) :serialize (s/conformer (constantly "A long time ago"))}} :interfaces {:character {:fields {:id {:type 'String} :name {:type 'String} :appears_in {:type '(list :episode)} :friends {:type '(list :character)} :enemies {:type '(list (non-null :character))} :family {:type '(non-null (list :character))} :droids {:type '(non-null (list (non-null :character)))} :forceSide {:type :force} :foo {:type '(non-null String)} :bar {:type :character} :best_friend {:type :character} :arch_enemy {:type '(non-null :character)}}}} :input-objects {:nestedInputObject ;; used for testing argument coercion and validation {:fields {:integerArray {:type '(list Int)} :name {:type 'String} :date {:type :Date}}} :testInputObject ;; used for testing argument coercion and validation {:fields {:integer {:type 'Int} :string {:type 'String} :nestedInputObject {:type :nestedInputObject}}}} :objects {:force {:fields {:id {:type 'String} :name {:type 'String} :members {:type '(list :character) :resolve (fn [ctx args v] (let [{:keys [members]} v] (get-force-members members)))}}} ;; used for testing argument coercion and validation :echoArgs {:fields {:integer {:type 'Int} :integerArray {:type '(list Int)} :inputObject {:type :testInputObject}}} :galaxy_date {:fields {:date {:type :Date}}} :droid {:implements [:character] :fields {:id {:type 'String} :name {:type 'String} :appears_in {:type '(list :episode)} :friends {:type '(list :character) :resolve (fn [ctx args v] (let [{:keys [friends]} v] (get-friends friends)))} :enemies {:type '(list (non-null :character)) :resolve (fn [ctx args v] (let [{:keys [enemies]} v] (get-enemies enemies)))} :family {:type '(non-null (list :character)) :resolve (fn [ctx args v] (let [{:keys [friends]} v] (get-friends friends)))} :droids {:type '(non-null (list (non-null :character))) :resolve (fn [ctx args v] [])} :forceSide {:type :force :resolve (fn [ctx args v] (let [{:keys [force-side]} v] (get-force-data force-side)))} :foo {:type '(non-null String)} :bar {:type :character} :best_friend {:type :character :resolve (fn [ctx args v] (let [{:keys [friends]} v] (first (get-friends friends))))} :arch_enemy {:type '(non-null :character) :resolve (fn [ctx args v] nil)} :primary_function {:type '(list String)} :incept_date {:type 'Int ;; This will cause a failure, since expecting single: :resolve (fn [_ _ _] [1 2 3])} :accessories {:type '(list String) ;; This will cause a failure, since expecting multiple: :resolve (fn [_ _ _] "<Single Value>")}}} :human {:implements [:character] :fields {:id {:type 'String} :name {:type 'String} :appears_in {:type '(list :episode)} :friends {:type '(list :character) :resolve (fn [ctx args v] (let [{:keys [friends]} v] (get-friends friends)))} :enemies {:type '(list (non-null :character)) :resolve (fn [ctx args v] (let [{:keys [enemies]} v] (get-enemies enemies)))} :family {:type '(non-null (list :character)) :resolve (fn [ctx args v] (let [{:keys [friends]} v] (get-friends friends)))} :droids {:type '(non-null (list (non-null :character))) :resolve (fn [ctx args v] [])} :forceSide {:type :force :resolve (fn [ctx args v] (let [{:keys [force-side]} v] (get-force-data force-side)))} :foo {:type '(non-null String)} :bar {:type :character} :best_friend {:type :character :resolve (fn [ctx args v] (let [{:keys [friends]} v] (first (get-friends friends))))} :arch_enemy {:type '(non-null :character) :resolve (fn [ctx args v] nil)} :primary_function {:type '(list String)} :homePlanet {:type 'String}}}} :mutations {:changeHeroName {:type :character :args {:from {:type 'String} :to {:type 'String :default-value "Rey"}} :resolve (fn [ctx args v] (let [{:keys [from to]} args] (-> (find-by-name from) (assoc :name to) with-tag)))} :addHeroEpisodes {:type :character :args {:id {:type '(non-null String)} :episodes {:type '(non-null (list :episode))} :does_nothing {:type 'String}} :resolve (fn [ctx args v] (with-tag (let [{:keys [id episodes]} args hero (get humans-data id)] (update hero :appears-in concat episodes))))} :changeHeroHomePlanet {:type :human :args {:id {:type '(non-null String)} :newHomePlanet {:type 'String}} :resolve (fn [ctx args v] (with-tag (let [hero (get humans-data (:id args))] (if (contains? args :newHomePlanet) (assoc hero :homePlanet (:newHomePlanet args)) hero))))}} :queries {:hero {:type '(non-null :character) :args {:episode {:type :episode}} :resolve (fn [ctx args v] (let [{:keys [episode]} args] (get-hero episode)))} :echoArgs {:type :echoArgs :args {:integer {:type 'Int} :integerArray {:type '(list Int)} :inputObject {:type :testInputObject}} :resolve (fn [ctx args v] args)} :now {:type :galaxy_date :resolve (fn [ctx args v] {:date (java.util.Date.)})} :human {:type '(non-null :human) :args {:id {:type 'String :default-value "1001"}} :resolve (fn [ctx args v] (let [{:keys [id]} args] (get humans-data id)))} :droid {:type :droid :args {:id {:type 'String :default-value "2001"}} :resolve (fn [ctx args v] (get droids-data (:id args)))}}})
[ { "context": " :maintainer \"Me Myself\"})\n \"leiningen vs. the an", "end": 2092, "score": 0.6718704104423523, "start": 2086, "tag": "NAME", "value": "Myself" }, { "context": " :maintainer \"Me Myself\"})\n \"Booty McBootface\")))", "end": 2447, "score": 0.8211922645568848, "start": 2441, "tag": "NAME", "value": "Myself" }, { "context": " :maintainer \"Me Myself\"})\n \"Tools Deps is not a ", "end": 2873, "score": 0.688757061958313, "start": 2867, "tag": "NAME", "value": "Myself" } ]
test/docker_clojure/dockerfile_test.clj
rwstauner/docker-clojure
0
(ns docker-clojure.dockerfile-test (:require [clojure.string :as str] [clojure.test :refer :all] [docker-clojure.dockerfile :refer :all] [docker-clojure.dockerfile.lein :as lein] [docker-clojure.dockerfile.boot :as boot] [docker-clojure.dockerfile.tools-deps :as tools-deps])) (deftest base-image-tag-test (testing "debian is omitted" (is (= "base" (base-image-tag {:base-image "base", :distro "debian"})))) (testing "other distros are added to base-image" (is (= "base-alpine" (base-image-tag {:base-image "base" :distro "alpine"}))))) (deftest base-image-filename-test (testing "replaces colons with hyphens in tag" (is (= "openjdk-11-alpine" (base-image-filename {:base-image "openjdk:11" :distro "alpine"}))))) (deftest filename-test (testing "starts with 'Dockerfile'" (is (str/starts-with? (filename {:base-image "openjdk:11"}) "Dockerfile"))) (with-redefs [base-image-filename (constantly "foo")] (testing "includes base-image-filename" (is (str/includes? (filename {}) "foo")))) (testing "includes build-tool" (is (str/includes? (filename {:build-tool "lein"}) "lein")))) (deftest contents-test (testing "includes 'FROM base-image'" (is (str/includes? (contents {:base-image "base:foo" :build-tool "boot"}) "FROM base:foo"))) (testing "includes maintainer label" (is (str/includes? (contents {:base-image "base:foo" :build-tool "boot" :maintainer "Me Myself"}) "LABEL maintainer=\"Me Myself\""))) (testing "lein variant includes lein-specific contents" (with-redefs [lein/contents (constantly ["leiningen vs. the ants"])] (is (str/includes? (contents {:base-image "base:foo" :build-tool "lein" :maintainer "Me Myself"}) "leiningen vs. the ants")))) (testing "boot variant includes boot-specific contents" (with-redefs [boot/contents (constantly ["Booty McBootface"])] (is (str/includes? (contents {:base-image "base:foo" :build-tool "boot" :maintainer "Me Myself"}) "Booty McBootface")))) (testing "tools-deps variant includes tools-deps-specific contents" (with-redefs [tools-deps/contents (constantly ["Tools Deps is not a build tool"])] (is (str/includes? (contents {:base-image "base:foo" :build-tool "tools-deps" :maintainer "Me Myself"}) "Tools Deps is not a build tool")))))
14997
(ns docker-clojure.dockerfile-test (:require [clojure.string :as str] [clojure.test :refer :all] [docker-clojure.dockerfile :refer :all] [docker-clojure.dockerfile.lein :as lein] [docker-clojure.dockerfile.boot :as boot] [docker-clojure.dockerfile.tools-deps :as tools-deps])) (deftest base-image-tag-test (testing "debian is omitted" (is (= "base" (base-image-tag {:base-image "base", :distro "debian"})))) (testing "other distros are added to base-image" (is (= "base-alpine" (base-image-tag {:base-image "base" :distro "alpine"}))))) (deftest base-image-filename-test (testing "replaces colons with hyphens in tag" (is (= "openjdk-11-alpine" (base-image-filename {:base-image "openjdk:11" :distro "alpine"}))))) (deftest filename-test (testing "starts with 'Dockerfile'" (is (str/starts-with? (filename {:base-image "openjdk:11"}) "Dockerfile"))) (with-redefs [base-image-filename (constantly "foo")] (testing "includes base-image-filename" (is (str/includes? (filename {}) "foo")))) (testing "includes build-tool" (is (str/includes? (filename {:build-tool "lein"}) "lein")))) (deftest contents-test (testing "includes 'FROM base-image'" (is (str/includes? (contents {:base-image "base:foo" :build-tool "boot"}) "FROM base:foo"))) (testing "includes maintainer label" (is (str/includes? (contents {:base-image "base:foo" :build-tool "boot" :maintainer "Me Myself"}) "LABEL maintainer=\"Me Myself\""))) (testing "lein variant includes lein-specific contents" (with-redefs [lein/contents (constantly ["leiningen vs. the ants"])] (is (str/includes? (contents {:base-image "base:foo" :build-tool "lein" :maintainer "Me <NAME>"}) "leiningen vs. the ants")))) (testing "boot variant includes boot-specific contents" (with-redefs [boot/contents (constantly ["Booty McBootface"])] (is (str/includes? (contents {:base-image "base:foo" :build-tool "boot" :maintainer "Me <NAME>"}) "Booty McBootface")))) (testing "tools-deps variant includes tools-deps-specific contents" (with-redefs [tools-deps/contents (constantly ["Tools Deps is not a build tool"])] (is (str/includes? (contents {:base-image "base:foo" :build-tool "tools-deps" :maintainer "Me <NAME>"}) "Tools Deps is not a build tool")))))
true
(ns docker-clojure.dockerfile-test (:require [clojure.string :as str] [clojure.test :refer :all] [docker-clojure.dockerfile :refer :all] [docker-clojure.dockerfile.lein :as lein] [docker-clojure.dockerfile.boot :as boot] [docker-clojure.dockerfile.tools-deps :as tools-deps])) (deftest base-image-tag-test (testing "debian is omitted" (is (= "base" (base-image-tag {:base-image "base", :distro "debian"})))) (testing "other distros are added to base-image" (is (= "base-alpine" (base-image-tag {:base-image "base" :distro "alpine"}))))) (deftest base-image-filename-test (testing "replaces colons with hyphens in tag" (is (= "openjdk-11-alpine" (base-image-filename {:base-image "openjdk:11" :distro "alpine"}))))) (deftest filename-test (testing "starts with 'Dockerfile'" (is (str/starts-with? (filename {:base-image "openjdk:11"}) "Dockerfile"))) (with-redefs [base-image-filename (constantly "foo")] (testing "includes base-image-filename" (is (str/includes? (filename {}) "foo")))) (testing "includes build-tool" (is (str/includes? (filename {:build-tool "lein"}) "lein")))) (deftest contents-test (testing "includes 'FROM base-image'" (is (str/includes? (contents {:base-image "base:foo" :build-tool "boot"}) "FROM base:foo"))) (testing "includes maintainer label" (is (str/includes? (contents {:base-image "base:foo" :build-tool "boot" :maintainer "Me Myself"}) "LABEL maintainer=\"Me Myself\""))) (testing "lein variant includes lein-specific contents" (with-redefs [lein/contents (constantly ["leiningen vs. the ants"])] (is (str/includes? (contents {:base-image "base:foo" :build-tool "lein" :maintainer "Me PI:NAME:<NAME>END_PI"}) "leiningen vs. the ants")))) (testing "boot variant includes boot-specific contents" (with-redefs [boot/contents (constantly ["Booty McBootface"])] (is (str/includes? (contents {:base-image "base:foo" :build-tool "boot" :maintainer "Me PI:NAME:<NAME>END_PI"}) "Booty McBootface")))) (testing "tools-deps variant includes tools-deps-specific contents" (with-redefs [tools-deps/contents (constantly ["Tools Deps is not a build tool"])] (is (str/includes? (contents {:base-image "base:foo" :build-tool "tools-deps" :maintainer "Me PI:NAME:<NAME>END_PI"}) "Tools Deps is not a build tool")))))
[ { "context": " [:p {:style \"font-size: 0.8em\"}\n [:strong \"Christian Meter\"]]\n [:small\n \"Institut für Informatik\" [:b", "end": 626, "score": 0.9997865557670593, "start": 611, "tag": "NAME", "value": "Christian Meter" }, { "context": "eldorf\" [:br]\n \"19.02.2020\" [:br] [:br]\n \"meter@hhu.de\" [:br]\n \"@cmeter_ / @clojure_dus\"]]])\n\n(def s", "end": 778, "score": 0.9998965263366699, "start": 766, "tag": "EMAIL", "value": "meter@hhu.de" }, { "context": "2.2020\" [:br] [:br]\n \"meter@hhu.de\" [:br]\n \"@cmeter_ / @clojure_dus\"]]])\n\n(def slide-clojuredus\n (sec", "end": 800, "score": 0.9975021481513977, "start": 791, "tag": "USERNAME", "value": "\"@cmeter_" }, { "context": "] [:br]\n \"meter@hhu.de\" [:br]\n \"@cmeter_ / @clojure_dus\"]]])\n\n(def slide-clojuredus\n (section-with-title", "end": 815, "score": 0.9975687861442566, "start": 803, "tag": "USERNAME", "value": "@clojure_dus" }, { "context": "ght: .25em\"}]\n [:a {:href \"https://github.com/clojuredus/fizzbuzz-einsteiger\"}\n \"clojuredus/fizzbuzz-", "end": 2896, "score": 0.9996792674064636, "start": 2886, "tag": "USERNAME", "value": "clojuredus" }, { "context": "ithub.com/clojuredus/fizzbuzz-einsteiger\"}\n \"clojuredus/fizzbuzz-einsteiger\"]]\n\n [:p \"Code aus diesem ", "end": 2936, "score": 0.9708013534545898, "start": 2926, "tag": "USERNAME", "value": "clojuredus" }, { "context": "ght: .25em\"}]\n [:a {:href \"https://github.com/n2o/2020-clojure-von-null-zu-fizzbuzz-talk\"}\n \"n", "end": 3153, "score": 0.999519407749176, "start": 3150, "tag": "USERNAME", "value": "n2o" }, { "context": "o/2020-clojure-von-null-zu-fizzbuzz-talk\"}\n \"n2o/2020-clojure-von-null-zu-fizzbuzz-talk\"]]\n\n [:", "end": 3205, "score": 0.5840175151824951, "start": 3202, "tag": "USERNAME", "value": "n2o" } ]
src/reveal/slides.cljs
n2o/2020-clojure-von-null-zu-fizzbuzz-talk
2
(ns reveal.slides (:require [clojure.string :as string])) (defn- section-with-title [title & htmls] (let [slugged (string/replace title #"\W" "")] [:section {:data-state slugged} [:style (str "." slugged " header span:after {content: \"" title "\";}")] htmls])) ;; ---------------------------------------------------------------------------- (def slide-1 [:section {:data-state "footer"} [:div#title [:h3 [:img {:style "height: 3em;" :src "img/clojure_logo.svg"}] [:br] "Clojure: Von Null zu FizzBuzz"] [:hr] [:p {:style "font-size: 0.8em"} [:strong "Christian Meter"]] [:small "Institut für Informatik" [:br] "Heinrich-Heine-Universität Düsseldorf" [:br] "19.02.2020" [:br] [:br] "meter@hhu.de" [:br] "@cmeter_ / @clojure_dus"]]]) (def slide-clojuredus (section-with-title "Wer sind wir?" [:img {:src "img/logo2019.svg"}] [:p [:a {:href "http://clojure-duesseldorf.de"} "clojure-duesseldorf.de"]])) (def slide-next (section-with-title "Was kommt als nächstes?" [:p [:strong "Lightning Talks"] [:br] "am 26.03.2020"] [:div.row [:div.col-6 [:p "Themenideen:"] [:p "👩‍🏫 Data-Science in Clojure"] [:p "🕵️‍♂️ Statische Codeanalyse"] [:p "🐣 Anfängererfahrungen"] [:p "🔥 Scala vs. Clojure"]] [:div.col-6 [:p "Wir suchen noch Speaker!"] [:p "Sprecht uns einfach an, wir coachen auch Newcomer 🚀"] [:p "Jeder Talk dauert ca. 10 Minuten"]]])) (def slide-2 (section-with-title "Clojure ist..." [:p "funktional"] [:p "dynamisch typisiert"] [:p "auf der JVM gehostet"] [:p "ein Lisp-Dialekt"])) (def slide-history (section-with-title "Geschichte von Clojure" [:div.row [:div.col-4 [:img {:alt "", :src "img/clojure_logo.svg"}]] [:div.col-8 [:p "Öffentliches Release: Okt. 2007"] [:p "Aktuelle Version 1.10.1"] [:p "Extrem seriöse Entwicklung"] [:p "Nicht \"der neuste heiße Scheiß\" "] [:p.highlight "Trotzdem nicht langweilig"]]])) (def slide-usage (section-with-title "Wo wird Clojure eingesetzt?" [:p "web development (81%)"] [:p "open source (48%)"] [:p "building and delivering commercial services (31%)"] [:small [:small [:a {:href "https://clojure.org/news/2019/02/04/state-of-clojure-2019"} "Source: Clojure Developer Survey 2019"]]])) (def slide-repl (section-with-title "To the REPL!" [:pre [:code ";; Die REPL – ein mächtiges Werkzeug (loop (print (eval (read)))) ^ ^ ^ ^ └─────└──────└─────└───── *REPL*"]])) (def slide-links (section-with-title "Aufgaben" [:p "Hier geht's weiter:" [:br] [:img {:src "img/github.svg" :style "height: 1em; vertical-align: middle; padding-right: .25em"}] [:a {:href "https://github.com/clojuredus/fizzbuzz-einsteiger"} "clojuredus/fizzbuzz-einsteiger"]] [:p "Code aus diesem Talk:" [:br] [:img {:src "img/github.svg" :style "height: 1em; vertical-align: middle; padding-right: .25em"}] [:a {:href "https://github.com/n2o/2020-clojure-von-null-zu-fizzbuzz-talk"} "n2o/2020-clojure-von-null-zu-fizzbuzz-talk"]] [:p "Aufzeichnung dieses Talks:" [:br] [:img {:src "img/youtube.svg" :style "height: 2em; vertical-align: middle;"}] [:a {:href "https://youtu.be/1nprvnKYXr4"} "November 2019"]])) (defn all "Add here all slides you want to see in your presentation." [] [slide-1 slide-clojuredus slide-next slide-2 slide-history slide-usage slide-repl slide-links])
93887
(ns reveal.slides (:require [clojure.string :as string])) (defn- section-with-title [title & htmls] (let [slugged (string/replace title #"\W" "")] [:section {:data-state slugged} [:style (str "." slugged " header span:after {content: \"" title "\";}")] htmls])) ;; ---------------------------------------------------------------------------- (def slide-1 [:section {:data-state "footer"} [:div#title [:h3 [:img {:style "height: 3em;" :src "img/clojure_logo.svg"}] [:br] "Clojure: Von Null zu FizzBuzz"] [:hr] [:p {:style "font-size: 0.8em"} [:strong "<NAME>"]] [:small "Institut für Informatik" [:br] "Heinrich-Heine-Universität Düsseldorf" [:br] "19.02.2020" [:br] [:br] "<EMAIL>" [:br] "@cmeter_ / @clojure_dus"]]]) (def slide-clojuredus (section-with-title "Wer sind wir?" [:img {:src "img/logo2019.svg"}] [:p [:a {:href "http://clojure-duesseldorf.de"} "clojure-duesseldorf.de"]])) (def slide-next (section-with-title "Was kommt als nächstes?" [:p [:strong "Lightning Talks"] [:br] "am 26.03.2020"] [:div.row [:div.col-6 [:p "Themenideen:"] [:p "👩‍🏫 Data-Science in Clojure"] [:p "🕵️‍♂️ Statische Codeanalyse"] [:p "🐣 Anfängererfahrungen"] [:p "🔥 Scala vs. Clojure"]] [:div.col-6 [:p "Wir suchen noch Speaker!"] [:p "Sprecht uns einfach an, wir coachen auch Newcomer 🚀"] [:p "Jeder Talk dauert ca. 10 Minuten"]]])) (def slide-2 (section-with-title "Clojure ist..." [:p "funktional"] [:p "dynamisch typisiert"] [:p "auf der JVM gehostet"] [:p "ein Lisp-Dialekt"])) (def slide-history (section-with-title "Geschichte von Clojure" [:div.row [:div.col-4 [:img {:alt "", :src "img/clojure_logo.svg"}]] [:div.col-8 [:p "Öffentliches Release: Okt. 2007"] [:p "Aktuelle Version 1.10.1"] [:p "Extrem seriöse Entwicklung"] [:p "Nicht \"der neuste heiße Scheiß\" "] [:p.highlight "Trotzdem nicht langweilig"]]])) (def slide-usage (section-with-title "Wo wird Clojure eingesetzt?" [:p "web development (81%)"] [:p "open source (48%)"] [:p "building and delivering commercial services (31%)"] [:small [:small [:a {:href "https://clojure.org/news/2019/02/04/state-of-clojure-2019"} "Source: Clojure Developer Survey 2019"]]])) (def slide-repl (section-with-title "To the REPL!" [:pre [:code ";; Die REPL – ein mächtiges Werkzeug (loop (print (eval (read)))) ^ ^ ^ ^ └─────└──────└─────└───── *REPL*"]])) (def slide-links (section-with-title "Aufgaben" [:p "Hier geht's weiter:" [:br] [:img {:src "img/github.svg" :style "height: 1em; vertical-align: middle; padding-right: .25em"}] [:a {:href "https://github.com/clojuredus/fizzbuzz-einsteiger"} "clojuredus/fizzbuzz-einsteiger"]] [:p "Code aus diesem Talk:" [:br] [:img {:src "img/github.svg" :style "height: 1em; vertical-align: middle; padding-right: .25em"}] [:a {:href "https://github.com/n2o/2020-clojure-von-null-zu-fizzbuzz-talk"} "n2o/2020-clojure-von-null-zu-fizzbuzz-talk"]] [:p "Aufzeichnung dieses Talks:" [:br] [:img {:src "img/youtube.svg" :style "height: 2em; vertical-align: middle;"}] [:a {:href "https://youtu.be/1nprvnKYXr4"} "November 2019"]])) (defn all "Add here all slides you want to see in your presentation." [] [slide-1 slide-clojuredus slide-next slide-2 slide-history slide-usage slide-repl slide-links])
true
(ns reveal.slides (:require [clojure.string :as string])) (defn- section-with-title [title & htmls] (let [slugged (string/replace title #"\W" "")] [:section {:data-state slugged} [:style (str "." slugged " header span:after {content: \"" title "\";}")] htmls])) ;; ---------------------------------------------------------------------------- (def slide-1 [:section {:data-state "footer"} [:div#title [:h3 [:img {:style "height: 3em;" :src "img/clojure_logo.svg"}] [:br] "Clojure: Von Null zu FizzBuzz"] [:hr] [:p {:style "font-size: 0.8em"} [:strong "PI:NAME:<NAME>END_PI"]] [:small "Institut für Informatik" [:br] "Heinrich-Heine-Universität Düsseldorf" [:br] "19.02.2020" [:br] [:br] "PI:EMAIL:<EMAIL>END_PI" [:br] "@cmeter_ / @clojure_dus"]]]) (def slide-clojuredus (section-with-title "Wer sind wir?" [:img {:src "img/logo2019.svg"}] [:p [:a {:href "http://clojure-duesseldorf.de"} "clojure-duesseldorf.de"]])) (def slide-next (section-with-title "Was kommt als nächstes?" [:p [:strong "Lightning Talks"] [:br] "am 26.03.2020"] [:div.row [:div.col-6 [:p "Themenideen:"] [:p "👩‍🏫 Data-Science in Clojure"] [:p "🕵️‍♂️ Statische Codeanalyse"] [:p "🐣 Anfängererfahrungen"] [:p "🔥 Scala vs. Clojure"]] [:div.col-6 [:p "Wir suchen noch Speaker!"] [:p "Sprecht uns einfach an, wir coachen auch Newcomer 🚀"] [:p "Jeder Talk dauert ca. 10 Minuten"]]])) (def slide-2 (section-with-title "Clojure ist..." [:p "funktional"] [:p "dynamisch typisiert"] [:p "auf der JVM gehostet"] [:p "ein Lisp-Dialekt"])) (def slide-history (section-with-title "Geschichte von Clojure" [:div.row [:div.col-4 [:img {:alt "", :src "img/clojure_logo.svg"}]] [:div.col-8 [:p "Öffentliches Release: Okt. 2007"] [:p "Aktuelle Version 1.10.1"] [:p "Extrem seriöse Entwicklung"] [:p "Nicht \"der neuste heiße Scheiß\" "] [:p.highlight "Trotzdem nicht langweilig"]]])) (def slide-usage (section-with-title "Wo wird Clojure eingesetzt?" [:p "web development (81%)"] [:p "open source (48%)"] [:p "building and delivering commercial services (31%)"] [:small [:small [:a {:href "https://clojure.org/news/2019/02/04/state-of-clojure-2019"} "Source: Clojure Developer Survey 2019"]]])) (def slide-repl (section-with-title "To the REPL!" [:pre [:code ";; Die REPL – ein mächtiges Werkzeug (loop (print (eval (read)))) ^ ^ ^ ^ └─────└──────└─────└───── *REPL*"]])) (def slide-links (section-with-title "Aufgaben" [:p "Hier geht's weiter:" [:br] [:img {:src "img/github.svg" :style "height: 1em; vertical-align: middle; padding-right: .25em"}] [:a {:href "https://github.com/clojuredus/fizzbuzz-einsteiger"} "clojuredus/fizzbuzz-einsteiger"]] [:p "Code aus diesem Talk:" [:br] [:img {:src "img/github.svg" :style "height: 1em; vertical-align: middle; padding-right: .25em"}] [:a {:href "https://github.com/n2o/2020-clojure-von-null-zu-fizzbuzz-talk"} "n2o/2020-clojure-von-null-zu-fizzbuzz-talk"]] [:p "Aufzeichnung dieses Talks:" [:br] [:img {:src "img/youtube.svg" :style "height: 2em; vertical-align: middle;"}] [:a {:href "https://youtu.be/1nprvnKYXr4"} "November 2019"]])) (defn all "Add here all slides you want to see in your presentation." [] [slide-1 slide-clojuredus slide-next slide-2 slide-history slide-usage slide-repl slide-links])
[ { "context": "ourtion.Pattern04.person)\n\n(def p\n {:first-name \"John\"\n :middle-name \"Quincy\"\n :last-name \"Adams\"})", "end": 63, "score": 0.9998433589935303, "start": 59, "tag": "NAME", "value": "John" }, { "context": "n)\n\n(def p\n {:first-name \"John\"\n :middle-name \"Quincy\"\n :last-name \"Adams\"})\n\n(defrecord Cat [color n", "end": 88, "score": 0.9996490478515625, "start": 82, "tag": "NAME", "value": "Quincy" }, { "context": "me \"John\"\n :middle-name \"Quincy\"\n :last-name \"Adams\"})\n\n(defrecord Cat [color name])\n\n(defrecord Dog ", "end": 110, "score": 0.9996634125709534, "start": 105, "tag": "NAME", "value": "Adams" } ]
Clojure/src/com/yourtion/Pattern04/person.clj
yourtion/LearningFunctionalProgramming
14
(ns com.yourtion.Pattern04.person) (def p {:first-name "John" :middle-name "Quincy" :last-name "Adams"}) (defrecord Cat [color name]) (defrecord Dog [color name]) (defprotocol NoiseMaker (make-noise [this])) (defrecord NoisyCat [color name] NoiseMaker (make-noise [this] (str (:name this) " meows!"))) (defrecord NoisyDog [color name] NoiseMaker (make-noise [this] (str (:name this) " barks!"))) (def cat1 (Cat. "Calico" "Fuzzy McBootings")) (def dog1 (Dog. "Brown" "Brown Dog")) (def noisy-cat (NoisyCat. "Calico" "Fuzzy McBootings")) (def noisy-dog (NoisyDog. "Brown" "Brown Dog")) (defn run [] (println "# use map") (println (p :first-name) (p :middle-name) (p :last-name)) (println "Upper: " (into {} (for [[k, v] p] [k (.toUpperCase v)]))) (println) (println "# use record") (println "cat: " (:name cat1)) (println "dog: " (:name dog1)) (println "noisy-cat: " (:name noisy-cat)) (println "noisy-dog: " (:name noisy-dog)) (println (make-noise noisy-cat)) (println (make-noise noisy-dog)) )
48061
(ns com.yourtion.Pattern04.person) (def p {:first-name "<NAME>" :middle-name "<NAME>" :last-name "<NAME>"}) (defrecord Cat [color name]) (defrecord Dog [color name]) (defprotocol NoiseMaker (make-noise [this])) (defrecord NoisyCat [color name] NoiseMaker (make-noise [this] (str (:name this) " meows!"))) (defrecord NoisyDog [color name] NoiseMaker (make-noise [this] (str (:name this) " barks!"))) (def cat1 (Cat. "Calico" "Fuzzy McBootings")) (def dog1 (Dog. "Brown" "Brown Dog")) (def noisy-cat (NoisyCat. "Calico" "Fuzzy McBootings")) (def noisy-dog (NoisyDog. "Brown" "Brown Dog")) (defn run [] (println "# use map") (println (p :first-name) (p :middle-name) (p :last-name)) (println "Upper: " (into {} (for [[k, v] p] [k (.toUpperCase v)]))) (println) (println "# use record") (println "cat: " (:name cat1)) (println "dog: " (:name dog1)) (println "noisy-cat: " (:name noisy-cat)) (println "noisy-dog: " (:name noisy-dog)) (println (make-noise noisy-cat)) (println (make-noise noisy-dog)) )
true
(ns com.yourtion.Pattern04.person) (def p {:first-name "PI:NAME:<NAME>END_PI" :middle-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}) (defrecord Cat [color name]) (defrecord Dog [color name]) (defprotocol NoiseMaker (make-noise [this])) (defrecord NoisyCat [color name] NoiseMaker (make-noise [this] (str (:name this) " meows!"))) (defrecord NoisyDog [color name] NoiseMaker (make-noise [this] (str (:name this) " barks!"))) (def cat1 (Cat. "Calico" "Fuzzy McBootings")) (def dog1 (Dog. "Brown" "Brown Dog")) (def noisy-cat (NoisyCat. "Calico" "Fuzzy McBootings")) (def noisy-dog (NoisyDog. "Brown" "Brown Dog")) (defn run [] (println "# use map") (println (p :first-name) (p :middle-name) (p :last-name)) (println "Upper: " (into {} (for [[k, v] p] [k (.toUpperCase v)]))) (println) (println "# use record") (println "cat: " (:name cat1)) (println "dog: " (:name dog1)) (println "noisy-cat: " (:name noisy-cat)) (println "noisy-dog: " (:name noisy-dog)) (println (make-noise noisy-cat)) (println (make-noise noisy-dog)) )
[ { "context": "ty functions for feature creation\"\n :author \"Paul Landes\"}\n zensols.nlparse.feature.util\n (:require [c", "end": 78, "score": 0.9998821020126343, "start": 67, "tag": "NAME", "value": "Paul Landes" } ]
src/clojure/zensols/nlparse/feature/util.clj
plandes/cli-nlp-feature
2
(ns ^{:doc "Utility functions for feature creation" :author "Paul Landes"} zensols.nlparse.feature.util (:require [clojure.tools.logging :as log] [clojure.string :as s])) (def none-label "Value used for missing features." "<none>") (def beginning-of-sentence-label "Beginning of sentence marker." "<bos>") (def end-of-sentence-label "End of sentence marker." "<eos>") ;; util (defn upper-case? [text] (= (count text) (count (take-while #(Character/isUpperCase %) text)))) (defn lc-null "Return the lower case version of a string or nil if nil given." [str] (if str (s/lower-case str))) (defn or-none "Return **str** if non-`nil` or otherwise the sepcial [[none-label]]." [str] (or str none-label)) (defn or-0 "Call and return the value given by **val-fn** iff **check** is non-`nil`, otherwise return 0." ([val] (or val 0)) ([check val-fn] (if check (val-fn check) 0))) (defn ratio-0-if-empty "Return a ratio or 0 if **b** is 0 to guard against divide by zero." [a b] (if (= 0 b) 0 (/ a b))) (defn ratio-neg-if-empty "Return a ratio or -1 if **b** is 0 to guard against divide by zero." [a b] (if (= 0 b) -1 (/ a b))) (defn ratio-true "Return the ratio of **items** whose evaluation of **true-fn** is `true`. If **items** is empty return 0." [items true-fn] (let [cnt (count items)] (if (= cnt 0) 0 (/ (->> items (map true-fn) (filter true?) count) cnt)))) (defn or-empty-0 "If sequence **seq** is non-empty, apply **afn** to seq. Otherwise return 0." [seq afn] (if (or (not seq) (empty? seq) (nil? (first seq))) 0 (afn seq)))
22956
(ns ^{:doc "Utility functions for feature creation" :author "<NAME>"} zensols.nlparse.feature.util (:require [clojure.tools.logging :as log] [clojure.string :as s])) (def none-label "Value used for missing features." "<none>") (def beginning-of-sentence-label "Beginning of sentence marker." "<bos>") (def end-of-sentence-label "End of sentence marker." "<eos>") ;; util (defn upper-case? [text] (= (count text) (count (take-while #(Character/isUpperCase %) text)))) (defn lc-null "Return the lower case version of a string or nil if nil given." [str] (if str (s/lower-case str))) (defn or-none "Return **str** if non-`nil` or otherwise the sepcial [[none-label]]." [str] (or str none-label)) (defn or-0 "Call and return the value given by **val-fn** iff **check** is non-`nil`, otherwise return 0." ([val] (or val 0)) ([check val-fn] (if check (val-fn check) 0))) (defn ratio-0-if-empty "Return a ratio or 0 if **b** is 0 to guard against divide by zero." [a b] (if (= 0 b) 0 (/ a b))) (defn ratio-neg-if-empty "Return a ratio or -1 if **b** is 0 to guard against divide by zero." [a b] (if (= 0 b) -1 (/ a b))) (defn ratio-true "Return the ratio of **items** whose evaluation of **true-fn** is `true`. If **items** is empty return 0." [items true-fn] (let [cnt (count items)] (if (= cnt 0) 0 (/ (->> items (map true-fn) (filter true?) count) cnt)))) (defn or-empty-0 "If sequence **seq** is non-empty, apply **afn** to seq. Otherwise return 0." [seq afn] (if (or (not seq) (empty? seq) (nil? (first seq))) 0 (afn seq)))
true
(ns ^{:doc "Utility functions for feature creation" :author "PI:NAME:<NAME>END_PI"} zensols.nlparse.feature.util (:require [clojure.tools.logging :as log] [clojure.string :as s])) (def none-label "Value used for missing features." "<none>") (def beginning-of-sentence-label "Beginning of sentence marker." "<bos>") (def end-of-sentence-label "End of sentence marker." "<eos>") ;; util (defn upper-case? [text] (= (count text) (count (take-while #(Character/isUpperCase %) text)))) (defn lc-null "Return the lower case version of a string or nil if nil given." [str] (if str (s/lower-case str))) (defn or-none "Return **str** if non-`nil` or otherwise the sepcial [[none-label]]." [str] (or str none-label)) (defn or-0 "Call and return the value given by **val-fn** iff **check** is non-`nil`, otherwise return 0." ([val] (or val 0)) ([check val-fn] (if check (val-fn check) 0))) (defn ratio-0-if-empty "Return a ratio or 0 if **b** is 0 to guard against divide by zero." [a b] (if (= 0 b) 0 (/ a b))) (defn ratio-neg-if-empty "Return a ratio or -1 if **b** is 0 to guard against divide by zero." [a b] (if (= 0 b) -1 (/ a b))) (defn ratio-true "Return the ratio of **items** whose evaluation of **true-fn** is `true`. If **items** is empty return 0." [items true-fn] (let [cnt (count items)] (if (= cnt 0) 0 (/ (->> items (map true-fn) (filter true?) count) cnt)))) (defn or-empty-0 "If sequence **seq** is non-empty, apply **afn** to seq. Otherwise return 0." [seq afn] (if (or (not seq) (empty? seq) (nil? (first seq))) 0 (afn seq)))
[ { "context": "java.io :as io]))\n\n(def example-posts [{:author \"Jochen\"\n :title \"First post\"\n ", "end": 209, "score": 0.9027016758918762, "start": 203, "tag": "NAME", "value": "Jochen" }, { "context": "mmodo consequat.\"}\n {:author \"Shawn\"\n :title \"Second post\"\n ", "end": 556, "score": 0.9716867208480835, "start": 551, "tag": "NAME", "value": "Shawn" } ]
src/clj/meetup/templating.clj
jocrau/clojure-meetup
7
(ns meetup.templating (:require [hiccup.core :as hiccup] [net.cgrand.enlive-html :as enlive] [clostache.parser :as clostache] [clojure.java.io :as io])) (def example-posts [{:author "Jochen" :title "First post" :content "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."} {:author "Shawn" :title "Second post" :content "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."}]) ;; Hiccup (defn render-blog-hiccup [title posts] (hiccup/html [:html [:head [:title title]] [:body [:h1 title] (for [post posts] [:article [:h2 (:title post)] [:p (str "By " (:author post))] [:p (:content post)]])]])) (render-blog-hiccup "My Blog with Hiccup" example-posts) ;; Enlive (defn render-blog-enlive [title posts] (let [post-snippet (enlive/snippet "templates/blog-enlive.html" [:article] [post] [:header :h1] (enlive/content (:title post)) [:header :.author] (enlive/content (:author post)) [:article :> :p] (enlive/content (:content post))) blog-template (enlive/template "templates/blog-enlive.html" [title posts] [:title] (enlive/content title) [:article] (enlive/substitute (map post-snippet posts)))] (reduce str (blog-template title posts)))) (render-blog-enlive "My Blog with Enlive" example-posts) ;; Clostache (defn render-blog-clostache [title posts] (let [blog-template (slurp (io/resource "templates/blog-clostache.html"))] (clostache/render blog-template {:blog-title title :posts posts}))) (render-blog-clostache "My Blog with Clostache" example-posts)
48283
(ns meetup.templating (:require [hiccup.core :as hiccup] [net.cgrand.enlive-html :as enlive] [clostache.parser :as clostache] [clojure.java.io :as io])) (def example-posts [{:author "<NAME>" :title "First post" :content "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."} {:author "<NAME>" :title "Second post" :content "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."}]) ;; Hiccup (defn render-blog-hiccup [title posts] (hiccup/html [:html [:head [:title title]] [:body [:h1 title] (for [post posts] [:article [:h2 (:title post)] [:p (str "By " (:author post))] [:p (:content post)]])]])) (render-blog-hiccup "My Blog with Hiccup" example-posts) ;; Enlive (defn render-blog-enlive [title posts] (let [post-snippet (enlive/snippet "templates/blog-enlive.html" [:article] [post] [:header :h1] (enlive/content (:title post)) [:header :.author] (enlive/content (:author post)) [:article :> :p] (enlive/content (:content post))) blog-template (enlive/template "templates/blog-enlive.html" [title posts] [:title] (enlive/content title) [:article] (enlive/substitute (map post-snippet posts)))] (reduce str (blog-template title posts)))) (render-blog-enlive "My Blog with Enlive" example-posts) ;; Clostache (defn render-blog-clostache [title posts] (let [blog-template (slurp (io/resource "templates/blog-clostache.html"))] (clostache/render blog-template {:blog-title title :posts posts}))) (render-blog-clostache "My Blog with Clostache" example-posts)
true
(ns meetup.templating (:require [hiccup.core :as hiccup] [net.cgrand.enlive-html :as enlive] [clostache.parser :as clostache] [clojure.java.io :as io])) (def example-posts [{:author "PI:NAME:<NAME>END_PI" :title "First post" :content "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."} {:author "PI:NAME:<NAME>END_PI" :title "Second post" :content "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."}]) ;; Hiccup (defn render-blog-hiccup [title posts] (hiccup/html [:html [:head [:title title]] [:body [:h1 title] (for [post posts] [:article [:h2 (:title post)] [:p (str "By " (:author post))] [:p (:content post)]])]])) (render-blog-hiccup "My Blog with Hiccup" example-posts) ;; Enlive (defn render-blog-enlive [title posts] (let [post-snippet (enlive/snippet "templates/blog-enlive.html" [:article] [post] [:header :h1] (enlive/content (:title post)) [:header :.author] (enlive/content (:author post)) [:article :> :p] (enlive/content (:content post))) blog-template (enlive/template "templates/blog-enlive.html" [title posts] [:title] (enlive/content title) [:article] (enlive/substitute (map post-snippet posts)))] (reduce str (blog-template title posts)))) (render-blog-enlive "My Blog with Enlive" example-posts) ;; Clostache (defn render-blog-clostache [title posts] (let [blog-template (slurp (io/resource "templates/blog-clostache.html"))] (clostache/render blog-template {:blog-title title :posts posts}))) (render-blog-clostache "My Blog with Clostache" example-posts)
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 30, "score": 0.9998260140419006, "start": 19, "tag": "NAME", "value": "Rich Hickey" }, { "context": "ice, or any other, from this software.\n;\n;\tAuthor: David Miller\n\n; Test of new interop code\n;\n; Place this file i", "end": 488, "score": 0.9997653365135193, "start": 476, "tag": "NAME", "value": "David Miller" } ]
Neptune/bin/Debug/clojure/samples/interop/testinterop.clj
yasir2000/Neptune-
2
; 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: David Miller ; Test of new interop code ; ; Place this file in the clojure subdirectory of your main directory. ; Compile the file C.cs via: csc /t:library C.cs ; Place C.dll in your root directory. ; Start Clojure and do: ; (System.Reflection.Assembly/LoadFrom "C.dll") ; (compile 'clojure.testinterop ') ; ; You should then be able to play games such as: ; (ns clojure.testinterop) ; Create some instances (def c1 (dm.interop.C1.)) (def c2 (dm.interop.C2.)) (def c3 (dm.interop.C3.)) (def c4 (dm.interop.C4.)) ; Test the instance field/property/method() (defn f1 [c] (.m1 c)) ; (f1 c1) => 11 ; accesses field ; (f1 c2) => 21 ; accesses property ; (f1 c3) => 31 ; acccesses zero-arity method ; (f1 c4) => throws ; Test the static field/property/method() (defn f1s [] (+ (dm.interop.C1/m1s) (dm.interop.C2/m1s) (dm.interop.C3/m1s))) ; Test overload resolving (defn f2none [c] (.m2 c)) ; (f2none c1) => writes something appropriate. ; Really test overload resolving (defn f2one [c x] (.m2 c x)) ; (f2one c1 7) ; (f2one c1 7.1) ; (f2one c1 "whatever") ; (f2one c1 '(a b c)) (defn f2two [c x y] (.m2 c x y)) ; (f2two c1 "Here it is: {0}" 12) ; (f2two c23 "Here it is: {0}" 12) ; Test by-ref, resolved at compile-time (defn f3c [c n] (let [m (int n)] (.m3 ^dm.interop.C1 c (by-ref m)) m)) ; Test by-ref, resolved at runtime (defn f3r [c n] (let [m (int n)] (.m3 c (by-ref m)) m)) ; Make sure we find the non-by-ref overload (defn f3n [c n] (let [m (int n)] (.m3 c m))) ; (f3c c1 12) => 13 ; (f3r c1 12) => 13 ; (f3n c1 12) => 12 ; Testing some ambiguity with refs (defn f5 [c x y] (let [m (int y) v (.m5 c x (by-ref m))] [v m])) ; (f5 c1 "help" 12) => ["help22" 22] ; (f5 c1 15 20) => [135 120] ; Try the following to test c-tor overloads ; (dm.interop.C5.) ; (dm.interop.C5. 7) ; (dm.interop.C5. "thing") ; (let [x (int 12)] (dm.interop.C5. (by-ref x)) x) ; ; Test dynamic overload resolution (defn make5 [x] (dm.interop.C5. x)) ; Test overload resolution with ref param (defn make5a [x y] (let [n (int y) v (dm.interop.C5. x (by-ref n))] [v n])) ; (make5a "help" 12) => [#<C5 Constructed with String+int-by-ref c-tor> 32] ; (make5a 20 30) => [#<C5 Constructed with int+int-by-ref c-tor> 60] (defn f6 [c a] [(.m6 c (by-ref a)) a]) ; (f6 c1 12) => [ "123" 123 ] NOPE ; (f6 c1 "def") => [ "defabc" "defab" ] NOPE (defn c6sm1a [x ys] (dm.interop.C6/sm1 x ^objects (into-array Object ys))) ; (c6sm1a 12 [ 1 2 3] ) => 15 (defn c6sm1b [x ys] (dm.interop.C6/sm1 x ^"System.String[]" (into-array String ys))) ; (c6sm1b 12 ["abc" "de" "f"]) => 18 (def c6 (dm.interop.C6.)) (defn c6m1a [c x ys] (.m1 c x ^objects (into-array Object ys))) ; (c6m1a c6 12 [ 1 2 3] ) => 15 (defn c6m1b [c x ys] (.m1 c x ^"System.String[]" (into-array String ys))) ; (c6m1b c6 12 ["abc" "de" "f"]) => 18 (defn c6m2 [x] (let [n (int x) v (dm.interop.C6/m2 (by-ref n) ^objects (into-array Object [1 2 3 4]))] [n v])) ; (c6m2 12) => [16 4]
82198
; 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> ; Test of new interop code ; ; Place this file in the clojure subdirectory of your main directory. ; Compile the file C.cs via: csc /t:library C.cs ; Place C.dll in your root directory. ; Start Clojure and do: ; (System.Reflection.Assembly/LoadFrom "C.dll") ; (compile 'clojure.testinterop ') ; ; You should then be able to play games such as: ; (ns clojure.testinterop) ; Create some instances (def c1 (dm.interop.C1.)) (def c2 (dm.interop.C2.)) (def c3 (dm.interop.C3.)) (def c4 (dm.interop.C4.)) ; Test the instance field/property/method() (defn f1 [c] (.m1 c)) ; (f1 c1) => 11 ; accesses field ; (f1 c2) => 21 ; accesses property ; (f1 c3) => 31 ; acccesses zero-arity method ; (f1 c4) => throws ; Test the static field/property/method() (defn f1s [] (+ (dm.interop.C1/m1s) (dm.interop.C2/m1s) (dm.interop.C3/m1s))) ; Test overload resolving (defn f2none [c] (.m2 c)) ; (f2none c1) => writes something appropriate. ; Really test overload resolving (defn f2one [c x] (.m2 c x)) ; (f2one c1 7) ; (f2one c1 7.1) ; (f2one c1 "whatever") ; (f2one c1 '(a b c)) (defn f2two [c x y] (.m2 c x y)) ; (f2two c1 "Here it is: {0}" 12) ; (f2two c23 "Here it is: {0}" 12) ; Test by-ref, resolved at compile-time (defn f3c [c n] (let [m (int n)] (.m3 ^dm.interop.C1 c (by-ref m)) m)) ; Test by-ref, resolved at runtime (defn f3r [c n] (let [m (int n)] (.m3 c (by-ref m)) m)) ; Make sure we find the non-by-ref overload (defn f3n [c n] (let [m (int n)] (.m3 c m))) ; (f3c c1 12) => 13 ; (f3r c1 12) => 13 ; (f3n c1 12) => 12 ; Testing some ambiguity with refs (defn f5 [c x y] (let [m (int y) v (.m5 c x (by-ref m))] [v m])) ; (f5 c1 "help" 12) => ["help22" 22] ; (f5 c1 15 20) => [135 120] ; Try the following to test c-tor overloads ; (dm.interop.C5.) ; (dm.interop.C5. 7) ; (dm.interop.C5. "thing") ; (let [x (int 12)] (dm.interop.C5. (by-ref x)) x) ; ; Test dynamic overload resolution (defn make5 [x] (dm.interop.C5. x)) ; Test overload resolution with ref param (defn make5a [x y] (let [n (int y) v (dm.interop.C5. x (by-ref n))] [v n])) ; (make5a "help" 12) => [#<C5 Constructed with String+int-by-ref c-tor> 32] ; (make5a 20 30) => [#<C5 Constructed with int+int-by-ref c-tor> 60] (defn f6 [c a] [(.m6 c (by-ref a)) a]) ; (f6 c1 12) => [ "123" 123 ] NOPE ; (f6 c1 "def") => [ "defabc" "defab" ] NOPE (defn c6sm1a [x ys] (dm.interop.C6/sm1 x ^objects (into-array Object ys))) ; (c6sm1a 12 [ 1 2 3] ) => 15 (defn c6sm1b [x ys] (dm.interop.C6/sm1 x ^"System.String[]" (into-array String ys))) ; (c6sm1b 12 ["abc" "de" "f"]) => 18 (def c6 (dm.interop.C6.)) (defn c6m1a [c x ys] (.m1 c x ^objects (into-array Object ys))) ; (c6m1a c6 12 [ 1 2 3] ) => 15 (defn c6m1b [c x ys] (.m1 c x ^"System.String[]" (into-array String ys))) ; (c6m1b c6 12 ["abc" "de" "f"]) => 18 (defn c6m2 [x] (let [n (int x) v (dm.interop.C6/m2 (by-ref n) ^objects (into-array Object [1 2 3 4]))] [n v])) ; (c6m2 12) => [16 4]
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; ; Author: PI:NAME:<NAME>END_PI ; Test of new interop code ; ; Place this file in the clojure subdirectory of your main directory. ; Compile the file C.cs via: csc /t:library C.cs ; Place C.dll in your root directory. ; Start Clojure and do: ; (System.Reflection.Assembly/LoadFrom "C.dll") ; (compile 'clojure.testinterop ') ; ; You should then be able to play games such as: ; (ns clojure.testinterop) ; Create some instances (def c1 (dm.interop.C1.)) (def c2 (dm.interop.C2.)) (def c3 (dm.interop.C3.)) (def c4 (dm.interop.C4.)) ; Test the instance field/property/method() (defn f1 [c] (.m1 c)) ; (f1 c1) => 11 ; accesses field ; (f1 c2) => 21 ; accesses property ; (f1 c3) => 31 ; acccesses zero-arity method ; (f1 c4) => throws ; Test the static field/property/method() (defn f1s [] (+ (dm.interop.C1/m1s) (dm.interop.C2/m1s) (dm.interop.C3/m1s))) ; Test overload resolving (defn f2none [c] (.m2 c)) ; (f2none c1) => writes something appropriate. ; Really test overload resolving (defn f2one [c x] (.m2 c x)) ; (f2one c1 7) ; (f2one c1 7.1) ; (f2one c1 "whatever") ; (f2one c1 '(a b c)) (defn f2two [c x y] (.m2 c x y)) ; (f2two c1 "Here it is: {0}" 12) ; (f2two c23 "Here it is: {0}" 12) ; Test by-ref, resolved at compile-time (defn f3c [c n] (let [m (int n)] (.m3 ^dm.interop.C1 c (by-ref m)) m)) ; Test by-ref, resolved at runtime (defn f3r [c n] (let [m (int n)] (.m3 c (by-ref m)) m)) ; Make sure we find the non-by-ref overload (defn f3n [c n] (let [m (int n)] (.m3 c m))) ; (f3c c1 12) => 13 ; (f3r c1 12) => 13 ; (f3n c1 12) => 12 ; Testing some ambiguity with refs (defn f5 [c x y] (let [m (int y) v (.m5 c x (by-ref m))] [v m])) ; (f5 c1 "help" 12) => ["help22" 22] ; (f5 c1 15 20) => [135 120] ; Try the following to test c-tor overloads ; (dm.interop.C5.) ; (dm.interop.C5. 7) ; (dm.interop.C5. "thing") ; (let [x (int 12)] (dm.interop.C5. (by-ref x)) x) ; ; Test dynamic overload resolution (defn make5 [x] (dm.interop.C5. x)) ; Test overload resolution with ref param (defn make5a [x y] (let [n (int y) v (dm.interop.C5. x (by-ref n))] [v n])) ; (make5a "help" 12) => [#<C5 Constructed with String+int-by-ref c-tor> 32] ; (make5a 20 30) => [#<C5 Constructed with int+int-by-ref c-tor> 60] (defn f6 [c a] [(.m6 c (by-ref a)) a]) ; (f6 c1 12) => [ "123" 123 ] NOPE ; (f6 c1 "def") => [ "defabc" "defab" ] NOPE (defn c6sm1a [x ys] (dm.interop.C6/sm1 x ^objects (into-array Object ys))) ; (c6sm1a 12 [ 1 2 3] ) => 15 (defn c6sm1b [x ys] (dm.interop.C6/sm1 x ^"System.String[]" (into-array String ys))) ; (c6sm1b 12 ["abc" "de" "f"]) => 18 (def c6 (dm.interop.C6.)) (defn c6m1a [c x ys] (.m1 c x ^objects (into-array Object ys))) ; (c6m1a c6 12 [ 1 2 3] ) => 15 (defn c6m1b [c x ys] (.m1 c x ^"System.String[]" (into-array String ys))) ; (c6m1b c6 12 ["abc" "de" "f"]) => 18 (defn c6m2 [x] (let [n (int x) v (dm.interop.C6/m2 (by-ref n) ^objects (into-array Object [1 2 3 4]))] [n v])) ; (c6m2 12) => [16 4]
[ { "context": "e: test/smiles_test.clj\n;;;\n;;; Copyright (c) 2010 Cyrus Harmon (ch-lisp@bobobeach.com) All rights\n;;; reserved.\n", "end": 70, "score": 0.999869704246521, "start": 58, "tag": "NAME", "value": "Cyrus Harmon" }, { "context": "test.clj\n;;;\n;;; Copyright (c) 2010 Cyrus Harmon (ch-lisp@bobobeach.com) All rights\n;;; reserved.\n;;;\n;;; Redistribution ", "end": 93, "score": 0.9999303817749023, "start": 72, "tag": "EMAIL", "value": "ch-lisp@bobobeach.com" } ]
test/smiles_test.clj
slyrus/chemiclj
1
;;; file: test/smiles_test.clj ;;; ;;; Copyright (c) 2010 Cyrus Harmon (ch-lisp@bobobeach.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: ;;; ;;; * 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 AUTHOR 'AS IS' AND ANY EXPRESSED ;;; 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. ;;; (require 'smiles-test) ;;; (in-ns 'smiles-test) (ns smiles-test (:use [chemiclj.core] [chemiclj.element] [chemiclj.smiles]) (:require [shortcut.graph :as graph])) (read-smiles-string "C") (read-smiles-string "CC") (read-smiles-string "C=C") (read-smiles-string "C1=CC1") (read-smiles-string "CC(C)CC") (read-smiles-string "C1CCC2CNCCC2C1") (read-smiles-string "CCC(C1=CC=CC=C1)=C(C2=CC=CC=C2)C3=CC=C(OCCN(C)C)C=C3") (read-smiles-string "CN1CCC23C4C1CC5=C2C(=C(C=C5)O)OC3C(C=C4)O") (read-smiles-string "CC12CCC3C(C1CCC2O)CCC4=C3C=CC(=C4)O") (def *molecules* (reduce (fn [acc [name smiles]] (into acc {name (name-molecule (read-smiles-string smiles) name)})) {} {"methane" "C" "ethane" "CC" "propane" "CCC" "butane" "CCCC" "pentane" "CCCCC" "hexane" "CCCCCC" "l-alanine" "C[C@@H](C(=O)O)N" "valine" "CC(C)C(C(=O)O)N" "paroxetine" "C1CNCC(C1C2=CC=C(C=C2)F)COC3=CC4=C(C=C3)OCO4" "tamoxifen" "CC/C(=C(\\C1=CC=CC=C1)/C2=CC=C(C=C2)OCCN(C)C)/C3=CC=CC=C3" "anastrozole" "CC(C)(C#N)C1=CC(=CC(=C1)CN2C=NC=N2)C(C)(C)C#N" "acetominophen" "CC(=O)NC1=CC=C(C=C1)O" "morphine" "CN1CCC23C4C1CC5=C2C(=C(C=C5)O)OC3C(C=C4)O" "estradiol" "CC12CCC3C(C1CCC2O)CCC4=C3C=CC(=C4)O" "dicyclohexyl" "C1CCCCC1C2CCCCC2" "spiro[5.5]undecane" "C12(CCCCC1)CCCCC2" "benzene" "c1ccccc1" "pyridine" "n1ccccc1" "tropone" "O=c1cccccc1" "indane" "c1ccc2CCCc2c1" "furan" "c1occc1" "fluoroform" "C(F)(F)F" "vanillin" "O=Cc1ccc(O)c(OC)c1" "thiamin" "OCCc1c(C)[n+](=cs1)Cc2cnc(C)nc(N)2" "oxytocin" "[H][C@]1(NC(=O)[C@H](Cc2ccc(O)cc2)NC(=O)[C@@H](N)CSSC[C@H](NC(=O)[C@H](CC(N)=O)NC(=O)[C@H](CCC(N)=O)NC1=O)C(=O)N1CCC[C@H]1C(=O)N[C@@H](CC(C)C)C(=O)NCC(N)=O)[C@@H](C)CC" "sildenafil" "CCCc1nn(C)c2c1nc([nH]c2=O)-c1cc(ccc1OCC)S(=O)(=O)N1CCN(C)CC1" "capsaicin" "COc1cc(CNC(=O)CCCC\\C=C\\C(C)C)ccc1O" "tricky" "[C@@]123[C@H](C(C=C3)(C)C)CC[C@@](C1)(CCC2)C" "6-amino-2-ethyl-5-(aminomethyl)-1-hexanol" "OCC(CC)CCC(CN)CN" "cubane" "C12C3C4C1C5C4C3C25" "cyclopropane" "C1CC1" "acetone" "CC(C)=O" "E-1,2-difluoroethane" "F/C=C/F" "Z-1,2-difluoroethane" "F\\C=C/F" "biphenyl" "c1ccccc1-c2ccccc2" ;; chiral ring-closing atom "chiral-cycle-test" "N1C[C@H]1C" ;; chiral ring-closing atom "chiral-cycle-test-2" "[H][C@]1(Br)CCC1" "serotonin" "NCCc1c[nH]c2ccc(O)cc12"})) (defn get-molecule [name] (get *molecules* name)) (read-smiles-string "C[C@](Br)(Cl)I") (read-smiles-string "C[C@H](Br)I") (read-smiles-string "N[C@](Br)(O)C") (read-smiles-string "N[C@@](Br)(C)O") ;;; these four should all yield the same molecule (assert (= (count (set (map mass [(read-smiles-string "C1=CC=CC=C1") (read-smiles-string "C1C=CC=CC=1") (read-smiles-string "C=1C=CC=CC1") (read-smiles-string "C=1C=CC=CC=1")]))) 1)) (assert (= (count (set (map #(read-smiles-string (write-smiles-string (read-smiles-string %))) ["C1=CC=CC=C1" "C1C=CC=CC=1" "C=1C=CC=CC1" "C=1C=CC=CC=1"]))) 1))
56666
;;; file: test/smiles_test.clj ;;; ;;; Copyright (c) 2010 <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 AUTHOR 'AS IS' AND ANY EXPRESSED ;;; 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. ;;; (require 'smiles-test) ;;; (in-ns 'smiles-test) (ns smiles-test (:use [chemiclj.core] [chemiclj.element] [chemiclj.smiles]) (:require [shortcut.graph :as graph])) (read-smiles-string "C") (read-smiles-string "CC") (read-smiles-string "C=C") (read-smiles-string "C1=CC1") (read-smiles-string "CC(C)CC") (read-smiles-string "C1CCC2CNCCC2C1") (read-smiles-string "CCC(C1=CC=CC=C1)=C(C2=CC=CC=C2)C3=CC=C(OCCN(C)C)C=C3") (read-smiles-string "CN1CCC23C4C1CC5=C2C(=C(C=C5)O)OC3C(C=C4)O") (read-smiles-string "CC12CCC3C(C1CCC2O)CCC4=C3C=CC(=C4)O") (def *molecules* (reduce (fn [acc [name smiles]] (into acc {name (name-molecule (read-smiles-string smiles) name)})) {} {"methane" "C" "ethane" "CC" "propane" "CCC" "butane" "CCCC" "pentane" "CCCCC" "hexane" "CCCCCC" "l-alanine" "C[C@@H](C(=O)O)N" "valine" "CC(C)C(C(=O)O)N" "paroxetine" "C1CNCC(C1C2=CC=C(C=C2)F)COC3=CC4=C(C=C3)OCO4" "tamoxifen" "CC/C(=C(\\C1=CC=CC=C1)/C2=CC=C(C=C2)OCCN(C)C)/C3=CC=CC=C3" "anastrozole" "CC(C)(C#N)C1=CC(=CC(=C1)CN2C=NC=N2)C(C)(C)C#N" "acetominophen" "CC(=O)NC1=CC=C(C=C1)O" "morphine" "CN1CCC23C4C1CC5=C2C(=C(C=C5)O)OC3C(C=C4)O" "estradiol" "CC12CCC3C(C1CCC2O)CCC4=C3C=CC(=C4)O" "dicyclohexyl" "C1CCCCC1C2CCCCC2" "spiro[5.5]undecane" "C12(CCCCC1)CCCCC2" "benzene" "c1ccccc1" "pyridine" "n1ccccc1" "tropone" "O=c1cccccc1" "indane" "c1ccc2CCCc2c1" "furan" "c1occc1" "fluoroform" "C(F)(F)F" "vanillin" "O=Cc1ccc(O)c(OC)c1" "thiamin" "OCCc1c(C)[n+](=cs1)Cc2cnc(C)nc(N)2" "oxytocin" "[H][C@]1(NC(=O)[C@H](Cc2ccc(O)cc2)NC(=O)[C@@H](N)CSSC[C@H](NC(=O)[C@H](CC(N)=O)NC(=O)[C@H](CCC(N)=O)NC1=O)C(=O)N1CCC[C@H]1C(=O)N[C@@H](CC(C)C)C(=O)NCC(N)=O)[C@@H](C)CC" "sildenafil" "CCCc1nn(C)c2c1nc([nH]c2=O)-c1cc(ccc1OCC)S(=O)(=O)N1CCN(C)CC1" "capsaicin" "COc1cc(CNC(=O)CCCC\\C=C\\C(C)C)ccc1O" "tricky" "[C@@]123[C@H](C(C=C3)(C)C)CC[C@@](C1)(CCC2)C" "6-amino-2-ethyl-5-(aminomethyl)-1-hexanol" "OCC(CC)CCC(CN)CN" "cubane" "C12C3C4C1C5C4C3C25" "cyclopropane" "C1CC1" "acetone" "CC(C)=O" "E-1,2-difluoroethane" "F/C=C/F" "Z-1,2-difluoroethane" "F\\C=C/F" "biphenyl" "c1ccccc1-c2ccccc2" ;; chiral ring-closing atom "chiral-cycle-test" "N1C[C@H]1C" ;; chiral ring-closing atom "chiral-cycle-test-2" "[H][C@]1(Br)CCC1" "serotonin" "NCCc1c[nH]c2ccc(O)cc12"})) (defn get-molecule [name] (get *molecules* name)) (read-smiles-string "C[C@](Br)(Cl)I") (read-smiles-string "C[C@H](Br)I") (read-smiles-string "N[C@](Br)(O)C") (read-smiles-string "N[C@@](Br)(C)O") ;;; these four should all yield the same molecule (assert (= (count (set (map mass [(read-smiles-string "C1=CC=CC=C1") (read-smiles-string "C1C=CC=CC=1") (read-smiles-string "C=1C=CC=CC1") (read-smiles-string "C=1C=CC=CC=1")]))) 1)) (assert (= (count (set (map #(read-smiles-string (write-smiles-string (read-smiles-string %))) ["C1=CC=CC=C1" "C1C=CC=CC=1" "C=1C=CC=CC1" "C=1C=CC=CC=1"]))) 1))
true
;;; file: test/smiles_test.clj ;;; ;;; Copyright (c) 2010 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 AUTHOR 'AS IS' AND ANY EXPRESSED ;;; 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. ;;; (require 'smiles-test) ;;; (in-ns 'smiles-test) (ns smiles-test (:use [chemiclj.core] [chemiclj.element] [chemiclj.smiles]) (:require [shortcut.graph :as graph])) (read-smiles-string "C") (read-smiles-string "CC") (read-smiles-string "C=C") (read-smiles-string "C1=CC1") (read-smiles-string "CC(C)CC") (read-smiles-string "C1CCC2CNCCC2C1") (read-smiles-string "CCC(C1=CC=CC=C1)=C(C2=CC=CC=C2)C3=CC=C(OCCN(C)C)C=C3") (read-smiles-string "CN1CCC23C4C1CC5=C2C(=C(C=C5)O)OC3C(C=C4)O") (read-smiles-string "CC12CCC3C(C1CCC2O)CCC4=C3C=CC(=C4)O") (def *molecules* (reduce (fn [acc [name smiles]] (into acc {name (name-molecule (read-smiles-string smiles) name)})) {} {"methane" "C" "ethane" "CC" "propane" "CCC" "butane" "CCCC" "pentane" "CCCCC" "hexane" "CCCCCC" "l-alanine" "C[C@@H](C(=O)O)N" "valine" "CC(C)C(C(=O)O)N" "paroxetine" "C1CNCC(C1C2=CC=C(C=C2)F)COC3=CC4=C(C=C3)OCO4" "tamoxifen" "CC/C(=C(\\C1=CC=CC=C1)/C2=CC=C(C=C2)OCCN(C)C)/C3=CC=CC=C3" "anastrozole" "CC(C)(C#N)C1=CC(=CC(=C1)CN2C=NC=N2)C(C)(C)C#N" "acetominophen" "CC(=O)NC1=CC=C(C=C1)O" "morphine" "CN1CCC23C4C1CC5=C2C(=C(C=C5)O)OC3C(C=C4)O" "estradiol" "CC12CCC3C(C1CCC2O)CCC4=C3C=CC(=C4)O" "dicyclohexyl" "C1CCCCC1C2CCCCC2" "spiro[5.5]undecane" "C12(CCCCC1)CCCCC2" "benzene" "c1ccccc1" "pyridine" "n1ccccc1" "tropone" "O=c1cccccc1" "indane" "c1ccc2CCCc2c1" "furan" "c1occc1" "fluoroform" "C(F)(F)F" "vanillin" "O=Cc1ccc(O)c(OC)c1" "thiamin" "OCCc1c(C)[n+](=cs1)Cc2cnc(C)nc(N)2" "oxytocin" "[H][C@]1(NC(=O)[C@H](Cc2ccc(O)cc2)NC(=O)[C@@H](N)CSSC[C@H](NC(=O)[C@H](CC(N)=O)NC(=O)[C@H](CCC(N)=O)NC1=O)C(=O)N1CCC[C@H]1C(=O)N[C@@H](CC(C)C)C(=O)NCC(N)=O)[C@@H](C)CC" "sildenafil" "CCCc1nn(C)c2c1nc([nH]c2=O)-c1cc(ccc1OCC)S(=O)(=O)N1CCN(C)CC1" "capsaicin" "COc1cc(CNC(=O)CCCC\\C=C\\C(C)C)ccc1O" "tricky" "[C@@]123[C@H](C(C=C3)(C)C)CC[C@@](C1)(CCC2)C" "6-amino-2-ethyl-5-(aminomethyl)-1-hexanol" "OCC(CC)CCC(CN)CN" "cubane" "C12C3C4C1C5C4C3C25" "cyclopropane" "C1CC1" "acetone" "CC(C)=O" "E-1,2-difluoroethane" "F/C=C/F" "Z-1,2-difluoroethane" "F\\C=C/F" "biphenyl" "c1ccccc1-c2ccccc2" ;; chiral ring-closing atom "chiral-cycle-test" "N1C[C@H]1C" ;; chiral ring-closing atom "chiral-cycle-test-2" "[H][C@]1(Br)CCC1" "serotonin" "NCCc1c[nH]c2ccc(O)cc12"})) (defn get-molecule [name] (get *molecules* name)) (read-smiles-string "C[C@](Br)(Cl)I") (read-smiles-string "C[C@H](Br)I") (read-smiles-string "N[C@](Br)(O)C") (read-smiles-string "N[C@@](Br)(C)O") ;;; these four should all yield the same molecule (assert (= (count (set (map mass [(read-smiles-string "C1=CC=CC=C1") (read-smiles-string "C1C=CC=CC=1") (read-smiles-string "C=1C=CC=CC1") (read-smiles-string "C=1C=CC=CC=1")]))) 1)) (assert (= (count (set (map #(read-smiles-string (write-smiles-string (read-smiles-string %))) ["C1=CC=CC=C1" "C1C=CC=CC=1" "C=1C=CC=CC1" "C=1C=CC=CC=1"]))) 1))
[ { "context": "flex-grow 0\n :min-width \"30%\"}} \"Léo Valais\"]\n [:div.badges {:style {:display :flex\n ", "end": 4740, "score": 0.9998235702514648, "start": 4730, "tag": "NAME", "value": "Léo Valais" }, { "context": "ter\"}}\n [contact [icon \"fas\" \"fa-envelope\"] \"leo.valais97@gmail.com\" \"mailto:leo.valais97@gmail.com\"] contact-separat", "end": 5110, "score": 0.9999276995658875, "start": 5088, "tag": "EMAIL", "value": "leo.valais97@gmail.com" }, { "context": "\" \"fa-envelope\"] \"leo.valais97@gmail.com\" \"mailto:leo.valais97@gmail.com\"] contact-separator\n [contact [icon \"fas\" \"f", "end": 5142, "score": 0.9999310374259949, "start": 5120, "tag": "EMAIL", "value": "leo.valais97@gmail.com" }, { "context": "ator\n [contact [icon \"fab\" \"fa-github-alt\"] \"leovalais\" \"https://github.com/leovalais\"] contact-separato", "end": 5318, "score": 0.9981572031974792, "start": 5309, "tag": "USERNAME", "value": "leovalais" }, { "context": " \"fa-github-alt\"] \"leovalais\" \"https://github.com/leovalais\"] contact-separator\n [contact [icon \"fab\" \"f", "end": 5349, "score": 0.9994235038757324, "start": 5340, "tag": "USERNAME", "value": "leovalais" }, { "context": "arator\n [contact [icon \"fab\" \"fa-linkedin\"] \"leovalais\" \"https://www.linkedin.com/in/leovalais/\"] contac", "end": 5422, "score": 0.9995665550231934, "start": 5413, "tag": "USERNAME", "value": "leovalais" }, { "context": "nkedin\"] \"leovalais\" \"https://www.linkedin.com/in/leovalais/\"] contact-separator\n [contact [icon \"fas\" \"", "end": 5462, "score": 0.9997239112854004, "start": 5453, "tag": "USERNAME", "value": "leovalais" }, { "context": "rnship at BeSport\"\n :link \"https://github.com/ocsigen/html_of_wiki\"\n :tags (list [code-tag \"OCaml\"]", "end": 9172, "score": 0.9995527267456055, "start": 9165, "tag": "USERNAME", "value": "ocsigen" } ]
src/leovalais/core.cljs
leovalais/leovalais
0
(ns leovalais.core (:require [reagent.core :as r] [goog.string :as gstring] [goog.string.format])) (def skills (r/atom [{:skill "C++" :accent true} {:skill "Python" :accent true} {:skill "C"} {:skill "C# .NET"} {:skill "Java"} {:skill "Common Lisp" :accent true} {:skill "Clojure(Script)"} {:skill "OCaml"} {:skill "LaTeX"} {:skill "Web"} {:skill "Image Processing" :accent true} {:skill "Image Synthesis"} {:skill "Machine Learning"} {:skill "Unity"} {:skill "Docker"} {:skill "Linux"} {:skill "macOS"}])) ;; ------------------------- ;; Views (defn icon [& classes] [:i.icon {:class (apply str (interleave (map str classes) (repeat " ")))}]) (defn contact [icon text url] [:a {:href url :style {:display "inline-block" :font-size "75%" :color "#777"}} [:span {:style {:margin-right "6px"}} icon] text]) (def contact-separator [:span.contact-separator {:style {:margin "0px 10px" :color "#777"}} "•"]) ;; (def skill-color "rgb(88, 86, 214)") ;; (def skill-accent-color "rgb(125, 122, 255)") (def skill-color "rgb(20, 20, 20)") (def skill-accent-color "rgb(40, 40, 40)") (defn skill [{:keys [skill accent]}] (let [style {:display :inline-block :color (if accent "white" skill-color) :background-color (if accent skill-accent-color "white") :font-size "75%" :font-weight (if accent :bold :normal) :margin-left "5px" :margin-bottom "3px" :padding "0px 10px" :border-width "1.5px" :border-style :solid :border-color (if accent skill-accent-color skill-color) :border-radius "20px"}] (if accent [:span.skill.accent {:style style} skill] [:span.skill {:style style} skill]))) (defn skillset [skills] [:div.skillset {:style {:width "100%" :margin "20px auto" :text-align :center}} (map skill skills)]) (defn hlist [min-width & items] [:ul.hlist (map (fn [i] [:li.hlist-item {:style {:float :left :min-width min-width}} i]) items)]) (defn tag [icon text] [:span.tag {:style {:display "inline-block" :font-size "75%" :color "#777"}} [:span {:style {:margin-right "6px"}} icon] text]) (def place-tag (partial tag [icon "fas" "fa-map-marker-alt"])) (def agenda-tag (partial tag [icon "far" "fa-calendar-alt"])) (def article-tag (partial tag [icon "far" "fa-newspaper"])) (def code-tag (partial tag [icon "fas" "fa-laptop-code"])) (def github-tag (tag [icon "fab" "fa-github"] "Hosted on GitHub")) (def gitlab-tag (tag [icon "fab" "fa-gitlab"] "Hosted on GitLab")) (def wip-tag (tag [icon "fas" "fa-hard-hat"] "Work in progress")) (defn entry [& {:keys [picture title tags content link]}] [:div.entry {:style {:display :flex :margin-top "10px"}} [:div.picture {:style {:width "7.5%" :flex-shrink 0 :margin-right "10px"}} [:img {:src picture :width "100%"}]] [:div.content {:style {:display :flex :flex-grow 1 :flex-direction :column}} [:div.heading {:style {:display :flex :width :auto}} [:h3 {:style {:margin 0}} [:a {:href link} title]] [:div.tags {:style {:display :flex :justify-content :flex-end :flex-grow 1}} tags]] [:div.description content]]]) (defn section [title icon & content] [:section {:style {:margin-bottom 20}} [:h2 {:style {:margin-bottom 0 :padding-bottom 2 :border-bottom "1px solid #DDD"}} [:span {:style {:margin-right "8px"}} icon] title] [:div.content {:style {:margin-left "10px"}} content]]) (defn emph [& things] [:span.emph things]) (defn flag [country] [:img {:src (str country ".png") :width "11.667mm"}]) (def lrde-logo "lrde.png") (def epita-logo "epita.jpg") (defn cv-view [] [:div.cv [:div.heading {:style {:display :flex}} [:h1 {:style {:margin "15px 0px" :font-variant :small-caps :flex-grow 0 :min-width "30%"}} "Léo Valais"] [:div.badges {:style {:display :flex :align-items :center :justify-content :flex-end :flex-grow 1 :color "#777"}} [:div.contact {:style {:width "100%" :margin "auto" :text-align "center"}} [contact [icon "fas" "fa-envelope"] "leo.valais97@gmail.com" "mailto:leo.valais97@gmail.com"] contact-separator [contact [icon "fas" "fa-phone-alt"] "+33 7 60 06 39 14" "tel:+33760063914"] contact-separator [contact [icon "fab" "fa-github-alt"] "leovalais" "https://github.com/leovalais"] contact-separator [contact [icon "fab" "fa-linkedin"] "leovalais" "https://www.linkedin.com/in/leovalais/"] contact-separator [contact [icon "fas" "fa-car"] "Driving licence" "#"] contact-separator [contact [flag "france"] "Native" "#"] contact-separator [contact [flag "uk"] "TOEIC & Semester abroad" "#"]]]] ;; [:p.abstract {:style {:margin 0 :margin-top 5 :font-size "120%"}} ;; "Looking for a six-month internship — starting late February, early March, 2020 — in " [emph "image processing"] ", " [emph "machine learning"] ;; " or about " [emph "Lisp languages"] ". J-1 visa candidate."] [section "Education" [icon "fas" "fa-graduation-cap"] [entry :picture epita-logo :title [:span "EPITA / CTI"] :link "https://www.epita.fr/nos-formations/diplome-ingenieur/cycle-ingenieur/les-majeures/#majeure-IMAGE" :tags (list [place-tag "Le Kremlin-Bicêtre"] [agenda-tag "2015-2020"]) :content [:p {:style {:margin 0}} "Computer Science engineering school. " [emph "Specialization in image processing and machine learning."] " Experience in raytracing, distributed computing, GPU computing, medical imaging, deep learning, real-time graphics, signal processing, algorithmic complexity, scientifc Python, etc."]] [entry :picture lrde-logo :title "LRDE" :link "https://www.lrde.epita.fr/" :tags (list [code-tag "Common Lisp"] [place-tag "Le Kremlin-Bicêtre"] [agenda-tag "2017-2020"]) :content [:p {:style {:margin 0}} "EPITA's research and development laboratory. " [emph "Second specialisation in research in computer science"] " and a project supervised by laboratory's full-time researchers."]]] [section "Publications" [icon "fas" "fa-scroll"] [entry :picture "els.png" :title "European Lisp Symposium 2019" :link "https://www.lrde.epita.fr/wiki/Publications/valais.19.els" :tags (list [code-tag "Common Lisp"] [article-tag [:a {:href "https://european-lisp-symposium.org/2019/index.html"} "In proceedings"]] [agenda-tag "April 1, 2019"]) :content [:p "“Implementing Baker’s " [:code "SUBTYPEP"] " Decision Procedure”, based on my research work at LRDE. Presentation of an alternative implementation for " [:code "SUBTYPEP"] ", a standard Common Lisp predicate. Involves type theory, type representation and performance concerns."]]] [section "Experience" [icon "fas" "fa-user-tie"] [entry :picture "https://media.glassdoor.com/sqll/3059/airbus-group-squarelogo-1484558058652.png" :title [:span "Satellite image processing internship at" [:br] "Airbus Defence & Space"] :tags (list [code-tag "C++"] [place-tag "Sophia Antipolis"] [agenda-tag "June-September 2020"]) :content [:p "Implementation and improvement of a cloud altitude estimation method. " "Based on stereovision by using the physical gap between optic sensors on PLEIADES satellites. " "Involves stereocorelation, epipolar geometry, Digital Elevation Models, image processing and denoising methods, prototyping with Python, etc."]] [entry :picture epita-logo :title "Teaching assistant C • Unix • C++ • Java • SQL" :tags (list [place-tag "Le Kremlin-Bicêtre"] [agenda-tag "January-December 2019"]) :content "Teaching assistant for third-year EPITA students. Responsible for tutorials, workshops and school projects in several languages and technologies."] [entry :picture "https://www.besport.com/images/be-red.svg" :title "Software development internship at BeSport" :link "https://github.com/ocsigen/html_of_wiki" :tags (list [code-tag "OCaml"] [place-tag "Paris"] [agenda-tag "September-December, 2018"]) :content [:p "Modernization and deployment of a static website generator written in OCaml. " "Currently used to generate the website " [:a {:href "https://ocsigen.org/"} "ocsigen.org"] " holding the documentation of the Ocsigen project."]]] [section "Skills" [icon "fas fa-toolbox"] [skillset @skills]] [section "Some selected projects" [icon "fas fa-tools"] [entry :picture "boat.jpg" :title "Ship classification model" :tags (list [code-tag "Python"] [code-tag "Keras"]) :content "Ship classification model based on Xception using Keras."] [entry :picture "xgboost.png" :title "Melanoma detection model" :link "imed.pdf" :tags (list [code-tag "Python"] [code-tag "xgboost"] [code-tag "scikit-image"]) :content "Automatic melanoma detection method written in Python. Uses scikit-learn and the XGBoost model."]] [:footer {:style {:position :absolute :bottom 0 :right 20 :font-size "60%" :color "#777"}} "Made with ClojureScript and Reagent. " "An interactive version of this résumé is available at " [:a {:href "https://leovalais.netlify.com"} "leovalais.netlify.com"] "."]]) (defn mount-root [] (r/render [cv-view] (.getElementById js/document "app"))) ;; ------------------------- ;; Initialize app (defn init! [] (mount-root))
113915
(ns leovalais.core (:require [reagent.core :as r] [goog.string :as gstring] [goog.string.format])) (def skills (r/atom [{:skill "C++" :accent true} {:skill "Python" :accent true} {:skill "C"} {:skill "C# .NET"} {:skill "Java"} {:skill "Common Lisp" :accent true} {:skill "Clojure(Script)"} {:skill "OCaml"} {:skill "LaTeX"} {:skill "Web"} {:skill "Image Processing" :accent true} {:skill "Image Synthesis"} {:skill "Machine Learning"} {:skill "Unity"} {:skill "Docker"} {:skill "Linux"} {:skill "macOS"}])) ;; ------------------------- ;; Views (defn icon [& classes] [:i.icon {:class (apply str (interleave (map str classes) (repeat " ")))}]) (defn contact [icon text url] [:a {:href url :style {:display "inline-block" :font-size "75%" :color "#777"}} [:span {:style {:margin-right "6px"}} icon] text]) (def contact-separator [:span.contact-separator {:style {:margin "0px 10px" :color "#777"}} "•"]) ;; (def skill-color "rgb(88, 86, 214)") ;; (def skill-accent-color "rgb(125, 122, 255)") (def skill-color "rgb(20, 20, 20)") (def skill-accent-color "rgb(40, 40, 40)") (defn skill [{:keys [skill accent]}] (let [style {:display :inline-block :color (if accent "white" skill-color) :background-color (if accent skill-accent-color "white") :font-size "75%" :font-weight (if accent :bold :normal) :margin-left "5px" :margin-bottom "3px" :padding "0px 10px" :border-width "1.5px" :border-style :solid :border-color (if accent skill-accent-color skill-color) :border-radius "20px"}] (if accent [:span.skill.accent {:style style} skill] [:span.skill {:style style} skill]))) (defn skillset [skills] [:div.skillset {:style {:width "100%" :margin "20px auto" :text-align :center}} (map skill skills)]) (defn hlist [min-width & items] [:ul.hlist (map (fn [i] [:li.hlist-item {:style {:float :left :min-width min-width}} i]) items)]) (defn tag [icon text] [:span.tag {:style {:display "inline-block" :font-size "75%" :color "#777"}} [:span {:style {:margin-right "6px"}} icon] text]) (def place-tag (partial tag [icon "fas" "fa-map-marker-alt"])) (def agenda-tag (partial tag [icon "far" "fa-calendar-alt"])) (def article-tag (partial tag [icon "far" "fa-newspaper"])) (def code-tag (partial tag [icon "fas" "fa-laptop-code"])) (def github-tag (tag [icon "fab" "fa-github"] "Hosted on GitHub")) (def gitlab-tag (tag [icon "fab" "fa-gitlab"] "Hosted on GitLab")) (def wip-tag (tag [icon "fas" "fa-hard-hat"] "Work in progress")) (defn entry [& {:keys [picture title tags content link]}] [:div.entry {:style {:display :flex :margin-top "10px"}} [:div.picture {:style {:width "7.5%" :flex-shrink 0 :margin-right "10px"}} [:img {:src picture :width "100%"}]] [:div.content {:style {:display :flex :flex-grow 1 :flex-direction :column}} [:div.heading {:style {:display :flex :width :auto}} [:h3 {:style {:margin 0}} [:a {:href link} title]] [:div.tags {:style {:display :flex :justify-content :flex-end :flex-grow 1}} tags]] [:div.description content]]]) (defn section [title icon & content] [:section {:style {:margin-bottom 20}} [:h2 {:style {:margin-bottom 0 :padding-bottom 2 :border-bottom "1px solid #DDD"}} [:span {:style {:margin-right "8px"}} icon] title] [:div.content {:style {:margin-left "10px"}} content]]) (defn emph [& things] [:span.emph things]) (defn flag [country] [:img {:src (str country ".png") :width "11.667mm"}]) (def lrde-logo "lrde.png") (def epita-logo "epita.jpg") (defn cv-view [] [:div.cv [:div.heading {:style {:display :flex}} [:h1 {:style {:margin "15px 0px" :font-variant :small-caps :flex-grow 0 :min-width "30%"}} "<NAME>"] [:div.badges {:style {:display :flex :align-items :center :justify-content :flex-end :flex-grow 1 :color "#777"}} [:div.contact {:style {:width "100%" :margin "auto" :text-align "center"}} [contact [icon "fas" "fa-envelope"] "<EMAIL>" "mailto:<EMAIL>"] contact-separator [contact [icon "fas" "fa-phone-alt"] "+33 7 60 06 39 14" "tel:+33760063914"] contact-separator [contact [icon "fab" "fa-github-alt"] "leovalais" "https://github.com/leovalais"] contact-separator [contact [icon "fab" "fa-linkedin"] "leovalais" "https://www.linkedin.com/in/leovalais/"] contact-separator [contact [icon "fas" "fa-car"] "Driving licence" "#"] contact-separator [contact [flag "france"] "Native" "#"] contact-separator [contact [flag "uk"] "TOEIC & Semester abroad" "#"]]]] ;; [:p.abstract {:style {:margin 0 :margin-top 5 :font-size "120%"}} ;; "Looking for a six-month internship — starting late February, early March, 2020 — in " [emph "image processing"] ", " [emph "machine learning"] ;; " or about " [emph "Lisp languages"] ". J-1 visa candidate."] [section "Education" [icon "fas" "fa-graduation-cap"] [entry :picture epita-logo :title [:span "EPITA / CTI"] :link "https://www.epita.fr/nos-formations/diplome-ingenieur/cycle-ingenieur/les-majeures/#majeure-IMAGE" :tags (list [place-tag "Le Kremlin-Bicêtre"] [agenda-tag "2015-2020"]) :content [:p {:style {:margin 0}} "Computer Science engineering school. " [emph "Specialization in image processing and machine learning."] " Experience in raytracing, distributed computing, GPU computing, medical imaging, deep learning, real-time graphics, signal processing, algorithmic complexity, scientifc Python, etc."]] [entry :picture lrde-logo :title "LRDE" :link "https://www.lrde.epita.fr/" :tags (list [code-tag "Common Lisp"] [place-tag "Le Kremlin-Bicêtre"] [agenda-tag "2017-2020"]) :content [:p {:style {:margin 0}} "EPITA's research and development laboratory. " [emph "Second specialisation in research in computer science"] " and a project supervised by laboratory's full-time researchers."]]] [section "Publications" [icon "fas" "fa-scroll"] [entry :picture "els.png" :title "European Lisp Symposium 2019" :link "https://www.lrde.epita.fr/wiki/Publications/valais.19.els" :tags (list [code-tag "Common Lisp"] [article-tag [:a {:href "https://european-lisp-symposium.org/2019/index.html"} "In proceedings"]] [agenda-tag "April 1, 2019"]) :content [:p "“Implementing Baker’s " [:code "SUBTYPEP"] " Decision Procedure”, based on my research work at LRDE. Presentation of an alternative implementation for " [:code "SUBTYPEP"] ", a standard Common Lisp predicate. Involves type theory, type representation and performance concerns."]]] [section "Experience" [icon "fas" "fa-user-tie"] [entry :picture "https://media.glassdoor.com/sqll/3059/airbus-group-squarelogo-1484558058652.png" :title [:span "Satellite image processing internship at" [:br] "Airbus Defence & Space"] :tags (list [code-tag "C++"] [place-tag "Sophia Antipolis"] [agenda-tag "June-September 2020"]) :content [:p "Implementation and improvement of a cloud altitude estimation method. " "Based on stereovision by using the physical gap between optic sensors on PLEIADES satellites. " "Involves stereocorelation, epipolar geometry, Digital Elevation Models, image processing and denoising methods, prototyping with Python, etc."]] [entry :picture epita-logo :title "Teaching assistant C • Unix • C++ • Java • SQL" :tags (list [place-tag "Le Kremlin-Bicêtre"] [agenda-tag "January-December 2019"]) :content "Teaching assistant for third-year EPITA students. Responsible for tutorials, workshops and school projects in several languages and technologies."] [entry :picture "https://www.besport.com/images/be-red.svg" :title "Software development internship at BeSport" :link "https://github.com/ocsigen/html_of_wiki" :tags (list [code-tag "OCaml"] [place-tag "Paris"] [agenda-tag "September-December, 2018"]) :content [:p "Modernization and deployment of a static website generator written in OCaml. " "Currently used to generate the website " [:a {:href "https://ocsigen.org/"} "ocsigen.org"] " holding the documentation of the Ocsigen project."]]] [section "Skills" [icon "fas fa-toolbox"] [skillset @skills]] [section "Some selected projects" [icon "fas fa-tools"] [entry :picture "boat.jpg" :title "Ship classification model" :tags (list [code-tag "Python"] [code-tag "Keras"]) :content "Ship classification model based on Xception using Keras."] [entry :picture "xgboost.png" :title "Melanoma detection model" :link "imed.pdf" :tags (list [code-tag "Python"] [code-tag "xgboost"] [code-tag "scikit-image"]) :content "Automatic melanoma detection method written in Python. Uses scikit-learn and the XGBoost model."]] [:footer {:style {:position :absolute :bottom 0 :right 20 :font-size "60%" :color "#777"}} "Made with ClojureScript and Reagent. " "An interactive version of this résumé is available at " [:a {:href "https://leovalais.netlify.com"} "leovalais.netlify.com"] "."]]) (defn mount-root [] (r/render [cv-view] (.getElementById js/document "app"))) ;; ------------------------- ;; Initialize app (defn init! [] (mount-root))
true
(ns leovalais.core (:require [reagent.core :as r] [goog.string :as gstring] [goog.string.format])) (def skills (r/atom [{:skill "C++" :accent true} {:skill "Python" :accent true} {:skill "C"} {:skill "C# .NET"} {:skill "Java"} {:skill "Common Lisp" :accent true} {:skill "Clojure(Script)"} {:skill "OCaml"} {:skill "LaTeX"} {:skill "Web"} {:skill "Image Processing" :accent true} {:skill "Image Synthesis"} {:skill "Machine Learning"} {:skill "Unity"} {:skill "Docker"} {:skill "Linux"} {:skill "macOS"}])) ;; ------------------------- ;; Views (defn icon [& classes] [:i.icon {:class (apply str (interleave (map str classes) (repeat " ")))}]) (defn contact [icon text url] [:a {:href url :style {:display "inline-block" :font-size "75%" :color "#777"}} [:span {:style {:margin-right "6px"}} icon] text]) (def contact-separator [:span.contact-separator {:style {:margin "0px 10px" :color "#777"}} "•"]) ;; (def skill-color "rgb(88, 86, 214)") ;; (def skill-accent-color "rgb(125, 122, 255)") (def skill-color "rgb(20, 20, 20)") (def skill-accent-color "rgb(40, 40, 40)") (defn skill [{:keys [skill accent]}] (let [style {:display :inline-block :color (if accent "white" skill-color) :background-color (if accent skill-accent-color "white") :font-size "75%" :font-weight (if accent :bold :normal) :margin-left "5px" :margin-bottom "3px" :padding "0px 10px" :border-width "1.5px" :border-style :solid :border-color (if accent skill-accent-color skill-color) :border-radius "20px"}] (if accent [:span.skill.accent {:style style} skill] [:span.skill {:style style} skill]))) (defn skillset [skills] [:div.skillset {:style {:width "100%" :margin "20px auto" :text-align :center}} (map skill skills)]) (defn hlist [min-width & items] [:ul.hlist (map (fn [i] [:li.hlist-item {:style {:float :left :min-width min-width}} i]) items)]) (defn tag [icon text] [:span.tag {:style {:display "inline-block" :font-size "75%" :color "#777"}} [:span {:style {:margin-right "6px"}} icon] text]) (def place-tag (partial tag [icon "fas" "fa-map-marker-alt"])) (def agenda-tag (partial tag [icon "far" "fa-calendar-alt"])) (def article-tag (partial tag [icon "far" "fa-newspaper"])) (def code-tag (partial tag [icon "fas" "fa-laptop-code"])) (def github-tag (tag [icon "fab" "fa-github"] "Hosted on GitHub")) (def gitlab-tag (tag [icon "fab" "fa-gitlab"] "Hosted on GitLab")) (def wip-tag (tag [icon "fas" "fa-hard-hat"] "Work in progress")) (defn entry [& {:keys [picture title tags content link]}] [:div.entry {:style {:display :flex :margin-top "10px"}} [:div.picture {:style {:width "7.5%" :flex-shrink 0 :margin-right "10px"}} [:img {:src picture :width "100%"}]] [:div.content {:style {:display :flex :flex-grow 1 :flex-direction :column}} [:div.heading {:style {:display :flex :width :auto}} [:h3 {:style {:margin 0}} [:a {:href link} title]] [:div.tags {:style {:display :flex :justify-content :flex-end :flex-grow 1}} tags]] [:div.description content]]]) (defn section [title icon & content] [:section {:style {:margin-bottom 20}} [:h2 {:style {:margin-bottom 0 :padding-bottom 2 :border-bottom "1px solid #DDD"}} [:span {:style {:margin-right "8px"}} icon] title] [:div.content {:style {:margin-left "10px"}} content]]) (defn emph [& things] [:span.emph things]) (defn flag [country] [:img {:src (str country ".png") :width "11.667mm"}]) (def lrde-logo "lrde.png") (def epita-logo "epita.jpg") (defn cv-view [] [:div.cv [:div.heading {:style {:display :flex}} [:h1 {:style {:margin "15px 0px" :font-variant :small-caps :flex-grow 0 :min-width "30%"}} "PI:NAME:<NAME>END_PI"] [:div.badges {:style {:display :flex :align-items :center :justify-content :flex-end :flex-grow 1 :color "#777"}} [:div.contact {:style {:width "100%" :margin "auto" :text-align "center"}} [contact [icon "fas" "fa-envelope"] "PI:EMAIL:<EMAIL>END_PI" "mailto:PI:EMAIL:<EMAIL>END_PI"] contact-separator [contact [icon "fas" "fa-phone-alt"] "+33 7 60 06 39 14" "tel:+33760063914"] contact-separator [contact [icon "fab" "fa-github-alt"] "leovalais" "https://github.com/leovalais"] contact-separator [contact [icon "fab" "fa-linkedin"] "leovalais" "https://www.linkedin.com/in/leovalais/"] contact-separator [contact [icon "fas" "fa-car"] "Driving licence" "#"] contact-separator [contact [flag "france"] "Native" "#"] contact-separator [contact [flag "uk"] "TOEIC & Semester abroad" "#"]]]] ;; [:p.abstract {:style {:margin 0 :margin-top 5 :font-size "120%"}} ;; "Looking for a six-month internship — starting late February, early March, 2020 — in " [emph "image processing"] ", " [emph "machine learning"] ;; " or about " [emph "Lisp languages"] ". J-1 visa candidate."] [section "Education" [icon "fas" "fa-graduation-cap"] [entry :picture epita-logo :title [:span "EPITA / CTI"] :link "https://www.epita.fr/nos-formations/diplome-ingenieur/cycle-ingenieur/les-majeures/#majeure-IMAGE" :tags (list [place-tag "Le Kremlin-Bicêtre"] [agenda-tag "2015-2020"]) :content [:p {:style {:margin 0}} "Computer Science engineering school. " [emph "Specialization in image processing and machine learning."] " Experience in raytracing, distributed computing, GPU computing, medical imaging, deep learning, real-time graphics, signal processing, algorithmic complexity, scientifc Python, etc."]] [entry :picture lrde-logo :title "LRDE" :link "https://www.lrde.epita.fr/" :tags (list [code-tag "Common Lisp"] [place-tag "Le Kremlin-Bicêtre"] [agenda-tag "2017-2020"]) :content [:p {:style {:margin 0}} "EPITA's research and development laboratory. " [emph "Second specialisation in research in computer science"] " and a project supervised by laboratory's full-time researchers."]]] [section "Publications" [icon "fas" "fa-scroll"] [entry :picture "els.png" :title "European Lisp Symposium 2019" :link "https://www.lrde.epita.fr/wiki/Publications/valais.19.els" :tags (list [code-tag "Common Lisp"] [article-tag [:a {:href "https://european-lisp-symposium.org/2019/index.html"} "In proceedings"]] [agenda-tag "April 1, 2019"]) :content [:p "“Implementing Baker’s " [:code "SUBTYPEP"] " Decision Procedure”, based on my research work at LRDE. Presentation of an alternative implementation for " [:code "SUBTYPEP"] ", a standard Common Lisp predicate. Involves type theory, type representation and performance concerns."]]] [section "Experience" [icon "fas" "fa-user-tie"] [entry :picture "https://media.glassdoor.com/sqll/3059/airbus-group-squarelogo-1484558058652.png" :title [:span "Satellite image processing internship at" [:br] "Airbus Defence & Space"] :tags (list [code-tag "C++"] [place-tag "Sophia Antipolis"] [agenda-tag "June-September 2020"]) :content [:p "Implementation and improvement of a cloud altitude estimation method. " "Based on stereovision by using the physical gap between optic sensors on PLEIADES satellites. " "Involves stereocorelation, epipolar geometry, Digital Elevation Models, image processing and denoising methods, prototyping with Python, etc."]] [entry :picture epita-logo :title "Teaching assistant C • Unix • C++ • Java • SQL" :tags (list [place-tag "Le Kremlin-Bicêtre"] [agenda-tag "January-December 2019"]) :content "Teaching assistant for third-year EPITA students. Responsible for tutorials, workshops and school projects in several languages and technologies."] [entry :picture "https://www.besport.com/images/be-red.svg" :title "Software development internship at BeSport" :link "https://github.com/ocsigen/html_of_wiki" :tags (list [code-tag "OCaml"] [place-tag "Paris"] [agenda-tag "September-December, 2018"]) :content [:p "Modernization and deployment of a static website generator written in OCaml. " "Currently used to generate the website " [:a {:href "https://ocsigen.org/"} "ocsigen.org"] " holding the documentation of the Ocsigen project."]]] [section "Skills" [icon "fas fa-toolbox"] [skillset @skills]] [section "Some selected projects" [icon "fas fa-tools"] [entry :picture "boat.jpg" :title "Ship classification model" :tags (list [code-tag "Python"] [code-tag "Keras"]) :content "Ship classification model based on Xception using Keras."] [entry :picture "xgboost.png" :title "Melanoma detection model" :link "imed.pdf" :tags (list [code-tag "Python"] [code-tag "xgboost"] [code-tag "scikit-image"]) :content "Automatic melanoma detection method written in Python. Uses scikit-learn and the XGBoost model."]] [:footer {:style {:position :absolute :bottom 0 :right 20 :font-size "60%" :color "#777"}} "Made with ClojureScript and Reagent. " "An interactive version of this résumé is available at " [:a {:href "https://leovalais.netlify.com"} "leovalais.netlify.com"] "."]]) (defn mount-root [] (r/render [cv-view] (.getElementById js/document "app"))) ;; ------------------------- ;; Initialize app (defn init! [] (mount-root))
[ { "context": "ft\" \"Mr Strong\"\n \"Sir Peter\" \"King Danny\" \"Lady Ace\")\n ", "end": 3186, "score": 0.9997320175170898, "start": 3177, "tag": "NAME", "value": "Sir Peter" }, { "context": "ng\"\n \"Sir Peter\" \"King Danny\" \"Lady Ace\")\n (array 0 0", "end": 3199, "score": 0.9995855689048767, "start": 3189, "tag": "NAME", "value": "King Danny" }, { "context": " \"Sir Peter\" \"King Danny\" \"Lady Ace\")\n (array 0 0 0 (array 4", "end": 3210, "score": 0.9949747323989868, "start": 3202, "tag": "NAME", "value": "Lady Ace" }, { "context": " (array 0 0 0 (array 4 2 0 6)))]\n (is (= [\"Sir Peter\" \"Miss Soft\" \"Mr Funny\" \"Lady Ace\"]\n (j", "end": 3293, "score": 0.9994717240333557, "start": 3284, "tag": "NAME", "value": "Sir Peter" } ]
test/cljs/cljs_nusmods/test_aux_module_array_repr.cljs
yanhan/cljs-nusmods
1
(ns cljs-nusmods.test-aux-module-array-repr (:require-macros [cemerick.cljs.test :refer (is deftest)]) (:require [cljs-nusmods.aux-module-array-repr :as aux-module-array-repr] [cemerick.cljs.test :as t])) (deftest test-get-module-type-faculty (let [typeBitmask aux-module-array-repr/MODULE_TYPE_FACULTY resultArray (aux-module-array-repr/get-module-types (array 0 0 typeBitmask))] (is (and (= (.-length resultArray) 1) (= (get aux-module-array-repr/MODULE_TYPES_MAP aux-module-array-repr/MODULE_TYPE_FACULTY) (nth resultArray 0)))))) (deftest test-get-module-type-multiple (let [typeBitmask (bit-or aux-module-array-repr/MODULE_TYPE_FACULTY aux-module-array-repr/MODULE_TYPE_SS aux-module-array-repr/MODULE_TYPE_GEM) resultArray (aux-module-array-repr/get-module-types (array 0 0 typeBitmask))] (is (and (= (.-length resultArray) 3) (= (get aux-module-array-repr/MODULE_TYPES_MAP aux-module-array-repr/MODULE_TYPE_FACULTY) (nth resultArray 0)) (= (get aux-module-array-repr/MODULE_TYPES_MAP aux-module-array-repr/MODULE_TYPE_SS) (nth resultArray 1)) (= (get aux-module-array-repr/MODULE_TYPES_MAP aux-module-array-repr/MODULE_TYPE_GEM) (nth resultArray 2)))))) (deftest test-get-module-type-not-in-cors (let [resultArray (aux-module-array-repr/get-module-types (array 0 0 0))] (is (and (= (.-length resultArray) 1) (= aux-module-array-repr/NOT_IN_CORS (nth resultArray 0)))))) (deftest test-get-module-description (is (= "Basic culinary skills in 3 months =)" (aux-module-array-repr/get-module-description (array "Basic culinary skills in 3 months =)"))))) (deftest test-get-module-department-has-faculty (let [moduleDepartment (aux-module-array-repr/get-module-department (js-obj 0 1, 1 1, 2 2, 3 1, 4 2, 5 1) (array "Chemistry" "Science" "Engineering" "Mathematics" "Electrical Engineering" "Statistics") (array 0 3))] (and (is (= 1 (.-length moduleDepartment))) (is (= "Mathematics" (first moduleDepartment)))))) (deftest test-get-module-department-no-faculty (let [moduleDepartment (aux-module-array-repr/get-module-department (js-obj 0 2, 1 2, 2 2, 3 5, 4 5, 5 5, 6 6) (array "Computer Science" "Information Systems" "School of Computing" "Economics" "Philosophy" "Arts & Social Sciences" "Law") (array 0 6))] (is (= "Law" moduleDepartment)))) (deftest test-get-module-lecturers (let [moduleLecturers (aux-module-array-repr/get-module-lecturers (array "Mr Funny" "Mr Boring" "Miss Soft" "Mr Strong" "Sir Peter" "King Danny" "Lady Ace") (array 0 0 0 (array 4 2 0 6)))] (is (= ["Sir Peter" "Miss Soft" "Mr Funny" "Lady Ace"] (js->clj moduleLecturers))))) (deftest test-get-module-prereqs-string-has-prereqs (is (= "CS1010 or equivalent" (aux-module-array-repr/get-module-prereqs-string (array "String One" "String Two" "CS1010 or equivalent" "String 3") (array 0 0 0 0 2))))) (deftest test-get-module-prereqs-string-no-prereqs (is (= -1 (aux-module-array-repr/get-module-prereqs-string (array "A1" "A2" "A3") (array 0 0 0 0 -1))))) (deftest test-get-module-preclusions-string-has-preclusions (is (= "ModOneA, ModOneB, ModOneE" (aux-module-array-repr/get-module-preclusions-string (array "String One" "ModOneA, ModOneB, ModOneE", "ModTwo") (array 0 0 0 0 0 1))))) (deftest test-get-module-preclusions-string-no-preclusions (is (= -1 (aux-module-array-repr/get-module-preclusions-string (array "String One" "String Two" "String Three") (array 0 0 0 0 0 -1))))) (deftest test-get-module-workload-string-has-workload (is (= "4-4-2-4-8" (aux-module-array-repr/get-module-workload-string (array "1-2-3-4-5" "3-4-5" "6-8-9-1-3" "4-4-2-4-8" "5-6-9-1-3") (array 0 0 0 0 0 0 3))))) (deftest test-get-module-workload-string-no-workload (is (= -1 (aux-module-array-repr/get-module-workload-string (array "workload1" "workload2") (array 0 0 0 0 0 0 -1)))))
63506
(ns cljs-nusmods.test-aux-module-array-repr (:require-macros [cemerick.cljs.test :refer (is deftest)]) (:require [cljs-nusmods.aux-module-array-repr :as aux-module-array-repr] [cemerick.cljs.test :as t])) (deftest test-get-module-type-faculty (let [typeBitmask aux-module-array-repr/MODULE_TYPE_FACULTY resultArray (aux-module-array-repr/get-module-types (array 0 0 typeBitmask))] (is (and (= (.-length resultArray) 1) (= (get aux-module-array-repr/MODULE_TYPES_MAP aux-module-array-repr/MODULE_TYPE_FACULTY) (nth resultArray 0)))))) (deftest test-get-module-type-multiple (let [typeBitmask (bit-or aux-module-array-repr/MODULE_TYPE_FACULTY aux-module-array-repr/MODULE_TYPE_SS aux-module-array-repr/MODULE_TYPE_GEM) resultArray (aux-module-array-repr/get-module-types (array 0 0 typeBitmask))] (is (and (= (.-length resultArray) 3) (= (get aux-module-array-repr/MODULE_TYPES_MAP aux-module-array-repr/MODULE_TYPE_FACULTY) (nth resultArray 0)) (= (get aux-module-array-repr/MODULE_TYPES_MAP aux-module-array-repr/MODULE_TYPE_SS) (nth resultArray 1)) (= (get aux-module-array-repr/MODULE_TYPES_MAP aux-module-array-repr/MODULE_TYPE_GEM) (nth resultArray 2)))))) (deftest test-get-module-type-not-in-cors (let [resultArray (aux-module-array-repr/get-module-types (array 0 0 0))] (is (and (= (.-length resultArray) 1) (= aux-module-array-repr/NOT_IN_CORS (nth resultArray 0)))))) (deftest test-get-module-description (is (= "Basic culinary skills in 3 months =)" (aux-module-array-repr/get-module-description (array "Basic culinary skills in 3 months =)"))))) (deftest test-get-module-department-has-faculty (let [moduleDepartment (aux-module-array-repr/get-module-department (js-obj 0 1, 1 1, 2 2, 3 1, 4 2, 5 1) (array "Chemistry" "Science" "Engineering" "Mathematics" "Electrical Engineering" "Statistics") (array 0 3))] (and (is (= 1 (.-length moduleDepartment))) (is (= "Mathematics" (first moduleDepartment)))))) (deftest test-get-module-department-no-faculty (let [moduleDepartment (aux-module-array-repr/get-module-department (js-obj 0 2, 1 2, 2 2, 3 5, 4 5, 5 5, 6 6) (array "Computer Science" "Information Systems" "School of Computing" "Economics" "Philosophy" "Arts & Social Sciences" "Law") (array 0 6))] (is (= "Law" moduleDepartment)))) (deftest test-get-module-lecturers (let [moduleLecturers (aux-module-array-repr/get-module-lecturers (array "Mr Funny" "Mr Boring" "Miss Soft" "Mr Strong" "<NAME>" "<NAME>" "<NAME>") (array 0 0 0 (array 4 2 0 6)))] (is (= ["<NAME>" "Miss Soft" "Mr Funny" "Lady Ace"] (js->clj moduleLecturers))))) (deftest test-get-module-prereqs-string-has-prereqs (is (= "CS1010 or equivalent" (aux-module-array-repr/get-module-prereqs-string (array "String One" "String Two" "CS1010 or equivalent" "String 3") (array 0 0 0 0 2))))) (deftest test-get-module-prereqs-string-no-prereqs (is (= -1 (aux-module-array-repr/get-module-prereqs-string (array "A1" "A2" "A3") (array 0 0 0 0 -1))))) (deftest test-get-module-preclusions-string-has-preclusions (is (= "ModOneA, ModOneB, ModOneE" (aux-module-array-repr/get-module-preclusions-string (array "String One" "ModOneA, ModOneB, ModOneE", "ModTwo") (array 0 0 0 0 0 1))))) (deftest test-get-module-preclusions-string-no-preclusions (is (= -1 (aux-module-array-repr/get-module-preclusions-string (array "String One" "String Two" "String Three") (array 0 0 0 0 0 -1))))) (deftest test-get-module-workload-string-has-workload (is (= "4-4-2-4-8" (aux-module-array-repr/get-module-workload-string (array "1-2-3-4-5" "3-4-5" "6-8-9-1-3" "4-4-2-4-8" "5-6-9-1-3") (array 0 0 0 0 0 0 3))))) (deftest test-get-module-workload-string-no-workload (is (= -1 (aux-module-array-repr/get-module-workload-string (array "workload1" "workload2") (array 0 0 0 0 0 0 -1)))))
true
(ns cljs-nusmods.test-aux-module-array-repr (:require-macros [cemerick.cljs.test :refer (is deftest)]) (:require [cljs-nusmods.aux-module-array-repr :as aux-module-array-repr] [cemerick.cljs.test :as t])) (deftest test-get-module-type-faculty (let [typeBitmask aux-module-array-repr/MODULE_TYPE_FACULTY resultArray (aux-module-array-repr/get-module-types (array 0 0 typeBitmask))] (is (and (= (.-length resultArray) 1) (= (get aux-module-array-repr/MODULE_TYPES_MAP aux-module-array-repr/MODULE_TYPE_FACULTY) (nth resultArray 0)))))) (deftest test-get-module-type-multiple (let [typeBitmask (bit-or aux-module-array-repr/MODULE_TYPE_FACULTY aux-module-array-repr/MODULE_TYPE_SS aux-module-array-repr/MODULE_TYPE_GEM) resultArray (aux-module-array-repr/get-module-types (array 0 0 typeBitmask))] (is (and (= (.-length resultArray) 3) (= (get aux-module-array-repr/MODULE_TYPES_MAP aux-module-array-repr/MODULE_TYPE_FACULTY) (nth resultArray 0)) (= (get aux-module-array-repr/MODULE_TYPES_MAP aux-module-array-repr/MODULE_TYPE_SS) (nth resultArray 1)) (= (get aux-module-array-repr/MODULE_TYPES_MAP aux-module-array-repr/MODULE_TYPE_GEM) (nth resultArray 2)))))) (deftest test-get-module-type-not-in-cors (let [resultArray (aux-module-array-repr/get-module-types (array 0 0 0))] (is (and (= (.-length resultArray) 1) (= aux-module-array-repr/NOT_IN_CORS (nth resultArray 0)))))) (deftest test-get-module-description (is (= "Basic culinary skills in 3 months =)" (aux-module-array-repr/get-module-description (array "Basic culinary skills in 3 months =)"))))) (deftest test-get-module-department-has-faculty (let [moduleDepartment (aux-module-array-repr/get-module-department (js-obj 0 1, 1 1, 2 2, 3 1, 4 2, 5 1) (array "Chemistry" "Science" "Engineering" "Mathematics" "Electrical Engineering" "Statistics") (array 0 3))] (and (is (= 1 (.-length moduleDepartment))) (is (= "Mathematics" (first moduleDepartment)))))) (deftest test-get-module-department-no-faculty (let [moduleDepartment (aux-module-array-repr/get-module-department (js-obj 0 2, 1 2, 2 2, 3 5, 4 5, 5 5, 6 6) (array "Computer Science" "Information Systems" "School of Computing" "Economics" "Philosophy" "Arts & Social Sciences" "Law") (array 0 6))] (is (= "Law" moduleDepartment)))) (deftest test-get-module-lecturers (let [moduleLecturers (aux-module-array-repr/get-module-lecturers (array "Mr Funny" "Mr Boring" "Miss Soft" "Mr Strong" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") (array 0 0 0 (array 4 2 0 6)))] (is (= ["PI:NAME:<NAME>END_PI" "Miss Soft" "Mr Funny" "Lady Ace"] (js->clj moduleLecturers))))) (deftest test-get-module-prereqs-string-has-prereqs (is (= "CS1010 or equivalent" (aux-module-array-repr/get-module-prereqs-string (array "String One" "String Two" "CS1010 or equivalent" "String 3") (array 0 0 0 0 2))))) (deftest test-get-module-prereqs-string-no-prereqs (is (= -1 (aux-module-array-repr/get-module-prereqs-string (array "A1" "A2" "A3") (array 0 0 0 0 -1))))) (deftest test-get-module-preclusions-string-has-preclusions (is (= "ModOneA, ModOneB, ModOneE" (aux-module-array-repr/get-module-preclusions-string (array "String One" "ModOneA, ModOneB, ModOneE", "ModTwo") (array 0 0 0 0 0 1))))) (deftest test-get-module-preclusions-string-no-preclusions (is (= -1 (aux-module-array-repr/get-module-preclusions-string (array "String One" "String Two" "String Three") (array 0 0 0 0 0 -1))))) (deftest test-get-module-workload-string-has-workload (is (= "4-4-2-4-8" (aux-module-array-repr/get-module-workload-string (array "1-2-3-4-5" "3-4-5" "6-8-9-1-3" "4-4-2-4-8" "5-6-9-1-3") (array 0 0 0 0 0 0 3))))) (deftest test-get-module-workload-string-no-workload (is (= -1 (aux-module-array-repr/get-module-workload-string (array "workload1" "workload2") (array 0 0 0 0 0 0 -1)))))
[ { "context": "ser\n [{{cookie :cookie} :cofx\n {:keys [userUid username]} :params :as ctx}]\n (try\n (fetch-user-detail", "end": 2336, "score": 0.536316990852356, "start": 2328, "tag": "USERNAME", "value": "username" }, { "context": "gePasswordCde\" \"false\"\n \"fullName\" \"Dale Smithyman\"\n \"statusDesc\" \"Active\"\n ", "end": 5224, "score": 0.9998534917831421, "start": 5210, "tag": "NAME", "value": "Dale Smithyman" }, { "context": "aryContactId\" 3445\n \"loginNameNme\" \"Smithyman\"\n \"surnameNme\" \"Smithyman\"\n ", "end": 5512, "score": 0.9998719096183777, "start": 5503, "tag": "NAME", "value": "Smithyman" }, { "context": "NameNme\" \"Smithyman\"\n \"surnameNme\" \"Smithyman\"\n \"otherNme\" nil\n \"ba", "end": 5552, "score": 0.9998898506164551, "start": 5543, "tag": "NAME", "value": "Smithyman" }, { "context": "UploadViewCde\" \"false\"\n \"givenNme\" \"Dale\"\n \"lastSystemAccessTsp\" 14696645561", "end": 5659, "score": 0.9995313882827759, "start": 5655, "tag": "NAME", "value": "Dale" }, { "context": "ntactCde\" \"cde\"\n \"emailOrPhoneTxt\" \"dsmithyman@gplains.vic.gov.au\"\n \"modifiedTsp\" nil\n ", "end": 9892, "score": 0.9999301433563232, "start": 9863, "tag": "EMAIL", "value": "dsmithyman@gplains.vic.gov.au" }, { "context": "gePasswordCde\" \"false\"\n \"fullName\" \"Dale Smithyman\"\n \"statusDesc\" \"Active\"\n ", "end": 10337, "score": 0.9998792409896851, "start": 10323, "tag": "NAME", "value": "Dale Smithyman" }, { "context": "aryContactId\" 3445\n \"loginNameNme\" \"Smithyman\"\n \"surnameNme\" \"Smithyman\"\n ", "end": 10625, "score": 0.9998461604118347, "start": 10616, "tag": "NAME", "value": "Smithyman" }, { "context": "NameNme\" \"Smithyman\"\n \"surnameNme\" \"Smithyman\"\n \"otherNme\" nil\n \"ba", "end": 10665, "score": 0.9998807907104492, "start": 10656, "tag": "NAME", "value": "Smithyman" }, { "context": "UploadViewCde\" \"false\"\n \"givenNme\" \"Dale\"\n \"lastSystemAccessTsp\" 14696645561", "end": 10772, "score": 0.999352216720581, "start": 10768, "tag": "NAME", "value": "Dale" }, { "context": "\" 1469069246595\n \"emailOrPhoneTxt\" \"dsmithyman@gplains.vic.gov.au\"\n \"modifiedTsp\" nil}]\n :opera", "end": 14606, "score": 0.9999270439147949, "start": 14577, "tag": "EMAIL", "value": "dsmithyman@gplains.vic.gov.au" }, { "context": "ved-user-password)\n (let [{password :password\n login :login} (extract-crede", "end": 19307, "score": 0.6931530237197876, "start": 19299, "tag": "PASSWORD", "value": "password" }, { "context": " new-password (password-changed saved-user-password password)]\n {:save-legacy-event\n ", "end": 19983, "score": 0.7821974158287048, "start": 19964, "tag": "PASSWORD", "value": "saved-user-password" }, { "context": "rUid\n :password (crypto/encrypt new-password)})}))\n :handler {:save-legacy-event (fn [payloa", "end": 20528, "score": 0.9950695037841797, "start": 20516, "tag": "PASSWORD", "value": "new-password" }, { "context": "ze (malli/explain address/Schema %))) addresses)\n iuser\n\n (map #(address/parse %) addresses)\n (get-in {", "end": 27188, "score": 0.9972162246704102, "start": 27183, "tag": "USERNAME", "value": "iuser" } ]
src/glider/legacy/users.clj
JohanCodinha/glider
0
(ns glider.legacy.users (:require [clojure.data.xml :refer [emit-str]] #_[glider.event-store.core :as es] [glider.legacy.auth :as legacy-auth] [glider.legacy.transaction.users :as transactions] [glider.legacy.utils :as utils] [glider.system.command.core :as command] [meander.epsilon :as m] #_[glider.system :as system] [malli.provider :as mp] [malli.core :as malli] [malli.transform :as mt] [malli.error :as me] [glider.domain.collaborator.collaborator :refer [collaborator]] [glider.domain.collaborator.contact-method :refer [Schema]] [glider.domain.collaborator.address :as address] [malli.util :as mu] [java-time :as time] [editscript.core :as diff] [lib.editscript.core :as editscript] [glider.utils :refer [uuid timestamp]] [glider.db :refer [select! insert! execute!]] [crypto.password.bcrypt :as crypto] [clojure.core.async :as cca] [glider.system.operation.core :as operation] [clojure.walk :refer [postwalk]])) ;; Aggregate ;; Handling users management sync with legacy system. (defn get-all-users! "Fetch all users, return a lazy seq" [cookie] (println "get all users") (-> (utils/request2! (transactions/all-users-transaction) cookie) first :data)) (comment (transactions/all-users-transaction) (def all-users (future (get-all-users! @legacy-auth/admin-cookie))) (def all-userUid (map #(str (get % "userUid")) (-> @all-users first :data))) ) (defn fetch-user-details! [user-id cookie] (utils/request2! (transactions/user-details user-id) cookie)) (defn import-user-by-userUid! [user-id cookie] (let [res (fetch-user-details! user-id cookie)] res)) (def refresh-cookie [:cookie (fn [ctx] (legacy-auth/refresh-cookie))]) (def legacy-cookie [:cookie (fn [ctx] (let [previous-request (count (filter #{:cookie} (:execute/stack ctx)))] (case previous-request 0 @legacy-auth/admin-cookie 1 (legacy-auth/refresh-cookie) (throw (ex-info "Authentication loop" ctx)))))]) (defn import-user [{{cookie :cookie} :cofx {:keys [userUid username]} :params :as ctx}] (try (fetch-user-details! userUid cookie) (catch clojure.lang.ExceptionInfo e (if (= :cookie-expired (:type (ex-data e))) (command/enqueue ctx legacy-cookie) (throw e))))) (defn import-users-list! [{{cookie :cookie} :cofx :as ctx}] (try (get-all-users! cookie) (catch clojure.lang.ExceptionInfo e (if (= :cookie-expired (:type (ex-data e))) (doto (command/enqueue ctx legacy-cookie) tap>) (throw e))))) (defn legacy-user-synchronized-event [data userUid version] {:id (uuid) :type :legacy-user-synchronized :stream-id userUid :created-at (timestamp) :version version :payload data}) (defn diff-payload [saved imported] (try (let [saved-by-operation (into {} (map (juxt :operation identity) saved))] (if saved (->> imported (map (fn [{operation :operation :as i}] (update i :data #(editscript/diff->edits (:data (get saved-by-operation operation)) %)))) (remove #(empty? (:data %))) vec) imported)) (catch Exception e (println "diff failled, why ?") (tap> saved) (tap> imported) (throw e)))) (comment (diff-payload [{:operation {:content [{:content [{:content ["34"] :attrs nil :tag :userUid}] :attrs {:xsi:type "xsd:Object"} :tag :criteria} {:content [{:content ["UserInfoView_DS"] :attrs nil :tag :dataSource} {:content ["fetch"] :attrs nil :tag :operationType}] :attrs {:xsi:type "xsd:Object"} :tag :operationConfig} {:content ["builtinApplication"] :attrs nil :tag :appID} {:content ["userInfoById"] :attrs nil :tag :operation}] :attrs {:xsi:type "xsd:Object"} :tag :elem} :data-source "UserInfoView_DS" :data [{"confirmUserPasswordTxt" nil "creationTsp" 1313416800000 "preferredContactMethodCde" "pcme" "statusCde" "active" "nameId" 34 "organisationId" 99 "modifiedTsp" 1469664556170 "changePasswordCde" "false" "fullName" "Dale Smithyman" "statusDesc" "Active" "organisationNme" "Golden Plains Shire Council" "roleDesc" "Contributor" "primaryAddressId" 1 "roleCde" "con" "primaryContactId" 3445 "loginNameNme" "Smithyman" "surnameNme" "Smithyman" "otherNme" nil "batchUploadViewCde" "false" "givenNme" "Dale" "lastSystemAccessTsp" 1469664556138 "userUid" 34 "reasonTxt" "LGA user" "restrictedViewingCde" "false" "dateAcceptedTcTsp" nil}]} {:operation {:content [{:content [{:content ["34"] :attrs {:xsi:type "xsd:long"} :tag :USER_UID}] :attrs {:xsi:type "xsd:Object"} :tag :criteria} {:content [{:content ["AddressDetail_DS"] :attrs nil :tag :dataSource} {:content ["fetch"] :attrs nil :tag :operationType} {:content ["exact"] :attrs nil :tag :textMatchStyle}] :attrs {:xsi:type "xsd:Object"} :tag :operationConfig} {:content ["isc_ListGrid_1"] :attrs nil :tag :componentId} {:content ["builtinApplication"] :attrs nil :tag :appID} {:content ["fetchUserAddresses"] :attrs nil :tag :operation}] :attrs {:xsi:type "xsd:Object"} :tag :elem} :data-source "AddressDetail_DS" :data [{"addressId" 1 "creationTsp" 1313416800000 "mainAddressId" "" "modifiedTsp" nil "streetNme" nil "countryNme" nil "postcodeTxt" nil "cityNme" nil "streetNumberTxt" nil "stateNme" nil} {"addressId" 1832 "creationTsp" 1469084015579 "mainAddressId" "" "modifiedTsp" nil "streetNme" "P. O. Box 111" "countryNme" "Australia" "postcodeTxt" "3328" "cityNme" "Bannockburn" "streetNumberTxt" nil "stateNme" "VIC"}]} {:operation {:content [{:content [{:content ["34"] :attrs {:xsi:type "xsd:long"} :tag :USER_UID}] :attrs {:xsi:type "xsd:Object"} :tag :criteria} {:content [{:content ["ContactDetail_DS"] :attrs nil :tag :dataSource} {:content ["fetch"] :attrs nil :tag :operationType} {:content ["exact"] :attrs nil :tag :textMatchStyle}] :attrs {:xsi:type "xsd:Object"} :tag :operationConfig} {:content ["isc_ListGrid_2"] :attrs nil :tag :componentId} {:content ["builtinApplication"] :attrs nil :tag :appID} {:content ["fetchContactByUserUid"] :attrs nil :tag :operation}] :attrs {:xsi:type "xsd:Object"} :tag :elem} :data-source "ContactDetail_DS" :data [{"creationTsp" nil "contactCde" nil "emailOrPhoneTxt" nil "modifiedTsp" nil "contactId" 1} {"creationTsp" 1469069246595 "contactCde" "cde" "emailOrPhoneTxt" "dsmithyman@gplains.vic.gov.au" "modifiedTsp" nil "contactId" 3445}]}] [{:data [{"confirmUserPasswordTxt" nil "creationTsp" 1313416800000 "preferredContactMethodCde" "pcme" "statusCde" "active" "nameId" 34 "organisationId" 99 "modifiedTsp" 1469664556170 "changePasswordCde" "false" "fullName" "Dale Smithyman" "statusDesc" "Active" "organisationNme" "Golden Plains Shire Council" "roleDesc" "Contributor" "primaryAddressId" 1 "roleCde" "con" "primaryContactId" 3445 "loginNameNme" "Smithyman" "surnameNme" "Smithyman" "otherNme" nil "batchUploadViewCde" "false" "givenNme" "Dale" "lastSystemAccessTsp" 1469664556138 "userUid" 34 "reasonTxt" "LGA user" "restrictedViewingCde" "false" "dateAcceptedTcTsp" nil}] :operation {:tag :elem :attrs {:xsi:type "xsd:Object"} :content [{:tag :criteria :attrs {:xsi:type "xsd:Object"} :content [{:tag :userUid :attrs nil :content ["34"]}]} {:tag :operationConfig :attrs {:xsi:type "xsd:Object"} :content [{:tag :dataSource :attrs nil :content ["UserInfoView_DS"]} {:tag :operationType :attrs nil :content ["fetch"]}]} {:tag :appID :attrs nil :content ["builtinApplication"]} {:tag :operation :attrs nil :content ["userInfoById"]}]}} {:data [{"addressId" 1832 "creationTsp" 1469084015579 "mainAddressId" "" "modifiedTsp" nil "streetNme" "P. O. Box 111" "countryNme" "Australia" "postcodeTxt" "3328" "cityNme" "Bannockburn" "streetNumberTxt" nil "stateNme" "VIC"} {"addressId" 1 "creationTsp" 1313416800000 "mainAddressId" "" "modifiedTsp" nil "streetNme" nil "countryNme" nil "postcodeTxt" nil "cityNme" nil "streetNumberTxt" nil "stateNme" nil}] :operation {:tag :elem :attrs {:xsi:type "xsd:Object"} :content [{:tag :criteria :attrs {:xsi:type "xsd:Object"} :content [{:tag :USER_UID :attrs {:xsi:type "xsd:long"} :content ["34"]}]} {:tag :operationConfig :attrs {:xsi:type "xsd:Object"} :content [{:tag :dataSource :attrs nil :content ["AddressDetail_DS"]} {:tag :operationType :attrs nil :content ["fetch"]} {:tag :textMatchStyle :attrs nil :content ["exact"]}]} {:tag :componentId :attrs nil :content ["isc_ListGrid_1"]} {:tag :appID :attrs nil :content ["builtinApplication"]} {:tag :operation :attrs nil :content ["fetchUserAddresses"]}]}} {:data [{"contactCde" nil "contactId" 1 "creationTsp" nil "emailOrPhoneTxt" nil "modifiedTsp" nil} {"contactCde" "cde" "contactId" 3445 "creationTsp" 1469069246595 "emailOrPhoneTxt" "dsmithyman@gplains.vic.gov.au" "modifiedTsp" nil}] :operation {:tag :elem :attrs {:xsi:type "xsd:Object"} :content [{:tag :criteria :attrs {:xsi:type "xsd:Object"} :content [{:tag :USER_UID :attrs {:xsi:type "xsd:long"} :content ["34"]}]} {:tag :operationConfig :attrs {:xsi:type "xsd:Object"} :content [{:tag :dataSource :attrs nil :content ["ContactDetail_DS"]} {:tag :operationType :attrs nil :content ["fetch"]} {:tag :textMatchStyle :attrs nil :content ["exact"]}]} {:tag :componentId :attrs nil :content ["isc_ListGrid_2"]} {:tag :appID :attrs nil :content ["builtinApplication"]} {:tag :operation :attrs nil :content ["fetchContactByUserUid"]}]}}])) ;;Import users from legacy app (defn fetch-saved-user-stream [userUid] (select! ["SELECT * FROM legacy_events WHERE stream_id = ? ORDER BY version" userUid])) (defn merge-diffs "Merge a stream of diff, return nil if passed empty vector" [stream] (reduce (fn ([]) ([a b] (mapv (fn [{operation :operation :as payload}] (let [data-b (:data (first (get (group-by :operation b) operation)))] (cond-> payload (and (some? data-b) (diff/valid-edits? data-b)) (update :data #(diff/patch % (diff/edits->script data-b)))))) a))) (map :payload stream))) (defn extract-credentials [user-data] (m/find user-data (m/scan {:data [{"userPasswordTxt" ?password "loginNameNme" ?login}]}) {:password ?password :login ?login})) (defn remove-key [user-data key] (clojure.walk/postwalk #(when-not (and (vector? %) (= (first %) key)) %) user-data)) (defn fetch-saved-user-password [userUid] (first (select! ["SELECT * FROM authentication WHERE legacy_uid = ?" userUid]))) (defn fetch-credentials [{:keys [login uuid legacy-uid]}] (first (select! ["SELECT * FROM authentication WHERE uuid = ? OR login = ? OR legacy_uid = ?" uuid login legacy-uid]))) (defn upsert-authentication-credentials! [{:keys [uuid login legacy-uid] :as credentials} {db :db}] (let [exist (fetch-credentials credentials)] (when exist (execute! db ["DELETE FROM authentication WHERE uuid = ? OR login = ? OR legacy_uid = ?" uuid login legacy-uid])) (insert! db :authentication credentials))) (defn valid-credentials? [{:keys [password login uuid] :as credentials}] (let [{encrypted-passwrod :authentication/password} (fetch-credentials credentials)] (crypto/check password encrypted-passwrod))) (defn password-changed [saved new] (cond (and (nil? saved) (string? new)) new (and (string? saved) (string? new) (not (crypto/check new saved))) new)) (defn user-exists? [imported-user] (not-every? (fn [{data :data}] (or (= data nil) (= data []))) imported-user)) (def import-user-command {:id ::import-user :params [:map [:userUid :string]] :coeffects [legacy-cookie [:saved-user-stream (fn [{{:keys [userUid]} :params}] (fetch-saved-user-stream userUid))] [:saved-user-password (fn [{{:keys [userUid]} :params}] (:password (fetch-saved-user-password userUid)))] [:imported-user import-user]] :conditions [[(fn [{{:keys [imported-user]} :cofx}] (user-exists? imported-user)) :not-found "User with this id does not exist"]] :effects (fn [{{:keys [saved-user-stream imported-user saved-user-password]} :cofx {:keys [userUid]} :params}] (println userUid) (tap> saved-user-stream) (tap> imported-user) (tap> saved-user-password) (let [{password :password login :login} (extract-credentials imported-user) saved-user (merge-diffs saved-user-stream) next-version (-> saved-user-stream last (get :version 0) inc) data-diff (diff-payload saved-user (mapv #(select-keys % [:data :operation]) (remove-key imported-user "userPasswordTxt"))) new-password (password-changed saved-user-password password)] {:save-legacy-event (when-not (empty? data-diff) {:id (uuid) :type :legacy-user-synchronized :stream-id userUid :created-at (timestamp) :version next-version :payload data-diff}) :save-credentials (when new-password {:login login :legacy-uid userUid :password (crypto/encrypt new-password)})})) :handler {:save-legacy-event (fn [payload environment] (insert! (:db environment) :legacy-events payload)) :save-credentials upsert-authentication-credentials!} :return #(select-keys % [:side-effects]) :produce [:map [:side-effects [:map [:save-legacy-event [:or map? nil?] :save-credentials [:or map? nil?]]]]]}) (defn fetch-users [{{:keys [cookie users-list]} :cofx :as ctx}] (reduce (fn [acc id] (let [user (fetch-user-details! id cookie)] (operation/update! (get-in ctx [:environment :db]) (update-in (:operation ctx) [:metadata :users-fetched] (fnil inc 0))) (conj acc user))) [] (map #(get % "userUid") users-list))) (def import-users-command {:id ::import-users :coeffects [legacy-cookie [:users-list import-users-list!] [:update-operation (fn [{{:keys [users-list]} :cofx :as ctx}] (operation/update! (get-in ctx [:environment :db]) (assoc-in (:operation ctx) [:metadata :users-to-fetch] (count users-list))))] [:fetch-users fetch-users]] :return identity}) (comment (command/run! import-users-command) ) (comment (def ev (command/run! import-user-command {:userUid "16"} {:environment {:db @glider.db/datasource}} #_{:side-effects false})) (def iuser (import-user-by-userUid! "10660" @legacy-auth/admin-cookie)) (legacy-auth/refresh-cookie) (execute! ["DELETE FROM legacy_events WHERE stream_id = ?" "10660"]) (def re (first (select! ["SELECT * FROM legacy_events WHERE stream_id = ?" "10660"]))) ;; Test that merging all update bring aggregate to same state as current. (= (mapv #(dissoc % :operation) (:res iuser)) (merge-diffs (fetch-saved-user-stream "10660"))) (-> "10660" fetch-saved-user-stream merge-diffs) (count (fetch-saved-user-stream "10660")) (def lookups-data (utils/request! {:tag :transaction :attrsiy {:xsi:type "xsd:Object", :xmlns:xsi "http://www.w3.org/2000/10/XMLSchema-instance"}, :content [{:tag :operations, :attrs {:xsi:type "xsd:List"}, :content [{:tag :elem, :attrs {:xsi:type "xsd:Object"}, :content [{:tag :criteria, :attrs {:xsi:type "xsd:Object"}, :content nil} {:tag :operationConfig, :attrs {:xsi:type "xsd:Object"}, :content [{:tag :dataSource, :attrs nil, :content ["LookupExpansion_DS"]} {:tag :operationType, :attrs nil, :content ["fetch"]} {:tag :textMatchStyle, :attrs nil, :content ["substring"]}]} {:tag :componentId, :attrs nil, :content ["isc_ReferenceDataModule$1_0"]} {:tag :appID, :attrs nil, :content ["builtinApplication"]} {:tag :operation, :attrs nil, :content ["LookupExpansion_DS_fetch"]}]}]}]} @legacy-auth/admin-cookie)) (defn index-lookups [lookups] (into {} (map (fn [[type ls]] [type (into {} (map (fn [l] [(get l "lookupCde") (get l "lookupDesc")]) ls))]) (group-by #(get % "lookupTypeTxt") lookups)))) (def lookups (index-lookups (get lookups-data "LookupExpansion_DS")))) (defn hydrate-contact [lookups user-raw-response] (m/search (assoc user-raw-response "lookups" lookups) {"lookups" {"Contact Detail" {?contactCde ?desc}} "UserInfoView_DS" [{"primaryContactId" ?primaryContactId}] "ContactDetail_DS" (m/scan {"contactCde" ?contactCde "contactId" ?contactId "emailOrPhoneTxt" ?emailOrPhoneTxt & ?rest})} (merge {:type ?desc :primary (= ?primaryContactId ?contactId)} ?rest (if (= ?desc "Email Address") {:address ?emailOrPhoneTxt} {:number ?emailOrPhoneTxt})))) (defn hydrate-addresses [user-raw-response] (m/search user-raw-response {"UserInfoView_DS" [{"primaryAddressId" ?primaryAddressId}] "AddressDetail_DS" (m/scan {"addressId" ?addressId & ?rest})} (conj {:primary (= ?primaryAddressId ?addressId)} ?rest))) (comment (hydrate-contact lookups iuser) (hydrate-addresses iuser)) (defn remove-nils-and-string-keys [m] (into {} (remove (fn [[k v]] (or (string? k) (nil? v))) m))) (def keys-mapping {"UserInfoView_DS" {"creationTsp" :account-creation-date, "statusDesc" :status, "roleDesc" :role, "loginNameNme" :login-name, "surnameNme" :surname, "otherNme" :other-name, "batchUploadViewCde" :batch-upload-access, "givenNme" :given-name, "userUid" :legacy-Uid, "reasonTxt" :reason-of-use, "restrictedViewingCde" :restricted-viewing-access, "dateAcceptedTcTsp" :terms-and-conditions-accepted-date} "ContactDetail_DS" {"contactCde" :type} "AddressDetail_DS" {"creationTsp" :supplied-date, "streetNme" :street-name, "countryNme" :country-name, "postcodeTxt" :postcode, "cityNme" :city, "streetNumberTxt" :street-number, "stateNme" :state}}) (comment (def contact (->> iuser (hydrate-contact lookups) (map #(clojure.set/rename-keys % (get keys-mapping "ContactDetail_DS"))) (map remove-nils-and-string-keys))) (def addresses (->> iuser hydrate-addresses (map #(clojure.set/rename-keys % (get keys-mapping "AddressDetail_DS"))) (map remove-nils-and-string-keys))) (def saved (-> iuser (get-in #_iuser ["UserInfoView_DS" 0]) #_(hydrate-user) (clojure.set/rename-keys (get keys-mapping "UserInfoView_DS")) remove-nils-and-string-keys)) saved (map #(malli/validate Schema %) contact) (map #(if (malli/validate address/Schema %) % (me/humanize (malli/explain address/Schema %))) addresses) iuser (map #(address/parse %) addresses) (get-in {"a" [1 2]} ["a" 0]) (collaborator saved)) ;store raw data
21221
(ns glider.legacy.users (:require [clojure.data.xml :refer [emit-str]] #_[glider.event-store.core :as es] [glider.legacy.auth :as legacy-auth] [glider.legacy.transaction.users :as transactions] [glider.legacy.utils :as utils] [glider.system.command.core :as command] [meander.epsilon :as m] #_[glider.system :as system] [malli.provider :as mp] [malli.core :as malli] [malli.transform :as mt] [malli.error :as me] [glider.domain.collaborator.collaborator :refer [collaborator]] [glider.domain.collaborator.contact-method :refer [Schema]] [glider.domain.collaborator.address :as address] [malli.util :as mu] [java-time :as time] [editscript.core :as diff] [lib.editscript.core :as editscript] [glider.utils :refer [uuid timestamp]] [glider.db :refer [select! insert! execute!]] [crypto.password.bcrypt :as crypto] [clojure.core.async :as cca] [glider.system.operation.core :as operation] [clojure.walk :refer [postwalk]])) ;; Aggregate ;; Handling users management sync with legacy system. (defn get-all-users! "Fetch all users, return a lazy seq" [cookie] (println "get all users") (-> (utils/request2! (transactions/all-users-transaction) cookie) first :data)) (comment (transactions/all-users-transaction) (def all-users (future (get-all-users! @legacy-auth/admin-cookie))) (def all-userUid (map #(str (get % "userUid")) (-> @all-users first :data))) ) (defn fetch-user-details! [user-id cookie] (utils/request2! (transactions/user-details user-id) cookie)) (defn import-user-by-userUid! [user-id cookie] (let [res (fetch-user-details! user-id cookie)] res)) (def refresh-cookie [:cookie (fn [ctx] (legacy-auth/refresh-cookie))]) (def legacy-cookie [:cookie (fn [ctx] (let [previous-request (count (filter #{:cookie} (:execute/stack ctx)))] (case previous-request 0 @legacy-auth/admin-cookie 1 (legacy-auth/refresh-cookie) (throw (ex-info "Authentication loop" ctx)))))]) (defn import-user [{{cookie :cookie} :cofx {:keys [userUid username]} :params :as ctx}] (try (fetch-user-details! userUid cookie) (catch clojure.lang.ExceptionInfo e (if (= :cookie-expired (:type (ex-data e))) (command/enqueue ctx legacy-cookie) (throw e))))) (defn import-users-list! [{{cookie :cookie} :cofx :as ctx}] (try (get-all-users! cookie) (catch clojure.lang.ExceptionInfo e (if (= :cookie-expired (:type (ex-data e))) (doto (command/enqueue ctx legacy-cookie) tap>) (throw e))))) (defn legacy-user-synchronized-event [data userUid version] {:id (uuid) :type :legacy-user-synchronized :stream-id userUid :created-at (timestamp) :version version :payload data}) (defn diff-payload [saved imported] (try (let [saved-by-operation (into {} (map (juxt :operation identity) saved))] (if saved (->> imported (map (fn [{operation :operation :as i}] (update i :data #(editscript/diff->edits (:data (get saved-by-operation operation)) %)))) (remove #(empty? (:data %))) vec) imported)) (catch Exception e (println "diff failled, why ?") (tap> saved) (tap> imported) (throw e)))) (comment (diff-payload [{:operation {:content [{:content [{:content ["34"] :attrs nil :tag :userUid}] :attrs {:xsi:type "xsd:Object"} :tag :criteria} {:content [{:content ["UserInfoView_DS"] :attrs nil :tag :dataSource} {:content ["fetch"] :attrs nil :tag :operationType}] :attrs {:xsi:type "xsd:Object"} :tag :operationConfig} {:content ["builtinApplication"] :attrs nil :tag :appID} {:content ["userInfoById"] :attrs nil :tag :operation}] :attrs {:xsi:type "xsd:Object"} :tag :elem} :data-source "UserInfoView_DS" :data [{"confirmUserPasswordTxt" nil "creationTsp" 1313416800000 "preferredContactMethodCde" "pcme" "statusCde" "active" "nameId" 34 "organisationId" 99 "modifiedTsp" 1469664556170 "changePasswordCde" "false" "fullName" "<NAME>" "statusDesc" "Active" "organisationNme" "Golden Plains Shire Council" "roleDesc" "Contributor" "primaryAddressId" 1 "roleCde" "con" "primaryContactId" 3445 "loginNameNme" "<NAME>" "surnameNme" "<NAME>" "otherNme" nil "batchUploadViewCde" "false" "givenNme" "<NAME>" "lastSystemAccessTsp" 1469664556138 "userUid" 34 "reasonTxt" "LGA user" "restrictedViewingCde" "false" "dateAcceptedTcTsp" nil}]} {:operation {:content [{:content [{:content ["34"] :attrs {:xsi:type "xsd:long"} :tag :USER_UID}] :attrs {:xsi:type "xsd:Object"} :tag :criteria} {:content [{:content ["AddressDetail_DS"] :attrs nil :tag :dataSource} {:content ["fetch"] :attrs nil :tag :operationType} {:content ["exact"] :attrs nil :tag :textMatchStyle}] :attrs {:xsi:type "xsd:Object"} :tag :operationConfig} {:content ["isc_ListGrid_1"] :attrs nil :tag :componentId} {:content ["builtinApplication"] :attrs nil :tag :appID} {:content ["fetchUserAddresses"] :attrs nil :tag :operation}] :attrs {:xsi:type "xsd:Object"} :tag :elem} :data-source "AddressDetail_DS" :data [{"addressId" 1 "creationTsp" 1313416800000 "mainAddressId" "" "modifiedTsp" nil "streetNme" nil "countryNme" nil "postcodeTxt" nil "cityNme" nil "streetNumberTxt" nil "stateNme" nil} {"addressId" 1832 "creationTsp" 1469084015579 "mainAddressId" "" "modifiedTsp" nil "streetNme" "P. O. Box 111" "countryNme" "Australia" "postcodeTxt" "3328" "cityNme" "Bannockburn" "streetNumberTxt" nil "stateNme" "VIC"}]} {:operation {:content [{:content [{:content ["34"] :attrs {:xsi:type "xsd:long"} :tag :USER_UID}] :attrs {:xsi:type "xsd:Object"} :tag :criteria} {:content [{:content ["ContactDetail_DS"] :attrs nil :tag :dataSource} {:content ["fetch"] :attrs nil :tag :operationType} {:content ["exact"] :attrs nil :tag :textMatchStyle}] :attrs {:xsi:type "xsd:Object"} :tag :operationConfig} {:content ["isc_ListGrid_2"] :attrs nil :tag :componentId} {:content ["builtinApplication"] :attrs nil :tag :appID} {:content ["fetchContactByUserUid"] :attrs nil :tag :operation}] :attrs {:xsi:type "xsd:Object"} :tag :elem} :data-source "ContactDetail_DS" :data [{"creationTsp" nil "contactCde" nil "emailOrPhoneTxt" nil "modifiedTsp" nil "contactId" 1} {"creationTsp" 1469069246595 "contactCde" "cde" "emailOrPhoneTxt" "<EMAIL>" "modifiedTsp" nil "contactId" 3445}]}] [{:data [{"confirmUserPasswordTxt" nil "creationTsp" 1313416800000 "preferredContactMethodCde" "pcme" "statusCde" "active" "nameId" 34 "organisationId" 99 "modifiedTsp" 1469664556170 "changePasswordCde" "false" "fullName" "<NAME>" "statusDesc" "Active" "organisationNme" "Golden Plains Shire Council" "roleDesc" "Contributor" "primaryAddressId" 1 "roleCde" "con" "primaryContactId" 3445 "loginNameNme" "<NAME>" "surnameNme" "<NAME>" "otherNme" nil "batchUploadViewCde" "false" "givenNme" "<NAME>" "lastSystemAccessTsp" 1469664556138 "userUid" 34 "reasonTxt" "LGA user" "restrictedViewingCde" "false" "dateAcceptedTcTsp" nil}] :operation {:tag :elem :attrs {:xsi:type "xsd:Object"} :content [{:tag :criteria :attrs {:xsi:type "xsd:Object"} :content [{:tag :userUid :attrs nil :content ["34"]}]} {:tag :operationConfig :attrs {:xsi:type "xsd:Object"} :content [{:tag :dataSource :attrs nil :content ["UserInfoView_DS"]} {:tag :operationType :attrs nil :content ["fetch"]}]} {:tag :appID :attrs nil :content ["builtinApplication"]} {:tag :operation :attrs nil :content ["userInfoById"]}]}} {:data [{"addressId" 1832 "creationTsp" 1469084015579 "mainAddressId" "" "modifiedTsp" nil "streetNme" "P. O. Box 111" "countryNme" "Australia" "postcodeTxt" "3328" "cityNme" "Bannockburn" "streetNumberTxt" nil "stateNme" "VIC"} {"addressId" 1 "creationTsp" 1313416800000 "mainAddressId" "" "modifiedTsp" nil "streetNme" nil "countryNme" nil "postcodeTxt" nil "cityNme" nil "streetNumberTxt" nil "stateNme" nil}] :operation {:tag :elem :attrs {:xsi:type "xsd:Object"} :content [{:tag :criteria :attrs {:xsi:type "xsd:Object"} :content [{:tag :USER_UID :attrs {:xsi:type "xsd:long"} :content ["34"]}]} {:tag :operationConfig :attrs {:xsi:type "xsd:Object"} :content [{:tag :dataSource :attrs nil :content ["AddressDetail_DS"]} {:tag :operationType :attrs nil :content ["fetch"]} {:tag :textMatchStyle :attrs nil :content ["exact"]}]} {:tag :componentId :attrs nil :content ["isc_ListGrid_1"]} {:tag :appID :attrs nil :content ["builtinApplication"]} {:tag :operation :attrs nil :content ["fetchUserAddresses"]}]}} {:data [{"contactCde" nil "contactId" 1 "creationTsp" nil "emailOrPhoneTxt" nil "modifiedTsp" nil} {"contactCde" "cde" "contactId" 3445 "creationTsp" 1469069246595 "emailOrPhoneTxt" "<EMAIL>" "modifiedTsp" nil}] :operation {:tag :elem :attrs {:xsi:type "xsd:Object"} :content [{:tag :criteria :attrs {:xsi:type "xsd:Object"} :content [{:tag :USER_UID :attrs {:xsi:type "xsd:long"} :content ["34"]}]} {:tag :operationConfig :attrs {:xsi:type "xsd:Object"} :content [{:tag :dataSource :attrs nil :content ["ContactDetail_DS"]} {:tag :operationType :attrs nil :content ["fetch"]} {:tag :textMatchStyle :attrs nil :content ["exact"]}]} {:tag :componentId :attrs nil :content ["isc_ListGrid_2"]} {:tag :appID :attrs nil :content ["builtinApplication"]} {:tag :operation :attrs nil :content ["fetchContactByUserUid"]}]}}])) ;;Import users from legacy app (defn fetch-saved-user-stream [userUid] (select! ["SELECT * FROM legacy_events WHERE stream_id = ? ORDER BY version" userUid])) (defn merge-diffs "Merge a stream of diff, return nil if passed empty vector" [stream] (reduce (fn ([]) ([a b] (mapv (fn [{operation :operation :as payload}] (let [data-b (:data (first (get (group-by :operation b) operation)))] (cond-> payload (and (some? data-b) (diff/valid-edits? data-b)) (update :data #(diff/patch % (diff/edits->script data-b)))))) a))) (map :payload stream))) (defn extract-credentials [user-data] (m/find user-data (m/scan {:data [{"userPasswordTxt" ?password "loginNameNme" ?login}]}) {:password ?password :login ?login})) (defn remove-key [user-data key] (clojure.walk/postwalk #(when-not (and (vector? %) (= (first %) key)) %) user-data)) (defn fetch-saved-user-password [userUid] (first (select! ["SELECT * FROM authentication WHERE legacy_uid = ?" userUid]))) (defn fetch-credentials [{:keys [login uuid legacy-uid]}] (first (select! ["SELECT * FROM authentication WHERE uuid = ? OR login = ? OR legacy_uid = ?" uuid login legacy-uid]))) (defn upsert-authentication-credentials! [{:keys [uuid login legacy-uid] :as credentials} {db :db}] (let [exist (fetch-credentials credentials)] (when exist (execute! db ["DELETE FROM authentication WHERE uuid = ? OR login = ? OR legacy_uid = ?" uuid login legacy-uid])) (insert! db :authentication credentials))) (defn valid-credentials? [{:keys [password login uuid] :as credentials}] (let [{encrypted-passwrod :authentication/password} (fetch-credentials credentials)] (crypto/check password encrypted-passwrod))) (defn password-changed [saved new] (cond (and (nil? saved) (string? new)) new (and (string? saved) (string? new) (not (crypto/check new saved))) new)) (defn user-exists? [imported-user] (not-every? (fn [{data :data}] (or (= data nil) (= data []))) imported-user)) (def import-user-command {:id ::import-user :params [:map [:userUid :string]] :coeffects [legacy-cookie [:saved-user-stream (fn [{{:keys [userUid]} :params}] (fetch-saved-user-stream userUid))] [:saved-user-password (fn [{{:keys [userUid]} :params}] (:password (fetch-saved-user-password userUid)))] [:imported-user import-user]] :conditions [[(fn [{{:keys [imported-user]} :cofx}] (user-exists? imported-user)) :not-found "User with this id does not exist"]] :effects (fn [{{:keys [saved-user-stream imported-user saved-user-password]} :cofx {:keys [userUid]} :params}] (println userUid) (tap> saved-user-stream) (tap> imported-user) (tap> saved-user-password) (let [{password :<PASSWORD> login :login} (extract-credentials imported-user) saved-user (merge-diffs saved-user-stream) next-version (-> saved-user-stream last (get :version 0) inc) data-diff (diff-payload saved-user (mapv #(select-keys % [:data :operation]) (remove-key imported-user "userPasswordTxt"))) new-password (password-changed <PASSWORD> password)] {:save-legacy-event (when-not (empty? data-diff) {:id (uuid) :type :legacy-user-synchronized :stream-id userUid :created-at (timestamp) :version next-version :payload data-diff}) :save-credentials (when new-password {:login login :legacy-uid userUid :password (crypto/encrypt <PASSWORD>)})})) :handler {:save-legacy-event (fn [payload environment] (insert! (:db environment) :legacy-events payload)) :save-credentials upsert-authentication-credentials!} :return #(select-keys % [:side-effects]) :produce [:map [:side-effects [:map [:save-legacy-event [:or map? nil?] :save-credentials [:or map? nil?]]]]]}) (defn fetch-users [{{:keys [cookie users-list]} :cofx :as ctx}] (reduce (fn [acc id] (let [user (fetch-user-details! id cookie)] (operation/update! (get-in ctx [:environment :db]) (update-in (:operation ctx) [:metadata :users-fetched] (fnil inc 0))) (conj acc user))) [] (map #(get % "userUid") users-list))) (def import-users-command {:id ::import-users :coeffects [legacy-cookie [:users-list import-users-list!] [:update-operation (fn [{{:keys [users-list]} :cofx :as ctx}] (operation/update! (get-in ctx [:environment :db]) (assoc-in (:operation ctx) [:metadata :users-to-fetch] (count users-list))))] [:fetch-users fetch-users]] :return identity}) (comment (command/run! import-users-command) ) (comment (def ev (command/run! import-user-command {:userUid "16"} {:environment {:db @glider.db/datasource}} #_{:side-effects false})) (def iuser (import-user-by-userUid! "10660" @legacy-auth/admin-cookie)) (legacy-auth/refresh-cookie) (execute! ["DELETE FROM legacy_events WHERE stream_id = ?" "10660"]) (def re (first (select! ["SELECT * FROM legacy_events WHERE stream_id = ?" "10660"]))) ;; Test that merging all update bring aggregate to same state as current. (= (mapv #(dissoc % :operation) (:res iuser)) (merge-diffs (fetch-saved-user-stream "10660"))) (-> "10660" fetch-saved-user-stream merge-diffs) (count (fetch-saved-user-stream "10660")) (def lookups-data (utils/request! {:tag :transaction :attrsiy {:xsi:type "xsd:Object", :xmlns:xsi "http://www.w3.org/2000/10/XMLSchema-instance"}, :content [{:tag :operations, :attrs {:xsi:type "xsd:List"}, :content [{:tag :elem, :attrs {:xsi:type "xsd:Object"}, :content [{:tag :criteria, :attrs {:xsi:type "xsd:Object"}, :content nil} {:tag :operationConfig, :attrs {:xsi:type "xsd:Object"}, :content [{:tag :dataSource, :attrs nil, :content ["LookupExpansion_DS"]} {:tag :operationType, :attrs nil, :content ["fetch"]} {:tag :textMatchStyle, :attrs nil, :content ["substring"]}]} {:tag :componentId, :attrs nil, :content ["isc_ReferenceDataModule$1_0"]} {:tag :appID, :attrs nil, :content ["builtinApplication"]} {:tag :operation, :attrs nil, :content ["LookupExpansion_DS_fetch"]}]}]}]} @legacy-auth/admin-cookie)) (defn index-lookups [lookups] (into {} (map (fn [[type ls]] [type (into {} (map (fn [l] [(get l "lookupCde") (get l "lookupDesc")]) ls))]) (group-by #(get % "lookupTypeTxt") lookups)))) (def lookups (index-lookups (get lookups-data "LookupExpansion_DS")))) (defn hydrate-contact [lookups user-raw-response] (m/search (assoc user-raw-response "lookups" lookups) {"lookups" {"Contact Detail" {?contactCde ?desc}} "UserInfoView_DS" [{"primaryContactId" ?primaryContactId}] "ContactDetail_DS" (m/scan {"contactCde" ?contactCde "contactId" ?contactId "emailOrPhoneTxt" ?emailOrPhoneTxt & ?rest})} (merge {:type ?desc :primary (= ?primaryContactId ?contactId)} ?rest (if (= ?desc "Email Address") {:address ?emailOrPhoneTxt} {:number ?emailOrPhoneTxt})))) (defn hydrate-addresses [user-raw-response] (m/search user-raw-response {"UserInfoView_DS" [{"primaryAddressId" ?primaryAddressId}] "AddressDetail_DS" (m/scan {"addressId" ?addressId & ?rest})} (conj {:primary (= ?primaryAddressId ?addressId)} ?rest))) (comment (hydrate-contact lookups iuser) (hydrate-addresses iuser)) (defn remove-nils-and-string-keys [m] (into {} (remove (fn [[k v]] (or (string? k) (nil? v))) m))) (def keys-mapping {"UserInfoView_DS" {"creationTsp" :account-creation-date, "statusDesc" :status, "roleDesc" :role, "loginNameNme" :login-name, "surnameNme" :surname, "otherNme" :other-name, "batchUploadViewCde" :batch-upload-access, "givenNme" :given-name, "userUid" :legacy-Uid, "reasonTxt" :reason-of-use, "restrictedViewingCde" :restricted-viewing-access, "dateAcceptedTcTsp" :terms-and-conditions-accepted-date} "ContactDetail_DS" {"contactCde" :type} "AddressDetail_DS" {"creationTsp" :supplied-date, "streetNme" :street-name, "countryNme" :country-name, "postcodeTxt" :postcode, "cityNme" :city, "streetNumberTxt" :street-number, "stateNme" :state}}) (comment (def contact (->> iuser (hydrate-contact lookups) (map #(clojure.set/rename-keys % (get keys-mapping "ContactDetail_DS"))) (map remove-nils-and-string-keys))) (def addresses (->> iuser hydrate-addresses (map #(clojure.set/rename-keys % (get keys-mapping "AddressDetail_DS"))) (map remove-nils-and-string-keys))) (def saved (-> iuser (get-in #_iuser ["UserInfoView_DS" 0]) #_(hydrate-user) (clojure.set/rename-keys (get keys-mapping "UserInfoView_DS")) remove-nils-and-string-keys)) saved (map #(malli/validate Schema %) contact) (map #(if (malli/validate address/Schema %) % (me/humanize (malli/explain address/Schema %))) addresses) iuser (map #(address/parse %) addresses) (get-in {"a" [1 2]} ["a" 0]) (collaborator saved)) ;store raw data
true
(ns glider.legacy.users (:require [clojure.data.xml :refer [emit-str]] #_[glider.event-store.core :as es] [glider.legacy.auth :as legacy-auth] [glider.legacy.transaction.users :as transactions] [glider.legacy.utils :as utils] [glider.system.command.core :as command] [meander.epsilon :as m] #_[glider.system :as system] [malli.provider :as mp] [malli.core :as malli] [malli.transform :as mt] [malli.error :as me] [glider.domain.collaborator.collaborator :refer [collaborator]] [glider.domain.collaborator.contact-method :refer [Schema]] [glider.domain.collaborator.address :as address] [malli.util :as mu] [java-time :as time] [editscript.core :as diff] [lib.editscript.core :as editscript] [glider.utils :refer [uuid timestamp]] [glider.db :refer [select! insert! execute!]] [crypto.password.bcrypt :as crypto] [clojure.core.async :as cca] [glider.system.operation.core :as operation] [clojure.walk :refer [postwalk]])) ;; Aggregate ;; Handling users management sync with legacy system. (defn get-all-users! "Fetch all users, return a lazy seq" [cookie] (println "get all users") (-> (utils/request2! (transactions/all-users-transaction) cookie) first :data)) (comment (transactions/all-users-transaction) (def all-users (future (get-all-users! @legacy-auth/admin-cookie))) (def all-userUid (map #(str (get % "userUid")) (-> @all-users first :data))) ) (defn fetch-user-details! [user-id cookie] (utils/request2! (transactions/user-details user-id) cookie)) (defn import-user-by-userUid! [user-id cookie] (let [res (fetch-user-details! user-id cookie)] res)) (def refresh-cookie [:cookie (fn [ctx] (legacy-auth/refresh-cookie))]) (def legacy-cookie [:cookie (fn [ctx] (let [previous-request (count (filter #{:cookie} (:execute/stack ctx)))] (case previous-request 0 @legacy-auth/admin-cookie 1 (legacy-auth/refresh-cookie) (throw (ex-info "Authentication loop" ctx)))))]) (defn import-user [{{cookie :cookie} :cofx {:keys [userUid username]} :params :as ctx}] (try (fetch-user-details! userUid cookie) (catch clojure.lang.ExceptionInfo e (if (= :cookie-expired (:type (ex-data e))) (command/enqueue ctx legacy-cookie) (throw e))))) (defn import-users-list! [{{cookie :cookie} :cofx :as ctx}] (try (get-all-users! cookie) (catch clojure.lang.ExceptionInfo e (if (= :cookie-expired (:type (ex-data e))) (doto (command/enqueue ctx legacy-cookie) tap>) (throw e))))) (defn legacy-user-synchronized-event [data userUid version] {:id (uuid) :type :legacy-user-synchronized :stream-id userUid :created-at (timestamp) :version version :payload data}) (defn diff-payload [saved imported] (try (let [saved-by-operation (into {} (map (juxt :operation identity) saved))] (if saved (->> imported (map (fn [{operation :operation :as i}] (update i :data #(editscript/diff->edits (:data (get saved-by-operation operation)) %)))) (remove #(empty? (:data %))) vec) imported)) (catch Exception e (println "diff failled, why ?") (tap> saved) (tap> imported) (throw e)))) (comment (diff-payload [{:operation {:content [{:content [{:content ["34"] :attrs nil :tag :userUid}] :attrs {:xsi:type "xsd:Object"} :tag :criteria} {:content [{:content ["UserInfoView_DS"] :attrs nil :tag :dataSource} {:content ["fetch"] :attrs nil :tag :operationType}] :attrs {:xsi:type "xsd:Object"} :tag :operationConfig} {:content ["builtinApplication"] :attrs nil :tag :appID} {:content ["userInfoById"] :attrs nil :tag :operation}] :attrs {:xsi:type "xsd:Object"} :tag :elem} :data-source "UserInfoView_DS" :data [{"confirmUserPasswordTxt" nil "creationTsp" 1313416800000 "preferredContactMethodCde" "pcme" "statusCde" "active" "nameId" 34 "organisationId" 99 "modifiedTsp" 1469664556170 "changePasswordCde" "false" "fullName" "PI:NAME:<NAME>END_PI" "statusDesc" "Active" "organisationNme" "Golden Plains Shire Council" "roleDesc" "Contributor" "primaryAddressId" 1 "roleCde" "con" "primaryContactId" 3445 "loginNameNme" "PI:NAME:<NAME>END_PI" "surnameNme" "PI:NAME:<NAME>END_PI" "otherNme" nil "batchUploadViewCde" "false" "givenNme" "PI:NAME:<NAME>END_PI" "lastSystemAccessTsp" 1469664556138 "userUid" 34 "reasonTxt" "LGA user" "restrictedViewingCde" "false" "dateAcceptedTcTsp" nil}]} {:operation {:content [{:content [{:content ["34"] :attrs {:xsi:type "xsd:long"} :tag :USER_UID}] :attrs {:xsi:type "xsd:Object"} :tag :criteria} {:content [{:content ["AddressDetail_DS"] :attrs nil :tag :dataSource} {:content ["fetch"] :attrs nil :tag :operationType} {:content ["exact"] :attrs nil :tag :textMatchStyle}] :attrs {:xsi:type "xsd:Object"} :tag :operationConfig} {:content ["isc_ListGrid_1"] :attrs nil :tag :componentId} {:content ["builtinApplication"] :attrs nil :tag :appID} {:content ["fetchUserAddresses"] :attrs nil :tag :operation}] :attrs {:xsi:type "xsd:Object"} :tag :elem} :data-source "AddressDetail_DS" :data [{"addressId" 1 "creationTsp" 1313416800000 "mainAddressId" "" "modifiedTsp" nil "streetNme" nil "countryNme" nil "postcodeTxt" nil "cityNme" nil "streetNumberTxt" nil "stateNme" nil} {"addressId" 1832 "creationTsp" 1469084015579 "mainAddressId" "" "modifiedTsp" nil "streetNme" "P. O. Box 111" "countryNme" "Australia" "postcodeTxt" "3328" "cityNme" "Bannockburn" "streetNumberTxt" nil "stateNme" "VIC"}]} {:operation {:content [{:content [{:content ["34"] :attrs {:xsi:type "xsd:long"} :tag :USER_UID}] :attrs {:xsi:type "xsd:Object"} :tag :criteria} {:content [{:content ["ContactDetail_DS"] :attrs nil :tag :dataSource} {:content ["fetch"] :attrs nil :tag :operationType} {:content ["exact"] :attrs nil :tag :textMatchStyle}] :attrs {:xsi:type "xsd:Object"} :tag :operationConfig} {:content ["isc_ListGrid_2"] :attrs nil :tag :componentId} {:content ["builtinApplication"] :attrs nil :tag :appID} {:content ["fetchContactByUserUid"] :attrs nil :tag :operation}] :attrs {:xsi:type "xsd:Object"} :tag :elem} :data-source "ContactDetail_DS" :data [{"creationTsp" nil "contactCde" nil "emailOrPhoneTxt" nil "modifiedTsp" nil "contactId" 1} {"creationTsp" 1469069246595 "contactCde" "cde" "emailOrPhoneTxt" "PI:EMAIL:<EMAIL>END_PI" "modifiedTsp" nil "contactId" 3445}]}] [{:data [{"confirmUserPasswordTxt" nil "creationTsp" 1313416800000 "preferredContactMethodCde" "pcme" "statusCde" "active" "nameId" 34 "organisationId" 99 "modifiedTsp" 1469664556170 "changePasswordCde" "false" "fullName" "PI:NAME:<NAME>END_PI" "statusDesc" "Active" "organisationNme" "Golden Plains Shire Council" "roleDesc" "Contributor" "primaryAddressId" 1 "roleCde" "con" "primaryContactId" 3445 "loginNameNme" "PI:NAME:<NAME>END_PI" "surnameNme" "PI:NAME:<NAME>END_PI" "otherNme" nil "batchUploadViewCde" "false" "givenNme" "PI:NAME:<NAME>END_PI" "lastSystemAccessTsp" 1469664556138 "userUid" 34 "reasonTxt" "LGA user" "restrictedViewingCde" "false" "dateAcceptedTcTsp" nil}] :operation {:tag :elem :attrs {:xsi:type "xsd:Object"} :content [{:tag :criteria :attrs {:xsi:type "xsd:Object"} :content [{:tag :userUid :attrs nil :content ["34"]}]} {:tag :operationConfig :attrs {:xsi:type "xsd:Object"} :content [{:tag :dataSource :attrs nil :content ["UserInfoView_DS"]} {:tag :operationType :attrs nil :content ["fetch"]}]} {:tag :appID :attrs nil :content ["builtinApplication"]} {:tag :operation :attrs nil :content ["userInfoById"]}]}} {:data [{"addressId" 1832 "creationTsp" 1469084015579 "mainAddressId" "" "modifiedTsp" nil "streetNme" "P. O. Box 111" "countryNme" "Australia" "postcodeTxt" "3328" "cityNme" "Bannockburn" "streetNumberTxt" nil "stateNme" "VIC"} {"addressId" 1 "creationTsp" 1313416800000 "mainAddressId" "" "modifiedTsp" nil "streetNme" nil "countryNme" nil "postcodeTxt" nil "cityNme" nil "streetNumberTxt" nil "stateNme" nil}] :operation {:tag :elem :attrs {:xsi:type "xsd:Object"} :content [{:tag :criteria :attrs {:xsi:type "xsd:Object"} :content [{:tag :USER_UID :attrs {:xsi:type "xsd:long"} :content ["34"]}]} {:tag :operationConfig :attrs {:xsi:type "xsd:Object"} :content [{:tag :dataSource :attrs nil :content ["AddressDetail_DS"]} {:tag :operationType :attrs nil :content ["fetch"]} {:tag :textMatchStyle :attrs nil :content ["exact"]}]} {:tag :componentId :attrs nil :content ["isc_ListGrid_1"]} {:tag :appID :attrs nil :content ["builtinApplication"]} {:tag :operation :attrs nil :content ["fetchUserAddresses"]}]}} {:data [{"contactCde" nil "contactId" 1 "creationTsp" nil "emailOrPhoneTxt" nil "modifiedTsp" nil} {"contactCde" "cde" "contactId" 3445 "creationTsp" 1469069246595 "emailOrPhoneTxt" "PI:EMAIL:<EMAIL>END_PI" "modifiedTsp" nil}] :operation {:tag :elem :attrs {:xsi:type "xsd:Object"} :content [{:tag :criteria :attrs {:xsi:type "xsd:Object"} :content [{:tag :USER_UID :attrs {:xsi:type "xsd:long"} :content ["34"]}]} {:tag :operationConfig :attrs {:xsi:type "xsd:Object"} :content [{:tag :dataSource :attrs nil :content ["ContactDetail_DS"]} {:tag :operationType :attrs nil :content ["fetch"]} {:tag :textMatchStyle :attrs nil :content ["exact"]}]} {:tag :componentId :attrs nil :content ["isc_ListGrid_2"]} {:tag :appID :attrs nil :content ["builtinApplication"]} {:tag :operation :attrs nil :content ["fetchContactByUserUid"]}]}}])) ;;Import users from legacy app (defn fetch-saved-user-stream [userUid] (select! ["SELECT * FROM legacy_events WHERE stream_id = ? ORDER BY version" userUid])) (defn merge-diffs "Merge a stream of diff, return nil if passed empty vector" [stream] (reduce (fn ([]) ([a b] (mapv (fn [{operation :operation :as payload}] (let [data-b (:data (first (get (group-by :operation b) operation)))] (cond-> payload (and (some? data-b) (diff/valid-edits? data-b)) (update :data #(diff/patch % (diff/edits->script data-b)))))) a))) (map :payload stream))) (defn extract-credentials [user-data] (m/find user-data (m/scan {:data [{"userPasswordTxt" ?password "loginNameNme" ?login}]}) {:password ?password :login ?login})) (defn remove-key [user-data key] (clojure.walk/postwalk #(when-not (and (vector? %) (= (first %) key)) %) user-data)) (defn fetch-saved-user-password [userUid] (first (select! ["SELECT * FROM authentication WHERE legacy_uid = ?" userUid]))) (defn fetch-credentials [{:keys [login uuid legacy-uid]}] (first (select! ["SELECT * FROM authentication WHERE uuid = ? OR login = ? OR legacy_uid = ?" uuid login legacy-uid]))) (defn upsert-authentication-credentials! [{:keys [uuid login legacy-uid] :as credentials} {db :db}] (let [exist (fetch-credentials credentials)] (when exist (execute! db ["DELETE FROM authentication WHERE uuid = ? OR login = ? OR legacy_uid = ?" uuid login legacy-uid])) (insert! db :authentication credentials))) (defn valid-credentials? [{:keys [password login uuid] :as credentials}] (let [{encrypted-passwrod :authentication/password} (fetch-credentials credentials)] (crypto/check password encrypted-passwrod))) (defn password-changed [saved new] (cond (and (nil? saved) (string? new)) new (and (string? saved) (string? new) (not (crypto/check new saved))) new)) (defn user-exists? [imported-user] (not-every? (fn [{data :data}] (or (= data nil) (= data []))) imported-user)) (def import-user-command {:id ::import-user :params [:map [:userUid :string]] :coeffects [legacy-cookie [:saved-user-stream (fn [{{:keys [userUid]} :params}] (fetch-saved-user-stream userUid))] [:saved-user-password (fn [{{:keys [userUid]} :params}] (:password (fetch-saved-user-password userUid)))] [:imported-user import-user]] :conditions [[(fn [{{:keys [imported-user]} :cofx}] (user-exists? imported-user)) :not-found "User with this id does not exist"]] :effects (fn [{{:keys [saved-user-stream imported-user saved-user-password]} :cofx {:keys [userUid]} :params}] (println userUid) (tap> saved-user-stream) (tap> imported-user) (tap> saved-user-password) (let [{password :PI:PASSWORD:<PASSWORD>END_PI login :login} (extract-credentials imported-user) saved-user (merge-diffs saved-user-stream) next-version (-> saved-user-stream last (get :version 0) inc) data-diff (diff-payload saved-user (mapv #(select-keys % [:data :operation]) (remove-key imported-user "userPasswordTxt"))) new-password (password-changed PI:PASSWORD:<PASSWORD>END_PI password)] {:save-legacy-event (when-not (empty? data-diff) {:id (uuid) :type :legacy-user-synchronized :stream-id userUid :created-at (timestamp) :version next-version :payload data-diff}) :save-credentials (when new-password {:login login :legacy-uid userUid :password (crypto/encrypt PI:PASSWORD:<PASSWORD>END_PI)})})) :handler {:save-legacy-event (fn [payload environment] (insert! (:db environment) :legacy-events payload)) :save-credentials upsert-authentication-credentials!} :return #(select-keys % [:side-effects]) :produce [:map [:side-effects [:map [:save-legacy-event [:or map? nil?] :save-credentials [:or map? nil?]]]]]}) (defn fetch-users [{{:keys [cookie users-list]} :cofx :as ctx}] (reduce (fn [acc id] (let [user (fetch-user-details! id cookie)] (operation/update! (get-in ctx [:environment :db]) (update-in (:operation ctx) [:metadata :users-fetched] (fnil inc 0))) (conj acc user))) [] (map #(get % "userUid") users-list))) (def import-users-command {:id ::import-users :coeffects [legacy-cookie [:users-list import-users-list!] [:update-operation (fn [{{:keys [users-list]} :cofx :as ctx}] (operation/update! (get-in ctx [:environment :db]) (assoc-in (:operation ctx) [:metadata :users-to-fetch] (count users-list))))] [:fetch-users fetch-users]] :return identity}) (comment (command/run! import-users-command) ) (comment (def ev (command/run! import-user-command {:userUid "16"} {:environment {:db @glider.db/datasource}} #_{:side-effects false})) (def iuser (import-user-by-userUid! "10660" @legacy-auth/admin-cookie)) (legacy-auth/refresh-cookie) (execute! ["DELETE FROM legacy_events WHERE stream_id = ?" "10660"]) (def re (first (select! ["SELECT * FROM legacy_events WHERE stream_id = ?" "10660"]))) ;; Test that merging all update bring aggregate to same state as current. (= (mapv #(dissoc % :operation) (:res iuser)) (merge-diffs (fetch-saved-user-stream "10660"))) (-> "10660" fetch-saved-user-stream merge-diffs) (count (fetch-saved-user-stream "10660")) (def lookups-data (utils/request! {:tag :transaction :attrsiy {:xsi:type "xsd:Object", :xmlns:xsi "http://www.w3.org/2000/10/XMLSchema-instance"}, :content [{:tag :operations, :attrs {:xsi:type "xsd:List"}, :content [{:tag :elem, :attrs {:xsi:type "xsd:Object"}, :content [{:tag :criteria, :attrs {:xsi:type "xsd:Object"}, :content nil} {:tag :operationConfig, :attrs {:xsi:type "xsd:Object"}, :content [{:tag :dataSource, :attrs nil, :content ["LookupExpansion_DS"]} {:tag :operationType, :attrs nil, :content ["fetch"]} {:tag :textMatchStyle, :attrs nil, :content ["substring"]}]} {:tag :componentId, :attrs nil, :content ["isc_ReferenceDataModule$1_0"]} {:tag :appID, :attrs nil, :content ["builtinApplication"]} {:tag :operation, :attrs nil, :content ["LookupExpansion_DS_fetch"]}]}]}]} @legacy-auth/admin-cookie)) (defn index-lookups [lookups] (into {} (map (fn [[type ls]] [type (into {} (map (fn [l] [(get l "lookupCde") (get l "lookupDesc")]) ls))]) (group-by #(get % "lookupTypeTxt") lookups)))) (def lookups (index-lookups (get lookups-data "LookupExpansion_DS")))) (defn hydrate-contact [lookups user-raw-response] (m/search (assoc user-raw-response "lookups" lookups) {"lookups" {"Contact Detail" {?contactCde ?desc}} "UserInfoView_DS" [{"primaryContactId" ?primaryContactId}] "ContactDetail_DS" (m/scan {"contactCde" ?contactCde "contactId" ?contactId "emailOrPhoneTxt" ?emailOrPhoneTxt & ?rest})} (merge {:type ?desc :primary (= ?primaryContactId ?contactId)} ?rest (if (= ?desc "Email Address") {:address ?emailOrPhoneTxt} {:number ?emailOrPhoneTxt})))) (defn hydrate-addresses [user-raw-response] (m/search user-raw-response {"UserInfoView_DS" [{"primaryAddressId" ?primaryAddressId}] "AddressDetail_DS" (m/scan {"addressId" ?addressId & ?rest})} (conj {:primary (= ?primaryAddressId ?addressId)} ?rest))) (comment (hydrate-contact lookups iuser) (hydrate-addresses iuser)) (defn remove-nils-and-string-keys [m] (into {} (remove (fn [[k v]] (or (string? k) (nil? v))) m))) (def keys-mapping {"UserInfoView_DS" {"creationTsp" :account-creation-date, "statusDesc" :status, "roleDesc" :role, "loginNameNme" :login-name, "surnameNme" :surname, "otherNme" :other-name, "batchUploadViewCde" :batch-upload-access, "givenNme" :given-name, "userUid" :legacy-Uid, "reasonTxt" :reason-of-use, "restrictedViewingCde" :restricted-viewing-access, "dateAcceptedTcTsp" :terms-and-conditions-accepted-date} "ContactDetail_DS" {"contactCde" :type} "AddressDetail_DS" {"creationTsp" :supplied-date, "streetNme" :street-name, "countryNme" :country-name, "postcodeTxt" :postcode, "cityNme" :city, "streetNumberTxt" :street-number, "stateNme" :state}}) (comment (def contact (->> iuser (hydrate-contact lookups) (map #(clojure.set/rename-keys % (get keys-mapping "ContactDetail_DS"))) (map remove-nils-and-string-keys))) (def addresses (->> iuser hydrate-addresses (map #(clojure.set/rename-keys % (get keys-mapping "AddressDetail_DS"))) (map remove-nils-and-string-keys))) (def saved (-> iuser (get-in #_iuser ["UserInfoView_DS" 0]) #_(hydrate-user) (clojure.set/rename-keys (get keys-mapping "UserInfoView_DS")) remove-nils-and-string-keys)) saved (map #(malli/validate Schema %) contact) (map #(if (malli/validate address/Schema %) % (me/humanize (malli/explain address/Schema %))) addresses) iuser (map #(address/parse %) addresses) (get-in {"a" [1 2]} ["a" 0]) (collaborator saved)) ;store raw data
[ { "context": "unt_name\"]})))\n (is (= {:extra {:account_name \"broad_gcid-srv\" :workspace_name \"SARSCoV2-Illumina-Full\"}}\n ", "end": 919, "score": 0.8304071426391602, "start": 908, "tag": "KEY", "value": "broad_gcid-" } ]
api/test/wfl/unit/sink_test.clj
broadinstitute/wfl
15
(ns wfl.unit.sink-test (:require [clojure.test :refer [deftest is]] [wfl.sink :as sink] [wfl.tools.endpoints :refer [coercion-tester]] [wfl.tools.resources :as resources] [wfl.util :refer [uuid-nil]]) (:import [java.util UUID] [clojure.lang ExceptionInfo])) (deftest test-rename-gather (let [inputs (resources/read-resource "sarscov2_illumina_full/inputs.edn")] (is (= {:workspace_name "SARSCoV2-Illumina-Full"} (sink/rename-gather inputs {:workspace_name "$SARSCoV2-Illumina-Full"}))) (is (= {:instrument_model "Illumina NovaSeq 6000"} (sink/rename-gather inputs {:instrument_model "instrument_model"}))) (is (= {:extra ["broad_gcid-srv"]} (sink/rename-gather inputs {:extra ["package_genbank_ftp_submission.account_name"]}))) (is (= {:extra {:account_name "broad_gcid-srv" :workspace_name "SARSCoV2-Illumina-Full"}} (sink/rename-gather inputs {:extra {:account_name "package_genbank_ftp_submission.account_name" :workspace_name "$SARSCoV2-Illumina-Full"}}))))) (deftest test-rename-gather-bulk (let [inputs (resources/read-resource "sarscov2_illumina_full/inputs.edn") dataset (resources/read-resource "sarscov2-illumina-full-inputs.json") result (sink/rename-gather-bulk (UUID/randomUUID) dataset "flowcell" inputs {:flowcell_tgz "flowcell_tgz" :flowcell_id "flowcell_id" :sample_rename_map "sample_rename_map"})] (is (= (:flowcell_id inputs) (:flowcell_id result))) (is (= (:flowcell_tgz inputs) (-> result :flowcell_tgz :sourcePath))) (is (nil? (:sample_rename_map result))))) (def ^:private workspace-sink-request {:name @#'sink/terra-workspace-sink-name :workspace "namespace/name" :entityType "tablename" :identifier "sample_id" :fromOutputs {}}) (def ^:private datarepo-sink-request {:name @#'sink/datarepo-sink-name :dataset (str uuid-nil) :table "tablename" :fromOutputs {}}) (deftest test-workspace-sink-request-coercion (let [test! (coercion-tester ::sink/sink)] (test! workspace-sink-request))) (deftest test-datarepo-sink-request-coercion (let [test! (coercion-tester ::sink/sink)] (test! datarepo-sink-request))) (deftest test-throw-or-entity-name-from-workspace (let [inputs {:a "aInput" :b "bInput"} outputs {:b "bOutput" :c "cOutput"} workflow {:inputs inputs :outputs outputs} msg (re-pattern sink/entity-name-not-found-error-message)] (is (thrown-with-msg? ExceptionInfo msg (#'sink/throw-or-entity-name-from-workflow nil {:identifier "a"})) "When nil workflow, should throw") (is (thrown-with-msg? ExceptionInfo msg (#'sink/throw-or-entity-name-from-workflow (select-keys workflow [:inputs]) {:identifier "c"})) "When no outputs, should only check inputs") (is (thrown-with-msg? ExceptionInfo msg (#'sink/throw-or-entity-name-from-workflow (select-keys workflow [:outputs]) {:identifier "a"})) "When no inputs, should only check outputs") (is (= "aInput" (#'sink/throw-or-entity-name-from-workflow workflow {:identifier "a"})) "Key a only present in inputs map") (is (= "bOutput" (#'sink/throw-or-entity-name-from-workflow workflow {:identifier "b"})) "Key b present in both inputs and outputs maps should pull from outputs map") (is (= "cOutput" (#'sink/throw-or-entity-name-from-workflow workflow {:identifier "c"})) "Key c only present in outputs map") (is (thrown-with-msg? ExceptionInfo msg (#'sink/throw-or-entity-name-from-workflow workflow {:identifier "d"})) "Key d not found in inputs or outputs maps should throw")))
66379
(ns wfl.unit.sink-test (:require [clojure.test :refer [deftest is]] [wfl.sink :as sink] [wfl.tools.endpoints :refer [coercion-tester]] [wfl.tools.resources :as resources] [wfl.util :refer [uuid-nil]]) (:import [java.util UUID] [clojure.lang ExceptionInfo])) (deftest test-rename-gather (let [inputs (resources/read-resource "sarscov2_illumina_full/inputs.edn")] (is (= {:workspace_name "SARSCoV2-Illumina-Full"} (sink/rename-gather inputs {:workspace_name "$SARSCoV2-Illumina-Full"}))) (is (= {:instrument_model "Illumina NovaSeq 6000"} (sink/rename-gather inputs {:instrument_model "instrument_model"}))) (is (= {:extra ["broad_gcid-srv"]} (sink/rename-gather inputs {:extra ["package_genbank_ftp_submission.account_name"]}))) (is (= {:extra {:account_name "<KEY>srv" :workspace_name "SARSCoV2-Illumina-Full"}} (sink/rename-gather inputs {:extra {:account_name "package_genbank_ftp_submission.account_name" :workspace_name "$SARSCoV2-Illumina-Full"}}))))) (deftest test-rename-gather-bulk (let [inputs (resources/read-resource "sarscov2_illumina_full/inputs.edn") dataset (resources/read-resource "sarscov2-illumina-full-inputs.json") result (sink/rename-gather-bulk (UUID/randomUUID) dataset "flowcell" inputs {:flowcell_tgz "flowcell_tgz" :flowcell_id "flowcell_id" :sample_rename_map "sample_rename_map"})] (is (= (:flowcell_id inputs) (:flowcell_id result))) (is (= (:flowcell_tgz inputs) (-> result :flowcell_tgz :sourcePath))) (is (nil? (:sample_rename_map result))))) (def ^:private workspace-sink-request {:name @#'sink/terra-workspace-sink-name :workspace "namespace/name" :entityType "tablename" :identifier "sample_id" :fromOutputs {}}) (def ^:private datarepo-sink-request {:name @#'sink/datarepo-sink-name :dataset (str uuid-nil) :table "tablename" :fromOutputs {}}) (deftest test-workspace-sink-request-coercion (let [test! (coercion-tester ::sink/sink)] (test! workspace-sink-request))) (deftest test-datarepo-sink-request-coercion (let [test! (coercion-tester ::sink/sink)] (test! datarepo-sink-request))) (deftest test-throw-or-entity-name-from-workspace (let [inputs {:a "aInput" :b "bInput"} outputs {:b "bOutput" :c "cOutput"} workflow {:inputs inputs :outputs outputs} msg (re-pattern sink/entity-name-not-found-error-message)] (is (thrown-with-msg? ExceptionInfo msg (#'sink/throw-or-entity-name-from-workflow nil {:identifier "a"})) "When nil workflow, should throw") (is (thrown-with-msg? ExceptionInfo msg (#'sink/throw-or-entity-name-from-workflow (select-keys workflow [:inputs]) {:identifier "c"})) "When no outputs, should only check inputs") (is (thrown-with-msg? ExceptionInfo msg (#'sink/throw-or-entity-name-from-workflow (select-keys workflow [:outputs]) {:identifier "a"})) "When no inputs, should only check outputs") (is (= "aInput" (#'sink/throw-or-entity-name-from-workflow workflow {:identifier "a"})) "Key a only present in inputs map") (is (= "bOutput" (#'sink/throw-or-entity-name-from-workflow workflow {:identifier "b"})) "Key b present in both inputs and outputs maps should pull from outputs map") (is (= "cOutput" (#'sink/throw-or-entity-name-from-workflow workflow {:identifier "c"})) "Key c only present in outputs map") (is (thrown-with-msg? ExceptionInfo msg (#'sink/throw-or-entity-name-from-workflow workflow {:identifier "d"})) "Key d not found in inputs or outputs maps should throw")))
true
(ns wfl.unit.sink-test (:require [clojure.test :refer [deftest is]] [wfl.sink :as sink] [wfl.tools.endpoints :refer [coercion-tester]] [wfl.tools.resources :as resources] [wfl.util :refer [uuid-nil]]) (:import [java.util UUID] [clojure.lang ExceptionInfo])) (deftest test-rename-gather (let [inputs (resources/read-resource "sarscov2_illumina_full/inputs.edn")] (is (= {:workspace_name "SARSCoV2-Illumina-Full"} (sink/rename-gather inputs {:workspace_name "$SARSCoV2-Illumina-Full"}))) (is (= {:instrument_model "Illumina NovaSeq 6000"} (sink/rename-gather inputs {:instrument_model "instrument_model"}))) (is (= {:extra ["broad_gcid-srv"]} (sink/rename-gather inputs {:extra ["package_genbank_ftp_submission.account_name"]}))) (is (= {:extra {:account_name "PI:KEY:<KEY>END_PIsrv" :workspace_name "SARSCoV2-Illumina-Full"}} (sink/rename-gather inputs {:extra {:account_name "package_genbank_ftp_submission.account_name" :workspace_name "$SARSCoV2-Illumina-Full"}}))))) (deftest test-rename-gather-bulk (let [inputs (resources/read-resource "sarscov2_illumina_full/inputs.edn") dataset (resources/read-resource "sarscov2-illumina-full-inputs.json") result (sink/rename-gather-bulk (UUID/randomUUID) dataset "flowcell" inputs {:flowcell_tgz "flowcell_tgz" :flowcell_id "flowcell_id" :sample_rename_map "sample_rename_map"})] (is (= (:flowcell_id inputs) (:flowcell_id result))) (is (= (:flowcell_tgz inputs) (-> result :flowcell_tgz :sourcePath))) (is (nil? (:sample_rename_map result))))) (def ^:private workspace-sink-request {:name @#'sink/terra-workspace-sink-name :workspace "namespace/name" :entityType "tablename" :identifier "sample_id" :fromOutputs {}}) (def ^:private datarepo-sink-request {:name @#'sink/datarepo-sink-name :dataset (str uuid-nil) :table "tablename" :fromOutputs {}}) (deftest test-workspace-sink-request-coercion (let [test! (coercion-tester ::sink/sink)] (test! workspace-sink-request))) (deftest test-datarepo-sink-request-coercion (let [test! (coercion-tester ::sink/sink)] (test! datarepo-sink-request))) (deftest test-throw-or-entity-name-from-workspace (let [inputs {:a "aInput" :b "bInput"} outputs {:b "bOutput" :c "cOutput"} workflow {:inputs inputs :outputs outputs} msg (re-pattern sink/entity-name-not-found-error-message)] (is (thrown-with-msg? ExceptionInfo msg (#'sink/throw-or-entity-name-from-workflow nil {:identifier "a"})) "When nil workflow, should throw") (is (thrown-with-msg? ExceptionInfo msg (#'sink/throw-or-entity-name-from-workflow (select-keys workflow [:inputs]) {:identifier "c"})) "When no outputs, should only check inputs") (is (thrown-with-msg? ExceptionInfo msg (#'sink/throw-or-entity-name-from-workflow (select-keys workflow [:outputs]) {:identifier "a"})) "When no inputs, should only check outputs") (is (= "aInput" (#'sink/throw-or-entity-name-from-workflow workflow {:identifier "a"})) "Key a only present in inputs map") (is (= "bOutput" (#'sink/throw-or-entity-name-from-workflow workflow {:identifier "b"})) "Key b present in both inputs and outputs maps should pull from outputs map") (is (= "cOutput" (#'sink/throw-or-entity-name-from-workflow workflow {:identifier "c"})) "Key c only present in outputs map") (is (thrown-with-msg? ExceptionInfo msg (#'sink/throw-or-entity-name-from-workflow workflow {:identifier "d"})) "Key d not found in inputs or outputs maps should throw")))
[ { "context": ")))\n\n(defn new-user [user password]\n (let [pass (salt-password password)]\n (j/insert! @database \"aut", "end": 813, "score": 0.5364108681678772, "start": 809, "tag": "PASSWORD", "value": "salt" }, { "context": "(defn new-user [user password]\n (let [pass (salt-password password)]\n (j/insert! @database \"auth.authori", "end": 822, "score": 0.628057599067688, "start": 814, "tag": "PASSWORD", "value": "password" }, { "context": "efn verify-password [user password]\n (let [pass (salt-password password)\n r (j/query @database\n [\"SELEC", "end": 982, "score": 0.8168348073959351, "start": 960, "tag": "PASSWORD", "value": "salt-password password" }, { "context": "efn change-password [user password]\n (let [pass (salt-password password)]\n (j/update! @database \"aut", "end": 1240, "score": 0.5824467539787292, "start": 1236, "tag": "PASSWORD", "value": "salt" }, { "context": "hange-password [user password]\n (let [pass (salt-password password)]\n (j/update! @database \"auth.authori", "end": 1249, "score": 0.5221796631813049, "start": 1241, "tag": "PASSWORD", "value": "password" } ]
auth/src/db/db.clj
raymondpoling/rerun-tv
0
(ns db.db (:require [clojure.java.jdbc :as j]) (:import java.security.MessageDigest)) (def database (atom {:dbtype "mysql" :dbname "auth" :user nil :password nil :serverTimezone "America/New_York"})) (defn initialize ([] (swap! database (fn [_ s] s) {:dbtype "h2:mem" :dbname "auth"})) ([name password host port] (swap! database merge {:user name :password password :host host :port port}))) (defn sha256 [salt] (fn [password] (let [string (str password salt) digest (.digest (MessageDigest/getInstance "SHA-256") (.getBytes string "UTF-8"))] (apply str (map (partial format "%02x") digest))))) (def salt-password (sha256 (or (System/getenv "SALT") "SALTED"))) (defn new-user [user password] (let [pass (salt-password password)] (j/insert! @database "auth.authorize" {:user user :password pass}))) (defn verify-password [user password] (let [pass (salt-password password) r (j/query @database ["SELECT authorize.user FROM auth.authorize WHERE authorize.user = ? AND password = ?" user pass ])] (= 1 (count r)))) (defn change-password [user password] (let [pass (salt-password password)] (j/update! @database "auth.authorize" {:password pass} ["authorize.user = ?" user])))
101065
(ns db.db (:require [clojure.java.jdbc :as j]) (:import java.security.MessageDigest)) (def database (atom {:dbtype "mysql" :dbname "auth" :user nil :password nil :serverTimezone "America/New_York"})) (defn initialize ([] (swap! database (fn [_ s] s) {:dbtype "h2:mem" :dbname "auth"})) ([name password host port] (swap! database merge {:user name :password password :host host :port port}))) (defn sha256 [salt] (fn [password] (let [string (str password salt) digest (.digest (MessageDigest/getInstance "SHA-256") (.getBytes string "UTF-8"))] (apply str (map (partial format "%02x") digest))))) (def salt-password (sha256 (or (System/getenv "SALT") "SALTED"))) (defn new-user [user password] (let [pass (<PASSWORD>-<PASSWORD> password)] (j/insert! @database "auth.authorize" {:user user :password pass}))) (defn verify-password [user password] (let [pass (<PASSWORD>) r (j/query @database ["SELECT authorize.user FROM auth.authorize WHERE authorize.user = ? AND password = ?" user pass ])] (= 1 (count r)))) (defn change-password [user password] (let [pass (<PASSWORD>-<PASSWORD> password)] (j/update! @database "auth.authorize" {:password pass} ["authorize.user = ?" user])))
true
(ns db.db (:require [clojure.java.jdbc :as j]) (:import java.security.MessageDigest)) (def database (atom {:dbtype "mysql" :dbname "auth" :user nil :password nil :serverTimezone "America/New_York"})) (defn initialize ([] (swap! database (fn [_ s] s) {:dbtype "h2:mem" :dbname "auth"})) ([name password host port] (swap! database merge {:user name :password password :host host :port port}))) (defn sha256 [salt] (fn [password] (let [string (str password salt) digest (.digest (MessageDigest/getInstance "SHA-256") (.getBytes string "UTF-8"))] (apply str (map (partial format "%02x") digest))))) (def salt-password (sha256 (or (System/getenv "SALT") "SALTED"))) (defn new-user [user password] (let [pass (PI:PASSWORD:<PASSWORD>END_PI-PI:PASSWORD:<PASSWORD>END_PI password)] (j/insert! @database "auth.authorize" {:user user :password pass}))) (defn verify-password [user password] (let [pass (PI:PASSWORD:<PASSWORD>END_PI) r (j/query @database ["SELECT authorize.user FROM auth.authorize WHERE authorize.user = ? AND password = ?" user pass ])] (= 1 (count r)))) (defn change-password [user password] (let [pass (PI:PASSWORD:<PASSWORD>END_PI-PI:PASSWORD:<PASSWORD>END_PI password)] (j/update! @database "auth.authorize" {:password pass} ["authorize.user = ?" user])))
[ { "context": " {:class \"\"}\"Copyright 2021\"]\n [:div {:class \"\"}\"Chris Farnham \" [:a {:class \"underline\" :href \"mailto:chris.fa", "end": 1565, "score": 0.9998739957809448, "start": 1552, "tag": "NAME", "value": "Chris Farnham" }, { "context": " Farnham \" [:a {:class \"underline\" :href \"mailto:chris.farnham@gmail.com\"}]]\n [:div {:class \"\"}[:a {:class \"underline\" :h", "end": 1630, "score": 0.9999162554740906, "start": 1607, "tag": "EMAIL", "value": "chris.farnham@gmail.com" }, { "context": "underline\" :href \"https://www.paypal.com/paypalme/chrisfarnham\"} \"Donate\"]]\n [:div {:class \"\"} \"Source code ava", "end": 1729, "score": 0.9991964101791382, "start": 1717, "tag": "USERNAME", "value": "chrisfarnham" }, { "context": "[:a {:class \"underline\" :href \"https://github.com/chrisfarnham/diceandclocks\"} \"github\"]\n \" under the MIT Lice", "end": 1856, "score": 0.9991042017936707, "start": 1844, "tag": "USERNAME", "value": "chrisfarnham" }, { "context": "t itch.io\"] \" for the cool clock images\"]\n [:li \"Henry Widd's blog post, \\\"\"[:a {:class \"underline\" :href \"ht", "end": 2272, "score": 0.9546225666999817, "start": 2262, "tag": "NAME", "value": "Henry Widd" }, { "context": "uct of One Seven Design, developed and authored by John Harper, and licensed for our use under the \" [:a {:href ", "end": 2820, "score": 0.9997578263282776, "start": 2809, "tag": "NAME", "value": "John Harper" } ]
src/dice_and_clocks/intro_view.cljs
chrisfarnham/diceandclocks
3
(ns dice-and-clocks.intro-view (:require [dice-and-clocks.clocks :as clocks])) (defn intro-view [sign-in] [:div {:class "container mx-auto"} [:div {:class "overflow-auto grid grid-cols-4 gap-4"} [:div {:class ""}] [:div {:class "col-span-2 text-center"} [:p {:class "text-4xl"} "Clocks and Dice"]] [:div {:class ""}] [:div {:class ""}] [:div {:class "col-span-2 text-center"} [:p "Clocks and Dice is an assistant (dice roller, chat, and clock tracker) for Evil Hat Productions' Blades in the Dark RPG."]] [:div {:class ""}] [:div {:class ""}] [:div {:class "col-span-2 content-center"} [:div {:class "grid grid-cols-9"} (for [x (clocks/get-faces :eight-o)] ^{:key (str "intro-" x)} [:div [:img {:class "w-6" :src (str "images/clocks/" x)}]])]] [:div {:class ""}] [:div {:class ""}] [:div {:class "col-span-2 text-center"} sign-in] [:div {:class ""}] [:div {:class "col-span-4 mh-40 m-8 overflow-scroll"} [:p {:class "text-sm"} "This site tends to work poorly in private browsing modes. You'll also want to openlist this site for your ad-blocker. Treat your channel name as if it were a password. It should be complex enough that no one would guess it and only share it with friends joining your game. This site is intended for casual use and exchanging non-sensitive information."] ] [:div {:class "col-span-4 grid grid-cols-1 gap-3 h-40 ml-8 overflow-scroll"} [:div {:class ""} [:div {:class "flex flex-col"} [:div {:class ""}"Copyright 2021"] [:div {:class ""}"Chris Farnham " [:a {:class "underline" :href "mailto:chris.farnham@gmail.com"}]] [:div {:class ""}[:a {:class "underline" :href "https://www.paypal.com/paypalme/chrisfarnham"} "Donate"]] [:div {:class ""} "Source code available at " [:a {:class "underline" :href "https://github.com/chrisfarnham/diceandclocks"} "github"] " under the MIT License"] ]] [:div {:class ""} [:p {:class "mb-2"}"Thanks to:"] [:ul {:class "list-inside list-disc"} [:li "SkyJedi's " [:a {:class "underline" :href "https://dice.skyjedi.com/"} "Star Wars RPG game manager"] " for inspiration"] [:li [:a {:class "underline" :href "https://acegiak.itch.io/"} "acegiak at itch.io"] " for the cool clock images"] [:li "Henry Widd's blog post, \""[:a {:class "underline" :href "https://widdindustries.com/clojurescript-firebase-simple/"} "Wrapper-free Firebase with Clojurescript's Re-Frame"] "\" for technical inspiration"] ] ] [:div {:class "text-center"} [:img {:class "w-24" :src "images/forged_in_the_dark_logo2_0.png"}]] [:div {:class "mr-8 mb-8"} [:p "This work is based on Blades in the Dark (found at " [:a {:href "http://www.bladesinthedark.com/"} "http://www.bladesinthedark.com/"], "product of One Seven Design, developed and authored by John Harper, and licensed for our use under the " [:a {:href "http://creativecommons.org/licenses/by/3.0/)"} "Creative Commons Attribution 3.0 Unported license"]]] ] ]] )
109503
(ns dice-and-clocks.intro-view (:require [dice-and-clocks.clocks :as clocks])) (defn intro-view [sign-in] [:div {:class "container mx-auto"} [:div {:class "overflow-auto grid grid-cols-4 gap-4"} [:div {:class ""}] [:div {:class "col-span-2 text-center"} [:p {:class "text-4xl"} "Clocks and Dice"]] [:div {:class ""}] [:div {:class ""}] [:div {:class "col-span-2 text-center"} [:p "Clocks and Dice is an assistant (dice roller, chat, and clock tracker) for Evil Hat Productions' Blades in the Dark RPG."]] [:div {:class ""}] [:div {:class ""}] [:div {:class "col-span-2 content-center"} [:div {:class "grid grid-cols-9"} (for [x (clocks/get-faces :eight-o)] ^{:key (str "intro-" x)} [:div [:img {:class "w-6" :src (str "images/clocks/" x)}]])]] [:div {:class ""}] [:div {:class ""}] [:div {:class "col-span-2 text-center"} sign-in] [:div {:class ""}] [:div {:class "col-span-4 mh-40 m-8 overflow-scroll"} [:p {:class "text-sm"} "This site tends to work poorly in private browsing modes. You'll also want to openlist this site for your ad-blocker. Treat your channel name as if it were a password. It should be complex enough that no one would guess it and only share it with friends joining your game. This site is intended for casual use and exchanging non-sensitive information."] ] [:div {:class "col-span-4 grid grid-cols-1 gap-3 h-40 ml-8 overflow-scroll"} [:div {:class ""} [:div {:class "flex flex-col"} [:div {:class ""}"Copyright 2021"] [:div {:class ""}"<NAME> " [:a {:class "underline" :href "mailto:<EMAIL>"}]] [:div {:class ""}[:a {:class "underline" :href "https://www.paypal.com/paypalme/chrisfarnham"} "Donate"]] [:div {:class ""} "Source code available at " [:a {:class "underline" :href "https://github.com/chrisfarnham/diceandclocks"} "github"] " under the MIT License"] ]] [:div {:class ""} [:p {:class "mb-2"}"Thanks to:"] [:ul {:class "list-inside list-disc"} [:li "SkyJedi's " [:a {:class "underline" :href "https://dice.skyjedi.com/"} "Star Wars RPG game manager"] " for inspiration"] [:li [:a {:class "underline" :href "https://acegiak.itch.io/"} "acegiak at itch.io"] " for the cool clock images"] [:li "<NAME>'s blog post, \""[:a {:class "underline" :href "https://widdindustries.com/clojurescript-firebase-simple/"} "Wrapper-free Firebase with Clojurescript's Re-Frame"] "\" for technical inspiration"] ] ] [:div {:class "text-center"} [:img {:class "w-24" :src "images/forged_in_the_dark_logo2_0.png"}]] [:div {:class "mr-8 mb-8"} [:p "This work is based on Blades in the Dark (found at " [:a {:href "http://www.bladesinthedark.com/"} "http://www.bladesinthedark.com/"], "product of One Seven Design, developed and authored by <NAME>, and licensed for our use under the " [:a {:href "http://creativecommons.org/licenses/by/3.0/)"} "Creative Commons Attribution 3.0 Unported license"]]] ] ]] )
true
(ns dice-and-clocks.intro-view (:require [dice-and-clocks.clocks :as clocks])) (defn intro-view [sign-in] [:div {:class "container mx-auto"} [:div {:class "overflow-auto grid grid-cols-4 gap-4"} [:div {:class ""}] [:div {:class "col-span-2 text-center"} [:p {:class "text-4xl"} "Clocks and Dice"]] [:div {:class ""}] [:div {:class ""}] [:div {:class "col-span-2 text-center"} [:p "Clocks and Dice is an assistant (dice roller, chat, and clock tracker) for Evil Hat Productions' Blades in the Dark RPG."]] [:div {:class ""}] [:div {:class ""}] [:div {:class "col-span-2 content-center"} [:div {:class "grid grid-cols-9"} (for [x (clocks/get-faces :eight-o)] ^{:key (str "intro-" x)} [:div [:img {:class "w-6" :src (str "images/clocks/" x)}]])]] [:div {:class ""}] [:div {:class ""}] [:div {:class "col-span-2 text-center"} sign-in] [:div {:class ""}] [:div {:class "col-span-4 mh-40 m-8 overflow-scroll"} [:p {:class "text-sm"} "This site tends to work poorly in private browsing modes. You'll also want to openlist this site for your ad-blocker. Treat your channel name as if it were a password. It should be complex enough that no one would guess it and only share it with friends joining your game. This site is intended for casual use and exchanging non-sensitive information."] ] [:div {:class "col-span-4 grid grid-cols-1 gap-3 h-40 ml-8 overflow-scroll"} [:div {:class ""} [:div {:class "flex flex-col"} [:div {:class ""}"Copyright 2021"] [:div {:class ""}"PI:NAME:<NAME>END_PI " [:a {:class "underline" :href "mailto:PI:EMAIL:<EMAIL>END_PI"}]] [:div {:class ""}[:a {:class "underline" :href "https://www.paypal.com/paypalme/chrisfarnham"} "Donate"]] [:div {:class ""} "Source code available at " [:a {:class "underline" :href "https://github.com/chrisfarnham/diceandclocks"} "github"] " under the MIT License"] ]] [:div {:class ""} [:p {:class "mb-2"}"Thanks to:"] [:ul {:class "list-inside list-disc"} [:li "SkyJedi's " [:a {:class "underline" :href "https://dice.skyjedi.com/"} "Star Wars RPG game manager"] " for inspiration"] [:li [:a {:class "underline" :href "https://acegiak.itch.io/"} "acegiak at itch.io"] " for the cool clock images"] [:li "PI:NAME:<NAME>END_PI's blog post, \""[:a {:class "underline" :href "https://widdindustries.com/clojurescript-firebase-simple/"} "Wrapper-free Firebase with Clojurescript's Re-Frame"] "\" for technical inspiration"] ] ] [:div {:class "text-center"} [:img {:class "w-24" :src "images/forged_in_the_dark_logo2_0.png"}]] [:div {:class "mr-8 mb-8"} [:p "This work is based on Blades in the Dark (found at " [:a {:href "http://www.bladesinthedark.com/"} "http://www.bladesinthedark.com/"], "product of One Seven Design, developed and authored by PI:NAME:<NAME>END_PI, and licensed for our use under the " [:a {:href "http://creativecommons.org/licenses/by/3.0/)"} "Creative Commons Attribution 3.0 Unported license"]]] ] ]] )
[ { "context": "\\nIt shines as you hold it aloft. In the distance, Pedro howls in rage.\")\n (swap! dr", "end": 2635, "score": 0.9924888610839844, "start": 2630, "tag": "NAME", "value": "Pedro" }, { "context": " (do\n (js/alert \"Pedro has caught you!\\n\\nYOU ARE THE NEW PEDRO!\")\n ", "end": 2817, "score": 0.9890322685241699, "start": 2812, "tag": "NAME", "value": "Pedro" } ]
src/app/main.cljs
atulchin/shadow-noob
0
(ns app.main (:require ["rot-js" :as rot] [clojure.core.async :as a :refer [>! <! put! go go-loop chan]] [app.world :as world :refer [world-state init-grid! move-player! open-box!]] [app.drawrot :as draw :refer [init-disp! redraw-entity re-draw]])) (defonce key-chan (chan)) ;;channel for processing keyboard input ;;initialize world-map and interface with given width and height (defn init! [w h] (init-grid! w h) (init-disp! w h) (re-draw @world-state)) ;;maps input codes to functions (def keymap {[37] #(move-player! 6) [:shift 37] #(move-player! 7) [38] #(move-player! 0) [:shift 38] #(move-player! 1) [39] #(move-player! 2) [:shift 39] #(move-player! 3) [40] #(move-player! 4) [:shift 40] #(move-player! 5) [13] #(open-box!) [32] #(open-box!)}) ;;called on player's turn to process input (defn handle-input [code] (when-let [f (get keymap code)] (f))) ;; from the point of view of the world model, player and npcs are just game entities ;; but the user interface needs to handle them differently ;; use multi-method dispatch for this, based on a ":type" key ;; methods for specific values of :type are defined below (defmulti take-turn #(:type %)) ;; this method is called on the player's turn & waits for keyboard input ;; go-loop spawns a process that will eventually put something on out channel ;; (<! key-chan) will park until another fn puts something on key-chan ;; immediately returns out channel (defmethod take-turn :local-player [_] (let [out (chan)] (go-loop [] ;;wait for a code from key-chan (let [code (<! key-chan) ;;fn's called by handle-input return a result if player made a move result (handle-input code)] (if result ;;if there's a result, send it to out channel and exit loop (>! out result) ;;else, continue the go-loop (recur)))) out)) ;; this method is called on an npc's turn & calls a fn defined in the world state ;; an entity is a hashmap ;; contains :id key for looking itself up in world-state (defmethod take-turn :npc [entity] (let [out (chan)] (go (let [entity-fn (:action entity) result (entity-fn)] (>! out result))) out)) ;; put game rule logic in this fn for now (defn game-rules [result] (cond (:ananas result) (do (js/alert "The box contains a golden pineapple, heavy with promise and juice.\n\nIt shines as you hold it aloft. In the distance, Pedro howls in rage.") (swap! draw/icons #(assoc % :player (get % :ananas)))) (= 0 (:path-length result)) (do (js/alert "Pedro has caught you!\n\nYOU ARE THE NEW PEDRO!") (swap! draw/icons #(assoc % :player (get % :pedro))) (swap! world-state assoc-in [:entities :pedro :action] (fn [_] {:pedro :skip}))))) ;; turn-loop spawns a looping process that allocates game turns (defn turn-loop [scheduler ch] ;; get the next entity key from the scheduler (go-loop [entity-key (.next scheduler)] ;;save a snapshot of the world state (let [state @world-state ;;save a snapshot of the entity entity (get (:entities state) entity-key) ;; (take-turn) will change the world state, puts result on a channel ;; <! (take-turn) will park until something is put on that channel result (if entity (<! (take-turn entity)) {entity-key false})] ;; apply game rules based on the result or the world-state (game-rules result) ;;redraw changes made by current entity; (:coords entity) is the old position (redraw-entity @world-state entity-key (:coords entity)) ;;pass result to output channel (>! ch result)) (recur (.next scheduler)))) ;; creates and populates a rot-js scheduler ;; passes it to turn-loop (defn start-turn-loop [] (let [debug-ch (chan) scheduler (rot/Scheduler.Simple.)] ;;must add entity keys to the scheduler, not the entities themselves ;;-- clj data structures are immutable; entities added would just be snapshots (doseq [k (keys (:entities @world-state))] (.add scheduler k true)) (turn-loop scheduler debug-ch) ;;start a process to montior the output channel (go (while true (println (<! debug-ch)))))) ;; translates javascript keyboard event to input code ;; the cond-> macro threads its first argument through pairs of statements ;; applying the 2nd statement if the 1st is true ;; cond-> [] with conj statements is a way to build up a vector (defn key-event [e] (put! key-chan (cond-> [] (. e -shiftKey) (conj :shift) (. e -ctrlKey) (conj :ctrl) :always (conj (. e -keyCode))))) ;; called when app first loads (as specified in shadow-cljs.edn) (defn main! [] (init! 60 40) (. js/document addEventListener "keydown" key-event) (start-turn-loop) ) ;; hot reload; called by shadow-cljs when code is saved ;; object state is preserved (defn reload! [] (re-draw @world-state) )
36129
(ns app.main (:require ["rot-js" :as rot] [clojure.core.async :as a :refer [>! <! put! go go-loop chan]] [app.world :as world :refer [world-state init-grid! move-player! open-box!]] [app.drawrot :as draw :refer [init-disp! redraw-entity re-draw]])) (defonce key-chan (chan)) ;;channel for processing keyboard input ;;initialize world-map and interface with given width and height (defn init! [w h] (init-grid! w h) (init-disp! w h) (re-draw @world-state)) ;;maps input codes to functions (def keymap {[37] #(move-player! 6) [:shift 37] #(move-player! 7) [38] #(move-player! 0) [:shift 38] #(move-player! 1) [39] #(move-player! 2) [:shift 39] #(move-player! 3) [40] #(move-player! 4) [:shift 40] #(move-player! 5) [13] #(open-box!) [32] #(open-box!)}) ;;called on player's turn to process input (defn handle-input [code] (when-let [f (get keymap code)] (f))) ;; from the point of view of the world model, player and npcs are just game entities ;; but the user interface needs to handle them differently ;; use multi-method dispatch for this, based on a ":type" key ;; methods for specific values of :type are defined below (defmulti take-turn #(:type %)) ;; this method is called on the player's turn & waits for keyboard input ;; go-loop spawns a process that will eventually put something on out channel ;; (<! key-chan) will park until another fn puts something on key-chan ;; immediately returns out channel (defmethod take-turn :local-player [_] (let [out (chan)] (go-loop [] ;;wait for a code from key-chan (let [code (<! key-chan) ;;fn's called by handle-input return a result if player made a move result (handle-input code)] (if result ;;if there's a result, send it to out channel and exit loop (>! out result) ;;else, continue the go-loop (recur)))) out)) ;; this method is called on an npc's turn & calls a fn defined in the world state ;; an entity is a hashmap ;; contains :id key for looking itself up in world-state (defmethod take-turn :npc [entity] (let [out (chan)] (go (let [entity-fn (:action entity) result (entity-fn)] (>! out result))) out)) ;; put game rule logic in this fn for now (defn game-rules [result] (cond (:ananas result) (do (js/alert "The box contains a golden pineapple, heavy with promise and juice.\n\nIt shines as you hold it aloft. In the distance, <NAME> howls in rage.") (swap! draw/icons #(assoc % :player (get % :ananas)))) (= 0 (:path-length result)) (do (js/alert "<NAME> has caught you!\n\nYOU ARE THE NEW PEDRO!") (swap! draw/icons #(assoc % :player (get % :pedro))) (swap! world-state assoc-in [:entities :pedro :action] (fn [_] {:pedro :skip}))))) ;; turn-loop spawns a looping process that allocates game turns (defn turn-loop [scheduler ch] ;; get the next entity key from the scheduler (go-loop [entity-key (.next scheduler)] ;;save a snapshot of the world state (let [state @world-state ;;save a snapshot of the entity entity (get (:entities state) entity-key) ;; (take-turn) will change the world state, puts result on a channel ;; <! (take-turn) will park until something is put on that channel result (if entity (<! (take-turn entity)) {entity-key false})] ;; apply game rules based on the result or the world-state (game-rules result) ;;redraw changes made by current entity; (:coords entity) is the old position (redraw-entity @world-state entity-key (:coords entity)) ;;pass result to output channel (>! ch result)) (recur (.next scheduler)))) ;; creates and populates a rot-js scheduler ;; passes it to turn-loop (defn start-turn-loop [] (let [debug-ch (chan) scheduler (rot/Scheduler.Simple.)] ;;must add entity keys to the scheduler, not the entities themselves ;;-- clj data structures are immutable; entities added would just be snapshots (doseq [k (keys (:entities @world-state))] (.add scheduler k true)) (turn-loop scheduler debug-ch) ;;start a process to montior the output channel (go (while true (println (<! debug-ch)))))) ;; translates javascript keyboard event to input code ;; the cond-> macro threads its first argument through pairs of statements ;; applying the 2nd statement if the 1st is true ;; cond-> [] with conj statements is a way to build up a vector (defn key-event [e] (put! key-chan (cond-> [] (. e -shiftKey) (conj :shift) (. e -ctrlKey) (conj :ctrl) :always (conj (. e -keyCode))))) ;; called when app first loads (as specified in shadow-cljs.edn) (defn main! [] (init! 60 40) (. js/document addEventListener "keydown" key-event) (start-turn-loop) ) ;; hot reload; called by shadow-cljs when code is saved ;; object state is preserved (defn reload! [] (re-draw @world-state) )
true
(ns app.main (:require ["rot-js" :as rot] [clojure.core.async :as a :refer [>! <! put! go go-loop chan]] [app.world :as world :refer [world-state init-grid! move-player! open-box!]] [app.drawrot :as draw :refer [init-disp! redraw-entity re-draw]])) (defonce key-chan (chan)) ;;channel for processing keyboard input ;;initialize world-map and interface with given width and height (defn init! [w h] (init-grid! w h) (init-disp! w h) (re-draw @world-state)) ;;maps input codes to functions (def keymap {[37] #(move-player! 6) [:shift 37] #(move-player! 7) [38] #(move-player! 0) [:shift 38] #(move-player! 1) [39] #(move-player! 2) [:shift 39] #(move-player! 3) [40] #(move-player! 4) [:shift 40] #(move-player! 5) [13] #(open-box!) [32] #(open-box!)}) ;;called on player's turn to process input (defn handle-input [code] (when-let [f (get keymap code)] (f))) ;; from the point of view of the world model, player and npcs are just game entities ;; but the user interface needs to handle them differently ;; use multi-method dispatch for this, based on a ":type" key ;; methods for specific values of :type are defined below (defmulti take-turn #(:type %)) ;; this method is called on the player's turn & waits for keyboard input ;; go-loop spawns a process that will eventually put something on out channel ;; (<! key-chan) will park until another fn puts something on key-chan ;; immediately returns out channel (defmethod take-turn :local-player [_] (let [out (chan)] (go-loop [] ;;wait for a code from key-chan (let [code (<! key-chan) ;;fn's called by handle-input return a result if player made a move result (handle-input code)] (if result ;;if there's a result, send it to out channel and exit loop (>! out result) ;;else, continue the go-loop (recur)))) out)) ;; this method is called on an npc's turn & calls a fn defined in the world state ;; an entity is a hashmap ;; contains :id key for looking itself up in world-state (defmethod take-turn :npc [entity] (let [out (chan)] (go (let [entity-fn (:action entity) result (entity-fn)] (>! out result))) out)) ;; put game rule logic in this fn for now (defn game-rules [result] (cond (:ananas result) (do (js/alert "The box contains a golden pineapple, heavy with promise and juice.\n\nIt shines as you hold it aloft. In the distance, PI:NAME:<NAME>END_PI howls in rage.") (swap! draw/icons #(assoc % :player (get % :ananas)))) (= 0 (:path-length result)) (do (js/alert "PI:NAME:<NAME>END_PI has caught you!\n\nYOU ARE THE NEW PEDRO!") (swap! draw/icons #(assoc % :player (get % :pedro))) (swap! world-state assoc-in [:entities :pedro :action] (fn [_] {:pedro :skip}))))) ;; turn-loop spawns a looping process that allocates game turns (defn turn-loop [scheduler ch] ;; get the next entity key from the scheduler (go-loop [entity-key (.next scheduler)] ;;save a snapshot of the world state (let [state @world-state ;;save a snapshot of the entity entity (get (:entities state) entity-key) ;; (take-turn) will change the world state, puts result on a channel ;; <! (take-turn) will park until something is put on that channel result (if entity (<! (take-turn entity)) {entity-key false})] ;; apply game rules based on the result or the world-state (game-rules result) ;;redraw changes made by current entity; (:coords entity) is the old position (redraw-entity @world-state entity-key (:coords entity)) ;;pass result to output channel (>! ch result)) (recur (.next scheduler)))) ;; creates and populates a rot-js scheduler ;; passes it to turn-loop (defn start-turn-loop [] (let [debug-ch (chan) scheduler (rot/Scheduler.Simple.)] ;;must add entity keys to the scheduler, not the entities themselves ;;-- clj data structures are immutable; entities added would just be snapshots (doseq [k (keys (:entities @world-state))] (.add scheduler k true)) (turn-loop scheduler debug-ch) ;;start a process to montior the output channel (go (while true (println (<! debug-ch)))))) ;; translates javascript keyboard event to input code ;; the cond-> macro threads its first argument through pairs of statements ;; applying the 2nd statement if the 1st is true ;; cond-> [] with conj statements is a way to build up a vector (defn key-event [e] (put! key-chan (cond-> [] (. e -shiftKey) (conj :shift) (. e -ctrlKey) (conj :ctrl) :always (conj (. e -keyCode))))) ;; called when app first loads (as specified in shadow-cljs.edn) (defn main! [] (init! 60 40) (. js/document addEventListener "keydown" key-event) (start-turn-loop) ) ;; hot reload; called by shadow-cljs when code is saved ;; object state is preserved (defn reload! [] (re-draw @world-state) )
[ { "context": "`get` to retrieve the value of a given\n;; key.\n\n{\"jane\" \"jane@acme.com\"\n \"fred\" \"fred@acme.com\"\n \"rob\" ", "end": 7374, "score": 0.9985405206680298, "start": 7370, "tag": "USERNAME", "value": "jane" }, { "context": "o retrieve the value of a given\n;; key.\n\n{\"jane\" \"jane@acme.com\"\n \"fred\" \"fred@acme.com\"\n \"rob\" \"rob@acme.com\"}\n", "end": 7390, "score": 0.9999294281005859, "start": 7377, "tag": "EMAIL", "value": "jane@acme.com" }, { "context": "lue of a given\n;; key.\n\n{\"jane\" \"jane@acme.com\"\n \"fred\" \"fred@acme.com\"\n \"rob\" \"rob@acme.com\"}\n\n{:a 1, ", "end": 7398, "score": 0.9786065220832825, "start": 7394, "tag": "USERNAME", "value": "fred" }, { "context": "a given\n;; key.\n\n{\"jane\" \"jane@acme.com\"\n \"fred\" \"fred@acme.com\"\n \"rob\" \"rob@acme.com\"}\n\n{:a 1, :b 2, :c 3}\n(has", "end": 7414, "score": 0.999928891658783, "start": 7401, "tag": "EMAIL", "value": "fred@acme.com" }, { "context": "{\"jane\" \"jane@acme.com\"\n \"fred\" \"fred@acme.com\"\n \"rob\" \"rob@acme.com\"}\n\n{:a 1, :b 2, :c 3}\n(hash-map :", "end": 7421, "score": 0.9989389777183533, "start": 7418, "tag": "USERNAME", "value": "rob" }, { "context": " \"jane@acme.com\"\n \"fred\" \"fred@acme.com\"\n \"rob\" \"rob@acme.com\"}\n\n{:a 1, :b 2, :c 3}\n(hash-map :a 1, :b 2, :c 3)", "end": 7437, "score": 0.9999243021011353, "start": 7425, "tag": "EMAIL", "value": "rob@acme.com" }, { "context": "\n(re-find #\"[\\w\\d.-]+@[\\w\\d-.]+\\.[\\w]+\"\n \"bob.smith@acme.org\")\n\n(if (re-find #\"^[\\w\\d.-]+@[\\w\\d-.]+\\.[\\w]+$\"\n ", "end": 10586, "score": 0.9998957514762878, "start": 10568, "tag": "EMAIL", "value": "bob.smith@acme.org" }, { "context": "ind #\"^[\\w\\d.-]+@[\\w\\d-.]+\\.[\\w]+$\"\n \"bob.smith@acme.org\")\n \"it's an email\"\n \"it's not an email\")\n\n\n(re-", "end": 10667, "score": 0.9999004006385803, "start": 10649, "tag": "EMAIL", "value": "bob.smith@acme.org" }, { "context": "ttern \"[0-9]{1,3}(\\\\.[0-9]{1,3}){3}\")\n \"my IP is: 192.168.0.12\")\n\n\n;;\n;; Using `re-matcher`, `re-matches`, `re-g", "end": 10881, "score": 0.9997174739837646, "start": 10869, "tag": "IP_ADDRESS", "value": "192.168.0.12" }, { "context": "name\")\n(type (symbol \"username\"))\n\n(def username \"bruno1\")\nusername\n\nage ;; undefined var produces error\n(", "end": 11750, "score": 0.9996569752693176, "start": 11744, "tag": "USERNAME", "value": "bruno1" }, { "context": "e\n\n(type 'age)\n(type age)\n\n\n(def user {:username \"bruno1\"\n :score 12345\n :level ", "end": 11871, "score": 0.9996377825737, "start": 11865, "tag": "USERNAME", "value": "bruno1" }, { "context": "s))\n\n\nnew-colours\ncolours\n\n\n(def user {:username \"bruno1\"\n :score 12345\n :level ", "end": 13278, "score": 0.9995381832122803, "start": 13272, "tag": "USERNAME", "value": "bruno1" }, { "context": "le \" \" firstname \" \" lastname)))\n\n(greet)\n(greet \"James\")\n(greet \"James\" \"Bond\")\n(greet \"Dr\" \"John H.\" \"W", "end": 15520, "score": 0.9950243830680847, "start": 15515, "tag": "NAME", "value": "James" }, { "context": " \" \" lastname)))\n\n(greet)\n(greet \"James\")\n(greet \"James\" \"Bond\")\n(greet \"Dr\" \"John H.\" \"Watson\")\n\n\n;;\n;; ", "end": 15536, "score": 0.9974843859672546, "start": 15531, "tag": "NAME", "value": "James" }, { "context": "tname)))\n\n(greet)\n(greet \"James\")\n(greet \"James\" \"Bond\")\n(greet \"Dr\" \"John H.\" \"Watson\")\n\n\n;;\n;; #### Hi", "end": 15543, "score": 0.9983150959014893, "start": 15539, "tag": "NAME", "value": "Bond" }, { "context": "reet \"James\")\n(greet \"James\" \"Bond\")\n(greet \"Dr\" \"John H.\" \"Watson\")\n\n\n;;\n;; #### High-order functions\n;;\n", "end": 15565, "score": 0.9997588992118835, "start": 15559, "tag": "NAME", "value": "John H" }, { "context": "s\")\n(greet \"James\" \"Bond\")\n(greet \"Dr\" \"John H.\" \"Watson\")\n\n\n;;\n;; #### High-order functions\n;;\n;; In Cloj", "end": 15575, "score": 0.9994411468505859, "start": 15569, "tag": "NAME", "value": "Watson" }, { "context": "ble.\n\n\n(ns user.test.one)\n;;=> nil\n\n(def my-name \"john\")\n;;=> #'user.test.one/my-name\n\nmy-name\n;;=> \"joh", "end": 23136, "score": 0.9990018010139465, "start": 23132, "tag": "NAME", "value": "john" }, { "context": "ohn\")\n;;=> #'user.test.one/my-name\n\nmy-name\n;;=> \"john\"\n\n(ns user.test.two)\n;;=> nil\n\n(def my-name \"juli", "end": 23187, "score": 0.9991657733917236, "start": 23183, "tag": "NAME", "value": "john" }, { "context": "john\"\n\n(ns user.test.two)\n;;=> nil\n\n(def my-name \"julie\")\n;;=> #'user.test.two/my-name\n\nmy-name\n;;=> \"jul", "end": 23238, "score": 0.9995261430740356, "start": 23233, "tag": "NAME", "value": "julie" }, { "context": "lie\")\n;;=> #'user.test.two/my-name\n\nmy-name\n;;=> \"julie\"\n\nuser.test.one/my-name\n;;=> \"john\"\n\nuser.test.tw", "end": 23290, "score": 0.9994730353355408, "start": 23285, "tag": "NAME", "value": "julie" }, { "context": "my-name\n;;=> \"julie\"\n\nuser.test.one/my-name\n;;=> \"john\"\n\nuser.test.two/my-name\n;;=> \"julie\"\n\n\n(def my-na", "end": 23325, "score": 0.9984752535820007, "start": 23321, "tag": "NAME", "value": "john" }, { "context": "/my-name\n;;=> \"john\"\n\nuser.test.two/my-name\n;;=> \"julie\"\n\n\n(def my-name (clojure.string/upper-case \"john\"", "end": 23361, "score": 0.9881923794746399, "start": 23356, "tag": "NAME", "value": "julie" }, { "context": "julie\"\n\n\n(def my-name (clojure.string/upper-case \"john\"))\n;;=> #'user.test.one/my-name\n\n(ns user.test.on", "end": 23410, "score": 0.9985158443450928, "start": 23406, "tag": "NAME", "value": "john" }, { "context": "ng :as s]))\n;;=> nil\n\n(def my-name (s/upper-case \"john\"))\n;;=> #'user.test.one/my-name\n\n(ns user.test.on", "end": 23541, "score": 0.997694730758667, "start": 23537, "tag": "NAME", "value": "john" }, { "context": "pper-case]]))\n;;=> nil\n\n(def my-name (upper-case \"john\"))\n;;=> #'user.test.one/my-name\n\nmy-name\n;;=> \"JO", "end": 23684, "score": 0.9972566962242126, "start": 23680, "tag": "NAME", "value": "john" }, { "context": "hn\"))\n;;=> #'user.test.one/my-name\n\nmy-name\n;;=> \"JOHN\"\n\n;;\n;; The global accessible vars (globals) is o", "end": 23736, "score": 0.9992750883102417, "start": 23732, "tag": "NAME", "value": "JOHN" }, { "context": "amet\" \"sit\")\n\n(sort-by :score >\n [{:user \"john1\" :score 345}\n {:user \"fred3\" :score 75}\n", "end": 31511, "score": 0.9124743938446045, "start": 31506, "tag": "USERNAME", "value": "john1" }, { "context": " [{:user \"john1\" :score 345}\n {:user \"fred3\" :score 75}\n {:user \"sam2\" :score 291}]", "end": 31548, "score": 0.9995349049568176, "start": 31543, "tag": "USERNAME", "value": "fred3" }, { "context": " {:user \"fred3\" :score 75}\n {:user \"sam2\" :score 291}])\n;;=> ({:user \"john1\", :score 345}", "end": 31583, "score": 0.9992678165435791, "start": 31579, "tag": "USERNAME", "value": "sam2" }, { "context": " {:user \"sam2\" :score 291}])\n;;=> ({:user \"john1\", :score 345} {:user \"sam2\", :score 291} {:user \"", "end": 31619, "score": 0.9983005523681641, "start": 31614, "tag": "USERNAME", "value": "john1" }, { "context": " 291}])\n;;=> ({:user \"john1\", :score 345} {:user \"sam2\", :score 291} {:user \"fred3\", :score 75})\n\n;;\n;; ", "end": 31646, "score": 0.9993908405303955, "start": 31642, "tag": "USERNAME", "value": "sam2" }, { "context": "\", :score 345} {:user \"sam2\", :score 291} {:user \"fred3\", :score 75})\n\n;;\n;; A similar function is `sort-", "end": 31674, "score": 0.9995376467704773, "start": 31669, "tag": "USERNAME", "value": "fred3" }, { "context": "function called `frequencies`.\n;;\n\n(frequencies [\"john\" \"fred\" \"alice\" \"fred\" \"jason\" \"john\" \"alice\" \"jo", "end": 33153, "score": 0.9971254467964172, "start": 33149, "tag": "NAME", "value": "john" }, { "context": "n called `frequencies`.\n;;\n\n(frequencies [\"john\" \"fred\" \"alice\" \"fred\" \"jason\" \"john\" \"alice\" \"john\"])\n;", "end": 33160, "score": 0.9995925426483154, "start": 33156, "tag": "NAME", "value": "fred" }, { "context": "d `frequencies`.\n;;\n\n(frequencies [\"john\" \"fred\" \"alice\" \"fred\" \"jason\" \"john\" \"alice\" \"john\"])\n;;=> {\"jo", "end": 33168, "score": 0.9982209205627441, "start": 33163, "tag": "NAME", "value": "alice" }, { "context": "encies`.\n;;\n\n(frequencies [\"john\" \"fred\" \"alice\" \"fred\" \"jason\" \"john\" \"alice\" \"john\"])\n;;=> {\"john\" 3, ", "end": 33175, "score": 0.9996241331100464, "start": 33171, "tag": "NAME", "value": "fred" }, { "context": ".\n;;\n\n(frequencies [\"john\" \"fred\" \"alice\" \"fred\" \"jason\" \"john\" \"alice\" \"john\"])\n;;=> {\"john\" 3, \"fred\" 2", "end": 33183, "score": 0.9995076656341553, "start": 33178, "tag": "NAME", "value": "jason" }, { "context": "requencies [\"john\" \"fred\" \"alice\" \"fred\" \"jason\" \"john\" \"alice\" \"john\"])\n;;=> {\"john\" 3, \"fred\" 2, \"alic", "end": 33190, "score": 0.9967212080955505, "start": 33186, "tag": "NAME", "value": "john" }, { "context": "ies [\"john\" \"fred\" \"alice\" \"fred\" \"jason\" \"john\" \"alice\" \"john\"])\n;;=> {\"john\" 3, \"fred\" 2, \"alice\" 2, \"j", "end": 33198, "score": 0.9956713318824768, "start": 33193, "tag": "NAME", "value": "alice" }, { "context": "hn\" \"fred\" \"alice\" \"fred\" \"jason\" \"john\" \"alice\" \"john\"])\n;;=> {\"john\" 3, \"fred\" 2, \"alice\" 2, \"jason\" 1", "end": 33205, "score": 0.9958226680755615, "start": 33201, "tag": "NAME", "value": "john" }, { "context": "ce\" \"fred\" \"jason\" \"john\" \"alice\" \"john\"])\n;;=> {\"john\" 3, \"fred\" 2, \"alice\" 2, \"jason\" 1}\n\n\n(frequencie", "end": 33220, "score": 0.9940893650054932, "start": 33216, "tag": "NAME", "value": "john" }, { "context": " \"jason\" \"john\" \"alice\" \"john\"])\n;;=> {\"john\" 3, \"fred\" 2, \"alice\" 2, \"jason\" 1}\n\n\n(frequencies [1 2 3 1", "end": 33230, "score": 0.9996254444122314, "start": 33226, "tag": "NAME", "value": "fred" }, { "context": "john\" \"alice\" \"john\"])\n;;=> {\"john\" 3, \"fred\" 2, \"alice\" 2, \"jason\" 1}\n\n\n(frequencies [1 2 3 1 2 3 2 3 1 ", "end": 33241, "score": 0.9965384006500244, "start": 33236, "tag": "NAME", "value": "alice" }, { "context": "e\" \"john\"])\n;;=> {\"john\" 3, \"fred\" 2, \"alice\" 2, \"jason\" 1}\n\n\n(frequencies [1 2 3 1 2 3 2 3 1 2 3 3 2 3 2", "end": 33252, "score": 0.9985823631286621, "start": 33247, "tag": "NAME", "value": "jason" } ]
clojure-basics/learn_clojure/basics_simple.clj
BrunoBonacci/learn-clojure
9
(ns learn-clojure.basics-simple (:require [clojure.string :as str])) ;; ~~~ Introduction to Clojure programming ~~~ ;; ;; .okko. ;; lMMWMMMx ;; ;N:. ;XMo ;; x, 0W. ;; .Wk ;; xM. ;; .XMk ;; KMMM. ;; .KMMWMd ;; .XMMW,kW. ;; KMMM: 'Mo ;; 0MMMc 0N ;; 0MMMl ;Md ;; 0MMMl KM; .d ;; 0MMMd ,MWo. '0d ;; 0MMMk :WMMMMMK. ;; 'llll .:dxd; ;; ;; Bruno Bonacci ;; ;; ## Clojure basics ;; ;; Clojure basics, ground up, with no assumption ;; of previous Clojure knowledge (just general ;; programming). ;; ;; ### The REPL ;; ;; REPL stands for Read Eval Print Loop. ;; ;; Many languages have REPLs but none allow ;; for a full range of in-flow development ;; such as LISP ones. ;; ;; Better than TDD, the **REPL Driven Development** ;; offers the fastest feedback. ;; ;; ;; ### Clojure syntax ;; ;; Syntax is based on `s-expressions` ;; a regular markup language which ;; gives the power to LISP macro system. ;; ;; General format is: ;; ( funciton arg1 arg2 ... argn ) ;; The key is `homoiconicity`!!! ;; ;; ### Comments ;; this is a valid comment ;; and will be skipped by the reader ;; the next line is logical comment ;; more line a NO-OP instruction (comment "something") ; in-line comment ;; but it requires to have valid clojure (comment a : b : c) ; this is BAD ;; ;; ### The function call. ;; ;; // java and C++ ;; myObject.myFunction(arg1, arg2, arg3); ;; ;; // C ;; myFunction(myStruct, arg1, arg2, arg3); ;; ;; ;; Clojure ;; (my-function myObject arg1 arg2 arg3) ;; ;; ;; Examples: ;; ;; // java ;; "Hello World!".toLowerCase(); ;; ;; // C - single char ;; tolower(*c); ;; // C - Whole string ;; for ( ; *c; ++c) *c = tolower(*c); ;; ^^^^^^^^^^^^^ ;; ;; ;; Clojure ;; (lower-case "Hello World!") ;; ;; ### Simple values ;; ;; Al simple values evaluate to themselves. true false nil 1 -4 29384756298374652983746528376529837456 127 ;;=> 127 ; decimal 0x7F ;;=> 127 ; hexadecimal 0177 ;;=> 127 ; octal 32r3V ;;=> 127 ; base 32 2r01111111 ;;=> 127 ; binary 36r3J ;;=> 127 ; base 36 36rClojure ;;=> 27432414842 2r0111001101010001001001 ;;=> 1889353 ;; ;; In Clojure there are no operators, in fact `+`, ;; `-`, `*` and `/` are normal functions. ;; (+ 1 2 3 4 5) ;; ;; You can access static fields by ;; providing the fully qualified class name ;; followed by a slash (`/`) and the field name, ;; for example: `java.lang.Long/MAX_VALUE`. ;; Numbers can be auto-promoted using appropriate ;; functions like `+'` and `*'` (+ 1 java.lang.Long/MAX_VALUE) (+' 1 java.lang.Long/MAX_VALUE) (*' java.lang.Long/MAX_VALUE java.lang.Long/MAX_VALUE) 3.2 (type 3.2) (type 3.2M) (+ 0.3 0.3 0.3 0.1 ) ;; floating point (+ 0.3M 0.3M 0.3M 0.1M) ;; big-decimal (/ 1 3) (type 1/3) (+ 1/3 1/3 1/3) (/ 21 6) (+ 1/3 1/3 1/3 4) \a ; this is the character 'a' \A ; this is the character 'A' \\ ; this is the character '\' \u0041 ; this is unicode for 'A' \tab ; this is the tab character \newline ; this is the newline character \space ; this is the space character \a ;;=> \a (type \a) "This is a string" (type "This is a string") "Strings in Clojure can be multi lines as well!!" ;; java inter-operation ;; "This is a String".toUpperCase() (.toUpperCase "This is a String") (str "This" " is " "a" " concatenation.") (str "Number of lines: " 123) ;; ## Conditionals & Flow control ;; ;; `truthiness` in Clojure ;; `nil` and `false` are falsey, everything ;; else is truthy ;; ;; (if condition ;; then-expr ;; else-expr) ;; ;; ;; (cond ;; condition1 expr1 ;; condition2 expr2 ;; condition3 expr3 ;; :else default-expr) ;; ;; There are more options for flow control in Clojure ;; i.e `if`,`not`, `and`, `or`, `if-not`, ;; `when`, `when-not`, `cond` and `case`. (if true "it's true" "it's false") (if false "it's true" "it's false") (if nil "it's true" "it's false") (if "HELLO" "it's true" "it's false") (if 1 "it's true" "it's false") ;; ### Keywords ;; :blue (type :this-is-a-keyword) (keyword "blue") (= :blue :blue) ;;=> true (= (str "bl" "ue") (str "bl" "ue")) (identical? (str "bl" "ue") (str "bl" "ue")) (identical? :blue :blue) (identical? (keyword (str "bl" "ue")) (keyword (str "bl" "ue"))) ;; ;; ### Collections ;; ;; Collections in Clojure are: ;; - Immutable by default ;; - Persistent data structures (sharing) ;; - Just values (like 42) ;; - Every collection can hold any value ;; ;; #### Lists ;; ;; Clojure has single-linked lists built-in and ;; like all other Clojure collections are ;; immutable. Lists guarantee `O(1)` insertion on ;; the head, `O(n)` traversal and element search. ;; (list 1 2 3 4 5) (cons 0 (list 1 2 3 4 5)) ;; As the output suggest the lists literals in ;; Clojure are expressed with a sequence of values ;; surrounded by brackets, which is the same of ;; the function call. That is the reason why the ;; following line throws an error. (1 2 3 4 5) (quote (1 2 3 4 5)) '(1 2 3 4 5) '(1 "hi" :test 4/5 \c) ;; you can get the head of the list with the ;; function `first` and use `rest` or `next` to ;; get the tail. `count` returns the number of ;; elements in it. `nth` returns the nth element ;; of the list, while `last` returns last item in ;; the list. ;; (first '(1 2 3 4 5)) (rest '(1 2 3 4 5)) (next '(1 2 3 4 5)) (rest '(1)) (next '(1)) (count '(5)) (count '(1 2 3 4 5)) (nth '(1 2 3 4 5) 0) (nth '(1 2 3 4 5) 1) (nth '(1 2 3 4 5) 10) (nth '(1 2 3 4 5) 10 :not-found) (last '(1 2 3 4 5)) (last '(1)) (last '()) ;; ;; #### Vectors ;; ;; Vectors are collections of values which are ;; indexed by their position in the vector ;; (starting from 0) called **index**. Insertion ;; at the end of the vector is `near O(1)` as well ;; as retrieval of an element by it's index. The ;; literals is expressed with a sequence of values ;; surrounded by square brackets or you can use ;; the `vector` function to construct one. You ;; can append an element at the end of the vector ;; with `conj` and use `get` to retrieve an ;; element in a specific index. Function such as ;; `first`, `next` `rest`, `last` and `count` will ;; work just as fine with Vectors. [1 2 3 4 5] [1 "hi" :test 4/5 \c] (vector 1 2 3 4 5) (conj [1 2 3 4 5] 6) (count [1 2]) (first [:a :b :c]) (get [:a :b :c] 1) (get [:a :b :c] 10) (get [:a :b :c] 10 :z) ;; #### Maps ;; ;; Maps are associative data structures (often ;; called dictionaries) which maps keys to their ;; corresponding value. Maps have a literal form ;; which can be expressed by any number of ;; key/value pairs surrounded by curly brackets, ;; or by using `hash-map` or `array-map` ;; functions. Hash-maps provides a `near O(1)` ;; insertion time and `near O(1)` seek time. You ;; can use `assoc` to "add or overwrite" an new ;; pair, `dissoc` to "remove" a key and its value, ;; and use `get` to retrieve the value of a given ;; key. {"jane" "jane@acme.com" "fred" "fred@acme.com" "rob" "rob@acme.com"} {:a 1, :b 2, :c 3} (hash-map :a 1, :b 2, :c 3) (array-map :a 1, :b 2, :c 3) (assoc {:a 1, :b 2, :c 3} :d 4) (assoc {:a 1, :b 2, :c 3} :b 10) (dissoc {:a 1, :b 2, :c 3} :b) (count {:a 1, :b 2, :c 3}) (get {:a 1, :b 2, :c 3} :a) (get {:a 1, :b 2, :c 3} :a :not-found) (get {:a 1, :b 2, :c 3} :ZULU :not-found) (:a {:a 1, :b 2, :c 3}) ;; ;; #### Sets ;; ;; Sets are a type of collection which doesn't ;; allow for duplicate values. While lists and ;; vector can have duplicate elements, set ;; eliminates all duplicates. Clojure has a ;; literal form for sets which is expressed by a ;; sequence of values surrounded by `#{ ;; }`. Otherwise you construct a set using the ;; `set` function. With `conj` you can "add" a ;; new element to an existing set, and `disj` to ;; "remove" an element from the set. With ;; `clojure.set/union`, `clojure.set/difference` ;; and `clojure.set/intersection` you have typical ;; sets operations. `count` returns the number of ;; elements in the set in `O(1)` time. #{1 2 4} #{:a 4 5 :d "hello"} (type #{:a :z}) (set [:a :b :c]) (conj #{:a :c} :b) (conj #{:a :c} :c) (disj #{:a :b :c} :b) (clojure.set/union #{:a} #{:a :b} #{:c :a}) (clojure.set/difference #{:a :b} #{:c :a}) (clojure.set/intersection #{:a :b} #{:c :a}) ;; ;; ### The sequence abstraction ;; ;; One of the most powerful abstraction of ;; Clojure's data structures is the `sequence` ;; (`clojure.lang.ISeq`) which all data structure ;; implements. This interface resembles to a Java ;; iterator, and it implements methods like ;; `first()`, `rest()`, `more()` and `cons()`. The ;; power of this abstraction is that it is general ;; enough to be used in all data structures ;; (lists, vectors, maps, sets and even strings ;; can all produce sequences) and you have loads ;; of functions which manipulates it. Functions ;; such as `first`, `rest`, `next` and `last` and ;; many others such as `reverse`, `shuffle`, ;; `drop`, `take`, `partition`, `filter` etc are ;; all built on top of the sequence abstraction. ;; So if you create your own data-structure and ;; you implement the four methods of the ;; `clojure.lang.ISeq` interface you can benefit ;; from all these function without having to ;; re-implement them for your specific ;; data-structure. ;; (first [1 2 3 4]) (take 3 [:a :b :c :d :e]) (shuffle [1 2 3 4]) (shuffle #{1 2 3 4}) (reverse [1 2 3 4]) (last (reverse {:a 1 :b 2 :c 3})) (seq "Hello World!") (first "Hello") (rest "Hello") (count "Hello World!") ;; ;; #### Lazy Sequences ;; ;; Some of the sequences produced by the core ;; library are lazy which means that the entire ;; collection won't be created (*realised*) all at ;; once but when the elements are requested. (range 5 10) ;; _**WARNING!!!** Evaluating this from your REPL ;; might hang/crash your process_, as it will try ;; evaluate an infinite lazy sequence all at once. (range) (take 10 (range)) ;; ;; ### Regular expression patterns ;; #"[\w\d.-]+@[\w\d-.]+\.[\w]+" (type #"[\w\d.-]+@[\w\d-.]+\.[\w]+") (re-find #"[0-9]+" "only 123 numbers") (re-find #"[0-9]+" "no numbers") (re-find #"[\w\d.-]+@[\w\d-.]+\.[\w]+" "bob.smith@acme.org") (if (re-find #"^[\w\d.-]+@[\w\d-.]+\.[\w]+$" "bob.smith@acme.org") "it's an email" "it's not an email") (re-seq #"[0-9]+" "25, 43, 54, 12, 15, 65") (re-pattern "[0-9]{1,3}(\\.[0-9]{1,3}){3}") (re-find (re-pattern "[0-9]{1,3}(\\.[0-9]{1,3}){3}") "my IP is: 192.168.0.12") ;; ;; Using `re-matcher`, `re-matches`, `re-groups` ;; allows you to have fine control over the capturing ;; groups. ;; ;; ### Symbols and Vars ;; ;; Symbols in Clojure are a way to identify things ;; in your programs which may have various values ;; at runtime. Like in a mathematical notation, `x` ;; is something not known which could assume ;; several different values. In a programming ;; context, Clojure symbols are similar to ;; variables in other languages but not exactly. ;; In other languages variables are places where ;; you store information, symbols in Clojure ;; cannot contain data themselves. Vars in ;; Clojure are the containers of data (one type ;; of), and symbols are a way to identify them and ;; give vars meaningful names for your program. ;; username 'username (symbol "username") (type (symbol "username")) (def username "bruno1") username age ;; undefined var produces error (def age 21) age (type 'age) (type age) (def user {:username "bruno1" :score 12345 :level 32 :achievements #{:fast-run :precision10 :strategy}}) user (def user nil) user ;; ;; ### Immutability ;; ;; All basics data-types in Clojure are immutable, ;; including the collections. This is a very ;; important aspect of Clojure approach to ;; functional programming. In Clojure functions ;; transform values into new values and values are ;; just values. Since it is absurd to think of ;; changing a number (1 is always 1), ;; composite data structures are treated in the same way. ;; So functions do not mutate values they just produce new ones. ;; Like adding `1` to `42` produces `43` but ;; doesn't really change the number `42` as it keeps on ;; existing on its own, adding an element to a list will ;; produce a new list but the old one will still be same ;; and unmodified. ;; ;; The advantage of the immutability is that ;; values (even deeply nested and complex ;; structures) can be safely shared across threads ;; and with function callers without worrying ;; about unsafe or uncoordinated changes. This ;; simple constraint makes Clojure programs so ;; much easier to reason about, as the only way to ;; produce a new value is via a functional ;; transformation. ;; (def colours '(:red :green :blue)) (def new-colours (cons :black colours)) new-colours colours (def user {:username "bruno1" :score 12345 :level 32}) (def user' (assoc user :level 33)) user' user ;; ;; ### Functions ;; ;; So far we have seen how to represent data in ;; our system, now we will see how to make sense ;; of this data and how to ;; extract/process/transform it. The way we ;; express this in Clojure is via functions. ;; ;; ;; pure (+ 1 2 3) ;; impure (rand-int 100) ;; (+ 1 1 1) is referentially transparent (+ 1 2 (+ 1 1 1)) ;; ;; #### Function definition ;; ;; To define a function you have to use the ;; special form `fn` or `defn` with the following ;; syntax. ;; ;; for example if we want to define a function ;; which increments the input parameters by 1 you ;; will write something as follow: ;; ;; ``` ;; /- fn, special form ;; / parameter vector, 1 param called `n` ;; | | body -> expression to evaluate when ;; | | | this function is called ;; (fn [n] (+ n 1)) ;; ``` ;; ;; This is the simplest way to define a function. ;; ;; Now to refer to this function in our code we ;; need to give it a name. We can do so with `def` ;; as we done earlier. ;; (def plus-one (fn [n] (+ n 1))) ;;=> #'learn-clojure.basics/plus-one (plus-one 10) ;;=> 11 (plus-one -42) ;;=> -41 ;; ;; As mentioned earlier, during the evaluation process ;; the symbol `plus-one` is simply replaced with ;; its value, in the same way we can replace the ;; symbol with the function definition and obtain ;; the same result. So symbols can also refer to ;; functions. ;; Evaluation by substitution model. (plus-one 10) ((fn [n] (+ n 1)) 10) (fn [10] (+ 10 1)) (+ 10 1) 11 ;; def + fn = defn (defn plus-one [n] (+ n 1)) (plus-one 1) (defn plus-one "Returns a number which is one greater than the given `n`." [n] (+ n 1)) (inc 10) (defn make-ip4 [a b c d] (clojure.string/join "." [a b c d])) (make-ip4 192 168 0 1) (defn make-kebab [& words] (clojure.string/join "-" words)) (make-kebab "i" "like" "kebab") (defn greet ([] "Hey, Stranger!") ([name] (str "Hello " name)) ([firstname lastname] (str "Hi, you must be: " lastname ", " firstname " " lastname)) ([title firstname lastname] (str "Hello " title " " firstname " " lastname))) (greet) (greet "James") (greet "James" "Bond") (greet "Dr" "John H." "Watson") ;; ;; #### High-order functions ;; ;; In Clojure functions are reified constructs, ;; therefore we can threat them as normal ;; values. As such functions can be passed as ;; parameters of function or returned as result of ;; function call. ;; (defn is-commutative? [op a b] (= (op a b) (op b a))) (is-commutative? + 3 7) (is-commutative? / 3 7) ;; function which return a function (defn multiplier [m] (fn [n] (* n m))) (def doubler (multiplier 2)) (doubler 5) (doubler 10) (def mult-10x (multiplier 10)) (mult-10x 35) ;; ;; #### Lambda functions (Anonymous) ;; ;; Oftentimes you want to create a function for a ;; specific task in a local context. Such ;; functions don't have any reason to have a ;; global name as they are meaningful only in that ;; specific context, in this case you can create ;; anonymous functions (also called lambda ;; function) and Clojure has some support to make ;; this easier. We already seen an example of an ;; anonymous function with our very first function ;; example. ;; (fn [n] (+ n 1)) ((fn [n] (+ n 1)) 10) ;;=> 11 #(+ % 1) (#(+ % 1) 10) ;; ;; In this function the symbol `%` replace the argument ;; If you have more than one parameter you can denote them as ;; `%1` (or `%`), `%2`, `%3`, `%4` ... ;; ;; for example in our `is-commutative?` function we expect ;; and operation which accept two arguments: (is-commutative? #(+ %1 %2) 9 8) ;; ;; #### Closures ;; ;; Closures (with the `s`) are lambdas which refer ;; to a context (or values from another context). ;; These functions are said to be "closing over" ;; the environment. This means that it can access ;; parameters and values which are NOT in the ;; parameters list. ;; ;; Like in our `multiplier` function example, the ;; returned function is closing over the value `m` ;; which is not in its parameter list but it is a ;; parameter of the parent context the ;; `multiplier` fn. While `n` is a normal ;; parameter `m` is the value we are "closing ;; over" providing a context for that function. (defn multiplier [m] (fn [n] (* n m))) ;; ;; #### Recursion ;; ;; A recursive function is a function which ;; calls itself. There are two types of recursion ;; the mundane recursion and the tail recursion. ;; ;; Let's see an example of both with this function ;; which given a number it calculates the sum of ;; all natural numbers from 1 to the given ;; number. (defn sum1 ([n] (sum1 n 0)) ([n accumulator] (if (< n 1) accumulator ;; else (sum1 (dec n) (+ n accumulator))))) (sum1 1) (sum1 3) (sum1 10) ;; ;; This type of recursion is called mundane ;; recursion and every new call it allocates one ;; new frame on the stack so if you run this with ;; high enough numbers it will blow your stack. ;; (sum1 10000) ;;=> java.lang.StackOverflowError ;; ;; Let's see how we can write this ;; function with a tail recursion using ;; `recur`. ;; (defn sum2 ([n] (sum2 n 0)) ([n accumulator] (if (< n 1) accumulator ;; else (recur (dec n) (+ n accumulator))))) ;;=> #'learn-clojure.basics/sum2 (sum2 10) (sum2 10000) (sum2 1000000) (sum2 100000000) ;; Let's see how we can rewrite the previous ;; function to leverage the `loop/recur` ;; construct. (defn sum3 [num] (loop [n num accumulator 0] (if (< n 1) accumulator ;; else (recur (dec n) (+ n accumulator))))) (sum3 10) ;; Let's see another example with the Fibonacci ;; sequence. Let's start with the mundane ;; recursion. ;; !!! this is O(2^n) (defn fibonacci1 [n] (if (< n 2) 1 ;; else (+ (fibonacci1 (- n 1)) (fibonacci1 (- n 2))))) (fibonacci1 1) (fibonacci1 10) ;; ;; Now this is a simple and very functional ;; definition of the Fibonacci sequence, however ;; it is particularly bad in terms of computational ;; complexity. in fact this is `O(2^n)`. ;; Let's use the `time` function to ;; calculate how much it takes to compute the ;; 35th number in the sequence. ;; (time (fibonacci1 35)) ;; ;; Let's try to use tail recursion. ;; As you will see we have to restructure ;; our function to allow the recursion ;; to happen in the tail position. ;; (defn fibonacci2 [n] (loop [i n c 1 p 1] (if (< i 2) c (recur (dec i) (+' c p) c)))) (fibonacci2 10) (time (fibonacci2 35)) (time (fibonacci2 1000)) ;; ;; #### Function composition and partial functions ;; ;; We have seen earlier that there are functions ;; such as `first`, `second`, `last` and `rest` to ;; access respectively the first item of the ;; sequence, the second item, the last item and ;; the tail of the sequence. These functions can ;; be combined to create other functions for ;; accessing the third, fourth, fifth and other ;; positional items. The following functions are ;; an example of how to construct two such ;; functions. (defn third [coll] (first (rest (rest coll)))) (third '(1 2 3 4 5)) ;;=> 3 (defn fourth [coll] (first (rest (rest (rest coll))))) (fourth '(1 2 3 4 5)) ;;=> 4 ;; But there is another way. If, like in this ;; case, the output of a function can be passed ;; directly into the input of the next one as a ;; simple pipeline of functions then you can just ;; use the `comp` function. ;; ;; (comp f1 f2 f3 ... fn) ;; ;; (comp f1 f2 f3) = (f1 (f2 (f3 ,,,))) ;; (def third (comp first rest rest)) (def fourth (comp first rest rest rest)) (third '(1 2 3 4 5)) ;;=> 3 (fourth '(1 2 3 4 5)) ;;=> 4 ;; Let's see another example. Let's assume ;; we have to write a function which given ;; a number it doubles it and subtract 1 ;; from it. So we can use the `multiplier` ;; function we wrote earlier to accomplish ;; the first part and the Clojure core `dec` ;; to decrement it by one and compose them ;; together with `comp`. (defn multiplier [m] (fn [n] (* n m))) (def doubler (multiplier 2)) (def almost-twice (comp dec doubler)) (almost-twice 5) ;;=> 9 (almost-twice 9) ;;=> 17 ;; ;; Now let's say we want to create a function ;; which given a number perform `almost-twice` two ;; times. ;; (def almost-twice-twice (comp almost-twice almost-twice)) (almost-twice-twice 5) ;;=> 17 (almost-twice-twice 10) ;;=> 37 ;; Another way we could have written the `doubler` ;; function is by using the partial application of ;; the function `*`. In Clojure this is achieved ;; via the function `partial`. ;; ;; (partial f arg1 ... argn) ;; (def doubler (partial * 2)) (doubler 5) ;;=> 10 ;; what happens here is that the `partial` ;; function returns a function which calls `*` ;; with the parameters of the partial and the ;; parameter of the final call, all in one call. ;; ;; ;; ;; ### Vars, namespaces, scope and local bindings ;; ;; When defining a var using `def` or `defn` ;; followed by symbol, the symbol is created ;; in the local namespace. ;; When starting the REPL in a empty project ;; the default namespace is called `user` ;; so unless you configure differently ;; all your vars will be created there. ;; ;; Namespaces are like containers in which ;; vars live in, but namespaces, ;; once defined are **globally accessible**. ;; As a consequence when you define a var ;; using `def` or `defn` these will be accessible ;; globally. ;; ;; We will use `ns` which create a namespace if ;; not present and switch to it, and `in-ns` just ;; changes the current namespace. we will see how ;; to loads namespaces we need with our processing ;; with `require` and how vars are globally ;; accessible. (ns user.test.one) ;;=> nil (def my-name "john") ;;=> #'user.test.one/my-name my-name ;;=> "john" (ns user.test.two) ;;=> nil (def my-name "julie") ;;=> #'user.test.two/my-name my-name ;;=> "julie" user.test.one/my-name ;;=> "john" user.test.two/my-name ;;=> "julie" (def my-name (clojure.string/upper-case "john")) ;;=> #'user.test.one/my-name (ns user.test.one (:require [clojure.string :as s])) ;;=> nil (def my-name (s/upper-case "john")) ;;=> #'user.test.one/my-name (ns user.test.one (:require [clojure.string :refer [upper-case]])) ;;=> nil (def my-name (upper-case "john")) ;;=> #'user.test.one/my-name my-name ;;=> "JOHN" ;; ;; The global accessible vars (globals) is one ;; level of scoping. If you don't want to have ;; globally accessible vars then you have to ;; use local bindings. ;; ;; We already had a glimpse of these while ;; defining functions. In fact parameters ;; are only visible inside the function: ;; (def v1 1) (def v2 2) (defn sum [v1 v2] (+ v1 v2)) (sum 10 25) ;;=> 35 v1 v2 ;; ;; There is another way to create local binding ;; which are valid only inside the s-expr block, ;; using `let`. With the let form you can create ;; local variable which are visible only inside ;; the block. (let [v1 23 v2 45] ;; inside this block v1 v2 have the values 23 and 45 (+ v1 v2)) ;;=> 68 ;; ;; outside the block v1 and v2 are resolved in the ;; parent scope which in this case is the ;; namespace/global You can even nest `let` ;; bindings and use them inside functions. Here ;; we use `println` to print to the standard ;; output a message (let [v1 "this is a local value"] ;; outer block (println "outer-v1:" v1) (let [v1 1] ;; inner block (println "inner-v1:" v1)) (println "after-v1:" v1)) (println "global-v1:" v1) ;; global ;;=> outer-v1: this is a local value ;;=> inner-v1: 1 ;;=> after-v1: this is a local value ;;=> global-v1: hello ;; ;; ### Core functions ;; ;; The core has hundreds of functions defined, ;; which all work on the basic data structures ;; that we've seen so far. You can find the full list ;; in the [Clojure cheatsheet](http://clojure.org/api/cheatsheet) ;; ;; ;; #### The function: `apply` ;; ;; For the purpose of this course we will ;; only see a few examples starting with `apply`. ;; As the same suggests, it "applies" a function ;; to a given list of arguments. ;; ;; (apply f args) ;; (apply f x args) ;; (def words ["Hello" " " "world!"]) (str ["Hello" " " "world!"]) ;;=> "[\"Hello\" \" \" \"world!\"]" (apply str ["Hello" " " "world!"]) ;;=> "Hello world!" (apply str "first-argument: " ["Hello" " " "world!"]) ;;=> "first-argument: Hello world!" ;; ;; #### The function: `map` ;; ;; Next we will see one of the most used functions ;; in the core `map` which has nothing to do with ;; the associative maps (data structures) we seen ;; before. `map` comes from the set theory and is ;; a function which takes a function and a ;; sequence of values and applies the function to ;; all values in the sequence. It returns a ;; lazy-sequence which means that the function ;; application is not performed when calling `map`, ;; but it will be performed when the result will ;; be consumed. ;; ;; (map f coll) ;; (map clojure.string/upper-case ["Hello" "world!"]) ;;=> ("HELLO" "WORLD!") ;; ;; #### The function: `mapcat` ;; ;; Sometimes the application of the function `f` ;; returns a list of things. In the following ;; example, applying the split function to each sentence ;; spilts each sentence and returns a list of words. ;; (map #(clojure.string/split % #"\W+") ["Lorem ipsum dolor sit amet, consectetur adipiscing elit." "Duis vel ante est." "Pellentesque habitant morbi tristique" "senectus et netus et malesuada fames ac turpis egestas."]) ;; application of the split function to a single ;; sentence produces a list of words. Consequently ;; the application of the function to all ;; sentences produces a list of lists. If we ;; rather have a single list with all the words we ;; then need to concatenate all the sub-lists into ;; one. To do so Clojure core has the `concat` ;; function which just concatenates multiple lists ;; into one. (concat [0 1 2 3] [:a :b :c] '(d e f)) ;;=> (0 1 2 3 :a :b :c d e f) ;; To obtain a single list of all words we just need ;; to apply the `concat` function to the `map` result. (apply concat (map #(clojure.string/split % #"\W+") ["Lorem ipsum dolor sit amet, consectetur adipiscing elit." "Duis vel ante est." "Pellentesque habitant morbi tristique" "senectus et netus et malesuada fames ac turpis egestas."])) ;;=> ("Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing" "elit" "Duis" "vel" "ante" "est" "Pellentesque" "habitant" "morbi" "tristique" "senectus" "et" "netus" "et" "malesuada" "fames" "ac" "turpis" "egestas") ;; ;; This construct is common enough that Clojure has ;; a core function that does just this called `mapcat`. (mapcat #(clojure.string/split % #"\W+") ["Lorem ipsum dolor sit amet, consectetur adipiscing elit." "Duis vel ante est." "Pellentesque habitant morbi tristique" "senectus et netus et malesuada fames ac turpis egestas."]) ;;=> ("Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing" "elit" "Duis" "vel" "ante" "est" "Pellentesque" "habitant" "morbi" "tristique" "senectus" "et" "netus" "et" "malesuada" "fames" "ac" "turpis" "egestas") ;; ;; ;; #### The function: `reduce` ;; ;; Hadoop uses the two concept of `map` and ;; `reduce` to perform arbitrary computation on ;; large data. Clojure has `reduce` as core ;; function as well. While `map` is applied ;; one-by-one to all arguments with the objective ;; of performing a transformation `reduce` seeks ;; to summarize many values into one. For example ;; if you want to find the total sum of a list of ;; values you can use reduce in the following way. ;; ;; (reduce f coll) ;; ;; It can be used with many core functions ;; like the arithmetic functions `+`, `*` ;; but also with functions like `max` and `min` ;; which respectively return the highest and ;; the lowest value passed. But they ;; can be used with your own functions too. ;; (reduce + [10 15 23 32 43 54 12 11]) ;;=> 200 (reduce * [10 15 23 32 43 54 12 11]) ;;=> 33838041600 (reduce max [10 15 23 32 43 54 12 11]) ;;=> 54 (reduce str ["Hello" " " "world!"]) ;;=> "Hello world!" ;; ;; #### The function: `filter` ;; ;; The next function in the core is `filter` which ;; takes a *predicate function* and a collection ;; and returns a lazy-sequence of the items in the ;; collection for which the application of the ;; function returns a "truthy" value. Predicate ;; functions are functions which takes one ;; parameter and return a logical true or false. ;; ;; (filter pred? coll) ;; ;; For example: (filter odd? [0 1 2 3 4 5 6 7]) ;;=> (1 3 5 7) (filter #(> (count %) 5) ["Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing"]) ;;=> ("consectetur" "adipiscing") ;; ;; `identity` is a function which given a value ;; will just return the value. ;; This is often used when a function transformation ;; is required as parameter, but no transformation is wanted. ;; another idiomatic use of it is to remove nil and false ;; from a collection. ;; (filter identity ["Lorem" "ipsum" nil "sit" nil "consectetur" nil]) ;;=> ("Lorem" "ipsum" "sit" "consectetur") ;; ;; The function `remove` is the dual of `filter` ;; in the sense that is will remove the items ;; for which the predicate function returns true. ;; (filter odd? [0 1 2 3 4 5 6 7]) ;;=> (1 3 5 7) (remove odd? [0 1 2 3 4 5 6 7]) ;;=> (0 2 4 6) ;; ;; #### The function: `sort` ;; ;; `sort` as you would expect returns a sorted ;; sequence of the elements in the given collection. ;; ;; (sort coll) ;; (sort comp coll) ;; (sort [8 3 5 2 5 7 9 4 3 1 0]) ;;=> (0 1 2 3 3 4 5 5 7 8 9) (sort > [8 3 5 2 5 7 9 4 3 1 0]) ;;=> (9 8 7 5 5 4 3 3 2 1 0) (sort-by count ["Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing"]) ;;=> ("sit" "amet" "Lorem" "ipsum" "dolor" "adipiscing" "consectetur") (sort-by count > ["Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing"]) ;;=> ("consectetur" "adipiscing" "Lorem" "ipsum" "dolor" "amet" "sit") (sort-by :score > [{:user "john1" :score 345} {:user "fred3" :score 75} {:user "sam2" :score 291}]) ;;=> ({:user "john1", :score 345} {:user "sam2", :score 291} {:user "fred3", :score 75}) ;; ;; A similar function is `sort-by` which accepts a ;; function which is applied to the item before the ;; comparison. ;; ;; ;; #### The function: `group-by` ;; ;; Out of the box in Clojure you have a function ;; to perform grouping on your data. `group-by` ;; accepts a function and a collection and it will ;; apply the given function to all items in the ;; collection and then group the items using the ;; result of the function, i.e items that give the ;; same result when the function is applied end up ;; in the same group. Each group will be ;; associated with it's common function result. ;; It returns a map where the key is the group ;; common function result, and the value of the ;; map is a list of items which belong to that ;; group. (group-by odd? (range 10)) ;;=> {false [0 2 4 6 8], true [1 3 5 7 9]} (group-by count ["Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing"]) ;;=> {5 ["Lorem" "ipsum" "dolor"], 3 ["sit"], 4 ["amet"], 11 ["consectetur"], 10 ["adipiscing"]} (group-by :user-id [{:user-id 1 :uri "/"} {:user-id 2 :uri "/foo"} {:user-id 1 :uri "/account"}]) ;;=> {1 [{:user-id 1, :uri "/"} {:user-id 1, :uri "/account"}], 2 [{:user-id 2, :uri "/foo"}]} ;; ;; #### The function: `frequencies` ;; ;; When looking to count how frequent an item appears ;; in a collection for example to compute histograms ;; you can use the function called `frequencies`. ;; (frequencies ["john" "fred" "alice" "fred" "jason" "john" "alice" "john"]) ;;=> {"john" 3, "fred" 2, "alice" 2, "jason" 1} (frequencies [1 2 3 1 2 3 2 3 1 2 3 3 2 3 2 3 4 4]) ;;=> {1 3, 2 6, 3 7, 4 2} ;; ;; ;; #### The function: `partition` ;; ;; Another interesting group of functions in the Clojure ;; core are `partition`, `partition-all`, `partition-by`. ;; Here we will see only the first two. ;; `partition` chunks the given sequence into ;; sub-sequences (lazy) of `n` items each. ;; ;; (partition n coll) ;; (partition n step coll) ;; (partition 3 (range 11)) ;;=> ((0 1 2) (3 4 5) (6 7 8)) ;; `partition-all` does the same, but it returns ;; also chunks of which are incomplete. (partition-all 3 (range 11)) ;;=> ((0 1 2) (3 4 5) (6 7 8) (9 10)) ;; ;; The `step` parameters tells the function how ;; many item has to move forward after every ;; chunk. if not given `step` is equal to `n` (partition 3 1 (range 11)) ;;=> ((0 1 2) (1 2 3) (2 3 4) (3 4 5) (4 5 6) (5 6 7) (6 7 8) (7 8 9) (8 9 10)) (partition 3 5 (range 11)) ;;=> ((0 1 2) (5 6 7)) ;; ;; #### The function: `into` ;; ;; `into` is used to create a new collection of a ;; given type with all items from another ;; collection "into" it. Items are conjoined ;; using `conj`. It is often used to change the ;; type of a collection, or to build a map out of ;; key/value pairs. ;; ;; (into dest source) ;; (into [] '(0 1 2 3 4 5 6 7 8 9)) ;;=> [0 1 2 3 4 5 6 7 8 9] (into '() '(0 1 2 3 4 5 6 7 8 9)) ;;=> (9 8 7 6 5 4 3 2 1 0) (into (sorted-map) {:b 2, :c 3, :a 1}) ;;=> {:a 1, :b 2, :c 3} (into {} [[:a 1] [:b 2] [:c 3]]) ;;=> {:a 1, :b 2, :c 3} (map (fn [e] [(first e) (inc (second e))]) {:a 1, :b 2, :c 3}) ;;=> ([:a 2] [:b 3] [:c 4]) (into {} (map (fn [e] [(first e) (inc (second e))]) {:a 1, :b 2, :c 3})) ;;=> {:a 2, :b 3, :c 4} ;; ;; ;; ### Operation with files ;; ;; To open, read, write files there are wrappers ;; from the java machinery for files. However here ;; we will only see how to read and write text ;; files which are small enough to fit in memory. ;; ;; To write some text in a file you can use the ;; function `spit`, while to read the content of a ;; file as a string you can use `slurp`. ;; (spit "/tmp/my-file.txt" "This is the content") ;;=> nil (slurp "/tmp/my-file.txt") ;;=> "This is the content." ;; ;; ### Error handling ;; ;; What happens if the file you trying to read ;; doesn't exists? or the device you trying to ;; write to is full? The underlying Java APIs will ;; throw an exception. Clojure provides access to ;; the java machinery for error handling and you ;; can use `try`, `catch`, `finally` and `throw` ;; with the same semantic as the Java's ones. ;; ;; You have to surround the code which might throw ;; an exception using a `try` form, then you can ;; handle the errors by their native type with a ;; `catch` block. Finally is a block that gets ;; executed no matter what happen in the try block and ;; whether or not an exception is raised. `throw` ;; is used to throw an exception from your own code. (slurp "/this_doesnt_exists.txt") ;;=> FileNotFoundException /this_doesnt_exists.txt (No such file or directory) (try (slurp "/this_doesnt_exists.txt") (catch Exception x (println "unable to read file.") "")) ;;=> unable to read file ;;=> "" ;; ;; ### Destructuring ;; ;; The complete guide to Clojure destructuring ;; http://blog.brunobonacci.com/2014/11/16/clojure-complete-guide-to-destructuring/ ;; ;; ;; ### Macros ;; ;; The macros are function which are executed at ;; compile time by the compiler. The take code as ;; input, and the output is still code. The code ;; is expressed in the same stuff you have seen so ;; far: lists, symbols, keywords, vectors, maps ;; strings etc and from a user point of view they ;; look just like normal Clojure functions ;; (almost). It is a great way to extends the ;; language to meet your domain needs. However I ;; think this is a topic for a more advanced ;; course. If you want to learn the basics of the ;; macro you can read the following blog post: ;; ;; A "dead simple" introduction to Clojure macros. ;; http://blog.brunobonacci.com/2015/04/19/dead-simple-introduction-to-clojure-macros/ ;; (require '[clojure.string :as str]) (into #{} (map str/upper-case (str/split "this is a great language and a great platform" #" "))) (->> (str/split "this is a great language and a great platform" #" ") (map str/upper-case) (into #{})) (macroexpand '(->> (str/split "this is a great language and a great platform" #" ") (map str/upper-case) (into #{}))) ;; can write a macro which turn my expression into a Go-like ;; expression which never throws exceptions? ;;
7640
(ns learn-clojure.basics-simple (:require [clojure.string :as str])) ;; ~~~ Introduction to Clojure programming ~~~ ;; ;; .okko. ;; lMMWMMMx ;; ;N:. ;XMo ;; x, 0W. ;; .Wk ;; xM. ;; .XMk ;; KMMM. ;; .KMMWMd ;; .XMMW,kW. ;; KMMM: 'Mo ;; 0MMMc 0N ;; 0MMMl ;Md ;; 0MMMl KM; .d ;; 0MMMd ,MWo. '0d ;; 0MMMk :WMMMMMK. ;; 'llll .:dxd; ;; ;; Bruno Bonacci ;; ;; ## Clojure basics ;; ;; Clojure basics, ground up, with no assumption ;; of previous Clojure knowledge (just general ;; programming). ;; ;; ### The REPL ;; ;; REPL stands for Read Eval Print Loop. ;; ;; Many languages have REPLs but none allow ;; for a full range of in-flow development ;; such as LISP ones. ;; ;; Better than TDD, the **REPL Driven Development** ;; offers the fastest feedback. ;; ;; ;; ### Clojure syntax ;; ;; Syntax is based on `s-expressions` ;; a regular markup language which ;; gives the power to LISP macro system. ;; ;; General format is: ;; ( funciton arg1 arg2 ... argn ) ;; The key is `homoiconicity`!!! ;; ;; ### Comments ;; this is a valid comment ;; and will be skipped by the reader ;; the next line is logical comment ;; more line a NO-OP instruction (comment "something") ; in-line comment ;; but it requires to have valid clojure (comment a : b : c) ; this is BAD ;; ;; ### The function call. ;; ;; // java and C++ ;; myObject.myFunction(arg1, arg2, arg3); ;; ;; // C ;; myFunction(myStruct, arg1, arg2, arg3); ;; ;; ;; Clojure ;; (my-function myObject arg1 arg2 arg3) ;; ;; ;; Examples: ;; ;; // java ;; "Hello World!".toLowerCase(); ;; ;; // C - single char ;; tolower(*c); ;; // C - Whole string ;; for ( ; *c; ++c) *c = tolower(*c); ;; ^^^^^^^^^^^^^ ;; ;; ;; Clojure ;; (lower-case "Hello World!") ;; ;; ### Simple values ;; ;; Al simple values evaluate to themselves. true false nil 1 -4 29384756298374652983746528376529837456 127 ;;=> 127 ; decimal 0x7F ;;=> 127 ; hexadecimal 0177 ;;=> 127 ; octal 32r3V ;;=> 127 ; base 32 2r01111111 ;;=> 127 ; binary 36r3J ;;=> 127 ; base 36 36rClojure ;;=> 27432414842 2r0111001101010001001001 ;;=> 1889353 ;; ;; In Clojure there are no operators, in fact `+`, ;; `-`, `*` and `/` are normal functions. ;; (+ 1 2 3 4 5) ;; ;; You can access static fields by ;; providing the fully qualified class name ;; followed by a slash (`/`) and the field name, ;; for example: `java.lang.Long/MAX_VALUE`. ;; Numbers can be auto-promoted using appropriate ;; functions like `+'` and `*'` (+ 1 java.lang.Long/MAX_VALUE) (+' 1 java.lang.Long/MAX_VALUE) (*' java.lang.Long/MAX_VALUE java.lang.Long/MAX_VALUE) 3.2 (type 3.2) (type 3.2M) (+ 0.3 0.3 0.3 0.1 ) ;; floating point (+ 0.3M 0.3M 0.3M 0.1M) ;; big-decimal (/ 1 3) (type 1/3) (+ 1/3 1/3 1/3) (/ 21 6) (+ 1/3 1/3 1/3 4) \a ; this is the character 'a' \A ; this is the character 'A' \\ ; this is the character '\' \u0041 ; this is unicode for 'A' \tab ; this is the tab character \newline ; this is the newline character \space ; this is the space character \a ;;=> \a (type \a) "This is a string" (type "This is a string") "Strings in Clojure can be multi lines as well!!" ;; java inter-operation ;; "This is a String".toUpperCase() (.toUpperCase "This is a String") (str "This" " is " "a" " concatenation.") (str "Number of lines: " 123) ;; ## Conditionals & Flow control ;; ;; `truthiness` in Clojure ;; `nil` and `false` are falsey, everything ;; else is truthy ;; ;; (if condition ;; then-expr ;; else-expr) ;; ;; ;; (cond ;; condition1 expr1 ;; condition2 expr2 ;; condition3 expr3 ;; :else default-expr) ;; ;; There are more options for flow control in Clojure ;; i.e `if`,`not`, `and`, `or`, `if-not`, ;; `when`, `when-not`, `cond` and `case`. (if true "it's true" "it's false") (if false "it's true" "it's false") (if nil "it's true" "it's false") (if "HELLO" "it's true" "it's false") (if 1 "it's true" "it's false") ;; ### Keywords ;; :blue (type :this-is-a-keyword) (keyword "blue") (= :blue :blue) ;;=> true (= (str "bl" "ue") (str "bl" "ue")) (identical? (str "bl" "ue") (str "bl" "ue")) (identical? :blue :blue) (identical? (keyword (str "bl" "ue")) (keyword (str "bl" "ue"))) ;; ;; ### Collections ;; ;; Collections in Clojure are: ;; - Immutable by default ;; - Persistent data structures (sharing) ;; - Just values (like 42) ;; - Every collection can hold any value ;; ;; #### Lists ;; ;; Clojure has single-linked lists built-in and ;; like all other Clojure collections are ;; immutable. Lists guarantee `O(1)` insertion on ;; the head, `O(n)` traversal and element search. ;; (list 1 2 3 4 5) (cons 0 (list 1 2 3 4 5)) ;; As the output suggest the lists literals in ;; Clojure are expressed with a sequence of values ;; surrounded by brackets, which is the same of ;; the function call. That is the reason why the ;; following line throws an error. (1 2 3 4 5) (quote (1 2 3 4 5)) '(1 2 3 4 5) '(1 "hi" :test 4/5 \c) ;; you can get the head of the list with the ;; function `first` and use `rest` or `next` to ;; get the tail. `count` returns the number of ;; elements in it. `nth` returns the nth element ;; of the list, while `last` returns last item in ;; the list. ;; (first '(1 2 3 4 5)) (rest '(1 2 3 4 5)) (next '(1 2 3 4 5)) (rest '(1)) (next '(1)) (count '(5)) (count '(1 2 3 4 5)) (nth '(1 2 3 4 5) 0) (nth '(1 2 3 4 5) 1) (nth '(1 2 3 4 5) 10) (nth '(1 2 3 4 5) 10 :not-found) (last '(1 2 3 4 5)) (last '(1)) (last '()) ;; ;; #### Vectors ;; ;; Vectors are collections of values which are ;; indexed by their position in the vector ;; (starting from 0) called **index**. Insertion ;; at the end of the vector is `near O(1)` as well ;; as retrieval of an element by it's index. The ;; literals is expressed with a sequence of values ;; surrounded by square brackets or you can use ;; the `vector` function to construct one. You ;; can append an element at the end of the vector ;; with `conj` and use `get` to retrieve an ;; element in a specific index. Function such as ;; `first`, `next` `rest`, `last` and `count` will ;; work just as fine with Vectors. [1 2 3 4 5] [1 "hi" :test 4/5 \c] (vector 1 2 3 4 5) (conj [1 2 3 4 5] 6) (count [1 2]) (first [:a :b :c]) (get [:a :b :c] 1) (get [:a :b :c] 10) (get [:a :b :c] 10 :z) ;; #### Maps ;; ;; Maps are associative data structures (often ;; called dictionaries) which maps keys to their ;; corresponding value. Maps have a literal form ;; which can be expressed by any number of ;; key/value pairs surrounded by curly brackets, ;; or by using `hash-map` or `array-map` ;; functions. Hash-maps provides a `near O(1)` ;; insertion time and `near O(1)` seek time. You ;; can use `assoc` to "add or overwrite" an new ;; pair, `dissoc` to "remove" a key and its value, ;; and use `get` to retrieve the value of a given ;; key. {"jane" "<EMAIL>" "fred" "<EMAIL>" "rob" "<EMAIL>"} {:a 1, :b 2, :c 3} (hash-map :a 1, :b 2, :c 3) (array-map :a 1, :b 2, :c 3) (assoc {:a 1, :b 2, :c 3} :d 4) (assoc {:a 1, :b 2, :c 3} :b 10) (dissoc {:a 1, :b 2, :c 3} :b) (count {:a 1, :b 2, :c 3}) (get {:a 1, :b 2, :c 3} :a) (get {:a 1, :b 2, :c 3} :a :not-found) (get {:a 1, :b 2, :c 3} :ZULU :not-found) (:a {:a 1, :b 2, :c 3}) ;; ;; #### Sets ;; ;; Sets are a type of collection which doesn't ;; allow for duplicate values. While lists and ;; vector can have duplicate elements, set ;; eliminates all duplicates. Clojure has a ;; literal form for sets which is expressed by a ;; sequence of values surrounded by `#{ ;; }`. Otherwise you construct a set using the ;; `set` function. With `conj` you can "add" a ;; new element to an existing set, and `disj` to ;; "remove" an element from the set. With ;; `clojure.set/union`, `clojure.set/difference` ;; and `clojure.set/intersection` you have typical ;; sets operations. `count` returns the number of ;; elements in the set in `O(1)` time. #{1 2 4} #{:a 4 5 :d "hello"} (type #{:a :z}) (set [:a :b :c]) (conj #{:a :c} :b) (conj #{:a :c} :c) (disj #{:a :b :c} :b) (clojure.set/union #{:a} #{:a :b} #{:c :a}) (clojure.set/difference #{:a :b} #{:c :a}) (clojure.set/intersection #{:a :b} #{:c :a}) ;; ;; ### The sequence abstraction ;; ;; One of the most powerful abstraction of ;; Clojure's data structures is the `sequence` ;; (`clojure.lang.ISeq`) which all data structure ;; implements. This interface resembles to a Java ;; iterator, and it implements methods like ;; `first()`, `rest()`, `more()` and `cons()`. The ;; power of this abstraction is that it is general ;; enough to be used in all data structures ;; (lists, vectors, maps, sets and even strings ;; can all produce sequences) and you have loads ;; of functions which manipulates it. Functions ;; such as `first`, `rest`, `next` and `last` and ;; many others such as `reverse`, `shuffle`, ;; `drop`, `take`, `partition`, `filter` etc are ;; all built on top of the sequence abstraction. ;; So if you create your own data-structure and ;; you implement the four methods of the ;; `clojure.lang.ISeq` interface you can benefit ;; from all these function without having to ;; re-implement them for your specific ;; data-structure. ;; (first [1 2 3 4]) (take 3 [:a :b :c :d :e]) (shuffle [1 2 3 4]) (shuffle #{1 2 3 4}) (reverse [1 2 3 4]) (last (reverse {:a 1 :b 2 :c 3})) (seq "Hello World!") (first "Hello") (rest "Hello") (count "Hello World!") ;; ;; #### Lazy Sequences ;; ;; Some of the sequences produced by the core ;; library are lazy which means that the entire ;; collection won't be created (*realised*) all at ;; once but when the elements are requested. (range 5 10) ;; _**WARNING!!!** Evaluating this from your REPL ;; might hang/crash your process_, as it will try ;; evaluate an infinite lazy sequence all at once. (range) (take 10 (range)) ;; ;; ### Regular expression patterns ;; #"[\w\d.-]+@[\w\d-.]+\.[\w]+" (type #"[\w\d.-]+@[\w\d-.]+\.[\w]+") (re-find #"[0-9]+" "only 123 numbers") (re-find #"[0-9]+" "no numbers") (re-find #"[\w\d.-]+@[\w\d-.]+\.[\w]+" "<EMAIL>") (if (re-find #"^[\w\d.-]+@[\w\d-.]+\.[\w]+$" "<EMAIL>") "it's an email" "it's not an email") (re-seq #"[0-9]+" "25, 43, 54, 12, 15, 65") (re-pattern "[0-9]{1,3}(\\.[0-9]{1,3}){3}") (re-find (re-pattern "[0-9]{1,3}(\\.[0-9]{1,3}){3}") "my IP is: 192.168.0.12") ;; ;; Using `re-matcher`, `re-matches`, `re-groups` ;; allows you to have fine control over the capturing ;; groups. ;; ;; ### Symbols and Vars ;; ;; Symbols in Clojure are a way to identify things ;; in your programs which may have various values ;; at runtime. Like in a mathematical notation, `x` ;; is something not known which could assume ;; several different values. In a programming ;; context, Clojure symbols are similar to ;; variables in other languages but not exactly. ;; In other languages variables are places where ;; you store information, symbols in Clojure ;; cannot contain data themselves. Vars in ;; Clojure are the containers of data (one type ;; of), and symbols are a way to identify them and ;; give vars meaningful names for your program. ;; username 'username (symbol "username") (type (symbol "username")) (def username "bruno1") username age ;; undefined var produces error (def age 21) age (type 'age) (type age) (def user {:username "bruno1" :score 12345 :level 32 :achievements #{:fast-run :precision10 :strategy}}) user (def user nil) user ;; ;; ### Immutability ;; ;; All basics data-types in Clojure are immutable, ;; including the collections. This is a very ;; important aspect of Clojure approach to ;; functional programming. In Clojure functions ;; transform values into new values and values are ;; just values. Since it is absurd to think of ;; changing a number (1 is always 1), ;; composite data structures are treated in the same way. ;; So functions do not mutate values they just produce new ones. ;; Like adding `1` to `42` produces `43` but ;; doesn't really change the number `42` as it keeps on ;; existing on its own, adding an element to a list will ;; produce a new list but the old one will still be same ;; and unmodified. ;; ;; The advantage of the immutability is that ;; values (even deeply nested and complex ;; structures) can be safely shared across threads ;; and with function callers without worrying ;; about unsafe or uncoordinated changes. This ;; simple constraint makes Clojure programs so ;; much easier to reason about, as the only way to ;; produce a new value is via a functional ;; transformation. ;; (def colours '(:red :green :blue)) (def new-colours (cons :black colours)) new-colours colours (def user {:username "bruno1" :score 12345 :level 32}) (def user' (assoc user :level 33)) user' user ;; ;; ### Functions ;; ;; So far we have seen how to represent data in ;; our system, now we will see how to make sense ;; of this data and how to ;; extract/process/transform it. The way we ;; express this in Clojure is via functions. ;; ;; ;; pure (+ 1 2 3) ;; impure (rand-int 100) ;; (+ 1 1 1) is referentially transparent (+ 1 2 (+ 1 1 1)) ;; ;; #### Function definition ;; ;; To define a function you have to use the ;; special form `fn` or `defn` with the following ;; syntax. ;; ;; for example if we want to define a function ;; which increments the input parameters by 1 you ;; will write something as follow: ;; ;; ``` ;; /- fn, special form ;; / parameter vector, 1 param called `n` ;; | | body -> expression to evaluate when ;; | | | this function is called ;; (fn [n] (+ n 1)) ;; ``` ;; ;; This is the simplest way to define a function. ;; ;; Now to refer to this function in our code we ;; need to give it a name. We can do so with `def` ;; as we done earlier. ;; (def plus-one (fn [n] (+ n 1))) ;;=> #'learn-clojure.basics/plus-one (plus-one 10) ;;=> 11 (plus-one -42) ;;=> -41 ;; ;; As mentioned earlier, during the evaluation process ;; the symbol `plus-one` is simply replaced with ;; its value, in the same way we can replace the ;; symbol with the function definition and obtain ;; the same result. So symbols can also refer to ;; functions. ;; Evaluation by substitution model. (plus-one 10) ((fn [n] (+ n 1)) 10) (fn [10] (+ 10 1)) (+ 10 1) 11 ;; def + fn = defn (defn plus-one [n] (+ n 1)) (plus-one 1) (defn plus-one "Returns a number which is one greater than the given `n`." [n] (+ n 1)) (inc 10) (defn make-ip4 [a b c d] (clojure.string/join "." [a b c d])) (make-ip4 192 168 0 1) (defn make-kebab [& words] (clojure.string/join "-" words)) (make-kebab "i" "like" "kebab") (defn greet ([] "Hey, Stranger!") ([name] (str "Hello " name)) ([firstname lastname] (str "Hi, you must be: " lastname ", " firstname " " lastname)) ([title firstname lastname] (str "Hello " title " " firstname " " lastname))) (greet) (greet "<NAME>") (greet "<NAME>" "<NAME>") (greet "Dr" "<NAME>." "<NAME>") ;; ;; #### High-order functions ;; ;; In Clojure functions are reified constructs, ;; therefore we can threat them as normal ;; values. As such functions can be passed as ;; parameters of function or returned as result of ;; function call. ;; (defn is-commutative? [op a b] (= (op a b) (op b a))) (is-commutative? + 3 7) (is-commutative? / 3 7) ;; function which return a function (defn multiplier [m] (fn [n] (* n m))) (def doubler (multiplier 2)) (doubler 5) (doubler 10) (def mult-10x (multiplier 10)) (mult-10x 35) ;; ;; #### Lambda functions (Anonymous) ;; ;; Oftentimes you want to create a function for a ;; specific task in a local context. Such ;; functions don't have any reason to have a ;; global name as they are meaningful only in that ;; specific context, in this case you can create ;; anonymous functions (also called lambda ;; function) and Clojure has some support to make ;; this easier. We already seen an example of an ;; anonymous function with our very first function ;; example. ;; (fn [n] (+ n 1)) ((fn [n] (+ n 1)) 10) ;;=> 11 #(+ % 1) (#(+ % 1) 10) ;; ;; In this function the symbol `%` replace the argument ;; If you have more than one parameter you can denote them as ;; `%1` (or `%`), `%2`, `%3`, `%4` ... ;; ;; for example in our `is-commutative?` function we expect ;; and operation which accept two arguments: (is-commutative? #(+ %1 %2) 9 8) ;; ;; #### Closures ;; ;; Closures (with the `s`) are lambdas which refer ;; to a context (or values from another context). ;; These functions are said to be "closing over" ;; the environment. This means that it can access ;; parameters and values which are NOT in the ;; parameters list. ;; ;; Like in our `multiplier` function example, the ;; returned function is closing over the value `m` ;; which is not in its parameter list but it is a ;; parameter of the parent context the ;; `multiplier` fn. While `n` is a normal ;; parameter `m` is the value we are "closing ;; over" providing a context for that function. (defn multiplier [m] (fn [n] (* n m))) ;; ;; #### Recursion ;; ;; A recursive function is a function which ;; calls itself. There are two types of recursion ;; the mundane recursion and the tail recursion. ;; ;; Let's see an example of both with this function ;; which given a number it calculates the sum of ;; all natural numbers from 1 to the given ;; number. (defn sum1 ([n] (sum1 n 0)) ([n accumulator] (if (< n 1) accumulator ;; else (sum1 (dec n) (+ n accumulator))))) (sum1 1) (sum1 3) (sum1 10) ;; ;; This type of recursion is called mundane ;; recursion and every new call it allocates one ;; new frame on the stack so if you run this with ;; high enough numbers it will blow your stack. ;; (sum1 10000) ;;=> java.lang.StackOverflowError ;; ;; Let's see how we can write this ;; function with a tail recursion using ;; `recur`. ;; (defn sum2 ([n] (sum2 n 0)) ([n accumulator] (if (< n 1) accumulator ;; else (recur (dec n) (+ n accumulator))))) ;;=> #'learn-clojure.basics/sum2 (sum2 10) (sum2 10000) (sum2 1000000) (sum2 100000000) ;; Let's see how we can rewrite the previous ;; function to leverage the `loop/recur` ;; construct. (defn sum3 [num] (loop [n num accumulator 0] (if (< n 1) accumulator ;; else (recur (dec n) (+ n accumulator))))) (sum3 10) ;; Let's see another example with the Fibonacci ;; sequence. Let's start with the mundane ;; recursion. ;; !!! this is O(2^n) (defn fibonacci1 [n] (if (< n 2) 1 ;; else (+ (fibonacci1 (- n 1)) (fibonacci1 (- n 2))))) (fibonacci1 1) (fibonacci1 10) ;; ;; Now this is a simple and very functional ;; definition of the Fibonacci sequence, however ;; it is particularly bad in terms of computational ;; complexity. in fact this is `O(2^n)`. ;; Let's use the `time` function to ;; calculate how much it takes to compute the ;; 35th number in the sequence. ;; (time (fibonacci1 35)) ;; ;; Let's try to use tail recursion. ;; As you will see we have to restructure ;; our function to allow the recursion ;; to happen in the tail position. ;; (defn fibonacci2 [n] (loop [i n c 1 p 1] (if (< i 2) c (recur (dec i) (+' c p) c)))) (fibonacci2 10) (time (fibonacci2 35)) (time (fibonacci2 1000)) ;; ;; #### Function composition and partial functions ;; ;; We have seen earlier that there are functions ;; such as `first`, `second`, `last` and `rest` to ;; access respectively the first item of the ;; sequence, the second item, the last item and ;; the tail of the sequence. These functions can ;; be combined to create other functions for ;; accessing the third, fourth, fifth and other ;; positional items. The following functions are ;; an example of how to construct two such ;; functions. (defn third [coll] (first (rest (rest coll)))) (third '(1 2 3 4 5)) ;;=> 3 (defn fourth [coll] (first (rest (rest (rest coll))))) (fourth '(1 2 3 4 5)) ;;=> 4 ;; But there is another way. If, like in this ;; case, the output of a function can be passed ;; directly into the input of the next one as a ;; simple pipeline of functions then you can just ;; use the `comp` function. ;; ;; (comp f1 f2 f3 ... fn) ;; ;; (comp f1 f2 f3) = (f1 (f2 (f3 ,,,))) ;; (def third (comp first rest rest)) (def fourth (comp first rest rest rest)) (third '(1 2 3 4 5)) ;;=> 3 (fourth '(1 2 3 4 5)) ;;=> 4 ;; Let's see another example. Let's assume ;; we have to write a function which given ;; a number it doubles it and subtract 1 ;; from it. So we can use the `multiplier` ;; function we wrote earlier to accomplish ;; the first part and the Clojure core `dec` ;; to decrement it by one and compose them ;; together with `comp`. (defn multiplier [m] (fn [n] (* n m))) (def doubler (multiplier 2)) (def almost-twice (comp dec doubler)) (almost-twice 5) ;;=> 9 (almost-twice 9) ;;=> 17 ;; ;; Now let's say we want to create a function ;; which given a number perform `almost-twice` two ;; times. ;; (def almost-twice-twice (comp almost-twice almost-twice)) (almost-twice-twice 5) ;;=> 17 (almost-twice-twice 10) ;;=> 37 ;; Another way we could have written the `doubler` ;; function is by using the partial application of ;; the function `*`. In Clojure this is achieved ;; via the function `partial`. ;; ;; (partial f arg1 ... argn) ;; (def doubler (partial * 2)) (doubler 5) ;;=> 10 ;; what happens here is that the `partial` ;; function returns a function which calls `*` ;; with the parameters of the partial and the ;; parameter of the final call, all in one call. ;; ;; ;; ;; ### Vars, namespaces, scope and local bindings ;; ;; When defining a var using `def` or `defn` ;; followed by symbol, the symbol is created ;; in the local namespace. ;; When starting the REPL in a empty project ;; the default namespace is called `user` ;; so unless you configure differently ;; all your vars will be created there. ;; ;; Namespaces are like containers in which ;; vars live in, but namespaces, ;; once defined are **globally accessible**. ;; As a consequence when you define a var ;; using `def` or `defn` these will be accessible ;; globally. ;; ;; We will use `ns` which create a namespace if ;; not present and switch to it, and `in-ns` just ;; changes the current namespace. we will see how ;; to loads namespaces we need with our processing ;; with `require` and how vars are globally ;; accessible. (ns user.test.one) ;;=> nil (def my-name "<NAME>") ;;=> #'user.test.one/my-name my-name ;;=> "<NAME>" (ns user.test.two) ;;=> nil (def my-name "<NAME>") ;;=> #'user.test.two/my-name my-name ;;=> "<NAME>" user.test.one/my-name ;;=> "<NAME>" user.test.two/my-name ;;=> "<NAME>" (def my-name (clojure.string/upper-case "<NAME>")) ;;=> #'user.test.one/my-name (ns user.test.one (:require [clojure.string :as s])) ;;=> nil (def my-name (s/upper-case "<NAME>")) ;;=> #'user.test.one/my-name (ns user.test.one (:require [clojure.string :refer [upper-case]])) ;;=> nil (def my-name (upper-case "<NAME>")) ;;=> #'user.test.one/my-name my-name ;;=> "<NAME>" ;; ;; The global accessible vars (globals) is one ;; level of scoping. If you don't want to have ;; globally accessible vars then you have to ;; use local bindings. ;; ;; We already had a glimpse of these while ;; defining functions. In fact parameters ;; are only visible inside the function: ;; (def v1 1) (def v2 2) (defn sum [v1 v2] (+ v1 v2)) (sum 10 25) ;;=> 35 v1 v2 ;; ;; There is another way to create local binding ;; which are valid only inside the s-expr block, ;; using `let`. With the let form you can create ;; local variable which are visible only inside ;; the block. (let [v1 23 v2 45] ;; inside this block v1 v2 have the values 23 and 45 (+ v1 v2)) ;;=> 68 ;; ;; outside the block v1 and v2 are resolved in the ;; parent scope which in this case is the ;; namespace/global You can even nest `let` ;; bindings and use them inside functions. Here ;; we use `println` to print to the standard ;; output a message (let [v1 "this is a local value"] ;; outer block (println "outer-v1:" v1) (let [v1 1] ;; inner block (println "inner-v1:" v1)) (println "after-v1:" v1)) (println "global-v1:" v1) ;; global ;;=> outer-v1: this is a local value ;;=> inner-v1: 1 ;;=> after-v1: this is a local value ;;=> global-v1: hello ;; ;; ### Core functions ;; ;; The core has hundreds of functions defined, ;; which all work on the basic data structures ;; that we've seen so far. You can find the full list ;; in the [Clojure cheatsheet](http://clojure.org/api/cheatsheet) ;; ;; ;; #### The function: `apply` ;; ;; For the purpose of this course we will ;; only see a few examples starting with `apply`. ;; As the same suggests, it "applies" a function ;; to a given list of arguments. ;; ;; (apply f args) ;; (apply f x args) ;; (def words ["Hello" " " "world!"]) (str ["Hello" " " "world!"]) ;;=> "[\"Hello\" \" \" \"world!\"]" (apply str ["Hello" " " "world!"]) ;;=> "Hello world!" (apply str "first-argument: " ["Hello" " " "world!"]) ;;=> "first-argument: Hello world!" ;; ;; #### The function: `map` ;; ;; Next we will see one of the most used functions ;; in the core `map` which has nothing to do with ;; the associative maps (data structures) we seen ;; before. `map` comes from the set theory and is ;; a function which takes a function and a ;; sequence of values and applies the function to ;; all values in the sequence. It returns a ;; lazy-sequence which means that the function ;; application is not performed when calling `map`, ;; but it will be performed when the result will ;; be consumed. ;; ;; (map f coll) ;; (map clojure.string/upper-case ["Hello" "world!"]) ;;=> ("HELLO" "WORLD!") ;; ;; #### The function: `mapcat` ;; ;; Sometimes the application of the function `f` ;; returns a list of things. In the following ;; example, applying the split function to each sentence ;; spilts each sentence and returns a list of words. ;; (map #(clojure.string/split % #"\W+") ["Lorem ipsum dolor sit amet, consectetur adipiscing elit." "Duis vel ante est." "Pellentesque habitant morbi tristique" "senectus et netus et malesuada fames ac turpis egestas."]) ;; application of the split function to a single ;; sentence produces a list of words. Consequently ;; the application of the function to all ;; sentences produces a list of lists. If we ;; rather have a single list with all the words we ;; then need to concatenate all the sub-lists into ;; one. To do so Clojure core has the `concat` ;; function which just concatenates multiple lists ;; into one. (concat [0 1 2 3] [:a :b :c] '(d e f)) ;;=> (0 1 2 3 :a :b :c d e f) ;; To obtain a single list of all words we just need ;; to apply the `concat` function to the `map` result. (apply concat (map #(clojure.string/split % #"\W+") ["Lorem ipsum dolor sit amet, consectetur adipiscing elit." "Duis vel ante est." "Pellentesque habitant morbi tristique" "senectus et netus et malesuada fames ac turpis egestas."])) ;;=> ("Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing" "elit" "Duis" "vel" "ante" "est" "Pellentesque" "habitant" "morbi" "tristique" "senectus" "et" "netus" "et" "malesuada" "fames" "ac" "turpis" "egestas") ;; ;; This construct is common enough that Clojure has ;; a core function that does just this called `mapcat`. (mapcat #(clojure.string/split % #"\W+") ["Lorem ipsum dolor sit amet, consectetur adipiscing elit." "Duis vel ante est." "Pellentesque habitant morbi tristique" "senectus et netus et malesuada fames ac turpis egestas."]) ;;=> ("Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing" "elit" "Duis" "vel" "ante" "est" "Pellentesque" "habitant" "morbi" "tristique" "senectus" "et" "netus" "et" "malesuada" "fames" "ac" "turpis" "egestas") ;; ;; ;; #### The function: `reduce` ;; ;; Hadoop uses the two concept of `map` and ;; `reduce` to perform arbitrary computation on ;; large data. Clojure has `reduce` as core ;; function as well. While `map` is applied ;; one-by-one to all arguments with the objective ;; of performing a transformation `reduce` seeks ;; to summarize many values into one. For example ;; if you want to find the total sum of a list of ;; values you can use reduce in the following way. ;; ;; (reduce f coll) ;; ;; It can be used with many core functions ;; like the arithmetic functions `+`, `*` ;; but also with functions like `max` and `min` ;; which respectively return the highest and ;; the lowest value passed. But they ;; can be used with your own functions too. ;; (reduce + [10 15 23 32 43 54 12 11]) ;;=> 200 (reduce * [10 15 23 32 43 54 12 11]) ;;=> 33838041600 (reduce max [10 15 23 32 43 54 12 11]) ;;=> 54 (reduce str ["Hello" " " "world!"]) ;;=> "Hello world!" ;; ;; #### The function: `filter` ;; ;; The next function in the core is `filter` which ;; takes a *predicate function* and a collection ;; and returns a lazy-sequence of the items in the ;; collection for which the application of the ;; function returns a "truthy" value. Predicate ;; functions are functions which takes one ;; parameter and return a logical true or false. ;; ;; (filter pred? coll) ;; ;; For example: (filter odd? [0 1 2 3 4 5 6 7]) ;;=> (1 3 5 7) (filter #(> (count %) 5) ["Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing"]) ;;=> ("consectetur" "adipiscing") ;; ;; `identity` is a function which given a value ;; will just return the value. ;; This is often used when a function transformation ;; is required as parameter, but no transformation is wanted. ;; another idiomatic use of it is to remove nil and false ;; from a collection. ;; (filter identity ["Lorem" "ipsum" nil "sit" nil "consectetur" nil]) ;;=> ("Lorem" "ipsum" "sit" "consectetur") ;; ;; The function `remove` is the dual of `filter` ;; in the sense that is will remove the items ;; for which the predicate function returns true. ;; (filter odd? [0 1 2 3 4 5 6 7]) ;;=> (1 3 5 7) (remove odd? [0 1 2 3 4 5 6 7]) ;;=> (0 2 4 6) ;; ;; #### The function: `sort` ;; ;; `sort` as you would expect returns a sorted ;; sequence of the elements in the given collection. ;; ;; (sort coll) ;; (sort comp coll) ;; (sort [8 3 5 2 5 7 9 4 3 1 0]) ;;=> (0 1 2 3 3 4 5 5 7 8 9) (sort > [8 3 5 2 5 7 9 4 3 1 0]) ;;=> (9 8 7 5 5 4 3 3 2 1 0) (sort-by count ["Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing"]) ;;=> ("sit" "amet" "Lorem" "ipsum" "dolor" "adipiscing" "consectetur") (sort-by count > ["Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing"]) ;;=> ("consectetur" "adipiscing" "Lorem" "ipsum" "dolor" "amet" "sit") (sort-by :score > [{:user "john1" :score 345} {:user "fred3" :score 75} {:user "sam2" :score 291}]) ;;=> ({:user "john1", :score 345} {:user "sam2", :score 291} {:user "fred3", :score 75}) ;; ;; A similar function is `sort-by` which accepts a ;; function which is applied to the item before the ;; comparison. ;; ;; ;; #### The function: `group-by` ;; ;; Out of the box in Clojure you have a function ;; to perform grouping on your data. `group-by` ;; accepts a function and a collection and it will ;; apply the given function to all items in the ;; collection and then group the items using the ;; result of the function, i.e items that give the ;; same result when the function is applied end up ;; in the same group. Each group will be ;; associated with it's common function result. ;; It returns a map where the key is the group ;; common function result, and the value of the ;; map is a list of items which belong to that ;; group. (group-by odd? (range 10)) ;;=> {false [0 2 4 6 8], true [1 3 5 7 9]} (group-by count ["Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing"]) ;;=> {5 ["Lorem" "ipsum" "dolor"], 3 ["sit"], 4 ["amet"], 11 ["consectetur"], 10 ["adipiscing"]} (group-by :user-id [{:user-id 1 :uri "/"} {:user-id 2 :uri "/foo"} {:user-id 1 :uri "/account"}]) ;;=> {1 [{:user-id 1, :uri "/"} {:user-id 1, :uri "/account"}], 2 [{:user-id 2, :uri "/foo"}]} ;; ;; #### The function: `frequencies` ;; ;; When looking to count how frequent an item appears ;; in a collection for example to compute histograms ;; you can use the function called `frequencies`. ;; (frequencies ["<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"]) ;;=> {"<NAME>" 3, "<NAME>" 2, "<NAME>" 2, "<NAME>" 1} (frequencies [1 2 3 1 2 3 2 3 1 2 3 3 2 3 2 3 4 4]) ;;=> {1 3, 2 6, 3 7, 4 2} ;; ;; ;; #### The function: `partition` ;; ;; Another interesting group of functions in the Clojure ;; core are `partition`, `partition-all`, `partition-by`. ;; Here we will see only the first two. ;; `partition` chunks the given sequence into ;; sub-sequences (lazy) of `n` items each. ;; ;; (partition n coll) ;; (partition n step coll) ;; (partition 3 (range 11)) ;;=> ((0 1 2) (3 4 5) (6 7 8)) ;; `partition-all` does the same, but it returns ;; also chunks of which are incomplete. (partition-all 3 (range 11)) ;;=> ((0 1 2) (3 4 5) (6 7 8) (9 10)) ;; ;; The `step` parameters tells the function how ;; many item has to move forward after every ;; chunk. if not given `step` is equal to `n` (partition 3 1 (range 11)) ;;=> ((0 1 2) (1 2 3) (2 3 4) (3 4 5) (4 5 6) (5 6 7) (6 7 8) (7 8 9) (8 9 10)) (partition 3 5 (range 11)) ;;=> ((0 1 2) (5 6 7)) ;; ;; #### The function: `into` ;; ;; `into` is used to create a new collection of a ;; given type with all items from another ;; collection "into" it. Items are conjoined ;; using `conj`. It is often used to change the ;; type of a collection, or to build a map out of ;; key/value pairs. ;; ;; (into dest source) ;; (into [] '(0 1 2 3 4 5 6 7 8 9)) ;;=> [0 1 2 3 4 5 6 7 8 9] (into '() '(0 1 2 3 4 5 6 7 8 9)) ;;=> (9 8 7 6 5 4 3 2 1 0) (into (sorted-map) {:b 2, :c 3, :a 1}) ;;=> {:a 1, :b 2, :c 3} (into {} [[:a 1] [:b 2] [:c 3]]) ;;=> {:a 1, :b 2, :c 3} (map (fn [e] [(first e) (inc (second e))]) {:a 1, :b 2, :c 3}) ;;=> ([:a 2] [:b 3] [:c 4]) (into {} (map (fn [e] [(first e) (inc (second e))]) {:a 1, :b 2, :c 3})) ;;=> {:a 2, :b 3, :c 4} ;; ;; ;; ### Operation with files ;; ;; To open, read, write files there are wrappers ;; from the java machinery for files. However here ;; we will only see how to read and write text ;; files which are small enough to fit in memory. ;; ;; To write some text in a file you can use the ;; function `spit`, while to read the content of a ;; file as a string you can use `slurp`. ;; (spit "/tmp/my-file.txt" "This is the content") ;;=> nil (slurp "/tmp/my-file.txt") ;;=> "This is the content." ;; ;; ### Error handling ;; ;; What happens if the file you trying to read ;; doesn't exists? or the device you trying to ;; write to is full? The underlying Java APIs will ;; throw an exception. Clojure provides access to ;; the java machinery for error handling and you ;; can use `try`, `catch`, `finally` and `throw` ;; with the same semantic as the Java's ones. ;; ;; You have to surround the code which might throw ;; an exception using a `try` form, then you can ;; handle the errors by their native type with a ;; `catch` block. Finally is a block that gets ;; executed no matter what happen in the try block and ;; whether or not an exception is raised. `throw` ;; is used to throw an exception from your own code. (slurp "/this_doesnt_exists.txt") ;;=> FileNotFoundException /this_doesnt_exists.txt (No such file or directory) (try (slurp "/this_doesnt_exists.txt") (catch Exception x (println "unable to read file.") "")) ;;=> unable to read file ;;=> "" ;; ;; ### Destructuring ;; ;; The complete guide to Clojure destructuring ;; http://blog.brunobonacci.com/2014/11/16/clojure-complete-guide-to-destructuring/ ;; ;; ;; ### Macros ;; ;; The macros are function which are executed at ;; compile time by the compiler. The take code as ;; input, and the output is still code. The code ;; is expressed in the same stuff you have seen so ;; far: lists, symbols, keywords, vectors, maps ;; strings etc and from a user point of view they ;; look just like normal Clojure functions ;; (almost). It is a great way to extends the ;; language to meet your domain needs. However I ;; think this is a topic for a more advanced ;; course. If you want to learn the basics of the ;; macro you can read the following blog post: ;; ;; A "dead simple" introduction to Clojure macros. ;; http://blog.brunobonacci.com/2015/04/19/dead-simple-introduction-to-clojure-macros/ ;; (require '[clojure.string :as str]) (into #{} (map str/upper-case (str/split "this is a great language and a great platform" #" "))) (->> (str/split "this is a great language and a great platform" #" ") (map str/upper-case) (into #{})) (macroexpand '(->> (str/split "this is a great language and a great platform" #" ") (map str/upper-case) (into #{}))) ;; can write a macro which turn my expression into a Go-like ;; expression which never throws exceptions? ;;
true
(ns learn-clojure.basics-simple (:require [clojure.string :as str])) ;; ~~~ Introduction to Clojure programming ~~~ ;; ;; .okko. ;; lMMWMMMx ;; ;N:. ;XMo ;; x, 0W. ;; .Wk ;; xM. ;; .XMk ;; KMMM. ;; .KMMWMd ;; .XMMW,kW. ;; KMMM: 'Mo ;; 0MMMc 0N ;; 0MMMl ;Md ;; 0MMMl KM; .d ;; 0MMMd ,MWo. '0d ;; 0MMMk :WMMMMMK. ;; 'llll .:dxd; ;; ;; Bruno Bonacci ;; ;; ## Clojure basics ;; ;; Clojure basics, ground up, with no assumption ;; of previous Clojure knowledge (just general ;; programming). ;; ;; ### The REPL ;; ;; REPL stands for Read Eval Print Loop. ;; ;; Many languages have REPLs but none allow ;; for a full range of in-flow development ;; such as LISP ones. ;; ;; Better than TDD, the **REPL Driven Development** ;; offers the fastest feedback. ;; ;; ;; ### Clojure syntax ;; ;; Syntax is based on `s-expressions` ;; a regular markup language which ;; gives the power to LISP macro system. ;; ;; General format is: ;; ( funciton arg1 arg2 ... argn ) ;; The key is `homoiconicity`!!! ;; ;; ### Comments ;; this is a valid comment ;; and will be skipped by the reader ;; the next line is logical comment ;; more line a NO-OP instruction (comment "something") ; in-line comment ;; but it requires to have valid clojure (comment a : b : c) ; this is BAD ;; ;; ### The function call. ;; ;; // java and C++ ;; myObject.myFunction(arg1, arg2, arg3); ;; ;; // C ;; myFunction(myStruct, arg1, arg2, arg3); ;; ;; ;; Clojure ;; (my-function myObject arg1 arg2 arg3) ;; ;; ;; Examples: ;; ;; // java ;; "Hello World!".toLowerCase(); ;; ;; // C - single char ;; tolower(*c); ;; // C - Whole string ;; for ( ; *c; ++c) *c = tolower(*c); ;; ^^^^^^^^^^^^^ ;; ;; ;; Clojure ;; (lower-case "Hello World!") ;; ;; ### Simple values ;; ;; Al simple values evaluate to themselves. true false nil 1 -4 29384756298374652983746528376529837456 127 ;;=> 127 ; decimal 0x7F ;;=> 127 ; hexadecimal 0177 ;;=> 127 ; octal 32r3V ;;=> 127 ; base 32 2r01111111 ;;=> 127 ; binary 36r3J ;;=> 127 ; base 36 36rClojure ;;=> 27432414842 2r0111001101010001001001 ;;=> 1889353 ;; ;; In Clojure there are no operators, in fact `+`, ;; `-`, `*` and `/` are normal functions. ;; (+ 1 2 3 4 5) ;; ;; You can access static fields by ;; providing the fully qualified class name ;; followed by a slash (`/`) and the field name, ;; for example: `java.lang.Long/MAX_VALUE`. ;; Numbers can be auto-promoted using appropriate ;; functions like `+'` and `*'` (+ 1 java.lang.Long/MAX_VALUE) (+' 1 java.lang.Long/MAX_VALUE) (*' java.lang.Long/MAX_VALUE java.lang.Long/MAX_VALUE) 3.2 (type 3.2) (type 3.2M) (+ 0.3 0.3 0.3 0.1 ) ;; floating point (+ 0.3M 0.3M 0.3M 0.1M) ;; big-decimal (/ 1 3) (type 1/3) (+ 1/3 1/3 1/3) (/ 21 6) (+ 1/3 1/3 1/3 4) \a ; this is the character 'a' \A ; this is the character 'A' \\ ; this is the character '\' \u0041 ; this is unicode for 'A' \tab ; this is the tab character \newline ; this is the newline character \space ; this is the space character \a ;;=> \a (type \a) "This is a string" (type "This is a string") "Strings in Clojure can be multi lines as well!!" ;; java inter-operation ;; "This is a String".toUpperCase() (.toUpperCase "This is a String") (str "This" " is " "a" " concatenation.") (str "Number of lines: " 123) ;; ## Conditionals & Flow control ;; ;; `truthiness` in Clojure ;; `nil` and `false` are falsey, everything ;; else is truthy ;; ;; (if condition ;; then-expr ;; else-expr) ;; ;; ;; (cond ;; condition1 expr1 ;; condition2 expr2 ;; condition3 expr3 ;; :else default-expr) ;; ;; There are more options for flow control in Clojure ;; i.e `if`,`not`, `and`, `or`, `if-not`, ;; `when`, `when-not`, `cond` and `case`. (if true "it's true" "it's false") (if false "it's true" "it's false") (if nil "it's true" "it's false") (if "HELLO" "it's true" "it's false") (if 1 "it's true" "it's false") ;; ### Keywords ;; :blue (type :this-is-a-keyword) (keyword "blue") (= :blue :blue) ;;=> true (= (str "bl" "ue") (str "bl" "ue")) (identical? (str "bl" "ue") (str "bl" "ue")) (identical? :blue :blue) (identical? (keyword (str "bl" "ue")) (keyword (str "bl" "ue"))) ;; ;; ### Collections ;; ;; Collections in Clojure are: ;; - Immutable by default ;; - Persistent data structures (sharing) ;; - Just values (like 42) ;; - Every collection can hold any value ;; ;; #### Lists ;; ;; Clojure has single-linked lists built-in and ;; like all other Clojure collections are ;; immutable. Lists guarantee `O(1)` insertion on ;; the head, `O(n)` traversal and element search. ;; (list 1 2 3 4 5) (cons 0 (list 1 2 3 4 5)) ;; As the output suggest the lists literals in ;; Clojure are expressed with a sequence of values ;; surrounded by brackets, which is the same of ;; the function call. That is the reason why the ;; following line throws an error. (1 2 3 4 5) (quote (1 2 3 4 5)) '(1 2 3 4 5) '(1 "hi" :test 4/5 \c) ;; you can get the head of the list with the ;; function `first` and use `rest` or `next` to ;; get the tail. `count` returns the number of ;; elements in it. `nth` returns the nth element ;; of the list, while `last` returns last item in ;; the list. ;; (first '(1 2 3 4 5)) (rest '(1 2 3 4 5)) (next '(1 2 3 4 5)) (rest '(1)) (next '(1)) (count '(5)) (count '(1 2 3 4 5)) (nth '(1 2 3 4 5) 0) (nth '(1 2 3 4 5) 1) (nth '(1 2 3 4 5) 10) (nth '(1 2 3 4 5) 10 :not-found) (last '(1 2 3 4 5)) (last '(1)) (last '()) ;; ;; #### Vectors ;; ;; Vectors are collections of values which are ;; indexed by their position in the vector ;; (starting from 0) called **index**. Insertion ;; at the end of the vector is `near O(1)` as well ;; as retrieval of an element by it's index. The ;; literals is expressed with a sequence of values ;; surrounded by square brackets or you can use ;; the `vector` function to construct one. You ;; can append an element at the end of the vector ;; with `conj` and use `get` to retrieve an ;; element in a specific index. Function such as ;; `first`, `next` `rest`, `last` and `count` will ;; work just as fine with Vectors. [1 2 3 4 5] [1 "hi" :test 4/5 \c] (vector 1 2 3 4 5) (conj [1 2 3 4 5] 6) (count [1 2]) (first [:a :b :c]) (get [:a :b :c] 1) (get [:a :b :c] 10) (get [:a :b :c] 10 :z) ;; #### Maps ;; ;; Maps are associative data structures (often ;; called dictionaries) which maps keys to their ;; corresponding value. Maps have a literal form ;; which can be expressed by any number of ;; key/value pairs surrounded by curly brackets, ;; or by using `hash-map` or `array-map` ;; functions. Hash-maps provides a `near O(1)` ;; insertion time and `near O(1)` seek time. You ;; can use `assoc` to "add or overwrite" an new ;; pair, `dissoc` to "remove" a key and its value, ;; and use `get` to retrieve the value of a given ;; key. {"jane" "PI:EMAIL:<EMAIL>END_PI" "fred" "PI:EMAIL:<EMAIL>END_PI" "rob" "PI:EMAIL:<EMAIL>END_PI"} {:a 1, :b 2, :c 3} (hash-map :a 1, :b 2, :c 3) (array-map :a 1, :b 2, :c 3) (assoc {:a 1, :b 2, :c 3} :d 4) (assoc {:a 1, :b 2, :c 3} :b 10) (dissoc {:a 1, :b 2, :c 3} :b) (count {:a 1, :b 2, :c 3}) (get {:a 1, :b 2, :c 3} :a) (get {:a 1, :b 2, :c 3} :a :not-found) (get {:a 1, :b 2, :c 3} :ZULU :not-found) (:a {:a 1, :b 2, :c 3}) ;; ;; #### Sets ;; ;; Sets are a type of collection which doesn't ;; allow for duplicate values. While lists and ;; vector can have duplicate elements, set ;; eliminates all duplicates. Clojure has a ;; literal form for sets which is expressed by a ;; sequence of values surrounded by `#{ ;; }`. Otherwise you construct a set using the ;; `set` function. With `conj` you can "add" a ;; new element to an existing set, and `disj` to ;; "remove" an element from the set. With ;; `clojure.set/union`, `clojure.set/difference` ;; and `clojure.set/intersection` you have typical ;; sets operations. `count` returns the number of ;; elements in the set in `O(1)` time. #{1 2 4} #{:a 4 5 :d "hello"} (type #{:a :z}) (set [:a :b :c]) (conj #{:a :c} :b) (conj #{:a :c} :c) (disj #{:a :b :c} :b) (clojure.set/union #{:a} #{:a :b} #{:c :a}) (clojure.set/difference #{:a :b} #{:c :a}) (clojure.set/intersection #{:a :b} #{:c :a}) ;; ;; ### The sequence abstraction ;; ;; One of the most powerful abstraction of ;; Clojure's data structures is the `sequence` ;; (`clojure.lang.ISeq`) which all data structure ;; implements. This interface resembles to a Java ;; iterator, and it implements methods like ;; `first()`, `rest()`, `more()` and `cons()`. The ;; power of this abstraction is that it is general ;; enough to be used in all data structures ;; (lists, vectors, maps, sets and even strings ;; can all produce sequences) and you have loads ;; of functions which manipulates it. Functions ;; such as `first`, `rest`, `next` and `last` and ;; many others such as `reverse`, `shuffle`, ;; `drop`, `take`, `partition`, `filter` etc are ;; all built on top of the sequence abstraction. ;; So if you create your own data-structure and ;; you implement the four methods of the ;; `clojure.lang.ISeq` interface you can benefit ;; from all these function without having to ;; re-implement them for your specific ;; data-structure. ;; (first [1 2 3 4]) (take 3 [:a :b :c :d :e]) (shuffle [1 2 3 4]) (shuffle #{1 2 3 4}) (reverse [1 2 3 4]) (last (reverse {:a 1 :b 2 :c 3})) (seq "Hello World!") (first "Hello") (rest "Hello") (count "Hello World!") ;; ;; #### Lazy Sequences ;; ;; Some of the sequences produced by the core ;; library are lazy which means that the entire ;; collection won't be created (*realised*) all at ;; once but when the elements are requested. (range 5 10) ;; _**WARNING!!!** Evaluating this from your REPL ;; might hang/crash your process_, as it will try ;; evaluate an infinite lazy sequence all at once. (range) (take 10 (range)) ;; ;; ### Regular expression patterns ;; #"[\w\d.-]+@[\w\d-.]+\.[\w]+" (type #"[\w\d.-]+@[\w\d-.]+\.[\w]+") (re-find #"[0-9]+" "only 123 numbers") (re-find #"[0-9]+" "no numbers") (re-find #"[\w\d.-]+@[\w\d-.]+\.[\w]+" "PI:EMAIL:<EMAIL>END_PI") (if (re-find #"^[\w\d.-]+@[\w\d-.]+\.[\w]+$" "PI:EMAIL:<EMAIL>END_PI") "it's an email" "it's not an email") (re-seq #"[0-9]+" "25, 43, 54, 12, 15, 65") (re-pattern "[0-9]{1,3}(\\.[0-9]{1,3}){3}") (re-find (re-pattern "[0-9]{1,3}(\\.[0-9]{1,3}){3}") "my IP is: 192.168.0.12") ;; ;; Using `re-matcher`, `re-matches`, `re-groups` ;; allows you to have fine control over the capturing ;; groups. ;; ;; ### Symbols and Vars ;; ;; Symbols in Clojure are a way to identify things ;; in your programs which may have various values ;; at runtime. Like in a mathematical notation, `x` ;; is something not known which could assume ;; several different values. In a programming ;; context, Clojure symbols are similar to ;; variables in other languages but not exactly. ;; In other languages variables are places where ;; you store information, symbols in Clojure ;; cannot contain data themselves. Vars in ;; Clojure are the containers of data (one type ;; of), and symbols are a way to identify them and ;; give vars meaningful names for your program. ;; username 'username (symbol "username") (type (symbol "username")) (def username "bruno1") username age ;; undefined var produces error (def age 21) age (type 'age) (type age) (def user {:username "bruno1" :score 12345 :level 32 :achievements #{:fast-run :precision10 :strategy}}) user (def user nil) user ;; ;; ### Immutability ;; ;; All basics data-types in Clojure are immutable, ;; including the collections. This is a very ;; important aspect of Clojure approach to ;; functional programming. In Clojure functions ;; transform values into new values and values are ;; just values. Since it is absurd to think of ;; changing a number (1 is always 1), ;; composite data structures are treated in the same way. ;; So functions do not mutate values they just produce new ones. ;; Like adding `1` to `42` produces `43` but ;; doesn't really change the number `42` as it keeps on ;; existing on its own, adding an element to a list will ;; produce a new list but the old one will still be same ;; and unmodified. ;; ;; The advantage of the immutability is that ;; values (even deeply nested and complex ;; structures) can be safely shared across threads ;; and with function callers without worrying ;; about unsafe or uncoordinated changes. This ;; simple constraint makes Clojure programs so ;; much easier to reason about, as the only way to ;; produce a new value is via a functional ;; transformation. ;; (def colours '(:red :green :blue)) (def new-colours (cons :black colours)) new-colours colours (def user {:username "bruno1" :score 12345 :level 32}) (def user' (assoc user :level 33)) user' user ;; ;; ### Functions ;; ;; So far we have seen how to represent data in ;; our system, now we will see how to make sense ;; of this data and how to ;; extract/process/transform it. The way we ;; express this in Clojure is via functions. ;; ;; ;; pure (+ 1 2 3) ;; impure (rand-int 100) ;; (+ 1 1 1) is referentially transparent (+ 1 2 (+ 1 1 1)) ;; ;; #### Function definition ;; ;; To define a function you have to use the ;; special form `fn` or `defn` with the following ;; syntax. ;; ;; for example if we want to define a function ;; which increments the input parameters by 1 you ;; will write something as follow: ;; ;; ``` ;; /- fn, special form ;; / parameter vector, 1 param called `n` ;; | | body -> expression to evaluate when ;; | | | this function is called ;; (fn [n] (+ n 1)) ;; ``` ;; ;; This is the simplest way to define a function. ;; ;; Now to refer to this function in our code we ;; need to give it a name. We can do so with `def` ;; as we done earlier. ;; (def plus-one (fn [n] (+ n 1))) ;;=> #'learn-clojure.basics/plus-one (plus-one 10) ;;=> 11 (plus-one -42) ;;=> -41 ;; ;; As mentioned earlier, during the evaluation process ;; the symbol `plus-one` is simply replaced with ;; its value, in the same way we can replace the ;; symbol with the function definition and obtain ;; the same result. So symbols can also refer to ;; functions. ;; Evaluation by substitution model. (plus-one 10) ((fn [n] (+ n 1)) 10) (fn [10] (+ 10 1)) (+ 10 1) 11 ;; def + fn = defn (defn plus-one [n] (+ n 1)) (plus-one 1) (defn plus-one "Returns a number which is one greater than the given `n`." [n] (+ n 1)) (inc 10) (defn make-ip4 [a b c d] (clojure.string/join "." [a b c d])) (make-ip4 192 168 0 1) (defn make-kebab [& words] (clojure.string/join "-" words)) (make-kebab "i" "like" "kebab") (defn greet ([] "Hey, Stranger!") ([name] (str "Hello " name)) ([firstname lastname] (str "Hi, you must be: " lastname ", " firstname " " lastname)) ([title firstname lastname] (str "Hello " title " " firstname " " lastname))) (greet) (greet "PI:NAME:<NAME>END_PI") (greet "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") (greet "Dr" "PI:NAME:<NAME>END_PI." "PI:NAME:<NAME>END_PI") ;; ;; #### High-order functions ;; ;; In Clojure functions are reified constructs, ;; therefore we can threat them as normal ;; values. As such functions can be passed as ;; parameters of function or returned as result of ;; function call. ;; (defn is-commutative? [op a b] (= (op a b) (op b a))) (is-commutative? + 3 7) (is-commutative? / 3 7) ;; function which return a function (defn multiplier [m] (fn [n] (* n m))) (def doubler (multiplier 2)) (doubler 5) (doubler 10) (def mult-10x (multiplier 10)) (mult-10x 35) ;; ;; #### Lambda functions (Anonymous) ;; ;; Oftentimes you want to create a function for a ;; specific task in a local context. Such ;; functions don't have any reason to have a ;; global name as they are meaningful only in that ;; specific context, in this case you can create ;; anonymous functions (also called lambda ;; function) and Clojure has some support to make ;; this easier. We already seen an example of an ;; anonymous function with our very first function ;; example. ;; (fn [n] (+ n 1)) ((fn [n] (+ n 1)) 10) ;;=> 11 #(+ % 1) (#(+ % 1) 10) ;; ;; In this function the symbol `%` replace the argument ;; If you have more than one parameter you can denote them as ;; `%1` (or `%`), `%2`, `%3`, `%4` ... ;; ;; for example in our `is-commutative?` function we expect ;; and operation which accept two arguments: (is-commutative? #(+ %1 %2) 9 8) ;; ;; #### Closures ;; ;; Closures (with the `s`) are lambdas which refer ;; to a context (or values from another context). ;; These functions are said to be "closing over" ;; the environment. This means that it can access ;; parameters and values which are NOT in the ;; parameters list. ;; ;; Like in our `multiplier` function example, the ;; returned function is closing over the value `m` ;; which is not in its parameter list but it is a ;; parameter of the parent context the ;; `multiplier` fn. While `n` is a normal ;; parameter `m` is the value we are "closing ;; over" providing a context for that function. (defn multiplier [m] (fn [n] (* n m))) ;; ;; #### Recursion ;; ;; A recursive function is a function which ;; calls itself. There are two types of recursion ;; the mundane recursion and the tail recursion. ;; ;; Let's see an example of both with this function ;; which given a number it calculates the sum of ;; all natural numbers from 1 to the given ;; number. (defn sum1 ([n] (sum1 n 0)) ([n accumulator] (if (< n 1) accumulator ;; else (sum1 (dec n) (+ n accumulator))))) (sum1 1) (sum1 3) (sum1 10) ;; ;; This type of recursion is called mundane ;; recursion and every new call it allocates one ;; new frame on the stack so if you run this with ;; high enough numbers it will blow your stack. ;; (sum1 10000) ;;=> java.lang.StackOverflowError ;; ;; Let's see how we can write this ;; function with a tail recursion using ;; `recur`. ;; (defn sum2 ([n] (sum2 n 0)) ([n accumulator] (if (< n 1) accumulator ;; else (recur (dec n) (+ n accumulator))))) ;;=> #'learn-clojure.basics/sum2 (sum2 10) (sum2 10000) (sum2 1000000) (sum2 100000000) ;; Let's see how we can rewrite the previous ;; function to leverage the `loop/recur` ;; construct. (defn sum3 [num] (loop [n num accumulator 0] (if (< n 1) accumulator ;; else (recur (dec n) (+ n accumulator))))) (sum3 10) ;; Let's see another example with the Fibonacci ;; sequence. Let's start with the mundane ;; recursion. ;; !!! this is O(2^n) (defn fibonacci1 [n] (if (< n 2) 1 ;; else (+ (fibonacci1 (- n 1)) (fibonacci1 (- n 2))))) (fibonacci1 1) (fibonacci1 10) ;; ;; Now this is a simple and very functional ;; definition of the Fibonacci sequence, however ;; it is particularly bad in terms of computational ;; complexity. in fact this is `O(2^n)`. ;; Let's use the `time` function to ;; calculate how much it takes to compute the ;; 35th number in the sequence. ;; (time (fibonacci1 35)) ;; ;; Let's try to use tail recursion. ;; As you will see we have to restructure ;; our function to allow the recursion ;; to happen in the tail position. ;; (defn fibonacci2 [n] (loop [i n c 1 p 1] (if (< i 2) c (recur (dec i) (+' c p) c)))) (fibonacci2 10) (time (fibonacci2 35)) (time (fibonacci2 1000)) ;; ;; #### Function composition and partial functions ;; ;; We have seen earlier that there are functions ;; such as `first`, `second`, `last` and `rest` to ;; access respectively the first item of the ;; sequence, the second item, the last item and ;; the tail of the sequence. These functions can ;; be combined to create other functions for ;; accessing the third, fourth, fifth and other ;; positional items. The following functions are ;; an example of how to construct two such ;; functions. (defn third [coll] (first (rest (rest coll)))) (third '(1 2 3 4 5)) ;;=> 3 (defn fourth [coll] (first (rest (rest (rest coll))))) (fourth '(1 2 3 4 5)) ;;=> 4 ;; But there is another way. If, like in this ;; case, the output of a function can be passed ;; directly into the input of the next one as a ;; simple pipeline of functions then you can just ;; use the `comp` function. ;; ;; (comp f1 f2 f3 ... fn) ;; ;; (comp f1 f2 f3) = (f1 (f2 (f3 ,,,))) ;; (def third (comp first rest rest)) (def fourth (comp first rest rest rest)) (third '(1 2 3 4 5)) ;;=> 3 (fourth '(1 2 3 4 5)) ;;=> 4 ;; Let's see another example. Let's assume ;; we have to write a function which given ;; a number it doubles it and subtract 1 ;; from it. So we can use the `multiplier` ;; function we wrote earlier to accomplish ;; the first part and the Clojure core `dec` ;; to decrement it by one and compose them ;; together with `comp`. (defn multiplier [m] (fn [n] (* n m))) (def doubler (multiplier 2)) (def almost-twice (comp dec doubler)) (almost-twice 5) ;;=> 9 (almost-twice 9) ;;=> 17 ;; ;; Now let's say we want to create a function ;; which given a number perform `almost-twice` two ;; times. ;; (def almost-twice-twice (comp almost-twice almost-twice)) (almost-twice-twice 5) ;;=> 17 (almost-twice-twice 10) ;;=> 37 ;; Another way we could have written the `doubler` ;; function is by using the partial application of ;; the function `*`. In Clojure this is achieved ;; via the function `partial`. ;; ;; (partial f arg1 ... argn) ;; (def doubler (partial * 2)) (doubler 5) ;;=> 10 ;; what happens here is that the `partial` ;; function returns a function which calls `*` ;; with the parameters of the partial and the ;; parameter of the final call, all in one call. ;; ;; ;; ;; ### Vars, namespaces, scope and local bindings ;; ;; When defining a var using `def` or `defn` ;; followed by symbol, the symbol is created ;; in the local namespace. ;; When starting the REPL in a empty project ;; the default namespace is called `user` ;; so unless you configure differently ;; all your vars will be created there. ;; ;; Namespaces are like containers in which ;; vars live in, but namespaces, ;; once defined are **globally accessible**. ;; As a consequence when you define a var ;; using `def` or `defn` these will be accessible ;; globally. ;; ;; We will use `ns` which create a namespace if ;; not present and switch to it, and `in-ns` just ;; changes the current namespace. we will see how ;; to loads namespaces we need with our processing ;; with `require` and how vars are globally ;; accessible. (ns user.test.one) ;;=> nil (def my-name "PI:NAME:<NAME>END_PI") ;;=> #'user.test.one/my-name my-name ;;=> "PI:NAME:<NAME>END_PI" (ns user.test.two) ;;=> nil (def my-name "PI:NAME:<NAME>END_PI") ;;=> #'user.test.two/my-name my-name ;;=> "PI:NAME:<NAME>END_PI" user.test.one/my-name ;;=> "PI:NAME:<NAME>END_PI" user.test.two/my-name ;;=> "PI:NAME:<NAME>END_PI" (def my-name (clojure.string/upper-case "PI:NAME:<NAME>END_PI")) ;;=> #'user.test.one/my-name (ns user.test.one (:require [clojure.string :as s])) ;;=> nil (def my-name (s/upper-case "PI:NAME:<NAME>END_PI")) ;;=> #'user.test.one/my-name (ns user.test.one (:require [clojure.string :refer [upper-case]])) ;;=> nil (def my-name (upper-case "PI:NAME:<NAME>END_PI")) ;;=> #'user.test.one/my-name my-name ;;=> "PI:NAME:<NAME>END_PI" ;; ;; The global accessible vars (globals) is one ;; level of scoping. If you don't want to have ;; globally accessible vars then you have to ;; use local bindings. ;; ;; We already had a glimpse of these while ;; defining functions. In fact parameters ;; are only visible inside the function: ;; (def v1 1) (def v2 2) (defn sum [v1 v2] (+ v1 v2)) (sum 10 25) ;;=> 35 v1 v2 ;; ;; There is another way to create local binding ;; which are valid only inside the s-expr block, ;; using `let`. With the let form you can create ;; local variable which are visible only inside ;; the block. (let [v1 23 v2 45] ;; inside this block v1 v2 have the values 23 and 45 (+ v1 v2)) ;;=> 68 ;; ;; outside the block v1 and v2 are resolved in the ;; parent scope which in this case is the ;; namespace/global You can even nest `let` ;; bindings and use them inside functions. Here ;; we use `println` to print to the standard ;; output a message (let [v1 "this is a local value"] ;; outer block (println "outer-v1:" v1) (let [v1 1] ;; inner block (println "inner-v1:" v1)) (println "after-v1:" v1)) (println "global-v1:" v1) ;; global ;;=> outer-v1: this is a local value ;;=> inner-v1: 1 ;;=> after-v1: this is a local value ;;=> global-v1: hello ;; ;; ### Core functions ;; ;; The core has hundreds of functions defined, ;; which all work on the basic data structures ;; that we've seen so far. You can find the full list ;; in the [Clojure cheatsheet](http://clojure.org/api/cheatsheet) ;; ;; ;; #### The function: `apply` ;; ;; For the purpose of this course we will ;; only see a few examples starting with `apply`. ;; As the same suggests, it "applies" a function ;; to a given list of arguments. ;; ;; (apply f args) ;; (apply f x args) ;; (def words ["Hello" " " "world!"]) (str ["Hello" " " "world!"]) ;;=> "[\"Hello\" \" \" \"world!\"]" (apply str ["Hello" " " "world!"]) ;;=> "Hello world!" (apply str "first-argument: " ["Hello" " " "world!"]) ;;=> "first-argument: Hello world!" ;; ;; #### The function: `map` ;; ;; Next we will see one of the most used functions ;; in the core `map` which has nothing to do with ;; the associative maps (data structures) we seen ;; before. `map` comes from the set theory and is ;; a function which takes a function and a ;; sequence of values and applies the function to ;; all values in the sequence. It returns a ;; lazy-sequence which means that the function ;; application is not performed when calling `map`, ;; but it will be performed when the result will ;; be consumed. ;; ;; (map f coll) ;; (map clojure.string/upper-case ["Hello" "world!"]) ;;=> ("HELLO" "WORLD!") ;; ;; #### The function: `mapcat` ;; ;; Sometimes the application of the function `f` ;; returns a list of things. In the following ;; example, applying the split function to each sentence ;; spilts each sentence and returns a list of words. ;; (map #(clojure.string/split % #"\W+") ["Lorem ipsum dolor sit amet, consectetur adipiscing elit." "Duis vel ante est." "Pellentesque habitant morbi tristique" "senectus et netus et malesuada fames ac turpis egestas."]) ;; application of the split function to a single ;; sentence produces a list of words. Consequently ;; the application of the function to all ;; sentences produces a list of lists. If we ;; rather have a single list with all the words we ;; then need to concatenate all the sub-lists into ;; one. To do so Clojure core has the `concat` ;; function which just concatenates multiple lists ;; into one. (concat [0 1 2 3] [:a :b :c] '(d e f)) ;;=> (0 1 2 3 :a :b :c d e f) ;; To obtain a single list of all words we just need ;; to apply the `concat` function to the `map` result. (apply concat (map #(clojure.string/split % #"\W+") ["Lorem ipsum dolor sit amet, consectetur adipiscing elit." "Duis vel ante est." "Pellentesque habitant morbi tristique" "senectus et netus et malesuada fames ac turpis egestas."])) ;;=> ("Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing" "elit" "Duis" "vel" "ante" "est" "Pellentesque" "habitant" "morbi" "tristique" "senectus" "et" "netus" "et" "malesuada" "fames" "ac" "turpis" "egestas") ;; ;; This construct is common enough that Clojure has ;; a core function that does just this called `mapcat`. (mapcat #(clojure.string/split % #"\W+") ["Lorem ipsum dolor sit amet, consectetur adipiscing elit." "Duis vel ante est." "Pellentesque habitant morbi tristique" "senectus et netus et malesuada fames ac turpis egestas."]) ;;=> ("Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing" "elit" "Duis" "vel" "ante" "est" "Pellentesque" "habitant" "morbi" "tristique" "senectus" "et" "netus" "et" "malesuada" "fames" "ac" "turpis" "egestas") ;; ;; ;; #### The function: `reduce` ;; ;; Hadoop uses the two concept of `map` and ;; `reduce` to perform arbitrary computation on ;; large data. Clojure has `reduce` as core ;; function as well. While `map` is applied ;; one-by-one to all arguments with the objective ;; of performing a transformation `reduce` seeks ;; to summarize many values into one. For example ;; if you want to find the total sum of a list of ;; values you can use reduce in the following way. ;; ;; (reduce f coll) ;; ;; It can be used with many core functions ;; like the arithmetic functions `+`, `*` ;; but also with functions like `max` and `min` ;; which respectively return the highest and ;; the lowest value passed. But they ;; can be used with your own functions too. ;; (reduce + [10 15 23 32 43 54 12 11]) ;;=> 200 (reduce * [10 15 23 32 43 54 12 11]) ;;=> 33838041600 (reduce max [10 15 23 32 43 54 12 11]) ;;=> 54 (reduce str ["Hello" " " "world!"]) ;;=> "Hello world!" ;; ;; #### The function: `filter` ;; ;; The next function in the core is `filter` which ;; takes a *predicate function* and a collection ;; and returns a lazy-sequence of the items in the ;; collection for which the application of the ;; function returns a "truthy" value. Predicate ;; functions are functions which takes one ;; parameter and return a logical true or false. ;; ;; (filter pred? coll) ;; ;; For example: (filter odd? [0 1 2 3 4 5 6 7]) ;;=> (1 3 5 7) (filter #(> (count %) 5) ["Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing"]) ;;=> ("consectetur" "adipiscing") ;; ;; `identity` is a function which given a value ;; will just return the value. ;; This is often used when a function transformation ;; is required as parameter, but no transformation is wanted. ;; another idiomatic use of it is to remove nil and false ;; from a collection. ;; (filter identity ["Lorem" "ipsum" nil "sit" nil "consectetur" nil]) ;;=> ("Lorem" "ipsum" "sit" "consectetur") ;; ;; The function `remove` is the dual of `filter` ;; in the sense that is will remove the items ;; for which the predicate function returns true. ;; (filter odd? [0 1 2 3 4 5 6 7]) ;;=> (1 3 5 7) (remove odd? [0 1 2 3 4 5 6 7]) ;;=> (0 2 4 6) ;; ;; #### The function: `sort` ;; ;; `sort` as you would expect returns a sorted ;; sequence of the elements in the given collection. ;; ;; (sort coll) ;; (sort comp coll) ;; (sort [8 3 5 2 5 7 9 4 3 1 0]) ;;=> (0 1 2 3 3 4 5 5 7 8 9) (sort > [8 3 5 2 5 7 9 4 3 1 0]) ;;=> (9 8 7 5 5 4 3 3 2 1 0) (sort-by count ["Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing"]) ;;=> ("sit" "amet" "Lorem" "ipsum" "dolor" "adipiscing" "consectetur") (sort-by count > ["Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing"]) ;;=> ("consectetur" "adipiscing" "Lorem" "ipsum" "dolor" "amet" "sit") (sort-by :score > [{:user "john1" :score 345} {:user "fred3" :score 75} {:user "sam2" :score 291}]) ;;=> ({:user "john1", :score 345} {:user "sam2", :score 291} {:user "fred3", :score 75}) ;; ;; A similar function is `sort-by` which accepts a ;; function which is applied to the item before the ;; comparison. ;; ;; ;; #### The function: `group-by` ;; ;; Out of the box in Clojure you have a function ;; to perform grouping on your data. `group-by` ;; accepts a function and a collection and it will ;; apply the given function to all items in the ;; collection and then group the items using the ;; result of the function, i.e items that give the ;; same result when the function is applied end up ;; in the same group. Each group will be ;; associated with it's common function result. ;; It returns a map where the key is the group ;; common function result, and the value of the ;; map is a list of items which belong to that ;; group. (group-by odd? (range 10)) ;;=> {false [0 2 4 6 8], true [1 3 5 7 9]} (group-by count ["Lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing"]) ;;=> {5 ["Lorem" "ipsum" "dolor"], 3 ["sit"], 4 ["amet"], 11 ["consectetur"], 10 ["adipiscing"]} (group-by :user-id [{:user-id 1 :uri "/"} {:user-id 2 :uri "/foo"} {:user-id 1 :uri "/account"}]) ;;=> {1 [{:user-id 1, :uri "/"} {:user-id 1, :uri "/account"}], 2 [{:user-id 2, :uri "/foo"}]} ;; ;; #### The function: `frequencies` ;; ;; When looking to count how frequent an item appears ;; in a collection for example to compute histograms ;; you can use the function called `frequencies`. ;; (frequencies ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) ;;=> {"PI:NAME:<NAME>END_PI" 3, "PI:NAME:<NAME>END_PI" 2, "PI:NAME:<NAME>END_PI" 2, "PI:NAME:<NAME>END_PI" 1} (frequencies [1 2 3 1 2 3 2 3 1 2 3 3 2 3 2 3 4 4]) ;;=> {1 3, 2 6, 3 7, 4 2} ;; ;; ;; #### The function: `partition` ;; ;; Another interesting group of functions in the Clojure ;; core are `partition`, `partition-all`, `partition-by`. ;; Here we will see only the first two. ;; `partition` chunks the given sequence into ;; sub-sequences (lazy) of `n` items each. ;; ;; (partition n coll) ;; (partition n step coll) ;; (partition 3 (range 11)) ;;=> ((0 1 2) (3 4 5) (6 7 8)) ;; `partition-all` does the same, but it returns ;; also chunks of which are incomplete. (partition-all 3 (range 11)) ;;=> ((0 1 2) (3 4 5) (6 7 8) (9 10)) ;; ;; The `step` parameters tells the function how ;; many item has to move forward after every ;; chunk. if not given `step` is equal to `n` (partition 3 1 (range 11)) ;;=> ((0 1 2) (1 2 3) (2 3 4) (3 4 5) (4 5 6) (5 6 7) (6 7 8) (7 8 9) (8 9 10)) (partition 3 5 (range 11)) ;;=> ((0 1 2) (5 6 7)) ;; ;; #### The function: `into` ;; ;; `into` is used to create a new collection of a ;; given type with all items from another ;; collection "into" it. Items are conjoined ;; using `conj`. It is often used to change the ;; type of a collection, or to build a map out of ;; key/value pairs. ;; ;; (into dest source) ;; (into [] '(0 1 2 3 4 5 6 7 8 9)) ;;=> [0 1 2 3 4 5 6 7 8 9] (into '() '(0 1 2 3 4 5 6 7 8 9)) ;;=> (9 8 7 6 5 4 3 2 1 0) (into (sorted-map) {:b 2, :c 3, :a 1}) ;;=> {:a 1, :b 2, :c 3} (into {} [[:a 1] [:b 2] [:c 3]]) ;;=> {:a 1, :b 2, :c 3} (map (fn [e] [(first e) (inc (second e))]) {:a 1, :b 2, :c 3}) ;;=> ([:a 2] [:b 3] [:c 4]) (into {} (map (fn [e] [(first e) (inc (second e))]) {:a 1, :b 2, :c 3})) ;;=> {:a 2, :b 3, :c 4} ;; ;; ;; ### Operation with files ;; ;; To open, read, write files there are wrappers ;; from the java machinery for files. However here ;; we will only see how to read and write text ;; files which are small enough to fit in memory. ;; ;; To write some text in a file you can use the ;; function `spit`, while to read the content of a ;; file as a string you can use `slurp`. ;; (spit "/tmp/my-file.txt" "This is the content") ;;=> nil (slurp "/tmp/my-file.txt") ;;=> "This is the content." ;; ;; ### Error handling ;; ;; What happens if the file you trying to read ;; doesn't exists? or the device you trying to ;; write to is full? The underlying Java APIs will ;; throw an exception. Clojure provides access to ;; the java machinery for error handling and you ;; can use `try`, `catch`, `finally` and `throw` ;; with the same semantic as the Java's ones. ;; ;; You have to surround the code which might throw ;; an exception using a `try` form, then you can ;; handle the errors by their native type with a ;; `catch` block. Finally is a block that gets ;; executed no matter what happen in the try block and ;; whether or not an exception is raised. `throw` ;; is used to throw an exception from your own code. (slurp "/this_doesnt_exists.txt") ;;=> FileNotFoundException /this_doesnt_exists.txt (No such file or directory) (try (slurp "/this_doesnt_exists.txt") (catch Exception x (println "unable to read file.") "")) ;;=> unable to read file ;;=> "" ;; ;; ### Destructuring ;; ;; The complete guide to Clojure destructuring ;; http://blog.brunobonacci.com/2014/11/16/clojure-complete-guide-to-destructuring/ ;; ;; ;; ### Macros ;; ;; The macros are function which are executed at ;; compile time by the compiler. The take code as ;; input, and the output is still code. The code ;; is expressed in the same stuff you have seen so ;; far: lists, symbols, keywords, vectors, maps ;; strings etc and from a user point of view they ;; look just like normal Clojure functions ;; (almost). It is a great way to extends the ;; language to meet your domain needs. However I ;; think this is a topic for a more advanced ;; course. If you want to learn the basics of the ;; macro you can read the following blog post: ;; ;; A "dead simple" introduction to Clojure macros. ;; http://blog.brunobonacci.com/2015/04/19/dead-simple-introduction-to-clojure-macros/ ;; (require '[clojure.string :as str]) (into #{} (map str/upper-case (str/split "this is a great language and a great platform" #" "))) (->> (str/split "this is a great language and a great platform" #" ") (map str/upper-case) (into #{})) (macroexpand '(->> (str/split "this is a great language and a great platform" #" ") (map str/upper-case) (into #{}))) ;; can write a macro which turn my expression into a Go-like ;; expression which never throws exceptions? ;;
[ { "context": "e how your application should work.\"\n ^{:author \"Sameer Rahmani (@lxsameer)\"\n :added 1.0}\n (:require\n [hell", "end": 172, "score": 0.9998731017112732, "start": 158, "tag": "NAME", "value": "Sameer Rahmani" }, { "context": "lication should work.\"\n ^{:author \"Sameer Rahmani (@lxsameer)\"\n :added 1.0}\n (:require\n [hellhound.syste", "end": 183, "score": 0.9993241429328918, "start": 173, "tag": "USERNAME", "value": "(@lxsameer" } ]
core/src/cljc/hellhound/system.cljc
Codamic/hell-hound
34
(ns hellhound.system "Systems are the most important thing in the **HellHound** ecosystem. Systems define how your application should work." ^{:author "Sameer Rahmani (@lxsameer)" :added 1.0} (:require [hellhound.system.protocols :as impl] [hellhound.config :as config] [hellhound.logger :as logger] [hellhound.system.core :as core] [hellhound.system.store :as store] [hellhound.system.workflow :as workflow] [hellhound.system.defaults :as defaults])) (defn set-system! "Sets the default system of HellHound application to the given `system-map`." {:added 1.0 :public-api true} [system-fn] (store/set-system! system-fn) ;; TODO: We need to establish an official entry point for the system ;; and move the logger initialization to there. (logger/init! (impl/get-value (store/get-system) [:logger] {}))) (defn system "Returns the processed system which is set as the application wide system." {:added 1.0 :public-api true} [] (store/get-system)) (defn get-config [ks] (let [value (impl/get-value (system) ks :not-found)] (if (= value :not-found) (get-in defaults/config ks) value))) (defn start "Starts the given `system-map` by initalizing the system and call the `start-fn` of all the components in order and setting up the workflow by piping components IO together. It returns the started system map." [system-map] (let [new-system (-> system-map (core/start-system) (workflow/setup))] (logger/info "System has been started successfully.") new-system)) (defn start! "Starts the default system of application which is stored in `hellhound.system.store/store` by passing its value to `start` function and change the root of the store to the started system. Basically replace the old system with the started system." [] (alter-var-root #'hellhound.system.store/store #(start %))) (defn stop "Stops the given `system-map` by walking the dependency tree and call the `stop-fn` of the components in order and teardown the workflow. It returns the stopped system." [system-map] (when system-map (let [new-system (-> system-map (workflow/teardown) (core/stop-system))] (logger/info "System has been stopped successfully.") new-system))) (defn stop! "Stops the default system of application which is stored in `hellhound.system.store/store` and sets the root of the store to the stopped system. Basically stops and replaces the default system." [] (alter-var-root #'hellhound.system.store/store #(stop %))) (defn get-component "Finds and returns the component with the given `component-name` in the default system which is stored in `hellhound.system.store/store`." {:added 1.0 :public-api true} [component-name] (impl/get-component store/store component-name))
121202
(ns hellhound.system "Systems are the most important thing in the **HellHound** ecosystem. Systems define how your application should work." ^{:author "<NAME> (@lxsameer)" :added 1.0} (:require [hellhound.system.protocols :as impl] [hellhound.config :as config] [hellhound.logger :as logger] [hellhound.system.core :as core] [hellhound.system.store :as store] [hellhound.system.workflow :as workflow] [hellhound.system.defaults :as defaults])) (defn set-system! "Sets the default system of HellHound application to the given `system-map`." {:added 1.0 :public-api true} [system-fn] (store/set-system! system-fn) ;; TODO: We need to establish an official entry point for the system ;; and move the logger initialization to there. (logger/init! (impl/get-value (store/get-system) [:logger] {}))) (defn system "Returns the processed system which is set as the application wide system." {:added 1.0 :public-api true} [] (store/get-system)) (defn get-config [ks] (let [value (impl/get-value (system) ks :not-found)] (if (= value :not-found) (get-in defaults/config ks) value))) (defn start "Starts the given `system-map` by initalizing the system and call the `start-fn` of all the components in order and setting up the workflow by piping components IO together. It returns the started system map." [system-map] (let [new-system (-> system-map (core/start-system) (workflow/setup))] (logger/info "System has been started successfully.") new-system)) (defn start! "Starts the default system of application which is stored in `hellhound.system.store/store` by passing its value to `start` function and change the root of the store to the started system. Basically replace the old system with the started system." [] (alter-var-root #'hellhound.system.store/store #(start %))) (defn stop "Stops the given `system-map` by walking the dependency tree and call the `stop-fn` of the components in order and teardown the workflow. It returns the stopped system." [system-map] (when system-map (let [new-system (-> system-map (workflow/teardown) (core/stop-system))] (logger/info "System has been stopped successfully.") new-system))) (defn stop! "Stops the default system of application which is stored in `hellhound.system.store/store` and sets the root of the store to the stopped system. Basically stops and replaces the default system." [] (alter-var-root #'hellhound.system.store/store #(stop %))) (defn get-component "Finds and returns the component with the given `component-name` in the default system which is stored in `hellhound.system.store/store`." {:added 1.0 :public-api true} [component-name] (impl/get-component store/store component-name))
true
(ns hellhound.system "Systems are the most important thing in the **HellHound** ecosystem. Systems define how your application should work." ^{:author "PI:NAME:<NAME>END_PI (@lxsameer)" :added 1.0} (:require [hellhound.system.protocols :as impl] [hellhound.config :as config] [hellhound.logger :as logger] [hellhound.system.core :as core] [hellhound.system.store :as store] [hellhound.system.workflow :as workflow] [hellhound.system.defaults :as defaults])) (defn set-system! "Sets the default system of HellHound application to the given `system-map`." {:added 1.0 :public-api true} [system-fn] (store/set-system! system-fn) ;; TODO: We need to establish an official entry point for the system ;; and move the logger initialization to there. (logger/init! (impl/get-value (store/get-system) [:logger] {}))) (defn system "Returns the processed system which is set as the application wide system." {:added 1.0 :public-api true} [] (store/get-system)) (defn get-config [ks] (let [value (impl/get-value (system) ks :not-found)] (if (= value :not-found) (get-in defaults/config ks) value))) (defn start "Starts the given `system-map` by initalizing the system and call the `start-fn` of all the components in order and setting up the workflow by piping components IO together. It returns the started system map." [system-map] (let [new-system (-> system-map (core/start-system) (workflow/setup))] (logger/info "System has been started successfully.") new-system)) (defn start! "Starts the default system of application which is stored in `hellhound.system.store/store` by passing its value to `start` function and change the root of the store to the started system. Basically replace the old system with the started system." [] (alter-var-root #'hellhound.system.store/store #(start %))) (defn stop "Stops the given `system-map` by walking the dependency tree and call the `stop-fn` of the components in order and teardown the workflow. It returns the stopped system." [system-map] (when system-map (let [new-system (-> system-map (workflow/teardown) (core/stop-system))] (logger/info "System has been stopped successfully.") new-system))) (defn stop! "Stops the default system of application which is stored in `hellhound.system.store/store` and sets the root of the store to the stopped system. Basically stops and replaces the default system." [] (alter-var-root #'hellhound.system.store/store #(stop %))) (defn get-component "Finds and returns the component with the given `component-name` in the default system which is stored in `hellhound.system.store/store`." {:added 1.0 :public-api true} [component-name] (impl/get-component store/store component-name))
[ { "context": " (#{\"http\" \"https\"} protocol)))\n\n;; inspired by IonicaBizau/git-url-parse.\n(defn parse-git-url\n \"parse git u", "end": 1438, "score": 0.6968352794647217, "start": 1427, "tag": "USERNAME", "value": "IonicaBizau" }, { "context": "ds options)))))\n\n;; dev\n(comment\n (def ssh-repo \"git@github.com:jwells131313/goethe.gitt\")\n (def http-repo \"http", "end": 5555, "score": 0.980747401714325, "start": 5541, "tag": "EMAIL", "value": "git@github.com" }, { "context": "\n\n;; dev\n(comment\n (def ssh-repo \"git@github.com:jwells131313/goethe.gitt\")\n (def http-repo \"https://github.co", "end": 5568, "score": 0.9996073842048645, "start": 5556, "tag": "USERNAME", "value": "jwells131313" }, { "context": "oethe.gitt\")\n (def http-repo \"https://github.com/cxa/dicmd/tree/main/src\")\n (re-find ssh-regexp ssh-r", "end": 5623, "score": 0.9994250535964966, "start": 5620, "tag": "USERNAME", "value": "cxa" }, { "context": "clone \".\" u)\n (parse-git-url \"https://github.com/caddyserver/caddy#install\")\n (def p (parse-git-url \"git@gith", "end": 5923, "score": 0.9995859265327454, "start": 5912, "tag": "USERNAME", "value": "caddyserver" }, { "context": "dyserver/caddy#install\")\n (def p (parse-git-url \"git@github.com:gramineproject/gramine.ggit\"))\n (generate-git-ur", "end": 5979, "score": 0.8288065195083618, "start": 5965, "tag": "EMAIL", "value": "git@github.com" }, { "context": "install\")\n (def p (parse-git-url \"git@github.com:gramineproject/gramine.ggit\"))\n (generate-git-url p)\n )\n\n;; ru", "end": 5994, "score": 0.9992793202400208, "start": 5980, "tag": "USERNAME", "value": "gramineproject" } ]
gh.clj
shohi/cerise
1
#!/usr/bin/env bb ;; -*- mode: clojure; -*- ;; utils for github repos ;; - [x] clone repos from github ;; - [x] check local repo exists ;; clone github repos into configured directory - `GITHUB_WORKSHOP`. ;; If the env is not set, use current directory. Both account subdir ;; will be created if necessary. ;; ;; NOTE: ;; 1. if url schema is not provided, assuming the repo is from github ;; 2. If `--dir` option is set, use the value otherwise clone the repo ;; into `GITHUB_WORKSHOP`. ;; ;; NOTE: ;; 1. GITHUB_WORKSPACE must be absolute-path as babashka does not provide ;; `expand-home` util (ns gh (:require [babashka.fs :as fs] [babashka.process :as p] [battery :as b] [clojure.java.io :as io] [clojure.java.shell :as shell] [clojure.string :as str] [clojure.tools.cli :refer [parse-opts]])) (def ^:private ssh-regexp #"^((git)@)?github.com:([\w-]+)/([\w-]+)(\.git$)?") (def ^:private http-regexp #"^((http|https)://)?((\w+)@)?github.com/([\w-]+)/([\w-]+)/?") (defn- repo-base-dir [dir] (if (str/blank? dir) (let [dir (System/getenv "GITHUB_WORKSHOP")] (if (empty? dir) b/cwd dir)) dir)) (defn- ssh? "test whether the repo url is in ssh protocol." [protocol user] (and (= "ssh" protocol) (= "git" user))) (defn- http? "test whether the repo url is in http protocol." [protocol user] (and (empty? user) (#{"http" "https"} protocol))) ;; inspired by IonicaBizau/git-url-parse. (defn parse-git-url "parse git url, only extract owner and repository name." [url] (let [s (re-find ssh-regexp url) h (re-find http-regexp url)] (cond s {:raw url :protocol "ssh" :host "github.com" :user (nth s 2) :owner (nth s 3) :repo (nth s 4)} h {:raw url :protocol (nth h 2) :host "github.com" :user (nth h 4) :owner (nth h 5) :repo (nth h 6)} :else (throw (ex-info "Unrecognized github repo url" {:url url}))))) (defn- local-repo-dir "generate local repo dir" [base-dir owner repo] (str/join "/" [base-dir owner repo])) (defn- generate-git-url "generate regular repo url based on repo info map. " [{:keys [protocol host user owner repo]}] (cond (http? protocol user) (format "%s://%s/%s/%s" (or protocol "https") host owner repo) (ssh? protocol user) (format "%s@%s:%s/%s" user host owner repo))) (defn- normalize-git-url "normalize repo's url which is hosted on github. support multiple formats: - [https://][github.com/]<owner>/<repo-name>[.git] - https://github.com/<owner>/<repo-name>/xxx/yyy/zzz.. - git://github.com:<owner>/<repo-name>.git" [url] (let [info (parse-git-url url)] (generate-git-url info))) (defn- gh-clone "clone git repo under specified directory" [base-dir repo-path & {:keys [force] :or {force false}}] (let [info (parse-git-url repo-path) repo-url (generate-git-url info) {:keys [owner repo]} info repo-base (repo-base-dir base-dir) local-dir (local-repo-dir repo-base owner repo) _ (b/delete-dir local-dir force) cmd ["git" "clone" repo-url local-dir] p (p/process cmd {:inherit true :shutdown p/destroy-tree})] ;; TODO: check error (shell/sh "mkdir" "-p" local-dir) @p ;; return nil to avoid printing the process instance nil)) (defn gh-local-check "check whether local clone for the given repo exists" [base-dir repo-path] (let [info (parse-git-url repo-path) {:keys [owner repo]} info repo-base (repo-base-dir base-dir) local-dir (local-repo-dir repo-base owner repo)] (if (fs/directory? local-dir) (println (format "repo - %s" local-dir)) (println (format "repo - %s/%s not exist" owner repo))))) (defn usage "help info" [options-summary] (->> ["gh.clj - a github repo util" "" "Usage: gh.clj [options] <subcommands> <repo-path>" "" "Options:" options-summary "" "Subcommands" " clone clone github repo" " check check if local repo clone exists" "" ""] (str/join \newline))) (def cli-options [["-h" "--help"] ["-d" "--dir DIR" "Base dir for local github repos, default is $GITHUB_WORKSHOP" :default ""] ["-f" "--force" "Delete local repo directory before clone"]]) (defn dispatch "invoke subcommands based on given cmd args" [args options] (let [action (first args)] (case action "clone" (let [repo-path (second args) {:keys [dir force] :or {force false}} options] (if (str/blank? repo-path) (b/exit 1 "please specify <repo-path>") (gh-clone dir repo-path :force force))) "check" (let [repo-path (second args)] (if (str/blank? repo-path) (b/exit 1 "please specify <repo-path>") (gh-local-check (:dir options) repo-path))) (b/exit 1 (str "Unknown subcommand - " action))))) (defn- main "main entry" [& args] (let [arguments (parse-opts args cli-options :in-order false) options (:options arguments) summary (:summary arguments) subcommands (:arguments arguments)] (if-let [errors (:errors arguments)] (println (str/join \newline errors)) (if (or (:help options) (empty? subcommands)) (print (usage summary)) (dispatch subcommands options))))) ;; dev (comment (def ssh-repo "git@github.com:jwells131313/goethe.gitt") (def http-repo "https://github.com/cxa/dicmd/tree/main/src") (re-find ssh-regexp ssh-repo) (re-find http-regexp http-repo) (def a (io/as-url u)) (def a-path (.getPath a)) (str/starts-with? "aaabbb" "aa") (str/split "/a/b/c" #"/") (str/join "/" ["a" "b"]) (gh-clone "." u) (parse-git-url "https://github.com/caddyserver/caddy#install") (def p (parse-git-url "git@github.com:gramineproject/gramine.ggit")) (generate-git-url p) ) ;; run (when (= *file* (System/getProperty "babashka.file")) (apply main *command-line-args*))
55375
#!/usr/bin/env bb ;; -*- mode: clojure; -*- ;; utils for github repos ;; - [x] clone repos from github ;; - [x] check local repo exists ;; clone github repos into configured directory - `GITHUB_WORKSHOP`. ;; If the env is not set, use current directory. Both account subdir ;; will be created if necessary. ;; ;; NOTE: ;; 1. if url schema is not provided, assuming the repo is from github ;; 2. If `--dir` option is set, use the value otherwise clone the repo ;; into `GITHUB_WORKSHOP`. ;; ;; NOTE: ;; 1. GITHUB_WORKSPACE must be absolute-path as babashka does not provide ;; `expand-home` util (ns gh (:require [babashka.fs :as fs] [babashka.process :as p] [battery :as b] [clojure.java.io :as io] [clojure.java.shell :as shell] [clojure.string :as str] [clojure.tools.cli :refer [parse-opts]])) (def ^:private ssh-regexp #"^((git)@)?github.com:([\w-]+)/([\w-]+)(\.git$)?") (def ^:private http-regexp #"^((http|https)://)?((\w+)@)?github.com/([\w-]+)/([\w-]+)/?") (defn- repo-base-dir [dir] (if (str/blank? dir) (let [dir (System/getenv "GITHUB_WORKSHOP")] (if (empty? dir) b/cwd dir)) dir)) (defn- ssh? "test whether the repo url is in ssh protocol." [protocol user] (and (= "ssh" protocol) (= "git" user))) (defn- http? "test whether the repo url is in http protocol." [protocol user] (and (empty? user) (#{"http" "https"} protocol))) ;; inspired by IonicaBizau/git-url-parse. (defn parse-git-url "parse git url, only extract owner and repository name." [url] (let [s (re-find ssh-regexp url) h (re-find http-regexp url)] (cond s {:raw url :protocol "ssh" :host "github.com" :user (nth s 2) :owner (nth s 3) :repo (nth s 4)} h {:raw url :protocol (nth h 2) :host "github.com" :user (nth h 4) :owner (nth h 5) :repo (nth h 6)} :else (throw (ex-info "Unrecognized github repo url" {:url url}))))) (defn- local-repo-dir "generate local repo dir" [base-dir owner repo] (str/join "/" [base-dir owner repo])) (defn- generate-git-url "generate regular repo url based on repo info map. " [{:keys [protocol host user owner repo]}] (cond (http? protocol user) (format "%s://%s/%s/%s" (or protocol "https") host owner repo) (ssh? protocol user) (format "%s@%s:%s/%s" user host owner repo))) (defn- normalize-git-url "normalize repo's url which is hosted on github. support multiple formats: - [https://][github.com/]<owner>/<repo-name>[.git] - https://github.com/<owner>/<repo-name>/xxx/yyy/zzz.. - git://github.com:<owner>/<repo-name>.git" [url] (let [info (parse-git-url url)] (generate-git-url info))) (defn- gh-clone "clone git repo under specified directory" [base-dir repo-path & {:keys [force] :or {force false}}] (let [info (parse-git-url repo-path) repo-url (generate-git-url info) {:keys [owner repo]} info repo-base (repo-base-dir base-dir) local-dir (local-repo-dir repo-base owner repo) _ (b/delete-dir local-dir force) cmd ["git" "clone" repo-url local-dir] p (p/process cmd {:inherit true :shutdown p/destroy-tree})] ;; TODO: check error (shell/sh "mkdir" "-p" local-dir) @p ;; return nil to avoid printing the process instance nil)) (defn gh-local-check "check whether local clone for the given repo exists" [base-dir repo-path] (let [info (parse-git-url repo-path) {:keys [owner repo]} info repo-base (repo-base-dir base-dir) local-dir (local-repo-dir repo-base owner repo)] (if (fs/directory? local-dir) (println (format "repo - %s" local-dir)) (println (format "repo - %s/%s not exist" owner repo))))) (defn usage "help info" [options-summary] (->> ["gh.clj - a github repo util" "" "Usage: gh.clj [options] <subcommands> <repo-path>" "" "Options:" options-summary "" "Subcommands" " clone clone github repo" " check check if local repo clone exists" "" ""] (str/join \newline))) (def cli-options [["-h" "--help"] ["-d" "--dir DIR" "Base dir for local github repos, default is $GITHUB_WORKSHOP" :default ""] ["-f" "--force" "Delete local repo directory before clone"]]) (defn dispatch "invoke subcommands based on given cmd args" [args options] (let [action (first args)] (case action "clone" (let [repo-path (second args) {:keys [dir force] :or {force false}} options] (if (str/blank? repo-path) (b/exit 1 "please specify <repo-path>") (gh-clone dir repo-path :force force))) "check" (let [repo-path (second args)] (if (str/blank? repo-path) (b/exit 1 "please specify <repo-path>") (gh-local-check (:dir options) repo-path))) (b/exit 1 (str "Unknown subcommand - " action))))) (defn- main "main entry" [& args] (let [arguments (parse-opts args cli-options :in-order false) options (:options arguments) summary (:summary arguments) subcommands (:arguments arguments)] (if-let [errors (:errors arguments)] (println (str/join \newline errors)) (if (or (:help options) (empty? subcommands)) (print (usage summary)) (dispatch subcommands options))))) ;; dev (comment (def ssh-repo "<EMAIL>:jwells131313/goethe.gitt") (def http-repo "https://github.com/cxa/dicmd/tree/main/src") (re-find ssh-regexp ssh-repo) (re-find http-regexp http-repo) (def a (io/as-url u)) (def a-path (.getPath a)) (str/starts-with? "aaabbb" "aa") (str/split "/a/b/c" #"/") (str/join "/" ["a" "b"]) (gh-clone "." u) (parse-git-url "https://github.com/caddyserver/caddy#install") (def p (parse-git-url "<EMAIL>:gramineproject/gramine.ggit")) (generate-git-url p) ) ;; run (when (= *file* (System/getProperty "babashka.file")) (apply main *command-line-args*))
true
#!/usr/bin/env bb ;; -*- mode: clojure; -*- ;; utils for github repos ;; - [x] clone repos from github ;; - [x] check local repo exists ;; clone github repos into configured directory - `GITHUB_WORKSHOP`. ;; If the env is not set, use current directory. Both account subdir ;; will be created if necessary. ;; ;; NOTE: ;; 1. if url schema is not provided, assuming the repo is from github ;; 2. If `--dir` option is set, use the value otherwise clone the repo ;; into `GITHUB_WORKSHOP`. ;; ;; NOTE: ;; 1. GITHUB_WORKSPACE must be absolute-path as babashka does not provide ;; `expand-home` util (ns gh (:require [babashka.fs :as fs] [babashka.process :as p] [battery :as b] [clojure.java.io :as io] [clojure.java.shell :as shell] [clojure.string :as str] [clojure.tools.cli :refer [parse-opts]])) (def ^:private ssh-regexp #"^((git)@)?github.com:([\w-]+)/([\w-]+)(\.git$)?") (def ^:private http-regexp #"^((http|https)://)?((\w+)@)?github.com/([\w-]+)/([\w-]+)/?") (defn- repo-base-dir [dir] (if (str/blank? dir) (let [dir (System/getenv "GITHUB_WORKSHOP")] (if (empty? dir) b/cwd dir)) dir)) (defn- ssh? "test whether the repo url is in ssh protocol." [protocol user] (and (= "ssh" protocol) (= "git" user))) (defn- http? "test whether the repo url is in http protocol." [protocol user] (and (empty? user) (#{"http" "https"} protocol))) ;; inspired by IonicaBizau/git-url-parse. (defn parse-git-url "parse git url, only extract owner and repository name." [url] (let [s (re-find ssh-regexp url) h (re-find http-regexp url)] (cond s {:raw url :protocol "ssh" :host "github.com" :user (nth s 2) :owner (nth s 3) :repo (nth s 4)} h {:raw url :protocol (nth h 2) :host "github.com" :user (nth h 4) :owner (nth h 5) :repo (nth h 6)} :else (throw (ex-info "Unrecognized github repo url" {:url url}))))) (defn- local-repo-dir "generate local repo dir" [base-dir owner repo] (str/join "/" [base-dir owner repo])) (defn- generate-git-url "generate regular repo url based on repo info map. " [{:keys [protocol host user owner repo]}] (cond (http? protocol user) (format "%s://%s/%s/%s" (or protocol "https") host owner repo) (ssh? protocol user) (format "%s@%s:%s/%s" user host owner repo))) (defn- normalize-git-url "normalize repo's url which is hosted on github. support multiple formats: - [https://][github.com/]<owner>/<repo-name>[.git] - https://github.com/<owner>/<repo-name>/xxx/yyy/zzz.. - git://github.com:<owner>/<repo-name>.git" [url] (let [info (parse-git-url url)] (generate-git-url info))) (defn- gh-clone "clone git repo under specified directory" [base-dir repo-path & {:keys [force] :or {force false}}] (let [info (parse-git-url repo-path) repo-url (generate-git-url info) {:keys [owner repo]} info repo-base (repo-base-dir base-dir) local-dir (local-repo-dir repo-base owner repo) _ (b/delete-dir local-dir force) cmd ["git" "clone" repo-url local-dir] p (p/process cmd {:inherit true :shutdown p/destroy-tree})] ;; TODO: check error (shell/sh "mkdir" "-p" local-dir) @p ;; return nil to avoid printing the process instance nil)) (defn gh-local-check "check whether local clone for the given repo exists" [base-dir repo-path] (let [info (parse-git-url repo-path) {:keys [owner repo]} info repo-base (repo-base-dir base-dir) local-dir (local-repo-dir repo-base owner repo)] (if (fs/directory? local-dir) (println (format "repo - %s" local-dir)) (println (format "repo - %s/%s not exist" owner repo))))) (defn usage "help info" [options-summary] (->> ["gh.clj - a github repo util" "" "Usage: gh.clj [options] <subcommands> <repo-path>" "" "Options:" options-summary "" "Subcommands" " clone clone github repo" " check check if local repo clone exists" "" ""] (str/join \newline))) (def cli-options [["-h" "--help"] ["-d" "--dir DIR" "Base dir for local github repos, default is $GITHUB_WORKSHOP" :default ""] ["-f" "--force" "Delete local repo directory before clone"]]) (defn dispatch "invoke subcommands based on given cmd args" [args options] (let [action (first args)] (case action "clone" (let [repo-path (second args) {:keys [dir force] :or {force false}} options] (if (str/blank? repo-path) (b/exit 1 "please specify <repo-path>") (gh-clone dir repo-path :force force))) "check" (let [repo-path (second args)] (if (str/blank? repo-path) (b/exit 1 "please specify <repo-path>") (gh-local-check (:dir options) repo-path))) (b/exit 1 (str "Unknown subcommand - " action))))) (defn- main "main entry" [& args] (let [arguments (parse-opts args cli-options :in-order false) options (:options arguments) summary (:summary arguments) subcommands (:arguments arguments)] (if-let [errors (:errors arguments)] (println (str/join \newline errors)) (if (or (:help options) (empty? subcommands)) (print (usage summary)) (dispatch subcommands options))))) ;; dev (comment (def ssh-repo "PI:EMAIL:<EMAIL>END_PI:jwells131313/goethe.gitt") (def http-repo "https://github.com/cxa/dicmd/tree/main/src") (re-find ssh-regexp ssh-repo) (re-find http-regexp http-repo) (def a (io/as-url u)) (def a-path (.getPath a)) (str/starts-with? "aaabbb" "aa") (str/split "/a/b/c" #"/") (str/join "/" ["a" "b"]) (gh-clone "." u) (parse-git-url "https://github.com/caddyserver/caddy#install") (def p (parse-git-url "PI:EMAIL:<EMAIL>END_PI:gramineproject/gramine.ggit")) (generate-git-url p) ) ;; run (when (= *file* (System/getProperty "babashka.file")) (apply main *command-line-args*))
[ { "context": "r\"})\n\n )\n\n\n(comment\n\n (-> {:user/account-email \"zk+60@heyzk.com\",\n :user/id \"2399a725-2559-4bdc-ad28-546077", "end": 13007, "score": 0.9999237060546875, "start": 12992, "tag": "EMAIL", "value": "zk+60@heyzk.com" }, { "context": "77473e33\",\n :user/push-tokens-ios\n #{\"5bbd4cddebec021483f2f6e276a62c0d233b1fd71f55ad08ba17e89d4dc9cb98\"},\n :user/push-tokens-ios-with-errors\n ", "end": 13239, "score": 0.9918205738067627, "start": 13175, "tag": "KEY", "value": "5bbd4cddebec021483f2f6e276a62c0d233b1fd71f55ad08ba17e89d4dc9cb98" }, { "context": " :user/push-tokens-ios-with-errors\n #{\"5bbd4cddebec021483f2f6e276a62c0d233b1fd71f55ad08ba17e89d4dc9cb98\"},\n :user/business-name \"Z\",\n :db/id ", "end": 13358, "score": 0.9914985299110413, "start": 13294, "tag": "KEY", "value": "5bbd4cddebec021483f2f6e276a62c0d233b1fd71f55ad08ba17e89d4dc9cb98" } ]
src/clj/rx/awsdeploy.clj
zk/rx-lib
0
(ns rx.awsdeploy (:require [clojure.java.io :as io] [clojure.edn :as edn] [clojure.string :as str] [rx.kitchen-sink :as ks] [clj-http.client :as hc] [rx.aws :as aws] [me.raynes.conch :as ch] [me.raynes.conch.low-level :as sh] [cljsbuild.compiler :as cc])) (def lfn-required-keys #{:function-id :runtime-name :memory-mb :handler :role-arn :clean-script :package-script :package-dir}) (def lfn-defaults {:no-publish? false :timeout-seconds 10 :tracing-config "PassThrough"}) (defn read-config [] (edn/read (java.io.PushbackReader. (io/reader (.getBytes (slurp "awsdeploy.edn")))))) (defn first-lambda [] (-> (read-config) :lambda :functions first)) (defn lfnc->function-name [{:keys [function-id function-name] :as lfn-config}] (if function-id (str (namespace function-id) "__" (name function-id)) function-name)) (defn proc-blocking [command] (try (let [p (apply sh/proc command)] (future (sh/stream-to-out p :out)) (future (sh/stream-to-out p :err)) (let [exit-code (sh/exit-code p)] (if (= 0 exit-code) [{:exit-code exit-code}] [nil {:exit-code exit-code}]))) (catch Exception e [nil e]))) (defn proc-blocking-silent-stdout [command] (try (let [p (apply sh/proc command)] (future (sh/stream-to-string p :out)) (future (sh/stream-to-string p :err)) (let [exit-code (sh/exit-code p)] (if (= 0 exit-code) [{:exit-code exit-code}] [nil {:exit-code exit-code}]))) (catch Exception e [nil e]))) (defn report-and-run [command] (println " *" command) (let [[response err] (proc-blocking command)] (if err (do (println " ! Error" command err) [nil err]) [response err]))) (defn report-and-run-silent-stdout [command] (println " *" command) (let [[response err] (proc-blocking-silent-stdout command)] (if err (do (println " ! Error" command err) [nil err]) [response err]))) (comment (prn (report-and-run ["lein" "with-profile" "prod" "cljsbuild" "once" "canter-apiserver"])) ) (defn zip-name [lfn-config] (str (lfnc->function-name lfn-config) ".zip")) (defn lfnc->zip-path [{:keys [zip-path package-dir] :as lfn-config}] (or zip-path (str package-dir "/" (zip-name lfn-config)))) (defn zip-byte-buffer [lfn-config] (-> lfn-config lfnc->zip-path aws/path->zipfile)) (defn report-update-function-code [lfn-config] (let [lfn-name (lfnc->function-name lfn-config)] (println " * Updating function" lfn-name) (let [[res err] (aws/update-function-code lfn-config {:functionName lfn-name :zipFile (zip-byte-buffer lfn-config)})] (when err (println " ! Error updating function code" err)) [res err]))) (defn lfnc->create-function [{:keys [description env handler memory-mb publish? role-arn runtime-name tags timeout-seconds tracing-config kms-key-arn vpc-config] :as lfnc}] (merge {:code {:zipFile (-> lfnc lfnc->zip-path aws/path->zipfile)} :description description :environment {:variables env} :functionName (lfnc->function-name lfnc) :memorySize memory-mb :publish publish? :role role-arn :runtime runtime-name :tags tags :timeout timeout-seconds :handler handler} (when kms-key-arn {:kmsKeyArn kms-key-arn}) (when tracing-config {:tracingConfig {:mode tracing-config}}) (when vpc-config {:vpcConfig vpc-config}) {:zip-path (lfnc->zip-path lfnc)})) (defn report-create-function [lfn-config] (println " * Creating function" (lfnc->function-name lfn-config)) (let [[res err exc :as pl] (aws/create-function lfn-config (lfnc->create-function lfn-config))] (when err (ks/pp exc) (println " ! Error creating function" err)) pl)) (defn report-create-or-update-function [lfn-config] (let [function-name (lfnc->function-name lfn-config)] (println " * Checking for existing" function-name) (let [[exists?] (aws/get-function lfn-config {:functionName function-name})] (if exists? (report-update-function-code lfn-config) (report-create-function lfn-config))))) (defn report-test-invoke [lfn-config payload] (println " * Invoking" (lfnc->function-name lfn-config) "with payload" (pr-str payload)) (let [[res err] (aws/invoke lfn-config {:functionName (lfnc->function-name lfn-config) :logType "Tail"})] (if err (do (println " * Error running fn") [nil err]) (let [data res err? (get #{"Unhandled" "Handled"} (:functionError data))] (if err? (do (ks/pp data) (println "\n") (println (:logResult data)) (println "* Error running lfn" (lfnc->function-name lfn-config)) [nil data]) (do (println " * Run Log vvvvvvvvvvvvvvvvvvv\n\n") (println (:logResult data)) (println "\n * Result vvvvvvvvvvvvvvvvvvvv\n\n") (println (:payload data)) (println "\n") (println " * Test Invoke Succeeded") [data])))))) (defn test-deployed-function [{:keys [verify-payloads] :as lfn-config}] (println " * Verifying" (count verify-payloads) "payload(s)") (loop [pls verify-payloads] (if (empty? pls) [{:success? true}] (let [pl (first pls) [res err] (report-test-invoke lfn-config pl)] (if err [nil err] (recur (rest pls))))))) (defn zip-package [{:keys [package-dir] :as lfn-config}] "zip -vr rx-node.zip ./* | grep --color=none totalbytes" (println " * Zipping" package-dir) (let [[res err] (proc-blocking-silent-stdout ["zip" "-vr" (zip-name lfn-config) "." :dir package-dir])] (when err (println " ! Error zipping:" err)) [res err])) (defn exit-on-error [fns] (loop [fns fns] (when-let [f (first fns)] (let [[res err] (f)] (if (if (:exit-code res) (= 0 (:exit-code res)) (and res (not err))) (recur (rest fns)) (println " ! Error encountered, exiting block")))))) (defn deploy-lambda-fn [{:keys [clean-script package-script package-dir include-node-modules? cljsbuild] :as lfn-config}] (exit-on-error (->> [(when clean-script #(report-and-run clean-script)) #_(when package-dir #(report-and-run ["rm" "-rf" package-dir])) (when package-script #(report-and-run package-script)) (when include-node-modules? #(report-and-run ["rsync" "-a" "--stats" "./node_modules" package-dir])) (when package-dir #(zip-package lfn-config)) #(report-create-or-update-function lfn-config) #(test-deployed-function lfn-config)] (remove nil?))) #(println " * Complete")) (defn deploy [id-or-lfc] (let [deploy-config (when (keyword? id-or-lfc) (read-config)) creds (if (keyword? id-or-lfc) (select-keys deploy-config [:region :access-key :secret-key]))] (if-let [lfc (if (keyword? id-or-lfc) (->> deploy-config :lambda :functions (filter #(= id-or-lfc (:function-id %))) first) id-or-lfc)] (deploy-lambda-fn (merge creds lfc)) (println " ! No config found for id" id-or-lfc)))) (defn invoke [id] (let [deploy-config (read-config) creds (select-keys deploy-config [:region :access-key :secret-key])] (if-let [lfc (->> deploy-config :lambda :functions (filter #(= id (:function-id %))) first)] (test-deployed-function (merge creds lfc)) (println " ! No config found for id" id)))) (comment (deploy (merge {:function-id :canter/apiserver_20191205 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/lambda-exec" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["bin/apiserver-build-and-test"] :package-dir "target/prod/canter/apiserver"} {:region "us-west-2" :access-key "" :secret-key ""})) (deploy (merge {:function-id :evry/sync_lambda_20191201 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/evry-prod-lambda" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "evry-sync-lambda"] :package-dir "target/prod/evry-sync-lambda"} {:region "us-west-2" :access-key "" :secret-key ""})) (deploy (merge {:function-id :zkdev/sync_server_lambda_20191207 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/zkdev-prod-sync-server-lambda" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "zkdev-sync-server-lambda"] :package-dir "target/prod/zkdev-sync-server-lambda"} {:region "us-west-2" :access-key "" :secret-key ""})) (deploy (merge {:function-id :rx/sync_server_lambda_20191217 :runtime-name "nodejs12.x" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/rx-sync-server-lambda" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "rx-sync-server-lambda"] :package-dir "target/prod/rx-sync-server-lambda"} {:region "us-west-2" :access-key "" :secret-key ""})) #_(deploy :canter/anomaly-reporting) #_(deploy :canter/apiserver_20190513) #_(deploy (merge {:function-id :canter/reminderpoll_20190731 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 270 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/lambda-exec" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "canter-reminderpoll"] :package-dir "target/prod/canter/reminderpoll" :verify-payloads [{}]} {:region "us-west-2" :access-key "" :secret-key ""})) #_(deploy :canter/generatethumbs) #_(report-and-run ["rsync" "-a" "--stats" "./node_modules" "target/prod/canter/apiserver"]) (zip-package {:function-id :canter/apiserver_20190526 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/lambda-exec" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["bin/apiserver-build-and-test"] :package-dir "target/prod/canter/apiserver"}) ) (comment (-> {:user/account-email "zk+60@heyzk.com", :user/id "2399a725-2559-4bdc-ad28-546077473e33", :user/cognito-user-sub "2399a725-2559-4bdc-ad28-546077473e33", :user/push-tokens-ios #{"5bbd4cddebec021483f2f6e276a62c0d233b1fd71f55ad08ba17e89d4dc9cb98"}, :user/push-tokens-ios-with-errors #{"5bbd4cddebec021483f2f6e276a62c0d233b1fd71f55ad08ba17e89d4dc9cb98"}, :user/business-name "Z", :db/id 3} (dissoc :user/push-tokens-ios-with-errors)) )
114501
(ns rx.awsdeploy (:require [clojure.java.io :as io] [clojure.edn :as edn] [clojure.string :as str] [rx.kitchen-sink :as ks] [clj-http.client :as hc] [rx.aws :as aws] [me.raynes.conch :as ch] [me.raynes.conch.low-level :as sh] [cljsbuild.compiler :as cc])) (def lfn-required-keys #{:function-id :runtime-name :memory-mb :handler :role-arn :clean-script :package-script :package-dir}) (def lfn-defaults {:no-publish? false :timeout-seconds 10 :tracing-config "PassThrough"}) (defn read-config [] (edn/read (java.io.PushbackReader. (io/reader (.getBytes (slurp "awsdeploy.edn")))))) (defn first-lambda [] (-> (read-config) :lambda :functions first)) (defn lfnc->function-name [{:keys [function-id function-name] :as lfn-config}] (if function-id (str (namespace function-id) "__" (name function-id)) function-name)) (defn proc-blocking [command] (try (let [p (apply sh/proc command)] (future (sh/stream-to-out p :out)) (future (sh/stream-to-out p :err)) (let [exit-code (sh/exit-code p)] (if (= 0 exit-code) [{:exit-code exit-code}] [nil {:exit-code exit-code}]))) (catch Exception e [nil e]))) (defn proc-blocking-silent-stdout [command] (try (let [p (apply sh/proc command)] (future (sh/stream-to-string p :out)) (future (sh/stream-to-string p :err)) (let [exit-code (sh/exit-code p)] (if (= 0 exit-code) [{:exit-code exit-code}] [nil {:exit-code exit-code}]))) (catch Exception e [nil e]))) (defn report-and-run [command] (println " *" command) (let [[response err] (proc-blocking command)] (if err (do (println " ! Error" command err) [nil err]) [response err]))) (defn report-and-run-silent-stdout [command] (println " *" command) (let [[response err] (proc-blocking-silent-stdout command)] (if err (do (println " ! Error" command err) [nil err]) [response err]))) (comment (prn (report-and-run ["lein" "with-profile" "prod" "cljsbuild" "once" "canter-apiserver"])) ) (defn zip-name [lfn-config] (str (lfnc->function-name lfn-config) ".zip")) (defn lfnc->zip-path [{:keys [zip-path package-dir] :as lfn-config}] (or zip-path (str package-dir "/" (zip-name lfn-config)))) (defn zip-byte-buffer [lfn-config] (-> lfn-config lfnc->zip-path aws/path->zipfile)) (defn report-update-function-code [lfn-config] (let [lfn-name (lfnc->function-name lfn-config)] (println " * Updating function" lfn-name) (let [[res err] (aws/update-function-code lfn-config {:functionName lfn-name :zipFile (zip-byte-buffer lfn-config)})] (when err (println " ! Error updating function code" err)) [res err]))) (defn lfnc->create-function [{:keys [description env handler memory-mb publish? role-arn runtime-name tags timeout-seconds tracing-config kms-key-arn vpc-config] :as lfnc}] (merge {:code {:zipFile (-> lfnc lfnc->zip-path aws/path->zipfile)} :description description :environment {:variables env} :functionName (lfnc->function-name lfnc) :memorySize memory-mb :publish publish? :role role-arn :runtime runtime-name :tags tags :timeout timeout-seconds :handler handler} (when kms-key-arn {:kmsKeyArn kms-key-arn}) (when tracing-config {:tracingConfig {:mode tracing-config}}) (when vpc-config {:vpcConfig vpc-config}) {:zip-path (lfnc->zip-path lfnc)})) (defn report-create-function [lfn-config] (println " * Creating function" (lfnc->function-name lfn-config)) (let [[res err exc :as pl] (aws/create-function lfn-config (lfnc->create-function lfn-config))] (when err (ks/pp exc) (println " ! Error creating function" err)) pl)) (defn report-create-or-update-function [lfn-config] (let [function-name (lfnc->function-name lfn-config)] (println " * Checking for existing" function-name) (let [[exists?] (aws/get-function lfn-config {:functionName function-name})] (if exists? (report-update-function-code lfn-config) (report-create-function lfn-config))))) (defn report-test-invoke [lfn-config payload] (println " * Invoking" (lfnc->function-name lfn-config) "with payload" (pr-str payload)) (let [[res err] (aws/invoke lfn-config {:functionName (lfnc->function-name lfn-config) :logType "Tail"})] (if err (do (println " * Error running fn") [nil err]) (let [data res err? (get #{"Unhandled" "Handled"} (:functionError data))] (if err? (do (ks/pp data) (println "\n") (println (:logResult data)) (println "* Error running lfn" (lfnc->function-name lfn-config)) [nil data]) (do (println " * Run Log vvvvvvvvvvvvvvvvvvv\n\n") (println (:logResult data)) (println "\n * Result vvvvvvvvvvvvvvvvvvvv\n\n") (println (:payload data)) (println "\n") (println " * Test Invoke Succeeded") [data])))))) (defn test-deployed-function [{:keys [verify-payloads] :as lfn-config}] (println " * Verifying" (count verify-payloads) "payload(s)") (loop [pls verify-payloads] (if (empty? pls) [{:success? true}] (let [pl (first pls) [res err] (report-test-invoke lfn-config pl)] (if err [nil err] (recur (rest pls))))))) (defn zip-package [{:keys [package-dir] :as lfn-config}] "zip -vr rx-node.zip ./* | grep --color=none totalbytes" (println " * Zipping" package-dir) (let [[res err] (proc-blocking-silent-stdout ["zip" "-vr" (zip-name lfn-config) "." :dir package-dir])] (when err (println " ! Error zipping:" err)) [res err])) (defn exit-on-error [fns] (loop [fns fns] (when-let [f (first fns)] (let [[res err] (f)] (if (if (:exit-code res) (= 0 (:exit-code res)) (and res (not err))) (recur (rest fns)) (println " ! Error encountered, exiting block")))))) (defn deploy-lambda-fn [{:keys [clean-script package-script package-dir include-node-modules? cljsbuild] :as lfn-config}] (exit-on-error (->> [(when clean-script #(report-and-run clean-script)) #_(when package-dir #(report-and-run ["rm" "-rf" package-dir])) (when package-script #(report-and-run package-script)) (when include-node-modules? #(report-and-run ["rsync" "-a" "--stats" "./node_modules" package-dir])) (when package-dir #(zip-package lfn-config)) #(report-create-or-update-function lfn-config) #(test-deployed-function lfn-config)] (remove nil?))) #(println " * Complete")) (defn deploy [id-or-lfc] (let [deploy-config (when (keyword? id-or-lfc) (read-config)) creds (if (keyword? id-or-lfc) (select-keys deploy-config [:region :access-key :secret-key]))] (if-let [lfc (if (keyword? id-or-lfc) (->> deploy-config :lambda :functions (filter #(= id-or-lfc (:function-id %))) first) id-or-lfc)] (deploy-lambda-fn (merge creds lfc)) (println " ! No config found for id" id-or-lfc)))) (defn invoke [id] (let [deploy-config (read-config) creds (select-keys deploy-config [:region :access-key :secret-key])] (if-let [lfc (->> deploy-config :lambda :functions (filter #(= id (:function-id %))) first)] (test-deployed-function (merge creds lfc)) (println " ! No config found for id" id)))) (comment (deploy (merge {:function-id :canter/apiserver_20191205 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/lambda-exec" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["bin/apiserver-build-and-test"] :package-dir "target/prod/canter/apiserver"} {:region "us-west-2" :access-key "" :secret-key ""})) (deploy (merge {:function-id :evry/sync_lambda_20191201 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/evry-prod-lambda" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "evry-sync-lambda"] :package-dir "target/prod/evry-sync-lambda"} {:region "us-west-2" :access-key "" :secret-key ""})) (deploy (merge {:function-id :zkdev/sync_server_lambda_20191207 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/zkdev-prod-sync-server-lambda" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "zkdev-sync-server-lambda"] :package-dir "target/prod/zkdev-sync-server-lambda"} {:region "us-west-2" :access-key "" :secret-key ""})) (deploy (merge {:function-id :rx/sync_server_lambda_20191217 :runtime-name "nodejs12.x" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/rx-sync-server-lambda" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "rx-sync-server-lambda"] :package-dir "target/prod/rx-sync-server-lambda"} {:region "us-west-2" :access-key "" :secret-key ""})) #_(deploy :canter/anomaly-reporting) #_(deploy :canter/apiserver_20190513) #_(deploy (merge {:function-id :canter/reminderpoll_20190731 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 270 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/lambda-exec" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "canter-reminderpoll"] :package-dir "target/prod/canter/reminderpoll" :verify-payloads [{}]} {:region "us-west-2" :access-key "" :secret-key ""})) #_(deploy :canter/generatethumbs) #_(report-and-run ["rsync" "-a" "--stats" "./node_modules" "target/prod/canter/apiserver"]) (zip-package {:function-id :canter/apiserver_20190526 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/lambda-exec" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["bin/apiserver-build-and-test"] :package-dir "target/prod/canter/apiserver"}) ) (comment (-> {:user/account-email "<EMAIL>", :user/id "2399a725-2559-4bdc-ad28-546077473e33", :user/cognito-user-sub "2399a725-2559-4bdc-ad28-546077473e33", :user/push-tokens-ios #{"<KEY>"}, :user/push-tokens-ios-with-errors #{"<KEY>"}, :user/business-name "Z", :db/id 3} (dissoc :user/push-tokens-ios-with-errors)) )
true
(ns rx.awsdeploy (:require [clojure.java.io :as io] [clojure.edn :as edn] [clojure.string :as str] [rx.kitchen-sink :as ks] [clj-http.client :as hc] [rx.aws :as aws] [me.raynes.conch :as ch] [me.raynes.conch.low-level :as sh] [cljsbuild.compiler :as cc])) (def lfn-required-keys #{:function-id :runtime-name :memory-mb :handler :role-arn :clean-script :package-script :package-dir}) (def lfn-defaults {:no-publish? false :timeout-seconds 10 :tracing-config "PassThrough"}) (defn read-config [] (edn/read (java.io.PushbackReader. (io/reader (.getBytes (slurp "awsdeploy.edn")))))) (defn first-lambda [] (-> (read-config) :lambda :functions first)) (defn lfnc->function-name [{:keys [function-id function-name] :as lfn-config}] (if function-id (str (namespace function-id) "__" (name function-id)) function-name)) (defn proc-blocking [command] (try (let [p (apply sh/proc command)] (future (sh/stream-to-out p :out)) (future (sh/stream-to-out p :err)) (let [exit-code (sh/exit-code p)] (if (= 0 exit-code) [{:exit-code exit-code}] [nil {:exit-code exit-code}]))) (catch Exception e [nil e]))) (defn proc-blocking-silent-stdout [command] (try (let [p (apply sh/proc command)] (future (sh/stream-to-string p :out)) (future (sh/stream-to-string p :err)) (let [exit-code (sh/exit-code p)] (if (= 0 exit-code) [{:exit-code exit-code}] [nil {:exit-code exit-code}]))) (catch Exception e [nil e]))) (defn report-and-run [command] (println " *" command) (let [[response err] (proc-blocking command)] (if err (do (println " ! Error" command err) [nil err]) [response err]))) (defn report-and-run-silent-stdout [command] (println " *" command) (let [[response err] (proc-blocking-silent-stdout command)] (if err (do (println " ! Error" command err) [nil err]) [response err]))) (comment (prn (report-and-run ["lein" "with-profile" "prod" "cljsbuild" "once" "canter-apiserver"])) ) (defn zip-name [lfn-config] (str (lfnc->function-name lfn-config) ".zip")) (defn lfnc->zip-path [{:keys [zip-path package-dir] :as lfn-config}] (or zip-path (str package-dir "/" (zip-name lfn-config)))) (defn zip-byte-buffer [lfn-config] (-> lfn-config lfnc->zip-path aws/path->zipfile)) (defn report-update-function-code [lfn-config] (let [lfn-name (lfnc->function-name lfn-config)] (println " * Updating function" lfn-name) (let [[res err] (aws/update-function-code lfn-config {:functionName lfn-name :zipFile (zip-byte-buffer lfn-config)})] (when err (println " ! Error updating function code" err)) [res err]))) (defn lfnc->create-function [{:keys [description env handler memory-mb publish? role-arn runtime-name tags timeout-seconds tracing-config kms-key-arn vpc-config] :as lfnc}] (merge {:code {:zipFile (-> lfnc lfnc->zip-path aws/path->zipfile)} :description description :environment {:variables env} :functionName (lfnc->function-name lfnc) :memorySize memory-mb :publish publish? :role role-arn :runtime runtime-name :tags tags :timeout timeout-seconds :handler handler} (when kms-key-arn {:kmsKeyArn kms-key-arn}) (when tracing-config {:tracingConfig {:mode tracing-config}}) (when vpc-config {:vpcConfig vpc-config}) {:zip-path (lfnc->zip-path lfnc)})) (defn report-create-function [lfn-config] (println " * Creating function" (lfnc->function-name lfn-config)) (let [[res err exc :as pl] (aws/create-function lfn-config (lfnc->create-function lfn-config))] (when err (ks/pp exc) (println " ! Error creating function" err)) pl)) (defn report-create-or-update-function [lfn-config] (let [function-name (lfnc->function-name lfn-config)] (println " * Checking for existing" function-name) (let [[exists?] (aws/get-function lfn-config {:functionName function-name})] (if exists? (report-update-function-code lfn-config) (report-create-function lfn-config))))) (defn report-test-invoke [lfn-config payload] (println " * Invoking" (lfnc->function-name lfn-config) "with payload" (pr-str payload)) (let [[res err] (aws/invoke lfn-config {:functionName (lfnc->function-name lfn-config) :logType "Tail"})] (if err (do (println " * Error running fn") [nil err]) (let [data res err? (get #{"Unhandled" "Handled"} (:functionError data))] (if err? (do (ks/pp data) (println "\n") (println (:logResult data)) (println "* Error running lfn" (lfnc->function-name lfn-config)) [nil data]) (do (println " * Run Log vvvvvvvvvvvvvvvvvvv\n\n") (println (:logResult data)) (println "\n * Result vvvvvvvvvvvvvvvvvvvv\n\n") (println (:payload data)) (println "\n") (println " * Test Invoke Succeeded") [data])))))) (defn test-deployed-function [{:keys [verify-payloads] :as lfn-config}] (println " * Verifying" (count verify-payloads) "payload(s)") (loop [pls verify-payloads] (if (empty? pls) [{:success? true}] (let [pl (first pls) [res err] (report-test-invoke lfn-config pl)] (if err [nil err] (recur (rest pls))))))) (defn zip-package [{:keys [package-dir] :as lfn-config}] "zip -vr rx-node.zip ./* | grep --color=none totalbytes" (println " * Zipping" package-dir) (let [[res err] (proc-blocking-silent-stdout ["zip" "-vr" (zip-name lfn-config) "." :dir package-dir])] (when err (println " ! Error zipping:" err)) [res err])) (defn exit-on-error [fns] (loop [fns fns] (when-let [f (first fns)] (let [[res err] (f)] (if (if (:exit-code res) (= 0 (:exit-code res)) (and res (not err))) (recur (rest fns)) (println " ! Error encountered, exiting block")))))) (defn deploy-lambda-fn [{:keys [clean-script package-script package-dir include-node-modules? cljsbuild] :as lfn-config}] (exit-on-error (->> [(when clean-script #(report-and-run clean-script)) #_(when package-dir #(report-and-run ["rm" "-rf" package-dir])) (when package-script #(report-and-run package-script)) (when include-node-modules? #(report-and-run ["rsync" "-a" "--stats" "./node_modules" package-dir])) (when package-dir #(zip-package lfn-config)) #(report-create-or-update-function lfn-config) #(test-deployed-function lfn-config)] (remove nil?))) #(println " * Complete")) (defn deploy [id-or-lfc] (let [deploy-config (when (keyword? id-or-lfc) (read-config)) creds (if (keyword? id-or-lfc) (select-keys deploy-config [:region :access-key :secret-key]))] (if-let [lfc (if (keyword? id-or-lfc) (->> deploy-config :lambda :functions (filter #(= id-or-lfc (:function-id %))) first) id-or-lfc)] (deploy-lambda-fn (merge creds lfc)) (println " ! No config found for id" id-or-lfc)))) (defn invoke [id] (let [deploy-config (read-config) creds (select-keys deploy-config [:region :access-key :secret-key])] (if-let [lfc (->> deploy-config :lambda :functions (filter #(= id (:function-id %))) first)] (test-deployed-function (merge creds lfc)) (println " ! No config found for id" id)))) (comment (deploy (merge {:function-id :canter/apiserver_20191205 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/lambda-exec" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["bin/apiserver-build-and-test"] :package-dir "target/prod/canter/apiserver"} {:region "us-west-2" :access-key "" :secret-key ""})) (deploy (merge {:function-id :evry/sync_lambda_20191201 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/evry-prod-lambda" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "evry-sync-lambda"] :package-dir "target/prod/evry-sync-lambda"} {:region "us-west-2" :access-key "" :secret-key ""})) (deploy (merge {:function-id :zkdev/sync_server_lambda_20191207 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/zkdev-prod-sync-server-lambda" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "zkdev-sync-server-lambda"] :package-dir "target/prod/zkdev-sync-server-lambda"} {:region "us-west-2" :access-key "" :secret-key ""})) (deploy (merge {:function-id :rx/sync_server_lambda_20191217 :runtime-name "nodejs12.x" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/rx-sync-server-lambda" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "rx-sync-server-lambda"] :package-dir "target/prod/rx-sync-server-lambda"} {:region "us-west-2" :access-key "" :secret-key ""})) #_(deploy :canter/anomaly-reporting) #_(deploy :canter/apiserver_20190513) #_(deploy (merge {:function-id :canter/reminderpoll_20190731 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 270 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/lambda-exec" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["lein" "with-profile" "prod" "cljsbuild" "once" "canter-reminderpoll"] :package-dir "target/prod/canter/reminderpoll" :verify-payloads [{}]} {:region "us-west-2" :access-key "" :secret-key ""})) #_(deploy :canter/generatethumbs) #_(report-and-run ["rsync" "-a" "--stats" "./node_modules" "target/prod/canter/apiserver"]) (zip-package {:function-id :canter/apiserver_20190526 :runtime-name "nodejs8.10" :memory-mb 512 :timeout-seconds 30 :handler "run.handler" :role-arn "arn:aws:iam::753209818049:role/lambda-exec" :include-node-modules? true :clean-script ["lein" "with-profile" "prod" "clean"] :package-script ["bin/apiserver-build-and-test"] :package-dir "target/prod/canter/apiserver"}) ) (comment (-> {:user/account-email "PI:EMAIL:<EMAIL>END_PI", :user/id "2399a725-2559-4bdc-ad28-546077473e33", :user/cognito-user-sub "2399a725-2559-4bdc-ad28-546077473e33", :user/push-tokens-ios #{"PI:KEY:<KEY>END_PI"}, :user/push-tokens-ios-with-errors #{"PI:KEY:<KEY>END_PI"}, :user/business-name "Z", :db/id 3} (dissoc :user/push-tokens-ios-with-errors)) )
[ { "context": "ns\n ^{:doc \"Audio position fns\"\n :author \"Jeff Rose\"}\n overtone.helpers.stereo)\n\n(defn splay-pan\n \"", "end": 60, "score": 0.9998867511749268, "start": 51, "tag": "NAME", "value": "Jeff Rose" } ]
src/overtone/helpers/stereo.clj
ABaldwinHunter/overtone
3,870
(ns ^{:doc "Audio position fns" :author "Jeff Rose"} overtone.helpers.stereo) (defn splay-pan "Given n channels and a center point, returns a position in a stereo field for each channel, evenly distributed from the center +- spread." [n center spread] (for [i (range n)] (+ center (* spread (- (* i (/ 2 (dec n))) 1)))))
77698
(ns ^{:doc "Audio position fns" :author "<NAME>"} overtone.helpers.stereo) (defn splay-pan "Given n channels and a center point, returns a position in a stereo field for each channel, evenly distributed from the center +- spread." [n center spread] (for [i (range n)] (+ center (* spread (- (* i (/ 2 (dec n))) 1)))))
true
(ns ^{:doc "Audio position fns" :author "PI:NAME:<NAME>END_PI"} overtone.helpers.stereo) (defn splay-pan "Given n channels and a center point, returns a position in a stereo field for each channel, evenly distributed from the center +- spread." [n center spread] (for [i (range n)] (+ center (* spread (- (* i (/ 2 (dec n))) 1)))))
[ { "context": " (l/edn))\n expected {:fields [{:name :name\n :default nil\n ", "end": 3566, "score": 0.8522122502326965, "start": 3562, "tag": "NAME", "value": "name" }, { "context": " :name :name\n :ty", "end": 4366, "score": 0.9073628783226013, "start": 4362, "tag": "NAME", "value": "name" } ]
test/deercreeklabs/unit/edn_test.cljc
GriffinScribe-LLC/lancaster
42
(ns deercreeklabs.unit.edn-test (:require [clojure.test :refer [are deftest is]] [deercreeklabs.lancaster :as l] [deercreeklabs.unit.lancaster-test :as lt])) (l/def-enum-schema suits-schema :hearts :diamonds :spades :clubs) (l/def-record-schema user-schema [:name l/string-schema] [:nickname l/string-schema]) (l/def-array-schema users-schema user-schema) (l/def-record-schema msg-schema [:user user-schema] [:text l/string-schema]) (deftest test-edn->schema (are [edn] (= edn (-> edn l/edn->schema l/edn)) :string :int [:null :int :string] {:name ::test-fixed :type :fixed :size 16} {:name ::test-enum :type :enum :symbols [:a :b :c]} {:name ::test-rec :type :record :fields [{:name :a :type :int :default -1} {:name :b :type :string :default ""}]}) ) (deftest test-name-kw (let [cases [[l/string-schema :string] [l/int-schema :int] [lt/why-schema :deercreeklabs.unit.lancaster-test/why] [lt/a-fixed-schema :deercreeklabs.unit.lancaster-test/a-fixed] [lt/ages-schema :map] [lt/simple-array-schema :array] [lt/rec-w-array-and-enum-schema :deercreeklabs.unit.lancaster-test/rec-w-array-and-enum] [lt/maybe-int-schema :union]]] (doseq [[sch expected] cases] (let [edn (l/edn sch) ret (l/name-kw sch)] (is (= [edn expected] [edn ret])))))) (deftest test-round-trip-json-schema (let [json-schema (str "{\"type\":\"record\",\"name\":" "\"StringMinimalExample\",\"namespace\":" "\"com.piotr-yuxuan\",\"fields\":[{\"name\":" "\"someOtherField\",\"type\":[\"null\",\"long\"]}," "{\"name\":\"url\",\"type\":{\"type\":\"string\"," "\"avro.java.string\":\"String\"}}]}") schema (l/json->schema json-schema) rt-json-schema (l/json schema)] (is (= json-schema rt-json-schema)))) (deftest test-json-schema-w-evolution-no-default (let [data {:a 1} writer-schema (l/record-schema ::test-rec [[:a l/int-schema]]) reader-json (str "{\"name\":\"deercreeklabs.unit.edn_test.TestRec\"," "\"type\":\"record\",\"fields\":[" "{\"name\":\"a\",\"type\":\"int\"}," "{\"name\":\"b\",\"type\":\"string\"}]}") reader-schema (l/json->schema reader-json) encoded (l/serialize writer-schema data) decoded (l/deserialize reader-schema writer-schema encoded) expected (assoc data :b "")] (is (= expected decoded)))) #?(:clj (deftest test-issue-4 (let [json (slurp "test/example.avsc") schema (l/json->schema json)] (is (= json (l/json schema)))))) (deftest test-enum-pcf-rt (let [orig-edn (l/edn suits-schema) rt-edn (-> (l/pcf suits-schema) (l/json->schema) (l/edn)) expected {:default :hearts :name :deercreeklabs.unit.edn-test/suits :symbols [:hearts :diamonds :spades :clubs] :type :enum}] (is (= expected orig-edn)) (is (= expected rt-edn)))) (deftest test-record-pcf-rt (let [orig-edn (l/edn user-schema) rt-edn (-> (l/pcf user-schema) (l/json->schema) (l/edn)) expected {:fields [{:name :name :default nil :type [:null :string]} {:name :nickname :default nil :type [:null :string]}] :name :deercreeklabs.unit.edn-test/user :type :record}] (is (= expected orig-edn)) (is (= expected rt-edn)))) (deftest test-record-pcf-rt-nested-rec (let [orig-edn (l/edn msg-schema) rt-edn (-> (l/pcf msg-schema) (l/json->schema) (l/edn)) expected {:fields [{:name :user :default nil :type [:null {:fields [{:default nil :name :name :type [:null :string]} {:default nil :name :nickname :type [:null :string]}], :name :deercreeklabs.unit.edn-test/user, :type :record}]} {:name :text :default nil :type [:null :string]}] :name :deercreeklabs.unit.edn-test/msg :type :record}] (is (= expected orig-edn)) (is (= expected rt-edn))))
123572
(ns deercreeklabs.unit.edn-test (:require [clojure.test :refer [are deftest is]] [deercreeklabs.lancaster :as l] [deercreeklabs.unit.lancaster-test :as lt])) (l/def-enum-schema suits-schema :hearts :diamonds :spades :clubs) (l/def-record-schema user-schema [:name l/string-schema] [:nickname l/string-schema]) (l/def-array-schema users-schema user-schema) (l/def-record-schema msg-schema [:user user-schema] [:text l/string-schema]) (deftest test-edn->schema (are [edn] (= edn (-> edn l/edn->schema l/edn)) :string :int [:null :int :string] {:name ::test-fixed :type :fixed :size 16} {:name ::test-enum :type :enum :symbols [:a :b :c]} {:name ::test-rec :type :record :fields [{:name :a :type :int :default -1} {:name :b :type :string :default ""}]}) ) (deftest test-name-kw (let [cases [[l/string-schema :string] [l/int-schema :int] [lt/why-schema :deercreeklabs.unit.lancaster-test/why] [lt/a-fixed-schema :deercreeklabs.unit.lancaster-test/a-fixed] [lt/ages-schema :map] [lt/simple-array-schema :array] [lt/rec-w-array-and-enum-schema :deercreeklabs.unit.lancaster-test/rec-w-array-and-enum] [lt/maybe-int-schema :union]]] (doseq [[sch expected] cases] (let [edn (l/edn sch) ret (l/name-kw sch)] (is (= [edn expected] [edn ret])))))) (deftest test-round-trip-json-schema (let [json-schema (str "{\"type\":\"record\",\"name\":" "\"StringMinimalExample\",\"namespace\":" "\"com.piotr-yuxuan\",\"fields\":[{\"name\":" "\"someOtherField\",\"type\":[\"null\",\"long\"]}," "{\"name\":\"url\",\"type\":{\"type\":\"string\"," "\"avro.java.string\":\"String\"}}]}") schema (l/json->schema json-schema) rt-json-schema (l/json schema)] (is (= json-schema rt-json-schema)))) (deftest test-json-schema-w-evolution-no-default (let [data {:a 1} writer-schema (l/record-schema ::test-rec [[:a l/int-schema]]) reader-json (str "{\"name\":\"deercreeklabs.unit.edn_test.TestRec\"," "\"type\":\"record\",\"fields\":[" "{\"name\":\"a\",\"type\":\"int\"}," "{\"name\":\"b\",\"type\":\"string\"}]}") reader-schema (l/json->schema reader-json) encoded (l/serialize writer-schema data) decoded (l/deserialize reader-schema writer-schema encoded) expected (assoc data :b "")] (is (= expected decoded)))) #?(:clj (deftest test-issue-4 (let [json (slurp "test/example.avsc") schema (l/json->schema json)] (is (= json (l/json schema)))))) (deftest test-enum-pcf-rt (let [orig-edn (l/edn suits-schema) rt-edn (-> (l/pcf suits-schema) (l/json->schema) (l/edn)) expected {:default :hearts :name :deercreeklabs.unit.edn-test/suits :symbols [:hearts :diamonds :spades :clubs] :type :enum}] (is (= expected orig-edn)) (is (= expected rt-edn)))) (deftest test-record-pcf-rt (let [orig-edn (l/edn user-schema) rt-edn (-> (l/pcf user-schema) (l/json->schema) (l/edn)) expected {:fields [{:name :<NAME> :default nil :type [:null :string]} {:name :nickname :default nil :type [:null :string]}] :name :deercreeklabs.unit.edn-test/user :type :record}] (is (= expected orig-edn)) (is (= expected rt-edn)))) (deftest test-record-pcf-rt-nested-rec (let [orig-edn (l/edn msg-schema) rt-edn (-> (l/pcf msg-schema) (l/json->schema) (l/edn)) expected {:fields [{:name :user :default nil :type [:null {:fields [{:default nil :name :<NAME> :type [:null :string]} {:default nil :name :nickname :type [:null :string]}], :name :deercreeklabs.unit.edn-test/user, :type :record}]} {:name :text :default nil :type [:null :string]}] :name :deercreeklabs.unit.edn-test/msg :type :record}] (is (= expected orig-edn)) (is (= expected rt-edn))))
true
(ns deercreeklabs.unit.edn-test (:require [clojure.test :refer [are deftest is]] [deercreeklabs.lancaster :as l] [deercreeklabs.unit.lancaster-test :as lt])) (l/def-enum-schema suits-schema :hearts :diamonds :spades :clubs) (l/def-record-schema user-schema [:name l/string-schema] [:nickname l/string-schema]) (l/def-array-schema users-schema user-schema) (l/def-record-schema msg-schema [:user user-schema] [:text l/string-schema]) (deftest test-edn->schema (are [edn] (= edn (-> edn l/edn->schema l/edn)) :string :int [:null :int :string] {:name ::test-fixed :type :fixed :size 16} {:name ::test-enum :type :enum :symbols [:a :b :c]} {:name ::test-rec :type :record :fields [{:name :a :type :int :default -1} {:name :b :type :string :default ""}]}) ) (deftest test-name-kw (let [cases [[l/string-schema :string] [l/int-schema :int] [lt/why-schema :deercreeklabs.unit.lancaster-test/why] [lt/a-fixed-schema :deercreeklabs.unit.lancaster-test/a-fixed] [lt/ages-schema :map] [lt/simple-array-schema :array] [lt/rec-w-array-and-enum-schema :deercreeklabs.unit.lancaster-test/rec-w-array-and-enum] [lt/maybe-int-schema :union]]] (doseq [[sch expected] cases] (let [edn (l/edn sch) ret (l/name-kw sch)] (is (= [edn expected] [edn ret])))))) (deftest test-round-trip-json-schema (let [json-schema (str "{\"type\":\"record\",\"name\":" "\"StringMinimalExample\",\"namespace\":" "\"com.piotr-yuxuan\",\"fields\":[{\"name\":" "\"someOtherField\",\"type\":[\"null\",\"long\"]}," "{\"name\":\"url\",\"type\":{\"type\":\"string\"," "\"avro.java.string\":\"String\"}}]}") schema (l/json->schema json-schema) rt-json-schema (l/json schema)] (is (= json-schema rt-json-schema)))) (deftest test-json-schema-w-evolution-no-default (let [data {:a 1} writer-schema (l/record-schema ::test-rec [[:a l/int-schema]]) reader-json (str "{\"name\":\"deercreeklabs.unit.edn_test.TestRec\"," "\"type\":\"record\",\"fields\":[" "{\"name\":\"a\",\"type\":\"int\"}," "{\"name\":\"b\",\"type\":\"string\"}]}") reader-schema (l/json->schema reader-json) encoded (l/serialize writer-schema data) decoded (l/deserialize reader-schema writer-schema encoded) expected (assoc data :b "")] (is (= expected decoded)))) #?(:clj (deftest test-issue-4 (let [json (slurp "test/example.avsc") schema (l/json->schema json)] (is (= json (l/json schema)))))) (deftest test-enum-pcf-rt (let [orig-edn (l/edn suits-schema) rt-edn (-> (l/pcf suits-schema) (l/json->schema) (l/edn)) expected {:default :hearts :name :deercreeklabs.unit.edn-test/suits :symbols [:hearts :diamonds :spades :clubs] :type :enum}] (is (= expected orig-edn)) (is (= expected rt-edn)))) (deftest test-record-pcf-rt (let [orig-edn (l/edn user-schema) rt-edn (-> (l/pcf user-schema) (l/json->schema) (l/edn)) expected {:fields [{:name :PI:NAME:<NAME>END_PI :default nil :type [:null :string]} {:name :nickname :default nil :type [:null :string]}] :name :deercreeklabs.unit.edn-test/user :type :record}] (is (= expected orig-edn)) (is (= expected rt-edn)))) (deftest test-record-pcf-rt-nested-rec (let [orig-edn (l/edn msg-schema) rt-edn (-> (l/pcf msg-schema) (l/json->schema) (l/edn)) expected {:fields [{:name :user :default nil :type [:null {:fields [{:default nil :name :PI:NAME:<NAME>END_PI :type [:null :string]} {:default nil :name :nickname :type [:null :string]}], :name :deercreeklabs.unit.edn-test/user, :type :record}]} {:name :text :default nil :type [:null :string]}] :name :deercreeklabs.unit.edn-test/msg :type :record}] (is (= expected orig-edn)) (is (= expected rt-edn))))
[ { "context": "ers\n * non-alphabetic characters\"\n :author \"Paul Landes\"}\n zensols.nlparse.stopword\n (:require [cloju", "end": 422, "score": 0.9998955726623535, "start": 411, "tag": "NAME", "value": "Paul Landes" } ]
src/clojure/zensols/nlparse/stopword.clj
plandes/clj-nlp-parse
33
(ns ^{:doc "This namesapce provides ways of filtering *stop word* tokens. To avoid the double negative in function names, *go words* are defined to be the compliment of a vocabulary with a stop word list. Functions like [[go-word?]] tell whether or not a token is a stop word, which are defined to be: * stopwords (predefined list) * punctuation * numbers * non-alphabetic characters" :author "Paul Landes"} zensols.nlparse.stopword (:require [clojure.string :as s])) (def ^:dynamic *stopword-config* "Configuration for filtering stop words. Keys --- * **:post-tags** POS tags for *go words* (see namespace docs) * **:word-form-fn** function run on the token in [[go-word-form]]; for example if `#(-> % :lemma s/lower-case)` is given then lemmatization is used (i.e. Running -> run)" {:pos-tags #{"RB", "JJ", "JJR", "JJS", "MD", "NN", "NNS", "NNP", "NNPS", "VB", "VBD", "VBG", "VBN", "VBP", "VBZ", "PRP", "PDT", "POS", "RP", "FW"} :word-form-fn #(-> % :text s/lower-case)}) (defn go-word? "Return whether a token is a *go* token." [token] (let [tags (:pos-tags *stopword-config*)] (and (not (:stopword token)) (contains? tags (:pos-tag token))))) (defn go-word-form "Conical string word count form of a token." [token] ((:word-form-fn *stopword-config*) token)) (defn go-word-forms "Filter tokens per [[go-word?]] and return their *form* based on [[go-word-form]]." [tokens] (->> tokens (filter go-word?) (remove nil?) (map go-word-form)))
79117
(ns ^{:doc "This namesapce provides ways of filtering *stop word* tokens. To avoid the double negative in function names, *go words* are defined to be the compliment of a vocabulary with a stop word list. Functions like [[go-word?]] tell whether or not a token is a stop word, which are defined to be: * stopwords (predefined list) * punctuation * numbers * non-alphabetic characters" :author "<NAME>"} zensols.nlparse.stopword (:require [clojure.string :as s])) (def ^:dynamic *stopword-config* "Configuration for filtering stop words. Keys --- * **:post-tags** POS tags for *go words* (see namespace docs) * **:word-form-fn** function run on the token in [[go-word-form]]; for example if `#(-> % :lemma s/lower-case)` is given then lemmatization is used (i.e. Running -> run)" {:pos-tags #{"RB", "JJ", "JJR", "JJS", "MD", "NN", "NNS", "NNP", "NNPS", "VB", "VBD", "VBG", "VBN", "VBP", "VBZ", "PRP", "PDT", "POS", "RP", "FW"} :word-form-fn #(-> % :text s/lower-case)}) (defn go-word? "Return whether a token is a *go* token." [token] (let [tags (:pos-tags *stopword-config*)] (and (not (:stopword token)) (contains? tags (:pos-tag token))))) (defn go-word-form "Conical string word count form of a token." [token] ((:word-form-fn *stopword-config*) token)) (defn go-word-forms "Filter tokens per [[go-word?]] and return their *form* based on [[go-word-form]]." [tokens] (->> tokens (filter go-word?) (remove nil?) (map go-word-form)))
true
(ns ^{:doc "This namesapce provides ways of filtering *stop word* tokens. To avoid the double negative in function names, *go words* are defined to be the compliment of a vocabulary with a stop word list. Functions like [[go-word?]] tell whether or not a token is a stop word, which are defined to be: * stopwords (predefined list) * punctuation * numbers * non-alphabetic characters" :author "PI:NAME:<NAME>END_PI"} zensols.nlparse.stopword (:require [clojure.string :as s])) (def ^:dynamic *stopword-config* "Configuration for filtering stop words. Keys --- * **:post-tags** POS tags for *go words* (see namespace docs) * **:word-form-fn** function run on the token in [[go-word-form]]; for example if `#(-> % :lemma s/lower-case)` is given then lemmatization is used (i.e. Running -> run)" {:pos-tags #{"RB", "JJ", "JJR", "JJS", "MD", "NN", "NNS", "NNP", "NNPS", "VB", "VBD", "VBG", "VBN", "VBP", "VBZ", "PRP", "PDT", "POS", "RP", "FW"} :word-form-fn #(-> % :text s/lower-case)}) (defn go-word? "Return whether a token is a *go* token." [token] (let [tags (:pos-tags *stopword-config*)] (and (not (:stopword token)) (contains? tags (:pos-tag token))))) (defn go-word-form "Conical string word count form of a token." [token] ((:word-form-fn *stopword-config*) token)) (defn go-word-forms "Filter tokens per [[go-word?]] and return their *form* based on [[go-word-form]]." [tokens] (->> tokens (filter go-word?) (remove nil?) (map go-word-form)))
[ { "context": "ucting programs using only pure functions\")\n (m \" Paul Chiusano, Runar Bjarnason: Functional Programming in Scala", "end": 808, "score": 0.9998985528945923, "start": 795, "tag": "NAME", "value": "Paul Chiusano" }, { "context": " using only pure functions\")\n (m \" Paul Chiusano, Runar Bjarnason: Functional Programming in Scala, 1nd, page 1\"))\n", "end": 825, "score": 0.9999054074287415, "start": 810, "tag": "NAME", "value": "Runar Bjarnason" }, { "context": " programming?\")\n (a \"the lambda calculus\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 136\"", "end": 983, "score": 0.9998867511749268, "start": 970, "tag": "NAME", "value": "Michael Fogus" }, { "context": ")\n (a \"the lambda calculus\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 136\"))\n\n(qam\n (q ", "end": 997, "score": 0.9998912215232849, "start": 985, "tag": "NAME", "value": "Chris Houser" }, { "context": ".wikipedia.org/wiki/Higher-order_function\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 140\"", "end": 2961, "score": 0.9998449087142944, "start": 2948, "tag": "NAME", "value": "Michael Fogus" }, { "context": "/wiki/Higher-order_function\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 140\"))\n\n(qam\n (q ", "end": 2975, "score": 0.9998442530632019, "start": 2963, "tag": "NAME", "value": "Chris Houser" }, { "context": "low.com/questions/36636/what-is-a-closure\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.2 On cl", "end": 5995, "score": 0.9998559951782227, "start": 5982, "tag": "NAME", "value": "Michael Fogus" }, { "context": "ons/36636/what-is-a-closure\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.2 On closures, page 1", "end": 6009, "score": 0.999852180480957, "start": 5997, "tag": "NAME", "value": "Chris Houser" }, { "context": "rying in Clojure is the partial function.\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 139\"", "end": 8716, "score": 0.999882161617279, "start": 8703, "tag": "NAME", "value": "Michael Fogus" }, { "context": "re is the partial function.\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 139\")\n (m \"https:", "end": 8730, "score": 0.9998521208763123, "start": 8718, "tag": "NAME", "value": "Chris Houser" }, { "context": "of arguments - only then does it evaluate\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 139\"", "end": 9305, "score": 0.9998905658721924, "start": 9292, "tag": "NAME", "value": "Michael Fogus" }, { "context": " only then does it evaluate\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 139\"))\n\n(qam\n (q ", "end": 9319, "score": 0.9998394846916199, "start": 9307, "tag": "NAME", "value": "Chris Houser" }, { "context": "er pattern\")\n (a \"2. by callback pattern\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 140\"", "end": 9502, "score": 0.9998797178268433, "start": 9489, "tag": "NAME", "value": "Michael Fogus" }, { "context": " (a \"2. by callback pattern\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 140\"))\n\n(qam\n (q ", "end": 9516, "score": 0.9998366236686707, "start": 9504, "tag": "NAME", "value": "Chris Houser" }, { "context": "doesn't cause any observable side effects\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 144\"", "end": 9746, "score": 0.9998838901519775, "start": 9733, "tag": "NAME", "value": "Michael Fogus" }, { "context": "any observable side effects\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 144\")\n (m \"https:", "end": 9760, "score": 0.9998431205749512, "start": 9748, "tag": "NAME", "value": "Chris Houser" }, { "context": "a \"2. optimization\")\n (a \"3. testability\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 144\"", "end": 10015, "score": 0.9998824000358582, "start": 10002, "tag": "NAME", "value": "Michael Fogus" }, { "context": "tion\")\n (a \"3. testability\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 144\"))\n\n(qam\n (q ", "end": 10029, "score": 0.99982088804245, "start": 10017, "tag": "NAME", "value": "Chris Houser" }, { "context": "e without changing the program's behavior\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 144\"", "end": 10353, "score": 0.999871015548706, "start": 10340, "tag": "NAME", "value": "Michael Fogus" }, { "context": "ging the program's behavior\")\n (m \"Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 144\")\n (m \"https:", "end": 10367, "score": 0.9998748898506165, "start": 10355, "tag": "NAME", "value": "Chris Houser" } ]
src/test/clojure/pl/tomaszgigiel/quizzes/packs/functional_programming_test.clj
tomaszgigiel/quizzes
1
(ns pl.tomaszgigiel.quizzes.packs.functional-programming-test (:require [clojure.test :as tst]) (:require [pl.tomaszgigiel.quizzes.test-config :as test-config]) (:require [pl.tomaszgigiel.quizzes.quiz :refer [qam q a m]]) (:require [pl.tomaszgigiel.utils.misc :as misc])) (tst/use-fixtures :once test-config/once-fixture) (tst/use-fixtures :each test-config/each-fixture) (qam (q "What is a programming paradigm?") (a "a way to classify programming languages based on their features") (a "an approach to computer programming") (a "a style of building the computer programs") (m "https://en.wikipedia.org/wiki/Programming_paradigm")) (qam (q "What is a functional programming?") (a "a programming paradigm") (a "constructing programs using only pure functions") (m " Paul Chiusano, Runar Bjarnason: Functional Programming in Scala, 1nd, page 1")) (qam (q "What is at the core of functional programming?") (a "the lambda calculus") (m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 136")) (qam (q "What is the lambda calculus?") (a "1. also written as λ-calculus") (a "2. a formal system in mathematical logic") (a "3. for expressing computation") (a "4. based on function abstraction and application") (a "5. using variable binding and substitution") (a "6. is Turing complete") (m "https://en.wikipedia.org/wiki/Lambda_calculus")) (qam (q "What is a first-class citizen?") (a "an entity which supports all the operations generally available to other entities") (m "https://en.wikipedia.org/wiki/First-class_citizen")) (qam (q "What can be a first-class citizen?") (a "1. type") (a "2. object") (a "3. entity") (a "4. value") (a "5. function") (m "https://en.wikipedia.org/wiki/First-class_citizen")) (qam (q "What properties does a first-class citizen have?") (q "What operations are available for a first-class citizen?") (a "1. can be passed as an argument") (a "2. can be returned as a result") (a "3. can be assigned to a variable and stored in a data structure") (a "4. can be created and modified at run time") (a "5. can be tested for equality and identity (has an identity)") (a "6. need not be associated with an identifier (e.g. an anonymous function)") (m "https://en.wikipedia.org/wiki/First-class_citizen") (m "https://pl.wikipedia.org/wiki/Typ_pierwszoklasowy") (m "https://en.wikipedia.org/wiki/Anonymous_function")) (qam (q "What is an anonymous function?") (a "also: function literal, lambda abstraction, lambda expression") (a "a function definition that is not bound to an identifier") (m "https://en.wikipedia.org/wiki/Anonymous_function")) (qam (q "What is a higher-order function?") (a "a function that does at least one of the following:") (a "1. takes one or more functions as arguments") (a "2. returns a function as a result") (m "https://en.wikipedia.org/wiki/Higher-order_function") (m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 140")) (qam (q "What is a first-order function?") (a "a function that is not a higher-order function") (m "https://en.wikipedia.org/wiki/Higher-order_function")) (qam (q "What is specific to the functional programming language?") (a " 1. pure functions") (a " 2. first-class functions") (a " 3. higher-order functions") (a " 4. referential transparency") (a " 5. immutability") (a " 6. function composition") (a " 7. typeclasses") (a " 8. lambdas") (a " 9. closures") (a "20. recursion") (a "21. manipulation of lists") (a "22. lazy evaluation") (m "https://en.wikipedia.org/wiki/Functional_programming")) (qam (q "What is a typeclass?") (a "1. a type system construct that supports parametric polymorphism") (a "2. a kind of Java interfaces, only better") (a "3. in Scala typeclasses are defined as traits with a type parameter and functions for the type") (a "4. Clojure is dynamic, so there is no typeclass") (a "5. Clojure supports polymorphism in several ways") (m "https://en.wikipedia.org/wiki/Type_class") (m "https://stackoverflow.com/questions/22040115/what-are-the-reasons-that-protocols-and-multimethods-in-clojure-are-less-powerfu")) (qam (q "What type of polymorphism does Clojure support?") (a "1. ad-hoc polymorphism: multimethods, protocols, function overloading, function overriding") (a "2. parametric polymorphism: HOF") (a "3. inclusive/subtype polymorphism: type coercion, protocols") (a "4. prototype-based polymorphism: custom dynamic OO system, functions inside maps or records, merge") (a "5. inheritance polymorphism: proxy") (a "6. type-based polymorphism: protocols") (m "https://en.wikipedia.org/wiki/Polymorphism_(computer_science)") (m "https://randomseed.pl/pub/poczytaj-mi-clojure/21-polimorfizm/") (m "https://clojure.org/about/runtime_polymorphism") (m "http://clojure-doc.org/articles/language/polymorphism.html") (m "https://stackoverflow.com/questions/13553100/what-is-polymorphism-a-la-carte-and-how-can-i-benefit-from-it") (m "https://stackoverflow.com/questions/5024211/clojure-adding-functions-to-defrecord-without-defining-a-new-protocol")) (qam (q "What is a lambda?") (a "also anonymous function") (a "a function definition that is not bound to an identifier") (m "https://en.wikipedia.org/wiki/Closure_(computer_programming)")) (qam (q "What is a closure?") (a "also lexical closure, function closure") (a "a technique for implementing lexically scoped name binding in a language with first-class functions") (a "a record storing a function together with an environment") (a "a function containing one or more free variables") (a "a function that has access to some variable outside its own scope") (a "a function that has access to locals from the context where it was created") (m "https://en.wikipedia.org/wiki/Closure_(computer_programming)") (m "https://stackoverflow.com/questions/36636/what-is-a-closure") (m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, 7.2 On closures, page 148")) (qam (q "What is a first-class function?") (a "The first-class function is a feature of the programming language.") (a "A programming language is said to have first-class functions if it treats functions as first-class citizens.") (a "The first-class function is a first-class citizen.") (m "https://en.wikipedia.org/wiki/First-class_function")) (qam (q "What is a currying?") (a "the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument") (a "the process of taking a function that accepts n arguments and turning it into n functions that each accepts a single argument") (m "https://en.wikipedia.org/wiki/Currying")) (qam (q "Why use currying?") (q "1. to study functions with multiple arguments in simpler theoretical models which provide only one argument") (q "2. to automatically manage how arguments are passed to functions and exceptions") (q "3. to work with functions that take multiple arguments, and using them in frameworks where functions might take only one argument") (q "4. some programming languages almost always use curried functions to achieve multiple arguments, e.g. all functions in ML and Haskell have exactly one argument") (a "5. allows to effectively get multi-argument functions without actually defining semantics for them or defining semantics for products") (a "6. leads to a simpler language with as much expressiveness as another, more complicated language, and so is desirable") (m "https://softwareengineering.stackexchange.com/questions/185585/what-is-the-advantage-of-currying") (m "https://en.wikipedia.org/wiki/Currying")) (qam (q "What are the benefits of not having automatic currying?") (a "optional arguments with default values") (a "variadic arguments: you can have a single function foo, rather than foo, foo2, foo3") (a "the compiler can catch the fact that was passed too few arguments to a function") (a "manual currying can be more fully featured compared to automatic") (m "https://news.ycombinator.com/item?id=13322402")) (qam (q "Why no automatic currying in clojure?") (a "Clojure does not support automatic currying.") (a "Clojure allows functions with a variable number of arguments, so currying makes little sense.") (a "e.g. how to know whether (+ 3) should return 3, or wait for more arguments?") (a "e.g. in Haskell function + expects exactly two arguments. If called with 0 or 1, it will produce a function that waits for the rest.") (a "The closest thing to currying in Clojure is the partial function.") (m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 139") (m "https://stackoverflow.com/questions/31373507/rich-hickeys-reason-for-not-auto-currying-clojure-functions") (m "https://dragan.rocks/articles/18/Fluokitten-080-Fast-function-currying-in-Clojure")) (qam (q "What is the difference between partial application and currying?") (a "1. a partial function attempts to evaluate whenever it is given another argument") (a "2. a curried function returns another curried function until it receives a predetermined number of arguments - only then does it evaluate") (m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 139")) (qam (q "How to imitate higher-order functions in Java?") (a "1. by subscriber pattern") (a "2. by callback pattern") (m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 140")) (qam (q "What is a pure function?") (a "1. idempotent: always returns the same result, given the same arguments") (a "2. doesn't cause any observable side effects") (m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 144") (m "https://en.wikipedia.org/wiki/Pure_function")) (qam (q "Enumerate the reasons for using pure functions.") (a "1. referential transparency") (a "2. optimization") (a "3. testability") (m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 144")) (qam (q "What is a referential transparency?") (a "also purity") (a "a property of part of computer program") (a "an expression is called referentially transparent if it can be replaced with its corresponding value without changing the program's behavior") (m "Michael Fogus, Chris Houser: The Joy of Clojure, 2nd, page 144") (m "https://en.wikipedia.org/wiki/Referential_transparency") (m "https://stackoverflow.com/questions/4865616/purity-vs-referential-transparency")) (qam (q "What is a side effect?") (a "changing something somewhere") (a "an effect beside returning value") (m "https://en.wikipedia.org/wiki/Side_effect_(computer_science)") (m "https://pl.wikipedia.org/wiki/Skutek_uboczny_(informatyka)")) (qam (q "What is a referential opacity?") (a "An expression that is not referentially transparent is called referentially opaque.") (m "https://en.wikipedia.org/wiki/Referential_transparency")) (qam (q "What is the difference between purity and referential transparency?") (a "purity: idempotent, no side effects") (a "referential transparency: an ability to be replaced")) (qam (q "Can a pure function be not referentially transparent?") (a "no, by definition (idempotent, no side effects)") (a "If all functions involved in the expression are pure functions, then the expression is referentially transparent.") (m "https://en.wikipedia.org/wiki/Referential_transparency")) (qam (q "Can a referentially transparent function be not pure?") (a "to think about") (a "int f() {logToDB(); return 3;}") (a "int f() {logToFile(); return 3;}") (a "not pure") (a "can be replaced") (m "https://en.wikipedia.org/wiki/Referential_transparency")) (qam (q "What is a referential transparency?") (a "no agreement on the definition") (a "the referential transparency is not useful") (a "don't use it") (m "https://stackoverflow.com/questions/4865616/purity-vs-referential-transparency"))
61070
(ns pl.tomaszgigiel.quizzes.packs.functional-programming-test (:require [clojure.test :as tst]) (:require [pl.tomaszgigiel.quizzes.test-config :as test-config]) (:require [pl.tomaszgigiel.quizzes.quiz :refer [qam q a m]]) (:require [pl.tomaszgigiel.utils.misc :as misc])) (tst/use-fixtures :once test-config/once-fixture) (tst/use-fixtures :each test-config/each-fixture) (qam (q "What is a programming paradigm?") (a "a way to classify programming languages based on their features") (a "an approach to computer programming") (a "a style of building the computer programs") (m "https://en.wikipedia.org/wiki/Programming_paradigm")) (qam (q "What is a functional programming?") (a "a programming paradigm") (a "constructing programs using only pure functions") (m " <NAME>, <NAME>: Functional Programming in Scala, 1nd, page 1")) (qam (q "What is at the core of functional programming?") (a "the lambda calculus") (m "<NAME>, <NAME>: The Joy of Clojure, 2nd, page 136")) (qam (q "What is the lambda calculus?") (a "1. also written as λ-calculus") (a "2. a formal system in mathematical logic") (a "3. for expressing computation") (a "4. based on function abstraction and application") (a "5. using variable binding and substitution") (a "6. is Turing complete") (m "https://en.wikipedia.org/wiki/Lambda_calculus")) (qam (q "What is a first-class citizen?") (a "an entity which supports all the operations generally available to other entities") (m "https://en.wikipedia.org/wiki/First-class_citizen")) (qam (q "What can be a first-class citizen?") (a "1. type") (a "2. object") (a "3. entity") (a "4. value") (a "5. function") (m "https://en.wikipedia.org/wiki/First-class_citizen")) (qam (q "What properties does a first-class citizen have?") (q "What operations are available for a first-class citizen?") (a "1. can be passed as an argument") (a "2. can be returned as a result") (a "3. can be assigned to a variable and stored in a data structure") (a "4. can be created and modified at run time") (a "5. can be tested for equality and identity (has an identity)") (a "6. need not be associated with an identifier (e.g. an anonymous function)") (m "https://en.wikipedia.org/wiki/First-class_citizen") (m "https://pl.wikipedia.org/wiki/Typ_pierwszoklasowy") (m "https://en.wikipedia.org/wiki/Anonymous_function")) (qam (q "What is an anonymous function?") (a "also: function literal, lambda abstraction, lambda expression") (a "a function definition that is not bound to an identifier") (m "https://en.wikipedia.org/wiki/Anonymous_function")) (qam (q "What is a higher-order function?") (a "a function that does at least one of the following:") (a "1. takes one or more functions as arguments") (a "2. returns a function as a result") (m "https://en.wikipedia.org/wiki/Higher-order_function") (m "<NAME>, <NAME>: The Joy of Clojure, 2nd, page 140")) (qam (q "What is a first-order function?") (a "a function that is not a higher-order function") (m "https://en.wikipedia.org/wiki/Higher-order_function")) (qam (q "What is specific to the functional programming language?") (a " 1. pure functions") (a " 2. first-class functions") (a " 3. higher-order functions") (a " 4. referential transparency") (a " 5. immutability") (a " 6. function composition") (a " 7. typeclasses") (a " 8. lambdas") (a " 9. closures") (a "20. recursion") (a "21. manipulation of lists") (a "22. lazy evaluation") (m "https://en.wikipedia.org/wiki/Functional_programming")) (qam (q "What is a typeclass?") (a "1. a type system construct that supports parametric polymorphism") (a "2. a kind of Java interfaces, only better") (a "3. in Scala typeclasses are defined as traits with a type parameter and functions for the type") (a "4. Clojure is dynamic, so there is no typeclass") (a "5. Clojure supports polymorphism in several ways") (m "https://en.wikipedia.org/wiki/Type_class") (m "https://stackoverflow.com/questions/22040115/what-are-the-reasons-that-protocols-and-multimethods-in-clojure-are-less-powerfu")) (qam (q "What type of polymorphism does Clojure support?") (a "1. ad-hoc polymorphism: multimethods, protocols, function overloading, function overriding") (a "2. parametric polymorphism: HOF") (a "3. inclusive/subtype polymorphism: type coercion, protocols") (a "4. prototype-based polymorphism: custom dynamic OO system, functions inside maps or records, merge") (a "5. inheritance polymorphism: proxy") (a "6. type-based polymorphism: protocols") (m "https://en.wikipedia.org/wiki/Polymorphism_(computer_science)") (m "https://randomseed.pl/pub/poczytaj-mi-clojure/21-polimorfizm/") (m "https://clojure.org/about/runtime_polymorphism") (m "http://clojure-doc.org/articles/language/polymorphism.html") (m "https://stackoverflow.com/questions/13553100/what-is-polymorphism-a-la-carte-and-how-can-i-benefit-from-it") (m "https://stackoverflow.com/questions/5024211/clojure-adding-functions-to-defrecord-without-defining-a-new-protocol")) (qam (q "What is a lambda?") (a "also anonymous function") (a "a function definition that is not bound to an identifier") (m "https://en.wikipedia.org/wiki/Closure_(computer_programming)")) (qam (q "What is a closure?") (a "also lexical closure, function closure") (a "a technique for implementing lexically scoped name binding in a language with first-class functions") (a "a record storing a function together with an environment") (a "a function containing one or more free variables") (a "a function that has access to some variable outside its own scope") (a "a function that has access to locals from the context where it was created") (m "https://en.wikipedia.org/wiki/Closure_(computer_programming)") (m "https://stackoverflow.com/questions/36636/what-is-a-closure") (m "<NAME>, <NAME>: The Joy of Clojure, 2nd, 7.2 On closures, page 148")) (qam (q "What is a first-class function?") (a "The first-class function is a feature of the programming language.") (a "A programming language is said to have first-class functions if it treats functions as first-class citizens.") (a "The first-class function is a first-class citizen.") (m "https://en.wikipedia.org/wiki/First-class_function")) (qam (q "What is a currying?") (a "the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument") (a "the process of taking a function that accepts n arguments and turning it into n functions that each accepts a single argument") (m "https://en.wikipedia.org/wiki/Currying")) (qam (q "Why use currying?") (q "1. to study functions with multiple arguments in simpler theoretical models which provide only one argument") (q "2. to automatically manage how arguments are passed to functions and exceptions") (q "3. to work with functions that take multiple arguments, and using them in frameworks where functions might take only one argument") (q "4. some programming languages almost always use curried functions to achieve multiple arguments, e.g. all functions in ML and Haskell have exactly one argument") (a "5. allows to effectively get multi-argument functions without actually defining semantics for them or defining semantics for products") (a "6. leads to a simpler language with as much expressiveness as another, more complicated language, and so is desirable") (m "https://softwareengineering.stackexchange.com/questions/185585/what-is-the-advantage-of-currying") (m "https://en.wikipedia.org/wiki/Currying")) (qam (q "What are the benefits of not having automatic currying?") (a "optional arguments with default values") (a "variadic arguments: you can have a single function foo, rather than foo, foo2, foo3") (a "the compiler can catch the fact that was passed too few arguments to a function") (a "manual currying can be more fully featured compared to automatic") (m "https://news.ycombinator.com/item?id=13322402")) (qam (q "Why no automatic currying in clojure?") (a "Clojure does not support automatic currying.") (a "Clojure allows functions with a variable number of arguments, so currying makes little sense.") (a "e.g. how to know whether (+ 3) should return 3, or wait for more arguments?") (a "e.g. in Haskell function + expects exactly two arguments. If called with 0 or 1, it will produce a function that waits for the rest.") (a "The closest thing to currying in Clojure is the partial function.") (m "<NAME>, <NAME>: The Joy of Clojure, 2nd, page 139") (m "https://stackoverflow.com/questions/31373507/rich-hickeys-reason-for-not-auto-currying-clojure-functions") (m "https://dragan.rocks/articles/18/Fluokitten-080-Fast-function-currying-in-Clojure")) (qam (q "What is the difference between partial application and currying?") (a "1. a partial function attempts to evaluate whenever it is given another argument") (a "2. a curried function returns another curried function until it receives a predetermined number of arguments - only then does it evaluate") (m "<NAME>, <NAME>: The Joy of Clojure, 2nd, page 139")) (qam (q "How to imitate higher-order functions in Java?") (a "1. by subscriber pattern") (a "2. by callback pattern") (m "<NAME>, <NAME>: The Joy of Clojure, 2nd, page 140")) (qam (q "What is a pure function?") (a "1. idempotent: always returns the same result, given the same arguments") (a "2. doesn't cause any observable side effects") (m "<NAME>, <NAME>: The Joy of Clojure, 2nd, page 144") (m "https://en.wikipedia.org/wiki/Pure_function")) (qam (q "Enumerate the reasons for using pure functions.") (a "1. referential transparency") (a "2. optimization") (a "3. testability") (m "<NAME>, <NAME>: The Joy of Clojure, 2nd, page 144")) (qam (q "What is a referential transparency?") (a "also purity") (a "a property of part of computer program") (a "an expression is called referentially transparent if it can be replaced with its corresponding value without changing the program's behavior") (m "<NAME>, <NAME>: The Joy of Clojure, 2nd, page 144") (m "https://en.wikipedia.org/wiki/Referential_transparency") (m "https://stackoverflow.com/questions/4865616/purity-vs-referential-transparency")) (qam (q "What is a side effect?") (a "changing something somewhere") (a "an effect beside returning value") (m "https://en.wikipedia.org/wiki/Side_effect_(computer_science)") (m "https://pl.wikipedia.org/wiki/Skutek_uboczny_(informatyka)")) (qam (q "What is a referential opacity?") (a "An expression that is not referentially transparent is called referentially opaque.") (m "https://en.wikipedia.org/wiki/Referential_transparency")) (qam (q "What is the difference between purity and referential transparency?") (a "purity: idempotent, no side effects") (a "referential transparency: an ability to be replaced")) (qam (q "Can a pure function be not referentially transparent?") (a "no, by definition (idempotent, no side effects)") (a "If all functions involved in the expression are pure functions, then the expression is referentially transparent.") (m "https://en.wikipedia.org/wiki/Referential_transparency")) (qam (q "Can a referentially transparent function be not pure?") (a "to think about") (a "int f() {logToDB(); return 3;}") (a "int f() {logToFile(); return 3;}") (a "not pure") (a "can be replaced") (m "https://en.wikipedia.org/wiki/Referential_transparency")) (qam (q "What is a referential transparency?") (a "no agreement on the definition") (a "the referential transparency is not useful") (a "don't use it") (m "https://stackoverflow.com/questions/4865616/purity-vs-referential-transparency"))
true
(ns pl.tomaszgigiel.quizzes.packs.functional-programming-test (:require [clojure.test :as tst]) (:require [pl.tomaszgigiel.quizzes.test-config :as test-config]) (:require [pl.tomaszgigiel.quizzes.quiz :refer [qam q a m]]) (:require [pl.tomaszgigiel.utils.misc :as misc])) (tst/use-fixtures :once test-config/once-fixture) (tst/use-fixtures :each test-config/each-fixture) (qam (q "What is a programming paradigm?") (a "a way to classify programming languages based on their features") (a "an approach to computer programming") (a "a style of building the computer programs") (m "https://en.wikipedia.org/wiki/Programming_paradigm")) (qam (q "What is a functional programming?") (a "a programming paradigm") (a "constructing programs using only pure functions") (m " PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: Functional Programming in Scala, 1nd, page 1")) (qam (q "What is at the core of functional programming?") (a "the lambda calculus") (m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, page 136")) (qam (q "What is the lambda calculus?") (a "1. also written as λ-calculus") (a "2. a formal system in mathematical logic") (a "3. for expressing computation") (a "4. based on function abstraction and application") (a "5. using variable binding and substitution") (a "6. is Turing complete") (m "https://en.wikipedia.org/wiki/Lambda_calculus")) (qam (q "What is a first-class citizen?") (a "an entity which supports all the operations generally available to other entities") (m "https://en.wikipedia.org/wiki/First-class_citizen")) (qam (q "What can be a first-class citizen?") (a "1. type") (a "2. object") (a "3. entity") (a "4. value") (a "5. function") (m "https://en.wikipedia.org/wiki/First-class_citizen")) (qam (q "What properties does a first-class citizen have?") (q "What operations are available for a first-class citizen?") (a "1. can be passed as an argument") (a "2. can be returned as a result") (a "3. can be assigned to a variable and stored in a data structure") (a "4. can be created and modified at run time") (a "5. can be tested for equality and identity (has an identity)") (a "6. need not be associated with an identifier (e.g. an anonymous function)") (m "https://en.wikipedia.org/wiki/First-class_citizen") (m "https://pl.wikipedia.org/wiki/Typ_pierwszoklasowy") (m "https://en.wikipedia.org/wiki/Anonymous_function")) (qam (q "What is an anonymous function?") (a "also: function literal, lambda abstraction, lambda expression") (a "a function definition that is not bound to an identifier") (m "https://en.wikipedia.org/wiki/Anonymous_function")) (qam (q "What is a higher-order function?") (a "a function that does at least one of the following:") (a "1. takes one or more functions as arguments") (a "2. returns a function as a result") (m "https://en.wikipedia.org/wiki/Higher-order_function") (m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, page 140")) (qam (q "What is a first-order function?") (a "a function that is not a higher-order function") (m "https://en.wikipedia.org/wiki/Higher-order_function")) (qam (q "What is specific to the functional programming language?") (a " 1. pure functions") (a " 2. first-class functions") (a " 3. higher-order functions") (a " 4. referential transparency") (a " 5. immutability") (a " 6. function composition") (a " 7. typeclasses") (a " 8. lambdas") (a " 9. closures") (a "20. recursion") (a "21. manipulation of lists") (a "22. lazy evaluation") (m "https://en.wikipedia.org/wiki/Functional_programming")) (qam (q "What is a typeclass?") (a "1. a type system construct that supports parametric polymorphism") (a "2. a kind of Java interfaces, only better") (a "3. in Scala typeclasses are defined as traits with a type parameter and functions for the type") (a "4. Clojure is dynamic, so there is no typeclass") (a "5. Clojure supports polymorphism in several ways") (m "https://en.wikipedia.org/wiki/Type_class") (m "https://stackoverflow.com/questions/22040115/what-are-the-reasons-that-protocols-and-multimethods-in-clojure-are-less-powerfu")) (qam (q "What type of polymorphism does Clojure support?") (a "1. ad-hoc polymorphism: multimethods, protocols, function overloading, function overriding") (a "2. parametric polymorphism: HOF") (a "3. inclusive/subtype polymorphism: type coercion, protocols") (a "4. prototype-based polymorphism: custom dynamic OO system, functions inside maps or records, merge") (a "5. inheritance polymorphism: proxy") (a "6. type-based polymorphism: protocols") (m "https://en.wikipedia.org/wiki/Polymorphism_(computer_science)") (m "https://randomseed.pl/pub/poczytaj-mi-clojure/21-polimorfizm/") (m "https://clojure.org/about/runtime_polymorphism") (m "http://clojure-doc.org/articles/language/polymorphism.html") (m "https://stackoverflow.com/questions/13553100/what-is-polymorphism-a-la-carte-and-how-can-i-benefit-from-it") (m "https://stackoverflow.com/questions/5024211/clojure-adding-functions-to-defrecord-without-defining-a-new-protocol")) (qam (q "What is a lambda?") (a "also anonymous function") (a "a function definition that is not bound to an identifier") (m "https://en.wikipedia.org/wiki/Closure_(computer_programming)")) (qam (q "What is a closure?") (a "also lexical closure, function closure") (a "a technique for implementing lexically scoped name binding in a language with first-class functions") (a "a record storing a function together with an environment") (a "a function containing one or more free variables") (a "a function that has access to some variable outside its own scope") (a "a function that has access to locals from the context where it was created") (m "https://en.wikipedia.org/wiki/Closure_(computer_programming)") (m "https://stackoverflow.com/questions/36636/what-is-a-closure") (m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, 7.2 On closures, page 148")) (qam (q "What is a first-class function?") (a "The first-class function is a feature of the programming language.") (a "A programming language is said to have first-class functions if it treats functions as first-class citizens.") (a "The first-class function is a first-class citizen.") (m "https://en.wikipedia.org/wiki/First-class_function")) (qam (q "What is a currying?") (a "the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument") (a "the process of taking a function that accepts n arguments and turning it into n functions that each accepts a single argument") (m "https://en.wikipedia.org/wiki/Currying")) (qam (q "Why use currying?") (q "1. to study functions with multiple arguments in simpler theoretical models which provide only one argument") (q "2. to automatically manage how arguments are passed to functions and exceptions") (q "3. to work with functions that take multiple arguments, and using them in frameworks where functions might take only one argument") (q "4. some programming languages almost always use curried functions to achieve multiple arguments, e.g. all functions in ML and Haskell have exactly one argument") (a "5. allows to effectively get multi-argument functions without actually defining semantics for them or defining semantics for products") (a "6. leads to a simpler language with as much expressiveness as another, more complicated language, and so is desirable") (m "https://softwareengineering.stackexchange.com/questions/185585/what-is-the-advantage-of-currying") (m "https://en.wikipedia.org/wiki/Currying")) (qam (q "What are the benefits of not having automatic currying?") (a "optional arguments with default values") (a "variadic arguments: you can have a single function foo, rather than foo, foo2, foo3") (a "the compiler can catch the fact that was passed too few arguments to a function") (a "manual currying can be more fully featured compared to automatic") (m "https://news.ycombinator.com/item?id=13322402")) (qam (q "Why no automatic currying in clojure?") (a "Clojure does not support automatic currying.") (a "Clojure allows functions with a variable number of arguments, so currying makes little sense.") (a "e.g. how to know whether (+ 3) should return 3, or wait for more arguments?") (a "e.g. in Haskell function + expects exactly two arguments. If called with 0 or 1, it will produce a function that waits for the rest.") (a "The closest thing to currying in Clojure is the partial function.") (m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, page 139") (m "https://stackoverflow.com/questions/31373507/rich-hickeys-reason-for-not-auto-currying-clojure-functions") (m "https://dragan.rocks/articles/18/Fluokitten-080-Fast-function-currying-in-Clojure")) (qam (q "What is the difference between partial application and currying?") (a "1. a partial function attempts to evaluate whenever it is given another argument") (a "2. a curried function returns another curried function until it receives a predetermined number of arguments - only then does it evaluate") (m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, page 139")) (qam (q "How to imitate higher-order functions in Java?") (a "1. by subscriber pattern") (a "2. by callback pattern") (m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, page 140")) (qam (q "What is a pure function?") (a "1. idempotent: always returns the same result, given the same arguments") (a "2. doesn't cause any observable side effects") (m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, page 144") (m "https://en.wikipedia.org/wiki/Pure_function")) (qam (q "Enumerate the reasons for using pure functions.") (a "1. referential transparency") (a "2. optimization") (a "3. testability") (m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, page 144")) (qam (q "What is a referential transparency?") (a "also purity") (a "a property of part of computer program") (a "an expression is called referentially transparent if it can be replaced with its corresponding value without changing the program's behavior") (m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: The Joy of Clojure, 2nd, page 144") (m "https://en.wikipedia.org/wiki/Referential_transparency") (m "https://stackoverflow.com/questions/4865616/purity-vs-referential-transparency")) (qam (q "What is a side effect?") (a "changing something somewhere") (a "an effect beside returning value") (m "https://en.wikipedia.org/wiki/Side_effect_(computer_science)") (m "https://pl.wikipedia.org/wiki/Skutek_uboczny_(informatyka)")) (qam (q "What is a referential opacity?") (a "An expression that is not referentially transparent is called referentially opaque.") (m "https://en.wikipedia.org/wiki/Referential_transparency")) (qam (q "What is the difference between purity and referential transparency?") (a "purity: idempotent, no side effects") (a "referential transparency: an ability to be replaced")) (qam (q "Can a pure function be not referentially transparent?") (a "no, by definition (idempotent, no side effects)") (a "If all functions involved in the expression are pure functions, then the expression is referentially transparent.") (m "https://en.wikipedia.org/wiki/Referential_transparency")) (qam (q "Can a referentially transparent function be not pure?") (a "to think about") (a "int f() {logToDB(); return 3;}") (a "int f() {logToFile(); return 3;}") (a "not pure") (a "can be replaced") (m "https://en.wikipedia.org/wiki/Referential_transparency")) (qam (q "What is a referential transparency?") (a "no agreement on the definition") (a "the referential transparency is not useful") (a "don't use it") (m "https://stackoverflow.com/questions/4865616/purity-vs-referential-transparency"))
[ { "context": "interfaces {\n ethernet eth0 {\n address 172.16.16.2/24\n duplex auto\n hw-id 50:00:00:01:", "end": 60, "score": 0.9996985793113708, "start": 49, "tag": "IP_ADDRESS", "value": "172.16.16.2" }, { "context": " eth3 {\n duplex auto\n hw-id 50:00:00:01:00:03\n smp_affinity auto\n speed a", "end": 475, "score": 0.5151477456092834, "start": 475, "tag": "IP_ADDRESS", "value": "" }, { "context": "\n }\n}\nprotocols {\n bgp 2 {\n neighbor 172.16.16.1 {\n remote-as 1\n }\n }\n}\nsyste", "end": 614, "score": 0.9997110366821289, "start": 603, "tag": "IP_ADDRESS", "value": "172.16.16.1" }, { "context": " }\n host-name Router02\n login {\n user vyos {\n authentication {\n en", "end": 854, "score": 0.999686598777771, "start": 850, "tag": "USERNAME", "value": "vyos" }, { "context": "uthentication {\n encrypted-password $1$rgSzwnQx$L0KYH5pYbB.u32LKZWg.d1\n plaintext-password \"\"\n ", "end": 955, "score": 0.9994009733200073, "start": 921, "tag": "PASSWORD", "value": "$1$rgSzwnQx$L0KYH5pYbB.u32LKZWg.d1" } ]
backup/vyos_bgp_sessions.unl/Router02/config.boot
Fireman730/python-eveng-api
0
interfaces { ethernet eth0 { address 172.16.16.2/24 duplex auto hw-id 50:00:00:01:00:00 smp_affinity auto speed auto } ethernet eth1 { duplex auto hw-id 50:00:00:01:00:01 smp_affinity auto speed auto } ethernet eth2 { duplex auto hw-id 50:00:00:01:00:02 smp_affinity auto speed auto } ethernet eth3 { duplex auto hw-id 50:00:00:01:00:03 smp_affinity auto speed auto } loopback lo { } } protocols { bgp 2 { neighbor 172.16.16.1 { remote-as 1 } } } system { config-management { commit-revisions 20 } console { device ttyS0 { speed 9600 } } host-name Router02 login { user vyos { authentication { encrypted-password $1$rgSzwnQx$L0KYH5pYbB.u32LKZWg.d1 plaintext-password "" } level admin } } ntp { server 0.pool.ntp.org { } server 1.pool.ntp.org { } server 2.pool.ntp.org { } } package { auto-sync 1 repository community { components main distribution helium password "" url http://packages.vyos.net/vyos username "" } } syslog { global { facility all { level notice } facility protocols { level debug } } } time-zone UTC } /* Warning: Do not remove the following line. */ /* === vyatta-config-version: "system@6:firewall@5:ipsec@4:qos@1:conntrack-sync@1:dhcp-relay@1:nat@4:conntrack@1:config-management@1:vrrp@1:wanloadbalance@3:cluster@1:webproxy@1:quagga@2:dhcp-server@4:cron@1:zone-policy@1:webgui@1" === */ /* Release version: VyOS 1.1.8 */
32334
interfaces { ethernet eth0 { address 172.16.16.2/24 duplex auto hw-id 50:00:00:01:00:00 smp_affinity auto speed auto } ethernet eth1 { duplex auto hw-id 50:00:00:01:00:01 smp_affinity auto speed auto } ethernet eth2 { duplex auto hw-id 50:00:00:01:00:02 smp_affinity auto speed auto } ethernet eth3 { duplex auto hw-id 50:00:00:01:00:03 smp_affinity auto speed auto } loopback lo { } } protocols { bgp 2 { neighbor 172.16.16.1 { remote-as 1 } } } system { config-management { commit-revisions 20 } console { device ttyS0 { speed 9600 } } host-name Router02 login { user vyos { authentication { encrypted-password <PASSWORD> plaintext-password "" } level admin } } ntp { server 0.pool.ntp.org { } server 1.pool.ntp.org { } server 2.pool.ntp.org { } } package { auto-sync 1 repository community { components main distribution helium password "" url http://packages.vyos.net/vyos username "" } } syslog { global { facility all { level notice } facility protocols { level debug } } } time-zone UTC } /* Warning: Do not remove the following line. */ /* === vyatta-config-version: "system@6:firewall@5:ipsec@4:qos@1:conntrack-sync@1:dhcp-relay@1:nat@4:conntrack@1:config-management@1:vrrp@1:wanloadbalance@3:cluster@1:webproxy@1:quagga@2:dhcp-server@4:cron@1:zone-policy@1:webgui@1" === */ /* Release version: VyOS 1.1.8 */
true
interfaces { ethernet eth0 { address 172.16.16.2/24 duplex auto hw-id 50:00:00:01:00:00 smp_affinity auto speed auto } ethernet eth1 { duplex auto hw-id 50:00:00:01:00:01 smp_affinity auto speed auto } ethernet eth2 { duplex auto hw-id 50:00:00:01:00:02 smp_affinity auto speed auto } ethernet eth3 { duplex auto hw-id 50:00:00:01:00:03 smp_affinity auto speed auto } loopback lo { } } protocols { bgp 2 { neighbor 172.16.16.1 { remote-as 1 } } } system { config-management { commit-revisions 20 } console { device ttyS0 { speed 9600 } } host-name Router02 login { user vyos { authentication { encrypted-password PI:PASSWORD:<PASSWORD>END_PI plaintext-password "" } level admin } } ntp { server 0.pool.ntp.org { } server 1.pool.ntp.org { } server 2.pool.ntp.org { } } package { auto-sync 1 repository community { components main distribution helium password "" url http://packages.vyos.net/vyos username "" } } syslog { global { facility all { level notice } facility protocols { level debug } } } time-zone UTC } /* Warning: Do not remove the following line. */ /* === vyatta-config-version: "system@6:firewall@5:ipsec@4:qos@1:conntrack-sync@1:dhcp-relay@1:nat@4:conntrack@1:config-management@1:vrrp@1:wanloadbalance@3:cluster@1:webproxy@1:quagga@2:dhcp-server@4:cron@1:zone-policy@1:webgui@1" === */ /* Release version: VyOS 1.1.8 */
[ { "context": "images\n \n {:doc \"find image files.\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"2018-01-06\"}\n \n (:require [clojur", "end": 272, "score": 0.9834737777709961, "start": 236, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/scripts/clojure/palisades/lakes/curate/scripts/images.clj
palisades-lakes/curate
0
IMG_0227.JPG(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.curate.scripts.images {:doc "find image files." :author "palisades dot lakes at gmail dot com" :version "2018-01-06"} (:require [clojure.java.io :as io] [clojure.pprint :as pp] [palisades.lakes.curate.curate :as curate])) ;;---------------------------------------------------------------- (let [d (io/file "s:/" "porta" #_"Pictures") filetypes (into (sorted-set) (map curate/file-type) (file-seq d))] (pp/pprint filetypes) (pp/pprint (remove curate/image-file-type? filetypes)) (pp/pprint (filter curate/image-file-type? filetypes))) #_(let [d (io/file "e:/" "porta" #_"Pictures")] (pp/pprint (into (sorted-set) (map curate/file-type) (curate/image-file-seq d)))) ;;----------------------------------------------------------------
43802
IMG_0227.JPG(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.curate.scripts.images {:doc "find image files." :author "<EMAIL>" :version "2018-01-06"} (:require [clojure.java.io :as io] [clojure.pprint :as pp] [palisades.lakes.curate.curate :as curate])) ;;---------------------------------------------------------------- (let [d (io/file "s:/" "porta" #_"Pictures") filetypes (into (sorted-set) (map curate/file-type) (file-seq d))] (pp/pprint filetypes) (pp/pprint (remove curate/image-file-type? filetypes)) (pp/pprint (filter curate/image-file-type? filetypes))) #_(let [d (io/file "e:/" "porta" #_"Pictures")] (pp/pprint (into (sorted-set) (map curate/file-type) (curate/image-file-seq d)))) ;;----------------------------------------------------------------
true
IMG_0227.JPG(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.curate.scripts.images {:doc "find image files." :author "PI:EMAIL:<EMAIL>END_PI" :version "2018-01-06"} (:require [clojure.java.io :as io] [clojure.pprint :as pp] [palisades.lakes.curate.curate :as curate])) ;;---------------------------------------------------------------- (let [d (io/file "s:/" "porta" #_"Pictures") filetypes (into (sorted-set) (map curate/file-type) (file-seq d))] (pp/pprint filetypes) (pp/pprint (remove curate/image-file-type? filetypes)) (pp/pprint (filter curate/image-file-type? filetypes))) #_(let [d (io/file "e:/" "porta" #_"Pictures")] (pp/pprint (into (sorted-set) (map curate/file-type) (curate/image-file-seq d)))) ;;----------------------------------------------------------------
[ { "context": "; Copyright (C) 2014 Joseph Fosco. All Rights Reserved\n;\n; This program is free ", "end": 37, "score": 0.9998489618301392, "start": 25, "tag": "NAME", "value": "Joseph Fosco" } ]
data/train/clojure/4b7a9dd77b4050e3786dcb94cc11ec362d515249instrumentinfo.clj
harshp8l/deep-learning-lang-detection
84
; Copyright (C) 2014 Joseph Fosco. All Rights Reserved ; ; This program is free software: you can redistribute it and/or modify ; it under the terms of the GNU General Public License as published by ; the Free Software Foundation, either version 3 of the License, or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; ; You should have received a copy of the GNU General Public License ; along with this program. If not, see <http://www.gnu.org/licenses/>. (ns transport.instrumentinfo) (defrecord InstrumentInfo [instrument envelope-type release-dur range-hi range-lo]) (defn create-instrument-info "Used to create an InstrumentInfo record" [& {:keys [instrument envelope-type release-dur range-hi range-lo]}] (InstrumentInfo. instrument envelope-type release-dur range-hi range-lo ) ) (defn get-instrument-for-inst-info [inst-info] (:instrument inst-info)) (defn get-envelope-type-for-inst-info [inst-info] (:envelope-type inst-info)) (defn get-release-dur-for-inst-info [inst-info] (:release-dur inst-info)) (defn get-release-millis-for-inst-info [inst-info] (let [release-dur (:release-dur inst-info)] (if release-dur (int (* (:release-dur inst-info) 1000)) 0 )) ) (defn get-range-hi-for-inst-info [inst-info] (:range-hi inst-info)) (defn get-range-lo-for-inst-info [inst-info] (:range-lo inst-info)) (defn get-all-instrument-info [inst-info] {:envelope-type (:envelope-type inst-info) :release-dur (:release-dur inst-info) :range-hi (:range-hi inst-info) :range-lo (:range-lo inst-info) :instrument (:instrument inst-info)} )
35641
; Copyright (C) 2014 <NAME>. All Rights Reserved ; ; This program is free software: you can redistribute it and/or modify ; it under the terms of the GNU General Public License as published by ; the Free Software Foundation, either version 3 of the License, or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; ; You should have received a copy of the GNU General Public License ; along with this program. If not, see <http://www.gnu.org/licenses/>. (ns transport.instrumentinfo) (defrecord InstrumentInfo [instrument envelope-type release-dur range-hi range-lo]) (defn create-instrument-info "Used to create an InstrumentInfo record" [& {:keys [instrument envelope-type release-dur range-hi range-lo]}] (InstrumentInfo. instrument envelope-type release-dur range-hi range-lo ) ) (defn get-instrument-for-inst-info [inst-info] (:instrument inst-info)) (defn get-envelope-type-for-inst-info [inst-info] (:envelope-type inst-info)) (defn get-release-dur-for-inst-info [inst-info] (:release-dur inst-info)) (defn get-release-millis-for-inst-info [inst-info] (let [release-dur (:release-dur inst-info)] (if release-dur (int (* (:release-dur inst-info) 1000)) 0 )) ) (defn get-range-hi-for-inst-info [inst-info] (:range-hi inst-info)) (defn get-range-lo-for-inst-info [inst-info] (:range-lo inst-info)) (defn get-all-instrument-info [inst-info] {:envelope-type (:envelope-type inst-info) :release-dur (:release-dur inst-info) :range-hi (:range-hi inst-info) :range-lo (:range-lo inst-info) :instrument (:instrument inst-info)} )
true
; Copyright (C) 2014 PI:NAME:<NAME>END_PI. All Rights Reserved ; ; This program is free software: you can redistribute it and/or modify ; it under the terms of the GNU General Public License as published by ; the Free Software Foundation, either version 3 of the License, or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; ; You should have received a copy of the GNU General Public License ; along with this program. If not, see <http://www.gnu.org/licenses/>. (ns transport.instrumentinfo) (defrecord InstrumentInfo [instrument envelope-type release-dur range-hi range-lo]) (defn create-instrument-info "Used to create an InstrumentInfo record" [& {:keys [instrument envelope-type release-dur range-hi range-lo]}] (InstrumentInfo. instrument envelope-type release-dur range-hi range-lo ) ) (defn get-instrument-for-inst-info [inst-info] (:instrument inst-info)) (defn get-envelope-type-for-inst-info [inst-info] (:envelope-type inst-info)) (defn get-release-dur-for-inst-info [inst-info] (:release-dur inst-info)) (defn get-release-millis-for-inst-info [inst-info] (let [release-dur (:release-dur inst-info)] (if release-dur (int (* (:release-dur inst-info) 1000)) 0 )) ) (defn get-range-hi-for-inst-info [inst-info] (:range-hi inst-info)) (defn get-range-lo-for-inst-info [inst-info] (:range-lo inst-info)) (defn get-all-instrument-info [inst-info] {:envelope-type (:envelope-type inst-info) :release-dur (:release-dur inst-info) :range-hi (:range-hi inst-info) :range-lo (:range-lo inst-info) :instrument (:instrument inst-info)} )
[ { "context": "}\n {:tag :author :attributes {} :content [\"John McCarthy\"]}]}]}]})\n\n(deftest helpers-access\n (testing \"He", "end": 1788, "score": 0.9998271465301514, "start": 1775, "tag": "NAME", "value": "John McCarthy" }, { "context": " {:tag :author :attributes {} :content [\"John McCarthy\"]}))\n (is (= (helpers/find-first testing-data ", "end": 3042, "score": 0.9998461008071899, "start": 3029, "tag": "NAME", "value": "John McCarthy" }, { "context": " '({:tag :author :attributes {} :content [\"John McCarthy\"]})))\n (is (= (helpers/find-all testing-data {", "end": 6082, "score": 0.9997622966766357, "start": 6069, "tag": "NAME", "value": "John McCarthy" } ]
test/tubax/tests/helpers_test.cljs
Alotor/cljs-xml
21
(ns tubax.helpers-test (:require [tubax.helpers :as helpers] [cljs.test :as test :refer-macros [deftest is testing]])) (def testing-data {:tag :rss :attributes {:version "2.0"} :content [{:tag :channel :attributes {} :content [{:tag :title :attributes {} :content ["RSS Title"]} {:tag :description :attributes {} :content ["This is an example of an RSS feed"]} {:tag :link :attributes {} :content ["http://www.example.com/main.html"]} {:tag :lastBuildDate :attributes {} :content ["Mon, 06 Sep 2010 00:01:00 +0000"]} {:tag :pubDate :attributes {} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]} {:tag :ttl :attributes {} :content ["1800"]} {:tag :item :attributes {} :content [{:tag :title :attributes {} :content ["Example entry"]} {:tag :description :attributes {} :content ["Here is some text containing an interesting description."]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/1"]} {:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]} {:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]}]} {:tag :item :attributes {} :content [{:tag :title :attributes {} :content ["Example entry2"]} {:tag :description :attributes {} :content ["Here is some text containing an interesting description."]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/2"]} {:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]} {:tag :pubDate :attributes {:year "2009"} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]} {:tag :author :attributes {} :content ["John McCarthy"]}]}]}]}) (deftest helpers-access (testing "Helpers access" (let [node {:tag :item :attributes {:att1 "att"} :content ["value"]}] (is (= (helpers/tag node) :item)) (is (= (helpers/attributes node) {:att1 "att"})) (is (= (helpers/children node) ["value"])) (is (= (helpers/text node) "value")))) (testing "Unexpected values" (is (= (helpers/text {:tag :item :attributes {} :content [{:tag :itemb :attributes {} :content ["value"]}]}) nil))) (testing "Check if node" (is (= (helpers/is-node {:tag :item :attributes {} :content []}) true)) (is (= (helpers/is-node "test") false)) (is (= (helpers/is-node {:tag :item :content []}) false)) (is (= (helpers/is-node [:tag "test" :attributes {} :content []]) false)))) (deftest find-first (testing "Find first tag" (is (= (helpers/find-first testing-data {:tag :link}) {:tag :link :attributes {} :content ["http://www.example.com/main.html"]})) (is (= (helpers/find-first testing-data {:tag :guid}) {:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]})) (is (= (helpers/find-first testing-data {:tag :author}) {:tag :author :attributes {} :content ["John McCarthy"]})) (is (= (helpers/find-first testing-data {:tag :no-tag}) nil))) (testing "Find first path" (is (= (helpers/find-first testing-data {:path [:rss :channel :ttl]}) {:tag :ttl :attributes {} :content ["1800"]})) (is (= (helpers/find-first testing-data {:path [:rss :channel :item :link]}) {:tag :link :attributes {} :content ["http://www.example.com/blog/post/1"]})) (is (= (helpers/find-first testing-data {:path [:rss :channel :item :notexists]}) nil)) (is (= (helpers/find-first testing-data {:path nil}) nil)) (is (= (helpers/find-first testing-data {:path []}) nil)) (is (= (helpers/find-first testing-data {:path [:badroot]}) nil))) (testing "Find first keyword" (is (= (helpers/find-first testing-data {:attribute :isPermaLink}) {:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]})) (is (= (helpers/find-first testing-data {:attribute :year}) {:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]})) (is (= (helpers/find-first testing-data {:attribute :not-existing}) nil))) (testing "Find first keyword equality" (is (= (helpers/find-first testing-data {:attribute [:isPermaLink "false"]}) {:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]})) (is (= (helpers/find-first testing-data {:attribute [:isPermaLink "true"]}) {:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]})) (is (= (helpers/find-first testing-data {:attribute [:year "2013"]}) {:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]})) (is (= (helpers/find-first testing-data {:attribute [:year "2009"]}) {:tag :pubDate :attributes {:year "2009"} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]})) (is (= (helpers/find-first testing-data {:attribute [:year "2010"]}) nil)) (is (= (helpers/find-first testing-data {:attribute [:not-existing true]}) nil)) (is (= (helpers/find-first testing-data {:attribute [:shouldfail]}) nil)))) (deftest find-all (testing "Find all by tag" (is (= (helpers/find-all testing-data {:tag :link}) '({:tag :link :attributes {} :content ["http://www.example.com/main.html"]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/1"]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/2"]}))) (is (= (helpers/find-all testing-data {:tag :guid}) '({:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]} {:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]}))) (is (= (helpers/find-all testing-data {:tag :author}) '({:tag :author :attributes {} :content ["John McCarthy"]}))) (is (= (helpers/find-all testing-data {:tag :no-tag}) '()))) (testing "Find first path" (is (= (helpers/find-all testing-data {:path [:rss :channel :ttl]}) '({:tag :ttl :attributes {} :content ["1800"]}))) (is (= (helpers/find-all testing-data {:path [:rss :channel :item :link]}) '({:tag :link :attributes {} :content ["http://www.example.com/blog/post/1"]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/2"]}))) (is (= (helpers/find-all testing-data {:path [:rss :channel :item :notexists]}) '())) (is (= (helpers/find-all testing-data {:path nil}) '())) (is (= (helpers/find-all testing-data {:path []}) '())) (is (= (helpers/find-all testing-data {:path [:badroot]}) '())) ) (testing "Find all keyword" (is (= (helpers/find-all testing-data {:attribute :isPermaLink}) '({:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]} {:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]}))) (is (= (helpers/find-all testing-data {:attribute :year}) '({:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]} {:tag :pubDate :attributes {:year "2009"} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]}))) (is (= (helpers/find-all testing-data {:attribute :not-existing}) '()))) (testing "Find all keyword equality" (is (= (helpers/find-all testing-data {:attribute [:isPermaLink "false"]}) '({:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]}))) (is (= (helpers/find-all testing-data {:attribute [:isPermaLink "true"]}) '({:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]}))) (is (= (helpers/find-all testing-data {:attribute [:year "2013"]}) '({:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]}))) (is (= (helpers/find-all testing-data {:attribute [:year "2009"]}) '({:tag :pubDate :attributes {:year "2009"} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]}))) (is (= (helpers/find-all testing-data {:attribute [:year "2010"]}) '())) (is (= (helpers/find-all testing-data {:attribute [:not-existing true]}) '())) (is (= (helpers/find-all testing-data {:attribute [:shouldfail]}) '()))))
110845
(ns tubax.helpers-test (:require [tubax.helpers :as helpers] [cljs.test :as test :refer-macros [deftest is testing]])) (def testing-data {:tag :rss :attributes {:version "2.0"} :content [{:tag :channel :attributes {} :content [{:tag :title :attributes {} :content ["RSS Title"]} {:tag :description :attributes {} :content ["This is an example of an RSS feed"]} {:tag :link :attributes {} :content ["http://www.example.com/main.html"]} {:tag :lastBuildDate :attributes {} :content ["Mon, 06 Sep 2010 00:01:00 +0000"]} {:tag :pubDate :attributes {} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]} {:tag :ttl :attributes {} :content ["1800"]} {:tag :item :attributes {} :content [{:tag :title :attributes {} :content ["Example entry"]} {:tag :description :attributes {} :content ["Here is some text containing an interesting description."]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/1"]} {:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]} {:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]}]} {:tag :item :attributes {} :content [{:tag :title :attributes {} :content ["Example entry2"]} {:tag :description :attributes {} :content ["Here is some text containing an interesting description."]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/2"]} {:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]} {:tag :pubDate :attributes {:year "2009"} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]} {:tag :author :attributes {} :content ["<NAME>"]}]}]}]}) (deftest helpers-access (testing "Helpers access" (let [node {:tag :item :attributes {:att1 "att"} :content ["value"]}] (is (= (helpers/tag node) :item)) (is (= (helpers/attributes node) {:att1 "att"})) (is (= (helpers/children node) ["value"])) (is (= (helpers/text node) "value")))) (testing "Unexpected values" (is (= (helpers/text {:tag :item :attributes {} :content [{:tag :itemb :attributes {} :content ["value"]}]}) nil))) (testing "Check if node" (is (= (helpers/is-node {:tag :item :attributes {} :content []}) true)) (is (= (helpers/is-node "test") false)) (is (= (helpers/is-node {:tag :item :content []}) false)) (is (= (helpers/is-node [:tag "test" :attributes {} :content []]) false)))) (deftest find-first (testing "Find first tag" (is (= (helpers/find-first testing-data {:tag :link}) {:tag :link :attributes {} :content ["http://www.example.com/main.html"]})) (is (= (helpers/find-first testing-data {:tag :guid}) {:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]})) (is (= (helpers/find-first testing-data {:tag :author}) {:tag :author :attributes {} :content ["<NAME>"]})) (is (= (helpers/find-first testing-data {:tag :no-tag}) nil))) (testing "Find first path" (is (= (helpers/find-first testing-data {:path [:rss :channel :ttl]}) {:tag :ttl :attributes {} :content ["1800"]})) (is (= (helpers/find-first testing-data {:path [:rss :channel :item :link]}) {:tag :link :attributes {} :content ["http://www.example.com/blog/post/1"]})) (is (= (helpers/find-first testing-data {:path [:rss :channel :item :notexists]}) nil)) (is (= (helpers/find-first testing-data {:path nil}) nil)) (is (= (helpers/find-first testing-data {:path []}) nil)) (is (= (helpers/find-first testing-data {:path [:badroot]}) nil))) (testing "Find first keyword" (is (= (helpers/find-first testing-data {:attribute :isPermaLink}) {:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]})) (is (= (helpers/find-first testing-data {:attribute :year}) {:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]})) (is (= (helpers/find-first testing-data {:attribute :not-existing}) nil))) (testing "Find first keyword equality" (is (= (helpers/find-first testing-data {:attribute [:isPermaLink "false"]}) {:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]})) (is (= (helpers/find-first testing-data {:attribute [:isPermaLink "true"]}) {:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]})) (is (= (helpers/find-first testing-data {:attribute [:year "2013"]}) {:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]})) (is (= (helpers/find-first testing-data {:attribute [:year "2009"]}) {:tag :pubDate :attributes {:year "2009"} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]})) (is (= (helpers/find-first testing-data {:attribute [:year "2010"]}) nil)) (is (= (helpers/find-first testing-data {:attribute [:not-existing true]}) nil)) (is (= (helpers/find-first testing-data {:attribute [:shouldfail]}) nil)))) (deftest find-all (testing "Find all by tag" (is (= (helpers/find-all testing-data {:tag :link}) '({:tag :link :attributes {} :content ["http://www.example.com/main.html"]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/1"]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/2"]}))) (is (= (helpers/find-all testing-data {:tag :guid}) '({:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]} {:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]}))) (is (= (helpers/find-all testing-data {:tag :author}) '({:tag :author :attributes {} :content ["<NAME>"]}))) (is (= (helpers/find-all testing-data {:tag :no-tag}) '()))) (testing "Find first path" (is (= (helpers/find-all testing-data {:path [:rss :channel :ttl]}) '({:tag :ttl :attributes {} :content ["1800"]}))) (is (= (helpers/find-all testing-data {:path [:rss :channel :item :link]}) '({:tag :link :attributes {} :content ["http://www.example.com/blog/post/1"]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/2"]}))) (is (= (helpers/find-all testing-data {:path [:rss :channel :item :notexists]}) '())) (is (= (helpers/find-all testing-data {:path nil}) '())) (is (= (helpers/find-all testing-data {:path []}) '())) (is (= (helpers/find-all testing-data {:path [:badroot]}) '())) ) (testing "Find all keyword" (is (= (helpers/find-all testing-data {:attribute :isPermaLink}) '({:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]} {:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]}))) (is (= (helpers/find-all testing-data {:attribute :year}) '({:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]} {:tag :pubDate :attributes {:year "2009"} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]}))) (is (= (helpers/find-all testing-data {:attribute :not-existing}) '()))) (testing "Find all keyword equality" (is (= (helpers/find-all testing-data {:attribute [:isPermaLink "false"]}) '({:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]}))) (is (= (helpers/find-all testing-data {:attribute [:isPermaLink "true"]}) '({:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]}))) (is (= (helpers/find-all testing-data {:attribute [:year "2013"]}) '({:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]}))) (is (= (helpers/find-all testing-data {:attribute [:year "2009"]}) '({:tag :pubDate :attributes {:year "2009"} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]}))) (is (= (helpers/find-all testing-data {:attribute [:year "2010"]}) '())) (is (= (helpers/find-all testing-data {:attribute [:not-existing true]}) '())) (is (= (helpers/find-all testing-data {:attribute [:shouldfail]}) '()))))
true
(ns tubax.helpers-test (:require [tubax.helpers :as helpers] [cljs.test :as test :refer-macros [deftest is testing]])) (def testing-data {:tag :rss :attributes {:version "2.0"} :content [{:tag :channel :attributes {} :content [{:tag :title :attributes {} :content ["RSS Title"]} {:tag :description :attributes {} :content ["This is an example of an RSS feed"]} {:tag :link :attributes {} :content ["http://www.example.com/main.html"]} {:tag :lastBuildDate :attributes {} :content ["Mon, 06 Sep 2010 00:01:00 +0000"]} {:tag :pubDate :attributes {} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]} {:tag :ttl :attributes {} :content ["1800"]} {:tag :item :attributes {} :content [{:tag :title :attributes {} :content ["Example entry"]} {:tag :description :attributes {} :content ["Here is some text containing an interesting description."]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/1"]} {:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]} {:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]}]} {:tag :item :attributes {} :content [{:tag :title :attributes {} :content ["Example entry2"]} {:tag :description :attributes {} :content ["Here is some text containing an interesting description."]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/2"]} {:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]} {:tag :pubDate :attributes {:year "2009"} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]} {:tag :author :attributes {} :content ["PI:NAME:<NAME>END_PI"]}]}]}]}) (deftest helpers-access (testing "Helpers access" (let [node {:tag :item :attributes {:att1 "att"} :content ["value"]}] (is (= (helpers/tag node) :item)) (is (= (helpers/attributes node) {:att1 "att"})) (is (= (helpers/children node) ["value"])) (is (= (helpers/text node) "value")))) (testing "Unexpected values" (is (= (helpers/text {:tag :item :attributes {} :content [{:tag :itemb :attributes {} :content ["value"]}]}) nil))) (testing "Check if node" (is (= (helpers/is-node {:tag :item :attributes {} :content []}) true)) (is (= (helpers/is-node "test") false)) (is (= (helpers/is-node {:tag :item :content []}) false)) (is (= (helpers/is-node [:tag "test" :attributes {} :content []]) false)))) (deftest find-first (testing "Find first tag" (is (= (helpers/find-first testing-data {:tag :link}) {:tag :link :attributes {} :content ["http://www.example.com/main.html"]})) (is (= (helpers/find-first testing-data {:tag :guid}) {:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]})) (is (= (helpers/find-first testing-data {:tag :author}) {:tag :author :attributes {} :content ["PI:NAME:<NAME>END_PI"]})) (is (= (helpers/find-first testing-data {:tag :no-tag}) nil))) (testing "Find first path" (is (= (helpers/find-first testing-data {:path [:rss :channel :ttl]}) {:tag :ttl :attributes {} :content ["1800"]})) (is (= (helpers/find-first testing-data {:path [:rss :channel :item :link]}) {:tag :link :attributes {} :content ["http://www.example.com/blog/post/1"]})) (is (= (helpers/find-first testing-data {:path [:rss :channel :item :notexists]}) nil)) (is (= (helpers/find-first testing-data {:path nil}) nil)) (is (= (helpers/find-first testing-data {:path []}) nil)) (is (= (helpers/find-first testing-data {:path [:badroot]}) nil))) (testing "Find first keyword" (is (= (helpers/find-first testing-data {:attribute :isPermaLink}) {:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]})) (is (= (helpers/find-first testing-data {:attribute :year}) {:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]})) (is (= (helpers/find-first testing-data {:attribute :not-existing}) nil))) (testing "Find first keyword equality" (is (= (helpers/find-first testing-data {:attribute [:isPermaLink "false"]}) {:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]})) (is (= (helpers/find-first testing-data {:attribute [:isPermaLink "true"]}) {:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]})) (is (= (helpers/find-first testing-data {:attribute [:year "2013"]}) {:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]})) (is (= (helpers/find-first testing-data {:attribute [:year "2009"]}) {:tag :pubDate :attributes {:year "2009"} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]})) (is (= (helpers/find-first testing-data {:attribute [:year "2010"]}) nil)) (is (= (helpers/find-first testing-data {:attribute [:not-existing true]}) nil)) (is (= (helpers/find-first testing-data {:attribute [:shouldfail]}) nil)))) (deftest find-all (testing "Find all by tag" (is (= (helpers/find-all testing-data {:tag :link}) '({:tag :link :attributes {} :content ["http://www.example.com/main.html"]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/1"]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/2"]}))) (is (= (helpers/find-all testing-data {:tag :guid}) '({:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]} {:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]}))) (is (= (helpers/find-all testing-data {:tag :author}) '({:tag :author :attributes {} :content ["PI:NAME:<NAME>END_PI"]}))) (is (= (helpers/find-all testing-data {:tag :no-tag}) '()))) (testing "Find first path" (is (= (helpers/find-all testing-data {:path [:rss :channel :ttl]}) '({:tag :ttl :attributes {} :content ["1800"]}))) (is (= (helpers/find-all testing-data {:path [:rss :channel :item :link]}) '({:tag :link :attributes {} :content ["http://www.example.com/blog/post/1"]} {:tag :link :attributes {} :content ["http://www.example.com/blog/post/2"]}))) (is (= (helpers/find-all testing-data {:path [:rss :channel :item :notexists]}) '())) (is (= (helpers/find-all testing-data {:path nil}) '())) (is (= (helpers/find-all testing-data {:path []}) '())) (is (= (helpers/find-all testing-data {:path [:badroot]}) '())) ) (testing "Find all keyword" (is (= (helpers/find-all testing-data {:attribute :isPermaLink}) '({:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]} {:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]}))) (is (= (helpers/find-all testing-data {:attribute :year}) '({:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]} {:tag :pubDate :attributes {:year "2009"} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]}))) (is (= (helpers/find-all testing-data {:attribute :not-existing}) '()))) (testing "Find all keyword equality" (is (= (helpers/find-all testing-data {:attribute [:isPermaLink "false"]}) '({:tag :guid :attributes {:isPermaLink "false"} :content ["7bd204c6-1655-4c27-aaaa-111111111111"]}))) (is (= (helpers/find-all testing-data {:attribute [:isPermaLink "true"]}) '({:tag :guid :attributes {:isPermaLink "true"} :content ["7bd204c6-1655-4c27-bbbb-222222222222"]}))) (is (= (helpers/find-all testing-data {:attribute [:year "2013"]}) '({:tag :pubDate :attributes {:year "2013"} :content ["Sun, 06 Sep 2013 16:20:00 +0000"]}))) (is (= (helpers/find-all testing-data {:attribute [:year "2009"]}) '({:tag :pubDate :attributes {:year "2009"} :content ["Sun, 06 Sep 2009 16:20:00 +0000"]}))) (is (= (helpers/find-all testing-data {:attribute [:year "2010"]}) '())) (is (= (helpers/find-all testing-data {:attribute [:not-existing true]}) '())) (is (= (helpers/find-all testing-data {:attribute [:shouldfail]}) '()))))
[ { "context": " for Cross-Origin Resource Sharing.\"\n :author \"Mihael Konjević\"}\n macchiato.middleware.cors\n (:require [clojur", "end": 97, "score": 0.9998751878738403, "start": 82, "tag": "NAME", "value": "Mihael Konjević" } ]
src/macchiato/middleware/cors.cljs
arichiardi/macchiato-core
366
(ns ^{:doc "Ring middleware for Cross-Origin Resource Sharing." :author "Mihael Konjević"} macchiato.middleware.cors (:require [clojure.set :as set] [cuerdas.core :as str] [macchiato.util.response :as r :refer [get-header]])) (defn origin "Returns the Origin request header." [request] (get-header request "origin")) (defn preflight? "Returns true if the request is a preflight request" [request] (= (request :request-method) :options)) (defn lower-case-set "Converts strings in a sequence to lower-case, and put them into a set" [s] (->> s (map str/trim) (map str/lower) (set))) (defn parse-headers "Transforms a comma-separated string to a set" [s] (->> (str/split (str s) #",") (remove str/blank?) (lower-case-set))) (defn allow-preflight-headers? "Returns true if the request is a preflight request and all the headers that it's going to use are allowed. Returns false otherwise." [request allowed-headers] (if (nil? allowed-headers) true (set/subset? (parse-headers (get-header request "access-control-request-headers")) (lower-case-set (map name allowed-headers))))) (defn allow-method? "In the case of regular requests it checks if the request-method is allowed. In the case of preflight requests it checks if the access-control-request-method is allowed." [request allowed-methods] (let [preflight-name [:headers "access-control-request-method"] request-method (if (preflight? request) (keyword (str/lower (get-in request preflight-name ""))) (:request-method request))] (contains? allowed-methods request-method))) (defn allow-request? "Returns true if the request's origin matches the access control origin, otherwise false." [request access-control] (let [origin (origin request) allowed-origins (:access-control-allow-origin access-control) allowed-headers (:access-control-allow-headers access-control) allowed-methods (:access-control-allow-methods access-control)] (if (and origin (seq allowed-origins) (seq allowed-methods) (some #(re-matches % origin) allowed-origins) (if (preflight? request) (allow-preflight-headers? request allowed-headers) true) (allow-method? request allowed-methods)) true false))) (defn header-name "Returns the capitalized header name as a string." [header] (if header (->> (str/split (name header) #"-") (map str/capitalize) (str/join "-")))) (defn normalize-headers "Normalize the headers by converting them to capitalized strings." [headers] (let [upcase #(str/join ", " (sort (map (comp str/upper name) %))) to-header-names #(str/join ", " (sort (map (comp header-name name) %)))] (reduce (fn [acc [k v]] (assoc acc (header-name k) (case k :access-control-allow-methods (upcase v) :access-control-allow-headers (to-header-names v) v))) {} headers))) (defn add-headers "Add the access control headers using the request's origin to the response." [request access-control response] (if-let [origin (origin request)] (update-in response [:headers] merge (assoc access-control :access-control-allow-origin origin)) response)) (defn add-allowed-headers "Adds the allowed headers to the request" [request allowed-headers response] (if (preflight? request) (let [request-headers (get-header request "access-control-request-headers") allowed-headers (if (nil? allowed-headers) (parse-headers request-headers) allowed-headers)] (if allowed-headers (update-in response [:headers] merge {:access-control-allow-headers allowed-headers}) response)) response)) (defn add-access-control "Add the access-control headers to the response based on the rules and what came on the header." [request access-control response] (let [allowed-headers (:access-control-allow-headers access-control) rest-of-headers (dissoc access-control :access-control-allow-headers) unnormalized-resp (->> response (add-headers request rest-of-headers) (add-allowed-headers request allowed-headers))] (update-in unnormalized-resp [:headers] normalize-headers))) (defn normalize-config [access-control] (-> access-control (update-in [:access-control-allow-methods] set) (update-in [:access-control-allow-headers] #(if (coll? %) (set %) %)) (update-in [:access-control-allow-origin] #(if (sequential? %) % [%])))) (defn wrap-cors "Middleware that adds Cross-Origin Resource Sharing headers. (def handler (-> routes (wrap-cors {:access-control-allow-origin #\"http://example.com\" :access-control-allow-methods [:get :put :post :delete]))}) " ([handler] (wrap-cors handler {})) ([handler {:keys [message] :as opts}] (let [access-control (normalize-config opts)] (fn [request respond raise] (if (and (preflight? request) (allow-request? request access-control)) (let [blank-response {:status 200 :headers {} :body (or message "preflight complete")}] (respond (add-access-control request access-control blank-response))) (if (origin request) (if (allow-request? request access-control) (handler request #(respond (add-access-control request access-control %)) raise) (handler request respond raise)) (handler request respond raise)))))))
97034
(ns ^{:doc "Ring middleware for Cross-Origin Resource Sharing." :author "<NAME>"} macchiato.middleware.cors (:require [clojure.set :as set] [cuerdas.core :as str] [macchiato.util.response :as r :refer [get-header]])) (defn origin "Returns the Origin request header." [request] (get-header request "origin")) (defn preflight? "Returns true if the request is a preflight request" [request] (= (request :request-method) :options)) (defn lower-case-set "Converts strings in a sequence to lower-case, and put them into a set" [s] (->> s (map str/trim) (map str/lower) (set))) (defn parse-headers "Transforms a comma-separated string to a set" [s] (->> (str/split (str s) #",") (remove str/blank?) (lower-case-set))) (defn allow-preflight-headers? "Returns true if the request is a preflight request and all the headers that it's going to use are allowed. Returns false otherwise." [request allowed-headers] (if (nil? allowed-headers) true (set/subset? (parse-headers (get-header request "access-control-request-headers")) (lower-case-set (map name allowed-headers))))) (defn allow-method? "In the case of regular requests it checks if the request-method is allowed. In the case of preflight requests it checks if the access-control-request-method is allowed." [request allowed-methods] (let [preflight-name [:headers "access-control-request-method"] request-method (if (preflight? request) (keyword (str/lower (get-in request preflight-name ""))) (:request-method request))] (contains? allowed-methods request-method))) (defn allow-request? "Returns true if the request's origin matches the access control origin, otherwise false." [request access-control] (let [origin (origin request) allowed-origins (:access-control-allow-origin access-control) allowed-headers (:access-control-allow-headers access-control) allowed-methods (:access-control-allow-methods access-control)] (if (and origin (seq allowed-origins) (seq allowed-methods) (some #(re-matches % origin) allowed-origins) (if (preflight? request) (allow-preflight-headers? request allowed-headers) true) (allow-method? request allowed-methods)) true false))) (defn header-name "Returns the capitalized header name as a string." [header] (if header (->> (str/split (name header) #"-") (map str/capitalize) (str/join "-")))) (defn normalize-headers "Normalize the headers by converting them to capitalized strings." [headers] (let [upcase #(str/join ", " (sort (map (comp str/upper name) %))) to-header-names #(str/join ", " (sort (map (comp header-name name) %)))] (reduce (fn [acc [k v]] (assoc acc (header-name k) (case k :access-control-allow-methods (upcase v) :access-control-allow-headers (to-header-names v) v))) {} headers))) (defn add-headers "Add the access control headers using the request's origin to the response." [request access-control response] (if-let [origin (origin request)] (update-in response [:headers] merge (assoc access-control :access-control-allow-origin origin)) response)) (defn add-allowed-headers "Adds the allowed headers to the request" [request allowed-headers response] (if (preflight? request) (let [request-headers (get-header request "access-control-request-headers") allowed-headers (if (nil? allowed-headers) (parse-headers request-headers) allowed-headers)] (if allowed-headers (update-in response [:headers] merge {:access-control-allow-headers allowed-headers}) response)) response)) (defn add-access-control "Add the access-control headers to the response based on the rules and what came on the header." [request access-control response] (let [allowed-headers (:access-control-allow-headers access-control) rest-of-headers (dissoc access-control :access-control-allow-headers) unnormalized-resp (->> response (add-headers request rest-of-headers) (add-allowed-headers request allowed-headers))] (update-in unnormalized-resp [:headers] normalize-headers))) (defn normalize-config [access-control] (-> access-control (update-in [:access-control-allow-methods] set) (update-in [:access-control-allow-headers] #(if (coll? %) (set %) %)) (update-in [:access-control-allow-origin] #(if (sequential? %) % [%])))) (defn wrap-cors "Middleware that adds Cross-Origin Resource Sharing headers. (def handler (-> routes (wrap-cors {:access-control-allow-origin #\"http://example.com\" :access-control-allow-methods [:get :put :post :delete]))}) " ([handler] (wrap-cors handler {})) ([handler {:keys [message] :as opts}] (let [access-control (normalize-config opts)] (fn [request respond raise] (if (and (preflight? request) (allow-request? request access-control)) (let [blank-response {:status 200 :headers {} :body (or message "preflight complete")}] (respond (add-access-control request access-control blank-response))) (if (origin request) (if (allow-request? request access-control) (handler request #(respond (add-access-control request access-control %)) raise) (handler request respond raise)) (handler request respond raise)))))))
true
(ns ^{:doc "Ring middleware for Cross-Origin Resource Sharing." :author "PI:NAME:<NAME>END_PI"} macchiato.middleware.cors (:require [clojure.set :as set] [cuerdas.core :as str] [macchiato.util.response :as r :refer [get-header]])) (defn origin "Returns the Origin request header." [request] (get-header request "origin")) (defn preflight? "Returns true if the request is a preflight request" [request] (= (request :request-method) :options)) (defn lower-case-set "Converts strings in a sequence to lower-case, and put them into a set" [s] (->> s (map str/trim) (map str/lower) (set))) (defn parse-headers "Transforms a comma-separated string to a set" [s] (->> (str/split (str s) #",") (remove str/blank?) (lower-case-set))) (defn allow-preflight-headers? "Returns true if the request is a preflight request and all the headers that it's going to use are allowed. Returns false otherwise." [request allowed-headers] (if (nil? allowed-headers) true (set/subset? (parse-headers (get-header request "access-control-request-headers")) (lower-case-set (map name allowed-headers))))) (defn allow-method? "In the case of regular requests it checks if the request-method is allowed. In the case of preflight requests it checks if the access-control-request-method is allowed." [request allowed-methods] (let [preflight-name [:headers "access-control-request-method"] request-method (if (preflight? request) (keyword (str/lower (get-in request preflight-name ""))) (:request-method request))] (contains? allowed-methods request-method))) (defn allow-request? "Returns true if the request's origin matches the access control origin, otherwise false." [request access-control] (let [origin (origin request) allowed-origins (:access-control-allow-origin access-control) allowed-headers (:access-control-allow-headers access-control) allowed-methods (:access-control-allow-methods access-control)] (if (and origin (seq allowed-origins) (seq allowed-methods) (some #(re-matches % origin) allowed-origins) (if (preflight? request) (allow-preflight-headers? request allowed-headers) true) (allow-method? request allowed-methods)) true false))) (defn header-name "Returns the capitalized header name as a string." [header] (if header (->> (str/split (name header) #"-") (map str/capitalize) (str/join "-")))) (defn normalize-headers "Normalize the headers by converting them to capitalized strings." [headers] (let [upcase #(str/join ", " (sort (map (comp str/upper name) %))) to-header-names #(str/join ", " (sort (map (comp header-name name) %)))] (reduce (fn [acc [k v]] (assoc acc (header-name k) (case k :access-control-allow-methods (upcase v) :access-control-allow-headers (to-header-names v) v))) {} headers))) (defn add-headers "Add the access control headers using the request's origin to the response." [request access-control response] (if-let [origin (origin request)] (update-in response [:headers] merge (assoc access-control :access-control-allow-origin origin)) response)) (defn add-allowed-headers "Adds the allowed headers to the request" [request allowed-headers response] (if (preflight? request) (let [request-headers (get-header request "access-control-request-headers") allowed-headers (if (nil? allowed-headers) (parse-headers request-headers) allowed-headers)] (if allowed-headers (update-in response [:headers] merge {:access-control-allow-headers allowed-headers}) response)) response)) (defn add-access-control "Add the access-control headers to the response based on the rules and what came on the header." [request access-control response] (let [allowed-headers (:access-control-allow-headers access-control) rest-of-headers (dissoc access-control :access-control-allow-headers) unnormalized-resp (->> response (add-headers request rest-of-headers) (add-allowed-headers request allowed-headers))] (update-in unnormalized-resp [:headers] normalize-headers))) (defn normalize-config [access-control] (-> access-control (update-in [:access-control-allow-methods] set) (update-in [:access-control-allow-headers] #(if (coll? %) (set %) %)) (update-in [:access-control-allow-origin] #(if (sequential? %) % [%])))) (defn wrap-cors "Middleware that adds Cross-Origin Resource Sharing headers. (def handler (-> routes (wrap-cors {:access-control-allow-origin #\"http://example.com\" :access-control-allow-methods [:get :put :post :delete]))}) " ([handler] (wrap-cors handler {})) ([handler {:keys [message] :as opts}] (let [access-control (normalize-config opts)] (fn [request respond raise] (if (and (preflight? request) (allow-request? request access-control)) (let [blank-response {:status 200 :headers {} :body (or message "preflight complete")}] (respond (add-access-control request access-control blank-response))) (if (origin request) (if (allow-request? request access-control) (handler request #(respond (add-access-control request access-control %)) raise) (handler request respond raise)) (handler request respond raise)))))))
[ { "context": "{:user {:signing {:gpg-key \"james@logi.cl\"}\n\n :dependencies [#_[acyclic/squiggly-clo", "end": 41, "score": 0.9995672106742859, "start": 28, "tag": "EMAIL", "value": "james@logi.cl" }, { "context": " [codox \"0.6.6\"]\n [jonase/eastwood \"0.2.1\"]\n [lein-ancient", "end": 694, "score": 0.9305846691131592, "start": 688, "tag": "USERNAME", "value": "jonase" } ]
roles/clojure/files/profiles.clj
jcf/ansible-dotfiles
12
{:user {:signing {:gpg-key "james@logi.cl"} :dependencies [#_[acyclic/squiggly-clojure "0.1.2-SNAPSHOT"] [alembic "0.2.1"] [clj-diff "1.0.0-SNAPSHOT"] [clj-stacktrace "0.2.8"] [com.cemerick/pomegranate "0.3.0"] [criterium "0.4.2"] [org.clojure/tools.namespace "0.2.5"] [org.clojure/tools.nrepl "0.2.7"] [pjstadig/humane-test-output "0.7.0"] [slamhound "1.5.3"]] :plugins [[cider/cider-nrepl "0.10.0-SNAPSHOT"] [codox "0.6.6"] [jonase/eastwood "0.2.1"] [lein-ancient "0.6.7"] [lein-clojars "0.9.1"] [lein-cloverage "1.0.2"] [lein-difftest "2.0.0"] [lein-kibit "0.0.8"] [lein-marginalia "0.7.1"] [lein-pprint "1.1.1"] [com.palletops/lein-shorthand "0.4.0"] [lein-swank "1.4.4"] [lein-try "0.4.3"] [lein-typed "0.3.5"] [refactor-nrepl "1.2.0-SNAPSHOT"]] :global-vars {*print-length* 100 *warn-on-reflection* true} :injections [(require 'pjstadig.humane-test-output) (pjstadig.humane-test-output/activate!)] :shorthand {. [^:lazy alembic.still/distill ^:lazy alembic.still/load-project ^:lazy ^:macro alembic.still/lein ^:lazy cemerick.pomegranate/add-classpath ^:lazy cemerick.pomegranate/get-classpath ^:lazy cemerick.pomegranate/resources ^:lazy clj-diff.core/diff ^:lazy ^:macro clojure.core.typed/cf ^:lazy clojure.core.typed/check-ns ^:lazy clojure.java.javadoc/javadoc ^:lazy clojure.java.shell/sh ^:lazy clojure.pprint/pp ^:lazy clojure.pprint/pprint ^:lazy clojure.pprint/print-table clojure.repl/apropos clojure.repl/dir clojure.repl/doc clojure.repl/find-doc clojure.repl/pst clojure.repl/source ^:lazy clojure.reflect/reflect ^:lazy clojure.test/run-all-tests ^:lazy clojure.test/run-tests ^:lazy clojure.tools.namespace.repl/refresh ^:lazy clojure.tools.namespace.repl/refresh-all ^:lazy ^:macro criterium.core/bench ^:lazy ^:macro criterium.core/quick-bench]} :aliases {"slamhound" ["run" "-m" "slam.hound"]} :search-page-size 50}}
56532
{:user {:signing {:gpg-key "<EMAIL>"} :dependencies [#_[acyclic/squiggly-clojure "0.1.2-SNAPSHOT"] [alembic "0.2.1"] [clj-diff "1.0.0-SNAPSHOT"] [clj-stacktrace "0.2.8"] [com.cemerick/pomegranate "0.3.0"] [criterium "0.4.2"] [org.clojure/tools.namespace "0.2.5"] [org.clojure/tools.nrepl "0.2.7"] [pjstadig/humane-test-output "0.7.0"] [slamhound "1.5.3"]] :plugins [[cider/cider-nrepl "0.10.0-SNAPSHOT"] [codox "0.6.6"] [jonase/eastwood "0.2.1"] [lein-ancient "0.6.7"] [lein-clojars "0.9.1"] [lein-cloverage "1.0.2"] [lein-difftest "2.0.0"] [lein-kibit "0.0.8"] [lein-marginalia "0.7.1"] [lein-pprint "1.1.1"] [com.palletops/lein-shorthand "0.4.0"] [lein-swank "1.4.4"] [lein-try "0.4.3"] [lein-typed "0.3.5"] [refactor-nrepl "1.2.0-SNAPSHOT"]] :global-vars {*print-length* 100 *warn-on-reflection* true} :injections [(require 'pjstadig.humane-test-output) (pjstadig.humane-test-output/activate!)] :shorthand {. [^:lazy alembic.still/distill ^:lazy alembic.still/load-project ^:lazy ^:macro alembic.still/lein ^:lazy cemerick.pomegranate/add-classpath ^:lazy cemerick.pomegranate/get-classpath ^:lazy cemerick.pomegranate/resources ^:lazy clj-diff.core/diff ^:lazy ^:macro clojure.core.typed/cf ^:lazy clojure.core.typed/check-ns ^:lazy clojure.java.javadoc/javadoc ^:lazy clojure.java.shell/sh ^:lazy clojure.pprint/pp ^:lazy clojure.pprint/pprint ^:lazy clojure.pprint/print-table clojure.repl/apropos clojure.repl/dir clojure.repl/doc clojure.repl/find-doc clojure.repl/pst clojure.repl/source ^:lazy clojure.reflect/reflect ^:lazy clojure.test/run-all-tests ^:lazy clojure.test/run-tests ^:lazy clojure.tools.namespace.repl/refresh ^:lazy clojure.tools.namespace.repl/refresh-all ^:lazy ^:macro criterium.core/bench ^:lazy ^:macro criterium.core/quick-bench]} :aliases {"slamhound" ["run" "-m" "slam.hound"]} :search-page-size 50}}
true
{:user {:signing {:gpg-key "PI:EMAIL:<EMAIL>END_PI"} :dependencies [#_[acyclic/squiggly-clojure "0.1.2-SNAPSHOT"] [alembic "0.2.1"] [clj-diff "1.0.0-SNAPSHOT"] [clj-stacktrace "0.2.8"] [com.cemerick/pomegranate "0.3.0"] [criterium "0.4.2"] [org.clojure/tools.namespace "0.2.5"] [org.clojure/tools.nrepl "0.2.7"] [pjstadig/humane-test-output "0.7.0"] [slamhound "1.5.3"]] :plugins [[cider/cider-nrepl "0.10.0-SNAPSHOT"] [codox "0.6.6"] [jonase/eastwood "0.2.1"] [lein-ancient "0.6.7"] [lein-clojars "0.9.1"] [lein-cloverage "1.0.2"] [lein-difftest "2.0.0"] [lein-kibit "0.0.8"] [lein-marginalia "0.7.1"] [lein-pprint "1.1.1"] [com.palletops/lein-shorthand "0.4.0"] [lein-swank "1.4.4"] [lein-try "0.4.3"] [lein-typed "0.3.5"] [refactor-nrepl "1.2.0-SNAPSHOT"]] :global-vars {*print-length* 100 *warn-on-reflection* true} :injections [(require 'pjstadig.humane-test-output) (pjstadig.humane-test-output/activate!)] :shorthand {. [^:lazy alembic.still/distill ^:lazy alembic.still/load-project ^:lazy ^:macro alembic.still/lein ^:lazy cemerick.pomegranate/add-classpath ^:lazy cemerick.pomegranate/get-classpath ^:lazy cemerick.pomegranate/resources ^:lazy clj-diff.core/diff ^:lazy ^:macro clojure.core.typed/cf ^:lazy clojure.core.typed/check-ns ^:lazy clojure.java.javadoc/javadoc ^:lazy clojure.java.shell/sh ^:lazy clojure.pprint/pp ^:lazy clojure.pprint/pprint ^:lazy clojure.pprint/print-table clojure.repl/apropos clojure.repl/dir clojure.repl/doc clojure.repl/find-doc clojure.repl/pst clojure.repl/source ^:lazy clojure.reflect/reflect ^:lazy clojure.test/run-all-tests ^:lazy clojure.test/run-tests ^:lazy clojure.tools.namespace.repl/refresh ^:lazy clojure.tools.namespace.repl/refresh-all ^:lazy ^:macro criterium.core/bench ^:lazy ^:macro criterium.core/quick-bench]} :aliases {"slamhound" ["run" "-m" "slam.hound"]} :search-page-size 50}}
[ { "context": "]\n (is (= 1119 (int (get-in ratings [:players \"roger-federer\"]))))\n (is (= 969 (int (get-in ratings [:playe", "end": 494, "score": 0.9994924068450928, "start": 481, "tag": "NAME", "value": "roger-federer" }, { "context": "))\n (is (= 969 (int (get-in ratings [:players \"rafael-nadal\"]))))\n (is (= 744 (int (get-in ratings [:playe", "end": 560, "score": 0.9992626309394836, "start": 548, "tag": "NAME", "value": "rafael-nadal" }, { "context": "))\n (is (= 744 (int (get-in ratings [:players \"andre-agassi\"]))))\n\n (is (= 95356 (:predictable-match-count", "end": 626, "score": 0.9995895624160767, "start": 614, "tag": "NAME", "value": "andre-agassi" } ]
Chapter05/tests/packt-clj.chapter-5-tests/test/packt_clj/chapter_5_tests/activity_5_01_test.clj
transducer/The-Clojure-Workshop
55
(ns packt-clj.chapter-5-tests.activity-5-01-test (:require [clojure.test :as t :refer [deftest is testing]] [packt-clj.chapter-5-tests.activity-5-01 :as tennis] [clojure.java.io :as io])) ;;; For convenience, we reference the csv file as a resource. (def data (io/file (io/resource "match_scores_1991-2016_unindexed_csv.csv"))) (deftest elo-world-simple (let [ratings (tennis/elo-world-simple data 32)] (is (= 1119 (int (get-in ratings [:players "roger-federer"])))) (is (= 969 (int (get-in ratings [:players "rafael-nadal"])))) (is (= 744 (int (get-in ratings [:players "andre-agassi"])))) (is (= 95356 (:predictable-match-count ratings))) (is (= 61991 (:correct-predictions ratings)))))
38742
(ns packt-clj.chapter-5-tests.activity-5-01-test (:require [clojure.test :as t :refer [deftest is testing]] [packt-clj.chapter-5-tests.activity-5-01 :as tennis] [clojure.java.io :as io])) ;;; For convenience, we reference the csv file as a resource. (def data (io/file (io/resource "match_scores_1991-2016_unindexed_csv.csv"))) (deftest elo-world-simple (let [ratings (tennis/elo-world-simple data 32)] (is (= 1119 (int (get-in ratings [:players "<NAME>"])))) (is (= 969 (int (get-in ratings [:players "<NAME>"])))) (is (= 744 (int (get-in ratings [:players "<NAME>"])))) (is (= 95356 (:predictable-match-count ratings))) (is (= 61991 (:correct-predictions ratings)))))
true
(ns packt-clj.chapter-5-tests.activity-5-01-test (:require [clojure.test :as t :refer [deftest is testing]] [packt-clj.chapter-5-tests.activity-5-01 :as tennis] [clojure.java.io :as io])) ;;; For convenience, we reference the csv file as a resource. (def data (io/file (io/resource "match_scores_1991-2016_unindexed_csv.csv"))) (deftest elo-world-simple (let [ratings (tennis/elo-world-simple data 32)] (is (= 1119 (int (get-in ratings [:players "PI:NAME:<NAME>END_PI"])))) (is (= 969 (int (get-in ratings [:players "PI:NAME:<NAME>END_PI"])))) (is (= 744 (int (get-in ratings [:players "PI:NAME:<NAME>END_PI"])))) (is (= 95356 (:predictable-match-count ratings))) (is (= 61991 (:correct-predictions ratings)))))
[ { "context": "; Copyright 2010 Mark Allerton. All rights reserved.\n;\n; Redistribution and u", "end": 33, "score": 0.9998759627342224, "start": 20, "tag": "NAME", "value": "Mark Allerton" } ]
Core/src/clojure/couverjure/core.clj
allertonm/Couverjure
3
; Copyright 2010 Mark Allerton. 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 MARK ALLERTON ``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 <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. ; ; The views and conclusions contained in the software and documentation are those of the ; authors and should not be interpreted as representing official policies, either expressed ; or implied, of Mark Allerton. (ns couverjure.core (:use couverjure.types couverjure.type-encoding) (:import (org.couverjure.core Core Foundation FoundationTypeMapper Foundation$Super ID MethodImplProxy) (com.sun.jna Native CallbackProxy TypeMappingCallbackProxy Pointer))) ; load foundation and objc-runtime libraries (def core (Core.)) ; ; Dealing with architecture specifics ; ; Use the instance of Core we created to resolve all of the JNA library interfaces ; - this allows core to load arch specific JNA interfaces, but at the expense of preventing ; us from adding type hints to the JNA calls - which means performance of these calls will ; be slow. (def foundation (.foundation core)) (def native-helper (.ivarHelper core)) (println "Loading Couverjure Core") ; ; Dealing with conversions of Objective-C identifiers ; (defn selector "Create method selectors from strings or keywords (or selectors - is a no-op)" [name-or-sel] (cond (instance? String name-or-sel) (.sel_registerName foundation name-or-sel) (keyword? name-or-sel) (.sel_registerName foundation (.replace (.substring (str name-or-sel) 1) \- \:)) (instance? Pointer name-or-sel) name-or-sel)) (defn to-name "make a simple name (i.e not a selector name) from a string or keyword" [name-or-kw] (if (keyword? name-or-kw) (.substring (str name-or-kw) 1) name-or-kw)) (defn to-write-accessor-name "make a write accessor name from the given identifier" [prop-name-or-kw] (let [name (to-name prop-name-or-kw) capitalized (str (Character/toUpperCase (first name)) (subs name 1))] (str "set" capitalized ":"))) ; ; Obtaining class references ; (defn objc-class "Get a reference to the named class" [name] (.objc_getClass foundation (to-name name))) (defn class-of "Get the class of the given object" [id] (.object_getClass foundation id)) ; ; Creating and registering new classes ; (defn new-objc-class "Create but do not register a new ObjC class" [name base-class] (.objc_allocateClassPair foundation base-class (to-name name) 0)) (defn register-objc-class "Register a class created using new-objc-class" [class] (.objc_registerClassPair foundation class)) ; ; Working with instance variables for class implementations ; (defn get-ivar "Gets the value of the named ivar as a java object" [id ivar-name] ;(println "get-ivar: " id) (.getJavaIvarByName native-helper id ivar-name)) (defn init-ivar "Initializes the named ivar with a java object" [id ivar-name value] ;(println "init-ivar: " id) (.setJavaIvarByName native-helper id ivar-name value)) (defn release-ivar "Releases the java object associated with the named ivar." [id ivar-name] ;(println "release-ivar: " id) (.releaseJavaIvarByName native-helper id ivar-name)) ; ; Building method implmentations ; (defn wrap-method "This function is invoked first when a method implemntation is invoked - it handles the necessary coercions of the arguments and return value based on the method signature" [wrapped-fn sig args] (let [result (apply wrapped-fn (for [arg args] (if (instance? ID arg) (.retainAndReleaseOnFinalize arg) arg)))] (if (= :void (first sig)) nil result))) (defn method-callback-proxy "Builds an instance of JNA's CallbackProxy for the given method signature and implementation function" [name sig fn] (let [param-types (into-array Class (map :java-type (rest sig))) return-type (:java-type (first sig))] ;(println "method-callback-proxy: " name " sig " sig " args " (map to-java-type (rest sig))) (proxy [MethodImplProxy] [(str name) return-type param-types] (typeMappedCallback ([args] (wrap-method fn sig (seq args))))) )) (defn add-method "Add a method to a class with the given name, signature and implementation function" [class name sig fn] ;(println "add-method " class " name " name " sig " sig) (let [sel (selector name) objc-sig (apply str (map :encoding sig))] ;(println "add-method: " name " sig " objc-sig) (.class_addMethod foundation class sel (method-callback-proxy name sig fn) objc-sig))) ; the following two functions are used to support the "method" macro and the ">>" family of macros (defn read-objc-msg "reads a sequence as an objective-c message in the form <keyword> <arg>? (<keyword> <arg>)* combines the keywords into an obj-C selector name and collects the arguments. used by the ... macro to build actual obj-c alls and can also be used with type signatures" [msg] (let [[_ msg args] (reduce (fn [reduced item] (let [[counter names args] reduced] (if (even? counter) [(inc counter) (conj names item) args] [(inc counter) names (conj args item)]))) [0 [] []] msg)] (if (seq args) [(apply str (map #(str (subs (str %) 1) ":") msg)) args] [(subs (str (first msg)) 1)]))) (defn read-objc-method-decl "reads a sequence as an objective-c method declaration in the form return-type keyword [arg-type [keyword arg-type]*]?" [return-type keys-and-arg-types] (let [[msg arg-types] (read-objc-msg keys-and-arg-types)] [msg (apply vector (concat [return-type OCID OCSel] arg-types))])) (defmacro method "Builds an invocation of add-method, reading the method signature 'objC style' as a set of key/type pairs. Also builds the implementation function using the supplied argument list and body, adding the implied 'self' and 'sel' arguments and ensuring access to the object's state. This macro is intended to be used in the scope of an implementation block, if not, callers must synthesize the class-def structure (see the implentation macro def)" [class-def spec args & body] (let [[name sig] (read-objc-method-decl (first spec) (rest spec))] `(add-method (:class ~class-def) ~name ~sig (fn [~(symbol "self") ~(symbol "sel") ~@args] ;(let [~(symbol "properties") (get-ivar ~(symbol "self") (:state-ivar-name ~class-def))] ~@body)))) (defn property "Builds a pair of read and write accessor methods for a given property name, which will get or set property values to the object's state map. In order to be modifiable, the things in the map must be either refs or atoms - specify which using the final argument. This macro is intended to be used in the scope of an implementation block, if not, callers must synthesize the class-def structure (see the implentation macro def)" [class-def name ref-or-atom] (let [properties (fn [self] (get-ivar self (:state-ivar-name class-def)))] (add-method (:class class-def) (to-name name) [OCID OCID OCSel] (fn [self sel] (deref (name (properties self))))) (condp = ref-or-atom :atom (add-method (:class class-def) (to-write-accessor-name name) [OCVoid OCID OCSel OCID] (fn [self sel id] (reset! (name (properties self)) id))) :ref (add-method (:class class-def) (to-write-accessor-name name) [OCVoid OCID OCSel OCID] (fn [self sel id] (dosync (ref-set (name (properties self)) id))))) )) ; ; Creating class implementations ; (defmacro implementation "Creates a class implementation, without binding it. The body of the implementation should consist of a set of (method) or (property) blocks." [class-name base-class & body] `(let [new-class# (new-objc-class (to-name ~class-name) ~base-class) state-ivar-name# (str (gensym)) ok# (.class_addIvar foundation new-class# state-ivar-name# (.pointerSize core) (.pointerAlign core) "?") class-def# {:class new-class# :state-ivar-name state-ivar-name#} ~(symbol "properties") (fn [self#] (get-ivar self# state-ivar-name#)) ~(symbol "init") (fn [self# initial-state#] (init-ivar self# state-ivar-name# initial-state#))] (doto class-def# ~@body) (method class-def# [OCVoid :dealloc] [] (release-ivar ~(symbol "self") state-ivar-name#)) (register-objc-class new-class#) new-class#)) (defmacro defimplementation "Creates and binds a class implementation. The body of the implementation should consist of a set of (method) or (property) blocks." [class-symbol base-class & body] `(def ~class-symbol (implementation ~(str class-symbol) ~base-class ~@body))) ; ; Working with instances ; (defn alloc "instantiate a class" [class] (.class_createInstance foundation class 0)) ; ; Method dispatch ; (defn coerce-return-value "Coerces an 'id' return value from objc_msgSend/SendSuper to the appropriate type, or set releaseOnFinalize and retain" [value type needs-retain?] (if (= (:kind type) :primitive) (let [primitive (:type type)] (condp (fn [set prim] (set prim)) primitive #{OCID} (if needs-retain? (.retainAndReleaseOnFinalize value) (.releaseOnFinalize value)) #{OCClass OCSel} value #{OCChar OCUChar} (.asByte value) #{OCShort OCUShort} (.asShort value) #{OCInt OCUInt OCLong OCULong} (.asInt value) #{OCLongLong OCULongLong} (.asLong value) #{OCFloat} (.asFloat value) #{OCDouble} (.asDouble value) #{OCCString} (.asString value) #{OCVoid} nil)))) (defn needs-retain? "Given a selector name (for a method whose return type is 'id') determines whether the object should be retained or not." [sel-name] (not (.startsWith sel-name "init"))) ; need to improve this test (defn send-msg [id sel args] "Low level message send to object - does not coerce return types or handle super" (let [args-array (to-array args)] (.objc_msgSend foundation id sel args-array))) (defn send-super [super sel args] "Low level message send to super - does not coerce return types" (let [args-array (to-array args)] (.objc_msgSendSuper foundation super sel args-array))) (defn dynamic-send-msg "Sends a message to an object, introspecting at runtime to discover the method signature and coercing arguments and return value correctly This is currently the core mechanism for message dispatch" [id-or-super selector-str & args] (let [super? (instance? Foundation$Super id-or-super) sel (selector selector-str) target-class (if super? (.supercls id-or-super) (.object_getClass foundation id-or-super)) target-method (.class_getInstanceMethod foundation target-class sel) _ (if (= target-method 0) (throw (Exception. (format "Method %s not found" selector-str)))) method-encoding (.method_getTypeEncoding foundation target-method) return-sig (:type (first (method-argument-encoding method-encoding))) ; parse first arg from encoding raw-result (if super? (send-super id-or-super sel args) (send-msg id-or-super sel args))] (coerce-return-value raw-result return-sig (needs-retain? selector-str)))) (defn super "Obtain a reference to the 'super' object for this instance. Send messages to this object to send to superclass." [receiver] (let [receiver-class (.object_getClass foundation receiver) super-class (.class_getSuperclass foundation receiver-class)] (Foundation$Super. receiver super-class))) (defmacro >> "Builds a call to dynamic-send-message, compiling the keys from the series of key/expression pairs into the method selector." [target & msg] (let [[selector-str args] (read-objc-msg msg)] `(dynamic-send-msg ~target ~selector-str ~@args))) (defmacro >>super "This is a shortcut for (>> (super self) ...)" [target & msg] (let [[selector-str args] (read-objc-msg msg)] `(dynamic-send-msg (super ~target) ~selector-str ~@args))) ; ; Macro assistance for autorelease pools ; (defmacro with-autorelease-pool "Wraps the body in a block that creates and releases an NSAutoreleasePool" [& body] ; NSAutoreleasePool requires special handling because we want the 'release' ; to occur at the end of the block, not at some later point when the GC runs `(let [pool# (send-msg (alloc couverjure.cocoa.foundation/NSAutoreleasePool) (selector "init") []) result# (do ~@body)] (send-msg pool# (selector "release") []) result# ))
91313
; Copyright 2010 <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 MARK ALLERTON ``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 <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. ; ; The views and conclusions contained in the software and documentation are those of the ; authors and should not be interpreted as representing official policies, either expressed ; or implied, of Mark Allerton. (ns couverjure.core (:use couverjure.types couverjure.type-encoding) (:import (org.couverjure.core Core Foundation FoundationTypeMapper Foundation$Super ID MethodImplProxy) (com.sun.jna Native CallbackProxy TypeMappingCallbackProxy Pointer))) ; load foundation and objc-runtime libraries (def core (Core.)) ; ; Dealing with architecture specifics ; ; Use the instance of Core we created to resolve all of the JNA library interfaces ; - this allows core to load arch specific JNA interfaces, but at the expense of preventing ; us from adding type hints to the JNA calls - which means performance of these calls will ; be slow. (def foundation (.foundation core)) (def native-helper (.ivarHelper core)) (println "Loading Couverjure Core") ; ; Dealing with conversions of Objective-C identifiers ; (defn selector "Create method selectors from strings or keywords (or selectors - is a no-op)" [name-or-sel] (cond (instance? String name-or-sel) (.sel_registerName foundation name-or-sel) (keyword? name-or-sel) (.sel_registerName foundation (.replace (.substring (str name-or-sel) 1) \- \:)) (instance? Pointer name-or-sel) name-or-sel)) (defn to-name "make a simple name (i.e not a selector name) from a string or keyword" [name-or-kw] (if (keyword? name-or-kw) (.substring (str name-or-kw) 1) name-or-kw)) (defn to-write-accessor-name "make a write accessor name from the given identifier" [prop-name-or-kw] (let [name (to-name prop-name-or-kw) capitalized (str (Character/toUpperCase (first name)) (subs name 1))] (str "set" capitalized ":"))) ; ; Obtaining class references ; (defn objc-class "Get a reference to the named class" [name] (.objc_getClass foundation (to-name name))) (defn class-of "Get the class of the given object" [id] (.object_getClass foundation id)) ; ; Creating and registering new classes ; (defn new-objc-class "Create but do not register a new ObjC class" [name base-class] (.objc_allocateClassPair foundation base-class (to-name name) 0)) (defn register-objc-class "Register a class created using new-objc-class" [class] (.objc_registerClassPair foundation class)) ; ; Working with instance variables for class implementations ; (defn get-ivar "Gets the value of the named ivar as a java object" [id ivar-name] ;(println "get-ivar: " id) (.getJavaIvarByName native-helper id ivar-name)) (defn init-ivar "Initializes the named ivar with a java object" [id ivar-name value] ;(println "init-ivar: " id) (.setJavaIvarByName native-helper id ivar-name value)) (defn release-ivar "Releases the java object associated with the named ivar." [id ivar-name] ;(println "release-ivar: " id) (.releaseJavaIvarByName native-helper id ivar-name)) ; ; Building method implmentations ; (defn wrap-method "This function is invoked first when a method implemntation is invoked - it handles the necessary coercions of the arguments and return value based on the method signature" [wrapped-fn sig args] (let [result (apply wrapped-fn (for [arg args] (if (instance? ID arg) (.retainAndReleaseOnFinalize arg) arg)))] (if (= :void (first sig)) nil result))) (defn method-callback-proxy "Builds an instance of JNA's CallbackProxy for the given method signature and implementation function" [name sig fn] (let [param-types (into-array Class (map :java-type (rest sig))) return-type (:java-type (first sig))] ;(println "method-callback-proxy: " name " sig " sig " args " (map to-java-type (rest sig))) (proxy [MethodImplProxy] [(str name) return-type param-types] (typeMappedCallback ([args] (wrap-method fn sig (seq args))))) )) (defn add-method "Add a method to a class with the given name, signature and implementation function" [class name sig fn] ;(println "add-method " class " name " name " sig " sig) (let [sel (selector name) objc-sig (apply str (map :encoding sig))] ;(println "add-method: " name " sig " objc-sig) (.class_addMethod foundation class sel (method-callback-proxy name sig fn) objc-sig))) ; the following two functions are used to support the "method" macro and the ">>" family of macros (defn read-objc-msg "reads a sequence as an objective-c message in the form <keyword> <arg>? (<keyword> <arg>)* combines the keywords into an obj-C selector name and collects the arguments. used by the ... macro to build actual obj-c alls and can also be used with type signatures" [msg] (let [[_ msg args] (reduce (fn [reduced item] (let [[counter names args] reduced] (if (even? counter) [(inc counter) (conj names item) args] [(inc counter) names (conj args item)]))) [0 [] []] msg)] (if (seq args) [(apply str (map #(str (subs (str %) 1) ":") msg)) args] [(subs (str (first msg)) 1)]))) (defn read-objc-method-decl "reads a sequence as an objective-c method declaration in the form return-type keyword [arg-type [keyword arg-type]*]?" [return-type keys-and-arg-types] (let [[msg arg-types] (read-objc-msg keys-and-arg-types)] [msg (apply vector (concat [return-type OCID OCSel] arg-types))])) (defmacro method "Builds an invocation of add-method, reading the method signature 'objC style' as a set of key/type pairs. Also builds the implementation function using the supplied argument list and body, adding the implied 'self' and 'sel' arguments and ensuring access to the object's state. This macro is intended to be used in the scope of an implementation block, if not, callers must synthesize the class-def structure (see the implentation macro def)" [class-def spec args & body] (let [[name sig] (read-objc-method-decl (first spec) (rest spec))] `(add-method (:class ~class-def) ~name ~sig (fn [~(symbol "self") ~(symbol "sel") ~@args] ;(let [~(symbol "properties") (get-ivar ~(symbol "self") (:state-ivar-name ~class-def))] ~@body)))) (defn property "Builds a pair of read and write accessor methods for a given property name, which will get or set property values to the object's state map. In order to be modifiable, the things in the map must be either refs or atoms - specify which using the final argument. This macro is intended to be used in the scope of an implementation block, if not, callers must synthesize the class-def structure (see the implentation macro def)" [class-def name ref-or-atom] (let [properties (fn [self] (get-ivar self (:state-ivar-name class-def)))] (add-method (:class class-def) (to-name name) [OCID OCID OCSel] (fn [self sel] (deref (name (properties self))))) (condp = ref-or-atom :atom (add-method (:class class-def) (to-write-accessor-name name) [OCVoid OCID OCSel OCID] (fn [self sel id] (reset! (name (properties self)) id))) :ref (add-method (:class class-def) (to-write-accessor-name name) [OCVoid OCID OCSel OCID] (fn [self sel id] (dosync (ref-set (name (properties self)) id))))) )) ; ; Creating class implementations ; (defmacro implementation "Creates a class implementation, without binding it. The body of the implementation should consist of a set of (method) or (property) blocks." [class-name base-class & body] `(let [new-class# (new-objc-class (to-name ~class-name) ~base-class) state-ivar-name# (str (gensym)) ok# (.class_addIvar foundation new-class# state-ivar-name# (.pointerSize core) (.pointerAlign core) "?") class-def# {:class new-class# :state-ivar-name state-ivar-name#} ~(symbol "properties") (fn [self#] (get-ivar self# state-ivar-name#)) ~(symbol "init") (fn [self# initial-state#] (init-ivar self# state-ivar-name# initial-state#))] (doto class-def# ~@body) (method class-def# [OCVoid :dealloc] [] (release-ivar ~(symbol "self") state-ivar-name#)) (register-objc-class new-class#) new-class#)) (defmacro defimplementation "Creates and binds a class implementation. The body of the implementation should consist of a set of (method) or (property) blocks." [class-symbol base-class & body] `(def ~class-symbol (implementation ~(str class-symbol) ~base-class ~@body))) ; ; Working with instances ; (defn alloc "instantiate a class" [class] (.class_createInstance foundation class 0)) ; ; Method dispatch ; (defn coerce-return-value "Coerces an 'id' return value from objc_msgSend/SendSuper to the appropriate type, or set releaseOnFinalize and retain" [value type needs-retain?] (if (= (:kind type) :primitive) (let [primitive (:type type)] (condp (fn [set prim] (set prim)) primitive #{OCID} (if needs-retain? (.retainAndReleaseOnFinalize value) (.releaseOnFinalize value)) #{OCClass OCSel} value #{OCChar OCUChar} (.asByte value) #{OCShort OCUShort} (.asShort value) #{OCInt OCUInt OCLong OCULong} (.asInt value) #{OCLongLong OCULongLong} (.asLong value) #{OCFloat} (.asFloat value) #{OCDouble} (.asDouble value) #{OCCString} (.asString value) #{OCVoid} nil)))) (defn needs-retain? "Given a selector name (for a method whose return type is 'id') determines whether the object should be retained or not." [sel-name] (not (.startsWith sel-name "init"))) ; need to improve this test (defn send-msg [id sel args] "Low level message send to object - does not coerce return types or handle super" (let [args-array (to-array args)] (.objc_msgSend foundation id sel args-array))) (defn send-super [super sel args] "Low level message send to super - does not coerce return types" (let [args-array (to-array args)] (.objc_msgSendSuper foundation super sel args-array))) (defn dynamic-send-msg "Sends a message to an object, introspecting at runtime to discover the method signature and coercing arguments and return value correctly This is currently the core mechanism for message dispatch" [id-or-super selector-str & args] (let [super? (instance? Foundation$Super id-or-super) sel (selector selector-str) target-class (if super? (.supercls id-or-super) (.object_getClass foundation id-or-super)) target-method (.class_getInstanceMethod foundation target-class sel) _ (if (= target-method 0) (throw (Exception. (format "Method %s not found" selector-str)))) method-encoding (.method_getTypeEncoding foundation target-method) return-sig (:type (first (method-argument-encoding method-encoding))) ; parse first arg from encoding raw-result (if super? (send-super id-or-super sel args) (send-msg id-or-super sel args))] (coerce-return-value raw-result return-sig (needs-retain? selector-str)))) (defn super "Obtain a reference to the 'super' object for this instance. Send messages to this object to send to superclass." [receiver] (let [receiver-class (.object_getClass foundation receiver) super-class (.class_getSuperclass foundation receiver-class)] (Foundation$Super. receiver super-class))) (defmacro >> "Builds a call to dynamic-send-message, compiling the keys from the series of key/expression pairs into the method selector." [target & msg] (let [[selector-str args] (read-objc-msg msg)] `(dynamic-send-msg ~target ~selector-str ~@args))) (defmacro >>super "This is a shortcut for (>> (super self) ...)" [target & msg] (let [[selector-str args] (read-objc-msg msg)] `(dynamic-send-msg (super ~target) ~selector-str ~@args))) ; ; Macro assistance for autorelease pools ; (defmacro with-autorelease-pool "Wraps the body in a block that creates and releases an NSAutoreleasePool" [& body] ; NSAutoreleasePool requires special handling because we want the 'release' ; to occur at the end of the block, not at some later point when the GC runs `(let [pool# (send-msg (alloc couverjure.cocoa.foundation/NSAutoreleasePool) (selector "init") []) result# (do ~@body)] (send-msg pool# (selector "release") []) result# ))
true
; Copyright 2010 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 MARK ALLERTON ``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 <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. ; ; The views and conclusions contained in the software and documentation are those of the ; authors and should not be interpreted as representing official policies, either expressed ; or implied, of Mark Allerton. (ns couverjure.core (:use couverjure.types couverjure.type-encoding) (:import (org.couverjure.core Core Foundation FoundationTypeMapper Foundation$Super ID MethodImplProxy) (com.sun.jna Native CallbackProxy TypeMappingCallbackProxy Pointer))) ; load foundation and objc-runtime libraries (def core (Core.)) ; ; Dealing with architecture specifics ; ; Use the instance of Core we created to resolve all of the JNA library interfaces ; - this allows core to load arch specific JNA interfaces, but at the expense of preventing ; us from adding type hints to the JNA calls - which means performance of these calls will ; be slow. (def foundation (.foundation core)) (def native-helper (.ivarHelper core)) (println "Loading Couverjure Core") ; ; Dealing with conversions of Objective-C identifiers ; (defn selector "Create method selectors from strings or keywords (or selectors - is a no-op)" [name-or-sel] (cond (instance? String name-or-sel) (.sel_registerName foundation name-or-sel) (keyword? name-or-sel) (.sel_registerName foundation (.replace (.substring (str name-or-sel) 1) \- \:)) (instance? Pointer name-or-sel) name-or-sel)) (defn to-name "make a simple name (i.e not a selector name) from a string or keyword" [name-or-kw] (if (keyword? name-or-kw) (.substring (str name-or-kw) 1) name-or-kw)) (defn to-write-accessor-name "make a write accessor name from the given identifier" [prop-name-or-kw] (let [name (to-name prop-name-or-kw) capitalized (str (Character/toUpperCase (first name)) (subs name 1))] (str "set" capitalized ":"))) ; ; Obtaining class references ; (defn objc-class "Get a reference to the named class" [name] (.objc_getClass foundation (to-name name))) (defn class-of "Get the class of the given object" [id] (.object_getClass foundation id)) ; ; Creating and registering new classes ; (defn new-objc-class "Create but do not register a new ObjC class" [name base-class] (.objc_allocateClassPair foundation base-class (to-name name) 0)) (defn register-objc-class "Register a class created using new-objc-class" [class] (.objc_registerClassPair foundation class)) ; ; Working with instance variables for class implementations ; (defn get-ivar "Gets the value of the named ivar as a java object" [id ivar-name] ;(println "get-ivar: " id) (.getJavaIvarByName native-helper id ivar-name)) (defn init-ivar "Initializes the named ivar with a java object" [id ivar-name value] ;(println "init-ivar: " id) (.setJavaIvarByName native-helper id ivar-name value)) (defn release-ivar "Releases the java object associated with the named ivar." [id ivar-name] ;(println "release-ivar: " id) (.releaseJavaIvarByName native-helper id ivar-name)) ; ; Building method implmentations ; (defn wrap-method "This function is invoked first when a method implemntation is invoked - it handles the necessary coercions of the arguments and return value based on the method signature" [wrapped-fn sig args] (let [result (apply wrapped-fn (for [arg args] (if (instance? ID arg) (.retainAndReleaseOnFinalize arg) arg)))] (if (= :void (first sig)) nil result))) (defn method-callback-proxy "Builds an instance of JNA's CallbackProxy for the given method signature and implementation function" [name sig fn] (let [param-types (into-array Class (map :java-type (rest sig))) return-type (:java-type (first sig))] ;(println "method-callback-proxy: " name " sig " sig " args " (map to-java-type (rest sig))) (proxy [MethodImplProxy] [(str name) return-type param-types] (typeMappedCallback ([args] (wrap-method fn sig (seq args))))) )) (defn add-method "Add a method to a class with the given name, signature and implementation function" [class name sig fn] ;(println "add-method " class " name " name " sig " sig) (let [sel (selector name) objc-sig (apply str (map :encoding sig))] ;(println "add-method: " name " sig " objc-sig) (.class_addMethod foundation class sel (method-callback-proxy name sig fn) objc-sig))) ; the following two functions are used to support the "method" macro and the ">>" family of macros (defn read-objc-msg "reads a sequence as an objective-c message in the form <keyword> <arg>? (<keyword> <arg>)* combines the keywords into an obj-C selector name and collects the arguments. used by the ... macro to build actual obj-c alls and can also be used with type signatures" [msg] (let [[_ msg args] (reduce (fn [reduced item] (let [[counter names args] reduced] (if (even? counter) [(inc counter) (conj names item) args] [(inc counter) names (conj args item)]))) [0 [] []] msg)] (if (seq args) [(apply str (map #(str (subs (str %) 1) ":") msg)) args] [(subs (str (first msg)) 1)]))) (defn read-objc-method-decl "reads a sequence as an objective-c method declaration in the form return-type keyword [arg-type [keyword arg-type]*]?" [return-type keys-and-arg-types] (let [[msg arg-types] (read-objc-msg keys-and-arg-types)] [msg (apply vector (concat [return-type OCID OCSel] arg-types))])) (defmacro method "Builds an invocation of add-method, reading the method signature 'objC style' as a set of key/type pairs. Also builds the implementation function using the supplied argument list and body, adding the implied 'self' and 'sel' arguments and ensuring access to the object's state. This macro is intended to be used in the scope of an implementation block, if not, callers must synthesize the class-def structure (see the implentation macro def)" [class-def spec args & body] (let [[name sig] (read-objc-method-decl (first spec) (rest spec))] `(add-method (:class ~class-def) ~name ~sig (fn [~(symbol "self") ~(symbol "sel") ~@args] ;(let [~(symbol "properties") (get-ivar ~(symbol "self") (:state-ivar-name ~class-def))] ~@body)))) (defn property "Builds a pair of read and write accessor methods for a given property name, which will get or set property values to the object's state map. In order to be modifiable, the things in the map must be either refs or atoms - specify which using the final argument. This macro is intended to be used in the scope of an implementation block, if not, callers must synthesize the class-def structure (see the implentation macro def)" [class-def name ref-or-atom] (let [properties (fn [self] (get-ivar self (:state-ivar-name class-def)))] (add-method (:class class-def) (to-name name) [OCID OCID OCSel] (fn [self sel] (deref (name (properties self))))) (condp = ref-or-atom :atom (add-method (:class class-def) (to-write-accessor-name name) [OCVoid OCID OCSel OCID] (fn [self sel id] (reset! (name (properties self)) id))) :ref (add-method (:class class-def) (to-write-accessor-name name) [OCVoid OCID OCSel OCID] (fn [self sel id] (dosync (ref-set (name (properties self)) id))))) )) ; ; Creating class implementations ; (defmacro implementation "Creates a class implementation, without binding it. The body of the implementation should consist of a set of (method) or (property) blocks." [class-name base-class & body] `(let [new-class# (new-objc-class (to-name ~class-name) ~base-class) state-ivar-name# (str (gensym)) ok# (.class_addIvar foundation new-class# state-ivar-name# (.pointerSize core) (.pointerAlign core) "?") class-def# {:class new-class# :state-ivar-name state-ivar-name#} ~(symbol "properties") (fn [self#] (get-ivar self# state-ivar-name#)) ~(symbol "init") (fn [self# initial-state#] (init-ivar self# state-ivar-name# initial-state#))] (doto class-def# ~@body) (method class-def# [OCVoid :dealloc] [] (release-ivar ~(symbol "self") state-ivar-name#)) (register-objc-class new-class#) new-class#)) (defmacro defimplementation "Creates and binds a class implementation. The body of the implementation should consist of a set of (method) or (property) blocks." [class-symbol base-class & body] `(def ~class-symbol (implementation ~(str class-symbol) ~base-class ~@body))) ; ; Working with instances ; (defn alloc "instantiate a class" [class] (.class_createInstance foundation class 0)) ; ; Method dispatch ; (defn coerce-return-value "Coerces an 'id' return value from objc_msgSend/SendSuper to the appropriate type, or set releaseOnFinalize and retain" [value type needs-retain?] (if (= (:kind type) :primitive) (let [primitive (:type type)] (condp (fn [set prim] (set prim)) primitive #{OCID} (if needs-retain? (.retainAndReleaseOnFinalize value) (.releaseOnFinalize value)) #{OCClass OCSel} value #{OCChar OCUChar} (.asByte value) #{OCShort OCUShort} (.asShort value) #{OCInt OCUInt OCLong OCULong} (.asInt value) #{OCLongLong OCULongLong} (.asLong value) #{OCFloat} (.asFloat value) #{OCDouble} (.asDouble value) #{OCCString} (.asString value) #{OCVoid} nil)))) (defn needs-retain? "Given a selector name (for a method whose return type is 'id') determines whether the object should be retained or not." [sel-name] (not (.startsWith sel-name "init"))) ; need to improve this test (defn send-msg [id sel args] "Low level message send to object - does not coerce return types or handle super" (let [args-array (to-array args)] (.objc_msgSend foundation id sel args-array))) (defn send-super [super sel args] "Low level message send to super - does not coerce return types" (let [args-array (to-array args)] (.objc_msgSendSuper foundation super sel args-array))) (defn dynamic-send-msg "Sends a message to an object, introspecting at runtime to discover the method signature and coercing arguments and return value correctly This is currently the core mechanism for message dispatch" [id-or-super selector-str & args] (let [super? (instance? Foundation$Super id-or-super) sel (selector selector-str) target-class (if super? (.supercls id-or-super) (.object_getClass foundation id-or-super)) target-method (.class_getInstanceMethod foundation target-class sel) _ (if (= target-method 0) (throw (Exception. (format "Method %s not found" selector-str)))) method-encoding (.method_getTypeEncoding foundation target-method) return-sig (:type (first (method-argument-encoding method-encoding))) ; parse first arg from encoding raw-result (if super? (send-super id-or-super sel args) (send-msg id-or-super sel args))] (coerce-return-value raw-result return-sig (needs-retain? selector-str)))) (defn super "Obtain a reference to the 'super' object for this instance. Send messages to this object to send to superclass." [receiver] (let [receiver-class (.object_getClass foundation receiver) super-class (.class_getSuperclass foundation receiver-class)] (Foundation$Super. receiver super-class))) (defmacro >> "Builds a call to dynamic-send-message, compiling the keys from the series of key/expression pairs into the method selector." [target & msg] (let [[selector-str args] (read-objc-msg msg)] `(dynamic-send-msg ~target ~selector-str ~@args))) (defmacro >>super "This is a shortcut for (>> (super self) ...)" [target & msg] (let [[selector-str args] (read-objc-msg msg)] `(dynamic-send-msg (super ~target) ~selector-str ~@args))) ; ; Macro assistance for autorelease pools ; (defmacro with-autorelease-pool "Wraps the body in a block that creates and releases an NSAutoreleasePool" [& body] ; NSAutoreleasePool requires special handling because we want the 'release' ; to occur at the end of the block, not at some later point when the GC runs `(let [pool# (send-msg (alloc couverjure.cocoa.foundation/NSAutoreleasePool) (selector "init") []) result# (do ~@body)] (send-msg pool# (selector "release") []) result# ))
[ { "context": "(ns chapter05.calling-java)\n\n(.concat \"Hello \" \"Makoto\")\n;;=> \"Hello Makoto\"\n\n(Float/valueOf \"1000.0\")\n;", "end": 54, "score": 0.9970085620880127, "start": 48, "tag": "NAME", "value": "Makoto" }, { "context": "ing-java)\n\n(.concat \"Hello \" \"Makoto\")\n;;=> \"Hello Makoto\"\n\n(Float/valueOf \"1000.0\")\n;;=> 1000.0\n(. Float v", "end": 75, "score": 0.9804692268371582, "start": 69, "tag": "NAME", "value": "Makoto" } ]
Chapter 05 Code/src/chapter05/calling_java.clj
PacktPublishing/Clojure-Programming-Cookbook
14
(ns chapter05.calling-java) (.concat "Hello " "Makoto") ;;=> "Hello Makoto" (Float/valueOf "1000.0") ;;=> 1000.0 (. Float valueOf "1000.0") ;;=> 1000.0 (import java.util.TimeZone) ;;=> java.util.TimeZone (def time-zone (TimeZone/getTimeZone "Asia/Tokyo" )) ;;=> #'chapter05.calling-java/time-zone (.getDisplayName time-zone (java.util.Locale. "en_US")) ;;=> "Japan Standard Time" (import java.awt.Point) ;;=> java.awt.Point (def p (Point. 100 200)) ;;=> #'chapter05.calling-java/p (. p x) ;;=> 100 (. p y) ;;=> 200 (set! (.x p) 300) ;;=> 300 (. p x) ;;=> 300 Math/E ;;=> 2.718281828459045 (def t (Thread.)) ;;=> #'chapter05.calling-java/t (.getState t) ;;=> #object[java.lang.Thread$State 0xc736e3e "NEW"] (= (.getState t) Thread$State/NEW) ;;=> true (.start t) ;;=> nil (= (.getState t) Thread$State/TERMINATED) (Thread$State/values) ;;=> #object["[Ljava.lang.Thread$State;" 0x3efd737c "[Ljava.lang.Thread$State;@3efd737c"] (Thread$State/valueOf "NEW") ;=> #object[java.lang.Thread$State 0xc736e3e "NEW"] String ;;=> java.lang.String (= String (Class/forName "java.lang.String")) ;;=> true (= java.lang.String (Class/forName "java.lang.String")) ;;=> true (def str-array (into-array '("a" "b" "c" "d" "e"))) ;;=> #'chapter05.calling-java/str-array (aget str-array 0) ;;=> "a" (aset str-array 0 "x") ;;=> "x" (aget str-array 0) ;;=> "x" (time (let [n 10000000 a (long-array (range n))] (reduce + a))) ;;=> "Elapsed time: 1339.504072 msecs" ;;=> 49999995000000 (time (let [n 10000000 a (into-array (range n))] (reduce + a))) ;;=> "Elapsed time: 6101.370939 msecs" ;;=> 49999995000000 (byte-array (map int [\C \l \o \j \o \u \r \e])) ;;=> #object["[B" 0x590f9b92 "[B@590f9b92"] (String. (byte-array (map int [\C \l \o \j \o \u \r \e]))) ;;=> "Clojoure" (def mat1 (make-array Double/TYPE 10 10)) ;;=> #'chapter05.calling-java/mat1 (aget mat1 9 9) ;;=> 0.0 (int-array [1 2]) ;;=> #object["[I" 0x4d307a58 "[I@4d307a58"] (make-array Double/TYPE 10 10) ;;=> #object["[[D" 0x77570b3c "[[D@77570b3c"] (.. System getenv (get "JAVA_HOME")) ;;=> "/usr/local/oss/jdk1.8.0_65" (macroexpand-1 '(.. System getenv (get "JAVA_HOME"))) ;;=> (.. (. System getenv) (get "JAVA_HOME")) (doto (java.util.HashMap.) (.put "key1" "value1") (.put "key2" "value2") (.put "key3" "value3") ) ;;=> {"key1" "value1", "key2" "value2", "key3" "value3"} (let [hash (java.util.HashMap.)] (.put hash "key1" "value1") (.put hash "key2" "value2") (.put hash "key3" "value3") hash ) ;;=> {"key1" "value1", "key2" "value2", "key3" "value3"} (use 'clojure.reflect) ;;=>nil (use 'clojure.pprint) ;;=>nil (->> (clojure.reflect/reflect java.lang.String) :members (filter #(.startsWith (str (:name %)) "get")) (clojure.pprint/pprint)) ;;=>({:name getChars, ;;=> :return-type void, ;;=> :declaring-class java.lang.String, ;;=> :parameter-types [int int char<> int], ;;=> :exception-types [], ;;=> :flags #{:public}} ;;=> {:name getBytes, ;;=> :return-type byte<>, ;;=> :declaring-class java.lang.String, ;;=> :parameter-types [], ;;=> :exception-types [], ;;=> :flags #{:public}} ;;=> ....
28877
(ns chapter05.calling-java) (.concat "Hello " "<NAME>") ;;=> "Hello <NAME>" (Float/valueOf "1000.0") ;;=> 1000.0 (. Float valueOf "1000.0") ;;=> 1000.0 (import java.util.TimeZone) ;;=> java.util.TimeZone (def time-zone (TimeZone/getTimeZone "Asia/Tokyo" )) ;;=> #'chapter05.calling-java/time-zone (.getDisplayName time-zone (java.util.Locale. "en_US")) ;;=> "Japan Standard Time" (import java.awt.Point) ;;=> java.awt.Point (def p (Point. 100 200)) ;;=> #'chapter05.calling-java/p (. p x) ;;=> 100 (. p y) ;;=> 200 (set! (.x p) 300) ;;=> 300 (. p x) ;;=> 300 Math/E ;;=> 2.718281828459045 (def t (Thread.)) ;;=> #'chapter05.calling-java/t (.getState t) ;;=> #object[java.lang.Thread$State 0xc736e3e "NEW"] (= (.getState t) Thread$State/NEW) ;;=> true (.start t) ;;=> nil (= (.getState t) Thread$State/TERMINATED) (Thread$State/values) ;;=> #object["[Ljava.lang.Thread$State;" 0x3efd737c "[Ljava.lang.Thread$State;@3efd737c"] (Thread$State/valueOf "NEW") ;=> #object[java.lang.Thread$State 0xc736e3e "NEW"] String ;;=> java.lang.String (= String (Class/forName "java.lang.String")) ;;=> true (= java.lang.String (Class/forName "java.lang.String")) ;;=> true (def str-array (into-array '("a" "b" "c" "d" "e"))) ;;=> #'chapter05.calling-java/str-array (aget str-array 0) ;;=> "a" (aset str-array 0 "x") ;;=> "x" (aget str-array 0) ;;=> "x" (time (let [n 10000000 a (long-array (range n))] (reduce + a))) ;;=> "Elapsed time: 1339.504072 msecs" ;;=> 49999995000000 (time (let [n 10000000 a (into-array (range n))] (reduce + a))) ;;=> "Elapsed time: 6101.370939 msecs" ;;=> 49999995000000 (byte-array (map int [\C \l \o \j \o \u \r \e])) ;;=> #object["[B" 0x590f9b92 "[B@590f9b92"] (String. (byte-array (map int [\C \l \o \j \o \u \r \e]))) ;;=> "Clojoure" (def mat1 (make-array Double/TYPE 10 10)) ;;=> #'chapter05.calling-java/mat1 (aget mat1 9 9) ;;=> 0.0 (int-array [1 2]) ;;=> #object["[I" 0x4d307a58 "[I@4d307a58"] (make-array Double/TYPE 10 10) ;;=> #object["[[D" 0x77570b3c "[[D@77570b3c"] (.. System getenv (get "JAVA_HOME")) ;;=> "/usr/local/oss/jdk1.8.0_65" (macroexpand-1 '(.. System getenv (get "JAVA_HOME"))) ;;=> (.. (. System getenv) (get "JAVA_HOME")) (doto (java.util.HashMap.) (.put "key1" "value1") (.put "key2" "value2") (.put "key3" "value3") ) ;;=> {"key1" "value1", "key2" "value2", "key3" "value3"} (let [hash (java.util.HashMap.)] (.put hash "key1" "value1") (.put hash "key2" "value2") (.put hash "key3" "value3") hash ) ;;=> {"key1" "value1", "key2" "value2", "key3" "value3"} (use 'clojure.reflect) ;;=>nil (use 'clojure.pprint) ;;=>nil (->> (clojure.reflect/reflect java.lang.String) :members (filter #(.startsWith (str (:name %)) "get")) (clojure.pprint/pprint)) ;;=>({:name getChars, ;;=> :return-type void, ;;=> :declaring-class java.lang.String, ;;=> :parameter-types [int int char<> int], ;;=> :exception-types [], ;;=> :flags #{:public}} ;;=> {:name getBytes, ;;=> :return-type byte<>, ;;=> :declaring-class java.lang.String, ;;=> :parameter-types [], ;;=> :exception-types [], ;;=> :flags #{:public}} ;;=> ....
true
(ns chapter05.calling-java) (.concat "Hello " "PI:NAME:<NAME>END_PI") ;;=> "Hello PI:NAME:<NAME>END_PI" (Float/valueOf "1000.0") ;;=> 1000.0 (. Float valueOf "1000.0") ;;=> 1000.0 (import java.util.TimeZone) ;;=> java.util.TimeZone (def time-zone (TimeZone/getTimeZone "Asia/Tokyo" )) ;;=> #'chapter05.calling-java/time-zone (.getDisplayName time-zone (java.util.Locale. "en_US")) ;;=> "Japan Standard Time" (import java.awt.Point) ;;=> java.awt.Point (def p (Point. 100 200)) ;;=> #'chapter05.calling-java/p (. p x) ;;=> 100 (. p y) ;;=> 200 (set! (.x p) 300) ;;=> 300 (. p x) ;;=> 300 Math/E ;;=> 2.718281828459045 (def t (Thread.)) ;;=> #'chapter05.calling-java/t (.getState t) ;;=> #object[java.lang.Thread$State 0xc736e3e "NEW"] (= (.getState t) Thread$State/NEW) ;;=> true (.start t) ;;=> nil (= (.getState t) Thread$State/TERMINATED) (Thread$State/values) ;;=> #object["[Ljava.lang.Thread$State;" 0x3efd737c "[Ljava.lang.Thread$State;@3efd737c"] (Thread$State/valueOf "NEW") ;=> #object[java.lang.Thread$State 0xc736e3e "NEW"] String ;;=> java.lang.String (= String (Class/forName "java.lang.String")) ;;=> true (= java.lang.String (Class/forName "java.lang.String")) ;;=> true (def str-array (into-array '("a" "b" "c" "d" "e"))) ;;=> #'chapter05.calling-java/str-array (aget str-array 0) ;;=> "a" (aset str-array 0 "x") ;;=> "x" (aget str-array 0) ;;=> "x" (time (let [n 10000000 a (long-array (range n))] (reduce + a))) ;;=> "Elapsed time: 1339.504072 msecs" ;;=> 49999995000000 (time (let [n 10000000 a (into-array (range n))] (reduce + a))) ;;=> "Elapsed time: 6101.370939 msecs" ;;=> 49999995000000 (byte-array (map int [\C \l \o \j \o \u \r \e])) ;;=> #object["[B" 0x590f9b92 "[B@590f9b92"] (String. (byte-array (map int [\C \l \o \j \o \u \r \e]))) ;;=> "Clojoure" (def mat1 (make-array Double/TYPE 10 10)) ;;=> #'chapter05.calling-java/mat1 (aget mat1 9 9) ;;=> 0.0 (int-array [1 2]) ;;=> #object["[I" 0x4d307a58 "[I@4d307a58"] (make-array Double/TYPE 10 10) ;;=> #object["[[D" 0x77570b3c "[[D@77570b3c"] (.. System getenv (get "JAVA_HOME")) ;;=> "/usr/local/oss/jdk1.8.0_65" (macroexpand-1 '(.. System getenv (get "JAVA_HOME"))) ;;=> (.. (. System getenv) (get "JAVA_HOME")) (doto (java.util.HashMap.) (.put "key1" "value1") (.put "key2" "value2") (.put "key3" "value3") ) ;;=> {"key1" "value1", "key2" "value2", "key3" "value3"} (let [hash (java.util.HashMap.)] (.put hash "key1" "value1") (.put hash "key2" "value2") (.put hash "key3" "value3") hash ) ;;=> {"key1" "value1", "key2" "value2", "key3" "value3"} (use 'clojure.reflect) ;;=>nil (use 'clojure.pprint) ;;=>nil (->> (clojure.reflect/reflect java.lang.String) :members (filter #(.startsWith (str (:name %)) "get")) (clojure.pprint/pprint)) ;;=>({:name getChars, ;;=> :return-type void, ;;=> :declaring-class java.lang.String, ;;=> :parameter-types [int int char<> int], ;;=> :exception-types [], ;;=> :flags #{:public}} ;;=> {:name getBytes, ;;=> :return-type byte<>, ;;=> :declaring-class java.lang.String, ;;=> :parameter-types [], ;;=> :exception-types [], ;;=> :flags #{:public}} ;;=> ....
[ { "context": " 0.045\n :name \"Eroica\"\n :cohumulone 0.4\n ", "end": 2231, "score": 0.9959810376167297, "start": 2225, "tag": "NAME", "value": "Eroica" }, { "context": "0.11\n :name \"Tillicum\"\n :cohumulone ", "end": 2835, "score": 0.5064701437950134, "start": 2832, "tag": "NAME", "value": "Til" }, { "context": " 0.06\n :name \"Nugget\"\n :cohumulone 0.26\n ", "end": 4148, "score": 0.7838727831840515, "start": 4142, "tag": "NAME", "value": "Nugget" }, { "context": " 0.04\n :name \"Chinook\"\n :cohumulone 0.3\n ", "end": 9232, "score": 0.9729301333427429, "start": 9225, "tag": "NAME", "value": "Chinook" }, { "context": " 0.09\n :name \"Newport\"\n :cohumulone 0.37\n", "end": 9836, "score": 0.9085285067558289, "start": 9829, "tag": "NAME", "value": "Newport" }, { "context": " 0.09\n :name \"Galena\"\n :cohumulone 0.4\n ", "end": 10454, "score": 0.8861746788024902, "start": 10448, "tag": "NAME", "value": "Galena" }, { "context": " 0.06\n :name \"Bullion\"\n :cohumulone 0.4\n ", "end": 11102, "score": 0.9162576198577881, "start": 11095, "tag": "NAME", "value": "Bullion" } ]
src/common_beer_format/data/hops/bittering.cljc
Wall-Brew-Co/common-beer-format
1
(ns common-beer-format.data.hops.bittering "Data for bitter hops" (:require [common-beer-format.data.hops.hops :as hops])) (def summit (hops/build-hop :summit {:beta 0.06 :name "Summit" :cohumulone 0.3 :type "bittering" :myrcene 0.4 :humulene 0.2 :hsi 0.85 :notes "Summit boasts citric aromas of tangerine, grapefruit and orange along with an impressive alpha content giving it a wide spectrum of potential use." :caryophyllene 0.13 :alpha 0.18 :substitutes "Columbus, Simcoe, Apollo"})) (def chelan (hops/build-hop :chelan {:beta 0.098 :name "Chelan" :cohumulone 0.34 :type "bittering" :myrcene 0.5 :humulene 0.13 :hsi 0.8 :notes "Despite being comparable in style, Chelan enjoys higher yields and a higher alpha percentage than its parent Galena." :caryophyllene 0.11 :alpha 0.15 :substitutes "Galena, Nugget"})) (def cluster (hops/build-hop :cluster {:beta 0.055 :name "Cluster" :cohumulone 0.39 :type "bittering" :myrcene 0.45 :humulene 0.17 :hsi 0.83 :notes "Clean, neutral, and slightly floral in taste." :caryophyllene 0.08 :alpha 0.085 :substitutes "Galena, Eroica"})) (def eroica (hops/build-hop :eroica {:beta 0.045 :name "Eroica" :cohumulone 0.4 :type "bittering" :myrcene 0.6 :humulene 0.005 :hsi 0.8 :notes "Possesses a sharp fruity essence" :caryophyllene 0.09 :alpha 0.12 :substitutes "Galena, Cluster, Brewer's Gold"})) (def tillicum (hops/build-hop :tillicum {:beta 0.11 :name "Tillicum" :cohumulone 0.34 :type "bittering" :myrcene 0.39 :humulene 0.15 :hsi 0.8 :notes "Elements of citrus and peach" :caryophyllene 0.07 :alpha 0.15 :substitutes "Galena, Chelan"})) (def brewers-gold-us (hops/build-hop :brewers-gold-us {:beta 0.045 :name "Brewer's Gold US" :cohumulone 0.4 :type "bittering" :myrcene 0.4 :humulene 0.35 :hsi 0.1 :notes "An incredibly sharp bittering flavor." :caryophyllene 0.35 :alpha 0.1 :substitutes "Cascade, Galena"})) (def nugget (hops/build-hop :nugget {:beta 0.06 :name "Nugget" :cohumulone 0.26 :type "bittering" :myrcene 0.54 :humulene 0.17 :hsi 0.75 :notes "Solid bittering, light flavor, herbal aroma" :caryophyllene 0.08 :alpha 0.14 :substitutes "Galena"})) (def bravo (hops/build-hop :bravo {:beta 0.05 :name "Bravo" :cohumulone 0.32 :type "bittering" :myrcene 0.38 :humulene 0.2 :hsi 0.7 :notes "Spicy, earthy, and lightly floral aroma" :caryophyllene 0.1 :alpha 0.18 :substitutes "Columbus, CTZ, Nugget"})) (def magnum-us (hops/build-hop :magnum-us {:beta 0.06 :name "Magnum US" :cohumulone 0.25 :type "bittering" :myrcene 0.3 :humulene 0.35 :hsi 0.85 :notes "Excellent bittering profile and a nice, hoppy, floral aroma and subtle characters of citrus. Genetically indistinguishable from the German variety" :caryophyllene 0.1 :alpha 0.14 :substitutes "Hallertau, Columbus, Nugget"})) (def apollo (hops/build-hop :apollo {:beta 0.08 :name "Apollo" :cohumulone 0.25 :type "bittering" :myrcene 0.4 :humulene 0.3 :hsi 0.85 :notes "Sharp, clean bittering with grapefruit notes" :caryophyllene 0.18 :alpha 0.2 :substitutes "Nugget, Columbus, CTZ"})) (def ctz (hops/build-hop :ctz {:beta 0.05 :name "CTZ" :cohumulone 0.35 :type "bittering" :myrcene 0.5 :humulene 0.12 :hsi 0.8 :notes "Also known as Zeus. Sweet citrus notes with an herbal aroma." :caryophyllene 0.07 :alpha 0.17 :substitutes "Columbus, Apollo"})) (def super-galena (hops/build-hop :super-galena {:beta 0.1 :name "Super Galena" :cohumulone 0.4 :type "bittering" :myrcene 0.5 :humulene 0.35 :hsi 0.7 :notes "A far more potent variety of Galena with great bittering potential and citrus notes." :caryophyllene 0.1 :alpha 0.16 :substitutes "Galena, Columbus, CTZ, Eroica"})) (def warrior (hops/build-hop :warrior {:beta 0.055 :name "Warrior" :cohumulone 0.26 :type "bittering" :myrcene 0.45 :humulene 0.17 :hsi 0.76 :notes "Strong aroma of spice and citrus." :caryophyllene 0.1 :alpha 0.18 :substitutes "Nugget, Columbus"})) (def millennium (hops/build-hop :millennium {:beta 0.053 :name "Millennium" :cohumulone 0.3 :type "bittering" :myrcene 0.35 :humulene 0.25 :hsi 0.75 :notes "Mild herbal notes with elements of resin." :caryophyllene 0.1 :alpha 0.165 :substitutes "CTZ, Nugget"})) (def chinook (hops/build-hop :chinook {:beta 0.04 :name "Chinook" :cohumulone 0.3 :type "bittering" :myrcene 0.35 :humulene 0.2 :hsi 0.7 :notes "Powerful notes of pine and spice" :caryophyllene 0.1 :alpha 0.14 :substitutes "Galena, Eroica, Nugget"})) (def newport (hops/build-hop :newport {:beta 0.09 :name "Newport" :cohumulone 0.37 :type "bittering" :myrcene 0.5 :humulene 0.09 :hsi 0.6 :notes "Derived from the Magnum genus. Provides clean bitterness." :caryophyllene 0.5 :alpha 0.17 :substitutes "Galena, Nugget"})) (def galena (hops/build-hop :galena {:beta 0.09 :name "Galena" :cohumulone 0.4 :type "bittering" :myrcene 0.55 :humulene 0.12 :hsi 0.75 :notes "One of the most commonly used bittering hops with a pleasant fruity aroma." :caryophyllene 0.04 :alpha 0.135 :substitutes "Galena, Columbus, CTZ, Eroica"})) (def bullion (hops/build-hop :bullion {:beta 0.06 :name "Bullion" :cohumulone 0.4 :type "bittering" :myrcene 0.5 :humulene 0.25 :hsi 0.45 :notes "Scents of dark fruit and spice" :caryophyllene 0.1 :alpha 0.08 :substitutes "Columbus, Chinook, Galena"})) (def bittering (merge summit chelan cluster eroica tillicum brewers-gold-us nugget bravo magnum-us apollo ctz super-galena warrior chinook millennium newport galena bullion))
98671
(ns common-beer-format.data.hops.bittering "Data for bitter hops" (:require [common-beer-format.data.hops.hops :as hops])) (def summit (hops/build-hop :summit {:beta 0.06 :name "Summit" :cohumulone 0.3 :type "bittering" :myrcene 0.4 :humulene 0.2 :hsi 0.85 :notes "Summit boasts citric aromas of tangerine, grapefruit and orange along with an impressive alpha content giving it a wide spectrum of potential use." :caryophyllene 0.13 :alpha 0.18 :substitutes "Columbus, Simcoe, Apollo"})) (def chelan (hops/build-hop :chelan {:beta 0.098 :name "Chelan" :cohumulone 0.34 :type "bittering" :myrcene 0.5 :humulene 0.13 :hsi 0.8 :notes "Despite being comparable in style, Chelan enjoys higher yields and a higher alpha percentage than its parent Galena." :caryophyllene 0.11 :alpha 0.15 :substitutes "Galena, Nugget"})) (def cluster (hops/build-hop :cluster {:beta 0.055 :name "Cluster" :cohumulone 0.39 :type "bittering" :myrcene 0.45 :humulene 0.17 :hsi 0.83 :notes "Clean, neutral, and slightly floral in taste." :caryophyllene 0.08 :alpha 0.085 :substitutes "Galena, Eroica"})) (def eroica (hops/build-hop :eroica {:beta 0.045 :name "<NAME>" :cohumulone 0.4 :type "bittering" :myrcene 0.6 :humulene 0.005 :hsi 0.8 :notes "Possesses a sharp fruity essence" :caryophyllene 0.09 :alpha 0.12 :substitutes "Galena, Cluster, Brewer's Gold"})) (def tillicum (hops/build-hop :tillicum {:beta 0.11 :name "<NAME>licum" :cohumulone 0.34 :type "bittering" :myrcene 0.39 :humulene 0.15 :hsi 0.8 :notes "Elements of citrus and peach" :caryophyllene 0.07 :alpha 0.15 :substitutes "Galena, Chelan"})) (def brewers-gold-us (hops/build-hop :brewers-gold-us {:beta 0.045 :name "Brewer's Gold US" :cohumulone 0.4 :type "bittering" :myrcene 0.4 :humulene 0.35 :hsi 0.1 :notes "An incredibly sharp bittering flavor." :caryophyllene 0.35 :alpha 0.1 :substitutes "Cascade, Galena"})) (def nugget (hops/build-hop :nugget {:beta 0.06 :name "<NAME>" :cohumulone 0.26 :type "bittering" :myrcene 0.54 :humulene 0.17 :hsi 0.75 :notes "Solid bittering, light flavor, herbal aroma" :caryophyllene 0.08 :alpha 0.14 :substitutes "Galena"})) (def bravo (hops/build-hop :bravo {:beta 0.05 :name "Bravo" :cohumulone 0.32 :type "bittering" :myrcene 0.38 :humulene 0.2 :hsi 0.7 :notes "Spicy, earthy, and lightly floral aroma" :caryophyllene 0.1 :alpha 0.18 :substitutes "Columbus, CTZ, Nugget"})) (def magnum-us (hops/build-hop :magnum-us {:beta 0.06 :name "Magnum US" :cohumulone 0.25 :type "bittering" :myrcene 0.3 :humulene 0.35 :hsi 0.85 :notes "Excellent bittering profile and a nice, hoppy, floral aroma and subtle characters of citrus. Genetically indistinguishable from the German variety" :caryophyllene 0.1 :alpha 0.14 :substitutes "Hallertau, Columbus, Nugget"})) (def apollo (hops/build-hop :apollo {:beta 0.08 :name "Apollo" :cohumulone 0.25 :type "bittering" :myrcene 0.4 :humulene 0.3 :hsi 0.85 :notes "Sharp, clean bittering with grapefruit notes" :caryophyllene 0.18 :alpha 0.2 :substitutes "Nugget, Columbus, CTZ"})) (def ctz (hops/build-hop :ctz {:beta 0.05 :name "CTZ" :cohumulone 0.35 :type "bittering" :myrcene 0.5 :humulene 0.12 :hsi 0.8 :notes "Also known as Zeus. Sweet citrus notes with an herbal aroma." :caryophyllene 0.07 :alpha 0.17 :substitutes "Columbus, Apollo"})) (def super-galena (hops/build-hop :super-galena {:beta 0.1 :name "Super Galena" :cohumulone 0.4 :type "bittering" :myrcene 0.5 :humulene 0.35 :hsi 0.7 :notes "A far more potent variety of Galena with great bittering potential and citrus notes." :caryophyllene 0.1 :alpha 0.16 :substitutes "Galena, Columbus, CTZ, Eroica"})) (def warrior (hops/build-hop :warrior {:beta 0.055 :name "Warrior" :cohumulone 0.26 :type "bittering" :myrcene 0.45 :humulene 0.17 :hsi 0.76 :notes "Strong aroma of spice and citrus." :caryophyllene 0.1 :alpha 0.18 :substitutes "Nugget, Columbus"})) (def millennium (hops/build-hop :millennium {:beta 0.053 :name "Millennium" :cohumulone 0.3 :type "bittering" :myrcene 0.35 :humulene 0.25 :hsi 0.75 :notes "Mild herbal notes with elements of resin." :caryophyllene 0.1 :alpha 0.165 :substitutes "CTZ, Nugget"})) (def chinook (hops/build-hop :chinook {:beta 0.04 :name "<NAME>" :cohumulone 0.3 :type "bittering" :myrcene 0.35 :humulene 0.2 :hsi 0.7 :notes "Powerful notes of pine and spice" :caryophyllene 0.1 :alpha 0.14 :substitutes "Galena, Eroica, Nugget"})) (def newport (hops/build-hop :newport {:beta 0.09 :name "<NAME>" :cohumulone 0.37 :type "bittering" :myrcene 0.5 :humulene 0.09 :hsi 0.6 :notes "Derived from the Magnum genus. Provides clean bitterness." :caryophyllene 0.5 :alpha 0.17 :substitutes "Galena, Nugget"})) (def galena (hops/build-hop :galena {:beta 0.09 :name "<NAME>" :cohumulone 0.4 :type "bittering" :myrcene 0.55 :humulene 0.12 :hsi 0.75 :notes "One of the most commonly used bittering hops with a pleasant fruity aroma." :caryophyllene 0.04 :alpha 0.135 :substitutes "Galena, Columbus, CTZ, Eroica"})) (def bullion (hops/build-hop :bullion {:beta 0.06 :name "<NAME>" :cohumulone 0.4 :type "bittering" :myrcene 0.5 :humulene 0.25 :hsi 0.45 :notes "Scents of dark fruit and spice" :caryophyllene 0.1 :alpha 0.08 :substitutes "Columbus, Chinook, Galena"})) (def bittering (merge summit chelan cluster eroica tillicum brewers-gold-us nugget bravo magnum-us apollo ctz super-galena warrior chinook millennium newport galena bullion))
true
(ns common-beer-format.data.hops.bittering "Data for bitter hops" (:require [common-beer-format.data.hops.hops :as hops])) (def summit (hops/build-hop :summit {:beta 0.06 :name "Summit" :cohumulone 0.3 :type "bittering" :myrcene 0.4 :humulene 0.2 :hsi 0.85 :notes "Summit boasts citric aromas of tangerine, grapefruit and orange along with an impressive alpha content giving it a wide spectrum of potential use." :caryophyllene 0.13 :alpha 0.18 :substitutes "Columbus, Simcoe, Apollo"})) (def chelan (hops/build-hop :chelan {:beta 0.098 :name "Chelan" :cohumulone 0.34 :type "bittering" :myrcene 0.5 :humulene 0.13 :hsi 0.8 :notes "Despite being comparable in style, Chelan enjoys higher yields and a higher alpha percentage than its parent Galena." :caryophyllene 0.11 :alpha 0.15 :substitutes "Galena, Nugget"})) (def cluster (hops/build-hop :cluster {:beta 0.055 :name "Cluster" :cohumulone 0.39 :type "bittering" :myrcene 0.45 :humulene 0.17 :hsi 0.83 :notes "Clean, neutral, and slightly floral in taste." :caryophyllene 0.08 :alpha 0.085 :substitutes "Galena, Eroica"})) (def eroica (hops/build-hop :eroica {:beta 0.045 :name "PI:NAME:<NAME>END_PI" :cohumulone 0.4 :type "bittering" :myrcene 0.6 :humulene 0.005 :hsi 0.8 :notes "Possesses a sharp fruity essence" :caryophyllene 0.09 :alpha 0.12 :substitutes "Galena, Cluster, Brewer's Gold"})) (def tillicum (hops/build-hop :tillicum {:beta 0.11 :name "PI:NAME:<NAME>END_PIlicum" :cohumulone 0.34 :type "bittering" :myrcene 0.39 :humulene 0.15 :hsi 0.8 :notes "Elements of citrus and peach" :caryophyllene 0.07 :alpha 0.15 :substitutes "Galena, Chelan"})) (def brewers-gold-us (hops/build-hop :brewers-gold-us {:beta 0.045 :name "Brewer's Gold US" :cohumulone 0.4 :type "bittering" :myrcene 0.4 :humulene 0.35 :hsi 0.1 :notes "An incredibly sharp bittering flavor." :caryophyllene 0.35 :alpha 0.1 :substitutes "Cascade, Galena"})) (def nugget (hops/build-hop :nugget {:beta 0.06 :name "PI:NAME:<NAME>END_PI" :cohumulone 0.26 :type "bittering" :myrcene 0.54 :humulene 0.17 :hsi 0.75 :notes "Solid bittering, light flavor, herbal aroma" :caryophyllene 0.08 :alpha 0.14 :substitutes "Galena"})) (def bravo (hops/build-hop :bravo {:beta 0.05 :name "Bravo" :cohumulone 0.32 :type "bittering" :myrcene 0.38 :humulene 0.2 :hsi 0.7 :notes "Spicy, earthy, and lightly floral aroma" :caryophyllene 0.1 :alpha 0.18 :substitutes "Columbus, CTZ, Nugget"})) (def magnum-us (hops/build-hop :magnum-us {:beta 0.06 :name "Magnum US" :cohumulone 0.25 :type "bittering" :myrcene 0.3 :humulene 0.35 :hsi 0.85 :notes "Excellent bittering profile and a nice, hoppy, floral aroma and subtle characters of citrus. Genetically indistinguishable from the German variety" :caryophyllene 0.1 :alpha 0.14 :substitutes "Hallertau, Columbus, Nugget"})) (def apollo (hops/build-hop :apollo {:beta 0.08 :name "Apollo" :cohumulone 0.25 :type "bittering" :myrcene 0.4 :humulene 0.3 :hsi 0.85 :notes "Sharp, clean bittering with grapefruit notes" :caryophyllene 0.18 :alpha 0.2 :substitutes "Nugget, Columbus, CTZ"})) (def ctz (hops/build-hop :ctz {:beta 0.05 :name "CTZ" :cohumulone 0.35 :type "bittering" :myrcene 0.5 :humulene 0.12 :hsi 0.8 :notes "Also known as Zeus. Sweet citrus notes with an herbal aroma." :caryophyllene 0.07 :alpha 0.17 :substitutes "Columbus, Apollo"})) (def super-galena (hops/build-hop :super-galena {:beta 0.1 :name "Super Galena" :cohumulone 0.4 :type "bittering" :myrcene 0.5 :humulene 0.35 :hsi 0.7 :notes "A far more potent variety of Galena with great bittering potential and citrus notes." :caryophyllene 0.1 :alpha 0.16 :substitutes "Galena, Columbus, CTZ, Eroica"})) (def warrior (hops/build-hop :warrior {:beta 0.055 :name "Warrior" :cohumulone 0.26 :type "bittering" :myrcene 0.45 :humulene 0.17 :hsi 0.76 :notes "Strong aroma of spice and citrus." :caryophyllene 0.1 :alpha 0.18 :substitutes "Nugget, Columbus"})) (def millennium (hops/build-hop :millennium {:beta 0.053 :name "Millennium" :cohumulone 0.3 :type "bittering" :myrcene 0.35 :humulene 0.25 :hsi 0.75 :notes "Mild herbal notes with elements of resin." :caryophyllene 0.1 :alpha 0.165 :substitutes "CTZ, Nugget"})) (def chinook (hops/build-hop :chinook {:beta 0.04 :name "PI:NAME:<NAME>END_PI" :cohumulone 0.3 :type "bittering" :myrcene 0.35 :humulene 0.2 :hsi 0.7 :notes "Powerful notes of pine and spice" :caryophyllene 0.1 :alpha 0.14 :substitutes "Galena, Eroica, Nugget"})) (def newport (hops/build-hop :newport {:beta 0.09 :name "PI:NAME:<NAME>END_PI" :cohumulone 0.37 :type "bittering" :myrcene 0.5 :humulene 0.09 :hsi 0.6 :notes "Derived from the Magnum genus. Provides clean bitterness." :caryophyllene 0.5 :alpha 0.17 :substitutes "Galena, Nugget"})) (def galena (hops/build-hop :galena {:beta 0.09 :name "PI:NAME:<NAME>END_PI" :cohumulone 0.4 :type "bittering" :myrcene 0.55 :humulene 0.12 :hsi 0.75 :notes "One of the most commonly used bittering hops with a pleasant fruity aroma." :caryophyllene 0.04 :alpha 0.135 :substitutes "Galena, Columbus, CTZ, Eroica"})) (def bullion (hops/build-hop :bullion {:beta 0.06 :name "PI:NAME:<NAME>END_PI" :cohumulone 0.4 :type "bittering" :myrcene 0.5 :humulene 0.25 :hsi 0.45 :notes "Scents of dark fruit and spice" :caryophyllene 0.1 :alpha 0.08 :substitutes "Columbus, Chinook, Galena"})) (def bittering (merge summit chelan cluster eroica tillicum brewers-gold-us nugget bravo magnum-us apollo ctz super-galena warrior chinook millennium newport galena bullion))
[ { "context": " [clojure.string :as str]))\n\n(def people [{:name \"Luke\"}\n {:name \"Leia\"}\n {:name", "end": 209, "score": 0.9996544122695923, "start": 205, "tag": "NAME", "value": "Luke" }, { "context": "\n(def people [{:name \"Luke\"}\n {:name \"Leia\"}\n {:name \"Lando\"}])\n\n(defn str->rege", "end": 237, "score": 0.9997516870498657, "start": 233, "tag": "NAME", "value": "Leia" }, { "context": "\n {:name \"Leia\"}\n {:name \"Lando\"}])\n\n(defn str->regex [a-str]\n (let [escaped (st", "end": 266, "score": 0.9997367262840271, "start": 261, "tag": "NAME", "value": "Lando" } ]
ranger/resources/public/js/out/example/demos/autocomplete/demo_react_autosuggest.cljs
headwinds/daterangepicker
6
(ns example.demos.autocomplete.demo-react-autosuggest (:require [reagent.core :as r :refer [atom]] cljsjs.react-autosuggest [clojure.string :as str])) (def people [{:name "Luke"} {:name "Leia"} {:name "Lando"}]) (defn str->regex [a-str] (let [escaped (str/replace a-str #"[\+\.\?\[\]\(\)\^\$]" (partial str "\\"))] (re-pattern (str "(?i)^" escaped ".*")))) (defn getSuggestions [val] (let [trimmed-val (if (string? val) (str/trim val) "")] (if (empty? trimmed-val) [] (into [] (filter (comp #(re-matches (str->regex trimmed-val) %) :name) people))))) (defn getSuggestionValue [suggestion] (.-name suggestion)) (defn renderSuggestion [suggestion] (r/as-element [:span (.-name suggestion)])) (def Autosuggest (r/adapt-react-class js/Autosuggest)) (defn autosuggest-view [id] (let [suggestions (r/atom (getSuggestions "")) as-val (r/atom "") update-suggestions (fn [arg] (let [new-sugg (getSuggestions (.-value arg))] (reset! suggestions new-sugg) nil)) update-state-val (fn [evt new-val method] (reset! as-val (.-newValue new-val)) nil)] (fn [id] [Autosuggest {:id id :suggestions @suggestions :onSuggestionsFetchRequested update-suggestions :alwaysRenderSuggestions true :getSuggestionValue getSuggestionValue :renderSuggestion renderSuggestion :inputProps {:placeholder "Type 'l'" :value @as-val :onChange update-state-val}}])))
5891
(ns example.demos.autocomplete.demo-react-autosuggest (:require [reagent.core :as r :refer [atom]] cljsjs.react-autosuggest [clojure.string :as str])) (def people [{:name "<NAME>"} {:name "<NAME>"} {:name "<NAME>"}]) (defn str->regex [a-str] (let [escaped (str/replace a-str #"[\+\.\?\[\]\(\)\^\$]" (partial str "\\"))] (re-pattern (str "(?i)^" escaped ".*")))) (defn getSuggestions [val] (let [trimmed-val (if (string? val) (str/trim val) "")] (if (empty? trimmed-val) [] (into [] (filter (comp #(re-matches (str->regex trimmed-val) %) :name) people))))) (defn getSuggestionValue [suggestion] (.-name suggestion)) (defn renderSuggestion [suggestion] (r/as-element [:span (.-name suggestion)])) (def Autosuggest (r/adapt-react-class js/Autosuggest)) (defn autosuggest-view [id] (let [suggestions (r/atom (getSuggestions "")) as-val (r/atom "") update-suggestions (fn [arg] (let [new-sugg (getSuggestions (.-value arg))] (reset! suggestions new-sugg) nil)) update-state-val (fn [evt new-val method] (reset! as-val (.-newValue new-val)) nil)] (fn [id] [Autosuggest {:id id :suggestions @suggestions :onSuggestionsFetchRequested update-suggestions :alwaysRenderSuggestions true :getSuggestionValue getSuggestionValue :renderSuggestion renderSuggestion :inputProps {:placeholder "Type 'l'" :value @as-val :onChange update-state-val}}])))
true
(ns example.demos.autocomplete.demo-react-autosuggest (:require [reagent.core :as r :refer [atom]] cljsjs.react-autosuggest [clojure.string :as str])) (def people [{:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"}]) (defn str->regex [a-str] (let [escaped (str/replace a-str #"[\+\.\?\[\]\(\)\^\$]" (partial str "\\"))] (re-pattern (str "(?i)^" escaped ".*")))) (defn getSuggestions [val] (let [trimmed-val (if (string? val) (str/trim val) "")] (if (empty? trimmed-val) [] (into [] (filter (comp #(re-matches (str->regex trimmed-val) %) :name) people))))) (defn getSuggestionValue [suggestion] (.-name suggestion)) (defn renderSuggestion [suggestion] (r/as-element [:span (.-name suggestion)])) (def Autosuggest (r/adapt-react-class js/Autosuggest)) (defn autosuggest-view [id] (let [suggestions (r/atom (getSuggestions "")) as-val (r/atom "") update-suggestions (fn [arg] (let [new-sugg (getSuggestions (.-value arg))] (reset! suggestions new-sugg) nil)) update-state-val (fn [evt new-val method] (reset! as-val (.-newValue new-val)) nil)] (fn [id] [Autosuggest {:id id :suggestions @suggestions :onSuggestionsFetchRequested update-suggestions :alwaysRenderSuggestions true :getSuggestionValue getSuggestionValue :renderSuggestion renderSuggestion :inputProps {:placeholder "Type 'l'" :value @as-val :onChange update-state-val}}])))