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": " :on-click on-click\n :name name}\n children]))\n\n(def animate (r/create-class {", "end": 3892, "score": 0.6535687446594238, "start": 3888, "tag": "NAME", "value": "name" } ]
src/cljs/my_website/components/animate.cljs
sansarip/my-website
0
(ns my-website.components.animate (:require [reagent.core :as r] [anime] [my-website.utilities :refer [deep-merge word-concat omit-nil-keyword-args]] [my-website.styles :refer [color-palette]] [spade.core :refer [defclass]] [my-website.macros :refer-macros [assoc-component-state]] [clojure.string :as string])) (defclass animate-class [& {:keys [clickable] :or {clickable false}}] {:cursor (if clickable "hover" "inherit")}) (defn initialize-anime [this anime-props] (let [animation (anime (clj->js anime-props))] (assoc-component-state this -animation animation) animation)) (defn refine-props [props props-to-exclude] (let [keywordized (map keyword (js->clj props-to-exclude))] (apply dissoc (into [props] keywordized)))) (defn set-current-anime-props [this anime-props] (assoc-component-state this -currentAnimeProps (js->clj anime-props :keywordize-keys true))) (defn add-id-to-anime-targets [anime-props id] (let [clj-anime-props (js->clj anime-props :keywordize-keys true)] (clj->js (update clj-anime-props :targets #(conj (set %) (str "#" id)))))) (defn get-initial-state-fn [this] #js {:animation nil :id (or (.. this -props -id) (str "id-" (random-uuid))) :currentAnimeProps {}}) (defn mount-fn [this] (let [id (.. this -state -id) delay-start (or (.. this -props -delayStart) 0) anime-props (add-id-to-anime-targets (.. this -props -animeProps) id) anime-props-deep-copy (js->clj anime-props)] (set-current-anime-props this anime-props) ;; conversion serves as deep copy of anime props (js/setTimeout #(initialize-anime this anime-props-deep-copy) delay-start))) (defn update-fn [this] (let [pause (.. this -props -pause) play (.. this -props -play) seek (.. this -props -seek) restart (.. this -props -restart) id (.. this -state -id) incoming-id (.. this -props -id) incoming-anime-props (js->clj (add-id-to-anime-targets (.. this -props -animeProps) id) :keywordize-keys true) current-anime-props (.. this -state -currentAnimeProps) static-anime-props (.. this -props -staticAnimeProps) refined-incoming-anime-props (refine-props incoming-anime-props static-anime-props) refined-current-anime-props (refine-props current-anime-props static-anime-props) ;; handle anime prop updates animation (if (not= refined-incoming-anime-props refined-current-anime-props) (do (.remove anime (string/join " " (:targets current-anime-props))) (set-current-anime-props this incoming-anime-props) (initialize-anime this incoming-anime-props)) (.. this -state -animation))] (when (and incoming-id (not= incoming-id id)) (assoc-component-state this -id incoming-id)) (when animation (cond pause (.pause animation) play (.play animation) seek (.seek animation seek) restart (.restart animation restart))))) (defn render-fn [this] (let [children (.. this -props -children) classes (.. this -props -extraClasses) style (js->clj (.. this -props -style)) id (.. this -state -id) name (.. this -props -name) on-click (.. this -props -onClick) clickable (fn? on-click)] [:div {:style style :class (word-concat (omit-nil-keyword-args animate-class :clickable clickable) classes) :id id :on-click on-click :name name} children])) (def animate (r/create-class {:display-name :animate :render render-fn :get-initial-state get-initial-state-fn :component-did-mount mount-fn :component-did-update update-fn}))
29353
(ns my-website.components.animate (:require [reagent.core :as r] [anime] [my-website.utilities :refer [deep-merge word-concat omit-nil-keyword-args]] [my-website.styles :refer [color-palette]] [spade.core :refer [defclass]] [my-website.macros :refer-macros [assoc-component-state]] [clojure.string :as string])) (defclass animate-class [& {:keys [clickable] :or {clickable false}}] {:cursor (if clickable "hover" "inherit")}) (defn initialize-anime [this anime-props] (let [animation (anime (clj->js anime-props))] (assoc-component-state this -animation animation) animation)) (defn refine-props [props props-to-exclude] (let [keywordized (map keyword (js->clj props-to-exclude))] (apply dissoc (into [props] keywordized)))) (defn set-current-anime-props [this anime-props] (assoc-component-state this -currentAnimeProps (js->clj anime-props :keywordize-keys true))) (defn add-id-to-anime-targets [anime-props id] (let [clj-anime-props (js->clj anime-props :keywordize-keys true)] (clj->js (update clj-anime-props :targets #(conj (set %) (str "#" id)))))) (defn get-initial-state-fn [this] #js {:animation nil :id (or (.. this -props -id) (str "id-" (random-uuid))) :currentAnimeProps {}}) (defn mount-fn [this] (let [id (.. this -state -id) delay-start (or (.. this -props -delayStart) 0) anime-props (add-id-to-anime-targets (.. this -props -animeProps) id) anime-props-deep-copy (js->clj anime-props)] (set-current-anime-props this anime-props) ;; conversion serves as deep copy of anime props (js/setTimeout #(initialize-anime this anime-props-deep-copy) delay-start))) (defn update-fn [this] (let [pause (.. this -props -pause) play (.. this -props -play) seek (.. this -props -seek) restart (.. this -props -restart) id (.. this -state -id) incoming-id (.. this -props -id) incoming-anime-props (js->clj (add-id-to-anime-targets (.. this -props -animeProps) id) :keywordize-keys true) current-anime-props (.. this -state -currentAnimeProps) static-anime-props (.. this -props -staticAnimeProps) refined-incoming-anime-props (refine-props incoming-anime-props static-anime-props) refined-current-anime-props (refine-props current-anime-props static-anime-props) ;; handle anime prop updates animation (if (not= refined-incoming-anime-props refined-current-anime-props) (do (.remove anime (string/join " " (:targets current-anime-props))) (set-current-anime-props this incoming-anime-props) (initialize-anime this incoming-anime-props)) (.. this -state -animation))] (when (and incoming-id (not= incoming-id id)) (assoc-component-state this -id incoming-id)) (when animation (cond pause (.pause animation) play (.play animation) seek (.seek animation seek) restart (.restart animation restart))))) (defn render-fn [this] (let [children (.. this -props -children) classes (.. this -props -extraClasses) style (js->clj (.. this -props -style)) id (.. this -state -id) name (.. this -props -name) on-click (.. this -props -onClick) clickable (fn? on-click)] [:div {:style style :class (word-concat (omit-nil-keyword-args animate-class :clickable clickable) classes) :id id :on-click on-click :name <NAME>} children])) (def animate (r/create-class {:display-name :animate :render render-fn :get-initial-state get-initial-state-fn :component-did-mount mount-fn :component-did-update update-fn}))
true
(ns my-website.components.animate (:require [reagent.core :as r] [anime] [my-website.utilities :refer [deep-merge word-concat omit-nil-keyword-args]] [my-website.styles :refer [color-palette]] [spade.core :refer [defclass]] [my-website.macros :refer-macros [assoc-component-state]] [clojure.string :as string])) (defclass animate-class [& {:keys [clickable] :or {clickable false}}] {:cursor (if clickable "hover" "inherit")}) (defn initialize-anime [this anime-props] (let [animation (anime (clj->js anime-props))] (assoc-component-state this -animation animation) animation)) (defn refine-props [props props-to-exclude] (let [keywordized (map keyword (js->clj props-to-exclude))] (apply dissoc (into [props] keywordized)))) (defn set-current-anime-props [this anime-props] (assoc-component-state this -currentAnimeProps (js->clj anime-props :keywordize-keys true))) (defn add-id-to-anime-targets [anime-props id] (let [clj-anime-props (js->clj anime-props :keywordize-keys true)] (clj->js (update clj-anime-props :targets #(conj (set %) (str "#" id)))))) (defn get-initial-state-fn [this] #js {:animation nil :id (or (.. this -props -id) (str "id-" (random-uuid))) :currentAnimeProps {}}) (defn mount-fn [this] (let [id (.. this -state -id) delay-start (or (.. this -props -delayStart) 0) anime-props (add-id-to-anime-targets (.. this -props -animeProps) id) anime-props-deep-copy (js->clj anime-props)] (set-current-anime-props this anime-props) ;; conversion serves as deep copy of anime props (js/setTimeout #(initialize-anime this anime-props-deep-copy) delay-start))) (defn update-fn [this] (let [pause (.. this -props -pause) play (.. this -props -play) seek (.. this -props -seek) restart (.. this -props -restart) id (.. this -state -id) incoming-id (.. this -props -id) incoming-anime-props (js->clj (add-id-to-anime-targets (.. this -props -animeProps) id) :keywordize-keys true) current-anime-props (.. this -state -currentAnimeProps) static-anime-props (.. this -props -staticAnimeProps) refined-incoming-anime-props (refine-props incoming-anime-props static-anime-props) refined-current-anime-props (refine-props current-anime-props static-anime-props) ;; handle anime prop updates animation (if (not= refined-incoming-anime-props refined-current-anime-props) (do (.remove anime (string/join " " (:targets current-anime-props))) (set-current-anime-props this incoming-anime-props) (initialize-anime this incoming-anime-props)) (.. this -state -animation))] (when (and incoming-id (not= incoming-id id)) (assoc-component-state this -id incoming-id)) (when animation (cond pause (.pause animation) play (.play animation) seek (.seek animation seek) restart (.restart animation restart))))) (defn render-fn [this] (let [children (.. this -props -children) classes (.. this -props -extraClasses) style (js->clj (.. this -props -style)) id (.. this -state -id) name (.. this -props -name) on-click (.. this -props -onClick) clickable (fn? on-click)] [:div {:style style :class (word-concat (omit-nil-keyword-args animate-class :clickable clickable) classes) :id id :on-click on-click :name PI:NAME:<NAME>END_PI} children])) (def animate (r/create-class {:display-name :animate :render render-fn :get-initial-state get-initial-state-fn :component-did-mount mount-fn :component-did-update update-fn}))
[ { "context": ";; Copyright (c) Andrew A. Raines\n;;\n;; Permission is hereby granted, free of charg", "end": 33, "score": 0.999877393245697, "start": 17, "tag": "NAME", "value": "Andrew A. Raines" } ]
src/postal/message.clj
guv/postal
0
;; Copyright (c) Andrew A. Raines ;; ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, ;; copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the ;; Software is furnished to do so, subject to the following ;; conditions: ;; ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ;; OTHER DEALINGS IN THE SOFTWARE. (ns postal.message (:use [clojure.set :only [difference]] [clojure.java.io :only [as-url as-file]] [postal.date :only [make-date]] [postal.support :only [do-when make-props message-id user-agent]]) (:import [java.util UUID] [java.net MalformedURLException] [javax.activation DataHandler] [javax.mail Message Message$RecipientType PasswordAuthentication Session] [javax.mail.internet InternetAddress MimeMessage])) (def default-charset "utf-8") (declare make-jmessage) (defn recipients [msg] (let [^javax.mail.Message jmsg (make-jmessage msg)] (map str (.getAllRecipients jmsg)))) (defn sender [msg] (or (:sender msg) (:from msg))) (defn make-address ([addr ^String charset] (if (instance? InternetAddress addr) addr (when-let [^InternetAddress a (try (InternetAddress. addr) (catch Exception _))] (InternetAddress. (.getAddress a) (.getPersonal a) charset)))) ([^String addr ^String name-str ^String charset] (try (InternetAddress. addr name-str charset) (catch Exception _)))) (defn make-addresses [addresses charset] (if (string? addresses) (recur [addresses] charset) (into-array InternetAddress (map #(make-address % charset) addresses)))) (defn- ^java.net.URL make-url [x] (try (as-url x) (catch MalformedURLException e (as-url (as-file x))))) (defn ^String message->str [msg] (with-open [out (java.io.ByteArrayOutputStream.)] (let [^javax.mail.Message jmsg (if (instance? MimeMessage msg) msg (make-jmessage msg))] (.writeTo jmsg out) (str out)))) (defn add-recipient! [jmsg rtype addr charset] (if-let [addr (make-address addr charset)] (doto ^javax.mail.Message jmsg (.addRecipient rtype addr)) jmsg)) (defn add-recipients! [jmsg rtype addrs charset] (when addrs (cond (sequential? addrs) (doseq [addr addrs] (add-recipient! jmsg rtype addr charset))) :otherwise (add-recipient! jmsg rtype addrs charset)) jmsg) (declare eval-bodypart eval-multipart) (defprotocol PartEval (eval-part [part])) (extend-protocol PartEval clojure.lang.IPersistentMap (eval-part [part] (eval-bodypart part)) clojure.lang.IPersistentCollection (eval-part [part] (doto (javax.mail.internet.MimeBodyPart.) (.setContent (eval-multipart part))))) (defn- encode-filename [filename] (. javax.mail.internet.MimeUtility encodeText filename "UTF-8" nil)) (defn eval-bodypart [part] (condp (fn [test type] (some #(= % type) test)) (:type part) [:inline :attachment] (let [url (make-url (:content part))] (doto (javax.mail.internet.MimeBodyPart.) (.setDataHandler (DataHandler. url)) (.setFileName (-> (re-find #"[^/]+$" (.getPath url)) encode-filename)) (.setDisposition (name (:type part))) (cond-> (:content-type part) (.setHeader "Content-Type" (:content-type part))) (cond-> (:content-id part) (.setContentID (str "<" (:content-id part) ">"))) (cond-> (:file-name part) (.setFileName (encode-filename (:file-name part)))) (cond-> (:description part) (.setDescription (:description part))))) (doto (javax.mail.internet.MimeBodyPart.) (.setContent (:content part) (:type part)) (cond-> (:file-name part) (.setFileName (encode-filename (:file-name part)))) (cond-> (:description part) (.setDescription (:description part)))))) (defn eval-multipart [parts] (let [;; multiparts can have a number of different types: mixed, ;; alternative, encrypted... ;; The caller can use the first two entries to specify a type. ;; If no type is given, we default to "mixed" (for attachments etc.) [^String multiPartType, parts] (if (keyword? (first parts)) [(name (first parts)) (rest parts)] ["mixed" parts]) mp (javax.mail.internet.MimeMultipart. multiPartType)] (doseq [part parts] (.addBodyPart mp (eval-part part))) mp)) (defn add-multipart! [^javax.mail.Message jmsg parts] (.setContent jmsg (eval-multipart parts))) (defn add-extra! [^javax.mail.Message jmsg msgrest] (doseq [[n v] msgrest] (.addHeader jmsg (if (keyword? n) (name n) n) v)) jmsg) (defn add-body! [^javax.mail.Message jmsg body charset] (cond (string? body) (if (instance? MimeMessage jmsg) (doto ^MimeMessage jmsg (.setText body charset)) (doto jmsg (.setText body))) (map? body) (let [{:keys [content, type] :or {type "text/plain"}} body] (doto jmsg (.setContent content, type))) :else (doto jmsg (add-multipart! body)))) (defn make-auth [user pass] (proxy [javax.mail.Authenticator] [] (getPasswordAuthentication [] (PasswordAuthentication. user pass)))) (defn make-jmessage ([msg] (let [{:keys [sender from]} msg {:keys [user pass]} (meta msg) props (make-props (or sender from) (meta msg)) session (or (:session (meta msg)) (if user (Session/getInstance props (make-auth user pass)) (Session/getInstance props)))] (make-jmessage msg session))) ([msg session] (let [standard [:from :reply-to :to :cc :bcc :date :subject :body :message-id :user-agent :sender] charset (or (:charset msg) default-charset) jmsg (proxy [MimeMessage] [^Session session] (updateMessageID [] (.setHeader ^MimeMessage this "Message-ID" ((:message-id msg message-id)))))] (doto ^MimeMessage jmsg (add-recipients! Message$RecipientType/TO (:to msg) charset) (add-recipients! Message$RecipientType/CC (:cc msg) charset) (add-recipients! Message$RecipientType/BCC (:bcc msg) charset) (.setFrom (let [{:keys [from sender]} msg] ^InternetAddress (make-address (or from sender) charset))) (.setReplyTo (when-let [reply-to (:reply-to msg)] (make-addresses reply-to charset))) (.setSubject (:subject msg) ^String charset) (.setSentDate (or (:date msg) (make-date))) (.addHeader "User-Agent" (:user-agent msg (user-agent))) (add-extra! (apply dissoc msg standard)) (add-body! (:body msg) charset) (.saveChanges))))) (defn make-fixture [from to & {:keys [tag]}] (let [uuid (str (UUID/randomUUID)) tag (or tag "[POSTAL]")] {:from from :to to :subject (format "%s Test -- %s" tag uuid) :body (format "Test %s" uuid)}))
105579
;; Copyright (c) <NAME> ;; ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, ;; copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the ;; Software is furnished to do so, subject to the following ;; conditions: ;; ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ;; OTHER DEALINGS IN THE SOFTWARE. (ns postal.message (:use [clojure.set :only [difference]] [clojure.java.io :only [as-url as-file]] [postal.date :only [make-date]] [postal.support :only [do-when make-props message-id user-agent]]) (:import [java.util UUID] [java.net MalformedURLException] [javax.activation DataHandler] [javax.mail Message Message$RecipientType PasswordAuthentication Session] [javax.mail.internet InternetAddress MimeMessage])) (def default-charset "utf-8") (declare make-jmessage) (defn recipients [msg] (let [^javax.mail.Message jmsg (make-jmessage msg)] (map str (.getAllRecipients jmsg)))) (defn sender [msg] (or (:sender msg) (:from msg))) (defn make-address ([addr ^String charset] (if (instance? InternetAddress addr) addr (when-let [^InternetAddress a (try (InternetAddress. addr) (catch Exception _))] (InternetAddress. (.getAddress a) (.getPersonal a) charset)))) ([^String addr ^String name-str ^String charset] (try (InternetAddress. addr name-str charset) (catch Exception _)))) (defn make-addresses [addresses charset] (if (string? addresses) (recur [addresses] charset) (into-array InternetAddress (map #(make-address % charset) addresses)))) (defn- ^java.net.URL make-url [x] (try (as-url x) (catch MalformedURLException e (as-url (as-file x))))) (defn ^String message->str [msg] (with-open [out (java.io.ByteArrayOutputStream.)] (let [^javax.mail.Message jmsg (if (instance? MimeMessage msg) msg (make-jmessage msg))] (.writeTo jmsg out) (str out)))) (defn add-recipient! [jmsg rtype addr charset] (if-let [addr (make-address addr charset)] (doto ^javax.mail.Message jmsg (.addRecipient rtype addr)) jmsg)) (defn add-recipients! [jmsg rtype addrs charset] (when addrs (cond (sequential? addrs) (doseq [addr addrs] (add-recipient! jmsg rtype addr charset))) :otherwise (add-recipient! jmsg rtype addrs charset)) jmsg) (declare eval-bodypart eval-multipart) (defprotocol PartEval (eval-part [part])) (extend-protocol PartEval clojure.lang.IPersistentMap (eval-part [part] (eval-bodypart part)) clojure.lang.IPersistentCollection (eval-part [part] (doto (javax.mail.internet.MimeBodyPart.) (.setContent (eval-multipart part))))) (defn- encode-filename [filename] (. javax.mail.internet.MimeUtility encodeText filename "UTF-8" nil)) (defn eval-bodypart [part] (condp (fn [test type] (some #(= % type) test)) (:type part) [:inline :attachment] (let [url (make-url (:content part))] (doto (javax.mail.internet.MimeBodyPart.) (.setDataHandler (DataHandler. url)) (.setFileName (-> (re-find #"[^/]+$" (.getPath url)) encode-filename)) (.setDisposition (name (:type part))) (cond-> (:content-type part) (.setHeader "Content-Type" (:content-type part))) (cond-> (:content-id part) (.setContentID (str "<" (:content-id part) ">"))) (cond-> (:file-name part) (.setFileName (encode-filename (:file-name part)))) (cond-> (:description part) (.setDescription (:description part))))) (doto (javax.mail.internet.MimeBodyPart.) (.setContent (:content part) (:type part)) (cond-> (:file-name part) (.setFileName (encode-filename (:file-name part)))) (cond-> (:description part) (.setDescription (:description part)))))) (defn eval-multipart [parts] (let [;; multiparts can have a number of different types: mixed, ;; alternative, encrypted... ;; The caller can use the first two entries to specify a type. ;; If no type is given, we default to "mixed" (for attachments etc.) [^String multiPartType, parts] (if (keyword? (first parts)) [(name (first parts)) (rest parts)] ["mixed" parts]) mp (javax.mail.internet.MimeMultipart. multiPartType)] (doseq [part parts] (.addBodyPart mp (eval-part part))) mp)) (defn add-multipart! [^javax.mail.Message jmsg parts] (.setContent jmsg (eval-multipart parts))) (defn add-extra! [^javax.mail.Message jmsg msgrest] (doseq [[n v] msgrest] (.addHeader jmsg (if (keyword? n) (name n) n) v)) jmsg) (defn add-body! [^javax.mail.Message jmsg body charset] (cond (string? body) (if (instance? MimeMessage jmsg) (doto ^MimeMessage jmsg (.setText body charset)) (doto jmsg (.setText body))) (map? body) (let [{:keys [content, type] :or {type "text/plain"}} body] (doto jmsg (.setContent content, type))) :else (doto jmsg (add-multipart! body)))) (defn make-auth [user pass] (proxy [javax.mail.Authenticator] [] (getPasswordAuthentication [] (PasswordAuthentication. user pass)))) (defn make-jmessage ([msg] (let [{:keys [sender from]} msg {:keys [user pass]} (meta msg) props (make-props (or sender from) (meta msg)) session (or (:session (meta msg)) (if user (Session/getInstance props (make-auth user pass)) (Session/getInstance props)))] (make-jmessage msg session))) ([msg session] (let [standard [:from :reply-to :to :cc :bcc :date :subject :body :message-id :user-agent :sender] charset (or (:charset msg) default-charset) jmsg (proxy [MimeMessage] [^Session session] (updateMessageID [] (.setHeader ^MimeMessage this "Message-ID" ((:message-id msg message-id)))))] (doto ^MimeMessage jmsg (add-recipients! Message$RecipientType/TO (:to msg) charset) (add-recipients! Message$RecipientType/CC (:cc msg) charset) (add-recipients! Message$RecipientType/BCC (:bcc msg) charset) (.setFrom (let [{:keys [from sender]} msg] ^InternetAddress (make-address (or from sender) charset))) (.setReplyTo (when-let [reply-to (:reply-to msg)] (make-addresses reply-to charset))) (.setSubject (:subject msg) ^String charset) (.setSentDate (or (:date msg) (make-date))) (.addHeader "User-Agent" (:user-agent msg (user-agent))) (add-extra! (apply dissoc msg standard)) (add-body! (:body msg) charset) (.saveChanges))))) (defn make-fixture [from to & {:keys [tag]}] (let [uuid (str (UUID/randomUUID)) tag (or tag "[POSTAL]")] {:from from :to to :subject (format "%s Test -- %s" tag uuid) :body (format "Test %s" uuid)}))
true
;; Copyright (c) PI:NAME:<NAME>END_PI ;; ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, ;; copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the ;; Software is furnished to do so, subject to the following ;; conditions: ;; ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ;; OTHER DEALINGS IN THE SOFTWARE. (ns postal.message (:use [clojure.set :only [difference]] [clojure.java.io :only [as-url as-file]] [postal.date :only [make-date]] [postal.support :only [do-when make-props message-id user-agent]]) (:import [java.util UUID] [java.net MalformedURLException] [javax.activation DataHandler] [javax.mail Message Message$RecipientType PasswordAuthentication Session] [javax.mail.internet InternetAddress MimeMessage])) (def default-charset "utf-8") (declare make-jmessage) (defn recipients [msg] (let [^javax.mail.Message jmsg (make-jmessage msg)] (map str (.getAllRecipients jmsg)))) (defn sender [msg] (or (:sender msg) (:from msg))) (defn make-address ([addr ^String charset] (if (instance? InternetAddress addr) addr (when-let [^InternetAddress a (try (InternetAddress. addr) (catch Exception _))] (InternetAddress. (.getAddress a) (.getPersonal a) charset)))) ([^String addr ^String name-str ^String charset] (try (InternetAddress. addr name-str charset) (catch Exception _)))) (defn make-addresses [addresses charset] (if (string? addresses) (recur [addresses] charset) (into-array InternetAddress (map #(make-address % charset) addresses)))) (defn- ^java.net.URL make-url [x] (try (as-url x) (catch MalformedURLException e (as-url (as-file x))))) (defn ^String message->str [msg] (with-open [out (java.io.ByteArrayOutputStream.)] (let [^javax.mail.Message jmsg (if (instance? MimeMessage msg) msg (make-jmessage msg))] (.writeTo jmsg out) (str out)))) (defn add-recipient! [jmsg rtype addr charset] (if-let [addr (make-address addr charset)] (doto ^javax.mail.Message jmsg (.addRecipient rtype addr)) jmsg)) (defn add-recipients! [jmsg rtype addrs charset] (when addrs (cond (sequential? addrs) (doseq [addr addrs] (add-recipient! jmsg rtype addr charset))) :otherwise (add-recipient! jmsg rtype addrs charset)) jmsg) (declare eval-bodypart eval-multipart) (defprotocol PartEval (eval-part [part])) (extend-protocol PartEval clojure.lang.IPersistentMap (eval-part [part] (eval-bodypart part)) clojure.lang.IPersistentCollection (eval-part [part] (doto (javax.mail.internet.MimeBodyPart.) (.setContent (eval-multipart part))))) (defn- encode-filename [filename] (. javax.mail.internet.MimeUtility encodeText filename "UTF-8" nil)) (defn eval-bodypart [part] (condp (fn [test type] (some #(= % type) test)) (:type part) [:inline :attachment] (let [url (make-url (:content part))] (doto (javax.mail.internet.MimeBodyPart.) (.setDataHandler (DataHandler. url)) (.setFileName (-> (re-find #"[^/]+$" (.getPath url)) encode-filename)) (.setDisposition (name (:type part))) (cond-> (:content-type part) (.setHeader "Content-Type" (:content-type part))) (cond-> (:content-id part) (.setContentID (str "<" (:content-id part) ">"))) (cond-> (:file-name part) (.setFileName (encode-filename (:file-name part)))) (cond-> (:description part) (.setDescription (:description part))))) (doto (javax.mail.internet.MimeBodyPart.) (.setContent (:content part) (:type part)) (cond-> (:file-name part) (.setFileName (encode-filename (:file-name part)))) (cond-> (:description part) (.setDescription (:description part)))))) (defn eval-multipart [parts] (let [;; multiparts can have a number of different types: mixed, ;; alternative, encrypted... ;; The caller can use the first two entries to specify a type. ;; If no type is given, we default to "mixed" (for attachments etc.) [^String multiPartType, parts] (if (keyword? (first parts)) [(name (first parts)) (rest parts)] ["mixed" parts]) mp (javax.mail.internet.MimeMultipart. multiPartType)] (doseq [part parts] (.addBodyPart mp (eval-part part))) mp)) (defn add-multipart! [^javax.mail.Message jmsg parts] (.setContent jmsg (eval-multipart parts))) (defn add-extra! [^javax.mail.Message jmsg msgrest] (doseq [[n v] msgrest] (.addHeader jmsg (if (keyword? n) (name n) n) v)) jmsg) (defn add-body! [^javax.mail.Message jmsg body charset] (cond (string? body) (if (instance? MimeMessage jmsg) (doto ^MimeMessage jmsg (.setText body charset)) (doto jmsg (.setText body))) (map? body) (let [{:keys [content, type] :or {type "text/plain"}} body] (doto jmsg (.setContent content, type))) :else (doto jmsg (add-multipart! body)))) (defn make-auth [user pass] (proxy [javax.mail.Authenticator] [] (getPasswordAuthentication [] (PasswordAuthentication. user pass)))) (defn make-jmessage ([msg] (let [{:keys [sender from]} msg {:keys [user pass]} (meta msg) props (make-props (or sender from) (meta msg)) session (or (:session (meta msg)) (if user (Session/getInstance props (make-auth user pass)) (Session/getInstance props)))] (make-jmessage msg session))) ([msg session] (let [standard [:from :reply-to :to :cc :bcc :date :subject :body :message-id :user-agent :sender] charset (or (:charset msg) default-charset) jmsg (proxy [MimeMessage] [^Session session] (updateMessageID [] (.setHeader ^MimeMessage this "Message-ID" ((:message-id msg message-id)))))] (doto ^MimeMessage jmsg (add-recipients! Message$RecipientType/TO (:to msg) charset) (add-recipients! Message$RecipientType/CC (:cc msg) charset) (add-recipients! Message$RecipientType/BCC (:bcc msg) charset) (.setFrom (let [{:keys [from sender]} msg] ^InternetAddress (make-address (or from sender) charset))) (.setReplyTo (when-let [reply-to (:reply-to msg)] (make-addresses reply-to charset))) (.setSubject (:subject msg) ^String charset) (.setSentDate (or (:date msg) (make-date))) (.addHeader "User-Agent" (:user-agent msg (user-agent))) (add-extra! (apply dissoc msg standard)) (add-body! (:body msg) charset) (.saveChanges))))) (defn make-fixture [from to & {:keys [tag]}] (let [uuid (str (UUID/randomUUID)) tag (or tag "[POSTAL]")] {:from from :to to :subject (format "%s Test -- %s" tag uuid) :body (format "Test %s" uuid)}))
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2017-11-15\"\n ", "end": 96, "score": 0.7555345892906189, "start": 87, "tag": "EMAIL", "value": "wahpenayo" }, { "context": "-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2017-11-15\"\n :doc \"Common def", "end": 113, "score": 0.7653177976608276, "start": 100, "tag": "EMAIL", "value": "gmail dot com" } ]
src/test/clojure/taiga/test/measure/data/defs.clj
wahpenayo/taiga
4
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "wahpenayo at gmail dot com" :date "2017-11-15" :doc "Common definitions for unit tests." } taiga.test.measure.data.defs (:require [clojure.java.io :as io] [clojure.string :as s] [clojure.pprint :as pp] [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.measure.data.record :as record]) (:import [java.util Map] [clojure.lang IFn$OD])) ;;---------------------------------------------------------------- (defn options (^Map [^IFn$OD median ^long n] ;; Note: record/generator resets seed each time it's called (let [data (z/map (record/generator median) (range (* 3 n))) [train emp test] (z/partition n data) _ (test/is (== n (z/count train) (z/count emp) (z/count test))) predictors (dissoc record/attributes :ground-truth :prediction) m (int (z/count predictors)) _ (test/is (== 8 (z/count predictors))) mtry (Math/min m (int (Math/round (Math/sqrt m)))) nterms 128 mincount 127 options {:data train :empirical-distribution-data emp :test-data test :attributes record/attributes :nterms nterms :mincount mincount :mtry mtry}] _ (test/is (== 10 (count (:attributes options)))) _ (test/is (== 3 (:mtry options))) options)) (^Map [^IFn$OD median] (options median (* 32 1024)))) ;;---------------------------------------------------------------- (defn model-file [nss options model] (let [tokens (s/split nss #"\.") folder (apply io/file "tst" (butlast tokens)) fname (last tokens) file (io/file folder (str fname "-" (z/count (:data options)) "-" (taiga/nterms model) "-" (:mincount options) "-" (:mtry options) "." (:ext options)))] (io/make-parents file) file)) ;;---------------------------------------------------------------- (defn serialization-test [nss options model] (let [edn-file (model-file nss (assoc options :ext "edn.gz") model) ;;pretty-file (model-file nss (assoc options :ext "pretty.edn") model) json-file (model-file nss (assoc options :ext "json.gz") model) ;;bin-file (model-file nss (assoc options :ext "bin.gz") model) _ (io/make-parents edn-file) _ (taiga/write-json model json-file) _ (taiga/write-edn model edn-file) ;;_ (taiga/pprint-model model pretty-file) edn-model (taiga/read-edn edn-file)] (test/is (= model edn-model)))) ;;---------------------------------------------------------------- (defn predictions-file [nss options prefix model] (let [tokens (s/split nss #"\.") folder (apply io/file "tst" (butlast tokens)) fname (last tokens) file (io/file folder (str "predictions" "-" prefix "-" fname "-" (z/count (:data options)) "-" (taiga/nterms model) "-" (:mincount options) "-" (:mtry options) ".tsv.gz"))] (io/make-parents file) file)) ;;---------------------------------------------------------------- (defn write-predictions [nss options prefix model predictions] (z/write-tsv-file record/tsv-attributes predictions (predictions-file nss options prefix model))) ;;---------------------------------------------------------------- ;;----------------------------------------------------------------
96533
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<EMAIL> at <EMAIL>" :date "2017-11-15" :doc "Common definitions for unit tests." } taiga.test.measure.data.defs (:require [clojure.java.io :as io] [clojure.string :as s] [clojure.pprint :as pp] [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.measure.data.record :as record]) (:import [java.util Map] [clojure.lang IFn$OD])) ;;---------------------------------------------------------------- (defn options (^Map [^IFn$OD median ^long n] ;; Note: record/generator resets seed each time it's called (let [data (z/map (record/generator median) (range (* 3 n))) [train emp test] (z/partition n data) _ (test/is (== n (z/count train) (z/count emp) (z/count test))) predictors (dissoc record/attributes :ground-truth :prediction) m (int (z/count predictors)) _ (test/is (== 8 (z/count predictors))) mtry (Math/min m (int (Math/round (Math/sqrt m)))) nterms 128 mincount 127 options {:data train :empirical-distribution-data emp :test-data test :attributes record/attributes :nterms nterms :mincount mincount :mtry mtry}] _ (test/is (== 10 (count (:attributes options)))) _ (test/is (== 3 (:mtry options))) options)) (^Map [^IFn$OD median] (options median (* 32 1024)))) ;;---------------------------------------------------------------- (defn model-file [nss options model] (let [tokens (s/split nss #"\.") folder (apply io/file "tst" (butlast tokens)) fname (last tokens) file (io/file folder (str fname "-" (z/count (:data options)) "-" (taiga/nterms model) "-" (:mincount options) "-" (:mtry options) "." (:ext options)))] (io/make-parents file) file)) ;;---------------------------------------------------------------- (defn serialization-test [nss options model] (let [edn-file (model-file nss (assoc options :ext "edn.gz") model) ;;pretty-file (model-file nss (assoc options :ext "pretty.edn") model) json-file (model-file nss (assoc options :ext "json.gz") model) ;;bin-file (model-file nss (assoc options :ext "bin.gz") model) _ (io/make-parents edn-file) _ (taiga/write-json model json-file) _ (taiga/write-edn model edn-file) ;;_ (taiga/pprint-model model pretty-file) edn-model (taiga/read-edn edn-file)] (test/is (= model edn-model)))) ;;---------------------------------------------------------------- (defn predictions-file [nss options prefix model] (let [tokens (s/split nss #"\.") folder (apply io/file "tst" (butlast tokens)) fname (last tokens) file (io/file folder (str "predictions" "-" prefix "-" fname "-" (z/count (:data options)) "-" (taiga/nterms model) "-" (:mincount options) "-" (:mtry options) ".tsv.gz"))] (io/make-parents file) file)) ;;---------------------------------------------------------------- (defn write-predictions [nss options prefix model predictions] (z/write-tsv-file record/tsv-attributes predictions (predictions-file nss options prefix model))) ;;---------------------------------------------------------------- ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:EMAIL:<EMAIL>END_PI at PI:EMAIL:<EMAIL>END_PI" :date "2017-11-15" :doc "Common definitions for unit tests." } taiga.test.measure.data.defs (:require [clojure.java.io :as io] [clojure.string :as s] [clojure.pprint :as pp] [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.measure.data.record :as record]) (:import [java.util Map] [clojure.lang IFn$OD])) ;;---------------------------------------------------------------- (defn options (^Map [^IFn$OD median ^long n] ;; Note: record/generator resets seed each time it's called (let [data (z/map (record/generator median) (range (* 3 n))) [train emp test] (z/partition n data) _ (test/is (== n (z/count train) (z/count emp) (z/count test))) predictors (dissoc record/attributes :ground-truth :prediction) m (int (z/count predictors)) _ (test/is (== 8 (z/count predictors))) mtry (Math/min m (int (Math/round (Math/sqrt m)))) nterms 128 mincount 127 options {:data train :empirical-distribution-data emp :test-data test :attributes record/attributes :nterms nterms :mincount mincount :mtry mtry}] _ (test/is (== 10 (count (:attributes options)))) _ (test/is (== 3 (:mtry options))) options)) (^Map [^IFn$OD median] (options median (* 32 1024)))) ;;---------------------------------------------------------------- (defn model-file [nss options model] (let [tokens (s/split nss #"\.") folder (apply io/file "tst" (butlast tokens)) fname (last tokens) file (io/file folder (str fname "-" (z/count (:data options)) "-" (taiga/nterms model) "-" (:mincount options) "-" (:mtry options) "." (:ext options)))] (io/make-parents file) file)) ;;---------------------------------------------------------------- (defn serialization-test [nss options model] (let [edn-file (model-file nss (assoc options :ext "edn.gz") model) ;;pretty-file (model-file nss (assoc options :ext "pretty.edn") model) json-file (model-file nss (assoc options :ext "json.gz") model) ;;bin-file (model-file nss (assoc options :ext "bin.gz") model) _ (io/make-parents edn-file) _ (taiga/write-json model json-file) _ (taiga/write-edn model edn-file) ;;_ (taiga/pprint-model model pretty-file) edn-model (taiga/read-edn edn-file)] (test/is (= model edn-model)))) ;;---------------------------------------------------------------- (defn predictions-file [nss options prefix model] (let [tokens (s/split nss #"\.") folder (apply io/file "tst" (butlast tokens)) fname (last tokens) file (io/file folder (str "predictions" "-" prefix "-" fname "-" (z/count (:data options)) "-" (taiga/nterms model) "-" (:mincount options) "-" (:mtry options) ".tsv.gz"))] (io/make-parents file) file)) ;;---------------------------------------------------------------- (defn write-predictions [nss options prefix model predictions] (z/write-tsv-file record/tsv-attributes predictions (predictions-file nss options prefix model))) ;;---------------------------------------------------------------- ;;----------------------------------------------------------------
[ { "context": "ts for palisades.lakes.elements.sets\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-04-20\"\n :version \"2017-04-20\"}", "end": 284, "score": 0.9836280345916748, "start": 248, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/test/clojure/palisades/lakes/elements/test/sets.clj
palisades-lakes/les-elemens
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.test.sets {:doc "Unit tests for palisades.lakes.elements.sets" :author "palisades dot lakes at gmail dot com" :since "2017-04-20" :version "2017-04-20"} (:require [clojure.test :as test] [palisades.lakes.elements.api :as mc])) ;; mvn clojure:test -Dtest=palisades.lakes.elements.test.sets ;;---------------------------------------------------------------- (test/deftest clojure (test/is (mc/element? :a #{:a :b :c}))) ;;----------------------------------------------------------------
90394
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.test.sets {:doc "Unit tests for palisades.lakes.elements.sets" :author "<EMAIL>" :since "2017-04-20" :version "2017-04-20"} (:require [clojure.test :as test] [palisades.lakes.elements.api :as mc])) ;; mvn clojure:test -Dtest=palisades.lakes.elements.test.sets ;;---------------------------------------------------------------- (test/deftest clojure (test/is (mc/element? :a #{:a :b :c}))) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.test.sets {:doc "Unit tests for palisades.lakes.elements.sets" :author "PI:EMAIL:<EMAIL>END_PI" :since "2017-04-20" :version "2017-04-20"} (:require [clojure.test :as test] [palisades.lakes.elements.api :as mc])) ;; mvn clojure:test -Dtest=palisades.lakes.elements.test.sets ;;---------------------------------------------------------------- (test/deftest clojure (test/is (mc/element? :a #{:a :b :c}))) ;;----------------------------------------------------------------
[ { "context": ")))\n x)))\n\n(pass \"aAb\")\n(pass \"abBA\")\n(pass \"dabAcCaCBAcCcaDA\") ; => dabCBAcaDA ?\n\n(defn reaction-pass [pstring", "end": 1033, "score": 0.7812752723693848, "start": 1017, "tag": "PASSWORD", "value": "dabAcCaCBAcCcaDA" }, { "context": "action \"aAb\")\n(polymer-reaction \"abBA\")\n(pass \"dabAcCaCBAcCcaDA\") ; => dabCBAcaDA ?\n\n(count (polymer-r", "end": 2140, "score": 0.7575498819351196, "start": 2138, "tag": "PASSWORD", "value": "Ac" } ]
2018/5.clj
natw/aoc
0
(ns aoc) (def input (map str (seq (first (clojure.string/split-lines (slurp "inputs/5.txt")))))) (first input) (defn abs [n] (max n (-' n))) (defn inverse-units? [a b] (and (not= a b) (= 32 (abs (- (int a) (int b)))))) (defn react [a b] (cond (nil? a) (str b) (nil? b) (str a) :else (if (inverse-units? a b) "" (str a b)))) (= "" (react \a \A)) (= "aa" (react \a \a)) (= "x" (react nil \x)) (defn pass [polymer] (loop [x (str (first polymer)) remaining (rest polymer)] (println "x: " x " remaining: " remaining) (if (<= 2 (count remaining)) (let [product (react (last x) (first remaining)) untouched (rest remaining)] (println "product: " product " empty? " (empty? product)) (println "untouched:" untouched) (if (empty? product) (recur (str (butlast x) (first untouched)) (rest untouched) ) (recur (str x (rest product)) untouched))) x))) (pass "aAb") (pass "abBA") (pass "dabAcCaCBAcCcaDA") ; => dabCBAcaDA ? (defn reaction-pass [pstring] (apply str (if (empty? pstring) '() (if (= 1 (count pstring)) (seq pstring) (let [[a b & remaining] pstring] (let [first-reaction (react a b)] (condp = (count first-reaction) 0 (reaction-pass remaining) 1 first-reaction 2 (cons a (reaction-pass (cons b remaining)))))))))) (pass "aAb") (reaction-pass "aaAb") ; (defn polymer-reaction [pstring] ; (if (<= (count pstring) 1) ; pstring ; (let [[u1 u2 & remaining :as all] pstring] ; (if (inverse-units? u1 u2) ; (polymer-reaction remaining) ; (polymer-reaction (cons u1 (polymer-reaction (rest all)))))))) (defn polymer-reaction [pstring] (loop [orig pstring product (reaction-pass pstring)] (if (< (count orig) 2) orig (if (= product orig) orig (recur product (reaction-pass product)))) )) (polymer-reaction "aAb") (polymer-reaction "abBA") (pass "dabAcCaCBAcCcaDA") ; => dabCBAcaDA ? (count (polymer-reaction input))
75458
(ns aoc) (def input (map str (seq (first (clojure.string/split-lines (slurp "inputs/5.txt")))))) (first input) (defn abs [n] (max n (-' n))) (defn inverse-units? [a b] (and (not= a b) (= 32 (abs (- (int a) (int b)))))) (defn react [a b] (cond (nil? a) (str b) (nil? b) (str a) :else (if (inverse-units? a b) "" (str a b)))) (= "" (react \a \A)) (= "aa" (react \a \a)) (= "x" (react nil \x)) (defn pass [polymer] (loop [x (str (first polymer)) remaining (rest polymer)] (println "x: " x " remaining: " remaining) (if (<= 2 (count remaining)) (let [product (react (last x) (first remaining)) untouched (rest remaining)] (println "product: " product " empty? " (empty? product)) (println "untouched:" untouched) (if (empty? product) (recur (str (butlast x) (first untouched)) (rest untouched) ) (recur (str x (rest product)) untouched))) x))) (pass "aAb") (pass "abBA") (pass "<PASSWORD>") ; => dabCBAcaDA ? (defn reaction-pass [pstring] (apply str (if (empty? pstring) '() (if (= 1 (count pstring)) (seq pstring) (let [[a b & remaining] pstring] (let [first-reaction (react a b)] (condp = (count first-reaction) 0 (reaction-pass remaining) 1 first-reaction 2 (cons a (reaction-pass (cons b remaining)))))))))) (pass "aAb") (reaction-pass "aaAb") ; (defn polymer-reaction [pstring] ; (if (<= (count pstring) 1) ; pstring ; (let [[u1 u2 & remaining :as all] pstring] ; (if (inverse-units? u1 u2) ; (polymer-reaction remaining) ; (polymer-reaction (cons u1 (polymer-reaction (rest all)))))))) (defn polymer-reaction [pstring] (loop [orig pstring product (reaction-pass pstring)] (if (< (count orig) 2) orig (if (= product orig) orig (recur product (reaction-pass product)))) )) (polymer-reaction "aAb") (polymer-reaction "abBA") (pass "dab<PASSWORD>CaCBAcCcaDA") ; => dabCBAcaDA ? (count (polymer-reaction input))
true
(ns aoc) (def input (map str (seq (first (clojure.string/split-lines (slurp "inputs/5.txt")))))) (first input) (defn abs [n] (max n (-' n))) (defn inverse-units? [a b] (and (not= a b) (= 32 (abs (- (int a) (int b)))))) (defn react [a b] (cond (nil? a) (str b) (nil? b) (str a) :else (if (inverse-units? a b) "" (str a b)))) (= "" (react \a \A)) (= "aa" (react \a \a)) (= "x" (react nil \x)) (defn pass [polymer] (loop [x (str (first polymer)) remaining (rest polymer)] (println "x: " x " remaining: " remaining) (if (<= 2 (count remaining)) (let [product (react (last x) (first remaining)) untouched (rest remaining)] (println "product: " product " empty? " (empty? product)) (println "untouched:" untouched) (if (empty? product) (recur (str (butlast x) (first untouched)) (rest untouched) ) (recur (str x (rest product)) untouched))) x))) (pass "aAb") (pass "abBA") (pass "PI:PASSWORD:<PASSWORD>END_PI") ; => dabCBAcaDA ? (defn reaction-pass [pstring] (apply str (if (empty? pstring) '() (if (= 1 (count pstring)) (seq pstring) (let [[a b & remaining] pstring] (let [first-reaction (react a b)] (condp = (count first-reaction) 0 (reaction-pass remaining) 1 first-reaction 2 (cons a (reaction-pass (cons b remaining)))))))))) (pass "aAb") (reaction-pass "aaAb") ; (defn polymer-reaction [pstring] ; (if (<= (count pstring) 1) ; pstring ; (let [[u1 u2 & remaining :as all] pstring] ; (if (inverse-units? u1 u2) ; (polymer-reaction remaining) ; (polymer-reaction (cons u1 (polymer-reaction (rest all)))))))) (defn polymer-reaction [pstring] (loop [orig pstring product (reaction-pass pstring)] (if (< (count orig) 2) orig (if (= product orig) orig (recur product (reaction-pass product)))) )) (polymer-reaction "aAb") (polymer-reaction "abBA") (pass "dabPI:PASSWORD:<PASSWORD>END_PICaCBAcCcaDA") ; => dabCBAcaDA ? (count (polymer-reaction input))
[ { "context": "pe \"git\"\n :url \"git://github.com/marianoguerra/json.human.js.git\"}\n :license \"MIT\"\n :conf", "end": 336, "score": 0.9819524884223938, "start": 323, "tag": "USERNAME", "value": "marianoguerra" }, { "context": "human\"\n :bugs {:url \"https://github.com/yogthos/json-html/issues\"}\n :author \"Mariano Gue", "end": 1014, "score": 0.5381344556808472, "start": 1010, "tag": "USERNAME", "value": "ogth" }, { "context": "b.com/yogthos/json-html/issues\"}\n :author \"Mariano Guerra <mariano@marianoguerra.org>\"\n :contributors []\n ", "end": 1067, "score": 0.9998883008956909, "start": 1053, "tag": "NAME", "value": "Mariano Guerra" }, { "context": "on-html/issues\"}\n :author \"Mariano Guerra <mariano@marianoguerra.org>\"\n :contributors []\n :version \"0.1.0\"\n :m", "end": 1094, "score": 0.9999328851699829, "start": 1069, "tag": "EMAIL", "value": "mariano@marianoguerra.org" } ]
env/dev/cljs/json_html/test_page.cljs
rmcv/json-html
125
(ns json-html.test-page (:require [json-html.core :as core] [reagent.core :as r] [json-html.core :refer [edn->hiccup]])) (def data {:description "Convert\nJSON to human readable\r HTML" :tags ["DOM" "HTML" "JSON" "Pretty Print"] :repository {:type "git" :url "git://github.com/marianoguerra/json.human.js.git"} :license "MIT" :config {:emptyObject {} :what? "this object is just to show some extra stuff" :float 12.3 :emptyString "" :integer 42 :customization? ["customize the css prefix" "change the css file"] :htmlEntities " <- trailing <em> & </em> and some html " :how? ["add json.human.js" "add json.human.css" "???" "profit!"] :bool true :emptyArray []} :name "json.human" :bugs {:url "https://github.com/yogthos/json-html/issues"} :author "Mariano Guerra <mariano@marianoguerra.org>" :contributors [] :version "0.1.0" :main "json.human.js" :dependencies {:crel "1.0.0"}}) (defn home-page [] [:p "Hello World!"] [edn->hiccup data]) (defn mount-root [] (r/render [home-page] (.getElementById js/document "app"))) (defn init! [] (mount-root))
72738
(ns json-html.test-page (:require [json-html.core :as core] [reagent.core :as r] [json-html.core :refer [edn->hiccup]])) (def data {:description "Convert\nJSON to human readable\r HTML" :tags ["DOM" "HTML" "JSON" "Pretty Print"] :repository {:type "git" :url "git://github.com/marianoguerra/json.human.js.git"} :license "MIT" :config {:emptyObject {} :what? "this object is just to show some extra stuff" :float 12.3 :emptyString "" :integer 42 :customization? ["customize the css prefix" "change the css file"] :htmlEntities " <- trailing <em> & </em> and some html " :how? ["add json.human.js" "add json.human.css" "???" "profit!"] :bool true :emptyArray []} :name "json.human" :bugs {:url "https://github.com/yogthos/json-html/issues"} :author "<NAME> <<EMAIL>>" :contributors [] :version "0.1.0" :main "json.human.js" :dependencies {:crel "1.0.0"}}) (defn home-page [] [:p "Hello World!"] [edn->hiccup data]) (defn mount-root [] (r/render [home-page] (.getElementById js/document "app"))) (defn init! [] (mount-root))
true
(ns json-html.test-page (:require [json-html.core :as core] [reagent.core :as r] [json-html.core :refer [edn->hiccup]])) (def data {:description "Convert\nJSON to human readable\r HTML" :tags ["DOM" "HTML" "JSON" "Pretty Print"] :repository {:type "git" :url "git://github.com/marianoguerra/json.human.js.git"} :license "MIT" :config {:emptyObject {} :what? "this object is just to show some extra stuff" :float 12.3 :emptyString "" :integer 42 :customization? ["customize the css prefix" "change the css file"] :htmlEntities " <- trailing <em> & </em> and some html " :how? ["add json.human.js" "add json.human.css" "???" "profit!"] :bool true :emptyArray []} :name "json.human" :bugs {:url "https://github.com/yogthos/json-html/issues"} :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :contributors [] :version "0.1.0" :main "json.human.js" :dependencies {:crel "1.0.0"}}) (defn home-page [] [:p "Hello World!"] [edn->hiccup data]) (defn mount-root [] (r/render [home-page] (.getElementById js/document "app"))) (defn init! [] (mount-root))
[ { "context": "\" \"false\")} icon text ])\n\n(defn create [& {:keys [name linkedin github]}]\n [:div.navbar\n [button :act", "end": 258, "score": 0.7327079176902771, "start": 254, "tag": "USERNAME", "value": "name" }, { "context": "alse\")} icon text ])\n\n(defn create [& {:keys [name linkedin github]}]\n [:div.navbar\n [button :active tru", "end": 265, "score": 0.4416695535182953, "start": 259, "tag": "NAME", "value": "linked" } ]
src/website/navbar.cljs
abdulbahajaj/mywebsite
0
(ns website.navbar (:require [reagent.core :as r] [reagent.dom :as d])) (defn button [& {:keys [link icon text active] :or {active false}}] [:a.button {:href link :active (if active "true" "false")} icon text ]) (defn create [& {:keys [name linkedin github]}] [:div.navbar [button :active true :link "#" :icon [:i.icon.fas.fa-poll-h] :text "About me"] [button :link github :icon [:i.icon.fab.fa-github] :text "Github"] [button :link linkedin :icon [:i.icon.fab.fa-linkedin] :text "Linkedin"]])
27740
(ns website.navbar (:require [reagent.core :as r] [reagent.dom :as d])) (defn button [& {:keys [link icon text active] :or {active false}}] [:a.button {:href link :active (if active "true" "false")} icon text ]) (defn create [& {:keys [name <NAME>in github]}] [:div.navbar [button :active true :link "#" :icon [:i.icon.fas.fa-poll-h] :text "About me"] [button :link github :icon [:i.icon.fab.fa-github] :text "Github"] [button :link linkedin :icon [:i.icon.fab.fa-linkedin] :text "Linkedin"]])
true
(ns website.navbar (:require [reagent.core :as r] [reagent.dom :as d])) (defn button [& {:keys [link icon text active] :or {active false}}] [:a.button {:href link :active (if active "true" "false")} icon text ]) (defn create [& {:keys [name PI:NAME:<NAME>END_PIin github]}] [:div.navbar [button :active true :link "#" :icon [:i.icon.fas.fa-poll-h] :text "About me"] [button :link github :icon [:i.icon.fab.fa-github] :text "Github"] [button :link linkedin :icon [:i.icon.fab.fa-linkedin] :text "Linkedin"]])
[ { "context": "; Copyright (C) 2013, 2014 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch)\n; Re", "end": 44, "score": 0.9997953772544861, "start": 31, "tag": "NAME", "value": "Thomas Schank" }, { "context": "; Copyright (C) 2013, 2014 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch)\n; Released under the M", "end": 62, "score": 0.999921977519989, "start": 47, "tag": "EMAIL", "value": "DrTom@schank.ch" }, { "context": "C) 2013, 2014 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch)\n; Released under the MIT license.\n\n(ns json-roa.", "end": 88, "score": 0.9999212622642517, "start": 64, "tag": "EMAIL", "value": "Thomas.Schank@algocon.ch" } ]
src/json_roa/ring_middleware/response.clj
json-roa/json-roa_clj-utils
0
; Copyright (C) 2013, 2014 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch) ; Released under the MIT license. (ns json-roa.ring-middleware.response (:require [clojure.data.json :as json] [clojure.tools.logging :as logging] [clojure.walk] [ring.util.response :as response] )) (defn- default-json-encoder [data] (json/write-str data)) (defn- build-roa-json-response [response body json-encoder] (-> response (assoc :body (json-encoder body)) (response/header "Content-Type" "application/json-roa+json") (response/charset "UTF8"))) (defn- check-and-build-roa-json-response [response json-encoder] (if-not (coll? (:body response)) response (if-let [body (-> response :body clojure.walk/keywordize-keys)] (if (or (and (map? body) (:_json-roa body)) (and (coll? body) (-> body first :_json-roa))) (build-roa-json-response response body json-encoder) response) response))) (defn wrap "Ring middleware which converts responses with a body of either map or array containing a _json-roa signature into a json-roa+json response." [handler & {:keys [json-encoder] :or {json-encoder default-json-encoder}}] (fn [request] (let [response (handler request)] (check-and-build-roa-json-response response json-encoder))))
95388
; Copyright (C) 2013, 2014 Dr. <NAME> (<EMAIL>, <EMAIL>) ; Released under the MIT license. (ns json-roa.ring-middleware.response (:require [clojure.data.json :as json] [clojure.tools.logging :as logging] [clojure.walk] [ring.util.response :as response] )) (defn- default-json-encoder [data] (json/write-str data)) (defn- build-roa-json-response [response body json-encoder] (-> response (assoc :body (json-encoder body)) (response/header "Content-Type" "application/json-roa+json") (response/charset "UTF8"))) (defn- check-and-build-roa-json-response [response json-encoder] (if-not (coll? (:body response)) response (if-let [body (-> response :body clojure.walk/keywordize-keys)] (if (or (and (map? body) (:_json-roa body)) (and (coll? body) (-> body first :_json-roa))) (build-roa-json-response response body json-encoder) response) response))) (defn wrap "Ring middleware which converts responses with a body of either map or array containing a _json-roa signature into a json-roa+json response." [handler & {:keys [json-encoder] :or {json-encoder default-json-encoder}}] (fn [request] (let [response (handler request)] (check-and-build-roa-json-response response json-encoder))))
true
; Copyright (C) 2013, 2014 Dr. PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI, PI:EMAIL:<EMAIL>END_PI) ; Released under the MIT license. (ns json-roa.ring-middleware.response (:require [clojure.data.json :as json] [clojure.tools.logging :as logging] [clojure.walk] [ring.util.response :as response] )) (defn- default-json-encoder [data] (json/write-str data)) (defn- build-roa-json-response [response body json-encoder] (-> response (assoc :body (json-encoder body)) (response/header "Content-Type" "application/json-roa+json") (response/charset "UTF8"))) (defn- check-and-build-roa-json-response [response json-encoder] (if-not (coll? (:body response)) response (if-let [body (-> response :body clojure.walk/keywordize-keys)] (if (or (and (map? body) (:_json-roa body)) (and (coll? body) (-> body first :_json-roa))) (build-roa-json-response response body json-encoder) response) response))) (defn wrap "Ring middleware which converts responses with a body of either map or array containing a _json-roa signature into a json-roa+json response." [handler & {:keys [json-encoder] :or {json-encoder default-json-encoder}}] (fn [request] (let [response (handler request)] (check-and-build-roa-json-response response json-encoder))))
[ { "context": "; auth.clj (clojure-firefly)\n;; Copyright (c) 2014 Austin Zheng\n;; Released under the terms of the MIT License\n\n(", "end": 64, "score": 0.9997726678848267, "start": 52, "tag": "NAME", "value": "Austin Zheng" }, { "context": "time (not (db/blog-has-accounts?))\n username (:new-username params nil)\n password (:new-password params ni", "end": 3102, "score": 0.9035446047782898, "start": 3090, "tag": "USERNAME", "value": "new-username" } ]
src/clojure_blog/auth.clj
austinzheng/clojure-firefly
1
;; auth.clj (clojure-firefly) ;; Copyright (c) 2014 Austin Zheng ;; Released under the terms of the MIT License (ns clojure-blog.auth (:require [clojure-blog.session :as ss] [clojure-blog.auth-database :as db] [clojurewerkz.scrypt.core :as scrypt])) (declare admin?) (declare username) ;; SESSION-RELATED (defn make-session-info [session] "Build the 'session-info' map, which encapsulates session-specific info useful when rendering a response body" { :logged-in (admin? session) :username (:username session "(error)") }) (defn admin? [session] (:admin-session session nil)) ;; SECURITY (defn first-time? [] ; Here in case we want to do something a bit more robust in the future... (not (db/blog-has-accounts?))) (defn- acceptable-username? [username] "Returns true if a username meets criteria for being a valid username (e.g. length), false otherwise" (and (string? username) (> (count username) 4))) (defn- acceptable-password? [password] "Returns true if a password meets criteria for being a valid password, false otherwise" (and (string? password) (> (count password) 7))) (defn- hash-password [password] "Takes a password and returns the scrypt hashed version" (scrypt/encrypt password 16384 8 1)) (defn- validate-password [password pw-hash] "Returns true if a password is equivalent to a scrypt hash, false otherwise or upon error" (try (scrypt/verify password pw-hash) (catch IllegalArgumentException e false))) (defn credentials-valid? [params] "Takes in unsanitized params and validates the credentials within, if there are any. All error conditions cause this function to return false." (let [ username (:username params nil) password (:password params nil) well-formed (and (acceptable-username? username) (acceptable-password? password)) retrieved-hash (when well-formed (db/hash-for-username username)) ] (if (and well-formed (seq retrieved-hash)) (validate-password password retrieved-hash) false))) (defn- add-account [username password] "Given a *well-formed* username and password, try to add a new account. Returns true if successful, false otherwise" (let [pw-hash (hash-password password)] (if (seq pw-hash) (db/add-account username pw-hash) false))) ;; AUTH RESPONSE HANDLERS (defn post-login [session params] (let [ is-valid (credentials-valid? params) return-url (:return-url session "/") username (:username params nil) session (if is-valid (ss/session-added-admin-privileges session username) (ss/session-removed-admin-privileges session)) flash-msg (if is-valid "Logged in!" "Invalid credentials.")] (ss/redirect session flash-msg return-url))) (defn post-logout [session params] (let [ flash-msg (if (admin? session) "Logged out." "Already logged out!") session (ss/session-removed-admin-privileges session) return-url "/"] (ss/redirect session flash-msg return-url))) (defn post-first-time [session params] (let [ actually-first-time (not (db/blog-has-accounts?)) username (:new-username params nil) password (:new-password params nil) well-formed (and (acceptable-username? username) (acceptable-password? password)) account-added (if (and actually-first-time well-formed) (add-account username password) false) flash-msg (cond (not actually-first-time) "Error: you've already done first-time setup!" (not well-formed) "Error: the username and/or password you provided were invalid." (not account-added) "Error: couldn't add the new account to the database." :else "Success! Added your new administrator account.") ] (ss/redirect session flash-msg (:return-url session "/"))))
44531
;; auth.clj (clojure-firefly) ;; Copyright (c) 2014 <NAME> ;; Released under the terms of the MIT License (ns clojure-blog.auth (:require [clojure-blog.session :as ss] [clojure-blog.auth-database :as db] [clojurewerkz.scrypt.core :as scrypt])) (declare admin?) (declare username) ;; SESSION-RELATED (defn make-session-info [session] "Build the 'session-info' map, which encapsulates session-specific info useful when rendering a response body" { :logged-in (admin? session) :username (:username session "(error)") }) (defn admin? [session] (:admin-session session nil)) ;; SECURITY (defn first-time? [] ; Here in case we want to do something a bit more robust in the future... (not (db/blog-has-accounts?))) (defn- acceptable-username? [username] "Returns true if a username meets criteria for being a valid username (e.g. length), false otherwise" (and (string? username) (> (count username) 4))) (defn- acceptable-password? [password] "Returns true if a password meets criteria for being a valid password, false otherwise" (and (string? password) (> (count password) 7))) (defn- hash-password [password] "Takes a password and returns the scrypt hashed version" (scrypt/encrypt password 16384 8 1)) (defn- validate-password [password pw-hash] "Returns true if a password is equivalent to a scrypt hash, false otherwise or upon error" (try (scrypt/verify password pw-hash) (catch IllegalArgumentException e false))) (defn credentials-valid? [params] "Takes in unsanitized params and validates the credentials within, if there are any. All error conditions cause this function to return false." (let [ username (:username params nil) password (:password params nil) well-formed (and (acceptable-username? username) (acceptable-password? password)) retrieved-hash (when well-formed (db/hash-for-username username)) ] (if (and well-formed (seq retrieved-hash)) (validate-password password retrieved-hash) false))) (defn- add-account [username password] "Given a *well-formed* username and password, try to add a new account. Returns true if successful, false otherwise" (let [pw-hash (hash-password password)] (if (seq pw-hash) (db/add-account username pw-hash) false))) ;; AUTH RESPONSE HANDLERS (defn post-login [session params] (let [ is-valid (credentials-valid? params) return-url (:return-url session "/") username (:username params nil) session (if is-valid (ss/session-added-admin-privileges session username) (ss/session-removed-admin-privileges session)) flash-msg (if is-valid "Logged in!" "Invalid credentials.")] (ss/redirect session flash-msg return-url))) (defn post-logout [session params] (let [ flash-msg (if (admin? session) "Logged out." "Already logged out!") session (ss/session-removed-admin-privileges session) return-url "/"] (ss/redirect session flash-msg return-url))) (defn post-first-time [session params] (let [ actually-first-time (not (db/blog-has-accounts?)) username (:new-username params nil) password (:new-password params nil) well-formed (and (acceptable-username? username) (acceptable-password? password)) account-added (if (and actually-first-time well-formed) (add-account username password) false) flash-msg (cond (not actually-first-time) "Error: you've already done first-time setup!" (not well-formed) "Error: the username and/or password you provided were invalid." (not account-added) "Error: couldn't add the new account to the database." :else "Success! Added your new administrator account.") ] (ss/redirect session flash-msg (:return-url session "/"))))
true
;; auth.clj (clojure-firefly) ;; Copyright (c) 2014 PI:NAME:<NAME>END_PI ;; Released under the terms of the MIT License (ns clojure-blog.auth (:require [clojure-blog.session :as ss] [clojure-blog.auth-database :as db] [clojurewerkz.scrypt.core :as scrypt])) (declare admin?) (declare username) ;; SESSION-RELATED (defn make-session-info [session] "Build the 'session-info' map, which encapsulates session-specific info useful when rendering a response body" { :logged-in (admin? session) :username (:username session "(error)") }) (defn admin? [session] (:admin-session session nil)) ;; SECURITY (defn first-time? [] ; Here in case we want to do something a bit more robust in the future... (not (db/blog-has-accounts?))) (defn- acceptable-username? [username] "Returns true if a username meets criteria for being a valid username (e.g. length), false otherwise" (and (string? username) (> (count username) 4))) (defn- acceptable-password? [password] "Returns true if a password meets criteria for being a valid password, false otherwise" (and (string? password) (> (count password) 7))) (defn- hash-password [password] "Takes a password and returns the scrypt hashed version" (scrypt/encrypt password 16384 8 1)) (defn- validate-password [password pw-hash] "Returns true if a password is equivalent to a scrypt hash, false otherwise or upon error" (try (scrypt/verify password pw-hash) (catch IllegalArgumentException e false))) (defn credentials-valid? [params] "Takes in unsanitized params and validates the credentials within, if there are any. All error conditions cause this function to return false." (let [ username (:username params nil) password (:password params nil) well-formed (and (acceptable-username? username) (acceptable-password? password)) retrieved-hash (when well-formed (db/hash-for-username username)) ] (if (and well-formed (seq retrieved-hash)) (validate-password password retrieved-hash) false))) (defn- add-account [username password] "Given a *well-formed* username and password, try to add a new account. Returns true if successful, false otherwise" (let [pw-hash (hash-password password)] (if (seq pw-hash) (db/add-account username pw-hash) false))) ;; AUTH RESPONSE HANDLERS (defn post-login [session params] (let [ is-valid (credentials-valid? params) return-url (:return-url session "/") username (:username params nil) session (if is-valid (ss/session-added-admin-privileges session username) (ss/session-removed-admin-privileges session)) flash-msg (if is-valid "Logged in!" "Invalid credentials.")] (ss/redirect session flash-msg return-url))) (defn post-logout [session params] (let [ flash-msg (if (admin? session) "Logged out." "Already logged out!") session (ss/session-removed-admin-privileges session) return-url "/"] (ss/redirect session flash-msg return-url))) (defn post-first-time [session params] (let [ actually-first-time (not (db/blog-has-accounts?)) username (:new-username params nil) password (:new-password params nil) well-formed (and (acceptable-username? username) (acceptable-password? password)) account-added (if (and actually-first-time well-formed) (add-account username password) false) flash-msg (cond (not actually-first-time) "Error: you've already done first-time setup!" (not well-formed) "Error: the username and/or password you provided were invalid." (not account-added) "Error: couldn't add the new account to the database." :else "Success! Added your new administrator account.") ] (ss/redirect session flash-msg (:return-url session "/"))))
[ { "context": "fmethod for performance experiments.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017", "end": 266, "score": 0.7509092092514038, "start": 263, "tag": "EMAIL", "value": "pal" }, { "context": "thod for performance experiments.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-06-02", "end": 272, "score": 0.5456714630126953, "start": 266, "tag": "NAME", "value": "isades" }, { "context": "or performance experiments.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-06-02\"\n :vers", "end": 282, "score": 0.6556019186973572, "start": 273, "tag": "EMAIL", "value": "dot lakes" }, { "context": "e experiments.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-06-02\"\n :version \"2017-06-03\"}", "end": 299, "score": 0.6793942451477051, "start": 286, "tag": "EMAIL", "value": "gmail dot com" } ]
src/main/clojure/palisades/lakes/elements/generic/multi.clj
palisades-lakes/les-elemens
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.generic.multi {:doc "Fork of defmulti/defmethod for performance experiments." :author "palisades dot lakes at gmail dot com" :since "2017-06-02" :version "2017-06-03"} (:refer-clojure :exclude [defmulti defmethod remove-all-methods remove-method prefer-method methods get-method prefers])) ;;---------------------------------------------------------------- (defn ^:private check-valid-options "Throws an exception if the given option map contains keys not listed as valid, else returns nil." [options & valid-keys] (when (seq (apply disj (apply hash-set (keys options)) valid-keys)) (throw (IllegalArgumentException. ^String (apply str "Only these options are valid: " (first valid-keys) (map #(str ", " %) (rest valid-keys))))))) ;;---------------------------------------------------------------- (defmacro defmulti "Creates a new multimethod with the associated dispatch function. The docstring and attr-map are optional. Options are key-value pairs and may be one of: :default The default dispatch value, defaults to :default" {:arglists '([name docstring? attr-map? dispatch-fn & options]) :added "1.0"} [mm-name & options] (let [docstring (if (string? (first options)) (first options) nil) options (if (string? (first options)) (next options) options) m (if (map? (first options)) (first options) {}) options (if (map? (first options)) (next options) options) dispatch-fn (first options) options (next options) m (if docstring (assoc m :doc docstring) m) m (if (meta mm-name) (conj (meta mm-name) m) m)] (when (= (count options) 1) (throw (Exception. "The syntax for defmulti has changed. Example: (defmulti name dispatch-fn :default dispatch-value)"))) (let [options (apply hash-map options) default (get options :default :default) ] (check-valid-options options :default :hierarchy) `(let [v# (def ~mm-name)] (when-not (and (.hasRoot v#) (instance? palisades.lakes.elements.java.generic.MultiFn (deref v#))) (def ~(with-meta mm-name m) (new palisades.lakes.elements.java.generic.MultiFn ~(name mm-name) ~dispatch-fn ~default))))))) ;;---------------------------------------------------------------- (defmacro defmethod "Creates and installs a new method of multimethod associated with dispatch-value. " {:added "1.0"} [multifn dispatch-val & fn-tail] `(. ~(with-meta multifn {:tag 'palisades.lakes.elements.java.generic.MultiFn}) addMethod ~dispatch-val (fn ~@fn-tail))) (defn remove-all-methods "Removes all of the methods of multimethod." {:added "1.2" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn] (.reset multifn)) (defn remove-method "Removes the method of multimethod associated with dispatch-value." {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn dispatch-val] (. multifn removeMethod dispatch-val)) (defn prefer-method "Causes the multimethod to prefer matches of dispatch-val-x over dispatch-val-y when there is a conflict" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn dispatch-val-x dispatch-val-y] (. multifn preferMethod dispatch-val-x dispatch-val-y)) (defn methods "Given a multimethod, returns a map of dispatch values -> dispatch fns" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn] (.getMethodTable multifn)) (defn get-method "Given a multimethod and a dispatch value, returns the dispatch fn that would apply to that value, or nil if none apply and no default" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn dispatch-val] (.getMethod multifn dispatch-val)) (defn prefers "Given a multimethod, returns a map of preferred value -> set of other values" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn] (.getPreferTable multifn)) ;;----------------------------------------------------------------
52109
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.generic.multi {:doc "Fork of defmulti/defmethod for performance experiments." :author "<EMAIL> <NAME> <EMAIL> at <EMAIL>" :since "2017-06-02" :version "2017-06-03"} (:refer-clojure :exclude [defmulti defmethod remove-all-methods remove-method prefer-method methods get-method prefers])) ;;---------------------------------------------------------------- (defn ^:private check-valid-options "Throws an exception if the given option map contains keys not listed as valid, else returns nil." [options & valid-keys] (when (seq (apply disj (apply hash-set (keys options)) valid-keys)) (throw (IllegalArgumentException. ^String (apply str "Only these options are valid: " (first valid-keys) (map #(str ", " %) (rest valid-keys))))))) ;;---------------------------------------------------------------- (defmacro defmulti "Creates a new multimethod with the associated dispatch function. The docstring and attr-map are optional. Options are key-value pairs and may be one of: :default The default dispatch value, defaults to :default" {:arglists '([name docstring? attr-map? dispatch-fn & options]) :added "1.0"} [mm-name & options] (let [docstring (if (string? (first options)) (first options) nil) options (if (string? (first options)) (next options) options) m (if (map? (first options)) (first options) {}) options (if (map? (first options)) (next options) options) dispatch-fn (first options) options (next options) m (if docstring (assoc m :doc docstring) m) m (if (meta mm-name) (conj (meta mm-name) m) m)] (when (= (count options) 1) (throw (Exception. "The syntax for defmulti has changed. Example: (defmulti name dispatch-fn :default dispatch-value)"))) (let [options (apply hash-map options) default (get options :default :default) ] (check-valid-options options :default :hierarchy) `(let [v# (def ~mm-name)] (when-not (and (.hasRoot v#) (instance? palisades.lakes.elements.java.generic.MultiFn (deref v#))) (def ~(with-meta mm-name m) (new palisades.lakes.elements.java.generic.MultiFn ~(name mm-name) ~dispatch-fn ~default))))))) ;;---------------------------------------------------------------- (defmacro defmethod "Creates and installs a new method of multimethod associated with dispatch-value. " {:added "1.0"} [multifn dispatch-val & fn-tail] `(. ~(with-meta multifn {:tag 'palisades.lakes.elements.java.generic.MultiFn}) addMethod ~dispatch-val (fn ~@fn-tail))) (defn remove-all-methods "Removes all of the methods of multimethod." {:added "1.2" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn] (.reset multifn)) (defn remove-method "Removes the method of multimethod associated with dispatch-value." {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn dispatch-val] (. multifn removeMethod dispatch-val)) (defn prefer-method "Causes the multimethod to prefer matches of dispatch-val-x over dispatch-val-y when there is a conflict" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn dispatch-val-x dispatch-val-y] (. multifn preferMethod dispatch-val-x dispatch-val-y)) (defn methods "Given a multimethod, returns a map of dispatch values -> dispatch fns" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn] (.getMethodTable multifn)) (defn get-method "Given a multimethod and a dispatch value, returns the dispatch fn that would apply to that value, or nil if none apply and no default" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn dispatch-val] (.getMethod multifn dispatch-val)) (defn prefers "Given a multimethod, returns a map of preferred value -> set of other values" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn] (.getPreferTable multifn)) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.generic.multi {:doc "Fork of defmulti/defmethod for performance experiments." :author "PI:EMAIL:<EMAIL>END_PI PI:NAME:<NAME>END_PI PI:EMAIL:<EMAIL>END_PI at PI:EMAIL:<EMAIL>END_PI" :since "2017-06-02" :version "2017-06-03"} (:refer-clojure :exclude [defmulti defmethod remove-all-methods remove-method prefer-method methods get-method prefers])) ;;---------------------------------------------------------------- (defn ^:private check-valid-options "Throws an exception if the given option map contains keys not listed as valid, else returns nil." [options & valid-keys] (when (seq (apply disj (apply hash-set (keys options)) valid-keys)) (throw (IllegalArgumentException. ^String (apply str "Only these options are valid: " (first valid-keys) (map #(str ", " %) (rest valid-keys))))))) ;;---------------------------------------------------------------- (defmacro defmulti "Creates a new multimethod with the associated dispatch function. The docstring and attr-map are optional. Options are key-value pairs and may be one of: :default The default dispatch value, defaults to :default" {:arglists '([name docstring? attr-map? dispatch-fn & options]) :added "1.0"} [mm-name & options] (let [docstring (if (string? (first options)) (first options) nil) options (if (string? (first options)) (next options) options) m (if (map? (first options)) (first options) {}) options (if (map? (first options)) (next options) options) dispatch-fn (first options) options (next options) m (if docstring (assoc m :doc docstring) m) m (if (meta mm-name) (conj (meta mm-name) m) m)] (when (= (count options) 1) (throw (Exception. "The syntax for defmulti has changed. Example: (defmulti name dispatch-fn :default dispatch-value)"))) (let [options (apply hash-map options) default (get options :default :default) ] (check-valid-options options :default :hierarchy) `(let [v# (def ~mm-name)] (when-not (and (.hasRoot v#) (instance? palisades.lakes.elements.java.generic.MultiFn (deref v#))) (def ~(with-meta mm-name m) (new palisades.lakes.elements.java.generic.MultiFn ~(name mm-name) ~dispatch-fn ~default))))))) ;;---------------------------------------------------------------- (defmacro defmethod "Creates and installs a new method of multimethod associated with dispatch-value. " {:added "1.0"} [multifn dispatch-val & fn-tail] `(. ~(with-meta multifn {:tag 'palisades.lakes.elements.java.generic.MultiFn}) addMethod ~dispatch-val (fn ~@fn-tail))) (defn remove-all-methods "Removes all of the methods of multimethod." {:added "1.2" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn] (.reset multifn)) (defn remove-method "Removes the method of multimethod associated with dispatch-value." {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn dispatch-val] (. multifn removeMethod dispatch-val)) (defn prefer-method "Causes the multimethod to prefer matches of dispatch-val-x over dispatch-val-y when there is a conflict" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn dispatch-val-x dispatch-val-y] (. multifn preferMethod dispatch-val-x dispatch-val-y)) (defn methods "Given a multimethod, returns a map of dispatch values -> dispatch fns" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn] (.getMethodTable multifn)) (defn get-method "Given a multimethod and a dispatch value, returns the dispatch fn that would apply to that value, or nil if none apply and no default" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn dispatch-val] (.getMethod multifn dispatch-val)) (defn prefers "Given a multimethod, returns a map of preferred value -> set of other values" {:added "1.0" :static true} [^palisades.lakes.elements.java.generic.MultiFn multifn] (.getPreferTable multifn)) ;;----------------------------------------------------------------
[ { "context": " \"A test-case for take operator.\"\n :author \"Vladimir Tsanev\"}\n reactor-core.publisher.take-test\n #?(:cljs (", "end": 677, "score": 0.9998339414596558, "start": 662, "tag": "NAME", "value": "Vladimir Tsanev" } ]
test/reactor_core/publisher/take_test.cljc
jaju/reactor-core-clojure
2
; ; Copyright 2018 the original author or authors. ; ; 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 ^{:doc "A test-case for take operator." :author "Vladimir Tsanev"} reactor-core.publisher.take-test #?(:cljs (:require-macros [cljs.test :refer [async]]) :clj (:use [reactor-core.test :only [async]])) (:require #?(:cljs [cljs.test :as t] :clj [clojure.test :as t]) [reactor-core.publisher :as reactor])) (t/deftest normal (async done (let [values (atom [])] (->> (reactor/range 1 10) (reactor/take 5) (reactor/subscribe (fn [value] (swap! values conj value)) (fn [_] (t/is false)) (fn [] (t/is (= @values [1 2 3 4 5])) (done))))))) (t/deftest take-zero (async done (->> (reactor/range 1 10) (reactor/take 0) (reactor/subscribe (fn [_] (t/is false)) (fn [_] (t/is false)) (fn [] (t/is true) (done))))))
58740
; ; Copyright 2018 the original author or authors. ; ; 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 ^{:doc "A test-case for take operator." :author "<NAME>"} reactor-core.publisher.take-test #?(:cljs (:require-macros [cljs.test :refer [async]]) :clj (:use [reactor-core.test :only [async]])) (:require #?(:cljs [cljs.test :as t] :clj [clojure.test :as t]) [reactor-core.publisher :as reactor])) (t/deftest normal (async done (let [values (atom [])] (->> (reactor/range 1 10) (reactor/take 5) (reactor/subscribe (fn [value] (swap! values conj value)) (fn [_] (t/is false)) (fn [] (t/is (= @values [1 2 3 4 5])) (done))))))) (t/deftest take-zero (async done (->> (reactor/range 1 10) (reactor/take 0) (reactor/subscribe (fn [_] (t/is false)) (fn [_] (t/is false)) (fn [] (t/is true) (done))))))
true
; ; Copyright 2018 the original author or authors. ; ; 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 ^{:doc "A test-case for take operator." :author "PI:NAME:<NAME>END_PI"} reactor-core.publisher.take-test #?(:cljs (:require-macros [cljs.test :refer [async]]) :clj (:use [reactor-core.test :only [async]])) (:require #?(:cljs [cljs.test :as t] :clj [clojure.test :as t]) [reactor-core.publisher :as reactor])) (t/deftest normal (async done (let [values (atom [])] (->> (reactor/range 1 10) (reactor/take 5) (reactor/subscribe (fn [value] (swap! values conj value)) (fn [_] (t/is false)) (fn [] (t/is (= @values [1 2 3 4 5])) (done))))))) (t/deftest take-zero (async done (->> (reactor/range 1 10) (reactor/take 0) (reactor/subscribe (fn [_] (t/is false)) (fn [_] (t/is false)) (fn [] (t/is true) (done))))))
[ { "context": "; blog.clj (clojure-firefly)\n;; Copyright (c) 2014 Austin Zheng\n;; Released under the terms of the MIT License\n\n(", "end": 64, "score": 0.9997556805610657, "start": 52, "tag": "NAME", "value": "Austin Zheng" } ]
src/clojure_blog/blog.clj
austinzheng/clojure-firefly
1
;; blog.clj (clojure-firefly) ;; Copyright (c) 2014 Austin Zheng ;; Released under the terms of the MIT License (ns clojure-blog.blog (:require [clojure-blog.tags :as tags] [clojure-blog.session :as ss] [clojure-blog.blog-database :as db] [clojure-blog.blog-template :as bt] [clojure-blog.template :as t] [clojure-blog.auth :as auth] [clojure-blog.routes :as r] [clojure-blog.util :as util] [clojure-blog.settings :as settings] [ring.middleware.flash :as flash])) ;; Utility functions (defn- next-route [start number total] (let [ next-start (+ start number) next-number (min (- total next-start) settings/posts-per-page) has-next (> total next-start)] (when has-next (r/blog-route next-start next-number)))) (defn- prev-route [start number total] (let [ prev-start (max 0 (- start settings/posts-per-page)) prev-number (min start settings/posts-per-page) has-prev (> start 0)] (when has-prev (r/blog-route prev-start prev-number)))) (defn- nav-description [start number] (if (= 1 number) (reduce str ["Currently showing post " (+ 1 start)]) (reduce str ["Currently showing posts " (+ 1 start) " through " (+ start number)]))) (defn- tag-description [tag] (reduce str ["Currently showing posts for tag '" tag "'"])) ;; 'action-' functions handle processing/state mutation related to an action. (defn action-create-post! [session params] "Create a post and save it to the database" (let [ return-url (:return-url session "/") post-title (:post-title params "") post-content (:post-content params "") raw-post-tags (:post-tags params nil) post-tags (when raw-post-tags (tags/split-raw-tags raw-post-tags)) can-create (and (seq post-title) (seq post-content)) post-id (when can-create (db/add-post! post-title post-content post-tags)) flash-msg (if post-id "Post created." "Couldn't create post!")] (ss/redirect session flash-msg return-url))) (defn action-edit-post! [session params] "Edit an existing post" (let [ new-title (:post-title params nil) new-content (:post-content params nil) post-id (:post-id params nil) raw-old-tags (:post-old-tags params nil) raw-new-tags (:post-tags params nil) old-tags (when raw-old-tags (tags/split-raw-tags raw-old-tags)) new-tags (when raw-new-tags (tags/split-raw-tags raw-new-tags)) can-edit (and (seq new-title) (seq new-content) (seq post-id)) success (when can-edit (db/edit-post! post-id new-title new-content new-tags old-tags)) flash-msg (if success "Post edited." "Couldn't edit post!")] (ss/redirect session flash-msg (:return-url session "/")))) (defn action-create-preview [session params] (let [ session-info (auth/make-session-info session) title (:post-title params) content (:post-content params nil) post-id (:post-id params nil) tags (:post-tags params nil) old-tags (:post-old-tags params nil) can-submit (and (seq title) (seq content)) response-body (bt/post-preview session-info nil can-submit post-id title content tags old-tags)] { :body response-body :session session })) (defn action-resume-editing [session params] (let [ session-info (auth/make-session-info session) post-id (:post-id params nil) show-delete (not (nil? post-id)) title (:post-title params) content (:post-content params) tags (:post-tags params nil) old-tags (:post-old-tags params nil) response-body (bt/post-compose session-info nil post-id show-delete title content tags old-tags)] { :body response-body :session session })) (defn action-delete-post! [session post-id] (let [ success (db/delete-post! post-id) flash-msg (if success "Post deleted." "Error deleting post.") return-url "/blog"] (ss/redirect session flash-msg return-url))) ;; 'post-' functions generate the :body of the response to a POST request. ; Optimally, delete should be a POST instead of a GET, w/o using js. (defn post-delete! [session params] "Delete a post and return the entire response map" (action-delete-post! session (:id params))) (defn post-npsubmit! [session params] "Handle the user pressing the 'preview', 'delete', or 'submit' buttons on the compose page" (cond (contains? params :add-post) (action-create-post! session params) (contains? params :edit-post) (action-edit-post! session params) (contains? params :preview) (action-create-preview session params) (contains? params :continue-editing) (action-resume-editing session params) (contains? params :delete) (action-delete-post! session (:post-id params)) :else (ss/redirect session "An error occurred" (:return-url session "/")))) ;; 'format-' functions generate HTML for a given blog page. (defn format-composer-edit [session-info flash-msg post-id post-map] (reduce str (bt/build-composer session-info flash-msg post-id post-map))) (defn format-composer-new [session-info flash-msg] (reduce str (bt/build-composer session-info flash-msg nil nil))) (defn format-post [session-info flash-msg post-id post-map] "Given raw data from the database, generate the HTML for a single post" (reduce str (bt/post-page session-info flash-msg post-id post-map))) (defn format-blog [session-info flash-msg post-id-list post-map-list start number total] "Given raw data from the database, generate the HTML for a page of posts" (let [ c-total (if (nil? total) 0 total) desc (when (> c-total 0) (nav-description start number)) prev-url (when (> c-total 0) (prev-route start number total)) next-url (when (> c-total 0) (next-route start number total)) no-posts-msg "(No posts)"] (reduce str (bt/blog-page session-info flash-msg post-id-list post-map-list no-posts-msg prev-url "Newer" desc next-url "Older")))) (defn format-blog-for-tag [session-info flash-msg post-id-list post-map-list tag] "Given raw data from the database, generate the HTML for a page of posts" (let [ desc (tag-description tag)] (reduce str (bt/blog-page session-info flash-msg post-id-list post-map-list "(No posts)" nil nil desc nil nil)))) (defn format-archive [session-info flash-msg metadata-list] "Given raw data from the database, generate the HTML for the posts archive page" (reduce str (bt/archive-page session-info flash-msg metadata-list "(No posts)"))) ;; 'get-' functions provide an interface for getting the :body of a response to a GET request. (defn get-post-composer [session-info flash-msg post-id] (if post-id (let [post-map (db/get-post post-id)] (if post-map (format-composer-edit session-info flash-msg post-id post-map) (t/error-page session-info flash-msg "Cannot edit post. Invalid post ID." nil nil))) (format-composer-new session-info flash-msg))) (defn get-post [session-info flash-msg post-id] "Given a raw ID, retrieve a post from the database" (let [post-map (db/get-post post-id)] (if post-map (format-post session-info flash-msg post-id post-map) (t/error-page session-info flash-msg "Could not retrieve post." nil nil)))) (defn get-posts [session-info flash-msg raw-start raw-number] "Given a start index and a number of posts, return as many posts as possible" (let [ start (util/parse-integer raw-start) n (util/parse-integer raw-number) no-posts (= 0 (db/total-post-count)) [post-map-list {:keys [id-seq post-count]}] (when (and start n) (db/get-posts start n)) final-count (if no-posts 0 post-count)] (if (or no-posts post-map-list) (format-blog session-info flash-msg id-seq post-map-list start (count post-map-list) final-count) (t/error-page session-info flash-msg "Could not retrieve the requested posts." nil nil)))) (defn get-posts-for-tag [session-info flash-msg tag] "Given a tag, return the posts for that tag or an error." (let [ valid (tags/tag-valid? tag) [post-map-list {:keys [id-seq]}] (when valid (db/get-posts-for-tag tag)) error-msg (reduce str ["Could not retrieve posts for the tag '" tag "'"])] (if post-map-list (format-blog-for-tag session-info flash-msg id-seq post-map-list tag) (t/error-page session-info flash-msg error-msg nil nil)))) (defn get-archive [session-info flash-msg] "Return the post archive." (let [ metadata-list (db/get-all-metadata) error-msg "Could not retrieve blog archive"] (if metadata-list (format-archive session-info flash-msg metadata-list) (t/error-page session-info flash-msg error-msg nil nil))))
116670
;; blog.clj (clojure-firefly) ;; Copyright (c) 2014 <NAME> ;; Released under the terms of the MIT License (ns clojure-blog.blog (:require [clojure-blog.tags :as tags] [clojure-blog.session :as ss] [clojure-blog.blog-database :as db] [clojure-blog.blog-template :as bt] [clojure-blog.template :as t] [clojure-blog.auth :as auth] [clojure-blog.routes :as r] [clojure-blog.util :as util] [clojure-blog.settings :as settings] [ring.middleware.flash :as flash])) ;; Utility functions (defn- next-route [start number total] (let [ next-start (+ start number) next-number (min (- total next-start) settings/posts-per-page) has-next (> total next-start)] (when has-next (r/blog-route next-start next-number)))) (defn- prev-route [start number total] (let [ prev-start (max 0 (- start settings/posts-per-page)) prev-number (min start settings/posts-per-page) has-prev (> start 0)] (when has-prev (r/blog-route prev-start prev-number)))) (defn- nav-description [start number] (if (= 1 number) (reduce str ["Currently showing post " (+ 1 start)]) (reduce str ["Currently showing posts " (+ 1 start) " through " (+ start number)]))) (defn- tag-description [tag] (reduce str ["Currently showing posts for tag '" tag "'"])) ;; 'action-' functions handle processing/state mutation related to an action. (defn action-create-post! [session params] "Create a post and save it to the database" (let [ return-url (:return-url session "/") post-title (:post-title params "") post-content (:post-content params "") raw-post-tags (:post-tags params nil) post-tags (when raw-post-tags (tags/split-raw-tags raw-post-tags)) can-create (and (seq post-title) (seq post-content)) post-id (when can-create (db/add-post! post-title post-content post-tags)) flash-msg (if post-id "Post created." "Couldn't create post!")] (ss/redirect session flash-msg return-url))) (defn action-edit-post! [session params] "Edit an existing post" (let [ new-title (:post-title params nil) new-content (:post-content params nil) post-id (:post-id params nil) raw-old-tags (:post-old-tags params nil) raw-new-tags (:post-tags params nil) old-tags (when raw-old-tags (tags/split-raw-tags raw-old-tags)) new-tags (when raw-new-tags (tags/split-raw-tags raw-new-tags)) can-edit (and (seq new-title) (seq new-content) (seq post-id)) success (when can-edit (db/edit-post! post-id new-title new-content new-tags old-tags)) flash-msg (if success "Post edited." "Couldn't edit post!")] (ss/redirect session flash-msg (:return-url session "/")))) (defn action-create-preview [session params] (let [ session-info (auth/make-session-info session) title (:post-title params) content (:post-content params nil) post-id (:post-id params nil) tags (:post-tags params nil) old-tags (:post-old-tags params nil) can-submit (and (seq title) (seq content)) response-body (bt/post-preview session-info nil can-submit post-id title content tags old-tags)] { :body response-body :session session })) (defn action-resume-editing [session params] (let [ session-info (auth/make-session-info session) post-id (:post-id params nil) show-delete (not (nil? post-id)) title (:post-title params) content (:post-content params) tags (:post-tags params nil) old-tags (:post-old-tags params nil) response-body (bt/post-compose session-info nil post-id show-delete title content tags old-tags)] { :body response-body :session session })) (defn action-delete-post! [session post-id] (let [ success (db/delete-post! post-id) flash-msg (if success "Post deleted." "Error deleting post.") return-url "/blog"] (ss/redirect session flash-msg return-url))) ;; 'post-' functions generate the :body of the response to a POST request. ; Optimally, delete should be a POST instead of a GET, w/o using js. (defn post-delete! [session params] "Delete a post and return the entire response map" (action-delete-post! session (:id params))) (defn post-npsubmit! [session params] "Handle the user pressing the 'preview', 'delete', or 'submit' buttons on the compose page" (cond (contains? params :add-post) (action-create-post! session params) (contains? params :edit-post) (action-edit-post! session params) (contains? params :preview) (action-create-preview session params) (contains? params :continue-editing) (action-resume-editing session params) (contains? params :delete) (action-delete-post! session (:post-id params)) :else (ss/redirect session "An error occurred" (:return-url session "/")))) ;; 'format-' functions generate HTML for a given blog page. (defn format-composer-edit [session-info flash-msg post-id post-map] (reduce str (bt/build-composer session-info flash-msg post-id post-map))) (defn format-composer-new [session-info flash-msg] (reduce str (bt/build-composer session-info flash-msg nil nil))) (defn format-post [session-info flash-msg post-id post-map] "Given raw data from the database, generate the HTML for a single post" (reduce str (bt/post-page session-info flash-msg post-id post-map))) (defn format-blog [session-info flash-msg post-id-list post-map-list start number total] "Given raw data from the database, generate the HTML for a page of posts" (let [ c-total (if (nil? total) 0 total) desc (when (> c-total 0) (nav-description start number)) prev-url (when (> c-total 0) (prev-route start number total)) next-url (when (> c-total 0) (next-route start number total)) no-posts-msg "(No posts)"] (reduce str (bt/blog-page session-info flash-msg post-id-list post-map-list no-posts-msg prev-url "Newer" desc next-url "Older")))) (defn format-blog-for-tag [session-info flash-msg post-id-list post-map-list tag] "Given raw data from the database, generate the HTML for a page of posts" (let [ desc (tag-description tag)] (reduce str (bt/blog-page session-info flash-msg post-id-list post-map-list "(No posts)" nil nil desc nil nil)))) (defn format-archive [session-info flash-msg metadata-list] "Given raw data from the database, generate the HTML for the posts archive page" (reduce str (bt/archive-page session-info flash-msg metadata-list "(No posts)"))) ;; 'get-' functions provide an interface for getting the :body of a response to a GET request. (defn get-post-composer [session-info flash-msg post-id] (if post-id (let [post-map (db/get-post post-id)] (if post-map (format-composer-edit session-info flash-msg post-id post-map) (t/error-page session-info flash-msg "Cannot edit post. Invalid post ID." nil nil))) (format-composer-new session-info flash-msg))) (defn get-post [session-info flash-msg post-id] "Given a raw ID, retrieve a post from the database" (let [post-map (db/get-post post-id)] (if post-map (format-post session-info flash-msg post-id post-map) (t/error-page session-info flash-msg "Could not retrieve post." nil nil)))) (defn get-posts [session-info flash-msg raw-start raw-number] "Given a start index and a number of posts, return as many posts as possible" (let [ start (util/parse-integer raw-start) n (util/parse-integer raw-number) no-posts (= 0 (db/total-post-count)) [post-map-list {:keys [id-seq post-count]}] (when (and start n) (db/get-posts start n)) final-count (if no-posts 0 post-count)] (if (or no-posts post-map-list) (format-blog session-info flash-msg id-seq post-map-list start (count post-map-list) final-count) (t/error-page session-info flash-msg "Could not retrieve the requested posts." nil nil)))) (defn get-posts-for-tag [session-info flash-msg tag] "Given a tag, return the posts for that tag or an error." (let [ valid (tags/tag-valid? tag) [post-map-list {:keys [id-seq]}] (when valid (db/get-posts-for-tag tag)) error-msg (reduce str ["Could not retrieve posts for the tag '" tag "'"])] (if post-map-list (format-blog-for-tag session-info flash-msg id-seq post-map-list tag) (t/error-page session-info flash-msg error-msg nil nil)))) (defn get-archive [session-info flash-msg] "Return the post archive." (let [ metadata-list (db/get-all-metadata) error-msg "Could not retrieve blog archive"] (if metadata-list (format-archive session-info flash-msg metadata-list) (t/error-page session-info flash-msg error-msg nil nil))))
true
;; blog.clj (clojure-firefly) ;; Copyright (c) 2014 PI:NAME:<NAME>END_PI ;; Released under the terms of the MIT License (ns clojure-blog.blog (:require [clojure-blog.tags :as tags] [clojure-blog.session :as ss] [clojure-blog.blog-database :as db] [clojure-blog.blog-template :as bt] [clojure-blog.template :as t] [clojure-blog.auth :as auth] [clojure-blog.routes :as r] [clojure-blog.util :as util] [clojure-blog.settings :as settings] [ring.middleware.flash :as flash])) ;; Utility functions (defn- next-route [start number total] (let [ next-start (+ start number) next-number (min (- total next-start) settings/posts-per-page) has-next (> total next-start)] (when has-next (r/blog-route next-start next-number)))) (defn- prev-route [start number total] (let [ prev-start (max 0 (- start settings/posts-per-page)) prev-number (min start settings/posts-per-page) has-prev (> start 0)] (when has-prev (r/blog-route prev-start prev-number)))) (defn- nav-description [start number] (if (= 1 number) (reduce str ["Currently showing post " (+ 1 start)]) (reduce str ["Currently showing posts " (+ 1 start) " through " (+ start number)]))) (defn- tag-description [tag] (reduce str ["Currently showing posts for tag '" tag "'"])) ;; 'action-' functions handle processing/state mutation related to an action. (defn action-create-post! [session params] "Create a post and save it to the database" (let [ return-url (:return-url session "/") post-title (:post-title params "") post-content (:post-content params "") raw-post-tags (:post-tags params nil) post-tags (when raw-post-tags (tags/split-raw-tags raw-post-tags)) can-create (and (seq post-title) (seq post-content)) post-id (when can-create (db/add-post! post-title post-content post-tags)) flash-msg (if post-id "Post created." "Couldn't create post!")] (ss/redirect session flash-msg return-url))) (defn action-edit-post! [session params] "Edit an existing post" (let [ new-title (:post-title params nil) new-content (:post-content params nil) post-id (:post-id params nil) raw-old-tags (:post-old-tags params nil) raw-new-tags (:post-tags params nil) old-tags (when raw-old-tags (tags/split-raw-tags raw-old-tags)) new-tags (when raw-new-tags (tags/split-raw-tags raw-new-tags)) can-edit (and (seq new-title) (seq new-content) (seq post-id)) success (when can-edit (db/edit-post! post-id new-title new-content new-tags old-tags)) flash-msg (if success "Post edited." "Couldn't edit post!")] (ss/redirect session flash-msg (:return-url session "/")))) (defn action-create-preview [session params] (let [ session-info (auth/make-session-info session) title (:post-title params) content (:post-content params nil) post-id (:post-id params nil) tags (:post-tags params nil) old-tags (:post-old-tags params nil) can-submit (and (seq title) (seq content)) response-body (bt/post-preview session-info nil can-submit post-id title content tags old-tags)] { :body response-body :session session })) (defn action-resume-editing [session params] (let [ session-info (auth/make-session-info session) post-id (:post-id params nil) show-delete (not (nil? post-id)) title (:post-title params) content (:post-content params) tags (:post-tags params nil) old-tags (:post-old-tags params nil) response-body (bt/post-compose session-info nil post-id show-delete title content tags old-tags)] { :body response-body :session session })) (defn action-delete-post! [session post-id] (let [ success (db/delete-post! post-id) flash-msg (if success "Post deleted." "Error deleting post.") return-url "/blog"] (ss/redirect session flash-msg return-url))) ;; 'post-' functions generate the :body of the response to a POST request. ; Optimally, delete should be a POST instead of a GET, w/o using js. (defn post-delete! [session params] "Delete a post and return the entire response map" (action-delete-post! session (:id params))) (defn post-npsubmit! [session params] "Handle the user pressing the 'preview', 'delete', or 'submit' buttons on the compose page" (cond (contains? params :add-post) (action-create-post! session params) (contains? params :edit-post) (action-edit-post! session params) (contains? params :preview) (action-create-preview session params) (contains? params :continue-editing) (action-resume-editing session params) (contains? params :delete) (action-delete-post! session (:post-id params)) :else (ss/redirect session "An error occurred" (:return-url session "/")))) ;; 'format-' functions generate HTML for a given blog page. (defn format-composer-edit [session-info flash-msg post-id post-map] (reduce str (bt/build-composer session-info flash-msg post-id post-map))) (defn format-composer-new [session-info flash-msg] (reduce str (bt/build-composer session-info flash-msg nil nil))) (defn format-post [session-info flash-msg post-id post-map] "Given raw data from the database, generate the HTML for a single post" (reduce str (bt/post-page session-info flash-msg post-id post-map))) (defn format-blog [session-info flash-msg post-id-list post-map-list start number total] "Given raw data from the database, generate the HTML for a page of posts" (let [ c-total (if (nil? total) 0 total) desc (when (> c-total 0) (nav-description start number)) prev-url (when (> c-total 0) (prev-route start number total)) next-url (when (> c-total 0) (next-route start number total)) no-posts-msg "(No posts)"] (reduce str (bt/blog-page session-info flash-msg post-id-list post-map-list no-posts-msg prev-url "Newer" desc next-url "Older")))) (defn format-blog-for-tag [session-info flash-msg post-id-list post-map-list tag] "Given raw data from the database, generate the HTML for a page of posts" (let [ desc (tag-description tag)] (reduce str (bt/blog-page session-info flash-msg post-id-list post-map-list "(No posts)" nil nil desc nil nil)))) (defn format-archive [session-info flash-msg metadata-list] "Given raw data from the database, generate the HTML for the posts archive page" (reduce str (bt/archive-page session-info flash-msg metadata-list "(No posts)"))) ;; 'get-' functions provide an interface for getting the :body of a response to a GET request. (defn get-post-composer [session-info flash-msg post-id] (if post-id (let [post-map (db/get-post post-id)] (if post-map (format-composer-edit session-info flash-msg post-id post-map) (t/error-page session-info flash-msg "Cannot edit post. Invalid post ID." nil nil))) (format-composer-new session-info flash-msg))) (defn get-post [session-info flash-msg post-id] "Given a raw ID, retrieve a post from the database" (let [post-map (db/get-post post-id)] (if post-map (format-post session-info flash-msg post-id post-map) (t/error-page session-info flash-msg "Could not retrieve post." nil nil)))) (defn get-posts [session-info flash-msg raw-start raw-number] "Given a start index and a number of posts, return as many posts as possible" (let [ start (util/parse-integer raw-start) n (util/parse-integer raw-number) no-posts (= 0 (db/total-post-count)) [post-map-list {:keys [id-seq post-count]}] (when (and start n) (db/get-posts start n)) final-count (if no-posts 0 post-count)] (if (or no-posts post-map-list) (format-blog session-info flash-msg id-seq post-map-list start (count post-map-list) final-count) (t/error-page session-info flash-msg "Could not retrieve the requested posts." nil nil)))) (defn get-posts-for-tag [session-info flash-msg tag] "Given a tag, return the posts for that tag or an error." (let [ valid (tags/tag-valid? tag) [post-map-list {:keys [id-seq]}] (when valid (db/get-posts-for-tag tag)) error-msg (reduce str ["Could not retrieve posts for the tag '" tag "'"])] (if post-map-list (format-blog-for-tag session-info flash-msg id-seq post-map-list tag) (t/error-page session-info flash-msg error-msg nil nil)))) (defn get-archive [session-info flash-msg] "Return the post archive." (let [ metadata-list (db/get-all-metadata) error-msg "Could not retrieve blog archive"] (if metadata-list (format-archive session-info flash-msg metadata-list) (t/error-page session-info flash-msg error-msg nil nil))))
[ { "context": "m:\"]\n\n [show\n [:div\n ['customer {:first \"John\" :last \"Doe\"}]\n ['customer {:first \"Werner\" :", "end": 1351, "score": 0.999853789806366, "start": 1347, "tag": "NAME", "value": "John" }, { "context": "w\n [:div\n ['customer {:first \"John\" :last \"Doe\"}]\n ['customer {:first \"Werner\" :last \"von Br", "end": 1363, "score": 0.9995921850204468, "start": 1360, "tag": "NAME", "value": "Doe" }, { "context": "rst \"John\" :last \"Doe\"}]\n ['customer {:first \"Werner\" :last \"von Braun\"}]\n ['text \"And now\\nWe see", "end": 1398, "score": 0.9997224807739258, "start": 1392, "tag": "NAME", "value": "Werner" }, { "context": "t \"Doe\"}]\n ['customer {:first \"Werner\" :last \"von Braun\"}]\n ['text \"And now\\nWe see!\\nBut this is rea", "end": 1416, "score": 0.9993875622749329, "start": 1407, "tag": "NAME", "value": "von Braun" } ]
profiles/demo/src/demo/app.cljs
pink-gorilla/gorilla-renderable-ui
2
(ns demo.app (:require [reagent.core :as r] [frontend.page :refer [reagent-page]] [pinkie.default-setup] [pinkie.html :refer [html]] ; html with script injection [pinkie.text :refer [text]] [pinkie.error :refer [error-boundary]] [pinkie.throw-exception :refer [exception-component]] [pinkie.pinkie :refer [tag-inject] :refer-macros [register-component]] ; demo [demo.events] ; side-effects [demo.jsrender] [demo.snippets :as s] [demo.vizspec-setup :refer [show]] )) (register-component :p/text text) (register-component :p/phtml html) (register-component :p/exc exception-component) (defn wrap [component] [:div.m-5.bg-blue-200 [:div.bg-gray-300.m-5.text-blue-400 [text (pr-str component)]] [error-boundary (tag-inject component)] ]) (defmethod reagent-page :demo/main [& args] [:div [:h1 "hello, pinkie"] [wrap [:p/text "hello,\n world! (text in 2 lines)"]] [wrap s/js-demo] [wrap [:p/exc "this goes wrong"]] [wrap [:p/unknown-something "No renderer registered for this.."]] [wrap [:div [:h1 "html in reagent"] [:p "please open developer tools to check if hello world gets printed."] [:p/phtml "<script src='/r/hello.js'></script>"]]] [:h1 "now new viz-spec system:"] [show [:div ['customer {:first "John" :last "Doe"}] ['customer {:first "Werner" :last "von Braun"}] ['text "And now\nWe see!\nBut this is really long\nand extended"]]] ])
77647
(ns demo.app (:require [reagent.core :as r] [frontend.page :refer [reagent-page]] [pinkie.default-setup] [pinkie.html :refer [html]] ; html with script injection [pinkie.text :refer [text]] [pinkie.error :refer [error-boundary]] [pinkie.throw-exception :refer [exception-component]] [pinkie.pinkie :refer [tag-inject] :refer-macros [register-component]] ; demo [demo.events] ; side-effects [demo.jsrender] [demo.snippets :as s] [demo.vizspec-setup :refer [show]] )) (register-component :p/text text) (register-component :p/phtml html) (register-component :p/exc exception-component) (defn wrap [component] [:div.m-5.bg-blue-200 [:div.bg-gray-300.m-5.text-blue-400 [text (pr-str component)]] [error-boundary (tag-inject component)] ]) (defmethod reagent-page :demo/main [& args] [:div [:h1 "hello, pinkie"] [wrap [:p/text "hello,\n world! (text in 2 lines)"]] [wrap s/js-demo] [wrap [:p/exc "this goes wrong"]] [wrap [:p/unknown-something "No renderer registered for this.."]] [wrap [:div [:h1 "html in reagent"] [:p "please open developer tools to check if hello world gets printed."] [:p/phtml "<script src='/r/hello.js'></script>"]]] [:h1 "now new viz-spec system:"] [show [:div ['customer {:first "<NAME>" :last "<NAME>"}] ['customer {:first "<NAME>" :last "<NAME>"}] ['text "And now\nWe see!\nBut this is really long\nand extended"]]] ])
true
(ns demo.app (:require [reagent.core :as r] [frontend.page :refer [reagent-page]] [pinkie.default-setup] [pinkie.html :refer [html]] ; html with script injection [pinkie.text :refer [text]] [pinkie.error :refer [error-boundary]] [pinkie.throw-exception :refer [exception-component]] [pinkie.pinkie :refer [tag-inject] :refer-macros [register-component]] ; demo [demo.events] ; side-effects [demo.jsrender] [demo.snippets :as s] [demo.vizspec-setup :refer [show]] )) (register-component :p/text text) (register-component :p/phtml html) (register-component :p/exc exception-component) (defn wrap [component] [:div.m-5.bg-blue-200 [:div.bg-gray-300.m-5.text-blue-400 [text (pr-str component)]] [error-boundary (tag-inject component)] ]) (defmethod reagent-page :demo/main [& args] [:div [:h1 "hello, pinkie"] [wrap [:p/text "hello,\n world! (text in 2 lines)"]] [wrap s/js-demo] [wrap [:p/exc "this goes wrong"]] [wrap [:p/unknown-something "No renderer registered for this.."]] [wrap [:div [:h1 "html in reagent"] [:p "please open developer tools to check if hello world gets printed."] [:p/phtml "<script src='/r/hello.js'></script>"]]] [:h1 "now new viz-spec system:"] [show [:div ['customer {:first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI"}] ['customer {:first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI"}] ['text "And now\nWe see!\nBut this is really long\nand extended"]]] ])
[ { "context": "(ns ^{:author \"Leeor Engel\"}\n chapter-2.chapter-2-q3-test\n (:require [cloj", "end": 26, "score": 0.9998857378959656, "start": 15, "tag": "NAME", "value": "Leeor Engel" } ]
Clojure/test/chapter_2/chapter_2_q3_test.clj
Kiandr/crackingcodinginterview
0
(ns ^{:author "Leeor Engel"} chapter-2.chapter-2-q3-test (:require [clojure.test :refer :all] [data-structures.mutable-linked-list :refer :all] [chapter-2.chapter-2-q3 :refer :all])) (deftest remove-middle-node-test (is (lists-eq? (create-linked-list 1 3) (let [l (create-linked-list 1 2 3)] (remove-middle-node (search l 2)) l))) (is (lists-eq? (create-linked-list 1 2 4) (let [l (create-linked-list 1 2 3 4)] (remove-middle-node (search l 3)) l))) (is (lists-eq? (create-linked-list 1 3 4) (let [l (create-linked-list 1 2 3 4)] (remove-middle-node (search l 2)) l))))
101088
(ns ^{:author "<NAME>"} chapter-2.chapter-2-q3-test (:require [clojure.test :refer :all] [data-structures.mutable-linked-list :refer :all] [chapter-2.chapter-2-q3 :refer :all])) (deftest remove-middle-node-test (is (lists-eq? (create-linked-list 1 3) (let [l (create-linked-list 1 2 3)] (remove-middle-node (search l 2)) l))) (is (lists-eq? (create-linked-list 1 2 4) (let [l (create-linked-list 1 2 3 4)] (remove-middle-node (search l 3)) l))) (is (lists-eq? (create-linked-list 1 3 4) (let [l (create-linked-list 1 2 3 4)] (remove-middle-node (search l 2)) l))))
true
(ns ^{:author "PI:NAME:<NAME>END_PI"} chapter-2.chapter-2-q3-test (:require [clojure.test :refer :all] [data-structures.mutable-linked-list :refer :all] [chapter-2.chapter-2-q3 :refer :all])) (deftest remove-middle-node-test (is (lists-eq? (create-linked-list 1 3) (let [l (create-linked-list 1 2 3)] (remove-middle-node (search l 2)) l))) (is (lists-eq? (create-linked-list 1 2 4) (let [l (create-linked-list 1 2 3 4)] (remove-middle-node (search l 3)) l))) (is (lists-eq? (create-linked-list 1 3 4) (let [l (create-linked-list 1 2 3 4)] (remove-middle-node (search l 2)) l))))
[ { "context": "(ns ^{:author \"Bruno Bonacci (@BrunoBonacci)\" :no-doc true}\n com.brunobonac", "end": 28, "score": 0.9998558163642883, "start": 15, "tag": "NAME", "value": "Bruno Bonacci" }, { "context": "(ns ^{:author \"Bruno Bonacci (@BrunoBonacci)\" :no-doc true}\n com.brunobonacci.oneconfig.ba", "end": 43, "score": 0.9988179802894592, "start": 29, "tag": "USERNAME", "value": "(@BrunoBonacci" }, { "context": " key)\n ver-key (str zver \"||\" (format \"%020d\" change-num))\n db-entry (assoc entry\n ", "end": 4123, "score": 0.5613026022911072, "start": 4121, "tag": "KEY", "value": "20" } ]
1config-core/src/com/brunobonacci/oneconfig/backends/dynamo.clj
obohrer/1config
1
(ns ^{:author "Bruno Bonacci (@BrunoBonacci)" :no-doc true} com.brunobonacci.oneconfig.backends.dynamo (:refer-clojure :exclude [find load list]) (:require [com.brunobonacci.oneconfig.backend :refer :all] [com.brunobonacci.oneconfig.backends.in-memory :refer [TestStore data]] [com.brunobonacci.oneconfig.util :refer :all] [amazonica.aws.dynamodbv2 :as dyn] [clojure.string :as str])) ;; ;;``` ;; | ;; V ;; -|--------------------------------------------------------------------------- ;; dynamo-backend ;; | it stores the entry into DynamoDB table called `1Config` in the given ;; | region with a conditional insert which it will fail if an entry ;; | with the same key exists. ;; ----------------------------------------------------------------------------- ;;``` ;; (defn default-dynamo-config [] {:endpoint nil ;; this is required to by amazonica ;; to consider first argument a config :table (config-property "1config.dynamo.table" "ONECONFIG_DYNAMO_TABLE" "1Config")}) (defn create-configure-table [aws-config tablename] (dyn/create-table (or aws-config (default-dynamo-config)) :table-name (or tablename (:table (default-dynamo-config))) :key-schema [{:attribute-name "__sys_key" :key-type "HASH"} {:attribute-name "__ver_key" :key-type "RANGE"}] :attribute-definitions [{:attribute-name "__sys_key" :attribute-type "S"} {:attribute-name "__ver_key" :attribute-type "S"}] :provisioned-throughput {:read-capacity-units 10 :write-capacity-units 10})) (defn- search-paths [version] ((juxt identity #(subs % 0 6) #(subs % 0 3) (constantly "")) (comparable-version version))) (defn lazy-query "Takes a query as a lambda function and retunrs a lazy pagination over the items" ([q] ;; mapcat is not lazy so defining one (lazy-mapcat :items (lazy-query q nil))) ;; paginate lazily the query ([q start-from] (let [result (q start-from)] (lazy-seq (if-let [next-page (:last-evaluated-key result)] (cons result (lazy-query q next-page)) [result]))))) (deftype DynamoTableConfigBackend [cfg] TestStore (data [_] nil) IConfigClient (find [this {:keys [key env version change-num] :as config-entry}] (let [zver (comparable-version version) sys-key (str env "||" key) ver-key (str zver "||" (or (and change-num (format "%020d" change-num )) (apply str (repeat 20 "9"))))] (some-> (dyn/query cfg :table-name (:table cfg) :limit 1 :select "ALL_ATTRIBUTES" :scan-index-forward false :key-conditions {:__sys_key {:attribute-value-list [sys-key] :comparison-operator "EQ"} :__ver_key {:attribute-value-list [ver-key] :comparison-operator "LE"}}) :items first entry-record))) IConfigBackend (load [_ {:keys [key env version change-num] :as config-entry}] (let [zver (comparable-version version) sys-key (str env "||" key) ver-key (str zver "||" (when change-num (format "%020d" change-num)))] (some-> (dyn/query cfg :table-name (:table cfg) :limit 1 :select "ALL_ATTRIBUTES" :scan-index-forward false :key-conditions {:__sys_key {:attribute-value-list [sys-key] :comparison-operator "EQ"} :__ver_key {:attribute-value-list [ver-key] :comparison-operator "BEGINS_WITH"}}) :items first entry-record))) (save [this config-entry] (let [{:keys [key env version value change-num] :as entry} (merge {:content-type "edn"} config-entry) zver (comparable-version version) change-num (or change-num (System/currentTimeMillis)) sys-key (str env "||" key) ver-key (str zver "||" (format "%020d" change-num)) db-entry (assoc entry :__sys_key sys-key :__ver_key ver-key :change-num change-num)] (dyn/put-item cfg :table-name (:table cfg) :return-consumed-capacity "TOTAL" :return-item-collection-metrics "SIZE" :condition-expression "attribute_not_exists(#ID)" :expression-attribute-names {"#ID" "__sys_key"} :item db-entry)) this) (list [this filters] (let [q (fn [start-from] (dyn/scan cfg (if start-from {:table-name (:table cfg) :exclusive-start-key start-from} {:table-name (:table cfg)})))] (->> (lazy-query q) (list-entries filters) (map #(assoc % :backend :dynamo)))))) (defn dynamo-config-backend [dynamo-config] (DynamoTableConfigBackend. dynamo-config))
13348
(ns ^{:author "<NAME> (@BrunoBonacci)" :no-doc true} com.brunobonacci.oneconfig.backends.dynamo (:refer-clojure :exclude [find load list]) (:require [com.brunobonacci.oneconfig.backend :refer :all] [com.brunobonacci.oneconfig.backends.in-memory :refer [TestStore data]] [com.brunobonacci.oneconfig.util :refer :all] [amazonica.aws.dynamodbv2 :as dyn] [clojure.string :as str])) ;; ;;``` ;; | ;; V ;; -|--------------------------------------------------------------------------- ;; dynamo-backend ;; | it stores the entry into DynamoDB table called `1Config` in the given ;; | region with a conditional insert which it will fail if an entry ;; | with the same key exists. ;; ----------------------------------------------------------------------------- ;;``` ;; (defn default-dynamo-config [] {:endpoint nil ;; this is required to by amazonica ;; to consider first argument a config :table (config-property "1config.dynamo.table" "ONECONFIG_DYNAMO_TABLE" "1Config")}) (defn create-configure-table [aws-config tablename] (dyn/create-table (or aws-config (default-dynamo-config)) :table-name (or tablename (:table (default-dynamo-config))) :key-schema [{:attribute-name "__sys_key" :key-type "HASH"} {:attribute-name "__ver_key" :key-type "RANGE"}] :attribute-definitions [{:attribute-name "__sys_key" :attribute-type "S"} {:attribute-name "__ver_key" :attribute-type "S"}] :provisioned-throughput {:read-capacity-units 10 :write-capacity-units 10})) (defn- search-paths [version] ((juxt identity #(subs % 0 6) #(subs % 0 3) (constantly "")) (comparable-version version))) (defn lazy-query "Takes a query as a lambda function and retunrs a lazy pagination over the items" ([q] ;; mapcat is not lazy so defining one (lazy-mapcat :items (lazy-query q nil))) ;; paginate lazily the query ([q start-from] (let [result (q start-from)] (lazy-seq (if-let [next-page (:last-evaluated-key result)] (cons result (lazy-query q next-page)) [result]))))) (deftype DynamoTableConfigBackend [cfg] TestStore (data [_] nil) IConfigClient (find [this {:keys [key env version change-num] :as config-entry}] (let [zver (comparable-version version) sys-key (str env "||" key) ver-key (str zver "||" (or (and change-num (format "%020d" change-num )) (apply str (repeat 20 "9"))))] (some-> (dyn/query cfg :table-name (:table cfg) :limit 1 :select "ALL_ATTRIBUTES" :scan-index-forward false :key-conditions {:__sys_key {:attribute-value-list [sys-key] :comparison-operator "EQ"} :__ver_key {:attribute-value-list [ver-key] :comparison-operator "LE"}}) :items first entry-record))) IConfigBackend (load [_ {:keys [key env version change-num] :as config-entry}] (let [zver (comparable-version version) sys-key (str env "||" key) ver-key (str zver "||" (when change-num (format "%020d" change-num)))] (some-> (dyn/query cfg :table-name (:table cfg) :limit 1 :select "ALL_ATTRIBUTES" :scan-index-forward false :key-conditions {:__sys_key {:attribute-value-list [sys-key] :comparison-operator "EQ"} :__ver_key {:attribute-value-list [ver-key] :comparison-operator "BEGINS_WITH"}}) :items first entry-record))) (save [this config-entry] (let [{:keys [key env version value change-num] :as entry} (merge {:content-type "edn"} config-entry) zver (comparable-version version) change-num (or change-num (System/currentTimeMillis)) sys-key (str env "||" key) ver-key (str zver "||" (format "%0<KEY>d" change-num)) db-entry (assoc entry :__sys_key sys-key :__ver_key ver-key :change-num change-num)] (dyn/put-item cfg :table-name (:table cfg) :return-consumed-capacity "TOTAL" :return-item-collection-metrics "SIZE" :condition-expression "attribute_not_exists(#ID)" :expression-attribute-names {"#ID" "__sys_key"} :item db-entry)) this) (list [this filters] (let [q (fn [start-from] (dyn/scan cfg (if start-from {:table-name (:table cfg) :exclusive-start-key start-from} {:table-name (:table cfg)})))] (->> (lazy-query q) (list-entries filters) (map #(assoc % :backend :dynamo)))))) (defn dynamo-config-backend [dynamo-config] (DynamoTableConfigBackend. dynamo-config))
true
(ns ^{:author "PI:NAME:<NAME>END_PI (@BrunoBonacci)" :no-doc true} com.brunobonacci.oneconfig.backends.dynamo (:refer-clojure :exclude [find load list]) (:require [com.brunobonacci.oneconfig.backend :refer :all] [com.brunobonacci.oneconfig.backends.in-memory :refer [TestStore data]] [com.brunobonacci.oneconfig.util :refer :all] [amazonica.aws.dynamodbv2 :as dyn] [clojure.string :as str])) ;; ;;``` ;; | ;; V ;; -|--------------------------------------------------------------------------- ;; dynamo-backend ;; | it stores the entry into DynamoDB table called `1Config` in the given ;; | region with a conditional insert which it will fail if an entry ;; | with the same key exists. ;; ----------------------------------------------------------------------------- ;;``` ;; (defn default-dynamo-config [] {:endpoint nil ;; this is required to by amazonica ;; to consider first argument a config :table (config-property "1config.dynamo.table" "ONECONFIG_DYNAMO_TABLE" "1Config")}) (defn create-configure-table [aws-config tablename] (dyn/create-table (or aws-config (default-dynamo-config)) :table-name (or tablename (:table (default-dynamo-config))) :key-schema [{:attribute-name "__sys_key" :key-type "HASH"} {:attribute-name "__ver_key" :key-type "RANGE"}] :attribute-definitions [{:attribute-name "__sys_key" :attribute-type "S"} {:attribute-name "__ver_key" :attribute-type "S"}] :provisioned-throughput {:read-capacity-units 10 :write-capacity-units 10})) (defn- search-paths [version] ((juxt identity #(subs % 0 6) #(subs % 0 3) (constantly "")) (comparable-version version))) (defn lazy-query "Takes a query as a lambda function and retunrs a lazy pagination over the items" ([q] ;; mapcat is not lazy so defining one (lazy-mapcat :items (lazy-query q nil))) ;; paginate lazily the query ([q start-from] (let [result (q start-from)] (lazy-seq (if-let [next-page (:last-evaluated-key result)] (cons result (lazy-query q next-page)) [result]))))) (deftype DynamoTableConfigBackend [cfg] TestStore (data [_] nil) IConfigClient (find [this {:keys [key env version change-num] :as config-entry}] (let [zver (comparable-version version) sys-key (str env "||" key) ver-key (str zver "||" (or (and change-num (format "%020d" change-num )) (apply str (repeat 20 "9"))))] (some-> (dyn/query cfg :table-name (:table cfg) :limit 1 :select "ALL_ATTRIBUTES" :scan-index-forward false :key-conditions {:__sys_key {:attribute-value-list [sys-key] :comparison-operator "EQ"} :__ver_key {:attribute-value-list [ver-key] :comparison-operator "LE"}}) :items first entry-record))) IConfigBackend (load [_ {:keys [key env version change-num] :as config-entry}] (let [zver (comparable-version version) sys-key (str env "||" key) ver-key (str zver "||" (when change-num (format "%020d" change-num)))] (some-> (dyn/query cfg :table-name (:table cfg) :limit 1 :select "ALL_ATTRIBUTES" :scan-index-forward false :key-conditions {:__sys_key {:attribute-value-list [sys-key] :comparison-operator "EQ"} :__ver_key {:attribute-value-list [ver-key] :comparison-operator "BEGINS_WITH"}}) :items first entry-record))) (save [this config-entry] (let [{:keys [key env version value change-num] :as entry} (merge {:content-type "edn"} config-entry) zver (comparable-version version) change-num (or change-num (System/currentTimeMillis)) sys-key (str env "||" key) ver-key (str zver "||" (format "%0PI:KEY:<KEY>END_PId" change-num)) db-entry (assoc entry :__sys_key sys-key :__ver_key ver-key :change-num change-num)] (dyn/put-item cfg :table-name (:table cfg) :return-consumed-capacity "TOTAL" :return-item-collection-metrics "SIZE" :condition-expression "attribute_not_exists(#ID)" :expression-attribute-names {"#ID" "__sys_key"} :item db-entry)) this) (list [this filters] (let [q (fn [start-from] (dyn/scan cfg (if start-from {:table-name (:table cfg) :exclusive-start-key start-from} {:table-name (:table cfg)})))] (->> (lazy-query q) (list-entries filters) (map #(assoc % :backend :dynamo)))))) (defn dynamo-config-backend [dynamo-config] (DynamoTableConfigBackend. dynamo-config))
[ { "context": " :method :get\n :params {:api-key \"TODO\"}\n :format (ajx/json-request-format)\n ", "end": 2793, "score": 0.9234488010406494, "start": 2789, "tag": "KEY", "value": "TODO" } ]
src/app/renderer/weather/handle_event.cljs
geekarist/cewth
0
(ns app.renderer.weather.handle-event (:require [ajax.core :as ajx] [clojure.string :as str] [goog.string :as gstr] [goog.string.format] [tick.core :as t] [tick.locale-en-us])) (defn change-query "Change query field: - State change: add query value - No effect" [state query] (let [new-state (assoc state :state/query query :state/failed nil :state/icon-src nil :state/location nil :state/temperature-unit nil :state/temperature-val nil :state/updated-at nil :state/weather-text nil) new-effect nil] [new-state new-effect])) (defn send-city-search-req "Convert query to city search request: - State change: clear query if blank, or create city search request - Effect: trigger search only if query is not blank and kbd key is Enter" [state kbd-key] (let [new-state (if (str/blank? (state :state/query)) (assoc state :state/location nil :state/failed nil) state) new-effect (if (and (not (str/blank? (state :state/query))) (= kbd-key "Enter")) [:fx/search {:uri (str "http://localhost:3000" "/dataservice.accuweather.com" "/locations/v1/cities/search") :method :get :params {:q (state :state/query) :api-key "TODO"} :format (ajx/json-request-format) :response-format (ajx/json-response-format)}] nil)] [new-state new-effect])) (defn take-city-search-response "Take search response: - State change: convert response to result (extract location and status) - No effect" [state [ok? city-search-resp :as _event-arg]] (let [new-state (if (empty? city-search-resp) (assoc state :state/location "Not found" :state/failed (not ok?)) (assoc state :state/location (-> city-search-resp (first) (get "LocalizedName")) :state/failed (not ok?))) new-effect (if (seq city-search-resp) [:fx/current-conditions {:uri (str "http://localhost:3000" "/dataservice.accuweather.com" "/currentconditions/v1/" (-> city-search-resp (first) (get "Key"))) :method :get :params {:api-key "TODO"} :format (ajx/json-request-format) :response-format (ajx/json-response-format)}] nil)] [new-state new-effect])) (defn take-current-conditions-response [state [_ok? current-conditions-resp :as _event-arg]] (let [new-state (assoc state :state/temperature-val (-> current-conditions-resp (first) (get "Temperature") (get "Metric") (get "Value")) :state/temperature-unit (-> current-conditions-resp (first) (get "Temperature") (get "Metric") (get "Unit")) :state/weather-text (-> current-conditions-resp (first) (get "WeatherText"))) new-effect [:fx/request-current-time]] [new-state new-effect])) (defn- parse-timestamp [zoned-date-time] (t/format (t/formatter "yyyy/MM/dd HH:mm") zoned-date-time)) (defn take-current-date-response [state zoned-date-time] (let [new-state (assoc state :state/updated-at (gstr/format "Last update: %s" (parse-timestamp zoned-date-time))) new-effect nil] [new-state new-effect]))
11980
(ns app.renderer.weather.handle-event (:require [ajax.core :as ajx] [clojure.string :as str] [goog.string :as gstr] [goog.string.format] [tick.core :as t] [tick.locale-en-us])) (defn change-query "Change query field: - State change: add query value - No effect" [state query] (let [new-state (assoc state :state/query query :state/failed nil :state/icon-src nil :state/location nil :state/temperature-unit nil :state/temperature-val nil :state/updated-at nil :state/weather-text nil) new-effect nil] [new-state new-effect])) (defn send-city-search-req "Convert query to city search request: - State change: clear query if blank, or create city search request - Effect: trigger search only if query is not blank and kbd key is Enter" [state kbd-key] (let [new-state (if (str/blank? (state :state/query)) (assoc state :state/location nil :state/failed nil) state) new-effect (if (and (not (str/blank? (state :state/query))) (= kbd-key "Enter")) [:fx/search {:uri (str "http://localhost:3000" "/dataservice.accuweather.com" "/locations/v1/cities/search") :method :get :params {:q (state :state/query) :api-key "TODO"} :format (ajx/json-request-format) :response-format (ajx/json-response-format)}] nil)] [new-state new-effect])) (defn take-city-search-response "Take search response: - State change: convert response to result (extract location and status) - No effect" [state [ok? city-search-resp :as _event-arg]] (let [new-state (if (empty? city-search-resp) (assoc state :state/location "Not found" :state/failed (not ok?)) (assoc state :state/location (-> city-search-resp (first) (get "LocalizedName")) :state/failed (not ok?))) new-effect (if (seq city-search-resp) [:fx/current-conditions {:uri (str "http://localhost:3000" "/dataservice.accuweather.com" "/currentconditions/v1/" (-> city-search-resp (first) (get "Key"))) :method :get :params {:api-key "<KEY>"} :format (ajx/json-request-format) :response-format (ajx/json-response-format)}] nil)] [new-state new-effect])) (defn take-current-conditions-response [state [_ok? current-conditions-resp :as _event-arg]] (let [new-state (assoc state :state/temperature-val (-> current-conditions-resp (first) (get "Temperature") (get "Metric") (get "Value")) :state/temperature-unit (-> current-conditions-resp (first) (get "Temperature") (get "Metric") (get "Unit")) :state/weather-text (-> current-conditions-resp (first) (get "WeatherText"))) new-effect [:fx/request-current-time]] [new-state new-effect])) (defn- parse-timestamp [zoned-date-time] (t/format (t/formatter "yyyy/MM/dd HH:mm") zoned-date-time)) (defn take-current-date-response [state zoned-date-time] (let [new-state (assoc state :state/updated-at (gstr/format "Last update: %s" (parse-timestamp zoned-date-time))) new-effect nil] [new-state new-effect]))
true
(ns app.renderer.weather.handle-event (:require [ajax.core :as ajx] [clojure.string :as str] [goog.string :as gstr] [goog.string.format] [tick.core :as t] [tick.locale-en-us])) (defn change-query "Change query field: - State change: add query value - No effect" [state query] (let [new-state (assoc state :state/query query :state/failed nil :state/icon-src nil :state/location nil :state/temperature-unit nil :state/temperature-val nil :state/updated-at nil :state/weather-text nil) new-effect nil] [new-state new-effect])) (defn send-city-search-req "Convert query to city search request: - State change: clear query if blank, or create city search request - Effect: trigger search only if query is not blank and kbd key is Enter" [state kbd-key] (let [new-state (if (str/blank? (state :state/query)) (assoc state :state/location nil :state/failed nil) state) new-effect (if (and (not (str/blank? (state :state/query))) (= kbd-key "Enter")) [:fx/search {:uri (str "http://localhost:3000" "/dataservice.accuweather.com" "/locations/v1/cities/search") :method :get :params {:q (state :state/query) :api-key "TODO"} :format (ajx/json-request-format) :response-format (ajx/json-response-format)}] nil)] [new-state new-effect])) (defn take-city-search-response "Take search response: - State change: convert response to result (extract location and status) - No effect" [state [ok? city-search-resp :as _event-arg]] (let [new-state (if (empty? city-search-resp) (assoc state :state/location "Not found" :state/failed (not ok?)) (assoc state :state/location (-> city-search-resp (first) (get "LocalizedName")) :state/failed (not ok?))) new-effect (if (seq city-search-resp) [:fx/current-conditions {:uri (str "http://localhost:3000" "/dataservice.accuweather.com" "/currentconditions/v1/" (-> city-search-resp (first) (get "Key"))) :method :get :params {:api-key "PI:KEY:<KEY>END_PI"} :format (ajx/json-request-format) :response-format (ajx/json-response-format)}] nil)] [new-state new-effect])) (defn take-current-conditions-response [state [_ok? current-conditions-resp :as _event-arg]] (let [new-state (assoc state :state/temperature-val (-> current-conditions-resp (first) (get "Temperature") (get "Metric") (get "Value")) :state/temperature-unit (-> current-conditions-resp (first) (get "Temperature") (get "Metric") (get "Unit")) :state/weather-text (-> current-conditions-resp (first) (get "WeatherText"))) new-effect [:fx/request-current-time]] [new-state new-effect])) (defn- parse-timestamp [zoned-date-time] (t/format (t/formatter "yyyy/MM/dd HH:mm") zoned-date-time)) (defn take-current-date-response [state zoned-date-time] (let [new-state (assoc state :state/updated-at (gstr/format "Last update: %s" (parse-timestamp zoned-date-time))) new-effect nil] [new-state new-effect]))
[ { "context": "v.crdt.ormap.realize :as real]))\n\n(def user \"mail:contact@radsmith.com\") ;; will be used to authenticate you (not yet)\n(", "end": 491, "score": 0.9999160766601562, "start": 471, "tag": "EMAIL", "value": "contact@radsmith.com" }, { "context": "e\n(def peer-a (<?? S (server-peer S store-a \"ws://127.0.0.1:9090\"))) ;; network and file IO\n(<?? S (start pee", "end": 765, "score": 0.9996998310089111, "start": 756, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "g\n(def peer-b (<?? S (server-peer S store-b \"ws://127.0.0.1:9091\")))\n(<?? S (start peer-b))\n(def stage-b (<??", "end": 1060, "score": 0.9996273517608643, "start": 1051, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " ormap-id] :foo))\n\n(<?? S (connect! stage-a \"ws://127.0.0.1:9091\")) \n\n(<?? S (ors/get stage-a [user ormap-id]", "end": 1355, "score": 0.9987561702728271, "start": 1346, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
examples/replikativ/src/rads/todop2p/replikativ.clj
rads/todop2p
0
(ns rads.todop2p.replikativ (:require [superv.async :refer [<?? S]] [kabel.peer :refer [start stop]] [konserve [filestore :refer [new-fs-store]] [memory :refer [new-mem-store]]] [replikativ [peer :refer [server-peer]] [stage :refer [connect! create-stage!]]] [replikativ.crdt.ormap.stage :as ors] [replikativ.crdt.ormap.realize :as real])) (def user "mail:contact@radsmith.com") ;; will be used to authenticate you (not yet) (def ormap-id #uuid "7d274663-9396-4247-910b-409ae35fe98d") ;; application specific datatype address (def store-a (<?? S (new-fs-store "/tmp/test"))) ;; durable store (def peer-a (<?? S (server-peer S store-a "ws://127.0.0.1:9090"))) ;; network and file IO (<?? S (start peer-a)) (def stage-a (<?? S (create-stage! user peer-a))) ;; API for peer<Paste> (<?? S (ors/create-ormap! stage-a :id ormap-id)) (def store-b (<?? S (new-mem-store))) ;; store for testing (def peer-b (<?? S (server-peer S store-b "ws://127.0.0.1:9091"))) (<?? S (start peer-b)) (def stage-b (<?? S (create-stage! user peer-b))) (<?? S (ors/create-ormap! stage-b :id ormap-id)) (<?? S (ors/assoc! stage-b [user ormap-id] :foo [['assoc [:foo :bars]]])) (<?? S (ors/get stage-b [user ormap-id] :foo)) (<?? S (connect! stage-a "ws://127.0.0.1:9091")) (<?? S (ors/get stage-a [user ormap-id] :foo)) ;; accordingly we can provide a dissoc operation on removal (<?? S (ors/dissoc! stage-a [user ormap-id] :foo [['dissoc :bars]]))
27908
(ns rads.todop2p.replikativ (:require [superv.async :refer [<?? S]] [kabel.peer :refer [start stop]] [konserve [filestore :refer [new-fs-store]] [memory :refer [new-mem-store]]] [replikativ [peer :refer [server-peer]] [stage :refer [connect! create-stage!]]] [replikativ.crdt.ormap.stage :as ors] [replikativ.crdt.ormap.realize :as real])) (def user "mail:<EMAIL>") ;; will be used to authenticate you (not yet) (def ormap-id #uuid "7d274663-9396-4247-910b-409ae35fe98d") ;; application specific datatype address (def store-a (<?? S (new-fs-store "/tmp/test"))) ;; durable store (def peer-a (<?? S (server-peer S store-a "ws://127.0.0.1:9090"))) ;; network and file IO (<?? S (start peer-a)) (def stage-a (<?? S (create-stage! user peer-a))) ;; API for peer<Paste> (<?? S (ors/create-ormap! stage-a :id ormap-id)) (def store-b (<?? S (new-mem-store))) ;; store for testing (def peer-b (<?? S (server-peer S store-b "ws://127.0.0.1:9091"))) (<?? S (start peer-b)) (def stage-b (<?? S (create-stage! user peer-b))) (<?? S (ors/create-ormap! stage-b :id ormap-id)) (<?? S (ors/assoc! stage-b [user ormap-id] :foo [['assoc [:foo :bars]]])) (<?? S (ors/get stage-b [user ormap-id] :foo)) (<?? S (connect! stage-a "ws://127.0.0.1:9091")) (<?? S (ors/get stage-a [user ormap-id] :foo)) ;; accordingly we can provide a dissoc operation on removal (<?? S (ors/dissoc! stage-a [user ormap-id] :foo [['dissoc :bars]]))
true
(ns rads.todop2p.replikativ (:require [superv.async :refer [<?? S]] [kabel.peer :refer [start stop]] [konserve [filestore :refer [new-fs-store]] [memory :refer [new-mem-store]]] [replikativ [peer :refer [server-peer]] [stage :refer [connect! create-stage!]]] [replikativ.crdt.ormap.stage :as ors] [replikativ.crdt.ormap.realize :as real])) (def user "mail:PI:EMAIL:<EMAIL>END_PI") ;; will be used to authenticate you (not yet) (def ormap-id #uuid "7d274663-9396-4247-910b-409ae35fe98d") ;; application specific datatype address (def store-a (<?? S (new-fs-store "/tmp/test"))) ;; durable store (def peer-a (<?? S (server-peer S store-a "ws://127.0.0.1:9090"))) ;; network and file IO (<?? S (start peer-a)) (def stage-a (<?? S (create-stage! user peer-a))) ;; API for peer<Paste> (<?? S (ors/create-ormap! stage-a :id ormap-id)) (def store-b (<?? S (new-mem-store))) ;; store for testing (def peer-b (<?? S (server-peer S store-b "ws://127.0.0.1:9091"))) (<?? S (start peer-b)) (def stage-b (<?? S (create-stage! user peer-b))) (<?? S (ors/create-ormap! stage-b :id ormap-id)) (<?? S (ors/assoc! stage-b [user ormap-id] :foo [['assoc [:foo :bars]]])) (<?? S (ors/get stage-b [user ormap-id] :foo)) (<?? S (connect! stage-a "ws://127.0.0.1:9091")) (<?? S (ors/get stage-a [user ormap-id] :foo)) ;; accordingly we can provide a dissoc operation on removal (<?? S (ors/dissoc! stage-a [user ormap-id] :foo [['dissoc :bars]]))
[ { "context": "l [app-page jsname html-name]\n (let [csrf-token \"llXxTmFvjm6KXhKBjY7nemz4GNRwF/ZgZbycGDgw8cdF1B/cbmX5JZElY3MCnyEYUUGCi7Cw3k3mUpMI\"\n html (app-page csrf-token)\n filen", "end": 478, "score": 0.9986953735351562, "start": 398, "tag": "KEY", "value": "llXxTmFvjm6KXhKBjY7nemz4GNRwF/ZgZbycGDgw8cdF1B/cbmX5JZElY3MCnyEYUUGCi7Cw3k3mUpMI" } ]
webly/src/webly/build/static.clj
pink-gorilla/webly
6
(ns webly.build.static (:require [clojure.java.io :as io] [taoensso.timbre :refer [debug info warn]] [modular.writer :refer [write write-status write-target]] [modular.resource.load :refer [write-resources-to]] [modular.config :refer [config-atom]] [webly.app.page :refer [app-page-static app-page-dynamic]])) (defn create-html [app-page jsname html-name] (let [csrf-token "llXxTmFvjm6KXhKBjY7nemz4GNRwF/ZgZbycGDgw8cdF1B/cbmX5JZElY3MCnyEYUUGCi7Cw3k3mUpMI" html (app-page csrf-token) filename html-name] (info "writing static page: " filename) (spit filename html))) (defn- ensure-directory [path] (when-not (.exists (io/file path)) (.mkdir (java.io.File. path)))) (defn generate-static-html [] (ensure-directory "target") (ensure-directory "target/static") (create-html app-page-static "/r/webly.js" "target/static/index.html") (create-html app-page-dynamic "/r/webly.js" "target/static/index_dynamic.html")) (defn save-resources [] (ensure-directory "target") (ensure-directory "target/res") (write-resources-to "target/res" "public")) (defn config-prefix-adjust [config] (let [prefix (:prefix config) static-main-path (:static-main-path config) asset-path (str static-main-path prefix)] (info "static asset path: " asset-path) (assoc config :prefix asset-path))) (defn write-static-config [] (let [filename "target/static/r/config.edn" config (-> @config-atom (dissoc :oauth2 :webly/web-server :shadow) ; oauth2 settings are private (config-prefix-adjust))] (ensure-directory "target") (ensure-directory "target/static") (ensure-directory "target/static/r") (write filename config))) (defn prepare-static-page [] ; 1. adjust config & write (write-static-config) (generate-static-html) (save-resources))
62912
(ns webly.build.static (:require [clojure.java.io :as io] [taoensso.timbre :refer [debug info warn]] [modular.writer :refer [write write-status write-target]] [modular.resource.load :refer [write-resources-to]] [modular.config :refer [config-atom]] [webly.app.page :refer [app-page-static app-page-dynamic]])) (defn create-html [app-page jsname html-name] (let [csrf-token "<KEY>" html (app-page csrf-token) filename html-name] (info "writing static page: " filename) (spit filename html))) (defn- ensure-directory [path] (when-not (.exists (io/file path)) (.mkdir (java.io.File. path)))) (defn generate-static-html [] (ensure-directory "target") (ensure-directory "target/static") (create-html app-page-static "/r/webly.js" "target/static/index.html") (create-html app-page-dynamic "/r/webly.js" "target/static/index_dynamic.html")) (defn save-resources [] (ensure-directory "target") (ensure-directory "target/res") (write-resources-to "target/res" "public")) (defn config-prefix-adjust [config] (let [prefix (:prefix config) static-main-path (:static-main-path config) asset-path (str static-main-path prefix)] (info "static asset path: " asset-path) (assoc config :prefix asset-path))) (defn write-static-config [] (let [filename "target/static/r/config.edn" config (-> @config-atom (dissoc :oauth2 :webly/web-server :shadow) ; oauth2 settings are private (config-prefix-adjust))] (ensure-directory "target") (ensure-directory "target/static") (ensure-directory "target/static/r") (write filename config))) (defn prepare-static-page [] ; 1. adjust config & write (write-static-config) (generate-static-html) (save-resources))
true
(ns webly.build.static (:require [clojure.java.io :as io] [taoensso.timbre :refer [debug info warn]] [modular.writer :refer [write write-status write-target]] [modular.resource.load :refer [write-resources-to]] [modular.config :refer [config-atom]] [webly.app.page :refer [app-page-static app-page-dynamic]])) (defn create-html [app-page jsname html-name] (let [csrf-token "PI:KEY:<KEY>END_PI" html (app-page csrf-token) filename html-name] (info "writing static page: " filename) (spit filename html))) (defn- ensure-directory [path] (when-not (.exists (io/file path)) (.mkdir (java.io.File. path)))) (defn generate-static-html [] (ensure-directory "target") (ensure-directory "target/static") (create-html app-page-static "/r/webly.js" "target/static/index.html") (create-html app-page-dynamic "/r/webly.js" "target/static/index_dynamic.html")) (defn save-resources [] (ensure-directory "target") (ensure-directory "target/res") (write-resources-to "target/res" "public")) (defn config-prefix-adjust [config] (let [prefix (:prefix config) static-main-path (:static-main-path config) asset-path (str static-main-path prefix)] (info "static asset path: " asset-path) (assoc config :prefix asset-path))) (defn write-static-config [] (let [filename "target/static/r/config.edn" config (-> @config-atom (dissoc :oauth2 :webly/web-server :shadow) ; oauth2 settings are private (config-prefix-adjust))] (ensure-directory "target") (ensure-directory "target/static") (ensure-directory "target/static/r") (write filename config))) (defn prepare-static-page [] ; 1. adjust config & write (write-static-config) (generate-static-html) (save-resources))
[ { "context": "(ns ^{:doc \"Utility functions\"\n :author \"Paul Landes\"}\n zensols.nlparse.util)\n\n(defn has-some?\n \"R", "end": 57, "score": 0.9998883008956909, "start": 46, "tag": "NAME", "value": "Paul Landes" } ]
src/clojure/zensols/nlparse/util.clj
plandes/clj-nlp-parse
33
(ns ^{:doc "Utility functions" :author "Paul Landes"} zensols.nlparse.util) (defn has-some? "Return whether or not the data should be added to a data structure." [data] (and data (or (not (or (associative? data) (sequential? data) (instance? java.util.Set data))) (not (empty? data))))) (defn map-if-data "Return the key/value pair sequences as a map for those values that are data per `has-some?`." [entries] (->> entries (map (fn [[k elt]] (if (has-some? elt) (array-map k elt)))) (remove nil?) (apply merge)))
1211
(ns ^{:doc "Utility functions" :author "<NAME>"} zensols.nlparse.util) (defn has-some? "Return whether or not the data should be added to a data structure." [data] (and data (or (not (or (associative? data) (sequential? data) (instance? java.util.Set data))) (not (empty? data))))) (defn map-if-data "Return the key/value pair sequences as a map for those values that are data per `has-some?`." [entries] (->> entries (map (fn [[k elt]] (if (has-some? elt) (array-map k elt)))) (remove nil?) (apply merge)))
true
(ns ^{:doc "Utility functions" :author "PI:NAME:<NAME>END_PI"} zensols.nlparse.util) (defn has-some? "Return whether or not the data should be added to a data structure." [data] (and data (or (not (or (associative? data) (sequential? data) (instance? java.util.Set data))) (not (empty? data))))) (defn map-if-data "Return the key/value pair sequences as a map for those values that are data per `has-some?`." [entries] (->> entries (map (fn [[k elt]] (if (has-some? elt) (array-map k elt)))) (remove nil?) (apply merge)))
[ { "context": ";; The MIT License (MIT)\n;;\n;; Copyright (c) 2016 Richard Hull\n;;\n;; Permission is hereby granted, free of charg", "end": 62, "score": 0.9997892379760742, "start": 50, "tag": "NAME", "value": "Richard Hull" } ]
src/nvd/task/purge_database.clj
plaguna/lein-nvd
160
;; The MIT License (MIT) ;; ;; Copyright (c) 2016 Richard Hull ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in all ;; copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns nvd.task.purge-database (:require [clojure.java.io :as io] [clansi :refer [style]] [nvd.config :refer [with-config]])) (defn -main [config-file] (with-config [project config-file] (let [db (io/file (get-in project [:nvd :data-directory]) "dc.h2.db")] (when (and (.exists db) (.delete db)) (println "Database file purged:" (style (.getAbsolutePath db) :bright)) true))))
44373
;; The MIT License (MIT) ;; ;; Copyright (c) 2016 <NAME> ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in all ;; copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns nvd.task.purge-database (:require [clojure.java.io :as io] [clansi :refer [style]] [nvd.config :refer [with-config]])) (defn -main [config-file] (with-config [project config-file] (let [db (io/file (get-in project [:nvd :data-directory]) "dc.h2.db")] (when (and (.exists db) (.delete db)) (println "Database file purged:" (style (.getAbsolutePath db) :bright)) true))))
true
;; The MIT License (MIT) ;; ;; Copyright (c) 2016 PI:NAME:<NAME>END_PI ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in all ;; copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns nvd.task.purge-database (:require [clojure.java.io :as io] [clansi :refer [style]] [nvd.config :refer [with-config]])) (defn -main [config-file] (with-config [project config-file] (let [db (io/file (get-in project [:nvd :data-directory]) "dc.h2.db")] (when (and (.exists db) (.delete db)) (println "Database file purged:" (style (.getAbsolutePath db) :bright)) true))))
[ { "context": ";\n; Copyright (C) 2011,2012 Carlo Sciolla\n; 2014 Peter Monks rewritten a", "end": 41, "score": 0.9998819231987, "start": 28, "tag": "NAME", "value": "Carlo Sciolla" }, { "context": " 2011,2012 Carlo Sciolla\n; 2014 Peter Monks rewritten around fn-generating macros\n;\n; License", "end": 79, "score": 0.9997324347496033, "start": 68, "tag": "NAME", "value": "Peter Monks" } ]
src/clojure/alfresco/behave.clj
lambdalf/lambdalf
11
; ; Copyright (C) 2011,2012 Carlo Sciolla ; 2014 Peter Monks rewritten around fn-generating macros ; ; 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 alfresco.behave (:require [alfresco.core :as c] [alfresco.model :as m]) (:import [org.alfresco.repo.policy JavaBehaviour Behaviour$NotificationFrequency PolicyComponent])) ;; Not available from the ServiceRegistry (yet), unfortunately... (defn ^PolicyComponent policy-component [] (c/get-bean "policyComponent")) (defmacro ^:private gen-policy-registration-fn "Generates a registration function for an Alfresco policy. fn-name: the name of the generated Clojure function policy-if: the Alfresco interface of the selected policy policy-method: the Java method in that interface that needs to be implemented by the custom behaviour params: the parameters that method takes" [fn-name policy-if policy-method params] `(defn ~fn-name ~(str "Registers the function f as a handler for behaviour " policy-if ", for the given qname. f must accept parameters: " "[" (clojure.string/join " " params) "]" "\nNote: Handlers only fire on transaction commit.") [~'qname ~'f] (let [p# (reify ~policy-if (~policy-method [~'this ~@params] (~'f ~@params))) b# (JavaBehaviour. p# ~(str policy-method) Behaviour$NotificationFrequency/TRANSACTION_COMMIT)] (.bindClassBehaviour (policy-component) ~(symbol (str policy-if "/QNAME")) (m/qname ~'qname) b#) nil))) (def ^:private policies "A list of all of the Alfresco policies supported by lambdalf (note: doesn't include all of the available policies). This list is used by the gen-policy-registration-fns macro to generate the various registration functions and Alfresco Java API interop boilerplate." [ ;clojure-fn-name alfresco-policy-class policy-method policy-method-parameters ;----------------------- -------------------------------------------------------------------------- ------------------------- -------------------------------- ; NodeServicePolicies ['on-create-node! 'org.alfresco.repo.node.NodeServicePolicies$OnCreateNodePolicy 'onCreateNode '[child-assoc-ref]] ['on-update-node! 'org.alfresco.repo.node.NodeServicePolicies$OnUpdateNodePolicy 'onUpdateNode '[node]] ['on-move-node! 'org.alfresco.repo.node.NodeServicePolicies$OnMoveNodePolicy 'onMoveNode '[old-child-assoc-ref new-child-assoc-ref]] ['on-update-properties! 'org.alfresco.repo.node.NodeServicePolicies$OnUpdatePropertiesPolicy 'onUpdateProperties '[node before-props after-props]] ['on-delete-node! 'org.alfresco.repo.node.NodeServicePolicies$OnDeleteNodePolicy 'onDeleteNode '[child-assoc-ref is-node-archived?]] ['on-restore-node! 'org.alfresco.repo.node.NodeServicePolicies$OnRestoreNodePolicy 'onRestoreNode '[child-assoc-ref]] ['on-set-node-type! 'org.alfresco.repo.node.NodeServicePolicies$OnSetNodeTypePolicy 'onSetNodeType '[node old-type new-type]] ['on-add-aspect! 'org.alfresco.repo.node.NodeServicePolicies$OnAddAspectPolicy 'onAddAspect '[node aspect-qname]] ['on-remove-aspect! 'org.alfresco.repo.node.NodeServicePolicies$OnRemoveAspectPolicy 'onRemoveAspect '[node aspect-qname]] ['on-create-child-assoc! 'org.alfresco.repo.node.NodeServicePolicies$OnCreateChildAssociationPolicy 'onCreateChildAssociation '[child-assoc-ref is-new-node?]] ['on-delete-child-assoc! 'org.alfresco.repo.node.NodeServicePolicies$OnDeleteChildAssociationPolicy 'onDeleteChildAssociation '[child-assoc-ref]] ['on-create-assoc! 'org.alfresco.repo.node.NodeServicePolicies$OnCreateAssociationPolicy 'onCreateAssociation '[node-assoc-ref]] ['on-delete-assoc! 'org.alfresco.repo.node.NodeServicePolicies$OnDeleteAssociationPolicy 'onDeleteAssociation '[node-assoc-ref]] ; ContentServicePolicies ['on-content-update! 'org.alfresco.repo.content.ContentServicePolicies$OnContentUpdatePolicy 'onContentUpdate '[node is-new-content?]] ['on-content-property-update! 'org.alfresco.repo.content.ContentServicePolicies$OnContentPropertyUpdatePolicy 'onContentPropertyUpdate '[node property-qname before-value after-value]] ['on-content-read! 'org.alfresco.repo.content.ContentServicePolicies$OnContentReadPolicy 'onContentRead '[node]] ; VersionServicePolicies ['on-create-version! 'org.alfresco.repo.version.VersionServicePolicies$OnCreateVersionPolicy 'onCreateVersion '[class-ref-qname node version-properties node-details]] ; CopyServicePolicies ['on-copy-complete! 'org.alfresco.repo.copy.CopyServicePolicies$OnCopyCompletePolicy 'onCopyComplete '[class-ref-qname source-node target-node is-copy-to-new-node? copy-map]] ; CheckOutCheckInServicePolicies ['on-check-out! 'org.alfresco.repo.coci.CheckOutCheckInServicePolicies$OnCheckOut 'onCheckOut '[working-copy-node]] ['on-check-in! 'org.alfresco.repo.coci.CheckOutCheckInServicePolicies$OnCheckIn 'onCheckIn '[node]] ['on-cancel-check-out! 'org.alfresco.repo.coci.CheckOutCheckInServicePolicies$OnCancelCheckOut 'onCancelCheckOut '[node]] ]) (defn- third "The third item in the given collection." [col] (first (next (next col)))) (defn- fourth "The fourth item in the given collection." [col] (first (next (next (next col))))) (defmacro ^:private gen-policy-registration-fns "Generates all policy registration fns defined in the 'policies' vector." [] `(do ~@(for [policy policies] `(gen-policy-registration-fn ~(first policy) ~(second policy) ~(third policy) ~(fourth policy))))) (gen-policy-registration-fns)
7181
; ; Copyright (C) 2011,2012 <NAME> ; 2014 <NAME> rewritten around fn-generating macros ; ; 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 alfresco.behave (:require [alfresco.core :as c] [alfresco.model :as m]) (:import [org.alfresco.repo.policy JavaBehaviour Behaviour$NotificationFrequency PolicyComponent])) ;; Not available from the ServiceRegistry (yet), unfortunately... (defn ^PolicyComponent policy-component [] (c/get-bean "policyComponent")) (defmacro ^:private gen-policy-registration-fn "Generates a registration function for an Alfresco policy. fn-name: the name of the generated Clojure function policy-if: the Alfresco interface of the selected policy policy-method: the Java method in that interface that needs to be implemented by the custom behaviour params: the parameters that method takes" [fn-name policy-if policy-method params] `(defn ~fn-name ~(str "Registers the function f as a handler for behaviour " policy-if ", for the given qname. f must accept parameters: " "[" (clojure.string/join " " params) "]" "\nNote: Handlers only fire on transaction commit.") [~'qname ~'f] (let [p# (reify ~policy-if (~policy-method [~'this ~@params] (~'f ~@params))) b# (JavaBehaviour. p# ~(str policy-method) Behaviour$NotificationFrequency/TRANSACTION_COMMIT)] (.bindClassBehaviour (policy-component) ~(symbol (str policy-if "/QNAME")) (m/qname ~'qname) b#) nil))) (def ^:private policies "A list of all of the Alfresco policies supported by lambdalf (note: doesn't include all of the available policies). This list is used by the gen-policy-registration-fns macro to generate the various registration functions and Alfresco Java API interop boilerplate." [ ;clojure-fn-name alfresco-policy-class policy-method policy-method-parameters ;----------------------- -------------------------------------------------------------------------- ------------------------- -------------------------------- ; NodeServicePolicies ['on-create-node! 'org.alfresco.repo.node.NodeServicePolicies$OnCreateNodePolicy 'onCreateNode '[child-assoc-ref]] ['on-update-node! 'org.alfresco.repo.node.NodeServicePolicies$OnUpdateNodePolicy 'onUpdateNode '[node]] ['on-move-node! 'org.alfresco.repo.node.NodeServicePolicies$OnMoveNodePolicy 'onMoveNode '[old-child-assoc-ref new-child-assoc-ref]] ['on-update-properties! 'org.alfresco.repo.node.NodeServicePolicies$OnUpdatePropertiesPolicy 'onUpdateProperties '[node before-props after-props]] ['on-delete-node! 'org.alfresco.repo.node.NodeServicePolicies$OnDeleteNodePolicy 'onDeleteNode '[child-assoc-ref is-node-archived?]] ['on-restore-node! 'org.alfresco.repo.node.NodeServicePolicies$OnRestoreNodePolicy 'onRestoreNode '[child-assoc-ref]] ['on-set-node-type! 'org.alfresco.repo.node.NodeServicePolicies$OnSetNodeTypePolicy 'onSetNodeType '[node old-type new-type]] ['on-add-aspect! 'org.alfresco.repo.node.NodeServicePolicies$OnAddAspectPolicy 'onAddAspect '[node aspect-qname]] ['on-remove-aspect! 'org.alfresco.repo.node.NodeServicePolicies$OnRemoveAspectPolicy 'onRemoveAspect '[node aspect-qname]] ['on-create-child-assoc! 'org.alfresco.repo.node.NodeServicePolicies$OnCreateChildAssociationPolicy 'onCreateChildAssociation '[child-assoc-ref is-new-node?]] ['on-delete-child-assoc! 'org.alfresco.repo.node.NodeServicePolicies$OnDeleteChildAssociationPolicy 'onDeleteChildAssociation '[child-assoc-ref]] ['on-create-assoc! 'org.alfresco.repo.node.NodeServicePolicies$OnCreateAssociationPolicy 'onCreateAssociation '[node-assoc-ref]] ['on-delete-assoc! 'org.alfresco.repo.node.NodeServicePolicies$OnDeleteAssociationPolicy 'onDeleteAssociation '[node-assoc-ref]] ; ContentServicePolicies ['on-content-update! 'org.alfresco.repo.content.ContentServicePolicies$OnContentUpdatePolicy 'onContentUpdate '[node is-new-content?]] ['on-content-property-update! 'org.alfresco.repo.content.ContentServicePolicies$OnContentPropertyUpdatePolicy 'onContentPropertyUpdate '[node property-qname before-value after-value]] ['on-content-read! 'org.alfresco.repo.content.ContentServicePolicies$OnContentReadPolicy 'onContentRead '[node]] ; VersionServicePolicies ['on-create-version! 'org.alfresco.repo.version.VersionServicePolicies$OnCreateVersionPolicy 'onCreateVersion '[class-ref-qname node version-properties node-details]] ; CopyServicePolicies ['on-copy-complete! 'org.alfresco.repo.copy.CopyServicePolicies$OnCopyCompletePolicy 'onCopyComplete '[class-ref-qname source-node target-node is-copy-to-new-node? copy-map]] ; CheckOutCheckInServicePolicies ['on-check-out! 'org.alfresco.repo.coci.CheckOutCheckInServicePolicies$OnCheckOut 'onCheckOut '[working-copy-node]] ['on-check-in! 'org.alfresco.repo.coci.CheckOutCheckInServicePolicies$OnCheckIn 'onCheckIn '[node]] ['on-cancel-check-out! 'org.alfresco.repo.coci.CheckOutCheckInServicePolicies$OnCancelCheckOut 'onCancelCheckOut '[node]] ]) (defn- third "The third item in the given collection." [col] (first (next (next col)))) (defn- fourth "The fourth item in the given collection." [col] (first (next (next (next col))))) (defmacro ^:private gen-policy-registration-fns "Generates all policy registration fns defined in the 'policies' vector." [] `(do ~@(for [policy policies] `(gen-policy-registration-fn ~(first policy) ~(second policy) ~(third policy) ~(fourth policy))))) (gen-policy-registration-fns)
true
; ; Copyright (C) 2011,2012 PI:NAME:<NAME>END_PI ; 2014 PI:NAME:<NAME>END_PI rewritten around fn-generating macros ; ; 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 alfresco.behave (:require [alfresco.core :as c] [alfresco.model :as m]) (:import [org.alfresco.repo.policy JavaBehaviour Behaviour$NotificationFrequency PolicyComponent])) ;; Not available from the ServiceRegistry (yet), unfortunately... (defn ^PolicyComponent policy-component [] (c/get-bean "policyComponent")) (defmacro ^:private gen-policy-registration-fn "Generates a registration function for an Alfresco policy. fn-name: the name of the generated Clojure function policy-if: the Alfresco interface of the selected policy policy-method: the Java method in that interface that needs to be implemented by the custom behaviour params: the parameters that method takes" [fn-name policy-if policy-method params] `(defn ~fn-name ~(str "Registers the function f as a handler for behaviour " policy-if ", for the given qname. f must accept parameters: " "[" (clojure.string/join " " params) "]" "\nNote: Handlers only fire on transaction commit.") [~'qname ~'f] (let [p# (reify ~policy-if (~policy-method [~'this ~@params] (~'f ~@params))) b# (JavaBehaviour. p# ~(str policy-method) Behaviour$NotificationFrequency/TRANSACTION_COMMIT)] (.bindClassBehaviour (policy-component) ~(symbol (str policy-if "/QNAME")) (m/qname ~'qname) b#) nil))) (def ^:private policies "A list of all of the Alfresco policies supported by lambdalf (note: doesn't include all of the available policies). This list is used by the gen-policy-registration-fns macro to generate the various registration functions and Alfresco Java API interop boilerplate." [ ;clojure-fn-name alfresco-policy-class policy-method policy-method-parameters ;----------------------- -------------------------------------------------------------------------- ------------------------- -------------------------------- ; NodeServicePolicies ['on-create-node! 'org.alfresco.repo.node.NodeServicePolicies$OnCreateNodePolicy 'onCreateNode '[child-assoc-ref]] ['on-update-node! 'org.alfresco.repo.node.NodeServicePolicies$OnUpdateNodePolicy 'onUpdateNode '[node]] ['on-move-node! 'org.alfresco.repo.node.NodeServicePolicies$OnMoveNodePolicy 'onMoveNode '[old-child-assoc-ref new-child-assoc-ref]] ['on-update-properties! 'org.alfresco.repo.node.NodeServicePolicies$OnUpdatePropertiesPolicy 'onUpdateProperties '[node before-props after-props]] ['on-delete-node! 'org.alfresco.repo.node.NodeServicePolicies$OnDeleteNodePolicy 'onDeleteNode '[child-assoc-ref is-node-archived?]] ['on-restore-node! 'org.alfresco.repo.node.NodeServicePolicies$OnRestoreNodePolicy 'onRestoreNode '[child-assoc-ref]] ['on-set-node-type! 'org.alfresco.repo.node.NodeServicePolicies$OnSetNodeTypePolicy 'onSetNodeType '[node old-type new-type]] ['on-add-aspect! 'org.alfresco.repo.node.NodeServicePolicies$OnAddAspectPolicy 'onAddAspect '[node aspect-qname]] ['on-remove-aspect! 'org.alfresco.repo.node.NodeServicePolicies$OnRemoveAspectPolicy 'onRemoveAspect '[node aspect-qname]] ['on-create-child-assoc! 'org.alfresco.repo.node.NodeServicePolicies$OnCreateChildAssociationPolicy 'onCreateChildAssociation '[child-assoc-ref is-new-node?]] ['on-delete-child-assoc! 'org.alfresco.repo.node.NodeServicePolicies$OnDeleteChildAssociationPolicy 'onDeleteChildAssociation '[child-assoc-ref]] ['on-create-assoc! 'org.alfresco.repo.node.NodeServicePolicies$OnCreateAssociationPolicy 'onCreateAssociation '[node-assoc-ref]] ['on-delete-assoc! 'org.alfresco.repo.node.NodeServicePolicies$OnDeleteAssociationPolicy 'onDeleteAssociation '[node-assoc-ref]] ; ContentServicePolicies ['on-content-update! 'org.alfresco.repo.content.ContentServicePolicies$OnContentUpdatePolicy 'onContentUpdate '[node is-new-content?]] ['on-content-property-update! 'org.alfresco.repo.content.ContentServicePolicies$OnContentPropertyUpdatePolicy 'onContentPropertyUpdate '[node property-qname before-value after-value]] ['on-content-read! 'org.alfresco.repo.content.ContentServicePolicies$OnContentReadPolicy 'onContentRead '[node]] ; VersionServicePolicies ['on-create-version! 'org.alfresco.repo.version.VersionServicePolicies$OnCreateVersionPolicy 'onCreateVersion '[class-ref-qname node version-properties node-details]] ; CopyServicePolicies ['on-copy-complete! 'org.alfresco.repo.copy.CopyServicePolicies$OnCopyCompletePolicy 'onCopyComplete '[class-ref-qname source-node target-node is-copy-to-new-node? copy-map]] ; CheckOutCheckInServicePolicies ['on-check-out! 'org.alfresco.repo.coci.CheckOutCheckInServicePolicies$OnCheckOut 'onCheckOut '[working-copy-node]] ['on-check-in! 'org.alfresco.repo.coci.CheckOutCheckInServicePolicies$OnCheckIn 'onCheckIn '[node]] ['on-cancel-check-out! 'org.alfresco.repo.coci.CheckOutCheckInServicePolicies$OnCancelCheckOut 'onCancelCheckOut '[node]] ]) (defn- third "The third item in the given collection." [col] (first (next (next col)))) (defn- fourth "The fourth item in the given collection." [col] (first (next (next (next col))))) (defmacro ^:private gen-policy-registration-fns "Generates all policy registration fns defined in the 'policies' vector." [] `(do ~@(for [policy policies] `(gen-policy-registration-fn ~(first policy) ~(second policy) ~(third policy) ~(fourth policy))))) (gen-policy-registration-fns)
[ { "context": "rofile_picture]\n (let [{:keys [id name first_name last_name badges mtime]} element-data\n badges (", "end": 1920, "score": 0.5329338908195496, "start": 1916, "tag": "NAME", "value": "last" } ]
src/cljs/salava/user/ui/embed.cljs
Vilikkki/salava
17
(ns salava.user.ui.embed (:require [reagent.core :refer [atom cursor]] [reagent.session :as session] [salava.core.ui.ajax-utils :as ajax] [salava.core.ui.layout :as layout] [salava.core.ui.share :as s] [salava.core.ui.helper :refer [path-for]] [salava.user.schemas :refer [contact-fields]] [salava.user.ui.helper :refer [profile-picture]] [salava.core.i18n :refer [t]] [salava.core.time :refer [date-from-unix-time]] [salava.core.helper :refer [dump]] [reagent-modals.modals :as m] )) (defn toggle-visibility [visibility-atom] (ajax/POST (path-for "/obpv1/user/profile/set_visibility") {:params {:visibility (if (= "internal" @visibility-atom) "public" "internal")} :handler (fn [new-value] (reset! visibility-atom new-value) )})) (defn profile-visibility-input [visibility-atom] [:div.col-xs-12 [:div.checkbox [:label [:input {:name "visibility" :type "checkbox" :on-change #(toggle-visibility visibility-atom) :checked (= "public" @visibility-atom)}] (t :user/Publishandshare)]]]) (defn badge-grid-element [element-data] (let [{:keys [id image_file name description]} element-data] [:div {:class "col-xs-12 col-sm-6 col-md-4" :key id} [:div {:class "media grid-container"} [:div.media-content (if image_file [:div.media-left [:img {:src (str "/" image_file)}]]) [:div.media-body [:div.media-heading [:a.heading-link {:target "_blank" :href (path-for (str "/badge/info/" id))} name]] [:div.media-description description]]]]])) (defn page-grid-element [element-data profile_picture] (let [{:keys [id name first_name last_name badges mtime]} element-data badges (take 4 badges)] [:div {:class "col-xs-12 col-sm-6 col-md-4" :key id} [:div {:class "media grid-container"} [:div.media-content [:div.media-body [:div.media-heading [:a.heading-link {:target "_blank" :href (path-for (str "/page/view/" id))} name]] [:div.media-content [:div.page-owner [:a {:href "#"} first_name " " last_name]] [:div.page-create-date (date-from-unix-time (* 1000 mtime) "minutes")] (into [:div.page-badges] (for [badge badges] [:img {:title (:name badge) :src (str "/" (:image_file badge))}]))]] [:div {:class "media-right"} [:img {:src (profile-picture profile_picture)}]]]]])) (defn badge-grid [badges] (into [:div {:class "row" :id "grid"}] (for [element-data (sort-by :mtime > badges)] (badge-grid-element element-data)))) (defn page-grid [pages profile_picture] (into [:div {:class "row" :id "grid"}] (for [element-data (sort-by :mtime > pages)] (page-grid-element element-data profile_picture)))) (defn content [state] (let [visibility-atom (cursor state [:user :profile_visibility]) link-or-embed-atom (cursor state [:user :show-link-or-embed-code]) {badges :badges pages :pages owner? :owner? {first_name :first_name last_name :last_name profile_picture :profile_picture about :about} :user profile :profile user-id :user-id} @state fullname (str first_name " " last_name)] [:div.panel {:id "profile"} [m/modal-window] [:div.panel-body [:h1.uppercase-header fullname] [:div.row [:div {:class "col-md-4 col-sm-4 col-xs-12"} [:img.profile-picture {:src (profile-picture profile_picture)}]] [:div {:class "col-md-8 col-sm-8 col-xs-12"} (if (not-empty about) [:div {:class "row about"} [:div.col-xs-12 [:b (t :user/Aboutme) ":"]] [:div.col-xs-12 about]]) (if (not-empty profile) [:div.row [:div.col-xs-12 [:b (t :user/Contactinfo) ":"]] [:div.col-xs-12 [:table.table (into [:tbody] (for [profile-field (sort-by :order profile) :let [{:keys [field value]} profile-field key (->> contact-fields (filter #(= (:type %) field)) first :key)]] [:tr [:td.profile-field (t key) ":"] [:td (cond (or (re-find #"www." (str value)) (re-find #"^https?://" (str value))) [:a {:href value :target "_blank"} (t value)] (and (re-find #"@" (str value)) (= "twitter" field)) [:a {:href (str "https://twitter.com/" value) :target "_blank" } (t value)] (and (re-find #"@" (str value)) (= "email" field)) [:a {:href (str "mailto:" value)} (t value)] (and (empty? (re-find #" " (str value))) (= "facebook" field)) [:a {:href (str "https://www.facebook.com/" value) :target "_blank" } (t value)] (= "twitter" field) [:a {:href (str "https://twitter.com/" value) :target "_blank" } (t value)] (and (empty? (re-find #" " (str value))) (= "pinterest" field)) [:a {:href (str "https://www.pinterest.com/" value) :target "_blank" } (t value)] (and (empty? (re-find #" " (str value))) (= "instagram" field)) [:a {:href (str "https://www.instagram.com/" value) :target "_blank" } (t value)] :else (t value))]]))]]] )]] (if (not-empty badges) [:div {:id "user-badges"} [:h2 {:class "uppercase-header user-profile-header"} (t :user/Recentbadges)] [badge-grid badges] [:div [:a {:target "_blank" :href (path-for (str "/gallery/badges/" user-id))} (t :user/Showmore)]]]) (if (not-empty pages) [:div {:id "user-pages"} [:h2 {:class "uppercase-header user-profile-header"} (t :user/Recentpages)] [page-grid pages profile_picture] [:div [:a {:target "_blank" :href (path-for (str "/gallery/pages/" user-id))} (t :user/Showmore)]]]) ]])) (defn init-data [user-id state] (ajax/GET (path-for (str "/obpv1/user/profile/" user-id) true) {:handler (fn [data] (reset! state (assoc data :user-id user-id :show-link-or-embed-code nil)))}) ) (defn handler [site-navi params] (let [user-id (:user-id params) state (atom {:user-id user-id :reporttool {}}) user (session/get :user)] (init-data user-id state) (fn [] (layout/embed-page (content state)))))
41426
(ns salava.user.ui.embed (:require [reagent.core :refer [atom cursor]] [reagent.session :as session] [salava.core.ui.ajax-utils :as ajax] [salava.core.ui.layout :as layout] [salava.core.ui.share :as s] [salava.core.ui.helper :refer [path-for]] [salava.user.schemas :refer [contact-fields]] [salava.user.ui.helper :refer [profile-picture]] [salava.core.i18n :refer [t]] [salava.core.time :refer [date-from-unix-time]] [salava.core.helper :refer [dump]] [reagent-modals.modals :as m] )) (defn toggle-visibility [visibility-atom] (ajax/POST (path-for "/obpv1/user/profile/set_visibility") {:params {:visibility (if (= "internal" @visibility-atom) "public" "internal")} :handler (fn [new-value] (reset! visibility-atom new-value) )})) (defn profile-visibility-input [visibility-atom] [:div.col-xs-12 [:div.checkbox [:label [:input {:name "visibility" :type "checkbox" :on-change #(toggle-visibility visibility-atom) :checked (= "public" @visibility-atom)}] (t :user/Publishandshare)]]]) (defn badge-grid-element [element-data] (let [{:keys [id image_file name description]} element-data] [:div {:class "col-xs-12 col-sm-6 col-md-4" :key id} [:div {:class "media grid-container"} [:div.media-content (if image_file [:div.media-left [:img {:src (str "/" image_file)}]]) [:div.media-body [:div.media-heading [:a.heading-link {:target "_blank" :href (path-for (str "/badge/info/" id))} name]] [:div.media-description description]]]]])) (defn page-grid-element [element-data profile_picture] (let [{:keys [id name first_name <NAME>_name badges mtime]} element-data badges (take 4 badges)] [:div {:class "col-xs-12 col-sm-6 col-md-4" :key id} [:div {:class "media grid-container"} [:div.media-content [:div.media-body [:div.media-heading [:a.heading-link {:target "_blank" :href (path-for (str "/page/view/" id))} name]] [:div.media-content [:div.page-owner [:a {:href "#"} first_name " " last_name]] [:div.page-create-date (date-from-unix-time (* 1000 mtime) "minutes")] (into [:div.page-badges] (for [badge badges] [:img {:title (:name badge) :src (str "/" (:image_file badge))}]))]] [:div {:class "media-right"} [:img {:src (profile-picture profile_picture)}]]]]])) (defn badge-grid [badges] (into [:div {:class "row" :id "grid"}] (for [element-data (sort-by :mtime > badges)] (badge-grid-element element-data)))) (defn page-grid [pages profile_picture] (into [:div {:class "row" :id "grid"}] (for [element-data (sort-by :mtime > pages)] (page-grid-element element-data profile_picture)))) (defn content [state] (let [visibility-atom (cursor state [:user :profile_visibility]) link-or-embed-atom (cursor state [:user :show-link-or-embed-code]) {badges :badges pages :pages owner? :owner? {first_name :first_name last_name :last_name profile_picture :profile_picture about :about} :user profile :profile user-id :user-id} @state fullname (str first_name " " last_name)] [:div.panel {:id "profile"} [m/modal-window] [:div.panel-body [:h1.uppercase-header fullname] [:div.row [:div {:class "col-md-4 col-sm-4 col-xs-12"} [:img.profile-picture {:src (profile-picture profile_picture)}]] [:div {:class "col-md-8 col-sm-8 col-xs-12"} (if (not-empty about) [:div {:class "row about"} [:div.col-xs-12 [:b (t :user/Aboutme) ":"]] [:div.col-xs-12 about]]) (if (not-empty profile) [:div.row [:div.col-xs-12 [:b (t :user/Contactinfo) ":"]] [:div.col-xs-12 [:table.table (into [:tbody] (for [profile-field (sort-by :order profile) :let [{:keys [field value]} profile-field key (->> contact-fields (filter #(= (:type %) field)) first :key)]] [:tr [:td.profile-field (t key) ":"] [:td (cond (or (re-find #"www." (str value)) (re-find #"^https?://" (str value))) [:a {:href value :target "_blank"} (t value)] (and (re-find #"@" (str value)) (= "twitter" field)) [:a {:href (str "https://twitter.com/" value) :target "_blank" } (t value)] (and (re-find #"@" (str value)) (= "email" field)) [:a {:href (str "mailto:" value)} (t value)] (and (empty? (re-find #" " (str value))) (= "facebook" field)) [:a {:href (str "https://www.facebook.com/" value) :target "_blank" } (t value)] (= "twitter" field) [:a {:href (str "https://twitter.com/" value) :target "_blank" } (t value)] (and (empty? (re-find #" " (str value))) (= "pinterest" field)) [:a {:href (str "https://www.pinterest.com/" value) :target "_blank" } (t value)] (and (empty? (re-find #" " (str value))) (= "instagram" field)) [:a {:href (str "https://www.instagram.com/" value) :target "_blank" } (t value)] :else (t value))]]))]]] )]] (if (not-empty badges) [:div {:id "user-badges"} [:h2 {:class "uppercase-header user-profile-header"} (t :user/Recentbadges)] [badge-grid badges] [:div [:a {:target "_blank" :href (path-for (str "/gallery/badges/" user-id))} (t :user/Showmore)]]]) (if (not-empty pages) [:div {:id "user-pages"} [:h2 {:class "uppercase-header user-profile-header"} (t :user/Recentpages)] [page-grid pages profile_picture] [:div [:a {:target "_blank" :href (path-for (str "/gallery/pages/" user-id))} (t :user/Showmore)]]]) ]])) (defn init-data [user-id state] (ajax/GET (path-for (str "/obpv1/user/profile/" user-id) true) {:handler (fn [data] (reset! state (assoc data :user-id user-id :show-link-or-embed-code nil)))}) ) (defn handler [site-navi params] (let [user-id (:user-id params) state (atom {:user-id user-id :reporttool {}}) user (session/get :user)] (init-data user-id state) (fn [] (layout/embed-page (content state)))))
true
(ns salava.user.ui.embed (:require [reagent.core :refer [atom cursor]] [reagent.session :as session] [salava.core.ui.ajax-utils :as ajax] [salava.core.ui.layout :as layout] [salava.core.ui.share :as s] [salava.core.ui.helper :refer [path-for]] [salava.user.schemas :refer [contact-fields]] [salava.user.ui.helper :refer [profile-picture]] [salava.core.i18n :refer [t]] [salava.core.time :refer [date-from-unix-time]] [salava.core.helper :refer [dump]] [reagent-modals.modals :as m] )) (defn toggle-visibility [visibility-atom] (ajax/POST (path-for "/obpv1/user/profile/set_visibility") {:params {:visibility (if (= "internal" @visibility-atom) "public" "internal")} :handler (fn [new-value] (reset! visibility-atom new-value) )})) (defn profile-visibility-input [visibility-atom] [:div.col-xs-12 [:div.checkbox [:label [:input {:name "visibility" :type "checkbox" :on-change #(toggle-visibility visibility-atom) :checked (= "public" @visibility-atom)}] (t :user/Publishandshare)]]]) (defn badge-grid-element [element-data] (let [{:keys [id image_file name description]} element-data] [:div {:class "col-xs-12 col-sm-6 col-md-4" :key id} [:div {:class "media grid-container"} [:div.media-content (if image_file [:div.media-left [:img {:src (str "/" image_file)}]]) [:div.media-body [:div.media-heading [:a.heading-link {:target "_blank" :href (path-for (str "/badge/info/" id))} name]] [:div.media-description description]]]]])) (defn page-grid-element [element-data profile_picture] (let [{:keys [id name first_name PI:NAME:<NAME>END_PI_name badges mtime]} element-data badges (take 4 badges)] [:div {:class "col-xs-12 col-sm-6 col-md-4" :key id} [:div {:class "media grid-container"} [:div.media-content [:div.media-body [:div.media-heading [:a.heading-link {:target "_blank" :href (path-for (str "/page/view/" id))} name]] [:div.media-content [:div.page-owner [:a {:href "#"} first_name " " last_name]] [:div.page-create-date (date-from-unix-time (* 1000 mtime) "minutes")] (into [:div.page-badges] (for [badge badges] [:img {:title (:name badge) :src (str "/" (:image_file badge))}]))]] [:div {:class "media-right"} [:img {:src (profile-picture profile_picture)}]]]]])) (defn badge-grid [badges] (into [:div {:class "row" :id "grid"}] (for [element-data (sort-by :mtime > badges)] (badge-grid-element element-data)))) (defn page-grid [pages profile_picture] (into [:div {:class "row" :id "grid"}] (for [element-data (sort-by :mtime > pages)] (page-grid-element element-data profile_picture)))) (defn content [state] (let [visibility-atom (cursor state [:user :profile_visibility]) link-or-embed-atom (cursor state [:user :show-link-or-embed-code]) {badges :badges pages :pages owner? :owner? {first_name :first_name last_name :last_name profile_picture :profile_picture about :about} :user profile :profile user-id :user-id} @state fullname (str first_name " " last_name)] [:div.panel {:id "profile"} [m/modal-window] [:div.panel-body [:h1.uppercase-header fullname] [:div.row [:div {:class "col-md-4 col-sm-4 col-xs-12"} [:img.profile-picture {:src (profile-picture profile_picture)}]] [:div {:class "col-md-8 col-sm-8 col-xs-12"} (if (not-empty about) [:div {:class "row about"} [:div.col-xs-12 [:b (t :user/Aboutme) ":"]] [:div.col-xs-12 about]]) (if (not-empty profile) [:div.row [:div.col-xs-12 [:b (t :user/Contactinfo) ":"]] [:div.col-xs-12 [:table.table (into [:tbody] (for [profile-field (sort-by :order profile) :let [{:keys [field value]} profile-field key (->> contact-fields (filter #(= (:type %) field)) first :key)]] [:tr [:td.profile-field (t key) ":"] [:td (cond (or (re-find #"www." (str value)) (re-find #"^https?://" (str value))) [:a {:href value :target "_blank"} (t value)] (and (re-find #"@" (str value)) (= "twitter" field)) [:a {:href (str "https://twitter.com/" value) :target "_blank" } (t value)] (and (re-find #"@" (str value)) (= "email" field)) [:a {:href (str "mailto:" value)} (t value)] (and (empty? (re-find #" " (str value))) (= "facebook" field)) [:a {:href (str "https://www.facebook.com/" value) :target "_blank" } (t value)] (= "twitter" field) [:a {:href (str "https://twitter.com/" value) :target "_blank" } (t value)] (and (empty? (re-find #" " (str value))) (= "pinterest" field)) [:a {:href (str "https://www.pinterest.com/" value) :target "_blank" } (t value)] (and (empty? (re-find #" " (str value))) (= "instagram" field)) [:a {:href (str "https://www.instagram.com/" value) :target "_blank" } (t value)] :else (t value))]]))]]] )]] (if (not-empty badges) [:div {:id "user-badges"} [:h2 {:class "uppercase-header user-profile-header"} (t :user/Recentbadges)] [badge-grid badges] [:div [:a {:target "_blank" :href (path-for (str "/gallery/badges/" user-id))} (t :user/Showmore)]]]) (if (not-empty pages) [:div {:id "user-pages"} [:h2 {:class "uppercase-header user-profile-header"} (t :user/Recentpages)] [page-grid pages profile_picture] [:div [:a {:target "_blank" :href (path-for (str "/gallery/pages/" user-id))} (t :user/Showmore)]]]) ]])) (defn init-data [user-id state] (ajax/GET (path-for (str "/obpv1/user/profile/" user-id) true) {:handler (fn [data] (reset! state (assoc data :user-id user-id :show-link-or-embed-code nil)))}) ) (defn handler [site-navi params] (let [user-id (:user-id params) state (atom {:user-id user-id :reporttool {}}) user (session/get :user)] (init-data user-id state) (fn [] (layout/embed-page (content state)))))
[ { "context": ";; The MIT License (MIT)\n;;\n;; Copyright (c) 2015 Richard Hull\n;;\n;; Permission is hereby granted, free of charg", "end": 62, "score": 0.9997815489768982, "start": 50, "tag": "NAME", "value": "Richard Hull" } ]
src/wam/compiler.clj
rm-hull/wam
23
;; The MIT License (MIT) ;; ;; Copyright (c) 2015 Richard Hull ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in all ;; copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns wam.compiler (:require [clojure.string :as s] [clojure.set :refer [union]] [jasentaa.parser :refer [parse-all]] [wam.instruction-set :refer :all] [wam.store :refer [friendly]] [wam.grammar :as g] [wam.graph-search :refer :all])) (defn register-names "Generates an infinite incrementing sequence of register symbols, e.g. X1, X2, X3, X4 ..." [prefix] (->> (iterate inc 1) (map #(symbol (str prefix %))))) (defn register-allocation "Variable registers are allocated to a term on a least available index basis such that (1) register X1 is always allocated to the otutermost term, and (2) the same register is allocated to all occurrences of a given variable. For example, registers are allocated to the variables of the term p(Z, h(Z,W), f(W)) as follows: X1 = p(X2, X3, X4) X2 = Z X3 = h(X2, X5) X4 = f(X5) X5 = W This amounts to saying that a term is seen as a flattened conjunctive set of equations of the form Xi = X or Xi = f(Xi1, ..., Xin), n>=0 where the Xi's are all distinct new variable names. A hashmap is returned with key as the term, and the value as allocated register," [term] (zipmap (bfs term) (register-names 'X))) (def query-builder {:structure-walker dfs-post-order :instruction-builder (fn [term register seen? arg?] (if (seen? term) (list set-value register) (cond (instance? wam.grammar.Structure term) (list put-structure (:functor term) register) (instance? wam.grammar.Variable term) (list set-variable register) :else nil)))}) (def program-builder {:structure-walker dfs-pre-order :instruction-builder (fn [term register seen? arg?] (cond (instance? wam.grammar.Structure term) (if arg? (list unify-variable register) (list get-structure (:functor term) register)) (instance? wam.grammar.Variable term) (if (seen? term) (list unify-value register) (list unify-variable register)) :else nil))}) (defn compile-structure [instruction-builder structure register-allocation seen?] (loop [args (:args structure) seen? seen? result [(instruction-builder structure (register-allocation structure) seen? false)]] (if (empty? args) result (recur (rest args) (conj seen? (first args)) (conj result (instruction-builder (first args) (register-allocation (first args)) seen? true)))))) (defn emit-instructions "Constructs a sequence of instructions (missing the context argument) suitable for threading with a context. The builder determines how the structures in the term are walked (generally pre-order for programs, and post-order for queries), and emits the most appropriate instructions for each structure, which is reliant on which arguments have been previously processed." [builder term register-allocation] (let [structure-walker (:structure-walker builder) instruction-builder (:instruction-builder builder)] (loop [structures (structure-walker term) seen? #{} result []] (if (empty? structures) result (let [structure (first structures)] (recur (rest structures) (conj (union seen? (set (:args structure))) structure) (concat result (compile-structure instruction-builder structure register-allocation seen?)))))))) (defn assoc-variables [ctx register-allocation] (->> register-allocation (filter #(instance? wam.grammar.Variable (first %))) (update ctx :variables concat))) (defn single-step "Execute an instruction with respect to the supplied context, if the fail flag has not been set. If the context has failed, then just return the context unchanged (i.e. don't execute the instruction). This causes the remaining instructions to also fall through." [ctx [instr & args]] (if-not (:fail ctx) (do (when (:trace ctx) (println (friendly (cons instr args)))) (apply instr ctx args)) ctx)) (defn compile-term "Emits a sequence of instructions that equates to provided term according to the rules of the builder. Returns a function which is capable of executing the instructions given a context." [builder term] (let [register-allocation (register-allocation term) instrs (emit-instructions builder term register-allocation)] (fn [ctx] (reduce single-step (assoc-variables ctx register-allocation) instrs)))) (defn query [ctx expression] (let [executor (->> expression (parse-all g/structure) (compile-term query-builder))] (executor ctx))) (defn program [ctx expression] (let [executor (->> expression (parse-all g/structure) (compile-term program-builder))] (executor ctx)))
72703
;; The MIT License (MIT) ;; ;; Copyright (c) 2015 <NAME> ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in all ;; copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns wam.compiler (:require [clojure.string :as s] [clojure.set :refer [union]] [jasentaa.parser :refer [parse-all]] [wam.instruction-set :refer :all] [wam.store :refer [friendly]] [wam.grammar :as g] [wam.graph-search :refer :all])) (defn register-names "Generates an infinite incrementing sequence of register symbols, e.g. X1, X2, X3, X4 ..." [prefix] (->> (iterate inc 1) (map #(symbol (str prefix %))))) (defn register-allocation "Variable registers are allocated to a term on a least available index basis such that (1) register X1 is always allocated to the otutermost term, and (2) the same register is allocated to all occurrences of a given variable. For example, registers are allocated to the variables of the term p(Z, h(Z,W), f(W)) as follows: X1 = p(X2, X3, X4) X2 = Z X3 = h(X2, X5) X4 = f(X5) X5 = W This amounts to saying that a term is seen as a flattened conjunctive set of equations of the form Xi = X or Xi = f(Xi1, ..., Xin), n>=0 where the Xi's are all distinct new variable names. A hashmap is returned with key as the term, and the value as allocated register," [term] (zipmap (bfs term) (register-names 'X))) (def query-builder {:structure-walker dfs-post-order :instruction-builder (fn [term register seen? arg?] (if (seen? term) (list set-value register) (cond (instance? wam.grammar.Structure term) (list put-structure (:functor term) register) (instance? wam.grammar.Variable term) (list set-variable register) :else nil)))}) (def program-builder {:structure-walker dfs-pre-order :instruction-builder (fn [term register seen? arg?] (cond (instance? wam.grammar.Structure term) (if arg? (list unify-variable register) (list get-structure (:functor term) register)) (instance? wam.grammar.Variable term) (if (seen? term) (list unify-value register) (list unify-variable register)) :else nil))}) (defn compile-structure [instruction-builder structure register-allocation seen?] (loop [args (:args structure) seen? seen? result [(instruction-builder structure (register-allocation structure) seen? false)]] (if (empty? args) result (recur (rest args) (conj seen? (first args)) (conj result (instruction-builder (first args) (register-allocation (first args)) seen? true)))))) (defn emit-instructions "Constructs a sequence of instructions (missing the context argument) suitable for threading with a context. The builder determines how the structures in the term are walked (generally pre-order for programs, and post-order for queries), and emits the most appropriate instructions for each structure, which is reliant on which arguments have been previously processed." [builder term register-allocation] (let [structure-walker (:structure-walker builder) instruction-builder (:instruction-builder builder)] (loop [structures (structure-walker term) seen? #{} result []] (if (empty? structures) result (let [structure (first structures)] (recur (rest structures) (conj (union seen? (set (:args structure))) structure) (concat result (compile-structure instruction-builder structure register-allocation seen?)))))))) (defn assoc-variables [ctx register-allocation] (->> register-allocation (filter #(instance? wam.grammar.Variable (first %))) (update ctx :variables concat))) (defn single-step "Execute an instruction with respect to the supplied context, if the fail flag has not been set. If the context has failed, then just return the context unchanged (i.e. don't execute the instruction). This causes the remaining instructions to also fall through." [ctx [instr & args]] (if-not (:fail ctx) (do (when (:trace ctx) (println (friendly (cons instr args)))) (apply instr ctx args)) ctx)) (defn compile-term "Emits a sequence of instructions that equates to provided term according to the rules of the builder. Returns a function which is capable of executing the instructions given a context." [builder term] (let [register-allocation (register-allocation term) instrs (emit-instructions builder term register-allocation)] (fn [ctx] (reduce single-step (assoc-variables ctx register-allocation) instrs)))) (defn query [ctx expression] (let [executor (->> expression (parse-all g/structure) (compile-term query-builder))] (executor ctx))) (defn program [ctx expression] (let [executor (->> expression (parse-all g/structure) (compile-term program-builder))] (executor ctx)))
true
;; The MIT License (MIT) ;; ;; Copyright (c) 2015 PI:NAME:<NAME>END_PI ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in all ;; copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns wam.compiler (:require [clojure.string :as s] [clojure.set :refer [union]] [jasentaa.parser :refer [parse-all]] [wam.instruction-set :refer :all] [wam.store :refer [friendly]] [wam.grammar :as g] [wam.graph-search :refer :all])) (defn register-names "Generates an infinite incrementing sequence of register symbols, e.g. X1, X2, X3, X4 ..." [prefix] (->> (iterate inc 1) (map #(symbol (str prefix %))))) (defn register-allocation "Variable registers are allocated to a term on a least available index basis such that (1) register X1 is always allocated to the otutermost term, and (2) the same register is allocated to all occurrences of a given variable. For example, registers are allocated to the variables of the term p(Z, h(Z,W), f(W)) as follows: X1 = p(X2, X3, X4) X2 = Z X3 = h(X2, X5) X4 = f(X5) X5 = W This amounts to saying that a term is seen as a flattened conjunctive set of equations of the form Xi = X or Xi = f(Xi1, ..., Xin), n>=0 where the Xi's are all distinct new variable names. A hashmap is returned with key as the term, and the value as allocated register," [term] (zipmap (bfs term) (register-names 'X))) (def query-builder {:structure-walker dfs-post-order :instruction-builder (fn [term register seen? arg?] (if (seen? term) (list set-value register) (cond (instance? wam.grammar.Structure term) (list put-structure (:functor term) register) (instance? wam.grammar.Variable term) (list set-variable register) :else nil)))}) (def program-builder {:structure-walker dfs-pre-order :instruction-builder (fn [term register seen? arg?] (cond (instance? wam.grammar.Structure term) (if arg? (list unify-variable register) (list get-structure (:functor term) register)) (instance? wam.grammar.Variable term) (if (seen? term) (list unify-value register) (list unify-variable register)) :else nil))}) (defn compile-structure [instruction-builder structure register-allocation seen?] (loop [args (:args structure) seen? seen? result [(instruction-builder structure (register-allocation structure) seen? false)]] (if (empty? args) result (recur (rest args) (conj seen? (first args)) (conj result (instruction-builder (first args) (register-allocation (first args)) seen? true)))))) (defn emit-instructions "Constructs a sequence of instructions (missing the context argument) suitable for threading with a context. The builder determines how the structures in the term are walked (generally pre-order for programs, and post-order for queries), and emits the most appropriate instructions for each structure, which is reliant on which arguments have been previously processed." [builder term register-allocation] (let [structure-walker (:structure-walker builder) instruction-builder (:instruction-builder builder)] (loop [structures (structure-walker term) seen? #{} result []] (if (empty? structures) result (let [structure (first structures)] (recur (rest structures) (conj (union seen? (set (:args structure))) structure) (concat result (compile-structure instruction-builder structure register-allocation seen?)))))))) (defn assoc-variables [ctx register-allocation] (->> register-allocation (filter #(instance? wam.grammar.Variable (first %))) (update ctx :variables concat))) (defn single-step "Execute an instruction with respect to the supplied context, if the fail flag has not been set. If the context has failed, then just return the context unchanged (i.e. don't execute the instruction). This causes the remaining instructions to also fall through." [ctx [instr & args]] (if-not (:fail ctx) (do (when (:trace ctx) (println (friendly (cons instr args)))) (apply instr ctx args)) ctx)) (defn compile-term "Emits a sequence of instructions that equates to provided term according to the rules of the builder. Returns a function which is capable of executing the instructions given a context." [builder term] (let [register-allocation (register-allocation term) instrs (emit-instructions builder term register-allocation)] (fn [ctx] (reduce single-step (assoc-variables ctx register-allocation) instrs)))) (defn query [ctx expression] (let [executor (->> expression (parse-all g/structure) (compile-term query-builder))] (executor ctx))) (defn program [ctx expression] (let [executor (->> expression (parse-all g/structure) (compile-term program-builder))] (executor ctx)))
[ { "context": "0\r\n :words words/common-words})\r\n\r\n(def ls-key \"presses-reframe\") ;; localstore key\r\n\r\n(d", "end": 768, "score": 0.9925954937934875, "start": 753, "tag": "KEY", "value": "presses-reframe" } ]
src/app/renderer/db.cljs
porkostomus/typo
0
(ns app.renderer.db (:require [cljs.reader] [re-frame.core :as re-frame] [app.renderer.words :as words] [cljs.spec.alpha :as s])) (s/def ::cursor-pos int?) (s/def ::ave-wpm int?) (s/def ::text string?) (s/def ::current-key string?) (s/def ::time int?) (s/def ::key string?) (s/def ::press (s/map-of ::time ::key)) (s/def ::presses (s/coll-of ::press)) (defn rand-text [n] (str (apply str (interpose " " (take n (shuffle words/common-words)))) " ")) (def default-db {:text (rand-text 4) :text2 (rand-text 4) :current-key "" :cursor-pos 0 :presses [] :last-press 0 :key-map {} :ave-wpm 0 :high-speed 0 :prob-keys [] :errors 0 :words words/common-words}) (def ls-key "presses-reframe") ;; localstore key (defn presses->local-store "Puts keypresses into localStorage" [presses] (.setItem js/localStorage ls-key (str presses))) ;; -- cofx Registrations ----------------------------------------------------- ;; Use `reg-cofx` to register a "coeffect handler" which will inject the keypresses ;; stored in localstore. ;; ;; In `events.cljs` there must be an event handler with ;; the interceptor `(inject-cofx :local-store-presses)` ;; The function registered below will be used to fulfill that request. ;; (re-frame/reg-cofx :local-store-presses (fn [cofx _] ;; put the localstore presses into the coeffect under :local-store-presses (assoc cofx :local-store-presses ;; read in presses from localstore, and process into vector of maps (into [] (some->> (.getItem js/localStorage ls-key) (cljs.reader/read-string) ;; EDN vector -> vector )))))
29973
(ns app.renderer.db (:require [cljs.reader] [re-frame.core :as re-frame] [app.renderer.words :as words] [cljs.spec.alpha :as s])) (s/def ::cursor-pos int?) (s/def ::ave-wpm int?) (s/def ::text string?) (s/def ::current-key string?) (s/def ::time int?) (s/def ::key string?) (s/def ::press (s/map-of ::time ::key)) (s/def ::presses (s/coll-of ::press)) (defn rand-text [n] (str (apply str (interpose " " (take n (shuffle words/common-words)))) " ")) (def default-db {:text (rand-text 4) :text2 (rand-text 4) :current-key "" :cursor-pos 0 :presses [] :last-press 0 :key-map {} :ave-wpm 0 :high-speed 0 :prob-keys [] :errors 0 :words words/common-words}) (def ls-key "<KEY>") ;; localstore key (defn presses->local-store "Puts keypresses into localStorage" [presses] (.setItem js/localStorage ls-key (str presses))) ;; -- cofx Registrations ----------------------------------------------------- ;; Use `reg-cofx` to register a "coeffect handler" which will inject the keypresses ;; stored in localstore. ;; ;; In `events.cljs` there must be an event handler with ;; the interceptor `(inject-cofx :local-store-presses)` ;; The function registered below will be used to fulfill that request. ;; (re-frame/reg-cofx :local-store-presses (fn [cofx _] ;; put the localstore presses into the coeffect under :local-store-presses (assoc cofx :local-store-presses ;; read in presses from localstore, and process into vector of maps (into [] (some->> (.getItem js/localStorage ls-key) (cljs.reader/read-string) ;; EDN vector -> vector )))))
true
(ns app.renderer.db (:require [cljs.reader] [re-frame.core :as re-frame] [app.renderer.words :as words] [cljs.spec.alpha :as s])) (s/def ::cursor-pos int?) (s/def ::ave-wpm int?) (s/def ::text string?) (s/def ::current-key string?) (s/def ::time int?) (s/def ::key string?) (s/def ::press (s/map-of ::time ::key)) (s/def ::presses (s/coll-of ::press)) (defn rand-text [n] (str (apply str (interpose " " (take n (shuffle words/common-words)))) " ")) (def default-db {:text (rand-text 4) :text2 (rand-text 4) :current-key "" :cursor-pos 0 :presses [] :last-press 0 :key-map {} :ave-wpm 0 :high-speed 0 :prob-keys [] :errors 0 :words words/common-words}) (def ls-key "PI:KEY:<KEY>END_PI") ;; localstore key (defn presses->local-store "Puts keypresses into localStorage" [presses] (.setItem js/localStorage ls-key (str presses))) ;; -- cofx Registrations ----------------------------------------------------- ;; Use `reg-cofx` to register a "coeffect handler" which will inject the keypresses ;; stored in localstore. ;; ;; In `events.cljs` there must be an event handler with ;; the interceptor `(inject-cofx :local-store-presses)` ;; The function registered below will be used to fulfill that request. ;; (re-frame/reg-cofx :local-store-presses (fn [cofx _] ;; put the localstore presses into the coeffect under :local-store-presses (assoc cofx :local-store-presses ;; read in presses from localstore, and process into vector of maps (into [] (some->> (.getItem js/localStorage ls-key) (cljs.reader/read-string) ;; EDN vector -> vector )))))
[ { "context": ";; Copyright (c) 2010 Tom Crayford,\n;;\n;; Redistribution and use in source and binar", "end": 34, "score": 0.9998272657394409, "start": 22, "tag": "NAME", "value": "Tom Crayford" } ]
src/clojure_refactoring/thread_expression.clj
tcrayford/clojure-refactoring
6
;; Copyright (c) 2010 Tom Crayford, ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; ;; Redistributions in binary form must reproduce the above ;; copyright notice, this list of conditions and the following ;; disclaimer in the documentation and/or other materials provided ;; with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS ;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED ;; OF THE POSSIBILITY OF SUCH DAMAGE. (ns clojure-refactoring.thread-expression (:use [clojure-refactoring.support core] [clojure.walk :only [postwalk]] clojure-refactoring.support.formatter) (:require [clojure-refactoring.support.parser :as parser]) (:require [clojure-refactoring.ast :as ast])) (def expression-threaders '#{->> -> clojure.core/->> clojure.core/->}) (def threaded? (all-of? seq? (comp expression-threaders first))) (defn- expand-threaded [coll] (if (threaded? coll) (macroexpand-1 coll) coll)) (defn- expand-all-threaded [node] (postwalk expand-threaded node)) (defn- any-threaded? [node] (some #(tree-contains? node %) expression-threaders)) (defn thread-unthread [code] "Takes an expression starting with ->> or -> and unthreads it" (format-code (loop [node (read-string code)] (if (any-threaded? node) (recur (expand-all-threaded node)) node)))) ;;;;; Threading below here (defn threading-fns-from-type [type] "Returns functions to be used by thread-with-type based on what type of threading is going to be" ({'-> {:position-f (comp second ast/relevant-content) :all-but-position-f (comp but-second ast/relevant-content)} '->> {:position-f (comp last ast/relevant-content) :all-but-position-f (comp butlast ast/relevant-content)}} type)) (defn not-last-threading-node? [ast position-f] (and (ast/tag= :list (position-f ast)) (ast/tag= :list (position-f (position-f ast))))) (defn finish-threading [{content :content :as node} new-ast thread-type] (let [{:keys [position-f all-but-position-f]} (threading-fns-from-type thread-type) useful-content (ast/relevant-content node)] (ast/conj new-ast (position-f node) (apply ast/list-without-whitespace (all-but-position-f node))))) (defn thread-with-type [thread-type ast] (let [{:keys [position-f all-but-position-f]} (threading-fns-from-type thread-type)] (loop [node ast new-node ast/empty-list] (if (not-last-threading-node? node position-f) (recur (position-f node) (ast/conj new-node (all-but-position-f node))) (finish-threading node new-node thread-type))))) (defn thread-ast [thread-type ast] (apply ast/list-without-whitespace `(~(ast/symbol thread-type) ~@(->> (thread-with-type thread-type ast) ast/relevant-content)))) (defn- construct-threaded [thread-type code] (->> (ast/strip-whitespace (parser/parse1 code)) (thread-ast thread-type) format-ast ast/ast->string)) (defn thread-last [code] (construct-threaded '->> code)) (defn thread-first [code] (construct-threaded '-> code))
102382
;; Copyright (c) 2010 <NAME>, ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; ;; Redistributions in binary form must reproduce the above ;; copyright notice, this list of conditions and the following ;; disclaimer in the documentation and/or other materials provided ;; with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS ;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED ;; OF THE POSSIBILITY OF SUCH DAMAGE. (ns clojure-refactoring.thread-expression (:use [clojure-refactoring.support core] [clojure.walk :only [postwalk]] clojure-refactoring.support.formatter) (:require [clojure-refactoring.support.parser :as parser]) (:require [clojure-refactoring.ast :as ast])) (def expression-threaders '#{->> -> clojure.core/->> clojure.core/->}) (def threaded? (all-of? seq? (comp expression-threaders first))) (defn- expand-threaded [coll] (if (threaded? coll) (macroexpand-1 coll) coll)) (defn- expand-all-threaded [node] (postwalk expand-threaded node)) (defn- any-threaded? [node] (some #(tree-contains? node %) expression-threaders)) (defn thread-unthread [code] "Takes an expression starting with ->> or -> and unthreads it" (format-code (loop [node (read-string code)] (if (any-threaded? node) (recur (expand-all-threaded node)) node)))) ;;;;; Threading below here (defn threading-fns-from-type [type] "Returns functions to be used by thread-with-type based on what type of threading is going to be" ({'-> {:position-f (comp second ast/relevant-content) :all-but-position-f (comp but-second ast/relevant-content)} '->> {:position-f (comp last ast/relevant-content) :all-but-position-f (comp butlast ast/relevant-content)}} type)) (defn not-last-threading-node? [ast position-f] (and (ast/tag= :list (position-f ast)) (ast/tag= :list (position-f (position-f ast))))) (defn finish-threading [{content :content :as node} new-ast thread-type] (let [{:keys [position-f all-but-position-f]} (threading-fns-from-type thread-type) useful-content (ast/relevant-content node)] (ast/conj new-ast (position-f node) (apply ast/list-without-whitespace (all-but-position-f node))))) (defn thread-with-type [thread-type ast] (let [{:keys [position-f all-but-position-f]} (threading-fns-from-type thread-type)] (loop [node ast new-node ast/empty-list] (if (not-last-threading-node? node position-f) (recur (position-f node) (ast/conj new-node (all-but-position-f node))) (finish-threading node new-node thread-type))))) (defn thread-ast [thread-type ast] (apply ast/list-without-whitespace `(~(ast/symbol thread-type) ~@(->> (thread-with-type thread-type ast) ast/relevant-content)))) (defn- construct-threaded [thread-type code] (->> (ast/strip-whitespace (parser/parse1 code)) (thread-ast thread-type) format-ast ast/ast->string)) (defn thread-last [code] (construct-threaded '->> code)) (defn thread-first [code] (construct-threaded '-> code))
true
;; Copyright (c) 2010 PI:NAME:<NAME>END_PI, ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; ;; Redistributions in binary form must reproduce the above ;; copyright notice, this list of conditions and the following ;; disclaimer in the documentation and/or other materials provided ;; with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS ;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED ;; OF THE POSSIBILITY OF SUCH DAMAGE. (ns clojure-refactoring.thread-expression (:use [clojure-refactoring.support core] [clojure.walk :only [postwalk]] clojure-refactoring.support.formatter) (:require [clojure-refactoring.support.parser :as parser]) (:require [clojure-refactoring.ast :as ast])) (def expression-threaders '#{->> -> clojure.core/->> clojure.core/->}) (def threaded? (all-of? seq? (comp expression-threaders first))) (defn- expand-threaded [coll] (if (threaded? coll) (macroexpand-1 coll) coll)) (defn- expand-all-threaded [node] (postwalk expand-threaded node)) (defn- any-threaded? [node] (some #(tree-contains? node %) expression-threaders)) (defn thread-unthread [code] "Takes an expression starting with ->> or -> and unthreads it" (format-code (loop [node (read-string code)] (if (any-threaded? node) (recur (expand-all-threaded node)) node)))) ;;;;; Threading below here (defn threading-fns-from-type [type] "Returns functions to be used by thread-with-type based on what type of threading is going to be" ({'-> {:position-f (comp second ast/relevant-content) :all-but-position-f (comp but-second ast/relevant-content)} '->> {:position-f (comp last ast/relevant-content) :all-but-position-f (comp butlast ast/relevant-content)}} type)) (defn not-last-threading-node? [ast position-f] (and (ast/tag= :list (position-f ast)) (ast/tag= :list (position-f (position-f ast))))) (defn finish-threading [{content :content :as node} new-ast thread-type] (let [{:keys [position-f all-but-position-f]} (threading-fns-from-type thread-type) useful-content (ast/relevant-content node)] (ast/conj new-ast (position-f node) (apply ast/list-without-whitespace (all-but-position-f node))))) (defn thread-with-type [thread-type ast] (let [{:keys [position-f all-but-position-f]} (threading-fns-from-type thread-type)] (loop [node ast new-node ast/empty-list] (if (not-last-threading-node? node position-f) (recur (position-f node) (ast/conj new-node (all-but-position-f node))) (finish-threading node new-node thread-type))))) (defn thread-ast [thread-type ast] (apply ast/list-without-whitespace `(~(ast/symbol thread-type) ~@(->> (thread-with-type thread-type ast) ast/relevant-content)))) (defn- construct-threaded [thread-type code] (->> (ast/strip-whitespace (parser/parse1 code)) (thread-ast thread-type) format-ast ast/ast->string)) (defn thread-last [code] (construct-threaded '->> code)) (defn thread-first [code] (construct-threaded '-> code))
[ { "context": " :email email}\n :password password)\n (login db-conn email password client-i", "end": 2944, "score": 0.9955844283103943, "start": 2936, "tag": "PASSWORD", "value": "password" } ]
src/dashboard/login.clj
Purple-Services/dashboard-service
3
(ns dashboard.login (:require [common.db :as db] [common.util :as util] [common.users :refer [valid-email? valid-password? auth-native?]] [crypto.password.bcrypt :as bcrypt])) (def safe-authd-user-keys "The keys of a user map that are safe to send out to auth'd user." [:id :email :permissions]) (defn get-user "Gets a user from db. Optionally add WHERE constraints." [db-conn & {:keys [where]}] (first (db/!select db-conn "dashboard_users" ["*"] (merge {} where)))) (defn get-user-by-email "Gets a user from db by email address" [db-conn email] (get-user db-conn :where {:email email})) (defn email-available? "Is there not a native account that is using this email address?" [db-conn email] (let [user (get-user-by-email db-conn email)] (empty? user))) (defn get-permissions "Given a user id, return the permissions as a set" [db-conn user-id] (let [user (get-user db-conn :where {:id user-id}) perms (:permissions user)] (if (not (nil? perms)) (-> (:permissions user) (util/split-on-comma) set) (set nil)))) (defn- add "Add a new user with password" [db-conn user & {:keys [password]}] (db/!insert db-conn "dashboard_users" (assoc user :password_hash (bcrypt/encrypt password)))) (defn init-session [db-conn user client-ip] (let [token (util/new-auth-token)] (db/!insert db-conn "sessions" {:user_id (:id user) :token token :source "dashboard" :ip (or client-ip "")}) {:success true :token token :user (select-keys user safe-authd-user-keys)})) (defn login "Given an email, password and client-ip, create a new session and return it" [db-conn email password client-ip] (let [user (get-user-by-email db-conn email)] (cond (nil? user) {:success false :message "Incorrect email / password combination."} (auth-native? user password) (init-session db-conn user client-ip) :else {:success false :message "Incorrect email / password combination."}))) (defn register "Register a new dashboard user" [db-conn email password client-ip] (cond (not (and (valid-email? email) (email-available? db-conn email))) {:success false :message (str "Email Address is incorrectly formatted or is already" " associated with an account")} (not (valid-password? password)) {:success false :message "Password must be at least 6 characters"} (and (valid-email? email) (email-available? db-conn email) (valid-password? password)) (do (add db-conn {:id (util/rand-str-alpha-num 20) :email email} :password password) (login db-conn email password client-ip)) :else {:success false :message "An unknown error occurred"})) (defn accessible-routes "Given a vector uri-permissions containing uri-perm maps, generate a set of uri / method maps that are accessible with the set user-permissions. A uri-perm map is of the form: {:uri route :permissions perms :method method} e.g. {:uri \"/dashboard/dash-map-couriers\" :permissions [\"view-orders\" \"view-couriers\" \"view-zones\"] :method \"GET\" } " [uri-permissions user-permissions] (let [user-has-permission? (fn [user-perms uri-perm] (let [route-perm (:permissions uri-perm) perms-contained-list (map #(contains? user-perms %) route-perm)] (boolean (and (every? identity perms-contained-list) (seq perms-contained-list)))))] (set (filter (comp not nil?) (map #(if (user-has-permission? user-permissions %) (select-keys % [:uri :method])) uri-permissions)))))
22172
(ns dashboard.login (:require [common.db :as db] [common.util :as util] [common.users :refer [valid-email? valid-password? auth-native?]] [crypto.password.bcrypt :as bcrypt])) (def safe-authd-user-keys "The keys of a user map that are safe to send out to auth'd user." [:id :email :permissions]) (defn get-user "Gets a user from db. Optionally add WHERE constraints." [db-conn & {:keys [where]}] (first (db/!select db-conn "dashboard_users" ["*"] (merge {} where)))) (defn get-user-by-email "Gets a user from db by email address" [db-conn email] (get-user db-conn :where {:email email})) (defn email-available? "Is there not a native account that is using this email address?" [db-conn email] (let [user (get-user-by-email db-conn email)] (empty? user))) (defn get-permissions "Given a user id, return the permissions as a set" [db-conn user-id] (let [user (get-user db-conn :where {:id user-id}) perms (:permissions user)] (if (not (nil? perms)) (-> (:permissions user) (util/split-on-comma) set) (set nil)))) (defn- add "Add a new user with password" [db-conn user & {:keys [password]}] (db/!insert db-conn "dashboard_users" (assoc user :password_hash (bcrypt/encrypt password)))) (defn init-session [db-conn user client-ip] (let [token (util/new-auth-token)] (db/!insert db-conn "sessions" {:user_id (:id user) :token token :source "dashboard" :ip (or client-ip "")}) {:success true :token token :user (select-keys user safe-authd-user-keys)})) (defn login "Given an email, password and client-ip, create a new session and return it" [db-conn email password client-ip] (let [user (get-user-by-email db-conn email)] (cond (nil? user) {:success false :message "Incorrect email / password combination."} (auth-native? user password) (init-session db-conn user client-ip) :else {:success false :message "Incorrect email / password combination."}))) (defn register "Register a new dashboard user" [db-conn email password client-ip] (cond (not (and (valid-email? email) (email-available? db-conn email))) {:success false :message (str "Email Address is incorrectly formatted or is already" " associated with an account")} (not (valid-password? password)) {:success false :message "Password must be at least 6 characters"} (and (valid-email? email) (email-available? db-conn email) (valid-password? password)) (do (add db-conn {:id (util/rand-str-alpha-num 20) :email email} :password <PASSWORD>) (login db-conn email password client-ip)) :else {:success false :message "An unknown error occurred"})) (defn accessible-routes "Given a vector uri-permissions containing uri-perm maps, generate a set of uri / method maps that are accessible with the set user-permissions. A uri-perm map is of the form: {:uri route :permissions perms :method method} e.g. {:uri \"/dashboard/dash-map-couriers\" :permissions [\"view-orders\" \"view-couriers\" \"view-zones\"] :method \"GET\" } " [uri-permissions user-permissions] (let [user-has-permission? (fn [user-perms uri-perm] (let [route-perm (:permissions uri-perm) perms-contained-list (map #(contains? user-perms %) route-perm)] (boolean (and (every? identity perms-contained-list) (seq perms-contained-list)))))] (set (filter (comp not nil?) (map #(if (user-has-permission? user-permissions %) (select-keys % [:uri :method])) uri-permissions)))))
true
(ns dashboard.login (:require [common.db :as db] [common.util :as util] [common.users :refer [valid-email? valid-password? auth-native?]] [crypto.password.bcrypt :as bcrypt])) (def safe-authd-user-keys "The keys of a user map that are safe to send out to auth'd user." [:id :email :permissions]) (defn get-user "Gets a user from db. Optionally add WHERE constraints." [db-conn & {:keys [where]}] (first (db/!select db-conn "dashboard_users" ["*"] (merge {} where)))) (defn get-user-by-email "Gets a user from db by email address" [db-conn email] (get-user db-conn :where {:email email})) (defn email-available? "Is there not a native account that is using this email address?" [db-conn email] (let [user (get-user-by-email db-conn email)] (empty? user))) (defn get-permissions "Given a user id, return the permissions as a set" [db-conn user-id] (let [user (get-user db-conn :where {:id user-id}) perms (:permissions user)] (if (not (nil? perms)) (-> (:permissions user) (util/split-on-comma) set) (set nil)))) (defn- add "Add a new user with password" [db-conn user & {:keys [password]}] (db/!insert db-conn "dashboard_users" (assoc user :password_hash (bcrypt/encrypt password)))) (defn init-session [db-conn user client-ip] (let [token (util/new-auth-token)] (db/!insert db-conn "sessions" {:user_id (:id user) :token token :source "dashboard" :ip (or client-ip "")}) {:success true :token token :user (select-keys user safe-authd-user-keys)})) (defn login "Given an email, password and client-ip, create a new session and return it" [db-conn email password client-ip] (let [user (get-user-by-email db-conn email)] (cond (nil? user) {:success false :message "Incorrect email / password combination."} (auth-native? user password) (init-session db-conn user client-ip) :else {:success false :message "Incorrect email / password combination."}))) (defn register "Register a new dashboard user" [db-conn email password client-ip] (cond (not (and (valid-email? email) (email-available? db-conn email))) {:success false :message (str "Email Address is incorrectly formatted or is already" " associated with an account")} (not (valid-password? password)) {:success false :message "Password must be at least 6 characters"} (and (valid-email? email) (email-available? db-conn email) (valid-password? password)) (do (add db-conn {:id (util/rand-str-alpha-num 20) :email email} :password PI:PASSWORD:<PASSWORD>END_PI) (login db-conn email password client-ip)) :else {:success false :message "An unknown error occurred"})) (defn accessible-routes "Given a vector uri-permissions containing uri-perm maps, generate a set of uri / method maps that are accessible with the set user-permissions. A uri-perm map is of the form: {:uri route :permissions perms :method method} e.g. {:uri \"/dashboard/dash-map-couriers\" :permissions [\"view-orders\" \"view-couriers\" \"view-zones\"] :method \"GET\" } " [uri-permissions user-permissions] (let [user-has-permission? (fn [user-perms uri-perm] (let [route-perm (:permissions uri-perm) perms-contained-list (map #(contains? user-perms %) route-perm)] (boolean (and (every? identity perms-contained-list) (seq perms-contained-list)))))] (set (filter (comp not nil?) (map #(if (user-has-permission? user-permissions %) (select-keys % [:uri :method])) uri-permissions)))))
[ { "context": "ent\"\n (let [expected {:company_name \"Hotel Sanders København A/S\"\n :country \"DK\"\n", "end": 8812, "score": 0.5841725468635559, "start": 8809, "tag": "NAME", "value": "ers" }, { "context": "t [expected {:company_name \"Hotel Sanders København A/S\"\n :country \"DK\"\n ", "end": 8822, "score": 0.5303931832313538, "start": 8821, "tag": "NAME", "value": "n" }, { "context": "ees 5215}\n document {:company_name \"Hotel Sanders København A/S\"\n :num_employees 5", "end": 8981, "score": 0.6627160906791687, "start": 8972, "tag": "NAME", "value": "Sanders K" }, { "context": " document {:company_name \"Hotel Sanders København A/S\"\n :num_employees 5215\n ", "end": 8989, "score": 0.6676129698753357, "start": 8982, "tag": "NAME", "value": "benhavn" }, { "context": "document\"\n (let [expected {:company_name \"Hotel Sanders København A/S\"\n :country \"DK\"\n", "end": 10376, "score": 0.7158225774765015, "start": 10369, "tag": "NAME", "value": "Sanders" }, { "context": " (let [expected {:company_name \"Hotel Sanders København A/S\"\n :country \"DK\"\n ", "end": 10386, "score": 0.6068320870399475, "start": 10378, "tag": "NAME", "value": "øbenhavn" }, { "context": " {:id \"1\"\n :name \"shoe\"\n :price 75}))\n\n (let ", "end": 15280, "score": 0.6966954469680786, "start": 15276, "tag": "NAME", "value": "shoe" }, { "context": "ttings \"brands_multi_search_test\" {:id \"1\" :name \"Nike\"}))\n\n (testing \"Multi search\"\n (let [exp {:re", "end": 15583, "score": 0.9868487119674683, "start": 15579, "tag": "NAME", "value": "Nike" }, { "context": "hits\n [{:document {:id \"1\" :name \"shoe\" :price 75}\n :highlights\n ", "end": 15771, "score": 0.7190312743186951, "start": 15767, "tag": "NAME", "value": "shoe" }, { "context": "hits\n [{:document {:id \"1\" :name \"Nike\"}\n :highlights\n ", "end": 16376, "score": 0.9963009357452393, "start": 16372, "tag": "NAME", "value": "Nike" }, { "context": "eld \"name\"\n :matched_tokens [\"Nike\"]\n :snippet \"<mark>Nike</mark", "end": 16488, "score": 0.9774023294448853, "start": 16484, "tag": "NAME", "value": "Nike" }, { "context": " document {:points 1\n :title \"Louvre Museuem\"\n :location [48.86093481609114 2", "end": 17702, "score": 0.9907381534576416, "start": 17688, "tag": "NAME", "value": "Louvre Museuem" }, { "context": " :points 1\n :title \"Louvre Museuem\"}\n :geo_distance_meters {:l", "end": 18152, "score": 0.9451233148574829, "start": 18144, "tag": "NAME", "value": "Louvre M" } ]
test/typesense/client_test.clj
runeanielsen/typesense-clj
4
(ns ^:integration typesense.client-test (:require [typesense.client :as sut] [clojure.test :as t :refer [deftest is testing]])) (def settings {:uri "http://localhost:8108" :key "key"}) (defn- clean-collections "Cleans all collections in Typesense." [] (let [collections (sut/list-collections settings)] (doseq [collection collections] (sut/delete-collection! settings (:name collection))))) (defn- clean-api-keys "Clean all api-keys." [] (let [keys (sut/list-api-keys settings)] (doseq [key (:keys keys)] (sut/delete-api-key! settings (:id key))))) (defn- clean-aliases "Cleans all aliases." [] (let [aliases (sut/list-aliases settings)] (doseq [key (:aliases aliases)] (sut/delete-alias! settings key)))) (defn- clean-typesense-fixture "Cleanup before each integration test run." [f] (clean-collections) (clean-api-keys) (clean-aliases) (f)) (t/use-fixtures :once clean-typesense-fixture) ;; Handles the primary workflow for interactiong with the Typesense Client. ;; The flow is inside of a single deftest because the interaction with the API ;; is stateful so it simplifies the test cases to keep them together. ;; If we had decided to split them out listing collections might result in issues. (deftest client-primary-workflow-tests (testing "Create collection" (let [expected {:default_sorting_field "num_employees" :fields [{:facet false :index true :name "company_name" :optional false :type "string" :infix false :locale "" :sort false} {:facet false :index true :name "num_employees" :optional false :type "int32" :infix false :locale "" :sort true} {:facet true :index true :name "country" :optional false :type "string" :infix false :locale "" :sort false}] :name "companies_collection_test" :num_documents 0 :symbols_to_index [] :token_separators []} schema {:name "companies_collection_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"} response (sut/create-collection! settings schema)] ;; We make individual test for :created_at since it changes each run. (is (> (:created_at response) 0)) ;; We remove :created_at it cannot be asserted since it changes each run. (is (= expected (dissoc response :created_at))))) (testing "List collections" (let [expected [{:default_sorting_field "num_employees" :fields [{:facet false :index true :name "company_name" :optional false :type "string" :infix false :locale "" :sort false} {:facet false :index true :name "num_employees" :optional false :type "int32" :infix false :locale "" :sort true} {:facet true :index true :name "country" :optional false :type "string" :infix false :locale "" :sort false}] :name "companies_collection_test" :num_documents 0 :symbols_to_index [] :token_separators []}] response (sut/list-collections settings)] ;; We make individual test for :created_at since it changes each run. (is (true? (every? #(> (:created_at %) 0) response))) ;; We remove :created_at it cannot be asserted since it changes each run. (is (= expected (map #(dissoc % :created_at) response))))) (testing "Retrieve collection" (let [expected {:default_sorting_field "num_employees" :fields [{:facet false :index true :infix false :locale "" :name "company_name" :optional false :sort false :type "string"} {:facet false :index true :infix false :locale "" :name "num_employees" :optional false :sort true :type "int32"} {:facet true :index true :infix false :locale "" :name "country" :optional false :sort false :type "string"}] :name "companies_collection_test" :num_documents 0 :symbols_to_index [] :token_separators []} response (sut/retrieve-collection settings "companies_collection_test")] (is (> (:created_at response) 0)) ;; We remove :created_at it cannot be asserted since it changes each run. (is (= expected (dissoc response :created_at))))) (testing "Delete collection" (let [expected {:default_sorting_field "num_employees" :fields [{:facet false :index true :name "company_name" :optional false :type "string" :infix false :locale "" :sort false} {:facet false :index true :name "num_employees" :optional false :type "int32" :infix false :locale "" :sort true} {:facet true :index true :name "country" :optional false :type "string" :infix false :locale "" :sort false}] :name "companies_collection_test" :num_documents 0 :symbols_to_index [] :token_separators []} response (sut/delete-collection! settings "companies_collection_test")] (is (> (:created_at response) 0)) ;; We remove :created_at it cannot be asserted since it changes each run. (is (= expected (dissoc response :created_at))))) ;; Initialize test collection for documents (let [schema {:name "companies_document_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Create document" (let [expected {:company_name "Hotel Sanders København A/S" :country "DK" :id "0" :num_employees 5215} document {:company_name "Hotel Sanders København A/S" :num_employees 5215 :country "DK"} response (sut/create-document! settings "companies_document_test" document)] (is (= expected response)))) (testing "Upsert document" (let [expected {:company_name "Awesome Inc." :num_employees 10 :country "Norway" :id "1"} document {:company_name "Awesome Inc." :num_employees 10 :country "Norway"} response (sut/upsert-document! settings "companies_document_test" document)] (is (= expected response)))) (testing "Retrieve document" (let [expected {:company_name "Awesome Inc." :num_employees 10 :country "Norway" :id "1"} response (sut/retrieve-document settings "companies_document_test" 1)] (is (= expected response)))) (testing "Update document" (let [expected {:company_name "Mega Awesome Inc." :num_employees 10 :country "Norway" :id "1"} update-doc {:company_name "Mega Awesome Inc."} response (sut/update-document! settings "companies_document_test" 1 update-doc)] (is (= expected response)))) (testing "Delete document" (let [expected {:company_name "Hotel Sanders København A/S" :country "DK" :id "0" :num_employees 5215} response (sut/delete-document! settings "companies_document_test" 0)] (is (= expected response)))) ;; Initize test collection for documents (let [schema {:name "companies_documents_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Create documents" (let [exp [{:success true} {:success true}] res (sut/create-documents! settings "companies_documents_test" [{:id "1" :company_name "Innovationsoft A/S" :num_employees 10 :country "Finland"} {:id "2" :company_name "GoSoftware" :num_employees 5000 :country "Sweden"}])] (is (= exp res)))) (testing "Upsert documents" (let [exp [{:success true} {:success true}] res (sut/upsert-documents! settings "companies_documents_test" [{:id "1" :company_name "Innovationsoft A/S" :num_employees 10 :country "Finland"} {:id "3" :company_name "Awesomesoftwaresoft" :num_employees 105 :country "Denmark"}])] (is (= exp res)))) (testing "Update documents" (let [exp [{:success true} {:success true}] res (sut/update-documents! settings "companies_documents_test" [{:id "1" :company_name "Innovationsoft A/S" :num_employees 10 :country "Finland"} {:id "2" :company_name "GoSoftware" :num_employees 5000 :country "Sweden"}])] (is (= exp res)))) (testing "Delete documents" (let [exp {:num_deleted 2} res (sut/delete-documents! settings "companies_documents_test" {:filter_by "num_employees:>=100"})] (is (= exp res)))) (testing "Export documents" (let [exp [{:id "1" :company_name "Innovationsoft A/S" :num_employees 10 :country "Finland"}] res (sut/export-documents settings "companies_documents_test" {:filter_by "num_employees:<=100"})] (is (= exp res)))) (testing "Search" (let [exp {:facet_counts [] :found 1 :hits [{:document {:company_name "Innovationsoft A/S" :country "Finland" :id "1" :num_employees 10} :highlights [{:field "company_name" :matched_tokens ["Innovation"] :snippet "<mark>Innovation</mark>soft A/S"}] :text_match 282583051272193}] :out_of 1 :page 1 :request_params {:collection_name "companies_documents_test" :per_page 10 :q "Innovation"} :search_cutoff false :search_time_ms 0} res (sut/search settings "companies_documents_test" {:q "Innovation" :query_by "company_name"})] (is (= res exp)))) ;; Creating test setup for multi search (let [schema {:name "products_multi_search_test" :fields [{:name "name" :type "string"} {:name "price" :type "int32"}]}] (sut/create-collection! settings schema) (sut/create-document! settings "products_multi_search_test" {:id "1" :name "shoe" :price 75})) (let [schema {:name "brands_multi_search_test" :fields [{:name "name" :type "string"}]}] (sut/create-collection! settings schema) (sut/create-document! settings "brands_multi_search_test" {:id "1" :name "Nike"})) (testing "Multi search" (let [exp {:results [{:facet_counts [] :found 1 :hits [{:document {:id "1" :name "shoe" :price 75} :highlights [{:field "name" :matched_tokens ["shoe"] :snippet "<mark>shoe</mark>"}] :text_match 282583068049665}] :out_of 1 :page 1 :request_params {:collection_name "products_multi_search_test" :per_page 10 :q "shoe"} :search_cutoff false :search_time_ms 0} {:facet_counts [] :found 1 :hits [{:document {:id "1" :name "Nike"} :highlights [{:field "name" :matched_tokens ["Nike"] :snippet "<mark>Nike</mark>"}] :text_match 282583068049665}] :out_of 1 :page 1 :request_params {:collection_name "brands_multi_search_test" :per_page 10 :q "Nike"} :search_cutoff false :search_time_ms 0}]} res (sut/multi-search settings {:searches [{:collection "products_multi_search_test" :q "shoe" :filter_by "price:=[50..120]"} {:collection "brands_multi_search_test" :q "Nike"}]} {:query_by "name"})] (is (= exp res)))) ;; Initialize test collection with documents for geosearch. (let [schema {:name "places" :fields [{:name "title" :type "string"} {:name "points" :type "int32"} {:name "location" :type "geopoint"}] :default_sorting_field "points"} document {:points 1 :title "Louvre Museuem" :location [48.86093481609114 2.33698396872901]}] (sut/create-collection! settings schema) (sut/create-document! settings "places" document)) (testing "Geosearch" (let [exp {:facet_counts [] :found 1 :hits [{:document {:id "0" :location [48.86093481609114 2.33698396872901] :points 1 :title "Louvre Museuem"} :geo_distance_meters {:location 1020} :highlights [] :text_match 100}] :out_of 1 :page 1 :request_params {:collection_name "places" :per_page 10 :q "*"} :search_cutoff false :search_time_ms 0} res (sut/search settings "places" {:q "*" :query_by "title" :filter_by "location:(48.90615915923891, 2.3435897727061175, 5.1 km)" :sort_by "location(48.853, 2.344):asc"})] ;; We test :search_time_ms individually since it can chane each run. (is (number? (res :search_time_ms))) (is (= (dissoc exp :search_time_ms) (dissoc res :search_time_ms))))) ;; Initialize test collection for curation. (let [schema {:name "companies_curation_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Upsert override" (let [exp {:excludes [{:id "287"}] :id "customize_apple" :includes [{:id "422" :position 1} {:id "54" :position 2}] :rule {:match "exact" :query "apple"}} res (sut/upsert-override! settings "companies_curation_test" "customize_apple" {:rule {:query "apple" :match "exact"} :includes [{:id "422" :position 1} {:id "54" :position 2}] :excludes [{:id "287"}]})] (is (= exp res)))) (testing "List all overrides" (let [exp {:overrides [{:excludes [{:id "287"}] :id "customize_apple" :includes [{:id "422" :position 1} {:id "54" :position 2}] :rule {:match "exact" :query "apple"} :filter_curated_hits false :remove_matched_tokens false}]} res (sut/list-overrides settings "companies_curation_test")] (is (= exp res)))) (testing "Retrieve override" (let [exp {:excludes [{:id "287"}] :id "customize_apple" :includes [{:id "422" :position 1} {:id "54" :position 2}] :rule {:match "exact" :query "apple"} :filter_curated_hits false :remove_matched_tokens false} res (sut/retrieve-override settings "companies_curation_test" "customize_apple")] (is (= exp res)))) (testing "Delete override" (let [exp {:id "customize_apple"} res (sut/delete-override! settings "companies_curation_test" "customize_apple")] (is (= exp res)))) ;; Initialize test collection for alias. (let [schema {:name "companies_alias_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Upsert alias" (let [exp {:collection_name "companies_alias_test" :name "companies"} res (sut/upsert-alias! settings "companies" {:collection_name "companies_alias_test"})] (is (= exp res)))) (testing "List all aliases" (let [exp {:aliases [{:collection_name "companies_alias_test" :name "companies"}]} res (sut/list-aliases settings)] (is (= exp res)))) (testing "Retrieve alias" (let [exp {:collection_name "companies_alias_test" :name "companies"} res (sut/retrieve-alias settings "companies")] (is (= exp res)))) (testing "Delete alias" (let [exp {:collection_name "companies_alias_test" :name "companies"} res (sut/delete-alias! settings "companies")] (is (= exp res)))) ;; Initialize test collection for synonyms. (let [schema {:name "products_synonyms_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Upsert synonym" (let [exp {:id "coat-synonyms" :synonyms ["blazer" "coat" "jacket"]} res (sut/upsert-synonym! settings "products_synonyms_test" "coat-synonyms" {:synonyms ["blazer" "coat" "jacket"]})] (is (= exp res)))) (testing "Retrieve synonym" (let [exp {:id "coat-synonyms" :root "" :synonyms ["blazer" "coat" "jacket"]} res (sut/retrieve-synonym settings "products_synonyms_test" "coat-synonyms")] (is (= exp res)))) (testing "List synonyms" (let [exp {:synonyms [{:id "coat-synonyms" :root "" :synonyms ["blazer" "coat" "jacket"]}]} res (sut/list-synonyms settings "products_synonyms_test")] (is (= exp res)))) (testing "Delete synonym" (let [exp {:id "coat-synonyms"} res (sut/delete-synonym! settings "products_synonyms_test" "coat-synonyms")] (is (= res exp))))) (defn api-key-constant-values "Helper function to get unique values of api-key." [k] (dissoc k :id :value :expires_at :value_prefix)) (deftest client-api-key-tests (testing "Create api key" (let [exp {:actions ["document:search"] :collections ["companies"] :description "Search only companies key." :expires_at 64723363199 :id 0 :value "sK0jo6CSn1EBoJJ8LKPjRZCtsJ1JCFkt"} key {:description "Search only companies key." :actions ["document:search"] :collections ["companies"]} res (sut/create-api-key! settings key)] ;; We test individual cases since they will change each run. (is (> (count (:value res)) 0)) (is (> (:expires_at res) 0)) (is (>= (:id res) 0)) ;; We test the values that do not change each run. (is (= (api-key-constant-values exp) (api-key-constant-values res))))) (testing "Retrieve api key" ;; We have to retrieve the first key-id this way because they change each run. (let [id (-> (sut/list-api-keys settings) :keys first :id) exp {:actions ["document:search"] :collections ["companies"] :description "Search only companies key." :expires_at 64723363199 :id 49 :value_prefix "Bx3y"} res (sut/retrieve-api-key settings id)] ;; We make individual tests for the parameters since they change each run. (is (>= (:id res) 0)) (is (> (:expires_at res) 0)) (is (> (count (:value_prefix res)) 0)) ;; We test the values that do not change each run. (is (= (api-key-constant-values exp) (api-key-constant-values res))))) (testing "List api keys" (let [exp {:keys [{:actions ["document:search"] :collections ["companies"] :description "Search only companies key." :expires_at 64723363199 :id 17 :value_prefix "vLbB"}]} res (sut/list-api-keys settings)] ;; We make individual tests for the parameters since they change each run. (is (every? #(>= (:id %) 0) (:keys res))) (is (every? #(>= (:expires_at %) 0) (:keys res))) (is (every? #(> (count (:value_prefix %)) 0) (:keys res))) ;; We test the values that do not change each run. (is (= (update-in exp [:keys] #(map api-key-constant-values %)) (update-in res [:keys] #(map api-key-constant-values %)))))) (testing "Delete api key" (let [id (-> (sut/list-api-keys settings) :keys first :id) exp {:id id} res (sut/delete-api-key! settings id)] (is (= exp res)))))
120315
(ns ^:integration typesense.client-test (:require [typesense.client :as sut] [clojure.test :as t :refer [deftest is testing]])) (def settings {:uri "http://localhost:8108" :key "key"}) (defn- clean-collections "Cleans all collections in Typesense." [] (let [collections (sut/list-collections settings)] (doseq [collection collections] (sut/delete-collection! settings (:name collection))))) (defn- clean-api-keys "Clean all api-keys." [] (let [keys (sut/list-api-keys settings)] (doseq [key (:keys keys)] (sut/delete-api-key! settings (:id key))))) (defn- clean-aliases "Cleans all aliases." [] (let [aliases (sut/list-aliases settings)] (doseq [key (:aliases aliases)] (sut/delete-alias! settings key)))) (defn- clean-typesense-fixture "Cleanup before each integration test run." [f] (clean-collections) (clean-api-keys) (clean-aliases) (f)) (t/use-fixtures :once clean-typesense-fixture) ;; Handles the primary workflow for interactiong with the Typesense Client. ;; The flow is inside of a single deftest because the interaction with the API ;; is stateful so it simplifies the test cases to keep them together. ;; If we had decided to split them out listing collections might result in issues. (deftest client-primary-workflow-tests (testing "Create collection" (let [expected {:default_sorting_field "num_employees" :fields [{:facet false :index true :name "company_name" :optional false :type "string" :infix false :locale "" :sort false} {:facet false :index true :name "num_employees" :optional false :type "int32" :infix false :locale "" :sort true} {:facet true :index true :name "country" :optional false :type "string" :infix false :locale "" :sort false}] :name "companies_collection_test" :num_documents 0 :symbols_to_index [] :token_separators []} schema {:name "companies_collection_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"} response (sut/create-collection! settings schema)] ;; We make individual test for :created_at since it changes each run. (is (> (:created_at response) 0)) ;; We remove :created_at it cannot be asserted since it changes each run. (is (= expected (dissoc response :created_at))))) (testing "List collections" (let [expected [{:default_sorting_field "num_employees" :fields [{:facet false :index true :name "company_name" :optional false :type "string" :infix false :locale "" :sort false} {:facet false :index true :name "num_employees" :optional false :type "int32" :infix false :locale "" :sort true} {:facet true :index true :name "country" :optional false :type "string" :infix false :locale "" :sort false}] :name "companies_collection_test" :num_documents 0 :symbols_to_index [] :token_separators []}] response (sut/list-collections settings)] ;; We make individual test for :created_at since it changes each run. (is (true? (every? #(> (:created_at %) 0) response))) ;; We remove :created_at it cannot be asserted since it changes each run. (is (= expected (map #(dissoc % :created_at) response))))) (testing "Retrieve collection" (let [expected {:default_sorting_field "num_employees" :fields [{:facet false :index true :infix false :locale "" :name "company_name" :optional false :sort false :type "string"} {:facet false :index true :infix false :locale "" :name "num_employees" :optional false :sort true :type "int32"} {:facet true :index true :infix false :locale "" :name "country" :optional false :sort false :type "string"}] :name "companies_collection_test" :num_documents 0 :symbols_to_index [] :token_separators []} response (sut/retrieve-collection settings "companies_collection_test")] (is (> (:created_at response) 0)) ;; We remove :created_at it cannot be asserted since it changes each run. (is (= expected (dissoc response :created_at))))) (testing "Delete collection" (let [expected {:default_sorting_field "num_employees" :fields [{:facet false :index true :name "company_name" :optional false :type "string" :infix false :locale "" :sort false} {:facet false :index true :name "num_employees" :optional false :type "int32" :infix false :locale "" :sort true} {:facet true :index true :name "country" :optional false :type "string" :infix false :locale "" :sort false}] :name "companies_collection_test" :num_documents 0 :symbols_to_index [] :token_separators []} response (sut/delete-collection! settings "companies_collection_test")] (is (> (:created_at response) 0)) ;; We remove :created_at it cannot be asserted since it changes each run. (is (= expected (dissoc response :created_at))))) ;; Initialize test collection for documents (let [schema {:name "companies_document_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Create document" (let [expected {:company_name "Hotel Sand<NAME> Københav<NAME> A/S" :country "DK" :id "0" :num_employees 5215} document {:company_name "Hotel <NAME>ø<NAME> A/S" :num_employees 5215 :country "DK"} response (sut/create-document! settings "companies_document_test" document)] (is (= expected response)))) (testing "Upsert document" (let [expected {:company_name "Awesome Inc." :num_employees 10 :country "Norway" :id "1"} document {:company_name "Awesome Inc." :num_employees 10 :country "Norway"} response (sut/upsert-document! settings "companies_document_test" document)] (is (= expected response)))) (testing "Retrieve document" (let [expected {:company_name "Awesome Inc." :num_employees 10 :country "Norway" :id "1"} response (sut/retrieve-document settings "companies_document_test" 1)] (is (= expected response)))) (testing "Update document" (let [expected {:company_name "Mega Awesome Inc." :num_employees 10 :country "Norway" :id "1"} update-doc {:company_name "Mega Awesome Inc."} response (sut/update-document! settings "companies_document_test" 1 update-doc)] (is (= expected response)))) (testing "Delete document" (let [expected {:company_name "Hotel <NAME> K<NAME> A/S" :country "DK" :id "0" :num_employees 5215} response (sut/delete-document! settings "companies_document_test" 0)] (is (= expected response)))) ;; Initize test collection for documents (let [schema {:name "companies_documents_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Create documents" (let [exp [{:success true} {:success true}] res (sut/create-documents! settings "companies_documents_test" [{:id "1" :company_name "Innovationsoft A/S" :num_employees 10 :country "Finland"} {:id "2" :company_name "GoSoftware" :num_employees 5000 :country "Sweden"}])] (is (= exp res)))) (testing "Upsert documents" (let [exp [{:success true} {:success true}] res (sut/upsert-documents! settings "companies_documents_test" [{:id "1" :company_name "Innovationsoft A/S" :num_employees 10 :country "Finland"} {:id "3" :company_name "Awesomesoftwaresoft" :num_employees 105 :country "Denmark"}])] (is (= exp res)))) (testing "Update documents" (let [exp [{:success true} {:success true}] res (sut/update-documents! settings "companies_documents_test" [{:id "1" :company_name "Innovationsoft A/S" :num_employees 10 :country "Finland"} {:id "2" :company_name "GoSoftware" :num_employees 5000 :country "Sweden"}])] (is (= exp res)))) (testing "Delete documents" (let [exp {:num_deleted 2} res (sut/delete-documents! settings "companies_documents_test" {:filter_by "num_employees:>=100"})] (is (= exp res)))) (testing "Export documents" (let [exp [{:id "1" :company_name "Innovationsoft A/S" :num_employees 10 :country "Finland"}] res (sut/export-documents settings "companies_documents_test" {:filter_by "num_employees:<=100"})] (is (= exp res)))) (testing "Search" (let [exp {:facet_counts [] :found 1 :hits [{:document {:company_name "Innovationsoft A/S" :country "Finland" :id "1" :num_employees 10} :highlights [{:field "company_name" :matched_tokens ["Innovation"] :snippet "<mark>Innovation</mark>soft A/S"}] :text_match 282583051272193}] :out_of 1 :page 1 :request_params {:collection_name "companies_documents_test" :per_page 10 :q "Innovation"} :search_cutoff false :search_time_ms 0} res (sut/search settings "companies_documents_test" {:q "Innovation" :query_by "company_name"})] (is (= res exp)))) ;; Creating test setup for multi search (let [schema {:name "products_multi_search_test" :fields [{:name "name" :type "string"} {:name "price" :type "int32"}]}] (sut/create-collection! settings schema) (sut/create-document! settings "products_multi_search_test" {:id "1" :name "<NAME>" :price 75})) (let [schema {:name "brands_multi_search_test" :fields [{:name "name" :type "string"}]}] (sut/create-collection! settings schema) (sut/create-document! settings "brands_multi_search_test" {:id "1" :name "<NAME>"})) (testing "Multi search" (let [exp {:results [{:facet_counts [] :found 1 :hits [{:document {:id "1" :name "<NAME>" :price 75} :highlights [{:field "name" :matched_tokens ["shoe"] :snippet "<mark>shoe</mark>"}] :text_match 282583068049665}] :out_of 1 :page 1 :request_params {:collection_name "products_multi_search_test" :per_page 10 :q "shoe"} :search_cutoff false :search_time_ms 0} {:facet_counts [] :found 1 :hits [{:document {:id "1" :name "<NAME>"} :highlights [{:field "name" :matched_tokens ["<NAME>"] :snippet "<mark>Nike</mark>"}] :text_match 282583068049665}] :out_of 1 :page 1 :request_params {:collection_name "brands_multi_search_test" :per_page 10 :q "Nike"} :search_cutoff false :search_time_ms 0}]} res (sut/multi-search settings {:searches [{:collection "products_multi_search_test" :q "shoe" :filter_by "price:=[50..120]"} {:collection "brands_multi_search_test" :q "Nike"}]} {:query_by "name"})] (is (= exp res)))) ;; Initialize test collection with documents for geosearch. (let [schema {:name "places" :fields [{:name "title" :type "string"} {:name "points" :type "int32"} {:name "location" :type "geopoint"}] :default_sorting_field "points"} document {:points 1 :title "<NAME>" :location [48.86093481609114 2.33698396872901]}] (sut/create-collection! settings schema) (sut/create-document! settings "places" document)) (testing "Geosearch" (let [exp {:facet_counts [] :found 1 :hits [{:document {:id "0" :location [48.86093481609114 2.33698396872901] :points 1 :title "<NAME>useuem"} :geo_distance_meters {:location 1020} :highlights [] :text_match 100}] :out_of 1 :page 1 :request_params {:collection_name "places" :per_page 10 :q "*"} :search_cutoff false :search_time_ms 0} res (sut/search settings "places" {:q "*" :query_by "title" :filter_by "location:(48.90615915923891, 2.3435897727061175, 5.1 km)" :sort_by "location(48.853, 2.344):asc"})] ;; We test :search_time_ms individually since it can chane each run. (is (number? (res :search_time_ms))) (is (= (dissoc exp :search_time_ms) (dissoc res :search_time_ms))))) ;; Initialize test collection for curation. (let [schema {:name "companies_curation_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Upsert override" (let [exp {:excludes [{:id "287"}] :id "customize_apple" :includes [{:id "422" :position 1} {:id "54" :position 2}] :rule {:match "exact" :query "apple"}} res (sut/upsert-override! settings "companies_curation_test" "customize_apple" {:rule {:query "apple" :match "exact"} :includes [{:id "422" :position 1} {:id "54" :position 2}] :excludes [{:id "287"}]})] (is (= exp res)))) (testing "List all overrides" (let [exp {:overrides [{:excludes [{:id "287"}] :id "customize_apple" :includes [{:id "422" :position 1} {:id "54" :position 2}] :rule {:match "exact" :query "apple"} :filter_curated_hits false :remove_matched_tokens false}]} res (sut/list-overrides settings "companies_curation_test")] (is (= exp res)))) (testing "Retrieve override" (let [exp {:excludes [{:id "287"}] :id "customize_apple" :includes [{:id "422" :position 1} {:id "54" :position 2}] :rule {:match "exact" :query "apple"} :filter_curated_hits false :remove_matched_tokens false} res (sut/retrieve-override settings "companies_curation_test" "customize_apple")] (is (= exp res)))) (testing "Delete override" (let [exp {:id "customize_apple"} res (sut/delete-override! settings "companies_curation_test" "customize_apple")] (is (= exp res)))) ;; Initialize test collection for alias. (let [schema {:name "companies_alias_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Upsert alias" (let [exp {:collection_name "companies_alias_test" :name "companies"} res (sut/upsert-alias! settings "companies" {:collection_name "companies_alias_test"})] (is (= exp res)))) (testing "List all aliases" (let [exp {:aliases [{:collection_name "companies_alias_test" :name "companies"}]} res (sut/list-aliases settings)] (is (= exp res)))) (testing "Retrieve alias" (let [exp {:collection_name "companies_alias_test" :name "companies"} res (sut/retrieve-alias settings "companies")] (is (= exp res)))) (testing "Delete alias" (let [exp {:collection_name "companies_alias_test" :name "companies"} res (sut/delete-alias! settings "companies")] (is (= exp res)))) ;; Initialize test collection for synonyms. (let [schema {:name "products_synonyms_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Upsert synonym" (let [exp {:id "coat-synonyms" :synonyms ["blazer" "coat" "jacket"]} res (sut/upsert-synonym! settings "products_synonyms_test" "coat-synonyms" {:synonyms ["blazer" "coat" "jacket"]})] (is (= exp res)))) (testing "Retrieve synonym" (let [exp {:id "coat-synonyms" :root "" :synonyms ["blazer" "coat" "jacket"]} res (sut/retrieve-synonym settings "products_synonyms_test" "coat-synonyms")] (is (= exp res)))) (testing "List synonyms" (let [exp {:synonyms [{:id "coat-synonyms" :root "" :synonyms ["blazer" "coat" "jacket"]}]} res (sut/list-synonyms settings "products_synonyms_test")] (is (= exp res)))) (testing "Delete synonym" (let [exp {:id "coat-synonyms"} res (sut/delete-synonym! settings "products_synonyms_test" "coat-synonyms")] (is (= res exp))))) (defn api-key-constant-values "Helper function to get unique values of api-key." [k] (dissoc k :id :value :expires_at :value_prefix)) (deftest client-api-key-tests (testing "Create api key" (let [exp {:actions ["document:search"] :collections ["companies"] :description "Search only companies key." :expires_at 64723363199 :id 0 :value "sK0jo6CSn1EBoJJ8LKPjRZCtsJ1JCFkt"} key {:description "Search only companies key." :actions ["document:search"] :collections ["companies"]} res (sut/create-api-key! settings key)] ;; We test individual cases since they will change each run. (is (> (count (:value res)) 0)) (is (> (:expires_at res) 0)) (is (>= (:id res) 0)) ;; We test the values that do not change each run. (is (= (api-key-constant-values exp) (api-key-constant-values res))))) (testing "Retrieve api key" ;; We have to retrieve the first key-id this way because they change each run. (let [id (-> (sut/list-api-keys settings) :keys first :id) exp {:actions ["document:search"] :collections ["companies"] :description "Search only companies key." :expires_at 64723363199 :id 49 :value_prefix "Bx3y"} res (sut/retrieve-api-key settings id)] ;; We make individual tests for the parameters since they change each run. (is (>= (:id res) 0)) (is (> (:expires_at res) 0)) (is (> (count (:value_prefix res)) 0)) ;; We test the values that do not change each run. (is (= (api-key-constant-values exp) (api-key-constant-values res))))) (testing "List api keys" (let [exp {:keys [{:actions ["document:search"] :collections ["companies"] :description "Search only companies key." :expires_at 64723363199 :id 17 :value_prefix "vLbB"}]} res (sut/list-api-keys settings)] ;; We make individual tests for the parameters since they change each run. (is (every? #(>= (:id %) 0) (:keys res))) (is (every? #(>= (:expires_at %) 0) (:keys res))) (is (every? #(> (count (:value_prefix %)) 0) (:keys res))) ;; We test the values that do not change each run. (is (= (update-in exp [:keys] #(map api-key-constant-values %)) (update-in res [:keys] #(map api-key-constant-values %)))))) (testing "Delete api key" (let [id (-> (sut/list-api-keys settings) :keys first :id) exp {:id id} res (sut/delete-api-key! settings id)] (is (= exp res)))))
true
(ns ^:integration typesense.client-test (:require [typesense.client :as sut] [clojure.test :as t :refer [deftest is testing]])) (def settings {:uri "http://localhost:8108" :key "key"}) (defn- clean-collections "Cleans all collections in Typesense." [] (let [collections (sut/list-collections settings)] (doseq [collection collections] (sut/delete-collection! settings (:name collection))))) (defn- clean-api-keys "Clean all api-keys." [] (let [keys (sut/list-api-keys settings)] (doseq [key (:keys keys)] (sut/delete-api-key! settings (:id key))))) (defn- clean-aliases "Cleans all aliases." [] (let [aliases (sut/list-aliases settings)] (doseq [key (:aliases aliases)] (sut/delete-alias! settings key)))) (defn- clean-typesense-fixture "Cleanup before each integration test run." [f] (clean-collections) (clean-api-keys) (clean-aliases) (f)) (t/use-fixtures :once clean-typesense-fixture) ;; Handles the primary workflow for interactiong with the Typesense Client. ;; The flow is inside of a single deftest because the interaction with the API ;; is stateful so it simplifies the test cases to keep them together. ;; If we had decided to split them out listing collections might result in issues. (deftest client-primary-workflow-tests (testing "Create collection" (let [expected {:default_sorting_field "num_employees" :fields [{:facet false :index true :name "company_name" :optional false :type "string" :infix false :locale "" :sort false} {:facet false :index true :name "num_employees" :optional false :type "int32" :infix false :locale "" :sort true} {:facet true :index true :name "country" :optional false :type "string" :infix false :locale "" :sort false}] :name "companies_collection_test" :num_documents 0 :symbols_to_index [] :token_separators []} schema {:name "companies_collection_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"} response (sut/create-collection! settings schema)] ;; We make individual test for :created_at since it changes each run. (is (> (:created_at response) 0)) ;; We remove :created_at it cannot be asserted since it changes each run. (is (= expected (dissoc response :created_at))))) (testing "List collections" (let [expected [{:default_sorting_field "num_employees" :fields [{:facet false :index true :name "company_name" :optional false :type "string" :infix false :locale "" :sort false} {:facet false :index true :name "num_employees" :optional false :type "int32" :infix false :locale "" :sort true} {:facet true :index true :name "country" :optional false :type "string" :infix false :locale "" :sort false}] :name "companies_collection_test" :num_documents 0 :symbols_to_index [] :token_separators []}] response (sut/list-collections settings)] ;; We make individual test for :created_at since it changes each run. (is (true? (every? #(> (:created_at %) 0) response))) ;; We remove :created_at it cannot be asserted since it changes each run. (is (= expected (map #(dissoc % :created_at) response))))) (testing "Retrieve collection" (let [expected {:default_sorting_field "num_employees" :fields [{:facet false :index true :infix false :locale "" :name "company_name" :optional false :sort false :type "string"} {:facet false :index true :infix false :locale "" :name "num_employees" :optional false :sort true :type "int32"} {:facet true :index true :infix false :locale "" :name "country" :optional false :sort false :type "string"}] :name "companies_collection_test" :num_documents 0 :symbols_to_index [] :token_separators []} response (sut/retrieve-collection settings "companies_collection_test")] (is (> (:created_at response) 0)) ;; We remove :created_at it cannot be asserted since it changes each run. (is (= expected (dissoc response :created_at))))) (testing "Delete collection" (let [expected {:default_sorting_field "num_employees" :fields [{:facet false :index true :name "company_name" :optional false :type "string" :infix false :locale "" :sort false} {:facet false :index true :name "num_employees" :optional false :type "int32" :infix false :locale "" :sort true} {:facet true :index true :name "country" :optional false :type "string" :infix false :locale "" :sort false}] :name "companies_collection_test" :num_documents 0 :symbols_to_index [] :token_separators []} response (sut/delete-collection! settings "companies_collection_test")] (is (> (:created_at response) 0)) ;; We remove :created_at it cannot be asserted since it changes each run. (is (= expected (dissoc response :created_at))))) ;; Initialize test collection for documents (let [schema {:name "companies_document_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Create document" (let [expected {:company_name "Hotel SandPI:NAME:<NAME>END_PI KøbenhavPI:NAME:<NAME>END_PI A/S" :country "DK" :id "0" :num_employees 5215} document {:company_name "Hotel PI:NAME:<NAME>END_PIøPI:NAME:<NAME>END_PI A/S" :num_employees 5215 :country "DK"} response (sut/create-document! settings "companies_document_test" document)] (is (= expected response)))) (testing "Upsert document" (let [expected {:company_name "Awesome Inc." :num_employees 10 :country "Norway" :id "1"} document {:company_name "Awesome Inc." :num_employees 10 :country "Norway"} response (sut/upsert-document! settings "companies_document_test" document)] (is (= expected response)))) (testing "Retrieve document" (let [expected {:company_name "Awesome Inc." :num_employees 10 :country "Norway" :id "1"} response (sut/retrieve-document settings "companies_document_test" 1)] (is (= expected response)))) (testing "Update document" (let [expected {:company_name "Mega Awesome Inc." :num_employees 10 :country "Norway" :id "1"} update-doc {:company_name "Mega Awesome Inc."} response (sut/update-document! settings "companies_document_test" 1 update-doc)] (is (= expected response)))) (testing "Delete document" (let [expected {:company_name "Hotel PI:NAME:<NAME>END_PI KPI:NAME:<NAME>END_PI A/S" :country "DK" :id "0" :num_employees 5215} response (sut/delete-document! settings "companies_document_test" 0)] (is (= expected response)))) ;; Initize test collection for documents (let [schema {:name "companies_documents_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Create documents" (let [exp [{:success true} {:success true}] res (sut/create-documents! settings "companies_documents_test" [{:id "1" :company_name "Innovationsoft A/S" :num_employees 10 :country "Finland"} {:id "2" :company_name "GoSoftware" :num_employees 5000 :country "Sweden"}])] (is (= exp res)))) (testing "Upsert documents" (let [exp [{:success true} {:success true}] res (sut/upsert-documents! settings "companies_documents_test" [{:id "1" :company_name "Innovationsoft A/S" :num_employees 10 :country "Finland"} {:id "3" :company_name "Awesomesoftwaresoft" :num_employees 105 :country "Denmark"}])] (is (= exp res)))) (testing "Update documents" (let [exp [{:success true} {:success true}] res (sut/update-documents! settings "companies_documents_test" [{:id "1" :company_name "Innovationsoft A/S" :num_employees 10 :country "Finland"} {:id "2" :company_name "GoSoftware" :num_employees 5000 :country "Sweden"}])] (is (= exp res)))) (testing "Delete documents" (let [exp {:num_deleted 2} res (sut/delete-documents! settings "companies_documents_test" {:filter_by "num_employees:>=100"})] (is (= exp res)))) (testing "Export documents" (let [exp [{:id "1" :company_name "Innovationsoft A/S" :num_employees 10 :country "Finland"}] res (sut/export-documents settings "companies_documents_test" {:filter_by "num_employees:<=100"})] (is (= exp res)))) (testing "Search" (let [exp {:facet_counts [] :found 1 :hits [{:document {:company_name "Innovationsoft A/S" :country "Finland" :id "1" :num_employees 10} :highlights [{:field "company_name" :matched_tokens ["Innovation"] :snippet "<mark>Innovation</mark>soft A/S"}] :text_match 282583051272193}] :out_of 1 :page 1 :request_params {:collection_name "companies_documents_test" :per_page 10 :q "Innovation"} :search_cutoff false :search_time_ms 0} res (sut/search settings "companies_documents_test" {:q "Innovation" :query_by "company_name"})] (is (= res exp)))) ;; Creating test setup for multi search (let [schema {:name "products_multi_search_test" :fields [{:name "name" :type "string"} {:name "price" :type "int32"}]}] (sut/create-collection! settings schema) (sut/create-document! settings "products_multi_search_test" {:id "1" :name "PI:NAME:<NAME>END_PI" :price 75})) (let [schema {:name "brands_multi_search_test" :fields [{:name "name" :type "string"}]}] (sut/create-collection! settings schema) (sut/create-document! settings "brands_multi_search_test" {:id "1" :name "PI:NAME:<NAME>END_PI"})) (testing "Multi search" (let [exp {:results [{:facet_counts [] :found 1 :hits [{:document {:id "1" :name "PI:NAME:<NAME>END_PI" :price 75} :highlights [{:field "name" :matched_tokens ["shoe"] :snippet "<mark>shoe</mark>"}] :text_match 282583068049665}] :out_of 1 :page 1 :request_params {:collection_name "products_multi_search_test" :per_page 10 :q "shoe"} :search_cutoff false :search_time_ms 0} {:facet_counts [] :found 1 :hits [{:document {:id "1" :name "PI:NAME:<NAME>END_PI"} :highlights [{:field "name" :matched_tokens ["PI:NAME:<NAME>END_PI"] :snippet "<mark>Nike</mark>"}] :text_match 282583068049665}] :out_of 1 :page 1 :request_params {:collection_name "brands_multi_search_test" :per_page 10 :q "Nike"} :search_cutoff false :search_time_ms 0}]} res (sut/multi-search settings {:searches [{:collection "products_multi_search_test" :q "shoe" :filter_by "price:=[50..120]"} {:collection "brands_multi_search_test" :q "Nike"}]} {:query_by "name"})] (is (= exp res)))) ;; Initialize test collection with documents for geosearch. (let [schema {:name "places" :fields [{:name "title" :type "string"} {:name "points" :type "int32"} {:name "location" :type "geopoint"}] :default_sorting_field "points"} document {:points 1 :title "PI:NAME:<NAME>END_PI" :location [48.86093481609114 2.33698396872901]}] (sut/create-collection! settings schema) (sut/create-document! settings "places" document)) (testing "Geosearch" (let [exp {:facet_counts [] :found 1 :hits [{:document {:id "0" :location [48.86093481609114 2.33698396872901] :points 1 :title "PI:NAME:<NAME>END_PIuseuem"} :geo_distance_meters {:location 1020} :highlights [] :text_match 100}] :out_of 1 :page 1 :request_params {:collection_name "places" :per_page 10 :q "*"} :search_cutoff false :search_time_ms 0} res (sut/search settings "places" {:q "*" :query_by "title" :filter_by "location:(48.90615915923891, 2.3435897727061175, 5.1 km)" :sort_by "location(48.853, 2.344):asc"})] ;; We test :search_time_ms individually since it can chane each run. (is (number? (res :search_time_ms))) (is (= (dissoc exp :search_time_ms) (dissoc res :search_time_ms))))) ;; Initialize test collection for curation. (let [schema {:name "companies_curation_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Upsert override" (let [exp {:excludes [{:id "287"}] :id "customize_apple" :includes [{:id "422" :position 1} {:id "54" :position 2}] :rule {:match "exact" :query "apple"}} res (sut/upsert-override! settings "companies_curation_test" "customize_apple" {:rule {:query "apple" :match "exact"} :includes [{:id "422" :position 1} {:id "54" :position 2}] :excludes [{:id "287"}]})] (is (= exp res)))) (testing "List all overrides" (let [exp {:overrides [{:excludes [{:id "287"}] :id "customize_apple" :includes [{:id "422" :position 1} {:id "54" :position 2}] :rule {:match "exact" :query "apple"} :filter_curated_hits false :remove_matched_tokens false}]} res (sut/list-overrides settings "companies_curation_test")] (is (= exp res)))) (testing "Retrieve override" (let [exp {:excludes [{:id "287"}] :id "customize_apple" :includes [{:id "422" :position 1} {:id "54" :position 2}] :rule {:match "exact" :query "apple"} :filter_curated_hits false :remove_matched_tokens false} res (sut/retrieve-override settings "companies_curation_test" "customize_apple")] (is (= exp res)))) (testing "Delete override" (let [exp {:id "customize_apple"} res (sut/delete-override! settings "companies_curation_test" "customize_apple")] (is (= exp res)))) ;; Initialize test collection for alias. (let [schema {:name "companies_alias_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Upsert alias" (let [exp {:collection_name "companies_alias_test" :name "companies"} res (sut/upsert-alias! settings "companies" {:collection_name "companies_alias_test"})] (is (= exp res)))) (testing "List all aliases" (let [exp {:aliases [{:collection_name "companies_alias_test" :name "companies"}]} res (sut/list-aliases settings)] (is (= exp res)))) (testing "Retrieve alias" (let [exp {:collection_name "companies_alias_test" :name "companies"} res (sut/retrieve-alias settings "companies")] (is (= exp res)))) (testing "Delete alias" (let [exp {:collection_name "companies_alias_test" :name "companies"} res (sut/delete-alias! settings "companies")] (is (= exp res)))) ;; Initialize test collection for synonyms. (let [schema {:name "products_synonyms_test" :fields [{:name "company_name" :type "string"} {:name "num_employees" :type "int32"} {:name "country" :type "string" :facet true}] :default_sorting_field "num_employees"}] (sut/create-collection! settings schema)) (testing "Upsert synonym" (let [exp {:id "coat-synonyms" :synonyms ["blazer" "coat" "jacket"]} res (sut/upsert-synonym! settings "products_synonyms_test" "coat-synonyms" {:synonyms ["blazer" "coat" "jacket"]})] (is (= exp res)))) (testing "Retrieve synonym" (let [exp {:id "coat-synonyms" :root "" :synonyms ["blazer" "coat" "jacket"]} res (sut/retrieve-synonym settings "products_synonyms_test" "coat-synonyms")] (is (= exp res)))) (testing "List synonyms" (let [exp {:synonyms [{:id "coat-synonyms" :root "" :synonyms ["blazer" "coat" "jacket"]}]} res (sut/list-synonyms settings "products_synonyms_test")] (is (= exp res)))) (testing "Delete synonym" (let [exp {:id "coat-synonyms"} res (sut/delete-synonym! settings "products_synonyms_test" "coat-synonyms")] (is (= res exp))))) (defn api-key-constant-values "Helper function to get unique values of api-key." [k] (dissoc k :id :value :expires_at :value_prefix)) (deftest client-api-key-tests (testing "Create api key" (let [exp {:actions ["document:search"] :collections ["companies"] :description "Search only companies key." :expires_at 64723363199 :id 0 :value "sK0jo6CSn1EBoJJ8LKPjRZCtsJ1JCFkt"} key {:description "Search only companies key." :actions ["document:search"] :collections ["companies"]} res (sut/create-api-key! settings key)] ;; We test individual cases since they will change each run. (is (> (count (:value res)) 0)) (is (> (:expires_at res) 0)) (is (>= (:id res) 0)) ;; We test the values that do not change each run. (is (= (api-key-constant-values exp) (api-key-constant-values res))))) (testing "Retrieve api key" ;; We have to retrieve the first key-id this way because they change each run. (let [id (-> (sut/list-api-keys settings) :keys first :id) exp {:actions ["document:search"] :collections ["companies"] :description "Search only companies key." :expires_at 64723363199 :id 49 :value_prefix "Bx3y"} res (sut/retrieve-api-key settings id)] ;; We make individual tests for the parameters since they change each run. (is (>= (:id res) 0)) (is (> (:expires_at res) 0)) (is (> (count (:value_prefix res)) 0)) ;; We test the values that do not change each run. (is (= (api-key-constant-values exp) (api-key-constant-values res))))) (testing "List api keys" (let [exp {:keys [{:actions ["document:search"] :collections ["companies"] :description "Search only companies key." :expires_at 64723363199 :id 17 :value_prefix "vLbB"}]} res (sut/list-api-keys settings)] ;; We make individual tests for the parameters since they change each run. (is (every? #(>= (:id %) 0) (:keys res))) (is (every? #(>= (:expires_at %) 0) (:keys res))) (is (every? #(> (count (:value_prefix %)) 0) (:keys res))) ;; We test the values that do not change each run. (is (= (update-in exp [:keys] #(map api-key-constant-values %)) (update-in res [:keys] #(map api-key-constant-values %)))))) (testing "Delete api key" (let [id (-> (sut/list-api-keys settings) :keys first :id) exp {:id id} res (sut/delete-api-key! settings id)] (is (= exp res)))))
[ { "context": "port = PORT\n user = USER\n passwd = PASSWD\n realm = REALM\n \"\n [config]\n (try\n ", "end": 1409, "score": 0.9987310171127319, "start": 1403, "tag": "PASSWORD", "value": "PASSWD" } ]
src/fops/core.clj
cyraxjoe/fops
0
(ns fops.core (:import (java.io FileNotFoundException)) (:require [clojure.string :as string] [ring.adapter.jetty :refer [run-jetty]] [com.brainbot.iniconfig :as iniconfig] [clojure.tools.cli :refer [parse-opts]] [ring.middleware.basic-authentication :refer [wrap-basic-authentication]] [fops.web :as web] [fops.utils :refer [error-msg]]) (:gen-class)) (def cli-options [["-p" "--port PORT" "Port number" :default 3000 :parse-fn #(Integer/parseInt %) :validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]] ["-H" "--host HOST" "Hostname" :default "localhost"] ["-c" "--config CONFIG" "Config file"] ["-h" "--help"]]) (def banner (str "FOPS Server v" (System/getProperty "fops.version"))) (def section-name "fops") (defmacro authenticated? [refname refpasswd] `(fn [name# passwd#] (and (= name# ~refname) (= passwd# ~refpasswd)))) (defmacro clean-string [word] `(when ~word (-> ~word string/trim strip-quotes))) (defn- strip-quotes "Remove the single and doble quotes from the input string." [word] (string/replace (string/replace word "'" "") "\"" "")) (defn- options-from-config "Read the configuration file with 'ini' syntax. It will look for: [fops] host = HOST port = PORT user = USER passwd = PASSWD realm = REALM " [config] (try (let [content (iniconfig/read-ini config)] (when-let [cfg-section (get content section-name)] (let [host (get cfg-section "host") port (get cfg-section "port")] (if (and host port) {:host (clean-string host) :port (Integer/parseInt port) :user (clean-string (get cfg-section "user")) :passwd (clean-string (get cfg-section "passwd")) :realm (clean-string (get cfg-section "realm"))} (error-msg "Missing required variables in config file 'host'/'port'."))))) (catch FileNotFoundException e (error-msg e)))) (defn- build-app [options] (let [user (:user options) passwd (:passwd options) app (if (and user passwd) (wrap-basic-authentication web/app (authenticated? user passwd) (:realm options "FOP Server")) web/app)] app)) (defn- run-server "Initialize the fops server from the cmdline options." [opts] (if-let [options (if-let [config (get-in opts [:options :config])] (options-from-config config) (:options opts))] (run-jetty (build-app options) {:port (:port options) :host (:host options)}) (System/exit 1))) (defn- show-cli-errors-and-exit "Display the cli errors on stderr and then exit with error code 1. The errors include the initial option validator." [opts] (error-msg "Errors: " (apply str (:errors opts)) banner (:summary opts)) (System/exit 1)) (defn- show-help [opts] (println banner "\n" (:summary opts))) (defn -main "Entry point of the standalone mode of fops." [& args] (let [opts (parse-opts args cli-options)] (cond (get-in opts [:options :help]) (show-help opts) (empty? (:errors opts)) (run-server opts) :else (show-cli-errors-and-exit opts))))
75717
(ns fops.core (:import (java.io FileNotFoundException)) (:require [clojure.string :as string] [ring.adapter.jetty :refer [run-jetty]] [com.brainbot.iniconfig :as iniconfig] [clojure.tools.cli :refer [parse-opts]] [ring.middleware.basic-authentication :refer [wrap-basic-authentication]] [fops.web :as web] [fops.utils :refer [error-msg]]) (:gen-class)) (def cli-options [["-p" "--port PORT" "Port number" :default 3000 :parse-fn #(Integer/parseInt %) :validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]] ["-H" "--host HOST" "Hostname" :default "localhost"] ["-c" "--config CONFIG" "Config file"] ["-h" "--help"]]) (def banner (str "FOPS Server v" (System/getProperty "fops.version"))) (def section-name "fops") (defmacro authenticated? [refname refpasswd] `(fn [name# passwd#] (and (= name# ~refname) (= passwd# ~refpasswd)))) (defmacro clean-string [word] `(when ~word (-> ~word string/trim strip-quotes))) (defn- strip-quotes "Remove the single and doble quotes from the input string." [word] (string/replace (string/replace word "'" "") "\"" "")) (defn- options-from-config "Read the configuration file with 'ini' syntax. It will look for: [fops] host = HOST port = PORT user = USER passwd = <PASSWORD> realm = REALM " [config] (try (let [content (iniconfig/read-ini config)] (when-let [cfg-section (get content section-name)] (let [host (get cfg-section "host") port (get cfg-section "port")] (if (and host port) {:host (clean-string host) :port (Integer/parseInt port) :user (clean-string (get cfg-section "user")) :passwd (clean-string (get cfg-section "passwd")) :realm (clean-string (get cfg-section "realm"))} (error-msg "Missing required variables in config file 'host'/'port'."))))) (catch FileNotFoundException e (error-msg e)))) (defn- build-app [options] (let [user (:user options) passwd (:passwd options) app (if (and user passwd) (wrap-basic-authentication web/app (authenticated? user passwd) (:realm options "FOP Server")) web/app)] app)) (defn- run-server "Initialize the fops server from the cmdline options." [opts] (if-let [options (if-let [config (get-in opts [:options :config])] (options-from-config config) (:options opts))] (run-jetty (build-app options) {:port (:port options) :host (:host options)}) (System/exit 1))) (defn- show-cli-errors-and-exit "Display the cli errors on stderr and then exit with error code 1. The errors include the initial option validator." [opts] (error-msg "Errors: " (apply str (:errors opts)) banner (:summary opts)) (System/exit 1)) (defn- show-help [opts] (println banner "\n" (:summary opts))) (defn -main "Entry point of the standalone mode of fops." [& args] (let [opts (parse-opts args cli-options)] (cond (get-in opts [:options :help]) (show-help opts) (empty? (:errors opts)) (run-server opts) :else (show-cli-errors-and-exit opts))))
true
(ns fops.core (:import (java.io FileNotFoundException)) (:require [clojure.string :as string] [ring.adapter.jetty :refer [run-jetty]] [com.brainbot.iniconfig :as iniconfig] [clojure.tools.cli :refer [parse-opts]] [ring.middleware.basic-authentication :refer [wrap-basic-authentication]] [fops.web :as web] [fops.utils :refer [error-msg]]) (:gen-class)) (def cli-options [["-p" "--port PORT" "Port number" :default 3000 :parse-fn #(Integer/parseInt %) :validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]] ["-H" "--host HOST" "Hostname" :default "localhost"] ["-c" "--config CONFIG" "Config file"] ["-h" "--help"]]) (def banner (str "FOPS Server v" (System/getProperty "fops.version"))) (def section-name "fops") (defmacro authenticated? [refname refpasswd] `(fn [name# passwd#] (and (= name# ~refname) (= passwd# ~refpasswd)))) (defmacro clean-string [word] `(when ~word (-> ~word string/trim strip-quotes))) (defn- strip-quotes "Remove the single and doble quotes from the input string." [word] (string/replace (string/replace word "'" "") "\"" "")) (defn- options-from-config "Read the configuration file with 'ini' syntax. It will look for: [fops] host = HOST port = PORT user = USER passwd = PI:PASSWORD:<PASSWORD>END_PI realm = REALM " [config] (try (let [content (iniconfig/read-ini config)] (when-let [cfg-section (get content section-name)] (let [host (get cfg-section "host") port (get cfg-section "port")] (if (and host port) {:host (clean-string host) :port (Integer/parseInt port) :user (clean-string (get cfg-section "user")) :passwd (clean-string (get cfg-section "passwd")) :realm (clean-string (get cfg-section "realm"))} (error-msg "Missing required variables in config file 'host'/'port'."))))) (catch FileNotFoundException e (error-msg e)))) (defn- build-app [options] (let [user (:user options) passwd (:passwd options) app (if (and user passwd) (wrap-basic-authentication web/app (authenticated? user passwd) (:realm options "FOP Server")) web/app)] app)) (defn- run-server "Initialize the fops server from the cmdline options." [opts] (if-let [options (if-let [config (get-in opts [:options :config])] (options-from-config config) (:options opts))] (run-jetty (build-app options) {:port (:port options) :host (:host options)}) (System/exit 1))) (defn- show-cli-errors-and-exit "Display the cli errors on stderr and then exit with error code 1. The errors include the initial option validator." [opts] (error-msg "Errors: " (apply str (:errors opts)) banner (:summary opts)) (System/exit 1)) (defn- show-help [opts] (println banner "\n" (:summary opts))) (defn -main "Entry point of the standalone mode of fops." [& args] (let [opts (parse-opts args cli-options)] (cond (get-in opts [:options :help]) (show-help opts) (empty? (:errors opts)) (run-server opts) :else (show-cli-errors-and-exit opts))))
[ { "context": "st.com:9999/some-database?user=some-user&password=some-password\"\n (clj-database-url.core/jdbc-database-", "end": 302, "score": 0.9991393089294434, "start": 289, "tag": "PASSWORD", "value": "some-password" }, { "context": "bc-database-url\n \"postgres://some-user:some-password@some.host.com:9999/some-database\"))))\n\n (testing \"DATABASE_URL", "end": 417, "score": 0.997345507144928, "start": 390, "tag": "EMAIL", "value": "some-password@some.host.com" }, { "context": "st.com:5432/some-database?user=some-user&password=some-password\"\n (clj-database-url.core/jdbc-database-", "end": 612, "score": 0.9990836977958679, "start": 599, "tag": "PASSWORD", "value": "some-password" }, { "context": "bc-database-url\n \"postgres://some-user:some-password@some.host.com/some-database\"))))\n\n (testing \"JDBC_DATABASE_URL", "end": 727, "score": 0.9632925391197205, "start": 700, "tag": "EMAIL", "value": "some-password@some.host.com" }, { "context": "st.com:5432/some-database?user=some-user&password=some-password\"\n (clj-database-url.core/jdbc-database-", "end": 928, "score": 0.9987942576408386, "start": 915, "tag": "PASSWORD", "value": "some-password" }, { "context": "st.com:5432/some-database?user=some-user&password=some-password\")))))\n", "end": 1083, "score": 0.9976756572723389, "start": 1070, "tag": "PASSWORD", "value": "some-password" } ]
test/clj_database_url/core_test.clj
kwrooijen/clj-database-url
0
(ns clj-database-url.core-test (:require [clojure.test :refer :all] [clj-database-url.core])) (deftest test-jdbc-database-url (testing "DATABASE_URL should be converted to JDBC_DATABASE_URL" (is (= "jdbc:postgresql://some.host.com:9999/some-database?user=some-user&password=some-password" (clj-database-url.core/jdbc-database-url "postgres://some-user:some-password@some.host.com:9999/some-database")))) (testing "DATABASE_URL should default to 5432 if no PORT supplied" (is (= "jdbc:postgresql://some.host.com:5432/some-database?user=some-user&password=some-password" (clj-database-url.core/jdbc-database-url "postgres://some-user:some-password@some.host.com/some-database")))) (testing "JDBC_DATABASE_URL should be returned if JDBC_DATABASE_URL is given" (is (= "jdbc:postgresql://some.host.com:5432/some-database?user=some-user&password=some-password" (clj-database-url.core/jdbc-database-url "jdbc:postgresql://some.host.com:5432/some-database?user=some-user&password=some-password")))))
26740
(ns clj-database-url.core-test (:require [clojure.test :refer :all] [clj-database-url.core])) (deftest test-jdbc-database-url (testing "DATABASE_URL should be converted to JDBC_DATABASE_URL" (is (= "jdbc:postgresql://some.host.com:9999/some-database?user=some-user&password=<PASSWORD>" (clj-database-url.core/jdbc-database-url "postgres://some-user:<EMAIL>:9999/some-database")))) (testing "DATABASE_URL should default to 5432 if no PORT supplied" (is (= "jdbc:postgresql://some.host.com:5432/some-database?user=some-user&password=<PASSWORD>" (clj-database-url.core/jdbc-database-url "postgres://some-user:<EMAIL>/some-database")))) (testing "JDBC_DATABASE_URL should be returned if JDBC_DATABASE_URL is given" (is (= "jdbc:postgresql://some.host.com:5432/some-database?user=some-user&password=<PASSWORD>" (clj-database-url.core/jdbc-database-url "jdbc:postgresql://some.host.com:5432/some-database?user=some-user&password=<PASSWORD>")))))
true
(ns clj-database-url.core-test (:require [clojure.test :refer :all] [clj-database-url.core])) (deftest test-jdbc-database-url (testing "DATABASE_URL should be converted to JDBC_DATABASE_URL" (is (= "jdbc:postgresql://some.host.com:9999/some-database?user=some-user&password=PI:PASSWORD:<PASSWORD>END_PI" (clj-database-url.core/jdbc-database-url "postgres://some-user:PI:EMAIL:<EMAIL>END_PI:9999/some-database")))) (testing "DATABASE_URL should default to 5432 if no PORT supplied" (is (= "jdbc:postgresql://some.host.com:5432/some-database?user=some-user&password=PI:PASSWORD:<PASSWORD>END_PI" (clj-database-url.core/jdbc-database-url "postgres://some-user:PI:EMAIL:<EMAIL>END_PI/some-database")))) (testing "JDBC_DATABASE_URL should be returned if JDBC_DATABASE_URL is given" (is (= "jdbc:postgresql://some.host.com:5432/some-database?user=some-user&password=PI:PASSWORD:<PASSWORD>END_PI" (clj-database-url.core/jdbc-database-url "jdbc:postgresql://some.host.com:5432/some-database?user=some-user&password=PI:PASSWORD:<PASSWORD>END_PI")))))
[ { "context": "432/cwl\"\n :user \"cwl\"\n :password \"wish\"})\n\n(defn create-wishlist []\n (sql/with-connecti", "end": 234, "score": 0.9995449781417847, "start": 230, "tag": "PASSWORD", "value": "wish" } ]
src/wishlistd/models/init.clj
yuhama/wishlisted
1
(ns wishlistd.models.init (:require [clojure.java.jdbc :as sql])) (def db {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname "//localhost:5432/cwl" :user "cwl" :password "wish"}) (defn create-wishlist [] (sql/with-connection db (sql/create-table :wishlist [:code :varchar "PRIMARY KEY"] [:title :varchar "NOT NULL"] [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]))) (defn create-wish [] (sql/with-connection db (sql/create-table :wish [:id :serial "PRIMARY KEY"] [:description :varchar "NOT NULL"] [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"] [:url :varchar] [:wishlist_code :varchar] ["constraint fk_wish_wishlist foreign key(wishlist_code) references wishlist(code) on delete cascade"]))) (defn drop-tables [] (sql/with-connection db (sql/drop-table :wish) (sql/drop-table :wishlist))) (defn -main [cmd] (try (when (= cmd "drop" (drop-tables))) ; optionally drop tables before creating (create-wishlist) (create-wish) (catch Exception e (sql/print-sql-exception e))) (println "Done!"))
111603
(ns wishlistd.models.init (:require [clojure.java.jdbc :as sql])) (def db {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname "//localhost:5432/cwl" :user "cwl" :password "<PASSWORD>"}) (defn create-wishlist [] (sql/with-connection db (sql/create-table :wishlist [:code :varchar "PRIMARY KEY"] [:title :varchar "NOT NULL"] [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]))) (defn create-wish [] (sql/with-connection db (sql/create-table :wish [:id :serial "PRIMARY KEY"] [:description :varchar "NOT NULL"] [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"] [:url :varchar] [:wishlist_code :varchar] ["constraint fk_wish_wishlist foreign key(wishlist_code) references wishlist(code) on delete cascade"]))) (defn drop-tables [] (sql/with-connection db (sql/drop-table :wish) (sql/drop-table :wishlist))) (defn -main [cmd] (try (when (= cmd "drop" (drop-tables))) ; optionally drop tables before creating (create-wishlist) (create-wish) (catch Exception e (sql/print-sql-exception e))) (println "Done!"))
true
(ns wishlistd.models.init (:require [clojure.java.jdbc :as sql])) (def db {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname "//localhost:5432/cwl" :user "cwl" :password "PI:PASSWORD:<PASSWORD>END_PI"}) (defn create-wishlist [] (sql/with-connection db (sql/create-table :wishlist [:code :varchar "PRIMARY KEY"] [:title :varchar "NOT NULL"] [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"]))) (defn create-wish [] (sql/with-connection db (sql/create-table :wish [:id :serial "PRIMARY KEY"] [:description :varchar "NOT NULL"] [:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"] [:url :varchar] [:wishlist_code :varchar] ["constraint fk_wish_wishlist foreign key(wishlist_code) references wishlist(code) on delete cascade"]))) (defn drop-tables [] (sql/with-connection db (sql/drop-table :wish) (sql/drop-table :wishlist))) (defn -main [cmd] (try (when (= cmd "drop" (drop-tables))) ; optionally drop tables before creating (create-wishlist) (create-wish) (catch Exception e (sql/print-sql-exception e))) (println "Done!"))
[ { "context": "/opensource.org/licenses/MIT\n;; Copyright (c) 2014 François Rey\n\n;; CounterClockWiwe plugin for adding ANSI escap", "end": 112, "score": 0.9998877644538879, "start": 100, "tag": "NAME", "value": "François Rey" }, { "context": "I console plugin found at:\n;; https://github.com/mihnita/ansi-econsole\n;; See CCW user documentation for d", "end": 290, "score": 0.9982029795646667, "start": 283, "tag": "USERNAME", "value": "mihnita" }, { "context": "wise/issues/detail?id=629\n;;\n;; Initial version by Fran�ois Rey at https://gist.github.com/fmjrey/9889500\n;; Fixe", "end": 617, "score": 0.9998798966407776, "start": 605, "tag": "NAME", "value": "Fran�ois Rey" }, { "context": "ersion by Fran�ois Rey at https://gist.github.com/fmjrey/9889500\n;; Fixes for further versions of Counterc", "end": 651, "score": 0.9996182322502136, "start": 645, "tag": "USERNAME", "value": "fmjrey" }, { "context": " Fixes for further versions of Counterclockwise by Laurent Petit\n;; available at https://github.com/l", "end": 715, "score": 0.7087356448173523, "start": 713, "tag": "NAME", "value": "La" }, { "context": "aurent Petit\n;; available at https://github.com/laurentpetit/ccw-plugin-ansi-repl\n\n(ns ansi-repl\n (:require [", "end": 776, "score": 0.998499870300293, "start": 764, "tag": "USERNAME", "value": "laurentpetit" } ]
ansi-repl.clj
laurentpetit/ccw-plugin-ansi-repl
2
;; Licensed under The MIT License (MIT) ;; http://opensource.org/licenses/MIT ;; Copyright (c) 2014 François Rey ;; CounterClockWiwe plugin for adding ANSI escape code support to REPLs. ;; To enable its functionality install the ANSI console plugin found at: ;; https://github.com/mihnita/ansi-econsole ;; See CCW user documentation for details on plugin installation: ;; http://doc.ccw-ide.org/documentation.html#_user_plugins ;; See also: ;; https://code.google.com/p/counterclockwise/issues/detail?id=624 ;; https://code.google.com/p/counterclockwise/issues/detail?id=629 ;; ;; Initial version by Fran�ois Rey at https://gist.github.com/fmjrey/9889500 ;; Fixes for further versions of Counterclockwise by Laurent Petit ;; available at https://github.com/laurentpetit/ccw-plugin-ansi-repl (ns ansi-repl (:require [ccw.bundle :as bundle] [ccw.core.factories :as factories] [ccw.e4.dsl :refer :all] [ccw.eclipse :as eclipse] [ccw.swt :as swt]) (:import ccw.CCWPlugin [ccw.repl REPLView] org.eclipse.jface.action.Action org.eclipse.jface.resource.ImageDescriptor [org.eclipse.ui PlatformUI IPartListener] [org.eclipse.swt.custom StyledText ST LineStyleListener])) ;; Test CCW compatibility with the plugin (when-not (.isAssignableFrom LineStyleListener REPLView) (throw (RuntimeException. "Incompatible version of Counterclockwise with ansi-repl user plugin"))) ;; logging to eclipse log (defn log [& m] ;; Comment out the line below when logging is no longer necessary. ;; Logging is useful for developing, but can be annoying because ;; it brings to the foreground the Error Log view. ;(CCWPlugin/log (str "ANSI-REPL: " (apply str m))) ) ;; The following methods use reflection otherwise clojure ;; compilation will fail without the ansi console plugin. (def ansi-console-bundle (bundle/bundle "net.mihai-nita.ansicon.plugin")) (declare make-ansi-listener) (if (bundle/available? ansi-console-bundle) (def make-ansi-listener (factories/make-factory ansi-console-bundle "mnita.ansiconsole.participants.AnsiConsoleStyleListener" []))) ;; Plugin state that survives plugin reload. ;; Used to make sure we're not adding new listeners when one ;; is already present, otherwise reloading the plugin keeps ;; adding new listeners. ;; No need for an atom if only accessed from the UI thread. (defonce state {:installed false :part-listener nil :repls {}}) (defn installed? [] (:installed state)) (defn flag-installed [] (alter-var-root #'state assoc :installed true)) (defn flag-uninstalled [] (alter-var-root #'state assoc :installed false)) (defn repl-names-where-installed [] "Returns a possibly empty list of REPL names where ANSI support is installed." (doall (map #(.getPartName %) (keys (:repls state))))) (defn status-msg [] (if (bundle/available? ansi-console-bundle) (if (installed?) (if-let [rn (seq (repl-names-where-installed))] (str "ANSI support installed on these REPLs: \n" (apply str (map #(str " - " % \newline) rn))) (str "ANSI support installed, but there's no REPL.")) "ANSI support disabled.") (if ansi-console-bundle (str "ANSI support disabled: ANSI Console bundle in state " (.getState ansi-console-bundle)) "ANSI support disabled: ANSI Console bundle not found!"))) ;; StyleListener functions (defn redraw [^StyledText st] (if-not (. st (isDisposed)) (.redrawRange st 0 (.getCharCount st) true))) (defn remove-style-listener [^REPLView rv] ;(log (str "removing ansi listener for " (.getPartName rv))) (let [^StyledText st (.logPanel rv) sl (get-in state [:repls rv :listener])] (when sl (if-not (. st (isDisposed)) (.removeLineStyleListener st sl)) (alter-var-root #'state update-in [:repls rv] dissoc :listener) (log (str "removed listener for " (.getPartName rv))) (swt/doasync (redraw st))))) (defn add-style-listener [^REPLView rv] (let [^StyledText st (.logPanel rv)] (when (get-in state [:repls rv :listener]) (log (str "replacing existing listener for " (.getPartName rv))) (remove-style-listener rv)) (let [sl (make-ansi-listener)] (log (str "adding listener to " (.getPartName rv))) (.removeLineStyleListener st rv) (.addLineStyleListener st sl) ;; let's move the default REPL style listener last so that it can ;; take precedence over AnsiStyleListener (especially useful because ;; AnsiStyleListener colorize with the same foreground colors all lines, ;; even those that should not be touched) (.addLineStyleListener st rv) (alter-var-root #'state assoc-in [:repls rv :listener] sl) (swt/doasync (redraw st))))) ;; REPL Toolbar toggle button (when ansi-console-bundle (def icon-enabled-descriptor (ImageDescriptor/createFromURL (.getEntry ansi-console-bundle "/icons/ansiconsole.gif")))) (def ansi-action-id "toggle-ansi-support") (defn remove-toolbar-action [^REPLView rv] (when-let [action (get-in state [:repls rv :action])] (.. rv getViewSite getActionBars getToolBarManager (remove ansi-action-id)) (alter-var-root #'state update-in [:repls rv] dissoc :action) (log (str "removed toolbar button from " (.getPartName rv))))) (defn update-repl-ansi-state [^REPLView rv] (if (.isChecked (get-in state [:repls rv :action])) (add-style-listener rv) (remove-style-listener rv))) (defn add-toolbar-action [^REPLView rv] (when (get-in state [:repls rv :action]) (log (str "replacing toolbar button on " (.getPartName rv))) (remove-toolbar-action rv)) (let [action (proxy [Action] ["Process ANSI escape code" Action/AS_CHECK_BOX] (run [] (update-repl-ansi-state rv)))] (doto action (.setToolTipText "Process ANSI escape code") (.setImageDescriptor icon-enabled-descriptor) (.setId ansi-action-id) (.setChecked true)) ;; we start with Ansi REPL enabled (log (str "adding toolbar button on " (.getPartName rv))) (.. rv getViewSite getActionBars getToolBarManager (add action)) (.. rv getViewSite getActionBars getToolBarManager (update true)) ;; In a proxy there's no easy way to emulate the self-reference (this) ;; so we keep a record of the action for a given repl. (alter-var-root #'state assoc-in [:repls rv :action] action) (update-repl-ansi-state rv))) ;; Install/uninstall on a given REPL (defn install-on [^REPLView rv] (if (bundle/available? ansi-console-bundle) (if (installed?) (add-toolbar-action rv) (log (str "can't install on " (.getPartName rv) ":\n" (status-msg)))) (log (str "can't install on " (.getPartName rv) ":\n" (status-msg))))) (defn uninstall-from [^REPLView rv] (remove-toolbar-action rv) (remove-style-listener rv) (alter-var-root #'state update-in [:repls] dissoc rv)) ;; PartListener functions ;; Note: SWT listener methods are invoked by the UI thread. (defn make-part-listener [] ;(log "creating part listener") (reify IPartListener (partOpened [this p] (if (instance? REPLView p) (install-on p))) (partClosed [this p] (if (instance? REPLView p) (uninstall-from p))) (partActivated [this p] ()) (partBroughtToTop [this p] ()) (partDeactivated [this p] ()))) (defn remove-part-listener [] ;(log (str "removing part listener")) (when-let [^IPartListener pl (:part-listener state)] (log (str "removing part listener " pl)) (.. PlatformUI getWorkbench getActiveWorkbenchWindow getPartService (removePartListener pl)) (alter-var-root #'state dissoc :part-listener))) (defn add-part-listener [] (if (bundle/available? ansi-console-bundle) (do (remove-part-listener) ;; adding part listener (let [^IPartListener pl (make-part-listener)] (log (str "adding part listener")) (.. PlatformUI getWorkbench getActiveWorkbenchWindow getPartService (addPartListener pl)) (alter-var-root #'state assoc :part-listener pl))) (log "Cannot add part listener: ANSI Console plugin no longer available?"))) ;; Install/Uninstall ansi support (defn install [] (log "installing ANSI REPL") (when (and (bundle/available? ansi-console-bundle) (not (installed?))) ;; install a part listener for handling future REPLs (add-part-listener) (flag-installed) ;; handle existing REPLs (->> (CCWPlugin/getREPLViews) ;(map #(do (log (str "found " (.getPartName %))) %)) (filter #(if-let [rvl (.getLaunch %)] (not (.isTerminated rvl)))) (map #(install-on %)) (doall))) (log (status-msg))) (defn uninstall [] (log "disabling ANSI REPL") ;; install a part listener for handling future REPLs (remove-part-listener) ;; handle existing REPLs (doall (map #(remove-style-listener %) (keys (:repls state)))) ;; mark as uninstalled (flag-uninstalled) (log (status-msg)) ) ;; Define eclipse key binding (defn display-status [context] (eclipse/info-dialog "ANSI REPL" (status-msg))) (defcommand ansi-repl-status "ANSI REPL: display status") (defhandler ansi-repl-status display-status) (defkeybinding ansi-repl-status "Alt+U A") ;; Install upon starting the plugin (swt/doasync (install))
108442
;; Licensed under The MIT License (MIT) ;; http://opensource.org/licenses/MIT ;; Copyright (c) 2014 <NAME> ;; CounterClockWiwe plugin for adding ANSI escape code support to REPLs. ;; To enable its functionality install the ANSI console plugin found at: ;; https://github.com/mihnita/ansi-econsole ;; See CCW user documentation for details on plugin installation: ;; http://doc.ccw-ide.org/documentation.html#_user_plugins ;; See also: ;; https://code.google.com/p/counterclockwise/issues/detail?id=624 ;; https://code.google.com/p/counterclockwise/issues/detail?id=629 ;; ;; Initial version by <NAME> at https://gist.github.com/fmjrey/9889500 ;; Fixes for further versions of Counterclockwise by <NAME>urent Petit ;; available at https://github.com/laurentpetit/ccw-plugin-ansi-repl (ns ansi-repl (:require [ccw.bundle :as bundle] [ccw.core.factories :as factories] [ccw.e4.dsl :refer :all] [ccw.eclipse :as eclipse] [ccw.swt :as swt]) (:import ccw.CCWPlugin [ccw.repl REPLView] org.eclipse.jface.action.Action org.eclipse.jface.resource.ImageDescriptor [org.eclipse.ui PlatformUI IPartListener] [org.eclipse.swt.custom StyledText ST LineStyleListener])) ;; Test CCW compatibility with the plugin (when-not (.isAssignableFrom LineStyleListener REPLView) (throw (RuntimeException. "Incompatible version of Counterclockwise with ansi-repl user plugin"))) ;; logging to eclipse log (defn log [& m] ;; Comment out the line below when logging is no longer necessary. ;; Logging is useful for developing, but can be annoying because ;; it brings to the foreground the Error Log view. ;(CCWPlugin/log (str "ANSI-REPL: " (apply str m))) ) ;; The following methods use reflection otherwise clojure ;; compilation will fail without the ansi console plugin. (def ansi-console-bundle (bundle/bundle "net.mihai-nita.ansicon.plugin")) (declare make-ansi-listener) (if (bundle/available? ansi-console-bundle) (def make-ansi-listener (factories/make-factory ansi-console-bundle "mnita.ansiconsole.participants.AnsiConsoleStyleListener" []))) ;; Plugin state that survives plugin reload. ;; Used to make sure we're not adding new listeners when one ;; is already present, otherwise reloading the plugin keeps ;; adding new listeners. ;; No need for an atom if only accessed from the UI thread. (defonce state {:installed false :part-listener nil :repls {}}) (defn installed? [] (:installed state)) (defn flag-installed [] (alter-var-root #'state assoc :installed true)) (defn flag-uninstalled [] (alter-var-root #'state assoc :installed false)) (defn repl-names-where-installed [] "Returns a possibly empty list of REPL names where ANSI support is installed." (doall (map #(.getPartName %) (keys (:repls state))))) (defn status-msg [] (if (bundle/available? ansi-console-bundle) (if (installed?) (if-let [rn (seq (repl-names-where-installed))] (str "ANSI support installed on these REPLs: \n" (apply str (map #(str " - " % \newline) rn))) (str "ANSI support installed, but there's no REPL.")) "ANSI support disabled.") (if ansi-console-bundle (str "ANSI support disabled: ANSI Console bundle in state " (.getState ansi-console-bundle)) "ANSI support disabled: ANSI Console bundle not found!"))) ;; StyleListener functions (defn redraw [^StyledText st] (if-not (. st (isDisposed)) (.redrawRange st 0 (.getCharCount st) true))) (defn remove-style-listener [^REPLView rv] ;(log (str "removing ansi listener for " (.getPartName rv))) (let [^StyledText st (.logPanel rv) sl (get-in state [:repls rv :listener])] (when sl (if-not (. st (isDisposed)) (.removeLineStyleListener st sl)) (alter-var-root #'state update-in [:repls rv] dissoc :listener) (log (str "removed listener for " (.getPartName rv))) (swt/doasync (redraw st))))) (defn add-style-listener [^REPLView rv] (let [^StyledText st (.logPanel rv)] (when (get-in state [:repls rv :listener]) (log (str "replacing existing listener for " (.getPartName rv))) (remove-style-listener rv)) (let [sl (make-ansi-listener)] (log (str "adding listener to " (.getPartName rv))) (.removeLineStyleListener st rv) (.addLineStyleListener st sl) ;; let's move the default REPL style listener last so that it can ;; take precedence over AnsiStyleListener (especially useful because ;; AnsiStyleListener colorize with the same foreground colors all lines, ;; even those that should not be touched) (.addLineStyleListener st rv) (alter-var-root #'state assoc-in [:repls rv :listener] sl) (swt/doasync (redraw st))))) ;; REPL Toolbar toggle button (when ansi-console-bundle (def icon-enabled-descriptor (ImageDescriptor/createFromURL (.getEntry ansi-console-bundle "/icons/ansiconsole.gif")))) (def ansi-action-id "toggle-ansi-support") (defn remove-toolbar-action [^REPLView rv] (when-let [action (get-in state [:repls rv :action])] (.. rv getViewSite getActionBars getToolBarManager (remove ansi-action-id)) (alter-var-root #'state update-in [:repls rv] dissoc :action) (log (str "removed toolbar button from " (.getPartName rv))))) (defn update-repl-ansi-state [^REPLView rv] (if (.isChecked (get-in state [:repls rv :action])) (add-style-listener rv) (remove-style-listener rv))) (defn add-toolbar-action [^REPLView rv] (when (get-in state [:repls rv :action]) (log (str "replacing toolbar button on " (.getPartName rv))) (remove-toolbar-action rv)) (let [action (proxy [Action] ["Process ANSI escape code" Action/AS_CHECK_BOX] (run [] (update-repl-ansi-state rv)))] (doto action (.setToolTipText "Process ANSI escape code") (.setImageDescriptor icon-enabled-descriptor) (.setId ansi-action-id) (.setChecked true)) ;; we start with Ansi REPL enabled (log (str "adding toolbar button on " (.getPartName rv))) (.. rv getViewSite getActionBars getToolBarManager (add action)) (.. rv getViewSite getActionBars getToolBarManager (update true)) ;; In a proxy there's no easy way to emulate the self-reference (this) ;; so we keep a record of the action for a given repl. (alter-var-root #'state assoc-in [:repls rv :action] action) (update-repl-ansi-state rv))) ;; Install/uninstall on a given REPL (defn install-on [^REPLView rv] (if (bundle/available? ansi-console-bundle) (if (installed?) (add-toolbar-action rv) (log (str "can't install on " (.getPartName rv) ":\n" (status-msg)))) (log (str "can't install on " (.getPartName rv) ":\n" (status-msg))))) (defn uninstall-from [^REPLView rv] (remove-toolbar-action rv) (remove-style-listener rv) (alter-var-root #'state update-in [:repls] dissoc rv)) ;; PartListener functions ;; Note: SWT listener methods are invoked by the UI thread. (defn make-part-listener [] ;(log "creating part listener") (reify IPartListener (partOpened [this p] (if (instance? REPLView p) (install-on p))) (partClosed [this p] (if (instance? REPLView p) (uninstall-from p))) (partActivated [this p] ()) (partBroughtToTop [this p] ()) (partDeactivated [this p] ()))) (defn remove-part-listener [] ;(log (str "removing part listener")) (when-let [^IPartListener pl (:part-listener state)] (log (str "removing part listener " pl)) (.. PlatformUI getWorkbench getActiveWorkbenchWindow getPartService (removePartListener pl)) (alter-var-root #'state dissoc :part-listener))) (defn add-part-listener [] (if (bundle/available? ansi-console-bundle) (do (remove-part-listener) ;; adding part listener (let [^IPartListener pl (make-part-listener)] (log (str "adding part listener")) (.. PlatformUI getWorkbench getActiveWorkbenchWindow getPartService (addPartListener pl)) (alter-var-root #'state assoc :part-listener pl))) (log "Cannot add part listener: ANSI Console plugin no longer available?"))) ;; Install/Uninstall ansi support (defn install [] (log "installing ANSI REPL") (when (and (bundle/available? ansi-console-bundle) (not (installed?))) ;; install a part listener for handling future REPLs (add-part-listener) (flag-installed) ;; handle existing REPLs (->> (CCWPlugin/getREPLViews) ;(map #(do (log (str "found " (.getPartName %))) %)) (filter #(if-let [rvl (.getLaunch %)] (not (.isTerminated rvl)))) (map #(install-on %)) (doall))) (log (status-msg))) (defn uninstall [] (log "disabling ANSI REPL") ;; install a part listener for handling future REPLs (remove-part-listener) ;; handle existing REPLs (doall (map #(remove-style-listener %) (keys (:repls state)))) ;; mark as uninstalled (flag-uninstalled) (log (status-msg)) ) ;; Define eclipse key binding (defn display-status [context] (eclipse/info-dialog "ANSI REPL" (status-msg))) (defcommand ansi-repl-status "ANSI REPL: display status") (defhandler ansi-repl-status display-status) (defkeybinding ansi-repl-status "Alt+U A") ;; Install upon starting the plugin (swt/doasync (install))
true
;; Licensed under The MIT License (MIT) ;; http://opensource.org/licenses/MIT ;; Copyright (c) 2014 PI:NAME:<NAME>END_PI ;; CounterClockWiwe plugin for adding ANSI escape code support to REPLs. ;; To enable its functionality install the ANSI console plugin found at: ;; https://github.com/mihnita/ansi-econsole ;; See CCW user documentation for details on plugin installation: ;; http://doc.ccw-ide.org/documentation.html#_user_plugins ;; See also: ;; https://code.google.com/p/counterclockwise/issues/detail?id=624 ;; https://code.google.com/p/counterclockwise/issues/detail?id=629 ;; ;; Initial version by PI:NAME:<NAME>END_PI at https://gist.github.com/fmjrey/9889500 ;; Fixes for further versions of Counterclockwise by PI:NAME:<NAME>END_PIurent Petit ;; available at https://github.com/laurentpetit/ccw-plugin-ansi-repl (ns ansi-repl (:require [ccw.bundle :as bundle] [ccw.core.factories :as factories] [ccw.e4.dsl :refer :all] [ccw.eclipse :as eclipse] [ccw.swt :as swt]) (:import ccw.CCWPlugin [ccw.repl REPLView] org.eclipse.jface.action.Action org.eclipse.jface.resource.ImageDescriptor [org.eclipse.ui PlatformUI IPartListener] [org.eclipse.swt.custom StyledText ST LineStyleListener])) ;; Test CCW compatibility with the plugin (when-not (.isAssignableFrom LineStyleListener REPLView) (throw (RuntimeException. "Incompatible version of Counterclockwise with ansi-repl user plugin"))) ;; logging to eclipse log (defn log [& m] ;; Comment out the line below when logging is no longer necessary. ;; Logging is useful for developing, but can be annoying because ;; it brings to the foreground the Error Log view. ;(CCWPlugin/log (str "ANSI-REPL: " (apply str m))) ) ;; The following methods use reflection otherwise clojure ;; compilation will fail without the ansi console plugin. (def ansi-console-bundle (bundle/bundle "net.mihai-nita.ansicon.plugin")) (declare make-ansi-listener) (if (bundle/available? ansi-console-bundle) (def make-ansi-listener (factories/make-factory ansi-console-bundle "mnita.ansiconsole.participants.AnsiConsoleStyleListener" []))) ;; Plugin state that survives plugin reload. ;; Used to make sure we're not adding new listeners when one ;; is already present, otherwise reloading the plugin keeps ;; adding new listeners. ;; No need for an atom if only accessed from the UI thread. (defonce state {:installed false :part-listener nil :repls {}}) (defn installed? [] (:installed state)) (defn flag-installed [] (alter-var-root #'state assoc :installed true)) (defn flag-uninstalled [] (alter-var-root #'state assoc :installed false)) (defn repl-names-where-installed [] "Returns a possibly empty list of REPL names where ANSI support is installed." (doall (map #(.getPartName %) (keys (:repls state))))) (defn status-msg [] (if (bundle/available? ansi-console-bundle) (if (installed?) (if-let [rn (seq (repl-names-where-installed))] (str "ANSI support installed on these REPLs: \n" (apply str (map #(str " - " % \newline) rn))) (str "ANSI support installed, but there's no REPL.")) "ANSI support disabled.") (if ansi-console-bundle (str "ANSI support disabled: ANSI Console bundle in state " (.getState ansi-console-bundle)) "ANSI support disabled: ANSI Console bundle not found!"))) ;; StyleListener functions (defn redraw [^StyledText st] (if-not (. st (isDisposed)) (.redrawRange st 0 (.getCharCount st) true))) (defn remove-style-listener [^REPLView rv] ;(log (str "removing ansi listener for " (.getPartName rv))) (let [^StyledText st (.logPanel rv) sl (get-in state [:repls rv :listener])] (when sl (if-not (. st (isDisposed)) (.removeLineStyleListener st sl)) (alter-var-root #'state update-in [:repls rv] dissoc :listener) (log (str "removed listener for " (.getPartName rv))) (swt/doasync (redraw st))))) (defn add-style-listener [^REPLView rv] (let [^StyledText st (.logPanel rv)] (when (get-in state [:repls rv :listener]) (log (str "replacing existing listener for " (.getPartName rv))) (remove-style-listener rv)) (let [sl (make-ansi-listener)] (log (str "adding listener to " (.getPartName rv))) (.removeLineStyleListener st rv) (.addLineStyleListener st sl) ;; let's move the default REPL style listener last so that it can ;; take precedence over AnsiStyleListener (especially useful because ;; AnsiStyleListener colorize with the same foreground colors all lines, ;; even those that should not be touched) (.addLineStyleListener st rv) (alter-var-root #'state assoc-in [:repls rv :listener] sl) (swt/doasync (redraw st))))) ;; REPL Toolbar toggle button (when ansi-console-bundle (def icon-enabled-descriptor (ImageDescriptor/createFromURL (.getEntry ansi-console-bundle "/icons/ansiconsole.gif")))) (def ansi-action-id "toggle-ansi-support") (defn remove-toolbar-action [^REPLView rv] (when-let [action (get-in state [:repls rv :action])] (.. rv getViewSite getActionBars getToolBarManager (remove ansi-action-id)) (alter-var-root #'state update-in [:repls rv] dissoc :action) (log (str "removed toolbar button from " (.getPartName rv))))) (defn update-repl-ansi-state [^REPLView rv] (if (.isChecked (get-in state [:repls rv :action])) (add-style-listener rv) (remove-style-listener rv))) (defn add-toolbar-action [^REPLView rv] (when (get-in state [:repls rv :action]) (log (str "replacing toolbar button on " (.getPartName rv))) (remove-toolbar-action rv)) (let [action (proxy [Action] ["Process ANSI escape code" Action/AS_CHECK_BOX] (run [] (update-repl-ansi-state rv)))] (doto action (.setToolTipText "Process ANSI escape code") (.setImageDescriptor icon-enabled-descriptor) (.setId ansi-action-id) (.setChecked true)) ;; we start with Ansi REPL enabled (log (str "adding toolbar button on " (.getPartName rv))) (.. rv getViewSite getActionBars getToolBarManager (add action)) (.. rv getViewSite getActionBars getToolBarManager (update true)) ;; In a proxy there's no easy way to emulate the self-reference (this) ;; so we keep a record of the action for a given repl. (alter-var-root #'state assoc-in [:repls rv :action] action) (update-repl-ansi-state rv))) ;; Install/uninstall on a given REPL (defn install-on [^REPLView rv] (if (bundle/available? ansi-console-bundle) (if (installed?) (add-toolbar-action rv) (log (str "can't install on " (.getPartName rv) ":\n" (status-msg)))) (log (str "can't install on " (.getPartName rv) ":\n" (status-msg))))) (defn uninstall-from [^REPLView rv] (remove-toolbar-action rv) (remove-style-listener rv) (alter-var-root #'state update-in [:repls] dissoc rv)) ;; PartListener functions ;; Note: SWT listener methods are invoked by the UI thread. (defn make-part-listener [] ;(log "creating part listener") (reify IPartListener (partOpened [this p] (if (instance? REPLView p) (install-on p))) (partClosed [this p] (if (instance? REPLView p) (uninstall-from p))) (partActivated [this p] ()) (partBroughtToTop [this p] ()) (partDeactivated [this p] ()))) (defn remove-part-listener [] ;(log (str "removing part listener")) (when-let [^IPartListener pl (:part-listener state)] (log (str "removing part listener " pl)) (.. PlatformUI getWorkbench getActiveWorkbenchWindow getPartService (removePartListener pl)) (alter-var-root #'state dissoc :part-listener))) (defn add-part-listener [] (if (bundle/available? ansi-console-bundle) (do (remove-part-listener) ;; adding part listener (let [^IPartListener pl (make-part-listener)] (log (str "adding part listener")) (.. PlatformUI getWorkbench getActiveWorkbenchWindow getPartService (addPartListener pl)) (alter-var-root #'state assoc :part-listener pl))) (log "Cannot add part listener: ANSI Console plugin no longer available?"))) ;; Install/Uninstall ansi support (defn install [] (log "installing ANSI REPL") (when (and (bundle/available? ansi-console-bundle) (not (installed?))) ;; install a part listener for handling future REPLs (add-part-listener) (flag-installed) ;; handle existing REPLs (->> (CCWPlugin/getREPLViews) ;(map #(do (log (str "found " (.getPartName %))) %)) (filter #(if-let [rvl (.getLaunch %)] (not (.isTerminated rvl)))) (map #(install-on %)) (doall))) (log (status-msg))) (defn uninstall [] (log "disabling ANSI REPL") ;; install a part listener for handling future REPLs (remove-part-listener) ;; handle existing REPLs (doall (map #(remove-style-listener %) (keys (:repls state)))) ;; mark as uninstalled (flag-uninstalled) (log (status-msg)) ) ;; Define eclipse key binding (defn display-status [context] (eclipse/info-dialog "ANSI REPL" (status-msg))) (defcommand ansi-repl-status "ANSI REPL: display status") (defhandler ansi-repl-status display-status) (defkeybinding ansi-repl-status "Alt+U A") ;; Install upon starting the plugin (swt/doasync (install))
[ { "context": "/the-state-of-css.html\r\n; https://speakerdeck.com/vjeux/react-css-in-js\r\n\r\n; Unity file format:\r\n; https:", "end": 132, "score": 0.9996703267097473, "start": 127, "tag": "USERNAME", "value": "vjeux" }, { "context": "/usd/docs/USD-Glossary.html\r\n; https://codepen.io/MarcRay/pen/vmJBn\r\n\r\n\r\noperator type:string all {\r\n fn", "end": 524, "score": 0.9996395707130432, "start": 517, "tag": "USERNAME", "value": "MarcRay" }, { "context": ".com/purecss@1.0.0/build/pure-min.css\" integrity=\"sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w\" crossorigin=\"anonymous\">' true)\r\n\r\n wr.cr", "end": 6791, "score": 0.9997054934501648, "start": 6720, "tag": "KEY", "value": "sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w" }, { "context": "onfig & dependencies:\r\n\t\t\t// - https://github.com/hakimel/reveal.js#configuration\r\n\t\t\t// - https://github.c", "end": 18426, "score": 0.9993112087249756, "start": 18419, "tag": "USERNAME", "value": "hakimel" }, { "context": "veal.js#configuration\r\n\t\t\t// - https://github.com/hakimel/reveal.js#dependencies\r\n\t\t\tReveal.initialize({\r\n ", "end": 18486, "score": 0.9994743466377258, "start": 18479, "tag": "USERNAME", "value": "hakimel" } ]
compiler/simplePlugin.clj
terotests/Ranger
6
Import "ng_Compiler.clj" ; http://ryanogles.by/css/javascript/2017/05/25/the-state-of-css.html ; https://speakerdeck.com/vjeux/react-css-in-js ; Unity file format: ; https://docs.unity3d.com/Manual/FormatDescription.html ; --> describing a database ; ---> fields, names, types etc. ; --> describe a wordpress site and publish it to cloud ; --> how to do that ? ; USD ; https://graphics.pixar.com/usd/docs/index.html ; https://graphics.pixar.com/usd/docs/USD-Glossary.html ; https://codepen.io/MarcRay/pen/vmJBn operator type:string all { fn remove_trailing:string (ch:string) { def parts (strsplit self ch) if( ( array_length parts ) == 1 ) { return self } removeLast parts return (join parts ch) } } class Plugin { def html_mode "" def vendor_prefixes:[string] ([] "-moz-" "-webkit-" "-o-" "-ms-") def prefixable:[string] ([] "borderRadius" "border-radius" ) def transform:[string] ([] "borderRadius" "border-radius" ) fn features:[string] () { return ([] "import_loader" "postprocess" "random" "generate_ast") } ; -- import command can be used by plugins to insert custom code and features fn import_loader:Any ( node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { ; Import "somelib" def sc (node.getSecond()) if(sc.string_value == "jabba") { return ' class jabba { fn jabbaTester() { } } ' } return false } fn generate_ast (root:CodeNode ctx:RangerAppWriterContext orig_wr:CodeWriter) { print "-------------------------------------------------------" print "--> Generate AST was called in plugin" ctx.pushAst( ` operator type:void all { fn alert (str:string) { print "ALERT!!! " + str } } class inserted_class { static fn foo () { print "inserted_class does exist!!!" } } ` root orig_wr) } fn doesRequirePrefix:boolean ( cssName:string) { return ( (indexOf prefixable cssName) >= 0 ) } fn transformName:string ( cssName:string) { def i (indexOf transform cssName) if( (i >= 0 ) && (0 == (i % 2)) ) { return (itemAt transform (i + 1)) } return cssName } fn applyCss (cssName:string cssValue:string ctx:RangerAppWriterContext wr:CodeWriter) { if( (this.doesRequirePrefix(cssName))) { vendor_prefixes.forEach({ wr.out( item + (this.transformName(cssName)) + ': ' , false ) wr.out(cssValue + ";" , true) }) } { wr.out( (this.transformName(cssName)) + ': ' , false ) wr.out(cssValue + ";" , true) } } ; can be written either as color or 'color' fn vrefOrString:string ( node:CodeNode ) { if( (strlen node.vref) > 0 ) { return node.vref } return node.string_value + (node.value_type) } fn nodeOrigValue:string ( node:CodeNode ) { if(node.value_type == RangerNodeType.VRef) { return node.vref } if(node.value_type == RangerNodeType.Integer) { return ("" + node.int_value) } if(node.value_type == RangerNodeType.Double) { return ("" + node.double_value) } return (node.getParsedString()) } fn collectValuesFromLine:string (start_index:int parentNode:CodeNode) { def res "" def cnt 0 def last_numeric false def unit_values:[string] ([] "px" "dp" "em" "s") for parentNode.children ch:CodeNode i { if( i >= start_index ) { if( (false == last_numeric) && (cnt > 0 ) ) { res = res + " " } def this_val (remove_trailing (trim (this.nodeOrigValue(ch))) ";" ) if last_numeric { if( (indexOf unit_values this_val) < 0) { res = res + " " } } res = res + (this.nodeOrigValue(ch)) cnt = cnt + 1 last_numeric = (ch.value_type == RangerNodeType.Integer || ch.value_type == RangerNodeType.Double) } } return res } fn walkStyleProps (node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { node.children.forEach({ def propName (item.getFirst()) def propValue (item.getSecond()) def theValue (this.collectValuesFromLine( 1 item)) def parts (strsplit theValue ";") theValue = (itemAt parts 0) this.applyCss( (this.vrefOrString(propName)) theValue ctx wr) }) } fn walkQueryBody (node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { node.children.forEach({ if( (array_length item.children ) == 0) { return } def propName (item.getFirst()) def name "" if( (array_length item.children ) == 1) { print " ---> fetching property " + propName.vref return } if( (array_length item.children ) == 2) { def propConnected (item.getSecond()) print "fetching links without filtering " + propName.vref this.walkQueryBody( (propConnected) ctx wr) return } if( (array_length item.children ) == 3) { def filters (item.getSecond()) def propConnected (item.getThird()) print "fetching links with filtering " + propName.vref filters.children.forEach({ print " ^^ filter: " + item.vref }) this.walkQueryBody( (propConnected) ctx wr) return } }) } fn createPureCSSPage (root:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { def hasMenu (root.children.contains({ return (item.isFirstVref("menu")) })) wr.out('<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="side-menu.css"></link> <link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/pure-min.css" integrity="sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w" crossorigin="anonymous">' true) wr.createTag('head') wr.out(' </head> <body> <div id="layout">' true) if hasMenu { wr.out(` <!-- Menu toggle --> <a href="#menu" id="menuLink" class="menu-link"> <!-- Hamburger icon --> <span></span> </a> <div id="menu"> <div class="pure-menu"> ` true) wr.createTag('menu') wr.out(' </div> </div>' true) } wr.out(' <div id="main"> <div class="content"> ' true) wr.createTag('content') wr.out(' </div> </div> <script src="/ui.js"></script> </body> </html>' false) } fn WalkHTML (node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { if(node.is_block_node) { node.children.forEach({ this.WalkHTML( item ctx wr) }) return } if(node.value_type == RangerNodeType.String) { wr.raw(node.string_value false) return } if(node.value_type == RangerNodeType.Integer) { wr.out( ('' + node.int_value) false) return } if(node.value_type == RangerNodeType.Double) { wr.out( (node.getParsedString()) false) return } if(node.value_type == RangerNodeType.Boolean) { if node.boolean_value { wr.out( 'true' false) } { wr.out( 'false' false) } return } if(node.value_type == RangerNodeType.VRef) { wr.out((node.vref + " ") false) return } if(node.expression) { def fc (node.getFirst()) def cmd (itemAt fc.ns 0 ) def class_string "" def ns_list (clone fc.ns) def bb false ns_list = (ns_list.filter({ if(index > 0 ) { bb = true } return (index > 0) })) class_string = (join ns_list " ") switch cmd { case "#" { cmd = "h1" } case "##" { cmd = "h2" } case "###" { cmd = "h3" } case "slide" { cmd = "section" } case "quote" { cmd = "blockquote" } } def simpleTags ([] "p" "b" "i" "u" "h1" "h2" "h3" "h4" "h5" "ul" "li" "ol" "section" "blockquote") def effects([] "fade-in" "fade-out" "zoom-in" "zoom-out" ) if( (indexOf simpleTags cmd) >= 0 ) { wr.out('<' + cmd , false) effects.forEach({ if( (indexOf fc.ns item) >= 0 ) { wr.out(' data-transition="' + item + '" ' , false) } }) if(node.hasStringProperty("class")) { wr.out(' class="' + class_string , false) wr.out( (node.getStringProperty('class')) false ) wr.out('" ' false) } { wr.out(' class="' + class_string + '" ' , false) } if(node.hasStringProperty("id")) { wr.out(' id="' false) wr.out( (node.getStringProperty('id')) false ) wr.out('" ' false) } wr.out( '>' , true) wr.indent(1) node.children.forEach({ if(index > 0 ) { this.WalkHTML( item ctx wr) } }) wr.newline() wr.indent(-1) wr.out('</' + cmd + '>' , true) return } switch cmd { case "code" { def linkRef (node.getSecond()) def tags "" if(node.hasBooleanProperty("noescape")) { tags = tags + 'data-noescape' } wr.out('<pre' false) wr.out(' class="' + class_string + '" ' , false) wr.out('><code ' + tags + '>' , false) this.WalkHTML( linkRef ctx wr ) wr.out('</code></pre>' true) } case "menutitle" { def linkRef (node.getSecond()) wr.out('<a class="pure-menu-heading" href="#">' false) this.WalkHTML( linkRef ctx wr ) wr.out('</a>' true) } case "menuitem" { def linkRef (node.getSecond()) wr.out('<li class="pure-menu-item"><a class="pure-menu-link" href="' false) this.WalkHTML( linkRef ctx wr ) wr.out('">' false) node.children.forEach({ if(index > 1 ) { this.WalkHTML( item ctx wr) } }) wr.out('</a></li>' true) } case "submenu" { def title (node.getSecond()) wr.out('<ul class="pure-menu-children">' false) node.children.forEach({ if(index > 0 ) { this.WalkHTML( item ctx wr) } }) wr.out('</ul>' true) } case "menulist" { def title (node.getSecond()) wr.out('<ul class="pure-menu-list">' false) node.children.forEach({ if(index > 0 ) { this.WalkHTML( item ctx wr) } }) wr.out('</ul>' true) } case "menu" { try { def menuWr (wr.getTag('menu')) def menuBody (node.getSecond()) this.WalkHTML( menuBody ctx menuWr ) } { } } case "a" { ; <a href="../html-link.htm#generator"> wr.out('<a href="' , false) def link (node.getSecond()) this.WalkHTML(link ctx wr) wr.out('" >' false) node.children.forEach({ if(index > 1 ) { this.WalkHTML( item ctx wr) } }) wr.out('</a>' false) } case "pre"{ def title (node.getSecond()) wr.out('<pre class="code">' false) node.children.forEach({ if(index > 0 ) { this.WalkHTML( item ctx wr) } }) wr.out('</pre>' true) } case "button"{ def title (node.getSecond()) wr.out('<button class="pure-button">' false) this.WalkHTML( title ctx wr ) wr.out('</button>' true) } case "thead" { wr.out('<thead>' false) wr.out('<tr>' true) wr.indent(1) node.children.forEach({ if(index > 0 ) { wr.out('<th>' false) this.WalkHTML( item ctx wr) wr.out('</th>' false) } }) wr.newline() wr.indent(-1) wr.out('</tr>' true) wr.out('</thead>' false) } case "tr" { def pIndex 1 try { if(!null? node.parent) { pIndex = (indexOf node.parent.children node) } } { } if( (pIndex % 2) == 0) { wr.out('<tr class="pure-table-odd">' true) } { wr.out('<tr>' true) } wr.indent(1) node.children.forEach({ if(index > 0 ) { wr.out('<td>' false) this.WalkHTML( item ctx wr) wr.out('</td>' false) } }) wr.newline() wr.indent(-1) wr.out('</tr>' true) } case "table" { wr.out('<table class="pure-table ' + class_string + '">' , false) wr.indent(1) def body (node.getSecond()) body.children.forEach({ this.WalkHTML(item ctx wr) }) wr.indent(-1) wr.out('</table>' true) } default { node.children.forEach({ this.WalkHTML( item ctx wr) }) } } } } fn initRevealPresentation(root:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { def titleNode (root.getSecond()) wr.out(`<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>` + titleNode.string_value + `</title> <link rel="stylesheet" href="css/reveal.css"> <link rel="stylesheet" href="css/theme/black.css"> <!-- Theme used for syntax highlighting of code --> <link rel="stylesheet" href="lib/css/zenburn.css"> <!-- Printing and PDF exports --> <script> var link = document.createElement( 'link' ); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css'; document.getElementsByTagName( 'head' )[0].appendChild( link ); </script> <style> mark { background-color:#ff3322;} .hljs { background: none; } </style> </head> <body> <div class="reveal"> <div class="slides"> ` , true) wr.createTag("slides") wr.out(` </div> </div> <script src="lib/js/head.min.js"></script> <script src="js/reveal.js"></script> <script> // More info about config & dependencies: // - https://github.com/hakimel/reveal.js#configuration // - https://github.com/hakimel/reveal.js#dependencies Reveal.initialize({ history:true, dependencies: [ { src: 'plugin/markdown/marked.js' }, { src: 'plugin/markdown/markdown.js' }, { src: 'plugin/notes/notes.js', async: true }, { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } } ] }); </script> </body> </html>` false) } fn writeTypeDef (item:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { if(item.hasFlag("optional")) { wr.out('<optional>' false) } switch item.value_type { case RangerNodeType.Array { wr.out("[" + item.array_type + "]" , false) } case RangerNodeType.Hash { wr.out("[" + item.key_type + ':' + item.array_type + "]" , false) } case RangerNodeType.ExpressionType { wr.out('(fn:' false) try { def rv:CodeNode (itemAt item.expression_value.children 0) def args:CodeNode (itemAt item.expression_value.children 1) this.writeTypeDef( rv ctx wr) wr.out( ' (' false) args.children.forEach({ if( index > 0 ) { wr.out(', ' false) } wr.out( item.vref false) wr.out(': ' false) this.writeTypeDef( item ctx wr) }) wr.out(')' false) } { } wr.out(')' false) } default { if( (strlen item.type_name ) > 0 ) { wr.out( ("" + item.type_name) false ) } } } } fn writeArgDefs (node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { node.children.forEach({ wr.out('tr ' false) wr.out( "`" + item.vref + "`" , false) wr.out("`" false) this.writeTypeDef(item ctx wr) wr.out("`" true) }) } fn create_op_slides (root:CodeNode ctx:RangerAppWriterContext orig_wr:CodeWriter) { def wr (new CodeWriter) wr.raw(` plugin.slides @noinfix(true) { presentation "Operators " "operators_slides.html" { ` true) def allOps (ctx.getAllOperators()) def statements (allOps.filter({ def is_map_array false if(item.firstArg) { is_map_array = ( (item.firstArg.value_type == RangerNodeType.Array) || (item.firstArg.value_type == RangerNodeType.Hash) ) } if( (indexOf item.name "if_") == 0 ) { return false } return ( (item.nameNode.type_name == "void") && (false == is_map_array) ) })) statements = (statements.groupBy({ return item.name })) statements.forEach({ def args:CodeNode (item.node.getThird()) wr.out(`slide {` true) wr.indent(1) wr.out('h1 ' + item.name , true) if(item.node.hasStringProperty('doc')) { wr.out('p `' false) wr.out((item.node.getStringProperty('doc')) false) wr.out('`' true) } wr.out('table { thead "Argument" "type" ' true) wr.indent(1) this.writeArgDefs(args ctx wr) wr.indent(-1) wr.out('}' true) try { wr.out('p ' false) def temps (itemAt item.node.children 3) temps.children.forEach({ if(item.isFirstVref('templates')) { def templateList (item.getSecond()) templateList.children.forEach({ def fc (item.getFirst()) def code (item.getSecond()) ; es 6 wr.out('(b ' + fc.vref + ') ' , false) }) } }) wr.newline() } { } wr.indent(-1) wr.out('}' true) }) wr.out(` } } ` false) ctx.pushCode((wr.getCode()) orig_wr) } fn postprocess (root:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { print "simplePlugin was called for postprosessing" ctx.definedClasses.forEach({ print " --> " + index }) try { print "--> starting" this.create_op_slides( root ctx wr ) print " ****************** CSS plugin running ***************************" def nodes (ctx.getPluginNodes("css")) def cssFile "style.css" if(ctx.hasCompilerSetting('css')) { cssFile = (ctx.getCompilerSetting("css")) } def cssWr (wr.getFileWriter('' cssFile) ) nodes.forEach({ def block (item.getSecond()) block.children.forEach({ ; print (item.getCode()) def styleName (item.getFirst()) cssWr.out( ( (this.vrefOrString(styleName)) + ' { ' ) true) cssWr.indent(1) this.walkStyleProps( (item.getSecond()) ctx cssWr ) cssWr.indent(-1) cssWr.out( '}' true) }) }) def nodes (ctx.getPluginNodes("html")) nodes.forEach({ def block (item.getSecond()) block.children.forEach({ if(item.isFirstVref("page")) { def nameNode (item.getSecond()) def pageWriter (wr.getFileWriter("." (nameNode.string_value + ".html"))) def content (item.getThird()) this.createPureCSSPage( content ctx pageWriter ) def wr (pageWriter.getTag("content")) content.children.forEach({ try { this.WalkHTML(item ctx wr) } { } }) } }) }) def nodes (ctx.getPluginNodes("graphql")) nodes.forEach({ def block (item.getSecond()) block.children.forEach({ if(item.isFirstVref("query")) { def nameNode (item.getSecond()) print "-------------------------------------------------------------" print " GraphQL " + nameNode.string_value def args (item.getThird()) print "Arguments : " + (args.getCode()) def qBody (itemAt item.children 3) print "Query body " + (qBody.getCode()) this.walkQueryBody( qBody ctx wr) print "-------------------------------------------------------------" } }) }) def nodes (ctx.getPluginNodes("slides")) nodes.forEach({ def block (item.getSecond()) block.children.forEach({ if(item.isFirstVref("presentation")) { try { def nameNode (item.getSecond()) if( (strlen nameNode.string_value ) == 0 ) { ctx.addError(item "Please give name to the presentation") return } def fileNode (item.getThird()) if( (strlen fileNode.string_value ) == 0 ) { ctx.addError(item "Please output file give name to the presentation") return } def presis (itemAt item.children 3) def pageWriter (wr.getFileWriter("." (fileNode.string_value ))) this.initRevealPresentation( item ctx pageWriter ) def slideWr (pageWriter.getTag("slides")) this.WalkHTML( presis ctx slideWr ) ; --- create also a static page --- def nameNode (item.getSecond()) def pageWriter (wr.getFileWriter("." ("static_" + fileNode.string_value))) this.createPureCSSPage( item ctx pageWriter ) def wr (pageWriter.getTag("content")) this.WalkHTML(presis ctx wr) } { ctx.addError( item "Invalid presentation") } } }) }) } { print (error_msg) } } }
46620
Import "ng_Compiler.clj" ; http://ryanogles.by/css/javascript/2017/05/25/the-state-of-css.html ; https://speakerdeck.com/vjeux/react-css-in-js ; Unity file format: ; https://docs.unity3d.com/Manual/FormatDescription.html ; --> describing a database ; ---> fields, names, types etc. ; --> describe a wordpress site and publish it to cloud ; --> how to do that ? ; USD ; https://graphics.pixar.com/usd/docs/index.html ; https://graphics.pixar.com/usd/docs/USD-Glossary.html ; https://codepen.io/MarcRay/pen/vmJBn operator type:string all { fn remove_trailing:string (ch:string) { def parts (strsplit self ch) if( ( array_length parts ) == 1 ) { return self } removeLast parts return (join parts ch) } } class Plugin { def html_mode "" def vendor_prefixes:[string] ([] "-moz-" "-webkit-" "-o-" "-ms-") def prefixable:[string] ([] "borderRadius" "border-radius" ) def transform:[string] ([] "borderRadius" "border-radius" ) fn features:[string] () { return ([] "import_loader" "postprocess" "random" "generate_ast") } ; -- import command can be used by plugins to insert custom code and features fn import_loader:Any ( node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { ; Import "somelib" def sc (node.getSecond()) if(sc.string_value == "jabba") { return ' class jabba { fn jabbaTester() { } } ' } return false } fn generate_ast (root:CodeNode ctx:RangerAppWriterContext orig_wr:CodeWriter) { print "-------------------------------------------------------" print "--> Generate AST was called in plugin" ctx.pushAst( ` operator type:void all { fn alert (str:string) { print "ALERT!!! " + str } } class inserted_class { static fn foo () { print "inserted_class does exist!!!" } } ` root orig_wr) } fn doesRequirePrefix:boolean ( cssName:string) { return ( (indexOf prefixable cssName) >= 0 ) } fn transformName:string ( cssName:string) { def i (indexOf transform cssName) if( (i >= 0 ) && (0 == (i % 2)) ) { return (itemAt transform (i + 1)) } return cssName } fn applyCss (cssName:string cssValue:string ctx:RangerAppWriterContext wr:CodeWriter) { if( (this.doesRequirePrefix(cssName))) { vendor_prefixes.forEach({ wr.out( item + (this.transformName(cssName)) + ': ' , false ) wr.out(cssValue + ";" , true) }) } { wr.out( (this.transformName(cssName)) + ': ' , false ) wr.out(cssValue + ";" , true) } } ; can be written either as color or 'color' fn vrefOrString:string ( node:CodeNode ) { if( (strlen node.vref) > 0 ) { return node.vref } return node.string_value + (node.value_type) } fn nodeOrigValue:string ( node:CodeNode ) { if(node.value_type == RangerNodeType.VRef) { return node.vref } if(node.value_type == RangerNodeType.Integer) { return ("" + node.int_value) } if(node.value_type == RangerNodeType.Double) { return ("" + node.double_value) } return (node.getParsedString()) } fn collectValuesFromLine:string (start_index:int parentNode:CodeNode) { def res "" def cnt 0 def last_numeric false def unit_values:[string] ([] "px" "dp" "em" "s") for parentNode.children ch:CodeNode i { if( i >= start_index ) { if( (false == last_numeric) && (cnt > 0 ) ) { res = res + " " } def this_val (remove_trailing (trim (this.nodeOrigValue(ch))) ";" ) if last_numeric { if( (indexOf unit_values this_val) < 0) { res = res + " " } } res = res + (this.nodeOrigValue(ch)) cnt = cnt + 1 last_numeric = (ch.value_type == RangerNodeType.Integer || ch.value_type == RangerNodeType.Double) } } return res } fn walkStyleProps (node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { node.children.forEach({ def propName (item.getFirst()) def propValue (item.getSecond()) def theValue (this.collectValuesFromLine( 1 item)) def parts (strsplit theValue ";") theValue = (itemAt parts 0) this.applyCss( (this.vrefOrString(propName)) theValue ctx wr) }) } fn walkQueryBody (node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { node.children.forEach({ if( (array_length item.children ) == 0) { return } def propName (item.getFirst()) def name "" if( (array_length item.children ) == 1) { print " ---> fetching property " + propName.vref return } if( (array_length item.children ) == 2) { def propConnected (item.getSecond()) print "fetching links without filtering " + propName.vref this.walkQueryBody( (propConnected) ctx wr) return } if( (array_length item.children ) == 3) { def filters (item.getSecond()) def propConnected (item.getThird()) print "fetching links with filtering " + propName.vref filters.children.forEach({ print " ^^ filter: " + item.vref }) this.walkQueryBody( (propConnected) ctx wr) return } }) } fn createPureCSSPage (root:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { def hasMenu (root.children.contains({ return (item.isFirstVref("menu")) })) wr.out('<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="side-menu.css"></link> <link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/pure-min.css" integrity="<KEY>" crossorigin="anonymous">' true) wr.createTag('head') wr.out(' </head> <body> <div id="layout">' true) if hasMenu { wr.out(` <!-- Menu toggle --> <a href="#menu" id="menuLink" class="menu-link"> <!-- Hamburger icon --> <span></span> </a> <div id="menu"> <div class="pure-menu"> ` true) wr.createTag('menu') wr.out(' </div> </div>' true) } wr.out(' <div id="main"> <div class="content"> ' true) wr.createTag('content') wr.out(' </div> </div> <script src="/ui.js"></script> </body> </html>' false) } fn WalkHTML (node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { if(node.is_block_node) { node.children.forEach({ this.WalkHTML( item ctx wr) }) return } if(node.value_type == RangerNodeType.String) { wr.raw(node.string_value false) return } if(node.value_type == RangerNodeType.Integer) { wr.out( ('' + node.int_value) false) return } if(node.value_type == RangerNodeType.Double) { wr.out( (node.getParsedString()) false) return } if(node.value_type == RangerNodeType.Boolean) { if node.boolean_value { wr.out( 'true' false) } { wr.out( 'false' false) } return } if(node.value_type == RangerNodeType.VRef) { wr.out((node.vref + " ") false) return } if(node.expression) { def fc (node.getFirst()) def cmd (itemAt fc.ns 0 ) def class_string "" def ns_list (clone fc.ns) def bb false ns_list = (ns_list.filter({ if(index > 0 ) { bb = true } return (index > 0) })) class_string = (join ns_list " ") switch cmd { case "#" { cmd = "h1" } case "##" { cmd = "h2" } case "###" { cmd = "h3" } case "slide" { cmd = "section" } case "quote" { cmd = "blockquote" } } def simpleTags ([] "p" "b" "i" "u" "h1" "h2" "h3" "h4" "h5" "ul" "li" "ol" "section" "blockquote") def effects([] "fade-in" "fade-out" "zoom-in" "zoom-out" ) if( (indexOf simpleTags cmd) >= 0 ) { wr.out('<' + cmd , false) effects.forEach({ if( (indexOf fc.ns item) >= 0 ) { wr.out(' data-transition="' + item + '" ' , false) } }) if(node.hasStringProperty("class")) { wr.out(' class="' + class_string , false) wr.out( (node.getStringProperty('class')) false ) wr.out('" ' false) } { wr.out(' class="' + class_string + '" ' , false) } if(node.hasStringProperty("id")) { wr.out(' id="' false) wr.out( (node.getStringProperty('id')) false ) wr.out('" ' false) } wr.out( '>' , true) wr.indent(1) node.children.forEach({ if(index > 0 ) { this.WalkHTML( item ctx wr) } }) wr.newline() wr.indent(-1) wr.out('</' + cmd + '>' , true) return } switch cmd { case "code" { def linkRef (node.getSecond()) def tags "" if(node.hasBooleanProperty("noescape")) { tags = tags + 'data-noescape' } wr.out('<pre' false) wr.out(' class="' + class_string + '" ' , false) wr.out('><code ' + tags + '>' , false) this.WalkHTML( linkRef ctx wr ) wr.out('</code></pre>' true) } case "menutitle" { def linkRef (node.getSecond()) wr.out('<a class="pure-menu-heading" href="#">' false) this.WalkHTML( linkRef ctx wr ) wr.out('</a>' true) } case "menuitem" { def linkRef (node.getSecond()) wr.out('<li class="pure-menu-item"><a class="pure-menu-link" href="' false) this.WalkHTML( linkRef ctx wr ) wr.out('">' false) node.children.forEach({ if(index > 1 ) { this.WalkHTML( item ctx wr) } }) wr.out('</a></li>' true) } case "submenu" { def title (node.getSecond()) wr.out('<ul class="pure-menu-children">' false) node.children.forEach({ if(index > 0 ) { this.WalkHTML( item ctx wr) } }) wr.out('</ul>' true) } case "menulist" { def title (node.getSecond()) wr.out('<ul class="pure-menu-list">' false) node.children.forEach({ if(index > 0 ) { this.WalkHTML( item ctx wr) } }) wr.out('</ul>' true) } case "menu" { try { def menuWr (wr.getTag('menu')) def menuBody (node.getSecond()) this.WalkHTML( menuBody ctx menuWr ) } { } } case "a" { ; <a href="../html-link.htm#generator"> wr.out('<a href="' , false) def link (node.getSecond()) this.WalkHTML(link ctx wr) wr.out('" >' false) node.children.forEach({ if(index > 1 ) { this.WalkHTML( item ctx wr) } }) wr.out('</a>' false) } case "pre"{ def title (node.getSecond()) wr.out('<pre class="code">' false) node.children.forEach({ if(index > 0 ) { this.WalkHTML( item ctx wr) } }) wr.out('</pre>' true) } case "button"{ def title (node.getSecond()) wr.out('<button class="pure-button">' false) this.WalkHTML( title ctx wr ) wr.out('</button>' true) } case "thead" { wr.out('<thead>' false) wr.out('<tr>' true) wr.indent(1) node.children.forEach({ if(index > 0 ) { wr.out('<th>' false) this.WalkHTML( item ctx wr) wr.out('</th>' false) } }) wr.newline() wr.indent(-1) wr.out('</tr>' true) wr.out('</thead>' false) } case "tr" { def pIndex 1 try { if(!null? node.parent) { pIndex = (indexOf node.parent.children node) } } { } if( (pIndex % 2) == 0) { wr.out('<tr class="pure-table-odd">' true) } { wr.out('<tr>' true) } wr.indent(1) node.children.forEach({ if(index > 0 ) { wr.out('<td>' false) this.WalkHTML( item ctx wr) wr.out('</td>' false) } }) wr.newline() wr.indent(-1) wr.out('</tr>' true) } case "table" { wr.out('<table class="pure-table ' + class_string + '">' , false) wr.indent(1) def body (node.getSecond()) body.children.forEach({ this.WalkHTML(item ctx wr) }) wr.indent(-1) wr.out('</table>' true) } default { node.children.forEach({ this.WalkHTML( item ctx wr) }) } } } } fn initRevealPresentation(root:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { def titleNode (root.getSecond()) wr.out(`<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>` + titleNode.string_value + `</title> <link rel="stylesheet" href="css/reveal.css"> <link rel="stylesheet" href="css/theme/black.css"> <!-- Theme used for syntax highlighting of code --> <link rel="stylesheet" href="lib/css/zenburn.css"> <!-- Printing and PDF exports --> <script> var link = document.createElement( 'link' ); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css'; document.getElementsByTagName( 'head' )[0].appendChild( link ); </script> <style> mark { background-color:#ff3322;} .hljs { background: none; } </style> </head> <body> <div class="reveal"> <div class="slides"> ` , true) wr.createTag("slides") wr.out(` </div> </div> <script src="lib/js/head.min.js"></script> <script src="js/reveal.js"></script> <script> // More info about config & dependencies: // - https://github.com/hakimel/reveal.js#configuration // - https://github.com/hakimel/reveal.js#dependencies Reveal.initialize({ history:true, dependencies: [ { src: 'plugin/markdown/marked.js' }, { src: 'plugin/markdown/markdown.js' }, { src: 'plugin/notes/notes.js', async: true }, { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } } ] }); </script> </body> </html>` false) } fn writeTypeDef (item:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { if(item.hasFlag("optional")) { wr.out('<optional>' false) } switch item.value_type { case RangerNodeType.Array { wr.out("[" + item.array_type + "]" , false) } case RangerNodeType.Hash { wr.out("[" + item.key_type + ':' + item.array_type + "]" , false) } case RangerNodeType.ExpressionType { wr.out('(fn:' false) try { def rv:CodeNode (itemAt item.expression_value.children 0) def args:CodeNode (itemAt item.expression_value.children 1) this.writeTypeDef( rv ctx wr) wr.out( ' (' false) args.children.forEach({ if( index > 0 ) { wr.out(', ' false) } wr.out( item.vref false) wr.out(': ' false) this.writeTypeDef( item ctx wr) }) wr.out(')' false) } { } wr.out(')' false) } default { if( (strlen item.type_name ) > 0 ) { wr.out( ("" + item.type_name) false ) } } } } fn writeArgDefs (node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { node.children.forEach({ wr.out('tr ' false) wr.out( "`" + item.vref + "`" , false) wr.out("`" false) this.writeTypeDef(item ctx wr) wr.out("`" true) }) } fn create_op_slides (root:CodeNode ctx:RangerAppWriterContext orig_wr:CodeWriter) { def wr (new CodeWriter) wr.raw(` plugin.slides @noinfix(true) { presentation "Operators " "operators_slides.html" { ` true) def allOps (ctx.getAllOperators()) def statements (allOps.filter({ def is_map_array false if(item.firstArg) { is_map_array = ( (item.firstArg.value_type == RangerNodeType.Array) || (item.firstArg.value_type == RangerNodeType.Hash) ) } if( (indexOf item.name "if_") == 0 ) { return false } return ( (item.nameNode.type_name == "void") && (false == is_map_array) ) })) statements = (statements.groupBy({ return item.name })) statements.forEach({ def args:CodeNode (item.node.getThird()) wr.out(`slide {` true) wr.indent(1) wr.out('h1 ' + item.name , true) if(item.node.hasStringProperty('doc')) { wr.out('p `' false) wr.out((item.node.getStringProperty('doc')) false) wr.out('`' true) } wr.out('table { thead "Argument" "type" ' true) wr.indent(1) this.writeArgDefs(args ctx wr) wr.indent(-1) wr.out('}' true) try { wr.out('p ' false) def temps (itemAt item.node.children 3) temps.children.forEach({ if(item.isFirstVref('templates')) { def templateList (item.getSecond()) templateList.children.forEach({ def fc (item.getFirst()) def code (item.getSecond()) ; es 6 wr.out('(b ' + fc.vref + ') ' , false) }) } }) wr.newline() } { } wr.indent(-1) wr.out('}' true) }) wr.out(` } } ` false) ctx.pushCode((wr.getCode()) orig_wr) } fn postprocess (root:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { print "simplePlugin was called for postprosessing" ctx.definedClasses.forEach({ print " --> " + index }) try { print "--> starting" this.create_op_slides( root ctx wr ) print " ****************** CSS plugin running ***************************" def nodes (ctx.getPluginNodes("css")) def cssFile "style.css" if(ctx.hasCompilerSetting('css')) { cssFile = (ctx.getCompilerSetting("css")) } def cssWr (wr.getFileWriter('' cssFile) ) nodes.forEach({ def block (item.getSecond()) block.children.forEach({ ; print (item.getCode()) def styleName (item.getFirst()) cssWr.out( ( (this.vrefOrString(styleName)) + ' { ' ) true) cssWr.indent(1) this.walkStyleProps( (item.getSecond()) ctx cssWr ) cssWr.indent(-1) cssWr.out( '}' true) }) }) def nodes (ctx.getPluginNodes("html")) nodes.forEach({ def block (item.getSecond()) block.children.forEach({ if(item.isFirstVref("page")) { def nameNode (item.getSecond()) def pageWriter (wr.getFileWriter("." (nameNode.string_value + ".html"))) def content (item.getThird()) this.createPureCSSPage( content ctx pageWriter ) def wr (pageWriter.getTag("content")) content.children.forEach({ try { this.WalkHTML(item ctx wr) } { } }) } }) }) def nodes (ctx.getPluginNodes("graphql")) nodes.forEach({ def block (item.getSecond()) block.children.forEach({ if(item.isFirstVref("query")) { def nameNode (item.getSecond()) print "-------------------------------------------------------------" print " GraphQL " + nameNode.string_value def args (item.getThird()) print "Arguments : " + (args.getCode()) def qBody (itemAt item.children 3) print "Query body " + (qBody.getCode()) this.walkQueryBody( qBody ctx wr) print "-------------------------------------------------------------" } }) }) def nodes (ctx.getPluginNodes("slides")) nodes.forEach({ def block (item.getSecond()) block.children.forEach({ if(item.isFirstVref("presentation")) { try { def nameNode (item.getSecond()) if( (strlen nameNode.string_value ) == 0 ) { ctx.addError(item "Please give name to the presentation") return } def fileNode (item.getThird()) if( (strlen fileNode.string_value ) == 0 ) { ctx.addError(item "Please output file give name to the presentation") return } def presis (itemAt item.children 3) def pageWriter (wr.getFileWriter("." (fileNode.string_value ))) this.initRevealPresentation( item ctx pageWriter ) def slideWr (pageWriter.getTag("slides")) this.WalkHTML( presis ctx slideWr ) ; --- create also a static page --- def nameNode (item.getSecond()) def pageWriter (wr.getFileWriter("." ("static_" + fileNode.string_value))) this.createPureCSSPage( item ctx pageWriter ) def wr (pageWriter.getTag("content")) this.WalkHTML(presis ctx wr) } { ctx.addError( item "Invalid presentation") } } }) }) } { print (error_msg) } } }
true
Import "ng_Compiler.clj" ; http://ryanogles.by/css/javascript/2017/05/25/the-state-of-css.html ; https://speakerdeck.com/vjeux/react-css-in-js ; Unity file format: ; https://docs.unity3d.com/Manual/FormatDescription.html ; --> describing a database ; ---> fields, names, types etc. ; --> describe a wordpress site and publish it to cloud ; --> how to do that ? ; USD ; https://graphics.pixar.com/usd/docs/index.html ; https://graphics.pixar.com/usd/docs/USD-Glossary.html ; https://codepen.io/MarcRay/pen/vmJBn operator type:string all { fn remove_trailing:string (ch:string) { def parts (strsplit self ch) if( ( array_length parts ) == 1 ) { return self } removeLast parts return (join parts ch) } } class Plugin { def html_mode "" def vendor_prefixes:[string] ([] "-moz-" "-webkit-" "-o-" "-ms-") def prefixable:[string] ([] "borderRadius" "border-radius" ) def transform:[string] ([] "borderRadius" "border-radius" ) fn features:[string] () { return ([] "import_loader" "postprocess" "random" "generate_ast") } ; -- import command can be used by plugins to insert custom code and features fn import_loader:Any ( node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { ; Import "somelib" def sc (node.getSecond()) if(sc.string_value == "jabba") { return ' class jabba { fn jabbaTester() { } } ' } return false } fn generate_ast (root:CodeNode ctx:RangerAppWriterContext orig_wr:CodeWriter) { print "-------------------------------------------------------" print "--> Generate AST was called in plugin" ctx.pushAst( ` operator type:void all { fn alert (str:string) { print "ALERT!!! " + str } } class inserted_class { static fn foo () { print "inserted_class does exist!!!" } } ` root orig_wr) } fn doesRequirePrefix:boolean ( cssName:string) { return ( (indexOf prefixable cssName) >= 0 ) } fn transformName:string ( cssName:string) { def i (indexOf transform cssName) if( (i >= 0 ) && (0 == (i % 2)) ) { return (itemAt transform (i + 1)) } return cssName } fn applyCss (cssName:string cssValue:string ctx:RangerAppWriterContext wr:CodeWriter) { if( (this.doesRequirePrefix(cssName))) { vendor_prefixes.forEach({ wr.out( item + (this.transformName(cssName)) + ': ' , false ) wr.out(cssValue + ";" , true) }) } { wr.out( (this.transformName(cssName)) + ': ' , false ) wr.out(cssValue + ";" , true) } } ; can be written either as color or 'color' fn vrefOrString:string ( node:CodeNode ) { if( (strlen node.vref) > 0 ) { return node.vref } return node.string_value + (node.value_type) } fn nodeOrigValue:string ( node:CodeNode ) { if(node.value_type == RangerNodeType.VRef) { return node.vref } if(node.value_type == RangerNodeType.Integer) { return ("" + node.int_value) } if(node.value_type == RangerNodeType.Double) { return ("" + node.double_value) } return (node.getParsedString()) } fn collectValuesFromLine:string (start_index:int parentNode:CodeNode) { def res "" def cnt 0 def last_numeric false def unit_values:[string] ([] "px" "dp" "em" "s") for parentNode.children ch:CodeNode i { if( i >= start_index ) { if( (false == last_numeric) && (cnt > 0 ) ) { res = res + " " } def this_val (remove_trailing (trim (this.nodeOrigValue(ch))) ";" ) if last_numeric { if( (indexOf unit_values this_val) < 0) { res = res + " " } } res = res + (this.nodeOrigValue(ch)) cnt = cnt + 1 last_numeric = (ch.value_type == RangerNodeType.Integer || ch.value_type == RangerNodeType.Double) } } return res } fn walkStyleProps (node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { node.children.forEach({ def propName (item.getFirst()) def propValue (item.getSecond()) def theValue (this.collectValuesFromLine( 1 item)) def parts (strsplit theValue ";") theValue = (itemAt parts 0) this.applyCss( (this.vrefOrString(propName)) theValue ctx wr) }) } fn walkQueryBody (node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { node.children.forEach({ if( (array_length item.children ) == 0) { return } def propName (item.getFirst()) def name "" if( (array_length item.children ) == 1) { print " ---> fetching property " + propName.vref return } if( (array_length item.children ) == 2) { def propConnected (item.getSecond()) print "fetching links without filtering " + propName.vref this.walkQueryBody( (propConnected) ctx wr) return } if( (array_length item.children ) == 3) { def filters (item.getSecond()) def propConnected (item.getThird()) print "fetching links with filtering " + propName.vref filters.children.forEach({ print " ^^ filter: " + item.vref }) this.walkQueryBody( (propConnected) ctx wr) return } }) } fn createPureCSSPage (root:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { def hasMenu (root.children.contains({ return (item.isFirstVref("menu")) })) wr.out('<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="side-menu.css"></link> <link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/pure-min.css" integrity="PI:KEY:<KEY>END_PI" crossorigin="anonymous">' true) wr.createTag('head') wr.out(' </head> <body> <div id="layout">' true) if hasMenu { wr.out(` <!-- Menu toggle --> <a href="#menu" id="menuLink" class="menu-link"> <!-- Hamburger icon --> <span></span> </a> <div id="menu"> <div class="pure-menu"> ` true) wr.createTag('menu') wr.out(' </div> </div>' true) } wr.out(' <div id="main"> <div class="content"> ' true) wr.createTag('content') wr.out(' </div> </div> <script src="/ui.js"></script> </body> </html>' false) } fn WalkHTML (node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { if(node.is_block_node) { node.children.forEach({ this.WalkHTML( item ctx wr) }) return } if(node.value_type == RangerNodeType.String) { wr.raw(node.string_value false) return } if(node.value_type == RangerNodeType.Integer) { wr.out( ('' + node.int_value) false) return } if(node.value_type == RangerNodeType.Double) { wr.out( (node.getParsedString()) false) return } if(node.value_type == RangerNodeType.Boolean) { if node.boolean_value { wr.out( 'true' false) } { wr.out( 'false' false) } return } if(node.value_type == RangerNodeType.VRef) { wr.out((node.vref + " ") false) return } if(node.expression) { def fc (node.getFirst()) def cmd (itemAt fc.ns 0 ) def class_string "" def ns_list (clone fc.ns) def bb false ns_list = (ns_list.filter({ if(index > 0 ) { bb = true } return (index > 0) })) class_string = (join ns_list " ") switch cmd { case "#" { cmd = "h1" } case "##" { cmd = "h2" } case "###" { cmd = "h3" } case "slide" { cmd = "section" } case "quote" { cmd = "blockquote" } } def simpleTags ([] "p" "b" "i" "u" "h1" "h2" "h3" "h4" "h5" "ul" "li" "ol" "section" "blockquote") def effects([] "fade-in" "fade-out" "zoom-in" "zoom-out" ) if( (indexOf simpleTags cmd) >= 0 ) { wr.out('<' + cmd , false) effects.forEach({ if( (indexOf fc.ns item) >= 0 ) { wr.out(' data-transition="' + item + '" ' , false) } }) if(node.hasStringProperty("class")) { wr.out(' class="' + class_string , false) wr.out( (node.getStringProperty('class')) false ) wr.out('" ' false) } { wr.out(' class="' + class_string + '" ' , false) } if(node.hasStringProperty("id")) { wr.out(' id="' false) wr.out( (node.getStringProperty('id')) false ) wr.out('" ' false) } wr.out( '>' , true) wr.indent(1) node.children.forEach({ if(index > 0 ) { this.WalkHTML( item ctx wr) } }) wr.newline() wr.indent(-1) wr.out('</' + cmd + '>' , true) return } switch cmd { case "code" { def linkRef (node.getSecond()) def tags "" if(node.hasBooleanProperty("noescape")) { tags = tags + 'data-noescape' } wr.out('<pre' false) wr.out(' class="' + class_string + '" ' , false) wr.out('><code ' + tags + '>' , false) this.WalkHTML( linkRef ctx wr ) wr.out('</code></pre>' true) } case "menutitle" { def linkRef (node.getSecond()) wr.out('<a class="pure-menu-heading" href="#">' false) this.WalkHTML( linkRef ctx wr ) wr.out('</a>' true) } case "menuitem" { def linkRef (node.getSecond()) wr.out('<li class="pure-menu-item"><a class="pure-menu-link" href="' false) this.WalkHTML( linkRef ctx wr ) wr.out('">' false) node.children.forEach({ if(index > 1 ) { this.WalkHTML( item ctx wr) } }) wr.out('</a></li>' true) } case "submenu" { def title (node.getSecond()) wr.out('<ul class="pure-menu-children">' false) node.children.forEach({ if(index > 0 ) { this.WalkHTML( item ctx wr) } }) wr.out('</ul>' true) } case "menulist" { def title (node.getSecond()) wr.out('<ul class="pure-menu-list">' false) node.children.forEach({ if(index > 0 ) { this.WalkHTML( item ctx wr) } }) wr.out('</ul>' true) } case "menu" { try { def menuWr (wr.getTag('menu')) def menuBody (node.getSecond()) this.WalkHTML( menuBody ctx menuWr ) } { } } case "a" { ; <a href="../html-link.htm#generator"> wr.out('<a href="' , false) def link (node.getSecond()) this.WalkHTML(link ctx wr) wr.out('" >' false) node.children.forEach({ if(index > 1 ) { this.WalkHTML( item ctx wr) } }) wr.out('</a>' false) } case "pre"{ def title (node.getSecond()) wr.out('<pre class="code">' false) node.children.forEach({ if(index > 0 ) { this.WalkHTML( item ctx wr) } }) wr.out('</pre>' true) } case "button"{ def title (node.getSecond()) wr.out('<button class="pure-button">' false) this.WalkHTML( title ctx wr ) wr.out('</button>' true) } case "thead" { wr.out('<thead>' false) wr.out('<tr>' true) wr.indent(1) node.children.forEach({ if(index > 0 ) { wr.out('<th>' false) this.WalkHTML( item ctx wr) wr.out('</th>' false) } }) wr.newline() wr.indent(-1) wr.out('</tr>' true) wr.out('</thead>' false) } case "tr" { def pIndex 1 try { if(!null? node.parent) { pIndex = (indexOf node.parent.children node) } } { } if( (pIndex % 2) == 0) { wr.out('<tr class="pure-table-odd">' true) } { wr.out('<tr>' true) } wr.indent(1) node.children.forEach({ if(index > 0 ) { wr.out('<td>' false) this.WalkHTML( item ctx wr) wr.out('</td>' false) } }) wr.newline() wr.indent(-1) wr.out('</tr>' true) } case "table" { wr.out('<table class="pure-table ' + class_string + '">' , false) wr.indent(1) def body (node.getSecond()) body.children.forEach({ this.WalkHTML(item ctx wr) }) wr.indent(-1) wr.out('</table>' true) } default { node.children.forEach({ this.WalkHTML( item ctx wr) }) } } } } fn initRevealPresentation(root:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { def titleNode (root.getSecond()) wr.out(`<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>` + titleNode.string_value + `</title> <link rel="stylesheet" href="css/reveal.css"> <link rel="stylesheet" href="css/theme/black.css"> <!-- Theme used for syntax highlighting of code --> <link rel="stylesheet" href="lib/css/zenburn.css"> <!-- Printing and PDF exports --> <script> var link = document.createElement( 'link' ); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css'; document.getElementsByTagName( 'head' )[0].appendChild( link ); </script> <style> mark { background-color:#ff3322;} .hljs { background: none; } </style> </head> <body> <div class="reveal"> <div class="slides"> ` , true) wr.createTag("slides") wr.out(` </div> </div> <script src="lib/js/head.min.js"></script> <script src="js/reveal.js"></script> <script> // More info about config & dependencies: // - https://github.com/hakimel/reveal.js#configuration // - https://github.com/hakimel/reveal.js#dependencies Reveal.initialize({ history:true, dependencies: [ { src: 'plugin/markdown/marked.js' }, { src: 'plugin/markdown/markdown.js' }, { src: 'plugin/notes/notes.js', async: true }, { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } } ] }); </script> </body> </html>` false) } fn writeTypeDef (item:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { if(item.hasFlag("optional")) { wr.out('<optional>' false) } switch item.value_type { case RangerNodeType.Array { wr.out("[" + item.array_type + "]" , false) } case RangerNodeType.Hash { wr.out("[" + item.key_type + ':' + item.array_type + "]" , false) } case RangerNodeType.ExpressionType { wr.out('(fn:' false) try { def rv:CodeNode (itemAt item.expression_value.children 0) def args:CodeNode (itemAt item.expression_value.children 1) this.writeTypeDef( rv ctx wr) wr.out( ' (' false) args.children.forEach({ if( index > 0 ) { wr.out(', ' false) } wr.out( item.vref false) wr.out(': ' false) this.writeTypeDef( item ctx wr) }) wr.out(')' false) } { } wr.out(')' false) } default { if( (strlen item.type_name ) > 0 ) { wr.out( ("" + item.type_name) false ) } } } } fn writeArgDefs (node:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { node.children.forEach({ wr.out('tr ' false) wr.out( "`" + item.vref + "`" , false) wr.out("`" false) this.writeTypeDef(item ctx wr) wr.out("`" true) }) } fn create_op_slides (root:CodeNode ctx:RangerAppWriterContext orig_wr:CodeWriter) { def wr (new CodeWriter) wr.raw(` plugin.slides @noinfix(true) { presentation "Operators " "operators_slides.html" { ` true) def allOps (ctx.getAllOperators()) def statements (allOps.filter({ def is_map_array false if(item.firstArg) { is_map_array = ( (item.firstArg.value_type == RangerNodeType.Array) || (item.firstArg.value_type == RangerNodeType.Hash) ) } if( (indexOf item.name "if_") == 0 ) { return false } return ( (item.nameNode.type_name == "void") && (false == is_map_array) ) })) statements = (statements.groupBy({ return item.name })) statements.forEach({ def args:CodeNode (item.node.getThird()) wr.out(`slide {` true) wr.indent(1) wr.out('h1 ' + item.name , true) if(item.node.hasStringProperty('doc')) { wr.out('p `' false) wr.out((item.node.getStringProperty('doc')) false) wr.out('`' true) } wr.out('table { thead "Argument" "type" ' true) wr.indent(1) this.writeArgDefs(args ctx wr) wr.indent(-1) wr.out('}' true) try { wr.out('p ' false) def temps (itemAt item.node.children 3) temps.children.forEach({ if(item.isFirstVref('templates')) { def templateList (item.getSecond()) templateList.children.forEach({ def fc (item.getFirst()) def code (item.getSecond()) ; es 6 wr.out('(b ' + fc.vref + ') ' , false) }) } }) wr.newline() } { } wr.indent(-1) wr.out('}' true) }) wr.out(` } } ` false) ctx.pushCode((wr.getCode()) orig_wr) } fn postprocess (root:CodeNode ctx:RangerAppWriterContext wr:CodeWriter) { print "simplePlugin was called for postprosessing" ctx.definedClasses.forEach({ print " --> " + index }) try { print "--> starting" this.create_op_slides( root ctx wr ) print " ****************** CSS plugin running ***************************" def nodes (ctx.getPluginNodes("css")) def cssFile "style.css" if(ctx.hasCompilerSetting('css')) { cssFile = (ctx.getCompilerSetting("css")) } def cssWr (wr.getFileWriter('' cssFile) ) nodes.forEach({ def block (item.getSecond()) block.children.forEach({ ; print (item.getCode()) def styleName (item.getFirst()) cssWr.out( ( (this.vrefOrString(styleName)) + ' { ' ) true) cssWr.indent(1) this.walkStyleProps( (item.getSecond()) ctx cssWr ) cssWr.indent(-1) cssWr.out( '}' true) }) }) def nodes (ctx.getPluginNodes("html")) nodes.forEach({ def block (item.getSecond()) block.children.forEach({ if(item.isFirstVref("page")) { def nameNode (item.getSecond()) def pageWriter (wr.getFileWriter("." (nameNode.string_value + ".html"))) def content (item.getThird()) this.createPureCSSPage( content ctx pageWriter ) def wr (pageWriter.getTag("content")) content.children.forEach({ try { this.WalkHTML(item ctx wr) } { } }) } }) }) def nodes (ctx.getPluginNodes("graphql")) nodes.forEach({ def block (item.getSecond()) block.children.forEach({ if(item.isFirstVref("query")) { def nameNode (item.getSecond()) print "-------------------------------------------------------------" print " GraphQL " + nameNode.string_value def args (item.getThird()) print "Arguments : " + (args.getCode()) def qBody (itemAt item.children 3) print "Query body " + (qBody.getCode()) this.walkQueryBody( qBody ctx wr) print "-------------------------------------------------------------" } }) }) def nodes (ctx.getPluginNodes("slides")) nodes.forEach({ def block (item.getSecond()) block.children.forEach({ if(item.isFirstVref("presentation")) { try { def nameNode (item.getSecond()) if( (strlen nameNode.string_value ) == 0 ) { ctx.addError(item "Please give name to the presentation") return } def fileNode (item.getThird()) if( (strlen fileNode.string_value ) == 0 ) { ctx.addError(item "Please output file give name to the presentation") return } def presis (itemAt item.children 3) def pageWriter (wr.getFileWriter("." (fileNode.string_value ))) this.initRevealPresentation( item ctx pageWriter ) def slideWr (pageWriter.getTag("slides")) this.WalkHTML( presis ctx slideWr ) ; --- create also a static page --- def nameNode (item.getSecond()) def pageWriter (wr.getFileWriter("." ("static_" + fileNode.string_value))) this.createPureCSSPage( item ctx pageWriter ) def wr (pageWriter.getTag("content")) this.WalkHTML(presis ctx wr) } { ctx.addError( item "Invalid presentation") } } }) }) } { print (error_msg) } } }
[ { "context": " ^{:doc \"Audio effects library\"\n :author \"Jeff Rose\"}\n overtone.studio.fx\n (:use [overtone.libs eve", "end": 63, "score": 0.999871015548706, "start": 54, "tag": "NAME", "value": "Jeff Rose" } ]
src/overtone/studio/fx.clj
samaaron/overtone
2
(ns ^{:doc "Audio effects library" :author "Jeff Rose"} overtone.studio.fx (:use [overtone.libs event] [overtone.sc synth ugens])) (defonce __FX-SYNTHS__ (do (defsynth fx-noise-gate [in-bus 20 out-bus 10 threshold 0.4 slope-below 1 slope-above 0.1 clamp-time 0.01 relax-time 0.1] (let [source (in in-bus)] (out out-bus (compander source source threshold slope-below slope-above clamp-time relax-time)))) (defsynth fx-compressor [in-bus 20 out-bus 10 threshold 0.2 slope-below 1 slope-above 0.5 clamp-time 0.01 relax-time 0.01] (let [source (in in-bus)] (out out-bus (compander source source threshold slope-below slope-above clamp-time relax-time)))) (defsynth fx-limiter [in-bus 20 out-bus 10 threshold 0.2 slope-below 1 slope-above 0.1 clamp-time 0.01 relax-time 0.01] (let [source (in in-bus)] (out out-bus (compander source source threshold slope-below slope-above clamp-time relax-time)))) (defsynth fx-sustainer [in-bus 20 out-bus 10 threshold 0.2 slope-below 1 slope-above 0.5 clamp-time 0.01 relax-time 0.01] (let [source (in in-bus)] (out out-bus (compander source source threshold slope-below slope-above clamp-time relax-time)))) (defsynth fx-reverb [in-bus 20 out-bus 10 wet-dry 0.5 room-size 0.5 dampening 0.5] (out out-bus (* 1.4 (free-verb (in in-bus) wet-dry room-size dampening)))) (defsynth fx-echo [in-bus 20 out-bus 10 max-delay 1.0 delay-time 0.4 decay-time 2.0] (let [source (in in-bus) echo (comb-n source max-delay delay-time decay-time)] (out out-bus (pan2 (+ echo source) 0)))) (defsynth fx-chorus [in-bus 20 out-bus 10 rate 0.002 depth 0.01] (let [src (in in-bus) dub-depth (* 2 depth) rates [rate (+ rate 0.001)] osc (+ dub-depth (* dub-depth (sin-osc:kr rates))) dly-a (delay-l src 0.3 osc) sig (apply + src dly-a)] (out out-bus (* 0.3 sig)))) (defsynth fx-distortion [in-bus 20 out-bus 10 boost 4 level 0.01] (let [src (in in-bus)] (out out-bus (distort (* boost (clip2 src level)))))) (defsynth fx-rlpf [in-bus 20 out-bus 10 cutoff 40000 res 0.6] (let [src (in in-bus)] (out out-bus (rlpf src cutoff res)))) (defsynth fx-rhpf [in-bus 20 out-bus 10 cutoff 2 res 0.6] (let [src (in in-bus)] (out out-bus (rhpf src cutoff res)))) ))
32366
(ns ^{:doc "Audio effects library" :author "<NAME>"} overtone.studio.fx (:use [overtone.libs event] [overtone.sc synth ugens])) (defonce __FX-SYNTHS__ (do (defsynth fx-noise-gate [in-bus 20 out-bus 10 threshold 0.4 slope-below 1 slope-above 0.1 clamp-time 0.01 relax-time 0.1] (let [source (in in-bus)] (out out-bus (compander source source threshold slope-below slope-above clamp-time relax-time)))) (defsynth fx-compressor [in-bus 20 out-bus 10 threshold 0.2 slope-below 1 slope-above 0.5 clamp-time 0.01 relax-time 0.01] (let [source (in in-bus)] (out out-bus (compander source source threshold slope-below slope-above clamp-time relax-time)))) (defsynth fx-limiter [in-bus 20 out-bus 10 threshold 0.2 slope-below 1 slope-above 0.1 clamp-time 0.01 relax-time 0.01] (let [source (in in-bus)] (out out-bus (compander source source threshold slope-below slope-above clamp-time relax-time)))) (defsynth fx-sustainer [in-bus 20 out-bus 10 threshold 0.2 slope-below 1 slope-above 0.5 clamp-time 0.01 relax-time 0.01] (let [source (in in-bus)] (out out-bus (compander source source threshold slope-below slope-above clamp-time relax-time)))) (defsynth fx-reverb [in-bus 20 out-bus 10 wet-dry 0.5 room-size 0.5 dampening 0.5] (out out-bus (* 1.4 (free-verb (in in-bus) wet-dry room-size dampening)))) (defsynth fx-echo [in-bus 20 out-bus 10 max-delay 1.0 delay-time 0.4 decay-time 2.0] (let [source (in in-bus) echo (comb-n source max-delay delay-time decay-time)] (out out-bus (pan2 (+ echo source) 0)))) (defsynth fx-chorus [in-bus 20 out-bus 10 rate 0.002 depth 0.01] (let [src (in in-bus) dub-depth (* 2 depth) rates [rate (+ rate 0.001)] osc (+ dub-depth (* dub-depth (sin-osc:kr rates))) dly-a (delay-l src 0.3 osc) sig (apply + src dly-a)] (out out-bus (* 0.3 sig)))) (defsynth fx-distortion [in-bus 20 out-bus 10 boost 4 level 0.01] (let [src (in in-bus)] (out out-bus (distort (* boost (clip2 src level)))))) (defsynth fx-rlpf [in-bus 20 out-bus 10 cutoff 40000 res 0.6] (let [src (in in-bus)] (out out-bus (rlpf src cutoff res)))) (defsynth fx-rhpf [in-bus 20 out-bus 10 cutoff 2 res 0.6] (let [src (in in-bus)] (out out-bus (rhpf src cutoff res)))) ))
true
(ns ^{:doc "Audio effects library" :author "PI:NAME:<NAME>END_PI"} overtone.studio.fx (:use [overtone.libs event] [overtone.sc synth ugens])) (defonce __FX-SYNTHS__ (do (defsynth fx-noise-gate [in-bus 20 out-bus 10 threshold 0.4 slope-below 1 slope-above 0.1 clamp-time 0.01 relax-time 0.1] (let [source (in in-bus)] (out out-bus (compander source source threshold slope-below slope-above clamp-time relax-time)))) (defsynth fx-compressor [in-bus 20 out-bus 10 threshold 0.2 slope-below 1 slope-above 0.5 clamp-time 0.01 relax-time 0.01] (let [source (in in-bus)] (out out-bus (compander source source threshold slope-below slope-above clamp-time relax-time)))) (defsynth fx-limiter [in-bus 20 out-bus 10 threshold 0.2 slope-below 1 slope-above 0.1 clamp-time 0.01 relax-time 0.01] (let [source (in in-bus)] (out out-bus (compander source source threshold slope-below slope-above clamp-time relax-time)))) (defsynth fx-sustainer [in-bus 20 out-bus 10 threshold 0.2 slope-below 1 slope-above 0.5 clamp-time 0.01 relax-time 0.01] (let [source (in in-bus)] (out out-bus (compander source source threshold slope-below slope-above clamp-time relax-time)))) (defsynth fx-reverb [in-bus 20 out-bus 10 wet-dry 0.5 room-size 0.5 dampening 0.5] (out out-bus (* 1.4 (free-verb (in in-bus) wet-dry room-size dampening)))) (defsynth fx-echo [in-bus 20 out-bus 10 max-delay 1.0 delay-time 0.4 decay-time 2.0] (let [source (in in-bus) echo (comb-n source max-delay delay-time decay-time)] (out out-bus (pan2 (+ echo source) 0)))) (defsynth fx-chorus [in-bus 20 out-bus 10 rate 0.002 depth 0.01] (let [src (in in-bus) dub-depth (* 2 depth) rates [rate (+ rate 0.001)] osc (+ dub-depth (* dub-depth (sin-osc:kr rates))) dly-a (delay-l src 0.3 osc) sig (apply + src dly-a)] (out out-bus (* 0.3 sig)))) (defsynth fx-distortion [in-bus 20 out-bus 10 boost 4 level 0.01] (let [src (in in-bus)] (out out-bus (distort (* boost (clip2 src level)))))) (defsynth fx-rlpf [in-bus 20 out-bus 10 cutoff 40000 res 0.6] (let [src (in in-bus)] (out out-bus (rlpf src cutoff res)))) (defsynth fx-rhpf [in-bus 20 out-bus 10 cutoff 2 res 0.6] (let [src (in in-bus)] (out out-bus (rhpf src cutoff res)))) ))
[ { "context": "sport :confidential\n :password :internal-only}}))\n\n ;; 2. Define your schema\n (def User\n ", "end": 1205, "score": 0.9911708831787109, "start": 1192, "tag": "PASSWORD", "value": "internal-only" } ]
src/main/clojure/secret/keeper/malli.cljc
sultanov-team/secret-keeper
24
(ns secret.keeper.malli "The simple wrapper for the malli library. Easy markup your secrets in one place - directly in your model." (:require [malli.core :as m] [malli.transform :as mt] [secret.keeper :as keeper])) (def secret? (m/-simple-schema {:type :secret :pred keeper/secret? :type-properties {:error/message "should be satisfied protocol `secret.keeper/ISecret`"}})) (defn transformer "Secret transformer. - Encoder - encodes all secrets using the specified categories. - Decoder - decodes all secrets. Strategy: 1. Try to extract the category from the schema properties using the specified key. Important: The local category has the highest priority. 2. Try to extract the category from the transformer secrets map by the schema type 3. Otherwise, if the schema has any entries, we take the specified categories from the transformer secrets map by the entry key Usage: ``` ;; 1. Define your transformer (def Transformer (transformer {:key :category ;; by default ::keeper/category :secrets {:passport :confidential :password :internal-only}})) ;; 2. Define your schema (def User [:map [:firstname string?] [:lastname string?] [:email string?] [:passport string?] [:address [:map {:category :personal} [:street string?] [:zip int?] [:city string?] [:country [:enum \"Russia\" \"USA\"]]]] [:credentials [:map [:login string?] [:password string?]]]]) ;; 3. Mark all secrets using the specified categories (m/encode User <your-data> Transformer) ;; 4. Decode all secrets (m/decode User <your-data> Transformer) ```" ([] (transformer nil)) ([{:keys [key secrets] :or {key ::keeper/category secrets {}}}] (let [global-keys (set (keys secrets)) get-category (fn [schema] (or (some-> schema m/properties key) (some->> schema m/type (get secrets)))) encoder (fn [schema _opts] (if-some [category (get-category schema)] (fn [x] (keeper/make-secret x category)) (when (seq global-keys) (when-some [entries (m/entries schema)] (let [ks (reduce (fn [acc [k & _]] (if (contains? global-keys k) (assoc acc k (get secrets k)) acc)) {} entries)] (fn [x] (if (map? x) (reduce-kv (fn [acc key category] (update acc key #(keeper/make-secret % category))) x ks) x))))))) decoder (fn [_schema _opts] (fn [x] (if (keeper/secret? x) (keeper/data x) x)))] (mt/transformer {:default-encoder {:compile encoder} :default-decoder {:compile decoder}}))))
14465
(ns secret.keeper.malli "The simple wrapper for the malli library. Easy markup your secrets in one place - directly in your model." (:require [malli.core :as m] [malli.transform :as mt] [secret.keeper :as keeper])) (def secret? (m/-simple-schema {:type :secret :pred keeper/secret? :type-properties {:error/message "should be satisfied protocol `secret.keeper/ISecret`"}})) (defn transformer "Secret transformer. - Encoder - encodes all secrets using the specified categories. - Decoder - decodes all secrets. Strategy: 1. Try to extract the category from the schema properties using the specified key. Important: The local category has the highest priority. 2. Try to extract the category from the transformer secrets map by the schema type 3. Otherwise, if the schema has any entries, we take the specified categories from the transformer secrets map by the entry key Usage: ``` ;; 1. Define your transformer (def Transformer (transformer {:key :category ;; by default ::keeper/category :secrets {:passport :confidential :password :<PASSWORD>}})) ;; 2. Define your schema (def User [:map [:firstname string?] [:lastname string?] [:email string?] [:passport string?] [:address [:map {:category :personal} [:street string?] [:zip int?] [:city string?] [:country [:enum \"Russia\" \"USA\"]]]] [:credentials [:map [:login string?] [:password string?]]]]) ;; 3. Mark all secrets using the specified categories (m/encode User <your-data> Transformer) ;; 4. Decode all secrets (m/decode User <your-data> Transformer) ```" ([] (transformer nil)) ([{:keys [key secrets] :or {key ::keeper/category secrets {}}}] (let [global-keys (set (keys secrets)) get-category (fn [schema] (or (some-> schema m/properties key) (some->> schema m/type (get secrets)))) encoder (fn [schema _opts] (if-some [category (get-category schema)] (fn [x] (keeper/make-secret x category)) (when (seq global-keys) (when-some [entries (m/entries schema)] (let [ks (reduce (fn [acc [k & _]] (if (contains? global-keys k) (assoc acc k (get secrets k)) acc)) {} entries)] (fn [x] (if (map? x) (reduce-kv (fn [acc key category] (update acc key #(keeper/make-secret % category))) x ks) x))))))) decoder (fn [_schema _opts] (fn [x] (if (keeper/secret? x) (keeper/data x) x)))] (mt/transformer {:default-encoder {:compile encoder} :default-decoder {:compile decoder}}))))
true
(ns secret.keeper.malli "The simple wrapper for the malli library. Easy markup your secrets in one place - directly in your model." (:require [malli.core :as m] [malli.transform :as mt] [secret.keeper :as keeper])) (def secret? (m/-simple-schema {:type :secret :pred keeper/secret? :type-properties {:error/message "should be satisfied protocol `secret.keeper/ISecret`"}})) (defn transformer "Secret transformer. - Encoder - encodes all secrets using the specified categories. - Decoder - decodes all secrets. Strategy: 1. Try to extract the category from the schema properties using the specified key. Important: The local category has the highest priority. 2. Try to extract the category from the transformer secrets map by the schema type 3. Otherwise, if the schema has any entries, we take the specified categories from the transformer secrets map by the entry key Usage: ``` ;; 1. Define your transformer (def Transformer (transformer {:key :category ;; by default ::keeper/category :secrets {:passport :confidential :password :PI:PASSWORD:<PASSWORD>END_PI}})) ;; 2. Define your schema (def User [:map [:firstname string?] [:lastname string?] [:email string?] [:passport string?] [:address [:map {:category :personal} [:street string?] [:zip int?] [:city string?] [:country [:enum \"Russia\" \"USA\"]]]] [:credentials [:map [:login string?] [:password string?]]]]) ;; 3. Mark all secrets using the specified categories (m/encode User <your-data> Transformer) ;; 4. Decode all secrets (m/decode User <your-data> Transformer) ```" ([] (transformer nil)) ([{:keys [key secrets] :or {key ::keeper/category secrets {}}}] (let [global-keys (set (keys secrets)) get-category (fn [schema] (or (some-> schema m/properties key) (some->> schema m/type (get secrets)))) encoder (fn [schema _opts] (if-some [category (get-category schema)] (fn [x] (keeper/make-secret x category)) (when (seq global-keys) (when-some [entries (m/entries schema)] (let [ks (reduce (fn [acc [k & _]] (if (contains? global-keys k) (assoc acc k (get secrets k)) acc)) {} entries)] (fn [x] (if (map? x) (reduce-kv (fn [acc key category] (update acc key #(keeper/make-secret % category))) x ks) x))))))) decoder (fn [_schema _opts] (fn [x] (if (keeper/secret? x) (keeper/data x) x)))] (mt/transformer {:default-encoder {:compile encoder} :default-decoder {:compile decoder}}))))
[ { "context": ";-\n; Copyright 2008-2011 (c) Meikel Brandmeyer.\n; All rights reserved.\n;\n; Permission is hereby ", "end": 46, "score": 0.9998713731765747, "start": 29, "tag": "NAME", "value": "Meikel Brandmeyer" }, { "context": "OFTWARE.\n\n;; Retreived from https://bitbucket.org/kotarak/lazymap/raw/5a2437e70a91/src/main/clojure/lazymap", "end": 1176, "score": 0.9976856708526611, "start": 1169, "tag": "USERNAME", "value": "kotarak" } ]
src/plumbing/lazymap.clj
ejackson/plumbing
1
;- ; Copyright 2008-2011 (c) Meikel Brandmeyer. ; All rights reserved. ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ; THE SOFTWARE. ;; Retreived from https://bitbucket.org/kotarak/lazymap/raw/5a2437e70a91/src/main/clojure/lazymap/core.clj ;; by JW on 11/17/2011, and slightly modified to fix a bug in .entryAt and add a safety check. ;; Also replaced 'force' with 'deref' so this can be used with futures (with marginal utility). ;; (our pull request with these changes has been been ignored, so we've just included ;; this fixed file in plumbing for the time being). ;; Known Issues: LazyMapEntries are not equal to persistent vectors like ordinary map entries. (ns plumbing.lazymap "Lazymap is to maps what lazy-seq is to lists. It allows to store values with evaluating them. This is only done in case the value is really accessed. Lazymap works with any map type (hash-map, sorted-map, struct-map) and may be used as a drop-in replacement everywhere where a normal map type may be used. Available macros: lazy-hash-map, lazy-sorted-map, lazy-struct-map, lazy-struct, lazy-assoc and their * counterpart functions." (:import clojure.lang.IObj clojure.lang.IFn clojure.lang.ILookup clojure.lang.IMapEntry clojure.lang.IPersistentMap clojure.lang.IPersistentVector clojure.lang.ASeq clojure.lang.ISeq clojure.lang.Seqable clojure.lang.SeqIterator)) (defprotocol ILazyMapEntry "ILazyMapEntry describes the behaviour of a lazy MapEntry. It provides an additional method (over IMapEntry), which returns the raw delay object and not the forced value." (get-key [lazy-map-entry] "Return the key of the map entry.") (get-raw-value [lazy-map-entry] "Return the underlying delay object.")) ; Extend the IMapEntry interface to act also like ILazyMapEntry. ; For a IMapEntry get-raw-value just returns the given value as ; wrapped in a delay. Similar a vector of two elements might be ; used in place of a IMapEntry. (extend-protocol ILazyMapEntry IMapEntry (get-key [#^IMapEntry this] (.getKey this)) (get-raw-value [#^IMapEntry this] (let [v (.getValue this)] (delay v))) IPersistentVector (get-key [this] (when-not (= (count this) 2) (throw (IllegalArgumentException. "Vector used as IMapEntry must be a pair"))) (this 0)) (get-raw-value [this] (when-not (= (count this) 2) (throw (IllegalArgumentException. "Vector used as IMapEntry must be a pair"))) (let [v (this 1)] (delay v)))) (defprotocol ILazyPersistentMap "ILazyPersistentMap extends IPersistentMap with a method to allow transportation of the underlying delay objects." (delay-assoc [lazy-map key delay] "Associates the given delay in the map.")) (deftype LazyMapEntry [k v] ILazyMapEntry (get-key [_] k) (get-raw-value [_] v) IMapEntry (key [_] k) (getKey [_] k) (val [_] (deref v)) (getValue [_] (deref v)) Object (toString [_] (str \[ (pr-str k) \space (pr-str (deref v)) \]))) (defmethod print-method LazyMapEntry [this #^java.io.Writer w] (.write w (str this))) (defn create-lazy-map-seq ([inner-seq] (create-lazy-map-seq inner-seq nil)) ([inner-seq metadata] (proxy [ASeq] [metadata] ; ISeq (first [] (let [first-val (first inner-seq)] (LazyMapEntry. (key first-val) (val first-val)))) (next [] (when-let [inner-rest (next inner-seq)] (create-lazy-map-seq inner-rest metadata))) (more [] (lazy-seq (next this)))))) (declare create-lazy-map) (deftype LazyPersistentMap [base metadata] ILazyPersistentMap (delay-assoc [this k v] (create-lazy-map (assoc base k v) metadata)) IPersistentMap (assoc [this k v] (create-lazy-map (assoc base k (delay v)) metadata)) (assocEx [this k v] (when (contains? base k) (throw (Exception. (str "Key already present in map: " k)))) (.assoc this k v)) (without [this k] (create-lazy-map (dissoc base k) metadata)) ; Associative (containsKey [this k] (contains? base k)) (entryAt [this k] (when-let [v (base k)] (LazyMapEntry. k v))) ; IPersistentCollection (count [this] (count base)) (cons [this o] (if (satisfies? ILazyMapEntry o) (delay-assoc this (get-key o) (get-raw-value o)) (into this o))) (empty [this] (create-lazy-map (empty base) nil)) ILookup (valAt [this k] (.valAt this k nil)) (valAt [this k not-found] (if (contains? base k) (-> base (get k) deref) not-found)) IFn (invoke [this k] (.valAt this k nil)) (invoke [this k not-found] (.valAt this k not-found)) (applyTo [this args] (let [[k v & rest-args :as args] (seq args)] (when (or (not args) rest-args) (throw (Exception. "lazy map must be called with one or two arguments"))) (.valAt this k v))) Seqable (seq [this] (when-let [inner-seq (seq base)] (create-lazy-map-seq inner-seq))) IObj (withMeta [this new-metadata] (create-lazy-map base new-metadata)) ; IMeta (meta [this] metadata) Iterable (iterator [this] (-> this .seq SeqIterator.))) (defn create-lazy-map ([base] (create-lazy-map base nil)) ([base metadata] (LazyPersistentMap. base metadata))) (defn- quote-values [kvs] (assert (even? (count kvs))) (mapcat (fn [[k v]] [k `(delay ~v)]) (partition 2 kvs))) (defn lazy-assoc* "lazy-assoc* is like lazy-assoc but a function and takes values as delays instead of expanding into a delay of val." [m & kvs] (assert (even? (count kvs))) (reduce (fn [m [k v]] (delay-assoc m k v)) m (partition 2 kvs))) (defmacro lazy-assoc "lazy-assoc associates new values to the given keys in the given lazy map. The values are not evaluated, before their first retrieval. They are evaluated at most once." [m & kvs] `(lazy-assoc* ~m ~@(quote-values kvs))) (defn lazy-hash-map* "lazy-hash-map* is the same as lazy-hash-map except that its a function and it takes a seq of keys-delayed-value pairs." [& kvs] (create-lazy-map (apply hash-map kvs))) (defmacro lazy-hash-map "lazy-hash-map creates a map. The values are not evaluated before their first retrieval. Each value is evaluated at most once. The underlying map is a hash map." [& kvs] `(lazy-hash-map* ~@(quote-values kvs))) (defn lazy-sorted-map* "lazy-sorted-map* is the same as lazy-sorted-map except that its a function and it takes a seq of keys-delayed-value pairs." [& kvs] (create-lazy-map (apply sorted-map kvs))) (defmacro lazy-sorted-map "lazy-sorted-map creates a map. The values are not evaluated before their first retrieval. Each value is evaluated at most once. The underlying map is a sorted map." [& kvs] `(lazy-sorted-map* ~@(quote-values kvs))) (defn lazy-struct-map* "lazy-struct-map* is the same as lazy-struct-map except that its a function and it takes a seq of keys-delayed-value pairs together with the struct basis." [s & kvs] (create-lazy-map (apply struct-map s kvs))) (defmacro lazy-struct-map "lazy-struct-map creates a map. The values are not evaluated before their first retrieval. Each value is evaluated at most once. The underlying map is a struct map according to the provided structure s." [s & kvs] `(lazy-struct-map* ~s ~@(quote-values kvs))) (defn lazy-struct* "lazy-struct* is the same as lazy-struct except that its a function and it takes a seq of delayed value together with the struct basis." [s & vs] (create-lazy-map (apply struct s vs))) (defmacro lazy-struct "lazy-struct creates a map. The values are not evaluated before their first retrieval. Each value is evaluated at most once. The underlying map is a struct map according to the provided structure s. As with Clojure's struct the values have to appear in the order of the keys in the structure." [s & vs] (let [vs (map (fn [v] `(delay ~v)) vs)] `(lazy-struct* ~s ~@vs)))
106
;- ; Copyright 2008-2011 (c) <NAME>. ; All rights reserved. ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ; THE SOFTWARE. ;; Retreived from https://bitbucket.org/kotarak/lazymap/raw/5a2437e70a91/src/main/clojure/lazymap/core.clj ;; by JW on 11/17/2011, and slightly modified to fix a bug in .entryAt and add a safety check. ;; Also replaced 'force' with 'deref' so this can be used with futures (with marginal utility). ;; (our pull request with these changes has been been ignored, so we've just included ;; this fixed file in plumbing for the time being). ;; Known Issues: LazyMapEntries are not equal to persistent vectors like ordinary map entries. (ns plumbing.lazymap "Lazymap is to maps what lazy-seq is to lists. It allows to store values with evaluating them. This is only done in case the value is really accessed. Lazymap works with any map type (hash-map, sorted-map, struct-map) and may be used as a drop-in replacement everywhere where a normal map type may be used. Available macros: lazy-hash-map, lazy-sorted-map, lazy-struct-map, lazy-struct, lazy-assoc and their * counterpart functions." (:import clojure.lang.IObj clojure.lang.IFn clojure.lang.ILookup clojure.lang.IMapEntry clojure.lang.IPersistentMap clojure.lang.IPersistentVector clojure.lang.ASeq clojure.lang.ISeq clojure.lang.Seqable clojure.lang.SeqIterator)) (defprotocol ILazyMapEntry "ILazyMapEntry describes the behaviour of a lazy MapEntry. It provides an additional method (over IMapEntry), which returns the raw delay object and not the forced value." (get-key [lazy-map-entry] "Return the key of the map entry.") (get-raw-value [lazy-map-entry] "Return the underlying delay object.")) ; Extend the IMapEntry interface to act also like ILazyMapEntry. ; For a IMapEntry get-raw-value just returns the given value as ; wrapped in a delay. Similar a vector of two elements might be ; used in place of a IMapEntry. (extend-protocol ILazyMapEntry IMapEntry (get-key [#^IMapEntry this] (.getKey this)) (get-raw-value [#^IMapEntry this] (let [v (.getValue this)] (delay v))) IPersistentVector (get-key [this] (when-not (= (count this) 2) (throw (IllegalArgumentException. "Vector used as IMapEntry must be a pair"))) (this 0)) (get-raw-value [this] (when-not (= (count this) 2) (throw (IllegalArgumentException. "Vector used as IMapEntry must be a pair"))) (let [v (this 1)] (delay v)))) (defprotocol ILazyPersistentMap "ILazyPersistentMap extends IPersistentMap with a method to allow transportation of the underlying delay objects." (delay-assoc [lazy-map key delay] "Associates the given delay in the map.")) (deftype LazyMapEntry [k v] ILazyMapEntry (get-key [_] k) (get-raw-value [_] v) IMapEntry (key [_] k) (getKey [_] k) (val [_] (deref v)) (getValue [_] (deref v)) Object (toString [_] (str \[ (pr-str k) \space (pr-str (deref v)) \]))) (defmethod print-method LazyMapEntry [this #^java.io.Writer w] (.write w (str this))) (defn create-lazy-map-seq ([inner-seq] (create-lazy-map-seq inner-seq nil)) ([inner-seq metadata] (proxy [ASeq] [metadata] ; ISeq (first [] (let [first-val (first inner-seq)] (LazyMapEntry. (key first-val) (val first-val)))) (next [] (when-let [inner-rest (next inner-seq)] (create-lazy-map-seq inner-rest metadata))) (more [] (lazy-seq (next this)))))) (declare create-lazy-map) (deftype LazyPersistentMap [base metadata] ILazyPersistentMap (delay-assoc [this k v] (create-lazy-map (assoc base k v) metadata)) IPersistentMap (assoc [this k v] (create-lazy-map (assoc base k (delay v)) metadata)) (assocEx [this k v] (when (contains? base k) (throw (Exception. (str "Key already present in map: " k)))) (.assoc this k v)) (without [this k] (create-lazy-map (dissoc base k) metadata)) ; Associative (containsKey [this k] (contains? base k)) (entryAt [this k] (when-let [v (base k)] (LazyMapEntry. k v))) ; IPersistentCollection (count [this] (count base)) (cons [this o] (if (satisfies? ILazyMapEntry o) (delay-assoc this (get-key o) (get-raw-value o)) (into this o))) (empty [this] (create-lazy-map (empty base) nil)) ILookup (valAt [this k] (.valAt this k nil)) (valAt [this k not-found] (if (contains? base k) (-> base (get k) deref) not-found)) IFn (invoke [this k] (.valAt this k nil)) (invoke [this k not-found] (.valAt this k not-found)) (applyTo [this args] (let [[k v & rest-args :as args] (seq args)] (when (or (not args) rest-args) (throw (Exception. "lazy map must be called with one or two arguments"))) (.valAt this k v))) Seqable (seq [this] (when-let [inner-seq (seq base)] (create-lazy-map-seq inner-seq))) IObj (withMeta [this new-metadata] (create-lazy-map base new-metadata)) ; IMeta (meta [this] metadata) Iterable (iterator [this] (-> this .seq SeqIterator.))) (defn create-lazy-map ([base] (create-lazy-map base nil)) ([base metadata] (LazyPersistentMap. base metadata))) (defn- quote-values [kvs] (assert (even? (count kvs))) (mapcat (fn [[k v]] [k `(delay ~v)]) (partition 2 kvs))) (defn lazy-assoc* "lazy-assoc* is like lazy-assoc but a function and takes values as delays instead of expanding into a delay of val." [m & kvs] (assert (even? (count kvs))) (reduce (fn [m [k v]] (delay-assoc m k v)) m (partition 2 kvs))) (defmacro lazy-assoc "lazy-assoc associates new values to the given keys in the given lazy map. The values are not evaluated, before their first retrieval. They are evaluated at most once." [m & kvs] `(lazy-assoc* ~m ~@(quote-values kvs))) (defn lazy-hash-map* "lazy-hash-map* is the same as lazy-hash-map except that its a function and it takes a seq of keys-delayed-value pairs." [& kvs] (create-lazy-map (apply hash-map kvs))) (defmacro lazy-hash-map "lazy-hash-map creates a map. The values are not evaluated before their first retrieval. Each value is evaluated at most once. The underlying map is a hash map." [& kvs] `(lazy-hash-map* ~@(quote-values kvs))) (defn lazy-sorted-map* "lazy-sorted-map* is the same as lazy-sorted-map except that its a function and it takes a seq of keys-delayed-value pairs." [& kvs] (create-lazy-map (apply sorted-map kvs))) (defmacro lazy-sorted-map "lazy-sorted-map creates a map. The values are not evaluated before their first retrieval. Each value is evaluated at most once. The underlying map is a sorted map." [& kvs] `(lazy-sorted-map* ~@(quote-values kvs))) (defn lazy-struct-map* "lazy-struct-map* is the same as lazy-struct-map except that its a function and it takes a seq of keys-delayed-value pairs together with the struct basis." [s & kvs] (create-lazy-map (apply struct-map s kvs))) (defmacro lazy-struct-map "lazy-struct-map creates a map. The values are not evaluated before their first retrieval. Each value is evaluated at most once. The underlying map is a struct map according to the provided structure s." [s & kvs] `(lazy-struct-map* ~s ~@(quote-values kvs))) (defn lazy-struct* "lazy-struct* is the same as lazy-struct except that its a function and it takes a seq of delayed value together with the struct basis." [s & vs] (create-lazy-map (apply struct s vs))) (defmacro lazy-struct "lazy-struct creates a map. The values are not evaluated before their first retrieval. Each value is evaluated at most once. The underlying map is a struct map according to the provided structure s. As with Clojure's struct the values have to appear in the order of the keys in the structure." [s & vs] (let [vs (map (fn [v] `(delay ~v)) vs)] `(lazy-struct* ~s ~@vs)))
true
;- ; Copyright 2008-2011 (c) PI:NAME:<NAME>END_PI. ; All rights reserved. ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ; THE SOFTWARE. ;; Retreived from https://bitbucket.org/kotarak/lazymap/raw/5a2437e70a91/src/main/clojure/lazymap/core.clj ;; by JW on 11/17/2011, and slightly modified to fix a bug in .entryAt and add a safety check. ;; Also replaced 'force' with 'deref' so this can be used with futures (with marginal utility). ;; (our pull request with these changes has been been ignored, so we've just included ;; this fixed file in plumbing for the time being). ;; Known Issues: LazyMapEntries are not equal to persistent vectors like ordinary map entries. (ns plumbing.lazymap "Lazymap is to maps what lazy-seq is to lists. It allows to store values with evaluating them. This is only done in case the value is really accessed. Lazymap works with any map type (hash-map, sorted-map, struct-map) and may be used as a drop-in replacement everywhere where a normal map type may be used. Available macros: lazy-hash-map, lazy-sorted-map, lazy-struct-map, lazy-struct, lazy-assoc and their * counterpart functions." (:import clojure.lang.IObj clojure.lang.IFn clojure.lang.ILookup clojure.lang.IMapEntry clojure.lang.IPersistentMap clojure.lang.IPersistentVector clojure.lang.ASeq clojure.lang.ISeq clojure.lang.Seqable clojure.lang.SeqIterator)) (defprotocol ILazyMapEntry "ILazyMapEntry describes the behaviour of a lazy MapEntry. It provides an additional method (over IMapEntry), which returns the raw delay object and not the forced value." (get-key [lazy-map-entry] "Return the key of the map entry.") (get-raw-value [lazy-map-entry] "Return the underlying delay object.")) ; Extend the IMapEntry interface to act also like ILazyMapEntry. ; For a IMapEntry get-raw-value just returns the given value as ; wrapped in a delay. Similar a vector of two elements might be ; used in place of a IMapEntry. (extend-protocol ILazyMapEntry IMapEntry (get-key [#^IMapEntry this] (.getKey this)) (get-raw-value [#^IMapEntry this] (let [v (.getValue this)] (delay v))) IPersistentVector (get-key [this] (when-not (= (count this) 2) (throw (IllegalArgumentException. "Vector used as IMapEntry must be a pair"))) (this 0)) (get-raw-value [this] (when-not (= (count this) 2) (throw (IllegalArgumentException. "Vector used as IMapEntry must be a pair"))) (let [v (this 1)] (delay v)))) (defprotocol ILazyPersistentMap "ILazyPersistentMap extends IPersistentMap with a method to allow transportation of the underlying delay objects." (delay-assoc [lazy-map key delay] "Associates the given delay in the map.")) (deftype LazyMapEntry [k v] ILazyMapEntry (get-key [_] k) (get-raw-value [_] v) IMapEntry (key [_] k) (getKey [_] k) (val [_] (deref v)) (getValue [_] (deref v)) Object (toString [_] (str \[ (pr-str k) \space (pr-str (deref v)) \]))) (defmethod print-method LazyMapEntry [this #^java.io.Writer w] (.write w (str this))) (defn create-lazy-map-seq ([inner-seq] (create-lazy-map-seq inner-seq nil)) ([inner-seq metadata] (proxy [ASeq] [metadata] ; ISeq (first [] (let [first-val (first inner-seq)] (LazyMapEntry. (key first-val) (val first-val)))) (next [] (when-let [inner-rest (next inner-seq)] (create-lazy-map-seq inner-rest metadata))) (more [] (lazy-seq (next this)))))) (declare create-lazy-map) (deftype LazyPersistentMap [base metadata] ILazyPersistentMap (delay-assoc [this k v] (create-lazy-map (assoc base k v) metadata)) IPersistentMap (assoc [this k v] (create-lazy-map (assoc base k (delay v)) metadata)) (assocEx [this k v] (when (contains? base k) (throw (Exception. (str "Key already present in map: " k)))) (.assoc this k v)) (without [this k] (create-lazy-map (dissoc base k) metadata)) ; Associative (containsKey [this k] (contains? base k)) (entryAt [this k] (when-let [v (base k)] (LazyMapEntry. k v))) ; IPersistentCollection (count [this] (count base)) (cons [this o] (if (satisfies? ILazyMapEntry o) (delay-assoc this (get-key o) (get-raw-value o)) (into this o))) (empty [this] (create-lazy-map (empty base) nil)) ILookup (valAt [this k] (.valAt this k nil)) (valAt [this k not-found] (if (contains? base k) (-> base (get k) deref) not-found)) IFn (invoke [this k] (.valAt this k nil)) (invoke [this k not-found] (.valAt this k not-found)) (applyTo [this args] (let [[k v & rest-args :as args] (seq args)] (when (or (not args) rest-args) (throw (Exception. "lazy map must be called with one or two arguments"))) (.valAt this k v))) Seqable (seq [this] (when-let [inner-seq (seq base)] (create-lazy-map-seq inner-seq))) IObj (withMeta [this new-metadata] (create-lazy-map base new-metadata)) ; IMeta (meta [this] metadata) Iterable (iterator [this] (-> this .seq SeqIterator.))) (defn create-lazy-map ([base] (create-lazy-map base nil)) ([base metadata] (LazyPersistentMap. base metadata))) (defn- quote-values [kvs] (assert (even? (count kvs))) (mapcat (fn [[k v]] [k `(delay ~v)]) (partition 2 kvs))) (defn lazy-assoc* "lazy-assoc* is like lazy-assoc but a function and takes values as delays instead of expanding into a delay of val." [m & kvs] (assert (even? (count kvs))) (reduce (fn [m [k v]] (delay-assoc m k v)) m (partition 2 kvs))) (defmacro lazy-assoc "lazy-assoc associates new values to the given keys in the given lazy map. The values are not evaluated, before their first retrieval. They are evaluated at most once." [m & kvs] `(lazy-assoc* ~m ~@(quote-values kvs))) (defn lazy-hash-map* "lazy-hash-map* is the same as lazy-hash-map except that its a function and it takes a seq of keys-delayed-value pairs." [& kvs] (create-lazy-map (apply hash-map kvs))) (defmacro lazy-hash-map "lazy-hash-map creates a map. The values are not evaluated before their first retrieval. Each value is evaluated at most once. The underlying map is a hash map." [& kvs] `(lazy-hash-map* ~@(quote-values kvs))) (defn lazy-sorted-map* "lazy-sorted-map* is the same as lazy-sorted-map except that its a function and it takes a seq of keys-delayed-value pairs." [& kvs] (create-lazy-map (apply sorted-map kvs))) (defmacro lazy-sorted-map "lazy-sorted-map creates a map. The values are not evaluated before their first retrieval. Each value is evaluated at most once. The underlying map is a sorted map." [& kvs] `(lazy-sorted-map* ~@(quote-values kvs))) (defn lazy-struct-map* "lazy-struct-map* is the same as lazy-struct-map except that its a function and it takes a seq of keys-delayed-value pairs together with the struct basis." [s & kvs] (create-lazy-map (apply struct-map s kvs))) (defmacro lazy-struct-map "lazy-struct-map creates a map. The values are not evaluated before their first retrieval. Each value is evaluated at most once. The underlying map is a struct map according to the provided structure s." [s & kvs] `(lazy-struct-map* ~s ~@(quote-values kvs))) (defn lazy-struct* "lazy-struct* is the same as lazy-struct except that its a function and it takes a seq of delayed value together with the struct basis." [s & vs] (create-lazy-map (apply struct s vs))) (defmacro lazy-struct "lazy-struct creates a map. The values are not evaluated before their first retrieval. Each value is evaluated at most once. The underlying map is a struct map according to the provided structure s. As with Clojure's struct the values have to appear in the order of the keys in the structure." [s & vs] (let [vs (map (fn [v] `(delay ~v)) vs)] `(lazy-struct* ~s ~@vs)))
[ { "context": " (test-util/route-response {:id \"B20\" :name \"Batman\"})}\n (let [response (execute-query uri \"from", "end": 710, "score": 0.9985523223876953, "start": 704, "tag": "NAME", "value": "Batman" }, { "context": "query uri \"from hero only name\")]\n (is (= \"Batman\" (get-in response [:hero :result :name])))\n ", "end": 801, "score": 0.9982714056968689, "start": 795, "tag": "NAME", "value": "Batman" }, { "context": " (test-util/route-response {:id \"B10\" :name \"Batman\"})\n (test-util/route-request \"/he", "end": 1065, "score": 0.9983990788459778, "start": 1059, "tag": "NAME", "value": "Batman" }, { "context": " (test-util/route-response {:id \"B20\" :name \"Robin\"})}\n (let [response (execute-query uri \"from", "end": 1194, "score": 0.9992774724960327, "start": 1189, "tag": "NAME", "value": "Robin" }, { "context": "= nil (:id (first result))))\n (is (= \"Batman\" (:name (first result))))\n (is (= nil ", "end": 1401, "score": 0.9960641264915466, "start": 1395, "tag": "NAME", "value": "Batman" }, { "context": " nil (:id (second result))))\n (is (= \"Robin\" (:name (second result)))))))\n\n(deftest array-fi", "end": 1497, "score": 0.9993818402290344, "start": 1492, "tag": "NAME", "value": "Robin" }, { "context": "til/route-response {:id \"B10\" :sidekicks [{:name \"Robin\"} {:name \"Alfred\"}]})}\n (let [response (exec", "end": 1682, "score": 0.9995315074920654, "start": 1677, "tag": "NAME", "value": "Robin" }, { "context": "se {:id \"B10\" :sidekicks [{:name \"Robin\"} {:name \"Alfred\"}]})}\n (let [response (execute-query uri \"fr", "end": 1699, "score": 0.999686062335968, "start": 1693, "tag": "NAME", "value": "Alfred" }, { "context": " (first (:sidekicks result)))))\n (is (= \"Robin\" (:name (first (:sidekicks result)))))\n ", "end": 1913, "score": 0.9996780157089233, "start": 1908, "tag": "NAME", "value": "Robin" }, { "context": "(second (:sidekicks result)))))\n (is (= \"Alfred\" (:name (second (:sidekicks result))))))))\n\n(deft", "end": 2035, "score": 0.9996622204780579, "start": 2029, "tag": "NAME", "value": "Alfred" }, { "context": " (test-util/route-response [{:id \"B10\" :name \"Batman\"} {:id \"B20\" :name \"Robin\"}])\n (t", "end": 2241, "score": 0.9992949962615967, "start": 2235, "tag": "NAME", "value": "Batman" }, { "context": "nse [{:id \"B10\" :name \"Batman\"} {:id \"B20\" :name \"Robin\"}])\n (test-util/route-request \"/h", "end": 2267, "score": 0.999664306640625, "start": 2262, "tag": "NAME", "value": "Robin" }, { "context": " (test-util/route-response [{:id \"B30\" :name \"Superman\"} {:id \"B40\" :name \"Superwoman\"}])}\n (let [res", "end": 2403, "score": 0.9938572645187378, "start": 2395, "tag": "NAME", "value": "Superman" }, { "context": "e [{:id \"B30\" :name \"Superman\"} {:id \"B40\" :name \"Superwoman\"}])}\n (let [response (execute-query uri \"", "end": 2429, "score": 0.8252850770950317, "start": 2424, "tag": "NAME", "value": "Super" }, { "context": " (:id (first first-request))))\n (is (= \"Batman\" (:name (first first-request))))\n (is (= nil", "end": 2728, "score": 0.9989835619926453, "start": 2722, "tag": "NAME", "value": "Batman" }, { "context": " (:id (second first-request))))\n (is (= \"Robin\" (:name (second first-request))))\n\n (is (= ", "end": 2834, "score": 0.9993228912353516, "start": 2829, "tag": "NAME", "value": "Robin" }, { "context": " (:id (first second-request))))\n (is (= \"Superman\" (:name (first second-request))))\n (is (= ", "end": 2950, "score": 0.9818987250328064, "start": 2942, "tag": "NAME", "value": "Superman" }, { "context": " (:id (second second-request))))\n (is (= \"Superwoman\" (:name (second second-request)))))))\n\n(deft", "end": 3064, "score": 0.5147143006324768, "start": 3059, "tag": "NAME", "value": "Super" }, { "context": " (test-util/route-response {:id \"B10\" :name \"Batman\"})\n (test-util/route-request \"/he", "end": 3391, "score": 0.9992759227752686, "start": 3385, "tag": "NAME", "value": "Batman" }, { "context": " (test-util/route-response {:id \"B10\" :name \"Robin\"})}\n (let [response (execute-query uri \"from h", "end": 3524, "score": 0.9998247623443604, "start": 3519, "tag": "NAME", "value": "Robin" }, { "context": "et-in response [:hero :result])))))\n (is (= \"Batman\" (:name (first (get-in response [:hero :result]))", "end": 3718, "score": 0.999748706817627, "start": 3712, "tag": "NAME", "value": "Batman" }, { "context": "et-in response [:hero :result])))))\n (is (= \"Robin\" (:name (second (get-in response [:hero :result]", "end": 3864, "score": 0.9998259544372559, "start": 3859, "tag": "NAME", "value": "Robin" }, { "context": " (test-util/route-response {:id \"B10\" :name \"Batman\" :sidekicks [{:name \"Catwoman\"}]})\n ", "end": 4216, "score": 0.9920602440834045, "start": 4210, "tag": "NAME", "value": "Batman" }, { "context": "nse {:id \"B10\" :name \"Batman\" :sidekicks [{:name \"Catwoman\"}]})\n (test-util/route-request \"/", "end": 4246, "score": 0.6072099208831787, "start": 4238, "tag": "NAME", "value": "Catwoman" }, { "context": " (test-util/route-response {:id \"B20\" :name \"Robin\" :sidekicks [{:name \"Alfred\"}]})\n ", "end": 4381, "score": 0.9997438192367554, "start": 4376, "tag": "NAME", "value": "Robin" }, { "context": "onse {:id \"B20\" :name \"Robin\" :sidekicks [{:name \"Alfred\"}]})\n (test-util/route-request \"/", "end": 4409, "score": 0.999346911907196, "start": 4403, "tag": "NAME", "value": "Alfred" }, { "context": " (test-util/route-request \"/sidekick\" {:name \"Catwoman\"})\n (test-util/route-response {:i", "end": 4485, "score": 0.5392321348190308, "start": 4480, "tag": "NAME", "value": "woman" }, { "context": " (test-util/route-response {:id \"S10\" :name \"Catwoman\" :movie \"Batman\"})\n (test-uti", "end": 4554, "score": 0.7531313896179199, "start": 4550, "tag": "NAME", "value": "Catw" }, { "context": "oute-response {:id \"S10\" :name \"Catwoman\" :movie \"Batman\"})\n (test-util/route-request \"/si", "end": 4574, "score": 0.599675714969635, "start": 4568, "tag": "NAME", "value": "Batman" }, { "context": " (test-util/route-request \"/sidekick\" {:name \"Alfred\"})\n (test-util/route-response {:i", "end": 4646, "score": 0.9995710849761963, "start": 4640, "tag": "NAME", "value": "Alfred" }, { "context": " (test-util/route-response {:id \"S20\" :name \"Alfred\" :movie \"Batman\"})}\n (let [response (execute-q", "end": 4717, "score": 0.9997156262397766, "start": 4711, "tag": "NAME", "value": "Alfred" }, { "context": "/route-response {:id \"S20\" :name \"Alfred\" :movie \"Batman\"})}\n (let [response (execute-query uri \"from h", "end": 4733, "score": 0.9247156977653503, "start": 4727, "tag": "NAME", "value": "Batman" }, { "context": " only id, name\")]\n (is (= [[{:name \"Batman\"} {:name \"Robin\"}]\n [{:name \"Batman\"", "end": 5233, "score": 0.9997798800468445, "start": 5227, "tag": "NAME", "value": "Batman" }, { "context": ", name\")]\n (is (= [[{:name \"Batman\"} {:name \"Robin\"}]\n [{:name \"Batman\"} {:name \"Robin\"", "end": 5249, "score": 0.9998235702514648, "start": 5244, "tag": "NAME", "value": "Robin" }, { "context": "\"Batman\"} {:name \"Robin\"}]\n [{:name \"Batman\"} {:name \"Robin\"}]] (get-in response [:hero :resu", "end": 5282, "score": 0.9998030662536621, "start": 5276, "tag": "NAME", "value": "Batman" }, { "context": "\"Robin\"}]\n [{:name \"Batman\"} {:name \"Robin\"}]] (get-in response [:hero :result])))\n (is", "end": 5298, "score": 0.9998297691345215, "start": 5293, "tag": "NAME", "value": "Robin" }, { "context": " (is (= [[[{:name \"Catwoman\" :id \"S10\"}] [{:name \"Alfred\" :id \"S20\"}]]\n [[{:name \"Catwoman\" :", "end": 5400, "score": 0.9998108744621277, "start": 5394, "tag": "NAME", "value": "Alfred" }, { "context": " [[{:name \"Catwoman\" :id \"S10\"}] [{:name \"Alfred\" :id \"S20\"}]]] (get-in response [:sidekick :resul", "end": 5476, "score": 0.9998176693916321, "start": 5470, "tag": "NAME", "value": "Alfred" } ]
test/integration/restql/filter_test.clj
MachadoLhes/restQL-core
2
(ns restql.filter-test (:require [clojure.test :refer [deftest is]] [restql.core.api.restql :as restql] [restql.test-util :as test-util] [cheshire.core :as json] [stub-http.core :refer :all] [clojure.pprint :refer :all])) (defn execute-query [baseUrl query] (restql/execute-query :mappings {:hero (str baseUrl "/hero") :sidekick (str baseUrl "/sidekick") :heroes (str baseUrl "/heroes")} :query query)) (deftest simple-filter (with-routes! {(test-util/route-request "/hero") (test-util/route-response {:id "B20" :name "Batman"})} (let [response (execute-query uri "from hero only name")] (is (= "Batman" (get-in response [:hero :result :name]))) (is (= nil (get-in response [:hero :result :id])))))) (deftest multiplex-filter (with-routes! {(test-util/route-request "/hero" {:id 1}) (test-util/route-response {:id "B10" :name "Batman"}) (test-util/route-request "/hero" {:id 2}) (test-util/route-response {:id "B20" :name "Robin"})} (let [response (execute-query uri "from hero with id = [1,2] only name") result (get-in response [:hero :result])] (is (= nil (:id (first result)))) (is (= "Batman" (:name (first result)))) (is (= nil (:id (second result)))) (is (= "Robin" (:name (second result))))))) (deftest array-filter (with-routes! {(test-util/route-request "/hero") (test-util/route-response {:id "B10" :sidekicks [{:name "Robin"} {:name "Alfred"}]})} (let [response (execute-query uri "from hero only sidekicks.name") result (get-in response [:hero :result])] (is (= nil (:id (first (:sidekicks result))))) (is (= "Robin" (:name (first (:sidekicks result))))) (is (= nil (:id (second (:sidekicks result))))) (is (= "Alfred" (:name (second (:sidekicks result)))))))) (deftest array-multiplex-filter (with-routes! {(test-util/route-request "/heroes" {:id 1}) (test-util/route-response [{:id "B10" :name "Batman"} {:id "B20" :name "Robin"}]) (test-util/route-request "/heroes" {:id 2}) (test-util/route-response [{:id "B30" :name "Superman"} {:id "B40" :name "Superwoman"}])} (let [response (execute-query uri "from heroes with id=[1,2] only name") first-request (first (get-in response [:heroes :result])) second-request (second (get-in response [:heroes :result]))] (is (= nil (:id (first first-request)))) (is (= "Batman" (:name (first first-request)))) (is (= nil (:id (second first-request)))) (is (= "Robin" (:name (second first-request)))) (is (= nil (:id (first second-request)))) (is (= "Superman" (:name (first second-request)))) (is (= nil (:id (second second-request)))) (is (= "Superwoman" (:name (second second-request))))))) (deftest multiplex-with-list (with-routes! {(test-util/route-request "/heroes") (test-util/route-response [{:id "B10"} {:id "B20"}]) (test-util/route-request "/hero" {:id "B10"}) (test-util/route-response {:id "B10" :name "Batman"}) (test-util/route-request "/hero" {:id "B20"}) (test-util/route-response {:id "B10" :name "Robin"})} (let [response (execute-query uri "from heroes \n from hero with id = heroes.id only name")] (is (= nil (:id (first (get-in response [:hero :result]))))) (is (= "Batman" (:name (first (get-in response [:hero :result]))))) (is (= nil (:id (second (get-in response [:hero :result]))))) (is (= "Robin" (:name (second (get-in response [:hero :result])))))))) (deftest multiplex-with-list (with-routes! {(test-util/route-request "/heroes") (test-util/route-response {:heroes [{:id "B10"} {:id "B20"}]}) (test-util/route-request "/hero" {:id "B10"}) (test-util/route-response {:id "B10" :name "Batman" :sidekicks [{:name "Catwoman"}]}) (test-util/route-request "/hero" {:id "B20"}) (test-util/route-response {:id "B20" :name "Robin" :sidekicks [{:name "Alfred"}]}) (test-util/route-request "/sidekick" {:name "Catwoman"}) (test-util/route-response {:id "S10" :name "Catwoman" :movie "Batman"}) (test-util/route-request "/sidekick" {:name "Alfred"}) (test-util/route-response {:id "S20" :name "Alfred" :movie "Batman"})} (let [response (execute-query uri "from heroes with id = [1,2] \n from hero with id = heroes.heroes.id only name \n from sidekick with name = hero.sidekicks.name only id, name")] (is (= [[{:name "Batman"} {:name "Robin"}] [{:name "Batman"} {:name "Robin"}]] (get-in response [:hero :result]))) (is (= [[[{:name "Catwoman" :id "S10"}] [{:name "Alfred" :id "S20"}]] [[{:name "Catwoman" :id "S10"}] [{:name "Alfred" :id "S20"}]]] (get-in response [:sidekick :result]))))))
10194
(ns restql.filter-test (:require [clojure.test :refer [deftest is]] [restql.core.api.restql :as restql] [restql.test-util :as test-util] [cheshire.core :as json] [stub-http.core :refer :all] [clojure.pprint :refer :all])) (defn execute-query [baseUrl query] (restql/execute-query :mappings {:hero (str baseUrl "/hero") :sidekick (str baseUrl "/sidekick") :heroes (str baseUrl "/heroes")} :query query)) (deftest simple-filter (with-routes! {(test-util/route-request "/hero") (test-util/route-response {:id "B20" :name "<NAME>"})} (let [response (execute-query uri "from hero only name")] (is (= "<NAME>" (get-in response [:hero :result :name]))) (is (= nil (get-in response [:hero :result :id])))))) (deftest multiplex-filter (with-routes! {(test-util/route-request "/hero" {:id 1}) (test-util/route-response {:id "B10" :name "<NAME>"}) (test-util/route-request "/hero" {:id 2}) (test-util/route-response {:id "B20" :name "<NAME>"})} (let [response (execute-query uri "from hero with id = [1,2] only name") result (get-in response [:hero :result])] (is (= nil (:id (first result)))) (is (= "<NAME>" (:name (first result)))) (is (= nil (:id (second result)))) (is (= "<NAME>" (:name (second result))))))) (deftest array-filter (with-routes! {(test-util/route-request "/hero") (test-util/route-response {:id "B10" :sidekicks [{:name "<NAME>"} {:name "<NAME>"}]})} (let [response (execute-query uri "from hero only sidekicks.name") result (get-in response [:hero :result])] (is (= nil (:id (first (:sidekicks result))))) (is (= "<NAME>" (:name (first (:sidekicks result))))) (is (= nil (:id (second (:sidekicks result))))) (is (= "<NAME>" (:name (second (:sidekicks result)))))))) (deftest array-multiplex-filter (with-routes! {(test-util/route-request "/heroes" {:id 1}) (test-util/route-response [{:id "B10" :name "<NAME>"} {:id "B20" :name "<NAME>"}]) (test-util/route-request "/heroes" {:id 2}) (test-util/route-response [{:id "B30" :name "<NAME>"} {:id "B40" :name "<NAME>woman"}])} (let [response (execute-query uri "from heroes with id=[1,2] only name") first-request (first (get-in response [:heroes :result])) second-request (second (get-in response [:heroes :result]))] (is (= nil (:id (first first-request)))) (is (= "<NAME>" (:name (first first-request)))) (is (= nil (:id (second first-request)))) (is (= "<NAME>" (:name (second first-request)))) (is (= nil (:id (first second-request)))) (is (= "<NAME>" (:name (first second-request)))) (is (= nil (:id (second second-request)))) (is (= "<NAME>woman" (:name (second second-request))))))) (deftest multiplex-with-list (with-routes! {(test-util/route-request "/heroes") (test-util/route-response [{:id "B10"} {:id "B20"}]) (test-util/route-request "/hero" {:id "B10"}) (test-util/route-response {:id "B10" :name "<NAME>"}) (test-util/route-request "/hero" {:id "B20"}) (test-util/route-response {:id "B10" :name "<NAME>"})} (let [response (execute-query uri "from heroes \n from hero with id = heroes.id only name")] (is (= nil (:id (first (get-in response [:hero :result]))))) (is (= "<NAME>" (:name (first (get-in response [:hero :result]))))) (is (= nil (:id (second (get-in response [:hero :result]))))) (is (= "<NAME>" (:name (second (get-in response [:hero :result])))))))) (deftest multiplex-with-list (with-routes! {(test-util/route-request "/heroes") (test-util/route-response {:heroes [{:id "B10"} {:id "B20"}]}) (test-util/route-request "/hero" {:id "B10"}) (test-util/route-response {:id "B10" :name "<NAME>" :sidekicks [{:name "<NAME>"}]}) (test-util/route-request "/hero" {:id "B20"}) (test-util/route-response {:id "B20" :name "<NAME>" :sidekicks [{:name "<NAME>"}]}) (test-util/route-request "/sidekick" {:name "Cat<NAME>"}) (test-util/route-response {:id "S10" :name "<NAME>oman" :movie "<NAME>"}) (test-util/route-request "/sidekick" {:name "<NAME>"}) (test-util/route-response {:id "S20" :name "<NAME>" :movie "<NAME>"})} (let [response (execute-query uri "from heroes with id = [1,2] \n from hero with id = heroes.heroes.id only name \n from sidekick with name = hero.sidekicks.name only id, name")] (is (= [[{:name "<NAME>"} {:name "<NAME>"}] [{:name "<NAME>"} {:name "<NAME>"}]] (get-in response [:hero :result]))) (is (= [[[{:name "Catwoman" :id "S10"}] [{:name "<NAME>" :id "S20"}]] [[{:name "Catwoman" :id "S10"}] [{:name "<NAME>" :id "S20"}]]] (get-in response [:sidekick :result]))))))
true
(ns restql.filter-test (:require [clojure.test :refer [deftest is]] [restql.core.api.restql :as restql] [restql.test-util :as test-util] [cheshire.core :as json] [stub-http.core :refer :all] [clojure.pprint :refer :all])) (defn execute-query [baseUrl query] (restql/execute-query :mappings {:hero (str baseUrl "/hero") :sidekick (str baseUrl "/sidekick") :heroes (str baseUrl "/heroes")} :query query)) (deftest simple-filter (with-routes! {(test-util/route-request "/hero") (test-util/route-response {:id "B20" :name "PI:NAME:<NAME>END_PI"})} (let [response (execute-query uri "from hero only name")] (is (= "PI:NAME:<NAME>END_PI" (get-in response [:hero :result :name]))) (is (= nil (get-in response [:hero :result :id])))))) (deftest multiplex-filter (with-routes! {(test-util/route-request "/hero" {:id 1}) (test-util/route-response {:id "B10" :name "PI:NAME:<NAME>END_PI"}) (test-util/route-request "/hero" {:id 2}) (test-util/route-response {:id "B20" :name "PI:NAME:<NAME>END_PI"})} (let [response (execute-query uri "from hero with id = [1,2] only name") result (get-in response [:hero :result])] (is (= nil (:id (first result)))) (is (= "PI:NAME:<NAME>END_PI" (:name (first result)))) (is (= nil (:id (second result)))) (is (= "PI:NAME:<NAME>END_PI" (:name (second result))))))) (deftest array-filter (with-routes! {(test-util/route-request "/hero") (test-util/route-response {:id "B10" :sidekicks [{:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"}]})} (let [response (execute-query uri "from hero only sidekicks.name") result (get-in response [:hero :result])] (is (= nil (:id (first (:sidekicks result))))) (is (= "PI:NAME:<NAME>END_PI" (:name (first (:sidekicks result))))) (is (= nil (:id (second (:sidekicks result))))) (is (= "PI:NAME:<NAME>END_PI" (:name (second (:sidekicks result)))))))) (deftest array-multiplex-filter (with-routes! {(test-util/route-request "/heroes" {:id 1}) (test-util/route-response [{:id "B10" :name "PI:NAME:<NAME>END_PI"} {:id "B20" :name "PI:NAME:<NAME>END_PI"}]) (test-util/route-request "/heroes" {:id 2}) (test-util/route-response [{:id "B30" :name "PI:NAME:<NAME>END_PI"} {:id "B40" :name "PI:NAME:<NAME>END_PIwoman"}])} (let [response (execute-query uri "from heroes with id=[1,2] only name") first-request (first (get-in response [:heroes :result])) second-request (second (get-in response [:heroes :result]))] (is (= nil (:id (first first-request)))) (is (= "PI:NAME:<NAME>END_PI" (:name (first first-request)))) (is (= nil (:id (second first-request)))) (is (= "PI:NAME:<NAME>END_PI" (:name (second first-request)))) (is (= nil (:id (first second-request)))) (is (= "PI:NAME:<NAME>END_PI" (:name (first second-request)))) (is (= nil (:id (second second-request)))) (is (= "PI:NAME:<NAME>END_PIwoman" (:name (second second-request))))))) (deftest multiplex-with-list (with-routes! {(test-util/route-request "/heroes") (test-util/route-response [{:id "B10"} {:id "B20"}]) (test-util/route-request "/hero" {:id "B10"}) (test-util/route-response {:id "B10" :name "PI:NAME:<NAME>END_PI"}) (test-util/route-request "/hero" {:id "B20"}) (test-util/route-response {:id "B10" :name "PI:NAME:<NAME>END_PI"})} (let [response (execute-query uri "from heroes \n from hero with id = heroes.id only name")] (is (= nil (:id (first (get-in response [:hero :result]))))) (is (= "PI:NAME:<NAME>END_PI" (:name (first (get-in response [:hero :result]))))) (is (= nil (:id (second (get-in response [:hero :result]))))) (is (= "PI:NAME:<NAME>END_PI" (:name (second (get-in response [:hero :result])))))))) (deftest multiplex-with-list (with-routes! {(test-util/route-request "/heroes") (test-util/route-response {:heroes [{:id "B10"} {:id "B20"}]}) (test-util/route-request "/hero" {:id "B10"}) (test-util/route-response {:id "B10" :name "PI:NAME:<NAME>END_PI" :sidekicks [{:name "PI:NAME:<NAME>END_PI"}]}) (test-util/route-request "/hero" {:id "B20"}) (test-util/route-response {:id "B20" :name "PI:NAME:<NAME>END_PI" :sidekicks [{:name "PI:NAME:<NAME>END_PI"}]}) (test-util/route-request "/sidekick" {:name "CatPI:NAME:<NAME>END_PI"}) (test-util/route-response {:id "S10" :name "PI:NAME:<NAME>END_PIoman" :movie "PI:NAME:<NAME>END_PI"}) (test-util/route-request "/sidekick" {:name "PI:NAME:<NAME>END_PI"}) (test-util/route-response {:id "S20" :name "PI:NAME:<NAME>END_PI" :movie "PI:NAME:<NAME>END_PI"})} (let [response (execute-query uri "from heroes with id = [1,2] \n from hero with id = heroes.heroes.id only name \n from sidekick with name = hero.sidekicks.name only id, name")] (is (= [[{:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"}] [{:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"}]] (get-in response [:hero :result]))) (is (= [[[{:name "Catwoman" :id "S10"}] [{:name "PI:NAME:<NAME>END_PI" :id "S20"}]] [[{:name "Catwoman" :id "S10"}] [{:name "PI:NAME:<NAME>END_PI" :id "S20"}]]] (get-in response [:sidekick :result]))))))
[ { "context": ";; Copyright 2011, Alex Miller, Apache 2 license\n(ns clojure-life.life-seq)\n\n;;;", "end": 30, "score": 0.9997962117195129, "start": 19, "tag": "NAME", "value": "Alex Miller" } ]
src/clojure_life/life_seq.clj
puredanger/clojure-life
1
;; Copyright 2011, Alex Miller, Apache 2 license (ns clojure-life.life-seq) ;;;; Data structure manipulation ;; The world is represented by a vector of vector of booleans. ;; Both rows and columns wrap around to the other side. (defn rows [world] (count world)) (defn cols [world] (count (first world))) (defn alive? [world r c] (boolean (get-in world [(mod r (rows world)) (mod c (cols world))]))) (defn mark-alive [world [row col]] (update-in world [row col] (constantly true))) (defn init-world "Create a new world. rc-pairs is a seq of [row col] of cells to initially mark alive." [rows cols & rc-pairs] (reduce mark-alive (vec (repeat rows (vec (repeat cols false)))) rc-pairs)) ;; data structure functions below this point don't need to understand ;; internal structure of the world data (defn world-seq "Retrieve a seq of every cell in the world as [row col alive?]." [world] (for [row (range (rows world)) col (range (cols world))] [row col (alive? world row col)])) (defn render [world] (apply str (flatten (for [row (range (rows world))] [(for [col (range (cols world))] (if (alive? world row col) \# \.)) \newline])))) (defn neighbors "Get neighbor count at row-column position in world." [world r c] {:post [(<= 0 % 8)]} (count (filter true? (for [row (range (dec r) (+ r 2)) col (range (dec c) (+ c 2)) :when (not (and (= row r) (= col c)))] (alive? world row col))))) (defn map-world "Map a rule-fn over every cell in the world. The rule-fn should be of the form: (fn [row col alive? neighbor-count]) -> boolean" [rule-fn world] (->> (world-seq world) (filter (fn [[row col alive]] (when (rule-fn row col alive (neighbors world row col)) [row col]))) (apply init-world (rows world) (cols world)))) ;;;; Apply the life rules using the "world" data structure (defn life-rule "Determine whether a cell should live in the next tick based the current value and the neighbor count." [row col alive neighbor-count] (if alive (<= 2 neighbor-count 3) (= neighbor-count 3))) (defn update-world "Take world and compute new world based on the life function." [world] (map-world life-rule world)) ;;;; Main entry (defn life "Starting with an initial world, compute specified iterations." [init-world iterations] (loop [remaining-iterations iterations world init-world] (if (= 0 remaining-iterations) (println "Simulation complete.") (do (println) (println "Iteration" (- iterations remaining-iterations) ":") (print (render world)) (recur (dec remaining-iterations) (update-world world)))))) ;;;; Test with glider (defn test-glider "Return initial world with a glider prepped." [] (let [iters 10 glider-world (init-world 10 10 [1 3] [2 1] [2 3] [3 2] [3 3])] (life glider-world iters)))
42004
;; Copyright 2011, <NAME>, Apache 2 license (ns clojure-life.life-seq) ;;;; Data structure manipulation ;; The world is represented by a vector of vector of booleans. ;; Both rows and columns wrap around to the other side. (defn rows [world] (count world)) (defn cols [world] (count (first world))) (defn alive? [world r c] (boolean (get-in world [(mod r (rows world)) (mod c (cols world))]))) (defn mark-alive [world [row col]] (update-in world [row col] (constantly true))) (defn init-world "Create a new world. rc-pairs is a seq of [row col] of cells to initially mark alive." [rows cols & rc-pairs] (reduce mark-alive (vec (repeat rows (vec (repeat cols false)))) rc-pairs)) ;; data structure functions below this point don't need to understand ;; internal structure of the world data (defn world-seq "Retrieve a seq of every cell in the world as [row col alive?]." [world] (for [row (range (rows world)) col (range (cols world))] [row col (alive? world row col)])) (defn render [world] (apply str (flatten (for [row (range (rows world))] [(for [col (range (cols world))] (if (alive? world row col) \# \.)) \newline])))) (defn neighbors "Get neighbor count at row-column position in world." [world r c] {:post [(<= 0 % 8)]} (count (filter true? (for [row (range (dec r) (+ r 2)) col (range (dec c) (+ c 2)) :when (not (and (= row r) (= col c)))] (alive? world row col))))) (defn map-world "Map a rule-fn over every cell in the world. The rule-fn should be of the form: (fn [row col alive? neighbor-count]) -> boolean" [rule-fn world] (->> (world-seq world) (filter (fn [[row col alive]] (when (rule-fn row col alive (neighbors world row col)) [row col]))) (apply init-world (rows world) (cols world)))) ;;;; Apply the life rules using the "world" data structure (defn life-rule "Determine whether a cell should live in the next tick based the current value and the neighbor count." [row col alive neighbor-count] (if alive (<= 2 neighbor-count 3) (= neighbor-count 3))) (defn update-world "Take world and compute new world based on the life function." [world] (map-world life-rule world)) ;;;; Main entry (defn life "Starting with an initial world, compute specified iterations." [init-world iterations] (loop [remaining-iterations iterations world init-world] (if (= 0 remaining-iterations) (println "Simulation complete.") (do (println) (println "Iteration" (- iterations remaining-iterations) ":") (print (render world)) (recur (dec remaining-iterations) (update-world world)))))) ;;;; Test with glider (defn test-glider "Return initial world with a glider prepped." [] (let [iters 10 glider-world (init-world 10 10 [1 3] [2 1] [2 3] [3 2] [3 3])] (life glider-world iters)))
true
;; Copyright 2011, PI:NAME:<NAME>END_PI, Apache 2 license (ns clojure-life.life-seq) ;;;; Data structure manipulation ;; The world is represented by a vector of vector of booleans. ;; Both rows and columns wrap around to the other side. (defn rows [world] (count world)) (defn cols [world] (count (first world))) (defn alive? [world r c] (boolean (get-in world [(mod r (rows world)) (mod c (cols world))]))) (defn mark-alive [world [row col]] (update-in world [row col] (constantly true))) (defn init-world "Create a new world. rc-pairs is a seq of [row col] of cells to initially mark alive." [rows cols & rc-pairs] (reduce mark-alive (vec (repeat rows (vec (repeat cols false)))) rc-pairs)) ;; data structure functions below this point don't need to understand ;; internal structure of the world data (defn world-seq "Retrieve a seq of every cell in the world as [row col alive?]." [world] (for [row (range (rows world)) col (range (cols world))] [row col (alive? world row col)])) (defn render [world] (apply str (flatten (for [row (range (rows world))] [(for [col (range (cols world))] (if (alive? world row col) \# \.)) \newline])))) (defn neighbors "Get neighbor count at row-column position in world." [world r c] {:post [(<= 0 % 8)]} (count (filter true? (for [row (range (dec r) (+ r 2)) col (range (dec c) (+ c 2)) :when (not (and (= row r) (= col c)))] (alive? world row col))))) (defn map-world "Map a rule-fn over every cell in the world. The rule-fn should be of the form: (fn [row col alive? neighbor-count]) -> boolean" [rule-fn world] (->> (world-seq world) (filter (fn [[row col alive]] (when (rule-fn row col alive (neighbors world row col)) [row col]))) (apply init-world (rows world) (cols world)))) ;;;; Apply the life rules using the "world" data structure (defn life-rule "Determine whether a cell should live in the next tick based the current value and the neighbor count." [row col alive neighbor-count] (if alive (<= 2 neighbor-count 3) (= neighbor-count 3))) (defn update-world "Take world and compute new world based on the life function." [world] (map-world life-rule world)) ;;;; Main entry (defn life "Starting with an initial world, compute specified iterations." [init-world iterations] (loop [remaining-iterations iterations world init-world] (if (= 0 remaining-iterations) (println "Simulation complete.") (do (println) (println "Iteration" (- iterations remaining-iterations) ":") (print (render world)) (recur (dec remaining-iterations) (update-world world)))))) ;;;; Test with glider (defn test-glider "Return initial world with a glider prepped." [] (let [iters 10 glider-world (init-world 10 10 [1 3] [2 1] [2 3] [3 2] [3 3])] (life glider-world iters)))
[ { "context": "able main\"\n key \"https://dl-ssl.google.com/linux/linux_signing_key.pub\"]\n (->\n (add-repo repo key \"7FAC59", "end": 342, "score": 0.5877735614776611, "start": 323, "tag": "KEY", "value": "linux/linux_signing" }, { "context": "https://dl-ssl.google.com/linux/linux_signing_key.pub\"]\n (->\n (add-repo repo key \"7FAC5991\")\n ", "end": 350, "score": 0.6915004849433899, "start": 347, "tag": "KEY", "value": "pub" }, { "context": "igning_key.pub\"]\n (->\n (add-repo repo key \"7FAC5991\")\n (package \"google-chrome-stable\")\n (sum", "end": 394, "score": 0.9991517066955566, "start": 386, "tag": "KEY", "value": "7FAC5991" } ]
src/re_base/recipes/web.cljs
re-ops/re-base
4
(ns re-base.recipes.web "Web tools setup" (:require [re-conf.resources.pkg :refer (package add-repo)] [re-conf.resources.output :refer (summary)])) (defn chrome "Google chrome setup" [] (let [repo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" key "https://dl-ssl.google.com/linux/linux_signing_key.pub"] (-> (add-repo repo key "7FAC5991") (package "google-chrome-stable") (summary "google-chrome install"))))
6074
(ns re-base.recipes.web "Web tools setup" (:require [re-conf.resources.pkg :refer (package add-repo)] [re-conf.resources.output :refer (summary)])) (defn chrome "Google chrome setup" [] (let [repo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" key "https://dl-ssl.google.com/<KEY>_key.<KEY>"] (-> (add-repo repo key "<KEY>") (package "google-chrome-stable") (summary "google-chrome install"))))
true
(ns re-base.recipes.web "Web tools setup" (:require [re-conf.resources.pkg :refer (package add-repo)] [re-conf.resources.output :refer (summary)])) (defn chrome "Google chrome setup" [] (let [repo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" key "https://dl-ssl.google.com/PI:KEY:<KEY>END_PI_key.PI:KEY:<KEY>END_PI"] (-> (add-repo repo key "PI:KEY:<KEY>END_PI") (package "google-chrome-stable") (summary "google-chrome install"))))
[ { "context": "(ns ^{:doc \"Utility functions.\"\n :author \"James Cunningham\"}\n simulator.utils\n (:use [clojure.algo.generic", "end": 63, "score": 0.999872624874115, "start": 47, "tag": "NAME", "value": "James Cunningham" } ]
src/patient-simulator/src/simulator/utils.clj
connectedhealthcities/anytown
0
(ns ^{:doc "Utility functions." :author "James Cunningham"} simulator.utils (:use [clojure.algo.generic.functor :only (fmap)] [clojure.core.matrix.random :only (sample-normal sample-binomial)])) (defn weighted-choice "Selects an element from choices weighted by the value extracted from each element by weight-fn. If no weight-fn is given each element is weighted equally." ([weight-fn choices] (letfn [(f [[total choice] next] (let [weight (weight-fn next) total (+ total weight)] [total (if (< (rand) (/ weight total)) next choice)]))] (second (reduce f [0 nil] choices)))) ([choices] (weighted-choice (fn [_] 1) choices))) (defn weight "Returns either :weight of an item or 1 if weight is nil." [item] (or (:weight item) 1)) (defn fmap' "A version of fmap that returns nil if s is empty." [f s] (if (not (empty? s)) (fmap f s))) (defn rand-normal [mean sd] (+ mean (* sd (first (sample-normal 1))))) (defn rand-binomial [n p] (* n (first (sample-binomial 1 p)))) (defn rand-range "Returns a random real value in the range [x y)." [x y] (+ x (rand (- y x))))
33818
(ns ^{:doc "Utility functions." :author "<NAME>"} simulator.utils (:use [clojure.algo.generic.functor :only (fmap)] [clojure.core.matrix.random :only (sample-normal sample-binomial)])) (defn weighted-choice "Selects an element from choices weighted by the value extracted from each element by weight-fn. If no weight-fn is given each element is weighted equally." ([weight-fn choices] (letfn [(f [[total choice] next] (let [weight (weight-fn next) total (+ total weight)] [total (if (< (rand) (/ weight total)) next choice)]))] (second (reduce f [0 nil] choices)))) ([choices] (weighted-choice (fn [_] 1) choices))) (defn weight "Returns either :weight of an item or 1 if weight is nil." [item] (or (:weight item) 1)) (defn fmap' "A version of fmap that returns nil if s is empty." [f s] (if (not (empty? s)) (fmap f s))) (defn rand-normal [mean sd] (+ mean (* sd (first (sample-normal 1))))) (defn rand-binomial [n p] (* n (first (sample-binomial 1 p)))) (defn rand-range "Returns a random real value in the range [x y)." [x y] (+ x (rand (- y x))))
true
(ns ^{:doc "Utility functions." :author "PI:NAME:<NAME>END_PI"} simulator.utils (:use [clojure.algo.generic.functor :only (fmap)] [clojure.core.matrix.random :only (sample-normal sample-binomial)])) (defn weighted-choice "Selects an element from choices weighted by the value extracted from each element by weight-fn. If no weight-fn is given each element is weighted equally." ([weight-fn choices] (letfn [(f [[total choice] next] (let [weight (weight-fn next) total (+ total weight)] [total (if (< (rand) (/ weight total)) next choice)]))] (second (reduce f [0 nil] choices)))) ([choices] (weighted-choice (fn [_] 1) choices))) (defn weight "Returns either :weight of an item or 1 if weight is nil." [item] (or (:weight item) 1)) (defn fmap' "A version of fmap that returns nil if s is empty." [f s] (if (not (empty? s)) (fmap f s))) (defn rand-normal [mean sd] (+ mean (* sd (first (sample-normal 1))))) (defn rand-binomial [n p] (* n (first (sample-binomial 1 p)))) (defn rand-range "Returns a random real value in the range [x y)." [x y] (+ x (rand (- y x))))
[ { "context": "ng?)\n\n\n\n\n\n#_(def blades-json\n {\n :info {:name \"Drav Farros\"\n :look [\"Male\"\n ", "end": 3071, "score": 0.9998098015785217, "start": 3060, "tag": "NAME", "value": "Drav Farros" }, { "context": " :person \"Cyrene\"\n :catego", "end": 3917, "score": 0.9996630549430847, "start": 3911, "tag": "NAME", "value": "Cyrene" }, { "context": "json\n {\n :blades.user/info {:blades.user/name \"Drav Farros\"\n :blades.user/look [\"Male\"\n", "end": 4685, "score": 0.9998563528060913, "start": 4674, "tag": "NAME", "value": "Drav Farros" }, { "context": " :blades/person \"Cyrene\"\n :blades", "end": 5655, "score": 0.9988358616828918, "start": 5649, "tag": "NAME", "value": "Cyrene" }, { "context": "s of using macros with eval\n;; https://github.com/clojure/clojurescript/blob/master/src/test/self/self_host", "end": 52046, "score": 0.9684970378875732, "start": 52039, "tag": "USERNAME", "value": "clojure" }, { "context": "er/src/test/self/self_host/test.cljs#L392\n\n;; from @mfikes on clojurians regarding AOT and macros\n;; You hav", "end": 52128, "score": 0.9996047019958496, "start": 52121, "tag": "USERNAME", "value": "@mfikes" } ]
src/membrane/autoui.cljc
rgkirch/membrane
0
(ns membrane.autoui #?(:cljs (:require-macros [membrane.component :refer [defui defeffect]] [membrane.autoui :refer [defgen]])) (:require #?(:clj [membrane.skia :as skia]) #?(:cljs membrane.webgl) ;; #?(:cljs membrane.vdom) [membrane.ui :as ui :refer [vertical-layout translate horizontal-layout label with-color bounds spacer on]] [com.rpl.specter :as spec] #?(:cljs [cljs.reader :refer [read-string]]) #?(:cljs [membrane.eval]) #?(:cljs [cljs.core.async :refer [put! chan <! timeout dropping-buffer promise-chan] :as async]) #?(:cljs [cognitect.transit :as transit]) #?(:cljs [cljs.js :as cljs]) [membrane.component :as component :refer [#?(:clj defui) #?(:clj defeffect)]] #?(:clj [clojure.data.json :as json]) [membrane.basic-components :as basic :refer [button textarea]] [clojure.spec.alpha :as s] [spec-provider.provider :as sp] [clojure.spec.gen.alpha :as gen]) #?(:clj (:gen-class))) ;; layouts ;; https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/controls/layouts ;; - grid ;; - stack? ;; https://www.crazyegg.com/blog/guides/great-form-ui-and-ux/ ;; extra elements ;; - multi select ;; - radio button ;; - collapsable ;; Show all selection options if under 6 (defn imeta? [obj] #?(:clj (instance? clojure.lang.IObj obj) :cljs (satisfies? IMeta obj))) (defn maybe-with-meta [obj m] (if (imeta? obj) (with-meta obj m) obj)) (s/def :blades.user/info (s/keys :req [:blades.user/name :blades.user/look :blades.user/heritage :blades.user/background :blades.user/vice])) (s/def :blades.user/name string?) (s/def :blades.user/look (s/coll-of string? :kind vector?)) (s/def :blades.user/heritage (s/keys :req [:blades.heritage/description :blades.heritage/place])) (s/def :blades.heritage/description string?) (s/def :blades.heritage/place string?) (s/def :blades.user/background (s/keys :req [:blades.background/description :blades/place])) (s/def :blades.background/description string?) (s/def :blades/place string?) (s/def :blades.user/vice (s/keys :req [:blades.vice/description :blades.vice/category :blades/person])) (s/def :blades.vice/description string?) (s/def :blades.vice/category string?) (s/def :blades/person string?) #_(def blades-json { :info {:name "Drav Farros" :look ["Male" "Long Cloak" "Tall Boots" "Tricorn Hat" "Collard Shirt" "Waistcoat"] :heritage {:description "Lowly crafters who couldn't pay the bills" :place "Akoros"} :background {:description "Grew up on the streets since there was no food at home" :place "Underworld"} :vice {:description "A thug with dulusions of grandeur, pleasure are suitably \"high\" class. Not that I can tell the difference." :person "Cyrene" :category "Pleasure"}} :status {:stress 4 :traumas ["Cold" "Haunted"] :harms ["welt on the back of the head" "holding a sword"] :armor {:armor false :heavy false :special true}} ;; :abilities ;; [] :attributes {:insight {:level 1 :hunt 0 :study 1 :survey 1 :tinker 0} :prowess {:level 1 :finesse 1 :prowl 1 :skirmish 3 :wreck 2} :resolve {:level 4 :attrune 1 :command 3 :consort 0 :sway 1}}}) (def blades-json { :blades.user/info {:blades.user/name "Drav Farros" :blades.user/look ["Male" "Long Cloak" "Tall Boots" "Tricorn Hat" "Collard Shirt" "Waistcoat"] :blades.user/heritage {:blades.heritage/description "Lowly crafters who couldn't pay the bills" :blades.heritage/place "Akoros"} :blades.user/background {:blades.background/description "Grew up on the streets since there was no food at home" :blades/place "Underworld"} :blades.user/vice {:blades.vice/description "A thug with dulusions of grandeur, pleasure are suitably \"high\" class. Not that I can tell the difference." :blades/person "Cyrene" :blades.vice/category "Pleasure"}} :blades/status {:blades.status/stress 4 :blades.status/traumas ["Cold" "Haunted"] :blades.status/harms ["welt on the back of the head" "holding a sword"] :blades.status/armor {:blades.armor/armor false :blades.armor/heavy false :blades.armor/special true}} ;; :abilities ;; [] :attributes {:insight {:level 1 :hunt 0 :study 1 :survey 1 :tinker 0} :prowess {:level 1 :finesse 1 :prowl 1 :skirmish 3 :wreck 2} :resolve {:level 4 :attrune 1 :command 3 :consort 0 :sway 1}}}) (defn inc-context-depth [ctx] (-> ctx (update-in [:depth] inc) (dissoc :spec))) (defn list-editor []) (def gen-editors (atom {})) (defprotocol IGenEditor :extend-via-metadata true (gen-editor [this sym])) (defprotocol ISubGens (subgens [this])) (defprotocol IEditableProps (editable-props [this])) (defprotocol IGenInspector (gen-inspector [this])) (extend-type #?(:clj Object :cljs default) ISubGens (subgens [this] nil)) (extend-type #?(:clj Object :cljs default) IEditableProps (editable-props [this] nil)) (extend-type #?(:clj Object :cljs default) IGenInspector (gen-inspector [this] nil)) (extend-type nil IGenEditor (gen-editor [this sym] (ui/label "got null editor"))) (extend-type nil ISubGens (subgens [this] (prn "calling subgens with nil") nil)) ;; (extend-type nil ;; IGenProps ;; (genprops [this] ;; (prn "calling genprops with nil") ;; nil)) (extend-type nil IGenInspector (gen-inspector [this] nil)) (defprotocol IGenPred (gen-pred? [this obj])) (defmulti can-gen-from-spec? (fn [new-gen-type specs spec] new-gen-type)) (declare best-gen) (defmulti re-gen (fn [new-gen-type specs spec context] new-gen-type)) (defmacro defgen [name params & body] `(let [ret# (defrecord ~name ~params ~@body)] (swap! gen-editors assoc (quote ~name) ret#) ret#)) ;; (defmacro def-gen ;; ([name pred body] ;; `(def-gen ~name ~pred nil ~body)) ;; ([name pred children body] ;; `(let [gen# (with-meta ;; {:pred ~pred ;; :children ~children ;; :generate (fn [~'sym ~'obj ~'children ~'context] ;; ~body)} ;; {(quote ~`gen-editor) ;; (fn [this# sym# obj# children# context#] ;; ((:generate this#) sym# obj# children# context#))})] ;; (swap! gen-editors assoc (quote ~name) gen#) ;; (def ~name gen#)))) (defgen OrGen [opts context] ;; :preds in opts takes in a [pred? gen] ;; pred? should be a fully qualified symbol pointing to a single arity predicate function IGenPred (gen-pred? [this obj] (every? #(% obj) (map first (:preds opts)))) IGenEditor (gen-editor [this sym] `(cond ~@(apply concat (for [[pred? gen] (:preds opts)] (do (assert (symbol? pred?) "pred? must be a symbol") [`(~pred? ~sym) (gen-editor gen sym)])))))) (defmethod re-gen OrGen [_ specs spec context] (let [key-preds (rest spec)] (->OrGen {:preds (for [[k pred] (partition 2 key-preds)] [[pred (best-gen specs pred context)]])} context))) (defmethod can-gen-from-spec? OrGen [this specs spec] (and (seq? spec) (#{'clojure.spec.alpha/or 'cljs.spec.alpha/or} (first spec)))) (defgen SimpleTextAreaGen [opts context] IGenPred (gen-pred? [this obj] (string? obj)) IGenEditor (gen-editor [this sym] `(basic/textarea {:text ~sym}))) (defmethod re-gen SimpleTextAreaGen [_ specs spec context] (->SimpleTextAreaGen {} context)) (defmethod can-gen-from-spec? SimpleTextAreaGen [this specs spec] (#{'clojure.core/string? 'cljs.core/string?} spec )) (defui number-counter-inspector [{:keys [gen]}] (vertical-layout (let [min (get-in gen [:opts :min]) min-checked? (get extra :min-checked?) last-min (get extra :last-min)] (horizontal-layout (ui/label "min: ") (on :membrane.basic-components/toggle (fn [$min-checked?] (conj (if min-checked? [[:set $min nil] [:set $last-min min]] [[:set $min (or last-min 0)]]) [:membrane.basic-components/toggle $min-checked?])) (basic/checkbox {:checked? min-checked?})) (when min (basic/counter {:num min})))) (let [max (get-in gen [:opts :max]) max-checked? (get extra :max-checked?) last-max (get extra :last-max)] (horizontal-layout (ui/label "max: ") (on :membrane.basic-components/toggle (fn [$max-checked?] (conj (if max-checked? [[:set $max nil] [:set $last-max max]] [[:set $max (or last-max 0)]]) [:membrane.basic-components/toggle $max-checked?])) (basic/checkbox {:checked? max-checked?})) (when max (basic/counter {:num max})))))) (defgen NumberCounterGen [opts context] IGenInspector (gen-inspector [this] #'number-counter-inspector) IGenPred (gen-pred? [this obj] (number? obj)) IGenEditor (gen-editor [this sym] `(if (number? ~sym) (basic/counter {:num ~sym}) (ui/label (str ~sym " is NaN!")))) ) (defmethod re-gen NumberCounterGen [_ specs spec context] (->NumberCounterGen {} context)) (defmethod can-gen-from-spec? NumberCounterGen [this specs spec] (#{'clojure.core/integer? 'cljs.core/integer?} spec )) (defui number-slider-inspector [{:keys [gen]}] (vertical-layout (let [min (get-in gen [:opts :min] 0)] (horizontal-layout (ui/label "min: ") (basic/counter {:num min}))) (let [max (get-in gen [:opts :max] 100)] (horizontal-layout (ui/label "max: ") (basic/counter {:num max}))) (let [max-width (get-in gen [:opts :max-width] 100)] (horizontal-layout (ui/label "max-width: ") (basic/counter {:num max-width}))) (let [integer? (get-in gen [:opts :integer?] true)] (horizontal-layout (ui/label "integer? ") (basic/checkbox {:checked? integer?}))))) (defgen NumberSliderGen [opts context] IGenInspector (gen-inspector [this] #'number-slider-inspector) IGenPred (gen-pred? [this obj] (number? obj)) IGenEditor (gen-editor [this sym] `(if (number? ~sym) (basic/number-slider {:num ~sym :min ~(get opts :min 0) :max ~(get opts :max 100) :integer? ~(get opts :integer? true) :max-width ~(get opts :max-width 100)}) (ui/label (str ~sym " is not a NaN!")))) ) (defmethod re-gen NumberSliderGen [_ specs spec context] (->NumberSliderGen {} context)) (defmethod can-gen-from-spec? NumberSliderGen [this specs spec] (#{'clojure.core/integer? 'cljs.core/integer? 'clojure.core/number? 'cljs.core/number? 'clojure.core/float? 'cljs.core/float? 'clojure.core/double? 'cljs.core/double?} spec)) (defgen CheckboxGen [opts context] IGenPred (gen-pred? [this obj] (boolean? obj)) IGenEditor (gen-editor [this sym] `(basic/checkbox {:checked? ~sym}))) (defmethod re-gen CheckboxGen [_ specs spec context] (->CheckboxGen {} context)) (defmethod can-gen-from-spec? CheckboxGen [this specs spec] (#{'clojure.core/boolean? 'cljs.core/boolean?} spec)) (defgen TitleGen [opts context] IGenPred (gen-pred? [this obj] (or (string? obj) (keyword? obj))) IGenEditor (gen-editor [this sym] `(ui/label (let [s# (str (if (keyword? ~sym) (name ~sym) ~sym))] (clojure.string/capitalize s#)) (ui/font nil ~(max 16 (- 22 (* 4 (get context :depth 0))))))) ) (defmethod re-gen TitleGen [_ specs spec context] (->TitleGen {} context)) (defmethod can-gen-from-spec? TitleGen [this specs spec] (#{'clojure.core/string? 'cljs.core/string? 'clojure.core/keyword? 'cljs.core/keyword?} spec)) (defgen LabelGen [opts context] ;; IEditableProps ;; (editable-props [this] ;; {:font-size (number-inspector :max 40 ;; :min 12)}) ;; IGenProps ;; (genprops [this] ;; [:font-size]) IGenPred (gen-pred? [this obj] (or (string? obj) (keyword? obj))) IGenEditor (gen-editor [this sym] `(ui/label ~sym (ui/font nil ~(:font-size opts)))) ) (defmethod re-gen LabelGen [_ specs spec context] (->LabelGen {} context)) (defmethod can-gen-from-spec? LabelGen [this specs spec] true) #_(def-gen static-vector vector? {:x identity} (let [x-sym (gensym "x-")] `(apply vertical-layout (for [~x-sym ~sym] ~(ui-code x-sym (first obj) (inc-context-depth context)))))) #_(def-gen static-horizontal-vector vector? {:x identity} (let [x-sym (gensym "x-") ] `(apply horizontal-layout (for [~x-sym ~sym] ~(ui-code x-sym (first obj) (inc-context-depth context)))))) (defn delete-X [] (ui/with-style :membrane.ui/style-stroke (ui/with-color [1 0 0] (ui/with-stroke-width 3 [(ui/path [0 0] [10 10]) (ui/path [10 0] [0 10])])))) (defn ->$sym [sym] (symbol (str "$" (name sym))) ) #_(def-gen dynamic-vector vector? (let [x-sym (gensym "x-")] `(apply vertical-layout (basic/button :text "New" :on-click (fn [] [[:update ~(->$sym sym) conj (first ~sym)]])) (for [~x-sym ~sym] (horizontal-layout (on :mouse-down (fn [_#] [[:delete ~(->$sym x-sym)]]) (delete-X)) ~(ui-code x-sym (first obj) (inc-context-depth context))))))) #_(def-gen checkbox boolean? `(basic/checkbox :checked? ~sym)) (defn stack-img [outer-layout inner-layout inner-elem outer-elem] (let [padding 1 rect-size 4] (apply outer-layout (interpose (spacer 0 padding) (for [i (range 3)] (inner-layout (inner-elem rect-size) (spacer padding 0) (outer-elem rect-size))))))) (defn kv-vertical-img [] (stack-img vertical-layout horizontal-layout #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)))) (defn vk-vertical-img [] (stack-img vertical-layout horizontal-layout #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) )) (defn kv-horizontal-img [] (stack-img horizontal-layout vertical-layout #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)))) (defn vk-horizontal-img [] (stack-img horizontal-layout vertical-layout #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) )) (defn kv-all-horizontal-img [] (stack-img horizontal-layout horizontal-layout #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)))) (defn vk-all-horizontal-img [] (stack-img horizontal-layout horizontal-layout #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) )) (defn kv-all-vertical-img [] (stack-img vertical-layout vertical-layout #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)))) (defn vk-all-vertical-img [] (stack-img vertical-layout vertical-layout #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) )) (defn test-view [] (apply vertical-layout (interpose (spacer 0 10) [(kv-vertical-img) (vk-vertical-img) (kv-horizontal-img) (vk-horizontal-img) (kv-all-horizontal-img) (vk-all-horizontal-img) (kv-all-vertical-img) (vk-all-vertical-img)]))) (defui option-toggle [{:keys [flag true-text false-text]}] (horizontal-layout (ui/button true-text (fn [] (when-not flag [[:set $flag true]])) flag) (ui/button false-text (fn [] (when flag [[:set $flag false]])) (not flag)))) (defui static-map-gen-inspector [{:keys [gen]}] (let [horizontal-rows? (get-in gen [:opts :horizontal-rows?]) horizontal-cols? (get-in gen [:opts :horizontal-cols?]) kv-order? (get-in gen [:opts :kv-order?] true)] (vertical-layout (let [k-elem #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) v-elem #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) [inner-elem outer-elem] (if kv-order? [k-elem v-elem] [v-elem k-elem])] [(spacer 45 45) (ui/padding 5 5 (stack-img (if horizontal-rows? horizontal-layout vertical-layout) (if horizontal-cols? horizontal-layout vertical-layout) inner-elem outer-elem))]) (ui/label "key value layout order") (option-toggle {:flag kv-order? :true-text "kv" :false-text "vk"}) (ui/label "row direction") (option-toggle {:flag horizontal-rows? :true-text "horizontal" :false-text "vertical"}) (ui/label "column direction") (option-toggle {:flag horizontal-cols? :true-text "horizontal" :false-text "vertical"}) ) #_(horizontal-layout (ui/label "horizontal?") (ui/translate 5 5 (basic/checkbox :checked? horizontal?))))) (defgen StaticMapGen [opts context] IGenInspector (gen-inspector [this] #'static-map-gen-inspector) IEditableProps (editable-props [this] {:k gen-inspector :v gen-inspector}) ISubGens (subgens [this] [[:opts :k] [:opts :v]]) IGenPred (gen-pred? [this obj] (map? obj)) IGenEditor (gen-editor [this sym] (let [k-sym (gensym "k-") v-sym (gensym "v-") klabel-sym (gensym "klabel-") table-sym (gensym "table-")] `(ui/translate 10 10 (let [~table-sym (for [[~k-sym ~v-sym] ~sym] ~(let [k-elem `(let [~klabel-sym (maybe-with-meta ~(gen-editor (:k opts) k-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :k)])})] (vertical-layout ~klabel-sym ~(when (<= (:depth context) 1) `(let [lbl-width# (ui/width ~klabel-sym)] (ui/with-style :membrane.ui/style-stroke (ui/with-color [0 0 0] (ui/path [0 0] [lbl-width# 0]))))))) v-elem `(let [~v-sym (get ~sym ~k-sym)] (maybe-with-meta ~(gen-editor (:v opts) v-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :v)])}))] (if (get opts :kv-order? true) [k-elem v-elem] [v-elem k-elem]))) ] ~(if (= (:horizontal-rows? opts) (:horizontal-cols? opts)) (let [layout (if (:horizontal-rows? opts) `horizontal-layout `vertical-layout)] `(apply ~layout (apply concat ~table-sym))) `(ui/table-layout ~(if (:horizontal-rows? opts) table-sym `[(map first ~table-sym) (map second ~table-sym)])) ) ) #_(apply ~(if (:horizontal-rows? opts) `horizontal-layout `vertical-layout) (for [[~k-sym ~v-sym] ~sym] (~(if (:horizontal-cols? opts) `horizontal-layout `vertical-layout) ~@(let [k-elem `(let [~klabel-sym (maybe-with-meta ~(gen-editor (:k opts) k-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :k)])})] (vertical-layout ~klabel-sym ~(when (<= (:depth context) 1) `(let [lbl-width# (ui/width ~klabel-sym)] (ui/with-style :membrane.ui/style-stroke (ui/with-color [0 0 0] (ui/path [0 0] [lbl-width# 0]))))))) v-elem `(let [~v-sym (get ~sym ~k-sym)] (maybe-with-meta ~(gen-editor (:v opts) v-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :v)])}))] (if (get opts :kv-order? true) [k-elem v-elem] [v-elem k-elem])))) ))))) (defmethod re-gen StaticMapGen [_ specs spec context] (let [subcontext (inc-context-depth context)] (let [spec-fn (first spec)] (case spec-fn (clojure.spec.alpha/map-of cljs.spec.alpha/map-of) (let [[kpred vpred & opts] (rest spec) k-spec (if (keyword? kpred) (get specs kpred) kpred) k-gen (if (can-gen-from-spec? TitleGen specs k-spec) (->TitleGen {} (assoc subcontext :spec k-spec)) (best-gen specs k-spec subcontext)) v-spec (if (keyword? vpred) (get specs vpred) vpred)] (->StaticMapGen {:k k-gen :v (best-gen specs v-spec subcontext)} context)) (clojure.spec.alpha/keys cljs.spec.alpha/keys) (let [[& {:keys [req req-un opt opt-un gen]}] (rest spec) key-specs (concat req req-un opt opt-un) first-key-spec (get specs (first key-specs))] (->StaticMapGen {:k (->TitleGen {} (dissoc subcontext :spec)) :v (best-gen specs first-key-spec subcontext)} context)) ))) ) (defmethod can-gen-from-spec? StaticMapGen [this specs spec] (and (seq? spec) (let [spec-fn (first spec)] (or (#{'clojure.spec.alpha/map-of 'cljs.spec.alpha/map-of} spec-fn ) (and (#{'clojure.spec.alpha/keys 'cljs.spec.alpha/keys} spec-fn ) ;; all key specs should return the same gen type ;; this is so ugly. forgive me (let [[& {:keys [req req-un opt opt-un gen]}] (rest spec) key-specs (concat req req-un opt opt-un) context {:depth 0} example-gen-type (type (best-gen specs (get specs (first key-specs)) context))] (every? #(= example-gen-type (type (best-gen specs (get specs %) context))) (rest key-specs)))))))) (defgen StaticSeqGen [opts context] ISubGens (subgens [this] [[:opts :vals]]) IGenPred (gen-pred? [this obj] (and (seqable? obj) (not (or (map? obj) (string? obj))))) IGenEditor (gen-editor [this sym] (let [v-sym (gensym "v-")] `(ui/translate 10 10 (apply ~(if (:horizontal? opts) `horizontal-layout `vertical-layout) (for [~v-sym ~sym] (maybe-with-meta ~(gen-editor (:vals opts) v-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :vals)])}))))))) (defmethod re-gen StaticSeqGen [_ specs spec context] (assert (can-gen-from-spec? StaticSeqGen specs spec)) (->StaticSeqGen {:vals (best-gen specs (second spec) (inc-context-depth context))} context)) (defmethod can-gen-from-spec? StaticSeqGen [this specs spec] (and (seq? spec) (#{'clojure.spec.alpha/coll-of 'cljs.spec.alpha/coll-of} (first spec)))) (defui keymap-gen-inspector [{:keys [gen]}] (let [bordered? (get-in gen [:opts :bordered?] true)] (horizontal-layout (ui/label "bordered?") (ui/translate 5 5 (basic/checkbox {:checked? bordered?}))))) (defgen KeyMapGen [opts context] IGenInspector (gen-inspector [this] #'keymap-gen-inspector) ISubGens (subgens [this] (conj (map #(vector :opts :val-gens %) (keys (:val-gens opts))) [:opts :k])) IGenPred (gen-pred? [this obj] (map? obj)) IGenEditor (gen-editor [this sym] (let [body `(vertical-layout ~@(apply concat (for [[k subgen] (:val-gens opts)] (let [v-sym (gensym "v-")] `[(maybe-with-meta ~(gen-editor (:k opts) k) ~{:relative-identity '(quote [(keypath :opts) (keypath :k)])}) (let [~v-sym (get ~sym ~k)] (maybe-with-meta ~(gen-editor subgen v-sym) ~{:relative-identity [(quote '(keypath :opts)) (quote '(keypath :val-gens)) (list 'list (list 'quote 'keypath) k)]}))])))) body (if (get opts :bordered? true) `(ui/bordered [5 5] ~body) body)] body))) (defmethod re-gen KeyMapGen [_ specs spec context] (assert (can-gen-from-spec? KeyMapGen specs spec)) (let [subcontext (inc-context-depth context) [& {:keys [req req-un opt opt-un gen]}] (rest spec)] (->KeyMapGen {:k (->TitleGen {} (dissoc subcontext :spec)) :val-gens (into {} (concat (for [k (concat req opt)] [k (best-gen specs (get specs k) subcontext)]) (for [k (concat req-un opt-un)] [(keyword (name k)) (best-gen specs (get specs k) subcontext)]))) :bordered? (if-let [depth (:depth context)] (pos? depth) true)} context))) (defmethod can-gen-from-spec? KeyMapGen [this specs spec] (and (seq? spec) (#{'clojure.spec.alpha/keys 'cljs.spec.alpha/keys} (first spec)))) (defui cat-gen-inspector [{:keys [gen]}] (let [bordered? (get-in gen [:opts :bordered?] true)] (horizontal-layout (ui/label "bordered?") (ui/translate 5 5 (basic/checkbox {:checked? bordered?}))))) (defgen CatGen [opts context] IGenInspector (gen-inspector [this] #'cat-gen-inspector) ISubGens (subgens [this] (map #(vector :opts :val-gens %) (range (count (:val-gens opts))))) IGenPred (gen-pred? [this obj] (and (seqable? obj) (not (or (map? obj) (string? obj))))) IGenEditor (gen-editor [this sym] (let [body `(vertical-layout ~@(apply concat (for [[i subgen] (map-indexed vector (:val-gens opts))] (let [v-sym (gensym "v-")] `[(let [~v-sym (nth ~sym ~i)] (maybe-with-meta ~(gen-editor subgen v-sym) ~{:relative-identity [(quote '(keypath :opts)) (quote '(keypath :val-gens)) (list 'list (list 'quote 'nth) i)]}))])))) body (if (get opts :bordered? true) `(ui/bordered [5 5] ~body) body)] body))) (defmethod re-gen CatGen [_ specs spec context] (assert (can-gen-from-spec? CatGen specs spec)) (let [subcontext (inc-context-depth context) val-specs (take-nth 2 (drop 2 spec))] (->CatGen {:val-gens (vec (for [val-spec val-specs] (best-gen specs (get specs val-spec val-spec) subcontext))) :bordered? (if-let [depth (:depth context)] (pos? depth) true)} context))) (defmethod can-gen-from-spec? CatGen [this specs spec] (and (seq? spec) (= 'clojure.spec.alpha/cat (first spec)))) (defn first-matching-gen [obj] (some #(when ((:pred %) obj) %) (vals @gen-editors)) ) #_(defn ui-code ([sym obj context] (let [generator (first-matching-gen obj) children (into {} (for [[k v] (:children generator)] [k (fn [sym context] (ui-code sym (first (v obj)) (inc-context-depth context)))]))] (assert generator (str "No generator for " (pr-str obj)) ) (gen-editor generator sym obj children context)))) (defn auto-component [ui-name ge] (let [arg-sym 'obj] `(defui ~ui-name [{:keys [~arg-sym]}] (basic/scrollview {:bounds [800 800] :body ~(gen-editor ge arg-sym)})))) (defn def-auto-component [ui-name ge] (let [code (auto-component ui-name ge)] (eval code))) #_(def-auto-component 'testblades (best-gen blades-json)) #_(def-auto-component map-example {:a 1 :b 2 :c 3}) (def testgen (let [context {:depth 0} subcontext (inc-context-depth context)] (->StaticMapGen {:k (->LabelGen {} subcontext) :v (->NumberCounterGen {} subcontext) #_ (->LabelGen {} subcontext)} context))) ;; todo ;; - have a way to set data ;; - have a way to generate the gen-tree ;; - have a way to swap out alternatives (do (defn infer-specs ([obj] (infer-specs obj :membrane.autoui/infer-specs)) ([obj spec-name] (let [inferred (sp/infer-specs [obj] spec-name) specs (into {} (for [[def k spec] inferred] [k spec]))] specs))) (defn best-gen ([obj] (let [spec-name :membrane.autoui/infer-specs specs (infer-specs obj spec-name)] (best-gen specs (get specs spec-name) {:depth 0 :specs specs}))) ([specs spec context] (let [gen (cond (#{'clojure.core/string? 'cljs.core/string?} spec ) (->SimpleTextAreaGen {} context) (#{'clojure.core/boolean? 'cljs.core/boolean?} spec ) (->CheckboxGen {} context) (#{'clojure.core/keyword? 'cljs.core/keyword?} spec ) (->TitleGen {} context) (#{'clojure.core/simple-symbol?} spec ) (->TitleGen {} context) (#{'clojure.core/integer? 'cljs.core/integer? } spec ) (->NumberCounterGen {} context) ('#{clojure.core/double? cljs.core/double? clojure.core/float? cljs.core/float?} spec) (->NumberSliderGen {} context) (seq? spec) (case (first spec) (clojure.spec.alpha/coll-of cljs.spec.alpha/coll-of) (let [[pred & {:keys [into kind count max-count min-count distinct gen-max gen]}] (rest spec) subcontext (inc-context-depth context) ] (->StaticSeqGen {:vals (best-gen specs pred subcontext)} context) ) clojure.spec.alpha/cat (let [] (re-gen CatGen specs spec context)) clojure.spec.alpha/? (let [pred (second spec) subcontext (inc-context-depth context)] (best-gen specs pred subcontext)) clojure.spec.alpha/* (let [pred (second spec) subcontext (inc-context-depth context)] (->StaticSeqGen {:vals (best-gen specs pred subcontext)} context)) (clojure.spec.alpha/keys cljs.spec.alpha/keys) (re-gen KeyMapGen specs spec context) (clojure.spec.alpha/map-of) (re-gen StaticMapGen specs spec context) (clojure.spec.alpha/or cljs.spec.alpha/or) (let [key-preds (rest spec)] (->OrGen {:preds (for [[k pred] (partition 2 key-preds)] [[pred (best-gen specs pred context)]])} context)) ;; else (str "unknown spec: " (first spec)) ) :else (str "unknown spec: " spec) )] (if (satisfies? IGenEditor gen) (assoc-in gen [:context :spec] spec) gen))) ) #_(prn (let [obj blades-json] (best-gen obj)))) (defn gen-options [specs spec] (->> @gen-editors vals (filter #(can-gen-from-spec? % specs spec)))) (def testgen2 (let [ge testgen] (->KeyMapGen {:k (:k (:opts ge)) :val-gens {:a (->NumberCounterGen {} (:context (:v (:opts ge)))) :b (->LabelGen {} (:context (:v (:opts ge)))) :c (->TitleGen {} (:context (:v (:opts ge))))}} (:context ge)))) (defui foldable-section [{:keys [title body visible?] :or {visible? true}}] (vertical-layout (on :mouse-down (fn [_] [[:update $visible? not]]) [#_(ui/filled-rectangle [0.9 0.9 0.9] 200 20) (horizontal-layout (let [size 5] (ui/with-style :membrane.ui/style-stroke-and-fill (if visible? (ui/translate 5 8 (ui/path [0 0] [size size] [(* 2 size) 0])) (ui/translate 5 5 (ui/path [0 0] [size size] [0 (* 2 size)]))))) (spacer 5 0) (ui/label title)) ]) (when visible? (ui/translate 10 0 body)))) (defn pr-label [obj] (let [s (pr-str obj)] (ui/label (subs s 0 (min (count s) 37))))) (defn get-gen-name [ge] #?(:clj (.getSimpleName ge) :cljs (pr-str ge))) ;; forward declare (defui gen-editor-inspector [{:keys [ge]}]) (defui gen-editor-inspector [{:keys [ge]}] (let [sub (subgens ge)] (foldable-section {:title (if-let [spec (-> ge :context :spec)] (pr-str spec) (get-gen-name (type ge))) :visible? (get extra [:foldable-visible $ge] true) :body (apply vertical-layout (when-let [spec (-> ge :context :spec)] (when-let [specs (-> ge :context :specs)] (vertical-layout (pr-label spec) (let [options (gen-options specs spec)] (apply horizontal-layout (for [option options] (basic/button {:text (get-gen-name option) :hover? (get extra [:switch :hover? option]) :on-click (fn [] [[:set $ge (re-gen option specs spec (:context ge))]])}))))))) (when-let [inspector (gen-inspector ge)] (let [inspector-extra (get extra [$ge :extra])] (inspector {:gen ge :$gen $ge :extra inspector-extra :$extra $inspector-extra :context context :$context $context}))) (for [k sub] (let [v (get-in ge k)] (gen-editor-inspector {:ge v}))))}))) (defn find-under ([pos elem delta] (find-under pos elem (Math/pow delta 2) nil [])) ([pos elem d2 elem-index ident] (let [[x y] pos [ox oy] (ui/origin elem) [width height] (ui/bounds elem) local-x (int (- x ox)) local-y (int (- y oy)) new-pos [local-x local-y] elem-meta (meta elem)] (if-let [m elem-meta] (if-let [identity (:identity m)] (let [child-results (mapcat #(find-under new-pos % d2 elem-index [identity]) (ui/children elem))] (if (and (< (Math/pow local-x 2) d2) (< (Math/pow local-y 2) d2)) (conj child-results {:elem elem :pos new-pos :identity identity}) child-results)) (if-let [relative-identity (:relative-identity m)] (let [identity (into ident relative-identity) child-results (mapcat #(find-under new-pos % d2 elem-index identity) (ui/children elem))] (if (and (< (Math/pow local-x 2) d2) (< (Math/pow local-y 2) d2)) (conj child-results {:elem elem :pos new-pos :identity identity}) child-results)) (mapcat #(find-under new-pos % d2 elem-index ident) (ui/children elem)))) (mapcat #(find-under new-pos % d2 elem-index ident) (ui/children elem)))))) (defn draw-circles ([elem] (draw-circles elem [0 0])) ([elem pos] (let [[x y] pos [ox oy] (ui/origin elem) [width height] (ui/bounds elem) local-x (int (+ x ox)) local-y (int (+ y oy)) new-pos [local-x local-y] elem-meta (meta elem)] (if-let [m elem-meta] (if-let [identity (:identity m)] (let [child-results (mapcat #(draw-circles % new-pos) (ui/children elem))] (conj child-results new-pos)) (if-let [relative-identity (:relative-identity m)] (let [child-results (mapcat #(draw-circles % new-pos) (ui/children elem))] (conj child-results new-pos)) (mapcat #(draw-circles % new-pos) (ui/children elem)))) (mapcat #(draw-circles % new-pos) (ui/children elem)))))) (def ^:dynamic *obj* nil) (def ^:dynamic *$ge* nil) (declare background-eval) (defui eval-form [{:keys [form eval-context cache eval-key]}] (let [cache (or cache {}) result (background-eval form eval-context cache $cache eval-key)] ;; (prn "result:" result) result)) (defui gen-editor-editor [{:keys [ge obj selected-ge-path ge-options]}] (horizontal-layout (basic/scrollview {:scroll-bounds [400 800] :body (let [body (ui/no-events (ui/try-draw (let [drawable #?(:clj (binding [*obj* obj *$ge* []] ;; (clojure.pprint/pprint (gen-editor ge 'obj)) (eval `(let [~'obj *obj*] (maybe-with-meta ~(gen-editor ge 'obj) {:identity *$ge*})))) :cljs (eval-form {:form `(maybe-with-meta ~(gen-editor ge 'obj) {:identity ~'ident}) :eval-context {'ident *$ge* 'obj obj} :eval-key ge}) ) ] drawable) (fn [draw e] (println e) (draw (ui/label "whoops!"))))) circles (delay (mapv (fn [[x y]] (ui/translate (- x 5) (- y 5) (ui/filled-rectangle [1 0 0] 10 10))) (draw-circles body)))] [ (on :mouse-down (fn [pos] (let [results (seq (find-under pos body 5))] (if-let [results results] (if (= (count results) 1) (let [ident (:identity (first results))] [[:set $selected-ge-path ident]]) [[:set $ge-options {:pos pos :options (vec (for [{:keys [elem pos elem-index identity]} results] [identity (get-gen-name (type (spec/select-one (component/path->spec [identity]) ge)))]))}]]) [[:set $selected-ge-path nil] [:set $ge-options nil]]))) body) ;; @circles (when ge-options (let [options-pos (:pos ge-options) options (:options ge-options)] (ui/translate (first options-pos) (second options-pos) (on ::basic/select (fn [_ $ident] [[:set $ge-options nil] [:set $selected-ge-path $ident]]) (basic/dropdown-list {:options options})))))])}) (let [[edit-ge $edit-ge] (if selected-ge-path [(spec/select-one (component/path->spec [selected-ge-path]) ge) [$ge selected-ge-path]] [ge $ge])] (basic/scrollview {:scroll-bounds [800 800] :body (gen-editor-inspector {:ge edit-ge :$ge $edit-ge})})))) (defui test-edit [{:keys [title?]}] (vertical-layout (horizontal-layout (ui/label "title?") (basic/checkbox {:checked? title?})) (let [testgen (if title? (-> testgen (assoc-in [:opts :k] (->TitleGen {} (:context (get-in testgen [:opts :k])))) (assoc-in [:opts :v] (->TitleGen {} (:context (get-in testgen [:opts :v]))))) testgen)] (eval`(let [~'m {:a 1 :b 2}] ~(gen-editor testgen 'm)))))) (comment (let [obj blades-json ge (best-gen obj)] (def editor-state (skia/run (component/make-app #'gen-editor-editor {:ge ge :obj obj}))))) (defn start-blades [] (let [obj blades-json ge (best-gen obj)] (def editor-state (skia/run (component/make-app #'gen-editor-editor {:ge ge :obj obj}))))) (comment (def test-data (with-open [rdr (clojure.java.io/reader "/var/tmp/test-savegame.json")] (clojure.data.json/read rdr :key-fn keyword)))) (comment (start-form-builder {:x 2, :y 10, :data ":/gamedata/enemies/test-enemy.json", :character {:role "Enemy", :wisdom 10, :weapon "", :firearm "", :experience 100, :mana 10, :inventory [{:data ":/gamedata/items/plants/healing-herb.json", :count 2} {:data ":/gamedata/items/weapons/sword.json", :count 2}], :strength 10, :healthMax 200, :manaMax 10, :health 200, :gender "male", :stealth 0}})) (defn start-form-builder [obj] (let [ge (best-gen obj)] (def editor-state (skia/run (component/make-app #'gen-editor-editor {:ge ge :obj obj}))))) (defn start-spec [] (let [obj (list 10 "Asfa") ge (let [specs {} #_(into {} (for [[k v] (s/registry) :let [form (try (s/form v) (catch Exception e nil))] :when form] [k form]))] (best-gen specs `(s/cat :foo integer? :bar string?) {:depth 0 :specs specs}))] (def editor-state (skia/run (component/make-app #'gen-editor-editor {:ge ge :obj obj}))))) #_(defui blades-scroll [{:keys [obj]}] (basic/scrollview :scroll-bounds [800 800] :body (testblades :obj obj))) ;; examples of using macros with eval ;; https://github.com/clojure/clojurescript/blob/master/src/test/self/self_host/test.cljs#L392 ;; from @mfikes on clojurians regarding AOT and macros ;; You have to roll your own way of doing that. Planck does this https://blog.fikesfarm.com/posts/2016-02-03-planck-macros-aot.html ;; The high-level idea is that you can use a build-time self-hosted compiler to compile macros namespaces down to JavaScript. ;; Also Replete does this as well, all in the name of fast loading. So, you can look at Plank and Replete as inspiration on how to do this. There might be other examples out there as well. #?(:cljs (do (def cljstate (cljs/empty-state)) (def aot-caches [ "js/compiled/out.autouitest/clojure/zip.cljs.cache.json" "js/compiled/out.autouitest/clojure/string.cljs.cache.json" "js/compiled/out.autouitest/clojure/walk.cljs.cache.json" "js/compiled/out.autouitest/clojure/set.cljs.cache.json" "js/compiled/out.autouitest/cognitect/transit.cljs.cache.json" "js/compiled/out.autouitest/spec_provider/util.cljc.cache.json" "js/compiled/out.autouitest/spec_provider/merge.cljc.cache.json" "js/compiled/out.autouitest/spec_provider/rewrite.cljc.cache.json" "js/compiled/out.autouitest/spec_provider/stats.cljc.cache.json" "js/compiled/out.autouitest/spec_provider/provider.cljc.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/impl/commons.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/impl/utils.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/impl/errors.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/impl/inspect.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/edn.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/reader_types.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader.cljs.cache.json" "js/compiled/out.autouitest/cljs/env.cljc.cache.json" "js/compiled/out.autouitest/cljs/core/async.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/channels.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/dispatch.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/timers.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/buffers.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/protocols.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/ioc_helpers.cljs.cache.json" "js/compiled/out.autouitest/cljs/compiler.cljc.cache.json" "js/compiled/out.autouitest/cljs/analyzer.cljc.cache.json" "js/compiled/out.autouitest/cljs/tagged_literals.cljc.cache.json" "js/compiled/out.autouitest/cljs/spec/test/alpha.cljs.cache.json" "js/compiled/out.autouitest/cljs/spec/gen/alpha.cljs.cache.json" "js/compiled/out.autouitest/cljs/spec/alpha.cljs.cache.json" "js/compiled/out.autouitest/cljs/reader.cljs.cache.json" "js/compiled/out.autouitest/cljs/source_map.cljs.cache.json" "js/compiled/out.autouitest/cljs/js.cljs.cache.json" "js/compiled/out.autouitest/cljs/pprint.cljs.cache.json" "js/compiled/out.autouitest/cljs/source_map/base64.cljs.cache.json" "js/compiled/out.autouitest/cljs/source_map/base64_vlq.cljs.cache.json" "js/compiled/out.autouitest/cljs/core$macros.cljc.cache.json" "js/compiled/out.autouitest/cljs/analyzer/api.cljc.cache.json" "js/compiled/out.autouitest/cljs/stacktrace.cljc.cache.json" "js/compiled/out.autouitest/membrane/audio.cljs.cache.json" "js/compiled/out.autouitest/membrane/jsonee.cljc.cache.json" "js/compiled/out.autouitest/membrane/webgl.cljs.cache.json" "js/compiled/out.autouitest/membrane/basic_components.cljc.cache.json" "js/compiled/out.autouitest/membrane/autoui.cljc.cache.json" "js/compiled/out.autouitest/membrane/builder.cljc.cache.json" "js/compiled/out.autouitest/membrane/ui.cljc.cache.json" "js/compiled/out.autouitest/membrane/component.cljc.cache.json" "js/compiled/out.autouitest/membrane/analyze.cljc.cache.json" "js/compiled/out.autouitest/membrane/example/counter.cljc.cache.json" "js/compiled/out.autouitest/membrane/example/todo.cljc.cache.json" "js/compiled/out.autouitest/membrane/macroexpand.cljs.cache.json" "js/compiled/out.autouitest/membrane/vdom.cljs.cache.json" "js/compiled/out.autouitest/membrane/eval.cljs.cache.json" "js/compiled/out.autouitest/membrane/webgltest.cljs.cache.json" "js/compiled/out.autouitest/com/rpl/specter.cljc.cache.json" "js/compiled/out.autouitest/com/rpl/specter/protocols.cljc.cache.json" "js/compiled/out.autouitest/com/rpl/specter/impl.cljc.cache.json" "js/compiled/out.autouitest/com/rpl/specter/navs.cljc.cache.json" "js/compiled/out.autouitest/vdom/core.cljs.cache.json" "js/compiled/out.autouitest/process/env.cljs.cache.json" ] ) (defn load-cache [state cache-path] (let [ch (chan 1)] (membrane.eval/get-file cache-path (fn [source] (try (let [ rdr (transit/reader :json) cache (transit/read rdr source) ns (:name cache)] (cljs.js/load-analysis-cache! state ns cache) (prn "loaded " cache-path)) (finally (async/close! ch))))) ch)) (let [state cljstate] (async/go (let [] (let [chs (doall (map (fn [path] (load-cache state path)) aot-caches))] (doseq [ch chs] (<! ch))) (println "loaded all cached") (async/go #_(prn (<! (membrane.eval/eval-async state '(require-macros '[membrane.component :refer [defui]]) #_(:require [membrane.audio :as audio])))) (let [obj blades-json ge (best-gen obj)] (def canvas (.getElementById js/document "canvas")) #_(defonce start-auto-app (membrane.component/run-ui #'gen-editor-editor {:ge ge :obj obj} nil {:container canvas})) #_(defonce start-auto-app (membrane.component/run-ui #'gen-editor-editor {:ge ge :obj obj} nil {:container (js/document.getElementById "app")}))) (def background-eval-context (atom {})) (def background-eval-context-key (atom 0)) (defn background-eval [form eval-context cache $cache eval-key] (if (contains? cache eval-key) (get cache eval-key) (let [context-key (swap! background-eval-context-key inc)] (spec/transform (component/path->spec $cache) (fn [m] (assoc m eval-key (ui/label "loading..."))) start-auto-app) (async/go (swap! background-eval-context assoc context-key eval-context) (let [bindings (for [[sym val] eval-context] [sym `(get-in @background-eval-context [~context-key (quote ~sym)])]) form-with-context `(let ~(vec (apply concat bindings)) ~form) result (<! (membrane.eval/eval-async cljstate form-with-context))] ;; (prn result) (if (:error result) (do (prn "error " (:error result)) (spec/transform (component/path->spec $cache) (fn [m] (assoc m eval-key (ui/label "error evaling...."))) start-auto-app)) (spec/transform (component/path->spec $cache) (fn [m] (assoc m eval-key (:value result))) start-auto-app)) (swap! background-eval-context dissoc context-key))) (ui/label "loading..."))))))) (set! (.-evaltest js/window ) (fn [] (let [source '(membrane.component/defui my-foo [{:keys [ a b]}]) ] (cljs/eval state source membrane.eval/default-compiler-options #(prn %))))) (set! (.-evaltually js/window) (fn [source] (cljs/eval-str state source nil membrane.eval/default-compiler-options #(prn %)) )) (set! (.-evaltually_statement js/window) (fn [source] (cljs/eval-str state source nil (assoc membrane.eval/default-compiler-options :context :statement) #(prn %))))))) (comment #?(:cljs (do (defn default-load-fn [{:keys [name macros path] :as m} cb] (prn "trying to load" m) (throw "whoops!")) (defn wrap-js-eval [resource] (try (cljs/js-eval resource) (catch js/Object e {::error e}))) (def compiler-options {:source-map true ;; :context :statement :ns 'test.ns :verbose true :load default-load-fn :def-emits-var true :eval wrap-js-eval}) (def state (cljs/empty-state)) (defn eval-next [statements] (when-let [statement (first statements)] (prn "evaling " statement) (cljs/eval state statement compiler-options #(do (prn "result: " %) (eval-next (rest statements)))))) (eval-next [ '(ns test.ns) '(defmacro test-macro [& body] `(vector 42 ~@body)) '(test-macro 123) ;; console log: ;; "evaling " (test-macro 123) ;; "result: " [42] ]))))
88048
(ns membrane.autoui #?(:cljs (:require-macros [membrane.component :refer [defui defeffect]] [membrane.autoui :refer [defgen]])) (:require #?(:clj [membrane.skia :as skia]) #?(:cljs membrane.webgl) ;; #?(:cljs membrane.vdom) [membrane.ui :as ui :refer [vertical-layout translate horizontal-layout label with-color bounds spacer on]] [com.rpl.specter :as spec] #?(:cljs [cljs.reader :refer [read-string]]) #?(:cljs [membrane.eval]) #?(:cljs [cljs.core.async :refer [put! chan <! timeout dropping-buffer promise-chan] :as async]) #?(:cljs [cognitect.transit :as transit]) #?(:cljs [cljs.js :as cljs]) [membrane.component :as component :refer [#?(:clj defui) #?(:clj defeffect)]] #?(:clj [clojure.data.json :as json]) [membrane.basic-components :as basic :refer [button textarea]] [clojure.spec.alpha :as s] [spec-provider.provider :as sp] [clojure.spec.gen.alpha :as gen]) #?(:clj (:gen-class))) ;; layouts ;; https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/controls/layouts ;; - grid ;; - stack? ;; https://www.crazyegg.com/blog/guides/great-form-ui-and-ux/ ;; extra elements ;; - multi select ;; - radio button ;; - collapsable ;; Show all selection options if under 6 (defn imeta? [obj] #?(:clj (instance? clojure.lang.IObj obj) :cljs (satisfies? IMeta obj))) (defn maybe-with-meta [obj m] (if (imeta? obj) (with-meta obj m) obj)) (s/def :blades.user/info (s/keys :req [:blades.user/name :blades.user/look :blades.user/heritage :blades.user/background :blades.user/vice])) (s/def :blades.user/name string?) (s/def :blades.user/look (s/coll-of string? :kind vector?)) (s/def :blades.user/heritage (s/keys :req [:blades.heritage/description :blades.heritage/place])) (s/def :blades.heritage/description string?) (s/def :blades.heritage/place string?) (s/def :blades.user/background (s/keys :req [:blades.background/description :blades/place])) (s/def :blades.background/description string?) (s/def :blades/place string?) (s/def :blades.user/vice (s/keys :req [:blades.vice/description :blades.vice/category :blades/person])) (s/def :blades.vice/description string?) (s/def :blades.vice/category string?) (s/def :blades/person string?) #_(def blades-json { :info {:name "<NAME>" :look ["Male" "Long Cloak" "Tall Boots" "Tricorn Hat" "Collard Shirt" "Waistcoat"] :heritage {:description "Lowly crafters who couldn't pay the bills" :place "Akoros"} :background {:description "Grew up on the streets since there was no food at home" :place "Underworld"} :vice {:description "A thug with dulusions of grandeur, pleasure are suitably \"high\" class. Not that I can tell the difference." :person "<NAME>" :category "Pleasure"}} :status {:stress 4 :traumas ["Cold" "Haunted"] :harms ["welt on the back of the head" "holding a sword"] :armor {:armor false :heavy false :special true}} ;; :abilities ;; [] :attributes {:insight {:level 1 :hunt 0 :study 1 :survey 1 :tinker 0} :prowess {:level 1 :finesse 1 :prowl 1 :skirmish 3 :wreck 2} :resolve {:level 4 :attrune 1 :command 3 :consort 0 :sway 1}}}) (def blades-json { :blades.user/info {:blades.user/name "<NAME>" :blades.user/look ["Male" "Long Cloak" "Tall Boots" "Tricorn Hat" "Collard Shirt" "Waistcoat"] :blades.user/heritage {:blades.heritage/description "Lowly crafters who couldn't pay the bills" :blades.heritage/place "Akoros"} :blades.user/background {:blades.background/description "Grew up on the streets since there was no food at home" :blades/place "Underworld"} :blades.user/vice {:blades.vice/description "A thug with dulusions of grandeur, pleasure are suitably \"high\" class. Not that I can tell the difference." :blades/person "<NAME>" :blades.vice/category "Pleasure"}} :blades/status {:blades.status/stress 4 :blades.status/traumas ["Cold" "Haunted"] :blades.status/harms ["welt on the back of the head" "holding a sword"] :blades.status/armor {:blades.armor/armor false :blades.armor/heavy false :blades.armor/special true}} ;; :abilities ;; [] :attributes {:insight {:level 1 :hunt 0 :study 1 :survey 1 :tinker 0} :prowess {:level 1 :finesse 1 :prowl 1 :skirmish 3 :wreck 2} :resolve {:level 4 :attrune 1 :command 3 :consort 0 :sway 1}}}) (defn inc-context-depth [ctx] (-> ctx (update-in [:depth] inc) (dissoc :spec))) (defn list-editor []) (def gen-editors (atom {})) (defprotocol IGenEditor :extend-via-metadata true (gen-editor [this sym])) (defprotocol ISubGens (subgens [this])) (defprotocol IEditableProps (editable-props [this])) (defprotocol IGenInspector (gen-inspector [this])) (extend-type #?(:clj Object :cljs default) ISubGens (subgens [this] nil)) (extend-type #?(:clj Object :cljs default) IEditableProps (editable-props [this] nil)) (extend-type #?(:clj Object :cljs default) IGenInspector (gen-inspector [this] nil)) (extend-type nil IGenEditor (gen-editor [this sym] (ui/label "got null editor"))) (extend-type nil ISubGens (subgens [this] (prn "calling subgens with nil") nil)) ;; (extend-type nil ;; IGenProps ;; (genprops [this] ;; (prn "calling genprops with nil") ;; nil)) (extend-type nil IGenInspector (gen-inspector [this] nil)) (defprotocol IGenPred (gen-pred? [this obj])) (defmulti can-gen-from-spec? (fn [new-gen-type specs spec] new-gen-type)) (declare best-gen) (defmulti re-gen (fn [new-gen-type specs spec context] new-gen-type)) (defmacro defgen [name params & body] `(let [ret# (defrecord ~name ~params ~@body)] (swap! gen-editors assoc (quote ~name) ret#) ret#)) ;; (defmacro def-gen ;; ([name pred body] ;; `(def-gen ~name ~pred nil ~body)) ;; ([name pred children body] ;; `(let [gen# (with-meta ;; {:pred ~pred ;; :children ~children ;; :generate (fn [~'sym ~'obj ~'children ~'context] ;; ~body)} ;; {(quote ~`gen-editor) ;; (fn [this# sym# obj# children# context#] ;; ((:generate this#) sym# obj# children# context#))})] ;; (swap! gen-editors assoc (quote ~name) gen#) ;; (def ~name gen#)))) (defgen OrGen [opts context] ;; :preds in opts takes in a [pred? gen] ;; pred? should be a fully qualified symbol pointing to a single arity predicate function IGenPred (gen-pred? [this obj] (every? #(% obj) (map first (:preds opts)))) IGenEditor (gen-editor [this sym] `(cond ~@(apply concat (for [[pred? gen] (:preds opts)] (do (assert (symbol? pred?) "pred? must be a symbol") [`(~pred? ~sym) (gen-editor gen sym)])))))) (defmethod re-gen OrGen [_ specs spec context] (let [key-preds (rest spec)] (->OrGen {:preds (for [[k pred] (partition 2 key-preds)] [[pred (best-gen specs pred context)]])} context))) (defmethod can-gen-from-spec? OrGen [this specs spec] (and (seq? spec) (#{'clojure.spec.alpha/or 'cljs.spec.alpha/or} (first spec)))) (defgen SimpleTextAreaGen [opts context] IGenPred (gen-pred? [this obj] (string? obj)) IGenEditor (gen-editor [this sym] `(basic/textarea {:text ~sym}))) (defmethod re-gen SimpleTextAreaGen [_ specs spec context] (->SimpleTextAreaGen {} context)) (defmethod can-gen-from-spec? SimpleTextAreaGen [this specs spec] (#{'clojure.core/string? 'cljs.core/string?} spec )) (defui number-counter-inspector [{:keys [gen]}] (vertical-layout (let [min (get-in gen [:opts :min]) min-checked? (get extra :min-checked?) last-min (get extra :last-min)] (horizontal-layout (ui/label "min: ") (on :membrane.basic-components/toggle (fn [$min-checked?] (conj (if min-checked? [[:set $min nil] [:set $last-min min]] [[:set $min (or last-min 0)]]) [:membrane.basic-components/toggle $min-checked?])) (basic/checkbox {:checked? min-checked?})) (when min (basic/counter {:num min})))) (let [max (get-in gen [:opts :max]) max-checked? (get extra :max-checked?) last-max (get extra :last-max)] (horizontal-layout (ui/label "max: ") (on :membrane.basic-components/toggle (fn [$max-checked?] (conj (if max-checked? [[:set $max nil] [:set $last-max max]] [[:set $max (or last-max 0)]]) [:membrane.basic-components/toggle $max-checked?])) (basic/checkbox {:checked? max-checked?})) (when max (basic/counter {:num max})))))) (defgen NumberCounterGen [opts context] IGenInspector (gen-inspector [this] #'number-counter-inspector) IGenPred (gen-pred? [this obj] (number? obj)) IGenEditor (gen-editor [this sym] `(if (number? ~sym) (basic/counter {:num ~sym}) (ui/label (str ~sym " is NaN!")))) ) (defmethod re-gen NumberCounterGen [_ specs spec context] (->NumberCounterGen {} context)) (defmethod can-gen-from-spec? NumberCounterGen [this specs spec] (#{'clojure.core/integer? 'cljs.core/integer?} spec )) (defui number-slider-inspector [{:keys [gen]}] (vertical-layout (let [min (get-in gen [:opts :min] 0)] (horizontal-layout (ui/label "min: ") (basic/counter {:num min}))) (let [max (get-in gen [:opts :max] 100)] (horizontal-layout (ui/label "max: ") (basic/counter {:num max}))) (let [max-width (get-in gen [:opts :max-width] 100)] (horizontal-layout (ui/label "max-width: ") (basic/counter {:num max-width}))) (let [integer? (get-in gen [:opts :integer?] true)] (horizontal-layout (ui/label "integer? ") (basic/checkbox {:checked? integer?}))))) (defgen NumberSliderGen [opts context] IGenInspector (gen-inspector [this] #'number-slider-inspector) IGenPred (gen-pred? [this obj] (number? obj)) IGenEditor (gen-editor [this sym] `(if (number? ~sym) (basic/number-slider {:num ~sym :min ~(get opts :min 0) :max ~(get opts :max 100) :integer? ~(get opts :integer? true) :max-width ~(get opts :max-width 100)}) (ui/label (str ~sym " is not a NaN!")))) ) (defmethod re-gen NumberSliderGen [_ specs spec context] (->NumberSliderGen {} context)) (defmethod can-gen-from-spec? NumberSliderGen [this specs spec] (#{'clojure.core/integer? 'cljs.core/integer? 'clojure.core/number? 'cljs.core/number? 'clojure.core/float? 'cljs.core/float? 'clojure.core/double? 'cljs.core/double?} spec)) (defgen CheckboxGen [opts context] IGenPred (gen-pred? [this obj] (boolean? obj)) IGenEditor (gen-editor [this sym] `(basic/checkbox {:checked? ~sym}))) (defmethod re-gen CheckboxGen [_ specs spec context] (->CheckboxGen {} context)) (defmethod can-gen-from-spec? CheckboxGen [this specs spec] (#{'clojure.core/boolean? 'cljs.core/boolean?} spec)) (defgen TitleGen [opts context] IGenPred (gen-pred? [this obj] (or (string? obj) (keyword? obj))) IGenEditor (gen-editor [this sym] `(ui/label (let [s# (str (if (keyword? ~sym) (name ~sym) ~sym))] (clojure.string/capitalize s#)) (ui/font nil ~(max 16 (- 22 (* 4 (get context :depth 0))))))) ) (defmethod re-gen TitleGen [_ specs spec context] (->TitleGen {} context)) (defmethod can-gen-from-spec? TitleGen [this specs spec] (#{'clojure.core/string? 'cljs.core/string? 'clojure.core/keyword? 'cljs.core/keyword?} spec)) (defgen LabelGen [opts context] ;; IEditableProps ;; (editable-props [this] ;; {:font-size (number-inspector :max 40 ;; :min 12)}) ;; IGenProps ;; (genprops [this] ;; [:font-size]) IGenPred (gen-pred? [this obj] (or (string? obj) (keyword? obj))) IGenEditor (gen-editor [this sym] `(ui/label ~sym (ui/font nil ~(:font-size opts)))) ) (defmethod re-gen LabelGen [_ specs spec context] (->LabelGen {} context)) (defmethod can-gen-from-spec? LabelGen [this specs spec] true) #_(def-gen static-vector vector? {:x identity} (let [x-sym (gensym "x-")] `(apply vertical-layout (for [~x-sym ~sym] ~(ui-code x-sym (first obj) (inc-context-depth context)))))) #_(def-gen static-horizontal-vector vector? {:x identity} (let [x-sym (gensym "x-") ] `(apply horizontal-layout (for [~x-sym ~sym] ~(ui-code x-sym (first obj) (inc-context-depth context)))))) (defn delete-X [] (ui/with-style :membrane.ui/style-stroke (ui/with-color [1 0 0] (ui/with-stroke-width 3 [(ui/path [0 0] [10 10]) (ui/path [10 0] [0 10])])))) (defn ->$sym [sym] (symbol (str "$" (name sym))) ) #_(def-gen dynamic-vector vector? (let [x-sym (gensym "x-")] `(apply vertical-layout (basic/button :text "New" :on-click (fn [] [[:update ~(->$sym sym) conj (first ~sym)]])) (for [~x-sym ~sym] (horizontal-layout (on :mouse-down (fn [_#] [[:delete ~(->$sym x-sym)]]) (delete-X)) ~(ui-code x-sym (first obj) (inc-context-depth context))))))) #_(def-gen checkbox boolean? `(basic/checkbox :checked? ~sym)) (defn stack-img [outer-layout inner-layout inner-elem outer-elem] (let [padding 1 rect-size 4] (apply outer-layout (interpose (spacer 0 padding) (for [i (range 3)] (inner-layout (inner-elem rect-size) (spacer padding 0) (outer-elem rect-size))))))) (defn kv-vertical-img [] (stack-img vertical-layout horizontal-layout #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)))) (defn vk-vertical-img [] (stack-img vertical-layout horizontal-layout #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) )) (defn kv-horizontal-img [] (stack-img horizontal-layout vertical-layout #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)))) (defn vk-horizontal-img [] (stack-img horizontal-layout vertical-layout #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) )) (defn kv-all-horizontal-img [] (stack-img horizontal-layout horizontal-layout #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)))) (defn vk-all-horizontal-img [] (stack-img horizontal-layout horizontal-layout #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) )) (defn kv-all-vertical-img [] (stack-img vertical-layout vertical-layout #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)))) (defn vk-all-vertical-img [] (stack-img vertical-layout vertical-layout #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) )) (defn test-view [] (apply vertical-layout (interpose (spacer 0 10) [(kv-vertical-img) (vk-vertical-img) (kv-horizontal-img) (vk-horizontal-img) (kv-all-horizontal-img) (vk-all-horizontal-img) (kv-all-vertical-img) (vk-all-vertical-img)]))) (defui option-toggle [{:keys [flag true-text false-text]}] (horizontal-layout (ui/button true-text (fn [] (when-not flag [[:set $flag true]])) flag) (ui/button false-text (fn [] (when flag [[:set $flag false]])) (not flag)))) (defui static-map-gen-inspector [{:keys [gen]}] (let [horizontal-rows? (get-in gen [:opts :horizontal-rows?]) horizontal-cols? (get-in gen [:opts :horizontal-cols?]) kv-order? (get-in gen [:opts :kv-order?] true)] (vertical-layout (let [k-elem #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) v-elem #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) [inner-elem outer-elem] (if kv-order? [k-elem v-elem] [v-elem k-elem])] [(spacer 45 45) (ui/padding 5 5 (stack-img (if horizontal-rows? horizontal-layout vertical-layout) (if horizontal-cols? horizontal-layout vertical-layout) inner-elem outer-elem))]) (ui/label "key value layout order") (option-toggle {:flag kv-order? :true-text "kv" :false-text "vk"}) (ui/label "row direction") (option-toggle {:flag horizontal-rows? :true-text "horizontal" :false-text "vertical"}) (ui/label "column direction") (option-toggle {:flag horizontal-cols? :true-text "horizontal" :false-text "vertical"}) ) #_(horizontal-layout (ui/label "horizontal?") (ui/translate 5 5 (basic/checkbox :checked? horizontal?))))) (defgen StaticMapGen [opts context] IGenInspector (gen-inspector [this] #'static-map-gen-inspector) IEditableProps (editable-props [this] {:k gen-inspector :v gen-inspector}) ISubGens (subgens [this] [[:opts :k] [:opts :v]]) IGenPred (gen-pred? [this obj] (map? obj)) IGenEditor (gen-editor [this sym] (let [k-sym (gensym "k-") v-sym (gensym "v-") klabel-sym (gensym "klabel-") table-sym (gensym "table-")] `(ui/translate 10 10 (let [~table-sym (for [[~k-sym ~v-sym] ~sym] ~(let [k-elem `(let [~klabel-sym (maybe-with-meta ~(gen-editor (:k opts) k-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :k)])})] (vertical-layout ~klabel-sym ~(when (<= (:depth context) 1) `(let [lbl-width# (ui/width ~klabel-sym)] (ui/with-style :membrane.ui/style-stroke (ui/with-color [0 0 0] (ui/path [0 0] [lbl-width# 0]))))))) v-elem `(let [~v-sym (get ~sym ~k-sym)] (maybe-with-meta ~(gen-editor (:v opts) v-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :v)])}))] (if (get opts :kv-order? true) [k-elem v-elem] [v-elem k-elem]))) ] ~(if (= (:horizontal-rows? opts) (:horizontal-cols? opts)) (let [layout (if (:horizontal-rows? opts) `horizontal-layout `vertical-layout)] `(apply ~layout (apply concat ~table-sym))) `(ui/table-layout ~(if (:horizontal-rows? opts) table-sym `[(map first ~table-sym) (map second ~table-sym)])) ) ) #_(apply ~(if (:horizontal-rows? opts) `horizontal-layout `vertical-layout) (for [[~k-sym ~v-sym] ~sym] (~(if (:horizontal-cols? opts) `horizontal-layout `vertical-layout) ~@(let [k-elem `(let [~klabel-sym (maybe-with-meta ~(gen-editor (:k opts) k-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :k)])})] (vertical-layout ~klabel-sym ~(when (<= (:depth context) 1) `(let [lbl-width# (ui/width ~klabel-sym)] (ui/with-style :membrane.ui/style-stroke (ui/with-color [0 0 0] (ui/path [0 0] [lbl-width# 0]))))))) v-elem `(let [~v-sym (get ~sym ~k-sym)] (maybe-with-meta ~(gen-editor (:v opts) v-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :v)])}))] (if (get opts :kv-order? true) [k-elem v-elem] [v-elem k-elem])))) ))))) (defmethod re-gen StaticMapGen [_ specs spec context] (let [subcontext (inc-context-depth context)] (let [spec-fn (first spec)] (case spec-fn (clojure.spec.alpha/map-of cljs.spec.alpha/map-of) (let [[kpred vpred & opts] (rest spec) k-spec (if (keyword? kpred) (get specs kpred) kpred) k-gen (if (can-gen-from-spec? TitleGen specs k-spec) (->TitleGen {} (assoc subcontext :spec k-spec)) (best-gen specs k-spec subcontext)) v-spec (if (keyword? vpred) (get specs vpred) vpred)] (->StaticMapGen {:k k-gen :v (best-gen specs v-spec subcontext)} context)) (clojure.spec.alpha/keys cljs.spec.alpha/keys) (let [[& {:keys [req req-un opt opt-un gen]}] (rest spec) key-specs (concat req req-un opt opt-un) first-key-spec (get specs (first key-specs))] (->StaticMapGen {:k (->TitleGen {} (dissoc subcontext :spec)) :v (best-gen specs first-key-spec subcontext)} context)) ))) ) (defmethod can-gen-from-spec? StaticMapGen [this specs spec] (and (seq? spec) (let [spec-fn (first spec)] (or (#{'clojure.spec.alpha/map-of 'cljs.spec.alpha/map-of} spec-fn ) (and (#{'clojure.spec.alpha/keys 'cljs.spec.alpha/keys} spec-fn ) ;; all key specs should return the same gen type ;; this is so ugly. forgive me (let [[& {:keys [req req-un opt opt-un gen]}] (rest spec) key-specs (concat req req-un opt opt-un) context {:depth 0} example-gen-type (type (best-gen specs (get specs (first key-specs)) context))] (every? #(= example-gen-type (type (best-gen specs (get specs %) context))) (rest key-specs)))))))) (defgen StaticSeqGen [opts context] ISubGens (subgens [this] [[:opts :vals]]) IGenPred (gen-pred? [this obj] (and (seqable? obj) (not (or (map? obj) (string? obj))))) IGenEditor (gen-editor [this sym] (let [v-sym (gensym "v-")] `(ui/translate 10 10 (apply ~(if (:horizontal? opts) `horizontal-layout `vertical-layout) (for [~v-sym ~sym] (maybe-with-meta ~(gen-editor (:vals opts) v-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :vals)])}))))))) (defmethod re-gen StaticSeqGen [_ specs spec context] (assert (can-gen-from-spec? StaticSeqGen specs spec)) (->StaticSeqGen {:vals (best-gen specs (second spec) (inc-context-depth context))} context)) (defmethod can-gen-from-spec? StaticSeqGen [this specs spec] (and (seq? spec) (#{'clojure.spec.alpha/coll-of 'cljs.spec.alpha/coll-of} (first spec)))) (defui keymap-gen-inspector [{:keys [gen]}] (let [bordered? (get-in gen [:opts :bordered?] true)] (horizontal-layout (ui/label "bordered?") (ui/translate 5 5 (basic/checkbox {:checked? bordered?}))))) (defgen KeyMapGen [opts context] IGenInspector (gen-inspector [this] #'keymap-gen-inspector) ISubGens (subgens [this] (conj (map #(vector :opts :val-gens %) (keys (:val-gens opts))) [:opts :k])) IGenPred (gen-pred? [this obj] (map? obj)) IGenEditor (gen-editor [this sym] (let [body `(vertical-layout ~@(apply concat (for [[k subgen] (:val-gens opts)] (let [v-sym (gensym "v-")] `[(maybe-with-meta ~(gen-editor (:k opts) k) ~{:relative-identity '(quote [(keypath :opts) (keypath :k)])}) (let [~v-sym (get ~sym ~k)] (maybe-with-meta ~(gen-editor subgen v-sym) ~{:relative-identity [(quote '(keypath :opts)) (quote '(keypath :val-gens)) (list 'list (list 'quote 'keypath) k)]}))])))) body (if (get opts :bordered? true) `(ui/bordered [5 5] ~body) body)] body))) (defmethod re-gen KeyMapGen [_ specs spec context] (assert (can-gen-from-spec? KeyMapGen specs spec)) (let [subcontext (inc-context-depth context) [& {:keys [req req-un opt opt-un gen]}] (rest spec)] (->KeyMapGen {:k (->TitleGen {} (dissoc subcontext :spec)) :val-gens (into {} (concat (for [k (concat req opt)] [k (best-gen specs (get specs k) subcontext)]) (for [k (concat req-un opt-un)] [(keyword (name k)) (best-gen specs (get specs k) subcontext)]))) :bordered? (if-let [depth (:depth context)] (pos? depth) true)} context))) (defmethod can-gen-from-spec? KeyMapGen [this specs spec] (and (seq? spec) (#{'clojure.spec.alpha/keys 'cljs.spec.alpha/keys} (first spec)))) (defui cat-gen-inspector [{:keys [gen]}] (let [bordered? (get-in gen [:opts :bordered?] true)] (horizontal-layout (ui/label "bordered?") (ui/translate 5 5 (basic/checkbox {:checked? bordered?}))))) (defgen CatGen [opts context] IGenInspector (gen-inspector [this] #'cat-gen-inspector) ISubGens (subgens [this] (map #(vector :opts :val-gens %) (range (count (:val-gens opts))))) IGenPred (gen-pred? [this obj] (and (seqable? obj) (not (or (map? obj) (string? obj))))) IGenEditor (gen-editor [this sym] (let [body `(vertical-layout ~@(apply concat (for [[i subgen] (map-indexed vector (:val-gens opts))] (let [v-sym (gensym "v-")] `[(let [~v-sym (nth ~sym ~i)] (maybe-with-meta ~(gen-editor subgen v-sym) ~{:relative-identity [(quote '(keypath :opts)) (quote '(keypath :val-gens)) (list 'list (list 'quote 'nth) i)]}))])))) body (if (get opts :bordered? true) `(ui/bordered [5 5] ~body) body)] body))) (defmethod re-gen CatGen [_ specs spec context] (assert (can-gen-from-spec? CatGen specs spec)) (let [subcontext (inc-context-depth context) val-specs (take-nth 2 (drop 2 spec))] (->CatGen {:val-gens (vec (for [val-spec val-specs] (best-gen specs (get specs val-spec val-spec) subcontext))) :bordered? (if-let [depth (:depth context)] (pos? depth) true)} context))) (defmethod can-gen-from-spec? CatGen [this specs spec] (and (seq? spec) (= 'clojure.spec.alpha/cat (first spec)))) (defn first-matching-gen [obj] (some #(when ((:pred %) obj) %) (vals @gen-editors)) ) #_(defn ui-code ([sym obj context] (let [generator (first-matching-gen obj) children (into {} (for [[k v] (:children generator)] [k (fn [sym context] (ui-code sym (first (v obj)) (inc-context-depth context)))]))] (assert generator (str "No generator for " (pr-str obj)) ) (gen-editor generator sym obj children context)))) (defn auto-component [ui-name ge] (let [arg-sym 'obj] `(defui ~ui-name [{:keys [~arg-sym]}] (basic/scrollview {:bounds [800 800] :body ~(gen-editor ge arg-sym)})))) (defn def-auto-component [ui-name ge] (let [code (auto-component ui-name ge)] (eval code))) #_(def-auto-component 'testblades (best-gen blades-json)) #_(def-auto-component map-example {:a 1 :b 2 :c 3}) (def testgen (let [context {:depth 0} subcontext (inc-context-depth context)] (->StaticMapGen {:k (->LabelGen {} subcontext) :v (->NumberCounterGen {} subcontext) #_ (->LabelGen {} subcontext)} context))) ;; todo ;; - have a way to set data ;; - have a way to generate the gen-tree ;; - have a way to swap out alternatives (do (defn infer-specs ([obj] (infer-specs obj :membrane.autoui/infer-specs)) ([obj spec-name] (let [inferred (sp/infer-specs [obj] spec-name) specs (into {} (for [[def k spec] inferred] [k spec]))] specs))) (defn best-gen ([obj] (let [spec-name :membrane.autoui/infer-specs specs (infer-specs obj spec-name)] (best-gen specs (get specs spec-name) {:depth 0 :specs specs}))) ([specs spec context] (let [gen (cond (#{'clojure.core/string? 'cljs.core/string?} spec ) (->SimpleTextAreaGen {} context) (#{'clojure.core/boolean? 'cljs.core/boolean?} spec ) (->CheckboxGen {} context) (#{'clojure.core/keyword? 'cljs.core/keyword?} spec ) (->TitleGen {} context) (#{'clojure.core/simple-symbol?} spec ) (->TitleGen {} context) (#{'clojure.core/integer? 'cljs.core/integer? } spec ) (->NumberCounterGen {} context) ('#{clojure.core/double? cljs.core/double? clojure.core/float? cljs.core/float?} spec) (->NumberSliderGen {} context) (seq? spec) (case (first spec) (clojure.spec.alpha/coll-of cljs.spec.alpha/coll-of) (let [[pred & {:keys [into kind count max-count min-count distinct gen-max gen]}] (rest spec) subcontext (inc-context-depth context) ] (->StaticSeqGen {:vals (best-gen specs pred subcontext)} context) ) clojure.spec.alpha/cat (let [] (re-gen CatGen specs spec context)) clojure.spec.alpha/? (let [pred (second spec) subcontext (inc-context-depth context)] (best-gen specs pred subcontext)) clojure.spec.alpha/* (let [pred (second spec) subcontext (inc-context-depth context)] (->StaticSeqGen {:vals (best-gen specs pred subcontext)} context)) (clojure.spec.alpha/keys cljs.spec.alpha/keys) (re-gen KeyMapGen specs spec context) (clojure.spec.alpha/map-of) (re-gen StaticMapGen specs spec context) (clojure.spec.alpha/or cljs.spec.alpha/or) (let [key-preds (rest spec)] (->OrGen {:preds (for [[k pred] (partition 2 key-preds)] [[pred (best-gen specs pred context)]])} context)) ;; else (str "unknown spec: " (first spec)) ) :else (str "unknown spec: " spec) )] (if (satisfies? IGenEditor gen) (assoc-in gen [:context :spec] spec) gen))) ) #_(prn (let [obj blades-json] (best-gen obj)))) (defn gen-options [specs spec] (->> @gen-editors vals (filter #(can-gen-from-spec? % specs spec)))) (def testgen2 (let [ge testgen] (->KeyMapGen {:k (:k (:opts ge)) :val-gens {:a (->NumberCounterGen {} (:context (:v (:opts ge)))) :b (->LabelGen {} (:context (:v (:opts ge)))) :c (->TitleGen {} (:context (:v (:opts ge))))}} (:context ge)))) (defui foldable-section [{:keys [title body visible?] :or {visible? true}}] (vertical-layout (on :mouse-down (fn [_] [[:update $visible? not]]) [#_(ui/filled-rectangle [0.9 0.9 0.9] 200 20) (horizontal-layout (let [size 5] (ui/with-style :membrane.ui/style-stroke-and-fill (if visible? (ui/translate 5 8 (ui/path [0 0] [size size] [(* 2 size) 0])) (ui/translate 5 5 (ui/path [0 0] [size size] [0 (* 2 size)]))))) (spacer 5 0) (ui/label title)) ]) (when visible? (ui/translate 10 0 body)))) (defn pr-label [obj] (let [s (pr-str obj)] (ui/label (subs s 0 (min (count s) 37))))) (defn get-gen-name [ge] #?(:clj (.getSimpleName ge) :cljs (pr-str ge))) ;; forward declare (defui gen-editor-inspector [{:keys [ge]}]) (defui gen-editor-inspector [{:keys [ge]}] (let [sub (subgens ge)] (foldable-section {:title (if-let [spec (-> ge :context :spec)] (pr-str spec) (get-gen-name (type ge))) :visible? (get extra [:foldable-visible $ge] true) :body (apply vertical-layout (when-let [spec (-> ge :context :spec)] (when-let [specs (-> ge :context :specs)] (vertical-layout (pr-label spec) (let [options (gen-options specs spec)] (apply horizontal-layout (for [option options] (basic/button {:text (get-gen-name option) :hover? (get extra [:switch :hover? option]) :on-click (fn [] [[:set $ge (re-gen option specs spec (:context ge))]])}))))))) (when-let [inspector (gen-inspector ge)] (let [inspector-extra (get extra [$ge :extra])] (inspector {:gen ge :$gen $ge :extra inspector-extra :$extra $inspector-extra :context context :$context $context}))) (for [k sub] (let [v (get-in ge k)] (gen-editor-inspector {:ge v}))))}))) (defn find-under ([pos elem delta] (find-under pos elem (Math/pow delta 2) nil [])) ([pos elem d2 elem-index ident] (let [[x y] pos [ox oy] (ui/origin elem) [width height] (ui/bounds elem) local-x (int (- x ox)) local-y (int (- y oy)) new-pos [local-x local-y] elem-meta (meta elem)] (if-let [m elem-meta] (if-let [identity (:identity m)] (let [child-results (mapcat #(find-under new-pos % d2 elem-index [identity]) (ui/children elem))] (if (and (< (Math/pow local-x 2) d2) (< (Math/pow local-y 2) d2)) (conj child-results {:elem elem :pos new-pos :identity identity}) child-results)) (if-let [relative-identity (:relative-identity m)] (let [identity (into ident relative-identity) child-results (mapcat #(find-under new-pos % d2 elem-index identity) (ui/children elem))] (if (and (< (Math/pow local-x 2) d2) (< (Math/pow local-y 2) d2)) (conj child-results {:elem elem :pos new-pos :identity identity}) child-results)) (mapcat #(find-under new-pos % d2 elem-index ident) (ui/children elem)))) (mapcat #(find-under new-pos % d2 elem-index ident) (ui/children elem)))))) (defn draw-circles ([elem] (draw-circles elem [0 0])) ([elem pos] (let [[x y] pos [ox oy] (ui/origin elem) [width height] (ui/bounds elem) local-x (int (+ x ox)) local-y (int (+ y oy)) new-pos [local-x local-y] elem-meta (meta elem)] (if-let [m elem-meta] (if-let [identity (:identity m)] (let [child-results (mapcat #(draw-circles % new-pos) (ui/children elem))] (conj child-results new-pos)) (if-let [relative-identity (:relative-identity m)] (let [child-results (mapcat #(draw-circles % new-pos) (ui/children elem))] (conj child-results new-pos)) (mapcat #(draw-circles % new-pos) (ui/children elem)))) (mapcat #(draw-circles % new-pos) (ui/children elem)))))) (def ^:dynamic *obj* nil) (def ^:dynamic *$ge* nil) (declare background-eval) (defui eval-form [{:keys [form eval-context cache eval-key]}] (let [cache (or cache {}) result (background-eval form eval-context cache $cache eval-key)] ;; (prn "result:" result) result)) (defui gen-editor-editor [{:keys [ge obj selected-ge-path ge-options]}] (horizontal-layout (basic/scrollview {:scroll-bounds [400 800] :body (let [body (ui/no-events (ui/try-draw (let [drawable #?(:clj (binding [*obj* obj *$ge* []] ;; (clojure.pprint/pprint (gen-editor ge 'obj)) (eval `(let [~'obj *obj*] (maybe-with-meta ~(gen-editor ge 'obj) {:identity *$ge*})))) :cljs (eval-form {:form `(maybe-with-meta ~(gen-editor ge 'obj) {:identity ~'ident}) :eval-context {'ident *$ge* 'obj obj} :eval-key ge}) ) ] drawable) (fn [draw e] (println e) (draw (ui/label "whoops!"))))) circles (delay (mapv (fn [[x y]] (ui/translate (- x 5) (- y 5) (ui/filled-rectangle [1 0 0] 10 10))) (draw-circles body)))] [ (on :mouse-down (fn [pos] (let [results (seq (find-under pos body 5))] (if-let [results results] (if (= (count results) 1) (let [ident (:identity (first results))] [[:set $selected-ge-path ident]]) [[:set $ge-options {:pos pos :options (vec (for [{:keys [elem pos elem-index identity]} results] [identity (get-gen-name (type (spec/select-one (component/path->spec [identity]) ge)))]))}]]) [[:set $selected-ge-path nil] [:set $ge-options nil]]))) body) ;; @circles (when ge-options (let [options-pos (:pos ge-options) options (:options ge-options)] (ui/translate (first options-pos) (second options-pos) (on ::basic/select (fn [_ $ident] [[:set $ge-options nil] [:set $selected-ge-path $ident]]) (basic/dropdown-list {:options options})))))])}) (let [[edit-ge $edit-ge] (if selected-ge-path [(spec/select-one (component/path->spec [selected-ge-path]) ge) [$ge selected-ge-path]] [ge $ge])] (basic/scrollview {:scroll-bounds [800 800] :body (gen-editor-inspector {:ge edit-ge :$ge $edit-ge})})))) (defui test-edit [{:keys [title?]}] (vertical-layout (horizontal-layout (ui/label "title?") (basic/checkbox {:checked? title?})) (let [testgen (if title? (-> testgen (assoc-in [:opts :k] (->TitleGen {} (:context (get-in testgen [:opts :k])))) (assoc-in [:opts :v] (->TitleGen {} (:context (get-in testgen [:opts :v]))))) testgen)] (eval`(let [~'m {:a 1 :b 2}] ~(gen-editor testgen 'm)))))) (comment (let [obj blades-json ge (best-gen obj)] (def editor-state (skia/run (component/make-app #'gen-editor-editor {:ge ge :obj obj}))))) (defn start-blades [] (let [obj blades-json ge (best-gen obj)] (def editor-state (skia/run (component/make-app #'gen-editor-editor {:ge ge :obj obj}))))) (comment (def test-data (with-open [rdr (clojure.java.io/reader "/var/tmp/test-savegame.json")] (clojure.data.json/read rdr :key-fn keyword)))) (comment (start-form-builder {:x 2, :y 10, :data ":/gamedata/enemies/test-enemy.json", :character {:role "Enemy", :wisdom 10, :weapon "", :firearm "", :experience 100, :mana 10, :inventory [{:data ":/gamedata/items/plants/healing-herb.json", :count 2} {:data ":/gamedata/items/weapons/sword.json", :count 2}], :strength 10, :healthMax 200, :manaMax 10, :health 200, :gender "male", :stealth 0}})) (defn start-form-builder [obj] (let [ge (best-gen obj)] (def editor-state (skia/run (component/make-app #'gen-editor-editor {:ge ge :obj obj}))))) (defn start-spec [] (let [obj (list 10 "Asfa") ge (let [specs {} #_(into {} (for [[k v] (s/registry) :let [form (try (s/form v) (catch Exception e nil))] :when form] [k form]))] (best-gen specs `(s/cat :foo integer? :bar string?) {:depth 0 :specs specs}))] (def editor-state (skia/run (component/make-app #'gen-editor-editor {:ge ge :obj obj}))))) #_(defui blades-scroll [{:keys [obj]}] (basic/scrollview :scroll-bounds [800 800] :body (testblades :obj obj))) ;; examples of using macros with eval ;; https://github.com/clojure/clojurescript/blob/master/src/test/self/self_host/test.cljs#L392 ;; from @mfikes on clojurians regarding AOT and macros ;; You have to roll your own way of doing that. Planck does this https://blog.fikesfarm.com/posts/2016-02-03-planck-macros-aot.html ;; The high-level idea is that you can use a build-time self-hosted compiler to compile macros namespaces down to JavaScript. ;; Also Replete does this as well, all in the name of fast loading. So, you can look at Plank and Replete as inspiration on how to do this. There might be other examples out there as well. #?(:cljs (do (def cljstate (cljs/empty-state)) (def aot-caches [ "js/compiled/out.autouitest/clojure/zip.cljs.cache.json" "js/compiled/out.autouitest/clojure/string.cljs.cache.json" "js/compiled/out.autouitest/clojure/walk.cljs.cache.json" "js/compiled/out.autouitest/clojure/set.cljs.cache.json" "js/compiled/out.autouitest/cognitect/transit.cljs.cache.json" "js/compiled/out.autouitest/spec_provider/util.cljc.cache.json" "js/compiled/out.autouitest/spec_provider/merge.cljc.cache.json" "js/compiled/out.autouitest/spec_provider/rewrite.cljc.cache.json" "js/compiled/out.autouitest/spec_provider/stats.cljc.cache.json" "js/compiled/out.autouitest/spec_provider/provider.cljc.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/impl/commons.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/impl/utils.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/impl/errors.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/impl/inspect.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/edn.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/reader_types.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader.cljs.cache.json" "js/compiled/out.autouitest/cljs/env.cljc.cache.json" "js/compiled/out.autouitest/cljs/core/async.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/channels.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/dispatch.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/timers.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/buffers.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/protocols.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/ioc_helpers.cljs.cache.json" "js/compiled/out.autouitest/cljs/compiler.cljc.cache.json" "js/compiled/out.autouitest/cljs/analyzer.cljc.cache.json" "js/compiled/out.autouitest/cljs/tagged_literals.cljc.cache.json" "js/compiled/out.autouitest/cljs/spec/test/alpha.cljs.cache.json" "js/compiled/out.autouitest/cljs/spec/gen/alpha.cljs.cache.json" "js/compiled/out.autouitest/cljs/spec/alpha.cljs.cache.json" "js/compiled/out.autouitest/cljs/reader.cljs.cache.json" "js/compiled/out.autouitest/cljs/source_map.cljs.cache.json" "js/compiled/out.autouitest/cljs/js.cljs.cache.json" "js/compiled/out.autouitest/cljs/pprint.cljs.cache.json" "js/compiled/out.autouitest/cljs/source_map/base64.cljs.cache.json" "js/compiled/out.autouitest/cljs/source_map/base64_vlq.cljs.cache.json" "js/compiled/out.autouitest/cljs/core$macros.cljc.cache.json" "js/compiled/out.autouitest/cljs/analyzer/api.cljc.cache.json" "js/compiled/out.autouitest/cljs/stacktrace.cljc.cache.json" "js/compiled/out.autouitest/membrane/audio.cljs.cache.json" "js/compiled/out.autouitest/membrane/jsonee.cljc.cache.json" "js/compiled/out.autouitest/membrane/webgl.cljs.cache.json" "js/compiled/out.autouitest/membrane/basic_components.cljc.cache.json" "js/compiled/out.autouitest/membrane/autoui.cljc.cache.json" "js/compiled/out.autouitest/membrane/builder.cljc.cache.json" "js/compiled/out.autouitest/membrane/ui.cljc.cache.json" "js/compiled/out.autouitest/membrane/component.cljc.cache.json" "js/compiled/out.autouitest/membrane/analyze.cljc.cache.json" "js/compiled/out.autouitest/membrane/example/counter.cljc.cache.json" "js/compiled/out.autouitest/membrane/example/todo.cljc.cache.json" "js/compiled/out.autouitest/membrane/macroexpand.cljs.cache.json" "js/compiled/out.autouitest/membrane/vdom.cljs.cache.json" "js/compiled/out.autouitest/membrane/eval.cljs.cache.json" "js/compiled/out.autouitest/membrane/webgltest.cljs.cache.json" "js/compiled/out.autouitest/com/rpl/specter.cljc.cache.json" "js/compiled/out.autouitest/com/rpl/specter/protocols.cljc.cache.json" "js/compiled/out.autouitest/com/rpl/specter/impl.cljc.cache.json" "js/compiled/out.autouitest/com/rpl/specter/navs.cljc.cache.json" "js/compiled/out.autouitest/vdom/core.cljs.cache.json" "js/compiled/out.autouitest/process/env.cljs.cache.json" ] ) (defn load-cache [state cache-path] (let [ch (chan 1)] (membrane.eval/get-file cache-path (fn [source] (try (let [ rdr (transit/reader :json) cache (transit/read rdr source) ns (:name cache)] (cljs.js/load-analysis-cache! state ns cache) (prn "loaded " cache-path)) (finally (async/close! ch))))) ch)) (let [state cljstate] (async/go (let [] (let [chs (doall (map (fn [path] (load-cache state path)) aot-caches))] (doseq [ch chs] (<! ch))) (println "loaded all cached") (async/go #_(prn (<! (membrane.eval/eval-async state '(require-macros '[membrane.component :refer [defui]]) #_(:require [membrane.audio :as audio])))) (let [obj blades-json ge (best-gen obj)] (def canvas (.getElementById js/document "canvas")) #_(defonce start-auto-app (membrane.component/run-ui #'gen-editor-editor {:ge ge :obj obj} nil {:container canvas})) #_(defonce start-auto-app (membrane.component/run-ui #'gen-editor-editor {:ge ge :obj obj} nil {:container (js/document.getElementById "app")}))) (def background-eval-context (atom {})) (def background-eval-context-key (atom 0)) (defn background-eval [form eval-context cache $cache eval-key] (if (contains? cache eval-key) (get cache eval-key) (let [context-key (swap! background-eval-context-key inc)] (spec/transform (component/path->spec $cache) (fn [m] (assoc m eval-key (ui/label "loading..."))) start-auto-app) (async/go (swap! background-eval-context assoc context-key eval-context) (let [bindings (for [[sym val] eval-context] [sym `(get-in @background-eval-context [~context-key (quote ~sym)])]) form-with-context `(let ~(vec (apply concat bindings)) ~form) result (<! (membrane.eval/eval-async cljstate form-with-context))] ;; (prn result) (if (:error result) (do (prn "error " (:error result)) (spec/transform (component/path->spec $cache) (fn [m] (assoc m eval-key (ui/label "error evaling...."))) start-auto-app)) (spec/transform (component/path->spec $cache) (fn [m] (assoc m eval-key (:value result))) start-auto-app)) (swap! background-eval-context dissoc context-key))) (ui/label "loading..."))))))) (set! (.-evaltest js/window ) (fn [] (let [source '(membrane.component/defui my-foo [{:keys [ a b]}]) ] (cljs/eval state source membrane.eval/default-compiler-options #(prn %))))) (set! (.-evaltually js/window) (fn [source] (cljs/eval-str state source nil membrane.eval/default-compiler-options #(prn %)) )) (set! (.-evaltually_statement js/window) (fn [source] (cljs/eval-str state source nil (assoc membrane.eval/default-compiler-options :context :statement) #(prn %))))))) (comment #?(:cljs (do (defn default-load-fn [{:keys [name macros path] :as m} cb] (prn "trying to load" m) (throw "whoops!")) (defn wrap-js-eval [resource] (try (cljs/js-eval resource) (catch js/Object e {::error e}))) (def compiler-options {:source-map true ;; :context :statement :ns 'test.ns :verbose true :load default-load-fn :def-emits-var true :eval wrap-js-eval}) (def state (cljs/empty-state)) (defn eval-next [statements] (when-let [statement (first statements)] (prn "evaling " statement) (cljs/eval state statement compiler-options #(do (prn "result: " %) (eval-next (rest statements)))))) (eval-next [ '(ns test.ns) '(defmacro test-macro [& body] `(vector 42 ~@body)) '(test-macro 123) ;; console log: ;; "evaling " (test-macro 123) ;; "result: " [42] ]))))
true
(ns membrane.autoui #?(:cljs (:require-macros [membrane.component :refer [defui defeffect]] [membrane.autoui :refer [defgen]])) (:require #?(:clj [membrane.skia :as skia]) #?(:cljs membrane.webgl) ;; #?(:cljs membrane.vdom) [membrane.ui :as ui :refer [vertical-layout translate horizontal-layout label with-color bounds spacer on]] [com.rpl.specter :as spec] #?(:cljs [cljs.reader :refer [read-string]]) #?(:cljs [membrane.eval]) #?(:cljs [cljs.core.async :refer [put! chan <! timeout dropping-buffer promise-chan] :as async]) #?(:cljs [cognitect.transit :as transit]) #?(:cljs [cljs.js :as cljs]) [membrane.component :as component :refer [#?(:clj defui) #?(:clj defeffect)]] #?(:clj [clojure.data.json :as json]) [membrane.basic-components :as basic :refer [button textarea]] [clojure.spec.alpha :as s] [spec-provider.provider :as sp] [clojure.spec.gen.alpha :as gen]) #?(:clj (:gen-class))) ;; layouts ;; https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/controls/layouts ;; - grid ;; - stack? ;; https://www.crazyegg.com/blog/guides/great-form-ui-and-ux/ ;; extra elements ;; - multi select ;; - radio button ;; - collapsable ;; Show all selection options if under 6 (defn imeta? [obj] #?(:clj (instance? clojure.lang.IObj obj) :cljs (satisfies? IMeta obj))) (defn maybe-with-meta [obj m] (if (imeta? obj) (with-meta obj m) obj)) (s/def :blades.user/info (s/keys :req [:blades.user/name :blades.user/look :blades.user/heritage :blades.user/background :blades.user/vice])) (s/def :blades.user/name string?) (s/def :blades.user/look (s/coll-of string? :kind vector?)) (s/def :blades.user/heritage (s/keys :req [:blades.heritage/description :blades.heritage/place])) (s/def :blades.heritage/description string?) (s/def :blades.heritage/place string?) (s/def :blades.user/background (s/keys :req [:blades.background/description :blades/place])) (s/def :blades.background/description string?) (s/def :blades/place string?) (s/def :blades.user/vice (s/keys :req [:blades.vice/description :blades.vice/category :blades/person])) (s/def :blades.vice/description string?) (s/def :blades.vice/category string?) (s/def :blades/person string?) #_(def blades-json { :info {:name "PI:NAME:<NAME>END_PI" :look ["Male" "Long Cloak" "Tall Boots" "Tricorn Hat" "Collard Shirt" "Waistcoat"] :heritage {:description "Lowly crafters who couldn't pay the bills" :place "Akoros"} :background {:description "Grew up on the streets since there was no food at home" :place "Underworld"} :vice {:description "A thug with dulusions of grandeur, pleasure are suitably \"high\" class. Not that I can tell the difference." :person "PI:NAME:<NAME>END_PI" :category "Pleasure"}} :status {:stress 4 :traumas ["Cold" "Haunted"] :harms ["welt on the back of the head" "holding a sword"] :armor {:armor false :heavy false :special true}} ;; :abilities ;; [] :attributes {:insight {:level 1 :hunt 0 :study 1 :survey 1 :tinker 0} :prowess {:level 1 :finesse 1 :prowl 1 :skirmish 3 :wreck 2} :resolve {:level 4 :attrune 1 :command 3 :consort 0 :sway 1}}}) (def blades-json { :blades.user/info {:blades.user/name "PI:NAME:<NAME>END_PI" :blades.user/look ["Male" "Long Cloak" "Tall Boots" "Tricorn Hat" "Collard Shirt" "Waistcoat"] :blades.user/heritage {:blades.heritage/description "Lowly crafters who couldn't pay the bills" :blades.heritage/place "Akoros"} :blades.user/background {:blades.background/description "Grew up on the streets since there was no food at home" :blades/place "Underworld"} :blades.user/vice {:blades.vice/description "A thug with dulusions of grandeur, pleasure are suitably \"high\" class. Not that I can tell the difference." :blades/person "PI:NAME:<NAME>END_PI" :blades.vice/category "Pleasure"}} :blades/status {:blades.status/stress 4 :blades.status/traumas ["Cold" "Haunted"] :blades.status/harms ["welt on the back of the head" "holding a sword"] :blades.status/armor {:blades.armor/armor false :blades.armor/heavy false :blades.armor/special true}} ;; :abilities ;; [] :attributes {:insight {:level 1 :hunt 0 :study 1 :survey 1 :tinker 0} :prowess {:level 1 :finesse 1 :prowl 1 :skirmish 3 :wreck 2} :resolve {:level 4 :attrune 1 :command 3 :consort 0 :sway 1}}}) (defn inc-context-depth [ctx] (-> ctx (update-in [:depth] inc) (dissoc :spec))) (defn list-editor []) (def gen-editors (atom {})) (defprotocol IGenEditor :extend-via-metadata true (gen-editor [this sym])) (defprotocol ISubGens (subgens [this])) (defprotocol IEditableProps (editable-props [this])) (defprotocol IGenInspector (gen-inspector [this])) (extend-type #?(:clj Object :cljs default) ISubGens (subgens [this] nil)) (extend-type #?(:clj Object :cljs default) IEditableProps (editable-props [this] nil)) (extend-type #?(:clj Object :cljs default) IGenInspector (gen-inspector [this] nil)) (extend-type nil IGenEditor (gen-editor [this sym] (ui/label "got null editor"))) (extend-type nil ISubGens (subgens [this] (prn "calling subgens with nil") nil)) ;; (extend-type nil ;; IGenProps ;; (genprops [this] ;; (prn "calling genprops with nil") ;; nil)) (extend-type nil IGenInspector (gen-inspector [this] nil)) (defprotocol IGenPred (gen-pred? [this obj])) (defmulti can-gen-from-spec? (fn [new-gen-type specs spec] new-gen-type)) (declare best-gen) (defmulti re-gen (fn [new-gen-type specs spec context] new-gen-type)) (defmacro defgen [name params & body] `(let [ret# (defrecord ~name ~params ~@body)] (swap! gen-editors assoc (quote ~name) ret#) ret#)) ;; (defmacro def-gen ;; ([name pred body] ;; `(def-gen ~name ~pred nil ~body)) ;; ([name pred children body] ;; `(let [gen# (with-meta ;; {:pred ~pred ;; :children ~children ;; :generate (fn [~'sym ~'obj ~'children ~'context] ;; ~body)} ;; {(quote ~`gen-editor) ;; (fn [this# sym# obj# children# context#] ;; ((:generate this#) sym# obj# children# context#))})] ;; (swap! gen-editors assoc (quote ~name) gen#) ;; (def ~name gen#)))) (defgen OrGen [opts context] ;; :preds in opts takes in a [pred? gen] ;; pred? should be a fully qualified symbol pointing to a single arity predicate function IGenPred (gen-pred? [this obj] (every? #(% obj) (map first (:preds opts)))) IGenEditor (gen-editor [this sym] `(cond ~@(apply concat (for [[pred? gen] (:preds opts)] (do (assert (symbol? pred?) "pred? must be a symbol") [`(~pred? ~sym) (gen-editor gen sym)])))))) (defmethod re-gen OrGen [_ specs spec context] (let [key-preds (rest spec)] (->OrGen {:preds (for [[k pred] (partition 2 key-preds)] [[pred (best-gen specs pred context)]])} context))) (defmethod can-gen-from-spec? OrGen [this specs spec] (and (seq? spec) (#{'clojure.spec.alpha/or 'cljs.spec.alpha/or} (first spec)))) (defgen SimpleTextAreaGen [opts context] IGenPred (gen-pred? [this obj] (string? obj)) IGenEditor (gen-editor [this sym] `(basic/textarea {:text ~sym}))) (defmethod re-gen SimpleTextAreaGen [_ specs spec context] (->SimpleTextAreaGen {} context)) (defmethod can-gen-from-spec? SimpleTextAreaGen [this specs spec] (#{'clojure.core/string? 'cljs.core/string?} spec )) (defui number-counter-inspector [{:keys [gen]}] (vertical-layout (let [min (get-in gen [:opts :min]) min-checked? (get extra :min-checked?) last-min (get extra :last-min)] (horizontal-layout (ui/label "min: ") (on :membrane.basic-components/toggle (fn [$min-checked?] (conj (if min-checked? [[:set $min nil] [:set $last-min min]] [[:set $min (or last-min 0)]]) [:membrane.basic-components/toggle $min-checked?])) (basic/checkbox {:checked? min-checked?})) (when min (basic/counter {:num min})))) (let [max (get-in gen [:opts :max]) max-checked? (get extra :max-checked?) last-max (get extra :last-max)] (horizontal-layout (ui/label "max: ") (on :membrane.basic-components/toggle (fn [$max-checked?] (conj (if max-checked? [[:set $max nil] [:set $last-max max]] [[:set $max (or last-max 0)]]) [:membrane.basic-components/toggle $max-checked?])) (basic/checkbox {:checked? max-checked?})) (when max (basic/counter {:num max})))))) (defgen NumberCounterGen [opts context] IGenInspector (gen-inspector [this] #'number-counter-inspector) IGenPred (gen-pred? [this obj] (number? obj)) IGenEditor (gen-editor [this sym] `(if (number? ~sym) (basic/counter {:num ~sym}) (ui/label (str ~sym " is NaN!")))) ) (defmethod re-gen NumberCounterGen [_ specs spec context] (->NumberCounterGen {} context)) (defmethod can-gen-from-spec? NumberCounterGen [this specs spec] (#{'clojure.core/integer? 'cljs.core/integer?} spec )) (defui number-slider-inspector [{:keys [gen]}] (vertical-layout (let [min (get-in gen [:opts :min] 0)] (horizontal-layout (ui/label "min: ") (basic/counter {:num min}))) (let [max (get-in gen [:opts :max] 100)] (horizontal-layout (ui/label "max: ") (basic/counter {:num max}))) (let [max-width (get-in gen [:opts :max-width] 100)] (horizontal-layout (ui/label "max-width: ") (basic/counter {:num max-width}))) (let [integer? (get-in gen [:opts :integer?] true)] (horizontal-layout (ui/label "integer? ") (basic/checkbox {:checked? integer?}))))) (defgen NumberSliderGen [opts context] IGenInspector (gen-inspector [this] #'number-slider-inspector) IGenPred (gen-pred? [this obj] (number? obj)) IGenEditor (gen-editor [this sym] `(if (number? ~sym) (basic/number-slider {:num ~sym :min ~(get opts :min 0) :max ~(get opts :max 100) :integer? ~(get opts :integer? true) :max-width ~(get opts :max-width 100)}) (ui/label (str ~sym " is not a NaN!")))) ) (defmethod re-gen NumberSliderGen [_ specs spec context] (->NumberSliderGen {} context)) (defmethod can-gen-from-spec? NumberSliderGen [this specs spec] (#{'clojure.core/integer? 'cljs.core/integer? 'clojure.core/number? 'cljs.core/number? 'clojure.core/float? 'cljs.core/float? 'clojure.core/double? 'cljs.core/double?} spec)) (defgen CheckboxGen [opts context] IGenPred (gen-pred? [this obj] (boolean? obj)) IGenEditor (gen-editor [this sym] `(basic/checkbox {:checked? ~sym}))) (defmethod re-gen CheckboxGen [_ specs spec context] (->CheckboxGen {} context)) (defmethod can-gen-from-spec? CheckboxGen [this specs spec] (#{'clojure.core/boolean? 'cljs.core/boolean?} spec)) (defgen TitleGen [opts context] IGenPred (gen-pred? [this obj] (or (string? obj) (keyword? obj))) IGenEditor (gen-editor [this sym] `(ui/label (let [s# (str (if (keyword? ~sym) (name ~sym) ~sym))] (clojure.string/capitalize s#)) (ui/font nil ~(max 16 (- 22 (* 4 (get context :depth 0))))))) ) (defmethod re-gen TitleGen [_ specs spec context] (->TitleGen {} context)) (defmethod can-gen-from-spec? TitleGen [this specs spec] (#{'clojure.core/string? 'cljs.core/string? 'clojure.core/keyword? 'cljs.core/keyword?} spec)) (defgen LabelGen [opts context] ;; IEditableProps ;; (editable-props [this] ;; {:font-size (number-inspector :max 40 ;; :min 12)}) ;; IGenProps ;; (genprops [this] ;; [:font-size]) IGenPred (gen-pred? [this obj] (or (string? obj) (keyword? obj))) IGenEditor (gen-editor [this sym] `(ui/label ~sym (ui/font nil ~(:font-size opts)))) ) (defmethod re-gen LabelGen [_ specs spec context] (->LabelGen {} context)) (defmethod can-gen-from-spec? LabelGen [this specs spec] true) #_(def-gen static-vector vector? {:x identity} (let [x-sym (gensym "x-")] `(apply vertical-layout (for [~x-sym ~sym] ~(ui-code x-sym (first obj) (inc-context-depth context)))))) #_(def-gen static-horizontal-vector vector? {:x identity} (let [x-sym (gensym "x-") ] `(apply horizontal-layout (for [~x-sym ~sym] ~(ui-code x-sym (first obj) (inc-context-depth context)))))) (defn delete-X [] (ui/with-style :membrane.ui/style-stroke (ui/with-color [1 0 0] (ui/with-stroke-width 3 [(ui/path [0 0] [10 10]) (ui/path [10 0] [0 10])])))) (defn ->$sym [sym] (symbol (str "$" (name sym))) ) #_(def-gen dynamic-vector vector? (let [x-sym (gensym "x-")] `(apply vertical-layout (basic/button :text "New" :on-click (fn [] [[:update ~(->$sym sym) conj (first ~sym)]])) (for [~x-sym ~sym] (horizontal-layout (on :mouse-down (fn [_#] [[:delete ~(->$sym x-sym)]]) (delete-X)) ~(ui-code x-sym (first obj) (inc-context-depth context))))))) #_(def-gen checkbox boolean? `(basic/checkbox :checked? ~sym)) (defn stack-img [outer-layout inner-layout inner-elem outer-elem] (let [padding 1 rect-size 4] (apply outer-layout (interpose (spacer 0 padding) (for [i (range 3)] (inner-layout (inner-elem rect-size) (spacer padding 0) (outer-elem rect-size))))))) (defn kv-vertical-img [] (stack-img vertical-layout horizontal-layout #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)))) (defn vk-vertical-img [] (stack-img vertical-layout horizontal-layout #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) )) (defn kv-horizontal-img [] (stack-img horizontal-layout vertical-layout #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)))) (defn vk-horizontal-img [] (stack-img horizontal-layout vertical-layout #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) )) (defn kv-all-horizontal-img [] (stack-img horizontal-layout horizontal-layout #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)))) (defn vk-all-horizontal-img [] (stack-img horizontal-layout horizontal-layout #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) )) (defn kv-all-vertical-img [] (stack-img vertical-layout vertical-layout #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)))) (defn vk-all-vertical-img [] (stack-img vertical-layout vertical-layout #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) )) (defn test-view [] (apply vertical-layout (interpose (spacer 0 10) [(kv-vertical-img) (vk-vertical-img) (kv-horizontal-img) (vk-horizontal-img) (kv-all-horizontal-img) (vk-all-horizontal-img) (kv-all-vertical-img) (vk-all-vertical-img)]))) (defui option-toggle [{:keys [flag true-text false-text]}] (horizontal-layout (ui/button true-text (fn [] (when-not flag [[:set $flag true]])) flag) (ui/button false-text (fn [] (when flag [[:set $flag false]])) (not flag)))) (defui static-map-gen-inspector [{:keys [gen]}] (let [horizontal-rows? (get-in gen [:opts :horizontal-rows?]) horizontal-cols? (get-in gen [:opts :horizontal-cols?]) kv-order? (get-in gen [:opts :kv-order?] true)] (vertical-layout (let [k-elem #(ui/with-style :membrane.ui/style-stroke (ui/rectangle % %)) v-elem #(ui/with-style :membrane.ui/style-stroke-and-fill (ui/rectangle % %)) [inner-elem outer-elem] (if kv-order? [k-elem v-elem] [v-elem k-elem])] [(spacer 45 45) (ui/padding 5 5 (stack-img (if horizontal-rows? horizontal-layout vertical-layout) (if horizontal-cols? horizontal-layout vertical-layout) inner-elem outer-elem))]) (ui/label "key value layout order") (option-toggle {:flag kv-order? :true-text "kv" :false-text "vk"}) (ui/label "row direction") (option-toggle {:flag horizontal-rows? :true-text "horizontal" :false-text "vertical"}) (ui/label "column direction") (option-toggle {:flag horizontal-cols? :true-text "horizontal" :false-text "vertical"}) ) #_(horizontal-layout (ui/label "horizontal?") (ui/translate 5 5 (basic/checkbox :checked? horizontal?))))) (defgen StaticMapGen [opts context] IGenInspector (gen-inspector [this] #'static-map-gen-inspector) IEditableProps (editable-props [this] {:k gen-inspector :v gen-inspector}) ISubGens (subgens [this] [[:opts :k] [:opts :v]]) IGenPred (gen-pred? [this obj] (map? obj)) IGenEditor (gen-editor [this sym] (let [k-sym (gensym "k-") v-sym (gensym "v-") klabel-sym (gensym "klabel-") table-sym (gensym "table-")] `(ui/translate 10 10 (let [~table-sym (for [[~k-sym ~v-sym] ~sym] ~(let [k-elem `(let [~klabel-sym (maybe-with-meta ~(gen-editor (:k opts) k-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :k)])})] (vertical-layout ~klabel-sym ~(when (<= (:depth context) 1) `(let [lbl-width# (ui/width ~klabel-sym)] (ui/with-style :membrane.ui/style-stroke (ui/with-color [0 0 0] (ui/path [0 0] [lbl-width# 0]))))))) v-elem `(let [~v-sym (get ~sym ~k-sym)] (maybe-with-meta ~(gen-editor (:v opts) v-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :v)])}))] (if (get opts :kv-order? true) [k-elem v-elem] [v-elem k-elem]))) ] ~(if (= (:horizontal-rows? opts) (:horizontal-cols? opts)) (let [layout (if (:horizontal-rows? opts) `horizontal-layout `vertical-layout)] `(apply ~layout (apply concat ~table-sym))) `(ui/table-layout ~(if (:horizontal-rows? opts) table-sym `[(map first ~table-sym) (map second ~table-sym)])) ) ) #_(apply ~(if (:horizontal-rows? opts) `horizontal-layout `vertical-layout) (for [[~k-sym ~v-sym] ~sym] (~(if (:horizontal-cols? opts) `horizontal-layout `vertical-layout) ~@(let [k-elem `(let [~klabel-sym (maybe-with-meta ~(gen-editor (:k opts) k-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :k)])})] (vertical-layout ~klabel-sym ~(when (<= (:depth context) 1) `(let [lbl-width# (ui/width ~klabel-sym)] (ui/with-style :membrane.ui/style-stroke (ui/with-color [0 0 0] (ui/path [0 0] [lbl-width# 0]))))))) v-elem `(let [~v-sym (get ~sym ~k-sym)] (maybe-with-meta ~(gen-editor (:v opts) v-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :v)])}))] (if (get opts :kv-order? true) [k-elem v-elem] [v-elem k-elem])))) ))))) (defmethod re-gen StaticMapGen [_ specs spec context] (let [subcontext (inc-context-depth context)] (let [spec-fn (first spec)] (case spec-fn (clojure.spec.alpha/map-of cljs.spec.alpha/map-of) (let [[kpred vpred & opts] (rest spec) k-spec (if (keyword? kpred) (get specs kpred) kpred) k-gen (if (can-gen-from-spec? TitleGen specs k-spec) (->TitleGen {} (assoc subcontext :spec k-spec)) (best-gen specs k-spec subcontext)) v-spec (if (keyword? vpred) (get specs vpred) vpred)] (->StaticMapGen {:k k-gen :v (best-gen specs v-spec subcontext)} context)) (clojure.spec.alpha/keys cljs.spec.alpha/keys) (let [[& {:keys [req req-un opt opt-un gen]}] (rest spec) key-specs (concat req req-un opt opt-un) first-key-spec (get specs (first key-specs))] (->StaticMapGen {:k (->TitleGen {} (dissoc subcontext :spec)) :v (best-gen specs first-key-spec subcontext)} context)) ))) ) (defmethod can-gen-from-spec? StaticMapGen [this specs spec] (and (seq? spec) (let [spec-fn (first spec)] (or (#{'clojure.spec.alpha/map-of 'cljs.spec.alpha/map-of} spec-fn ) (and (#{'clojure.spec.alpha/keys 'cljs.spec.alpha/keys} spec-fn ) ;; all key specs should return the same gen type ;; this is so ugly. forgive me (let [[& {:keys [req req-un opt opt-un gen]}] (rest spec) key-specs (concat req req-un opt opt-un) context {:depth 0} example-gen-type (type (best-gen specs (get specs (first key-specs)) context))] (every? #(= example-gen-type (type (best-gen specs (get specs %) context))) (rest key-specs)))))))) (defgen StaticSeqGen [opts context] ISubGens (subgens [this] [[:opts :vals]]) IGenPred (gen-pred? [this obj] (and (seqable? obj) (not (or (map? obj) (string? obj))))) IGenEditor (gen-editor [this sym] (let [v-sym (gensym "v-")] `(ui/translate 10 10 (apply ~(if (:horizontal? opts) `horizontal-layout `vertical-layout) (for [~v-sym ~sym] (maybe-with-meta ~(gen-editor (:vals opts) v-sym) ~{:relative-identity '(quote [(keypath :opts) (keypath :vals)])}))))))) (defmethod re-gen StaticSeqGen [_ specs spec context] (assert (can-gen-from-spec? StaticSeqGen specs spec)) (->StaticSeqGen {:vals (best-gen specs (second spec) (inc-context-depth context))} context)) (defmethod can-gen-from-spec? StaticSeqGen [this specs spec] (and (seq? spec) (#{'clojure.spec.alpha/coll-of 'cljs.spec.alpha/coll-of} (first spec)))) (defui keymap-gen-inspector [{:keys [gen]}] (let [bordered? (get-in gen [:opts :bordered?] true)] (horizontal-layout (ui/label "bordered?") (ui/translate 5 5 (basic/checkbox {:checked? bordered?}))))) (defgen KeyMapGen [opts context] IGenInspector (gen-inspector [this] #'keymap-gen-inspector) ISubGens (subgens [this] (conj (map #(vector :opts :val-gens %) (keys (:val-gens opts))) [:opts :k])) IGenPred (gen-pred? [this obj] (map? obj)) IGenEditor (gen-editor [this sym] (let [body `(vertical-layout ~@(apply concat (for [[k subgen] (:val-gens opts)] (let [v-sym (gensym "v-")] `[(maybe-with-meta ~(gen-editor (:k opts) k) ~{:relative-identity '(quote [(keypath :opts) (keypath :k)])}) (let [~v-sym (get ~sym ~k)] (maybe-with-meta ~(gen-editor subgen v-sym) ~{:relative-identity [(quote '(keypath :opts)) (quote '(keypath :val-gens)) (list 'list (list 'quote 'keypath) k)]}))])))) body (if (get opts :bordered? true) `(ui/bordered [5 5] ~body) body)] body))) (defmethod re-gen KeyMapGen [_ specs spec context] (assert (can-gen-from-spec? KeyMapGen specs spec)) (let [subcontext (inc-context-depth context) [& {:keys [req req-un opt opt-un gen]}] (rest spec)] (->KeyMapGen {:k (->TitleGen {} (dissoc subcontext :spec)) :val-gens (into {} (concat (for [k (concat req opt)] [k (best-gen specs (get specs k) subcontext)]) (for [k (concat req-un opt-un)] [(keyword (name k)) (best-gen specs (get specs k) subcontext)]))) :bordered? (if-let [depth (:depth context)] (pos? depth) true)} context))) (defmethod can-gen-from-spec? KeyMapGen [this specs spec] (and (seq? spec) (#{'clojure.spec.alpha/keys 'cljs.spec.alpha/keys} (first spec)))) (defui cat-gen-inspector [{:keys [gen]}] (let [bordered? (get-in gen [:opts :bordered?] true)] (horizontal-layout (ui/label "bordered?") (ui/translate 5 5 (basic/checkbox {:checked? bordered?}))))) (defgen CatGen [opts context] IGenInspector (gen-inspector [this] #'cat-gen-inspector) ISubGens (subgens [this] (map #(vector :opts :val-gens %) (range (count (:val-gens opts))))) IGenPred (gen-pred? [this obj] (and (seqable? obj) (not (or (map? obj) (string? obj))))) IGenEditor (gen-editor [this sym] (let [body `(vertical-layout ~@(apply concat (for [[i subgen] (map-indexed vector (:val-gens opts))] (let [v-sym (gensym "v-")] `[(let [~v-sym (nth ~sym ~i)] (maybe-with-meta ~(gen-editor subgen v-sym) ~{:relative-identity [(quote '(keypath :opts)) (quote '(keypath :val-gens)) (list 'list (list 'quote 'nth) i)]}))])))) body (if (get opts :bordered? true) `(ui/bordered [5 5] ~body) body)] body))) (defmethod re-gen CatGen [_ specs spec context] (assert (can-gen-from-spec? CatGen specs spec)) (let [subcontext (inc-context-depth context) val-specs (take-nth 2 (drop 2 spec))] (->CatGen {:val-gens (vec (for [val-spec val-specs] (best-gen specs (get specs val-spec val-spec) subcontext))) :bordered? (if-let [depth (:depth context)] (pos? depth) true)} context))) (defmethod can-gen-from-spec? CatGen [this specs spec] (and (seq? spec) (= 'clojure.spec.alpha/cat (first spec)))) (defn first-matching-gen [obj] (some #(when ((:pred %) obj) %) (vals @gen-editors)) ) #_(defn ui-code ([sym obj context] (let [generator (first-matching-gen obj) children (into {} (for [[k v] (:children generator)] [k (fn [sym context] (ui-code sym (first (v obj)) (inc-context-depth context)))]))] (assert generator (str "No generator for " (pr-str obj)) ) (gen-editor generator sym obj children context)))) (defn auto-component [ui-name ge] (let [arg-sym 'obj] `(defui ~ui-name [{:keys [~arg-sym]}] (basic/scrollview {:bounds [800 800] :body ~(gen-editor ge arg-sym)})))) (defn def-auto-component [ui-name ge] (let [code (auto-component ui-name ge)] (eval code))) #_(def-auto-component 'testblades (best-gen blades-json)) #_(def-auto-component map-example {:a 1 :b 2 :c 3}) (def testgen (let [context {:depth 0} subcontext (inc-context-depth context)] (->StaticMapGen {:k (->LabelGen {} subcontext) :v (->NumberCounterGen {} subcontext) #_ (->LabelGen {} subcontext)} context))) ;; todo ;; - have a way to set data ;; - have a way to generate the gen-tree ;; - have a way to swap out alternatives (do (defn infer-specs ([obj] (infer-specs obj :membrane.autoui/infer-specs)) ([obj spec-name] (let [inferred (sp/infer-specs [obj] spec-name) specs (into {} (for [[def k spec] inferred] [k spec]))] specs))) (defn best-gen ([obj] (let [spec-name :membrane.autoui/infer-specs specs (infer-specs obj spec-name)] (best-gen specs (get specs spec-name) {:depth 0 :specs specs}))) ([specs spec context] (let [gen (cond (#{'clojure.core/string? 'cljs.core/string?} spec ) (->SimpleTextAreaGen {} context) (#{'clojure.core/boolean? 'cljs.core/boolean?} spec ) (->CheckboxGen {} context) (#{'clojure.core/keyword? 'cljs.core/keyword?} spec ) (->TitleGen {} context) (#{'clojure.core/simple-symbol?} spec ) (->TitleGen {} context) (#{'clojure.core/integer? 'cljs.core/integer? } spec ) (->NumberCounterGen {} context) ('#{clojure.core/double? cljs.core/double? clojure.core/float? cljs.core/float?} spec) (->NumberSliderGen {} context) (seq? spec) (case (first spec) (clojure.spec.alpha/coll-of cljs.spec.alpha/coll-of) (let [[pred & {:keys [into kind count max-count min-count distinct gen-max gen]}] (rest spec) subcontext (inc-context-depth context) ] (->StaticSeqGen {:vals (best-gen specs pred subcontext)} context) ) clojure.spec.alpha/cat (let [] (re-gen CatGen specs spec context)) clojure.spec.alpha/? (let [pred (second spec) subcontext (inc-context-depth context)] (best-gen specs pred subcontext)) clojure.spec.alpha/* (let [pred (second spec) subcontext (inc-context-depth context)] (->StaticSeqGen {:vals (best-gen specs pred subcontext)} context)) (clojure.spec.alpha/keys cljs.spec.alpha/keys) (re-gen KeyMapGen specs spec context) (clojure.spec.alpha/map-of) (re-gen StaticMapGen specs spec context) (clojure.spec.alpha/or cljs.spec.alpha/or) (let [key-preds (rest spec)] (->OrGen {:preds (for [[k pred] (partition 2 key-preds)] [[pred (best-gen specs pred context)]])} context)) ;; else (str "unknown spec: " (first spec)) ) :else (str "unknown spec: " spec) )] (if (satisfies? IGenEditor gen) (assoc-in gen [:context :spec] spec) gen))) ) #_(prn (let [obj blades-json] (best-gen obj)))) (defn gen-options [specs spec] (->> @gen-editors vals (filter #(can-gen-from-spec? % specs spec)))) (def testgen2 (let [ge testgen] (->KeyMapGen {:k (:k (:opts ge)) :val-gens {:a (->NumberCounterGen {} (:context (:v (:opts ge)))) :b (->LabelGen {} (:context (:v (:opts ge)))) :c (->TitleGen {} (:context (:v (:opts ge))))}} (:context ge)))) (defui foldable-section [{:keys [title body visible?] :or {visible? true}}] (vertical-layout (on :mouse-down (fn [_] [[:update $visible? not]]) [#_(ui/filled-rectangle [0.9 0.9 0.9] 200 20) (horizontal-layout (let [size 5] (ui/with-style :membrane.ui/style-stroke-and-fill (if visible? (ui/translate 5 8 (ui/path [0 0] [size size] [(* 2 size) 0])) (ui/translate 5 5 (ui/path [0 0] [size size] [0 (* 2 size)]))))) (spacer 5 0) (ui/label title)) ]) (when visible? (ui/translate 10 0 body)))) (defn pr-label [obj] (let [s (pr-str obj)] (ui/label (subs s 0 (min (count s) 37))))) (defn get-gen-name [ge] #?(:clj (.getSimpleName ge) :cljs (pr-str ge))) ;; forward declare (defui gen-editor-inspector [{:keys [ge]}]) (defui gen-editor-inspector [{:keys [ge]}] (let [sub (subgens ge)] (foldable-section {:title (if-let [spec (-> ge :context :spec)] (pr-str spec) (get-gen-name (type ge))) :visible? (get extra [:foldable-visible $ge] true) :body (apply vertical-layout (when-let [spec (-> ge :context :spec)] (when-let [specs (-> ge :context :specs)] (vertical-layout (pr-label spec) (let [options (gen-options specs spec)] (apply horizontal-layout (for [option options] (basic/button {:text (get-gen-name option) :hover? (get extra [:switch :hover? option]) :on-click (fn [] [[:set $ge (re-gen option specs spec (:context ge))]])}))))))) (when-let [inspector (gen-inspector ge)] (let [inspector-extra (get extra [$ge :extra])] (inspector {:gen ge :$gen $ge :extra inspector-extra :$extra $inspector-extra :context context :$context $context}))) (for [k sub] (let [v (get-in ge k)] (gen-editor-inspector {:ge v}))))}))) (defn find-under ([pos elem delta] (find-under pos elem (Math/pow delta 2) nil [])) ([pos elem d2 elem-index ident] (let [[x y] pos [ox oy] (ui/origin elem) [width height] (ui/bounds elem) local-x (int (- x ox)) local-y (int (- y oy)) new-pos [local-x local-y] elem-meta (meta elem)] (if-let [m elem-meta] (if-let [identity (:identity m)] (let [child-results (mapcat #(find-under new-pos % d2 elem-index [identity]) (ui/children elem))] (if (and (< (Math/pow local-x 2) d2) (< (Math/pow local-y 2) d2)) (conj child-results {:elem elem :pos new-pos :identity identity}) child-results)) (if-let [relative-identity (:relative-identity m)] (let [identity (into ident relative-identity) child-results (mapcat #(find-under new-pos % d2 elem-index identity) (ui/children elem))] (if (and (< (Math/pow local-x 2) d2) (< (Math/pow local-y 2) d2)) (conj child-results {:elem elem :pos new-pos :identity identity}) child-results)) (mapcat #(find-under new-pos % d2 elem-index ident) (ui/children elem)))) (mapcat #(find-under new-pos % d2 elem-index ident) (ui/children elem)))))) (defn draw-circles ([elem] (draw-circles elem [0 0])) ([elem pos] (let [[x y] pos [ox oy] (ui/origin elem) [width height] (ui/bounds elem) local-x (int (+ x ox)) local-y (int (+ y oy)) new-pos [local-x local-y] elem-meta (meta elem)] (if-let [m elem-meta] (if-let [identity (:identity m)] (let [child-results (mapcat #(draw-circles % new-pos) (ui/children elem))] (conj child-results new-pos)) (if-let [relative-identity (:relative-identity m)] (let [child-results (mapcat #(draw-circles % new-pos) (ui/children elem))] (conj child-results new-pos)) (mapcat #(draw-circles % new-pos) (ui/children elem)))) (mapcat #(draw-circles % new-pos) (ui/children elem)))))) (def ^:dynamic *obj* nil) (def ^:dynamic *$ge* nil) (declare background-eval) (defui eval-form [{:keys [form eval-context cache eval-key]}] (let [cache (or cache {}) result (background-eval form eval-context cache $cache eval-key)] ;; (prn "result:" result) result)) (defui gen-editor-editor [{:keys [ge obj selected-ge-path ge-options]}] (horizontal-layout (basic/scrollview {:scroll-bounds [400 800] :body (let [body (ui/no-events (ui/try-draw (let [drawable #?(:clj (binding [*obj* obj *$ge* []] ;; (clojure.pprint/pprint (gen-editor ge 'obj)) (eval `(let [~'obj *obj*] (maybe-with-meta ~(gen-editor ge 'obj) {:identity *$ge*})))) :cljs (eval-form {:form `(maybe-with-meta ~(gen-editor ge 'obj) {:identity ~'ident}) :eval-context {'ident *$ge* 'obj obj} :eval-key ge}) ) ] drawable) (fn [draw e] (println e) (draw (ui/label "whoops!"))))) circles (delay (mapv (fn [[x y]] (ui/translate (- x 5) (- y 5) (ui/filled-rectangle [1 0 0] 10 10))) (draw-circles body)))] [ (on :mouse-down (fn [pos] (let [results (seq (find-under pos body 5))] (if-let [results results] (if (= (count results) 1) (let [ident (:identity (first results))] [[:set $selected-ge-path ident]]) [[:set $ge-options {:pos pos :options (vec (for [{:keys [elem pos elem-index identity]} results] [identity (get-gen-name (type (spec/select-one (component/path->spec [identity]) ge)))]))}]]) [[:set $selected-ge-path nil] [:set $ge-options nil]]))) body) ;; @circles (when ge-options (let [options-pos (:pos ge-options) options (:options ge-options)] (ui/translate (first options-pos) (second options-pos) (on ::basic/select (fn [_ $ident] [[:set $ge-options nil] [:set $selected-ge-path $ident]]) (basic/dropdown-list {:options options})))))])}) (let [[edit-ge $edit-ge] (if selected-ge-path [(spec/select-one (component/path->spec [selected-ge-path]) ge) [$ge selected-ge-path]] [ge $ge])] (basic/scrollview {:scroll-bounds [800 800] :body (gen-editor-inspector {:ge edit-ge :$ge $edit-ge})})))) (defui test-edit [{:keys [title?]}] (vertical-layout (horizontal-layout (ui/label "title?") (basic/checkbox {:checked? title?})) (let [testgen (if title? (-> testgen (assoc-in [:opts :k] (->TitleGen {} (:context (get-in testgen [:opts :k])))) (assoc-in [:opts :v] (->TitleGen {} (:context (get-in testgen [:opts :v]))))) testgen)] (eval`(let [~'m {:a 1 :b 2}] ~(gen-editor testgen 'm)))))) (comment (let [obj blades-json ge (best-gen obj)] (def editor-state (skia/run (component/make-app #'gen-editor-editor {:ge ge :obj obj}))))) (defn start-blades [] (let [obj blades-json ge (best-gen obj)] (def editor-state (skia/run (component/make-app #'gen-editor-editor {:ge ge :obj obj}))))) (comment (def test-data (with-open [rdr (clojure.java.io/reader "/var/tmp/test-savegame.json")] (clojure.data.json/read rdr :key-fn keyword)))) (comment (start-form-builder {:x 2, :y 10, :data ":/gamedata/enemies/test-enemy.json", :character {:role "Enemy", :wisdom 10, :weapon "", :firearm "", :experience 100, :mana 10, :inventory [{:data ":/gamedata/items/plants/healing-herb.json", :count 2} {:data ":/gamedata/items/weapons/sword.json", :count 2}], :strength 10, :healthMax 200, :manaMax 10, :health 200, :gender "male", :stealth 0}})) (defn start-form-builder [obj] (let [ge (best-gen obj)] (def editor-state (skia/run (component/make-app #'gen-editor-editor {:ge ge :obj obj}))))) (defn start-spec [] (let [obj (list 10 "Asfa") ge (let [specs {} #_(into {} (for [[k v] (s/registry) :let [form (try (s/form v) (catch Exception e nil))] :when form] [k form]))] (best-gen specs `(s/cat :foo integer? :bar string?) {:depth 0 :specs specs}))] (def editor-state (skia/run (component/make-app #'gen-editor-editor {:ge ge :obj obj}))))) #_(defui blades-scroll [{:keys [obj]}] (basic/scrollview :scroll-bounds [800 800] :body (testblades :obj obj))) ;; examples of using macros with eval ;; https://github.com/clojure/clojurescript/blob/master/src/test/self/self_host/test.cljs#L392 ;; from @mfikes on clojurians regarding AOT and macros ;; You have to roll your own way of doing that. Planck does this https://blog.fikesfarm.com/posts/2016-02-03-planck-macros-aot.html ;; The high-level idea is that you can use a build-time self-hosted compiler to compile macros namespaces down to JavaScript. ;; Also Replete does this as well, all in the name of fast loading. So, you can look at Plank and Replete as inspiration on how to do this. There might be other examples out there as well. #?(:cljs (do (def cljstate (cljs/empty-state)) (def aot-caches [ "js/compiled/out.autouitest/clojure/zip.cljs.cache.json" "js/compiled/out.autouitest/clojure/string.cljs.cache.json" "js/compiled/out.autouitest/clojure/walk.cljs.cache.json" "js/compiled/out.autouitest/clojure/set.cljs.cache.json" "js/compiled/out.autouitest/cognitect/transit.cljs.cache.json" "js/compiled/out.autouitest/spec_provider/util.cljc.cache.json" "js/compiled/out.autouitest/spec_provider/merge.cljc.cache.json" "js/compiled/out.autouitest/spec_provider/rewrite.cljc.cache.json" "js/compiled/out.autouitest/spec_provider/stats.cljc.cache.json" "js/compiled/out.autouitest/spec_provider/provider.cljc.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/impl/commons.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/impl/utils.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/impl/errors.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/impl/inspect.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/edn.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader/reader_types.cljs.cache.json" "js/compiled/out.autouitest/cljs/tools/reader.cljs.cache.json" "js/compiled/out.autouitest/cljs/env.cljc.cache.json" "js/compiled/out.autouitest/cljs/core/async.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/channels.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/dispatch.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/timers.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/buffers.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/protocols.cljs.cache.json" "js/compiled/out.autouitest/cljs/core/async/impl/ioc_helpers.cljs.cache.json" "js/compiled/out.autouitest/cljs/compiler.cljc.cache.json" "js/compiled/out.autouitest/cljs/analyzer.cljc.cache.json" "js/compiled/out.autouitest/cljs/tagged_literals.cljc.cache.json" "js/compiled/out.autouitest/cljs/spec/test/alpha.cljs.cache.json" "js/compiled/out.autouitest/cljs/spec/gen/alpha.cljs.cache.json" "js/compiled/out.autouitest/cljs/spec/alpha.cljs.cache.json" "js/compiled/out.autouitest/cljs/reader.cljs.cache.json" "js/compiled/out.autouitest/cljs/source_map.cljs.cache.json" "js/compiled/out.autouitest/cljs/js.cljs.cache.json" "js/compiled/out.autouitest/cljs/pprint.cljs.cache.json" "js/compiled/out.autouitest/cljs/source_map/base64.cljs.cache.json" "js/compiled/out.autouitest/cljs/source_map/base64_vlq.cljs.cache.json" "js/compiled/out.autouitest/cljs/core$macros.cljc.cache.json" "js/compiled/out.autouitest/cljs/analyzer/api.cljc.cache.json" "js/compiled/out.autouitest/cljs/stacktrace.cljc.cache.json" "js/compiled/out.autouitest/membrane/audio.cljs.cache.json" "js/compiled/out.autouitest/membrane/jsonee.cljc.cache.json" "js/compiled/out.autouitest/membrane/webgl.cljs.cache.json" "js/compiled/out.autouitest/membrane/basic_components.cljc.cache.json" "js/compiled/out.autouitest/membrane/autoui.cljc.cache.json" "js/compiled/out.autouitest/membrane/builder.cljc.cache.json" "js/compiled/out.autouitest/membrane/ui.cljc.cache.json" "js/compiled/out.autouitest/membrane/component.cljc.cache.json" "js/compiled/out.autouitest/membrane/analyze.cljc.cache.json" "js/compiled/out.autouitest/membrane/example/counter.cljc.cache.json" "js/compiled/out.autouitest/membrane/example/todo.cljc.cache.json" "js/compiled/out.autouitest/membrane/macroexpand.cljs.cache.json" "js/compiled/out.autouitest/membrane/vdom.cljs.cache.json" "js/compiled/out.autouitest/membrane/eval.cljs.cache.json" "js/compiled/out.autouitest/membrane/webgltest.cljs.cache.json" "js/compiled/out.autouitest/com/rpl/specter.cljc.cache.json" "js/compiled/out.autouitest/com/rpl/specter/protocols.cljc.cache.json" "js/compiled/out.autouitest/com/rpl/specter/impl.cljc.cache.json" "js/compiled/out.autouitest/com/rpl/specter/navs.cljc.cache.json" "js/compiled/out.autouitest/vdom/core.cljs.cache.json" "js/compiled/out.autouitest/process/env.cljs.cache.json" ] ) (defn load-cache [state cache-path] (let [ch (chan 1)] (membrane.eval/get-file cache-path (fn [source] (try (let [ rdr (transit/reader :json) cache (transit/read rdr source) ns (:name cache)] (cljs.js/load-analysis-cache! state ns cache) (prn "loaded " cache-path)) (finally (async/close! ch))))) ch)) (let [state cljstate] (async/go (let [] (let [chs (doall (map (fn [path] (load-cache state path)) aot-caches))] (doseq [ch chs] (<! ch))) (println "loaded all cached") (async/go #_(prn (<! (membrane.eval/eval-async state '(require-macros '[membrane.component :refer [defui]]) #_(:require [membrane.audio :as audio])))) (let [obj blades-json ge (best-gen obj)] (def canvas (.getElementById js/document "canvas")) #_(defonce start-auto-app (membrane.component/run-ui #'gen-editor-editor {:ge ge :obj obj} nil {:container canvas})) #_(defonce start-auto-app (membrane.component/run-ui #'gen-editor-editor {:ge ge :obj obj} nil {:container (js/document.getElementById "app")}))) (def background-eval-context (atom {})) (def background-eval-context-key (atom 0)) (defn background-eval [form eval-context cache $cache eval-key] (if (contains? cache eval-key) (get cache eval-key) (let [context-key (swap! background-eval-context-key inc)] (spec/transform (component/path->spec $cache) (fn [m] (assoc m eval-key (ui/label "loading..."))) start-auto-app) (async/go (swap! background-eval-context assoc context-key eval-context) (let [bindings (for [[sym val] eval-context] [sym `(get-in @background-eval-context [~context-key (quote ~sym)])]) form-with-context `(let ~(vec (apply concat bindings)) ~form) result (<! (membrane.eval/eval-async cljstate form-with-context))] ;; (prn result) (if (:error result) (do (prn "error " (:error result)) (spec/transform (component/path->spec $cache) (fn [m] (assoc m eval-key (ui/label "error evaling...."))) start-auto-app)) (spec/transform (component/path->spec $cache) (fn [m] (assoc m eval-key (:value result))) start-auto-app)) (swap! background-eval-context dissoc context-key))) (ui/label "loading..."))))))) (set! (.-evaltest js/window ) (fn [] (let [source '(membrane.component/defui my-foo [{:keys [ a b]}]) ] (cljs/eval state source membrane.eval/default-compiler-options #(prn %))))) (set! (.-evaltually js/window) (fn [source] (cljs/eval-str state source nil membrane.eval/default-compiler-options #(prn %)) )) (set! (.-evaltually_statement js/window) (fn [source] (cljs/eval-str state source nil (assoc membrane.eval/default-compiler-options :context :statement) #(prn %))))))) (comment #?(:cljs (do (defn default-load-fn [{:keys [name macros path] :as m} cb] (prn "trying to load" m) (throw "whoops!")) (defn wrap-js-eval [resource] (try (cljs/js-eval resource) (catch js/Object e {::error e}))) (def compiler-options {:source-map true ;; :context :statement :ns 'test.ns :verbose true :load default-load-fn :def-emits-var true :eval wrap-js-eval}) (def state (cljs/empty-state)) (defn eval-next [statements] (when-let [statement (first statements)] (prn "evaling " statement) (cljs/eval state statement compiler-options #(do (prn "result: " %) (eval-next (rest statements)))))) (eval-next [ '(ns test.ns) '(defmacro test-macro [& body] `(vector 42 ~@body)) '(test-macro 123) ;; console log: ;; "evaling " (test-macro 123) ;; "result: " [42] ]))))
[ { "context": "mmy classes for prefer-method tests.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-09-14\"\n :version \"2017-09-14\"}", "end": 280, "score": 0.8911804556846619, "start": 244, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/test/clojure/palisades/lakes/dynafun/test/classes.clj
palisades-lakes/dynamic-functions
3
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.dynafun.test.classes {:doc "dummy classes for prefer-method tests." :author "palisades dot lakes at gmail dot com" :since "2017-09-14" :version "2017-09-14"}) ;;---------------------------------------------------------------- (definterface A) (gen-class :name palisades.lakes.dynafun.test.classes.B) (gen-class :name palisades.lakes.dynafun.test.classes.C) (gen-class :name palisades.lakes.dynafun.test.classes.D :implements [palisades.lakes.dynafun.test.classes.A] :extends palisades.lakes.dynafun.test.classes.C) ;;---------------------------------------------------------------- (definterface A0) (definterface B0) (gen-class :name palisades.lakes.dynafun.test.classes.C0 :implements [palisades.lakes.dynafun.test.classes.A0]) (gen-class :name palisades.lakes.dynafun.test.classes.D0 :implements [palisades.lakes.dynafun.test.classes.B0] :extends palisades.lakes.dynafun.test.classes.C0) ;;---------------------------------------------------------------- (definterface A1) (definterface B1) (gen-class :name palisades.lakes.dynafun.test.classes.C1 :implements [palisades.lakes.dynafun.test.classes.A1]) (gen-class :name palisades.lakes.dynafun.test.classes.D1 :implements [palisades.lakes.dynafun.test.classes.B1] :extends palisades.lakes.dynafun.test.classes.C1) ;;---------------------------------------------------------------- (gen-interface :name palisades.lakes.dynafun.test.classes.A2) (gen-interface :name palisades.lakes.dynafun.test.classes.B2 :extends [palisades.lakes.dynafun.test.classes.A2]) (gen-interface :name palisades.lakes.dynafun.test.classes.D2) (gen-interface :name palisades.lakes.dynafun.test.classes.E2 :extends [palisades.lakes.dynafun.test.classes.D2]) (gen-class :name palisades.lakes.dynafun.test.classes.C2 :implements [palisades.lakes.dynafun.test.classes.B2 palisades.lakes.dynafun.test.classes.E2]) ;;----------------------------------------------------------------
29455
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.dynafun.test.classes {:doc "dummy classes for prefer-method tests." :author "<EMAIL>" :since "2017-09-14" :version "2017-09-14"}) ;;---------------------------------------------------------------- (definterface A) (gen-class :name palisades.lakes.dynafun.test.classes.B) (gen-class :name palisades.lakes.dynafun.test.classes.C) (gen-class :name palisades.lakes.dynafun.test.classes.D :implements [palisades.lakes.dynafun.test.classes.A] :extends palisades.lakes.dynafun.test.classes.C) ;;---------------------------------------------------------------- (definterface A0) (definterface B0) (gen-class :name palisades.lakes.dynafun.test.classes.C0 :implements [palisades.lakes.dynafun.test.classes.A0]) (gen-class :name palisades.lakes.dynafun.test.classes.D0 :implements [palisades.lakes.dynafun.test.classes.B0] :extends palisades.lakes.dynafun.test.classes.C0) ;;---------------------------------------------------------------- (definterface A1) (definterface B1) (gen-class :name palisades.lakes.dynafun.test.classes.C1 :implements [palisades.lakes.dynafun.test.classes.A1]) (gen-class :name palisades.lakes.dynafun.test.classes.D1 :implements [palisades.lakes.dynafun.test.classes.B1] :extends palisades.lakes.dynafun.test.classes.C1) ;;---------------------------------------------------------------- (gen-interface :name palisades.lakes.dynafun.test.classes.A2) (gen-interface :name palisades.lakes.dynafun.test.classes.B2 :extends [palisades.lakes.dynafun.test.classes.A2]) (gen-interface :name palisades.lakes.dynafun.test.classes.D2) (gen-interface :name palisades.lakes.dynafun.test.classes.E2 :extends [palisades.lakes.dynafun.test.classes.D2]) (gen-class :name palisades.lakes.dynafun.test.classes.C2 :implements [palisades.lakes.dynafun.test.classes.B2 palisades.lakes.dynafun.test.classes.E2]) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.dynafun.test.classes {:doc "dummy classes for prefer-method tests." :author "PI:EMAIL:<EMAIL>END_PI" :since "2017-09-14" :version "2017-09-14"}) ;;---------------------------------------------------------------- (definterface A) (gen-class :name palisades.lakes.dynafun.test.classes.B) (gen-class :name palisades.lakes.dynafun.test.classes.C) (gen-class :name palisades.lakes.dynafun.test.classes.D :implements [palisades.lakes.dynafun.test.classes.A] :extends palisades.lakes.dynafun.test.classes.C) ;;---------------------------------------------------------------- (definterface A0) (definterface B0) (gen-class :name palisades.lakes.dynafun.test.classes.C0 :implements [palisades.lakes.dynafun.test.classes.A0]) (gen-class :name palisades.lakes.dynafun.test.classes.D0 :implements [palisades.lakes.dynafun.test.classes.B0] :extends palisades.lakes.dynafun.test.classes.C0) ;;---------------------------------------------------------------- (definterface A1) (definterface B1) (gen-class :name palisades.lakes.dynafun.test.classes.C1 :implements [palisades.lakes.dynafun.test.classes.A1]) (gen-class :name palisades.lakes.dynafun.test.classes.D1 :implements [palisades.lakes.dynafun.test.classes.B1] :extends palisades.lakes.dynafun.test.classes.C1) ;;---------------------------------------------------------------- (gen-interface :name palisades.lakes.dynafun.test.classes.A2) (gen-interface :name palisades.lakes.dynafun.test.classes.B2 :extends [palisades.lakes.dynafun.test.classes.A2]) (gen-interface :name palisades.lakes.dynafun.test.classes.D2) (gen-interface :name palisades.lakes.dynafun.test.classes.E2 :extends [palisades.lakes.dynafun.test.classes.D2]) (gen-class :name palisades.lakes.dynafun.test.classes.C2 :implements [palisades.lakes.dynafun.test.classes.B2 palisades.lakes.dynafun.test.classes.E2]) ;;----------------------------------------------------------------
[ { "context": "\"\n :subprotocol \"postgresql\"\n :subname \"//192.168.18.51:5432/rumbl_dev\"\n :user \"postgres\"\n :pa", "end": 485, "score": 0.9996069669723511, "start": 472, "tag": "IP_ADDRESS", "value": "192.168.18.51" }, { "context": "_dev\"\n :user \"postgres\"\n :password \"postgres\"})\n\n(kDB/defdb korma-db db-spec)\n\n(defn- get-conn", "end": 554, "score": 0.9995241761207581, "start": 546, "tag": "PASSWORD", "value": "postgres" } ]
src/bacidro/db_postgres.clj
laingit/bacidro
0
(ns bacidro.db-postgres (:require [korma.core :as k :only (defentity set-fields insert update values)] [korma.db :as kDB :only (defdb get-connection)] [clojure.java.jdbc :as j] [clojure.pprint :as pp] [java-jdbc.ddl :as ddl])) (def db-spec {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname "//192.168.18.51:5432/rumbl_dev" :user "postgres" :password "postgres"}) (kDB/defdb korma-db db-spec) (defn- get-connection-from-pool [] (kDB/get-connection korma-db)) (defn get-idro-data [] (let [query "SELECT \n idropost.id, idropost.tipo, idropost.settore, idropost.valle FROM public.idropost WHERE public.idropost.settore = 1 ORDER BY idropost.settore,idropost.id, idropost.tipo;"] (j/query (get-connection-from-pool) [query])))
1254
(ns bacidro.db-postgres (:require [korma.core :as k :only (defentity set-fields insert update values)] [korma.db :as kDB :only (defdb get-connection)] [clojure.java.jdbc :as j] [clojure.pprint :as pp] [java-jdbc.ddl :as ddl])) (def db-spec {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname "//192.168.18.51:5432/rumbl_dev" :user "postgres" :password "<PASSWORD>"}) (kDB/defdb korma-db db-spec) (defn- get-connection-from-pool [] (kDB/get-connection korma-db)) (defn get-idro-data [] (let [query "SELECT \n idropost.id, idropost.tipo, idropost.settore, idropost.valle FROM public.idropost WHERE public.idropost.settore = 1 ORDER BY idropost.settore,idropost.id, idropost.tipo;"] (j/query (get-connection-from-pool) [query])))
true
(ns bacidro.db-postgres (:require [korma.core :as k :only (defentity set-fields insert update values)] [korma.db :as kDB :only (defdb get-connection)] [clojure.java.jdbc :as j] [clojure.pprint :as pp] [java-jdbc.ddl :as ddl])) (def db-spec {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname "//192.168.18.51:5432/rumbl_dev" :user "postgres" :password "PI:PASSWORD:<PASSWORD>END_PI"}) (kDB/defdb korma-db db-spec) (defn- get-connection-from-pool [] (kDB/get-connection korma-db)) (defn get-idro-data [] (let [query "SELECT \n idropost.id, idropost.tipo, idropost.settore, idropost.valle FROM public.idropost WHERE public.idropost.settore = 1 ORDER BY idropost.settore,idropost.id, idropost.tipo;"] (j/query (get-connection-from-pool) [query])))
[ { "context": "set clojure.xml))\n\n; START:song\n(def song {:name \"Agnus Dei\"\n\t :artist \"Krzysztof Penderecki\"\n\t :album \"P", "end": 115, "score": 0.9990600347518921, "start": 106, "tag": "NAME", "value": "Agnus Dei" }, { "context": "RT:song\n(def song {:name \"Agnus Dei\"\n\t :artist \"Krzysztof Penderecki\"\n\t :album \"Polish Requiem\"\n\t :genre \"Classica", "end": 150, "score": 0.9994161128997803, "start": 130, "tag": "NAME", "value": "Krzysztof Penderecki" }, { "context": "ions \n #{{:name \"The Art of the Fugue\" :composer \"J. S. Bach\"}\n {:name \"Musical Offering\" :composer \"J. S. B", "end": 311, "score": 0.9998204112052917, "start": 301, "tag": "NAME", "value": "J. S. Bach" }, { "context": "S. Bach\"}\n {:name \"Musical Offering\" :composer \"J. S. Bach\"}\n {:name \"Requiem\" :composer \"Giuseppe Verdi\"}", "end": 364, "score": 0.9998324513435364, "start": 354, "tag": "NAME", "value": "J. S. Bach" }, { "context": "ical Offering\" :composer \"J. S. Bach\"}\n {:name \"Requiem\" :composer \"Giuseppe Verdi\"}\n {:name \"Requiem\" ", "end": 385, "score": 0.735745906829834, "start": 378, "tag": "NAME", "value": "Requiem" }, { "context": "oser \"J. S. Bach\"}\n {:name \"Requiem\" :composer \"Giuseppe Verdi\"}\n {:name \"Requiem\" :composer \"W. A. Mozart\"}})", "end": 412, "score": 0.9998113512992859, "start": 398, "tag": "NAME", "value": "Giuseppe Verdi" }, { "context": " \"Requiem\" :composer \"Giuseppe Verdi\"}\n {:name \"Requiem\" :composer \"W. A. Mozart\"}})\n(def countries\n #{{:", "end": 433, "score": 0.9052627682685852, "start": 426, "tag": "NAME", "value": "Requiem" }, { "context": " \"Giuseppe Verdi\"}\n {:name \"Requiem\" :composer \"W. A. Mozart\"}})\n(def countries\n #{{:composer \"J. S. Bach\" :co", "end": 458, "score": 0.9998635649681091, "start": 446, "tag": "NAME", "value": "W. A. Mozart" }, { "context": "r \"W. A. Mozart\"}})\n(def countries\n #{{:composer \"J. S. Bach\" :country \"Germany\"}\n {:composer \"W. A. Mozart\"", "end": 503, "score": 0.9998180866241455, "start": 493, "tag": "NAME", "value": "J. S. Bach" }, { "context": "r \"J. S. Bach\" :country \"Germany\"}\n {:composer \"W. A. Mozart\" :country \"Austria\"}\n {:composer \"Giuseppe Verd", "end": 552, "score": 0.9998700022697449, "start": 540, "tag": "NAME", "value": "W. A. Mozart" }, { "context": "\"W. A. Mozart\" :country \"Austria\"}\n {:composer \"Giuseppe Verdi\" :country \"Italy\"}})\n; END:compositions\n\n; TODO: ", "end": 603, "score": 0.9998361468315125, "start": 589, "tag": "NAME", "value": "Giuseppe Verdi" }, { "context": "with\n (merge-with \n concat \n {:flintstone, [\"Fred\"], :rubble [\"Barney\"]}\n {:flintstone, [\"Wilma\"]", "end": 946, "score": 0.9988201260566711, "start": 942, "tag": "NAME", "value": "Fred" }, { "context": " \n concat \n {:flintstone, [\"Fred\"], :rubble [\"Barney\"]}\n {:flintstone, [\"Wilma\"], :rubble [\"Betty\"]}", "end": 966, "score": 0.9664875864982605, "start": 960, "tag": "NAME", "value": "Barney" }, { "context": " [\"Fred\"], :rubble [\"Barney\"]}\n {:flintstone, [\"Wilma\"], :rubble [\"Betty\"]}\n {:flintstone, [\"Pebbles\"", "end": 994, "score": 0.9723960757255554, "start": 989, "tag": "NAME", "value": "Wilma" }, { "context": "[\"Barney\"]}\n {:flintstone, [\"Wilma\"], :rubble [\"Betty\"]}\n {:flintstone, [\"Pebbles\"], :rubble [\"Bam-Ba", "end": 1013, "score": 0.8736332654953003, "start": 1008, "tag": "NAME", "value": "Betty" } ]
examples/sequences.clj
Chouser/programming-clojure
1
(ns examples.sequences (:use examples.utils clojure.set clojure.xml)) ; START:song (def song {:name "Agnus Dei" :artist "Krzysztof Penderecki" :album "Polish Requiem" :genre "Classical"}) ; END:song ; START:compositions (def compositions #{{:name "The Art of the Fugue" :composer "J. S. Bach"} {:name "Musical Offering" :composer "J. S. Bach"} {:name "Requiem" :composer "Giuseppe Verdi"} {:name "Requiem" :composer "W. A. Mozart"}}) (def countries #{{:composer "J. S. Bach" :country "Germany"} {:composer "W. A. Mozart" :country "Austria"} {:composer "Giuseppe Verdi" :country "Italy"}}) ; END:compositions ; TODO: add pretty-print that works with book margins. (defdemo demo-map-builders (assoc song :kind "MPEG Audio File") (dissoc song :genre) (select-keys song [:name :artist]) (merge song {:size 8118166 :time 507245})) (defdemo demo-merge-with (merge-with concat {:flintstone, ["Fred"], :rubble ["Barney"]} {:flintstone, ["Wilma"], :rubble ["Betty"]} {:flintstone, ["Pebbles"], :rubble ["Bam-Bam"]})) ; START:sets (def languages #{"java" "c" "d" "clojure"}) (def letters #{"a" "b" "c" "d" "e"}) (def beverages #{"java" "chai" "pop"}) (def inventors {"java" "gosling", "clojure" "hickey", "ruby" "matz"}) ; END: sets (defdemo demo-mutable-re ; START:mutable-re ; don't do this! (let [m (re-matcher #"\w+" "the quick brown fox")] (loop [match (re-find m)] (if (nil? match) nil (do (println match) (recur (re-find m)))))) ; END:mutable-re ) ; START:filter (defn minutes [mins] (* mins 1000 60)) (defn recently-modified? [file] (> (.lastModified file) (- (System/currentTimeMillis) (minutes 30)))) ; END:filter ; START:clojure-loc (use '[clojure.contrib.duck-streams :only (reader)]) (defn non-blank? [line] (if (re-find #"\S" line) true false)) (defn non-svn? [file] (not (.startsWith (.toString file) ".svn"))) (defn clojure-source? [file] (.endsWith (.toString file) ".clj")) (defn clojure-loc [base-file] (reduce + (for [file (file-seq base-file) :when (and (clojure-source? file) (non-svn? file))] (with-open [rdr (reader file)] (count (filter non-blank? (line-seq rdr))))))) ; END:clojure-loc (defn demo-xml-seq [] ; START:xml-seq (for [x (xml-seq (parse (java.io.File. "examples/sequences/compositions.xml"))) :when (= :composition (:tag x))] (:composer (:attrs x))) ; END:xml-seq )
58938
(ns examples.sequences (:use examples.utils clojure.set clojure.xml)) ; START:song (def song {:name "<NAME>" :artist "<NAME>" :album "Polish Requiem" :genre "Classical"}) ; END:song ; START:compositions (def compositions #{{:name "The Art of the Fugue" :composer "<NAME>"} {:name "Musical Offering" :composer "<NAME>"} {:name "<NAME>" :composer "<NAME>"} {:name "<NAME>" :composer "<NAME>"}}) (def countries #{{:composer "<NAME>" :country "Germany"} {:composer "<NAME>" :country "Austria"} {:composer "<NAME>" :country "Italy"}}) ; END:compositions ; TODO: add pretty-print that works with book margins. (defdemo demo-map-builders (assoc song :kind "MPEG Audio File") (dissoc song :genre) (select-keys song [:name :artist]) (merge song {:size 8118166 :time 507245})) (defdemo demo-merge-with (merge-with concat {:flintstone, ["<NAME>"], :rubble ["<NAME>"]} {:flintstone, ["<NAME>"], :rubble ["<NAME>"]} {:flintstone, ["Pebbles"], :rubble ["Bam-Bam"]})) ; START:sets (def languages #{"java" "c" "d" "clojure"}) (def letters #{"a" "b" "c" "d" "e"}) (def beverages #{"java" "chai" "pop"}) (def inventors {"java" "gosling", "clojure" "hickey", "ruby" "matz"}) ; END: sets (defdemo demo-mutable-re ; START:mutable-re ; don't do this! (let [m (re-matcher #"\w+" "the quick brown fox")] (loop [match (re-find m)] (if (nil? match) nil (do (println match) (recur (re-find m)))))) ; END:mutable-re ) ; START:filter (defn minutes [mins] (* mins 1000 60)) (defn recently-modified? [file] (> (.lastModified file) (- (System/currentTimeMillis) (minutes 30)))) ; END:filter ; START:clojure-loc (use '[clojure.contrib.duck-streams :only (reader)]) (defn non-blank? [line] (if (re-find #"\S" line) true false)) (defn non-svn? [file] (not (.startsWith (.toString file) ".svn"))) (defn clojure-source? [file] (.endsWith (.toString file) ".clj")) (defn clojure-loc [base-file] (reduce + (for [file (file-seq base-file) :when (and (clojure-source? file) (non-svn? file))] (with-open [rdr (reader file)] (count (filter non-blank? (line-seq rdr))))))) ; END:clojure-loc (defn demo-xml-seq [] ; START:xml-seq (for [x (xml-seq (parse (java.io.File. "examples/sequences/compositions.xml"))) :when (= :composition (:tag x))] (:composer (:attrs x))) ; END:xml-seq )
true
(ns examples.sequences (:use examples.utils clojure.set clojure.xml)) ; START:song (def song {:name "PI:NAME:<NAME>END_PI" :artist "PI:NAME:<NAME>END_PI" :album "Polish Requiem" :genre "Classical"}) ; END:song ; START:compositions (def compositions #{{:name "The Art of the Fugue" :composer "PI:NAME:<NAME>END_PI"} {:name "Musical Offering" :composer "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI" :composer "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI" :composer "PI:NAME:<NAME>END_PI"}}) (def countries #{{:composer "PI:NAME:<NAME>END_PI" :country "Germany"} {:composer "PI:NAME:<NAME>END_PI" :country "Austria"} {:composer "PI:NAME:<NAME>END_PI" :country "Italy"}}) ; END:compositions ; TODO: add pretty-print that works with book margins. (defdemo demo-map-builders (assoc song :kind "MPEG Audio File") (dissoc song :genre) (select-keys song [:name :artist]) (merge song {:size 8118166 :time 507245})) (defdemo demo-merge-with (merge-with concat {:flintstone, ["PI:NAME:<NAME>END_PI"], :rubble ["PI:NAME:<NAME>END_PI"]} {:flintstone, ["PI:NAME:<NAME>END_PI"], :rubble ["PI:NAME:<NAME>END_PI"]} {:flintstone, ["Pebbles"], :rubble ["Bam-Bam"]})) ; START:sets (def languages #{"java" "c" "d" "clojure"}) (def letters #{"a" "b" "c" "d" "e"}) (def beverages #{"java" "chai" "pop"}) (def inventors {"java" "gosling", "clojure" "hickey", "ruby" "matz"}) ; END: sets (defdemo demo-mutable-re ; START:mutable-re ; don't do this! (let [m (re-matcher #"\w+" "the quick brown fox")] (loop [match (re-find m)] (if (nil? match) nil (do (println match) (recur (re-find m)))))) ; END:mutable-re ) ; START:filter (defn minutes [mins] (* mins 1000 60)) (defn recently-modified? [file] (> (.lastModified file) (- (System/currentTimeMillis) (minutes 30)))) ; END:filter ; START:clojure-loc (use '[clojure.contrib.duck-streams :only (reader)]) (defn non-blank? [line] (if (re-find #"\S" line) true false)) (defn non-svn? [file] (not (.startsWith (.toString file) ".svn"))) (defn clojure-source? [file] (.endsWith (.toString file) ".clj")) (defn clojure-loc [base-file] (reduce + (for [file (file-seq base-file) :when (and (clojure-source? file) (non-svn? file))] (with-open [rdr (reader file)] (count (filter non-blank? (line-seq rdr))))))) ; END:clojure-loc (defn demo-xml-seq [] ; START:xml-seq (for [x (xml-seq (parse (java.io.File. "examples/sequences/compositions.xml"))) :when (= :composition (:tag x))] (:composer (:attrs x))) ; END:xml-seq )
[ { "context": "{ :doc \"Symbol Utility Functions\"\n :author \"Yannick Scherer\" }\n thrift-clj.utils.symbols)\n\n(defn inner\n \"Cr", "end": 70, "score": 0.9998602867126465, "start": 55, "tag": "NAME", "value": "Yannick Scherer" } ]
src/thrift_clj/utils/symbols.clj
ipostelnik/thrift-clj
35
(ns ^{ :doc "Symbol Utility Functions" :author "Yannick Scherer" } thrift-clj.utils.symbols) (defn inner "Create symbol representing an inner class." [outer-class inner-class] (symbol (str outer-class "$" inner-class))) (defn static "Create symbol representing a static method." [class method] (symbol (str class "/" method))) (defn full-class-symbol "Get Symbol representing Class (including Package)." [^Class class] (symbol (.getName class))) (defn class-symbol "Get Symbol representing Class (without Package)." [^Class class] (symbol (.getSimpleName class)))
39337
(ns ^{ :doc "Symbol Utility Functions" :author "<NAME>" } thrift-clj.utils.symbols) (defn inner "Create symbol representing an inner class." [outer-class inner-class] (symbol (str outer-class "$" inner-class))) (defn static "Create symbol representing a static method." [class method] (symbol (str class "/" method))) (defn full-class-symbol "Get Symbol representing Class (including Package)." [^Class class] (symbol (.getName class))) (defn class-symbol "Get Symbol representing Class (without Package)." [^Class class] (symbol (.getSimpleName class)))
true
(ns ^{ :doc "Symbol Utility Functions" :author "PI:NAME:<NAME>END_PI" } thrift-clj.utils.symbols) (defn inner "Create symbol representing an inner class." [outer-class inner-class] (symbol (str outer-class "$" inner-class))) (defn static "Create symbol representing a static method." [class method] (symbol (str class "/" method))) (defn full-class-symbol "Get Symbol representing Class (including Package)." [^Class class] (symbol (.getName class))) (defn class-symbol "Get Symbol representing Class (without Package)." [^Class class] (symbol (.getSimpleName class)))
[ { "context": "hor [\"wahpenayo at gmail dot com\"\n \"John Alan McDonald\"\n \"Kristina Lisa Klinkner\" ]\n ", "end": 150, "score": 0.9998663663864136, "start": 132, "tag": "NAME", "value": "John Alan McDonald" }, { "context": " \"John Alan McDonald\"\n \"Kristina Lisa Klinkner\" ]\n :since \"2016-11-15\"\n :date \"2017-11", "end": 190, "score": 0.9998733997344971, "start": 168, "tag": "NAME", "value": "Kristina Lisa Klinkner" } ]
src/main/clojure/taigabench/metrics.clj
wahpenayo/taigabench
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author ["wahpenayo at gmail dot com" "John Alan McDonald" "Kristina Lisa Klinkner" ] :since "2016-11-15" :date "2017-11-29" :doc "Accuracy metrics designed for permutation importance measures." } taigabench.metrics (:require [clojure.string :as s] [clojure.java.io :as io] [zana.api :as z])) ;;---------------------------------------------------------------- (def ^{:private true :tag java.util.Random} auc-prng (z/mersenne-twister-generator "C589FB216CD402EC0A711C04E40801BE")) ;;---------------------------------------------------------------- (defn rmse "A [metric function](1metrics.html). Returns RMSE (root mean squared error): ``` (sqrt (/ (l2-distance2 y yhat) (count y))) ``` <dl> <dt><code>model</code></dt> <dd>a <code>clojure.lang.IFn$OOD</code> that takes an attribute map and a datum, one of the elements of <code>data</code>. </dd> <dt><code>attributes</code></dt><dd>a <code>java.util.Map</code> from keywords to functions that can be applied to the elements of <code>data</code>. Must contain <code>:ground-truth</code> and <code>:prediction</code> as a keys. </dd> <dt><code>data</code></dt><dd>an <code>Iterable</code></dd> </dl>" ^double [^clojure.lang.IFn$OD truth ^clojure.lang.IFn$OD prediction ^Iterable data] (z/rms-difference truth prediction data)) ;;------------------------------------------------------------------------------ (defn roc-auc "A [metric function](1metrics.html). Returns AUC, the area under the precision/recall curve for a classification model. https://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U_test <dl> <dt><code>model</code></dt> <dd>a <code>clojure.lang.IFn$OOD</code> that takes an attribute map and a datum, one of the elements of <code>data</code>. </dd> <dt><code>attributes</code></dt><dd>a <code>java.util.Map</code> from keywords to functions that can be applied to the elements of <code>data</code>. Must contain <code>:ground-truth</code> and <code>:prediction</code> as a keys. </dd> <dt><code>data</code></dt><dd>an <code>Iterable</code></dd> </dl>" ^double [^clojure.lang.IFn$OD truth ^clojure.lang.IFn$OD prediction ^Iterable data] (let [;; shuffle to avoid handling tied predictions ;; TODO: sort in place, or shuffle/sort iterators it (z/iterator (z/sort-by prediction (z/shuffle data auc-prng)))] (loop [i (int 1) n0 (int 0) r0 (double 0.0)] (if (z/has-next? it) (let [datum (z/next-item it) t (.invokePrim truth datum)] (cond (== 0.0 t) (recur (inc i) (inc n0) (+ r0 i)) (== 1.0 t) (recur (inc i) n0 r0) :else (throw (IllegalArgumentException. (print-str "Ground truth isn't 0.0 or 1.0:" t "\n" datum))))) (let [u0 (- r0 (* 0.5 n0 (inc n0))) n1 (- (z/count data) n0) u1 (- (* n0 n1) u0)] (/ (Math/max u0 u1) (* n0 n1))))))) ;;------------------------------------------------------------------------------
50677
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author ["wahpenayo at gmail dot com" "<NAME>" "<NAME>" ] :since "2016-11-15" :date "2017-11-29" :doc "Accuracy metrics designed for permutation importance measures." } taigabench.metrics (:require [clojure.string :as s] [clojure.java.io :as io] [zana.api :as z])) ;;---------------------------------------------------------------- (def ^{:private true :tag java.util.Random} auc-prng (z/mersenne-twister-generator "C589FB216CD402EC0A711C04E40801BE")) ;;---------------------------------------------------------------- (defn rmse "A [metric function](1metrics.html). Returns RMSE (root mean squared error): ``` (sqrt (/ (l2-distance2 y yhat) (count y))) ``` <dl> <dt><code>model</code></dt> <dd>a <code>clojure.lang.IFn$OOD</code> that takes an attribute map and a datum, one of the elements of <code>data</code>. </dd> <dt><code>attributes</code></dt><dd>a <code>java.util.Map</code> from keywords to functions that can be applied to the elements of <code>data</code>. Must contain <code>:ground-truth</code> and <code>:prediction</code> as a keys. </dd> <dt><code>data</code></dt><dd>an <code>Iterable</code></dd> </dl>" ^double [^clojure.lang.IFn$OD truth ^clojure.lang.IFn$OD prediction ^Iterable data] (z/rms-difference truth prediction data)) ;;------------------------------------------------------------------------------ (defn roc-auc "A [metric function](1metrics.html). Returns AUC, the area under the precision/recall curve for a classification model. https://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U_test <dl> <dt><code>model</code></dt> <dd>a <code>clojure.lang.IFn$OOD</code> that takes an attribute map and a datum, one of the elements of <code>data</code>. </dd> <dt><code>attributes</code></dt><dd>a <code>java.util.Map</code> from keywords to functions that can be applied to the elements of <code>data</code>. Must contain <code>:ground-truth</code> and <code>:prediction</code> as a keys. </dd> <dt><code>data</code></dt><dd>an <code>Iterable</code></dd> </dl>" ^double [^clojure.lang.IFn$OD truth ^clojure.lang.IFn$OD prediction ^Iterable data] (let [;; shuffle to avoid handling tied predictions ;; TODO: sort in place, or shuffle/sort iterators it (z/iterator (z/sort-by prediction (z/shuffle data auc-prng)))] (loop [i (int 1) n0 (int 0) r0 (double 0.0)] (if (z/has-next? it) (let [datum (z/next-item it) t (.invokePrim truth datum)] (cond (== 0.0 t) (recur (inc i) (inc n0) (+ r0 i)) (== 1.0 t) (recur (inc i) n0 r0) :else (throw (IllegalArgumentException. (print-str "Ground truth isn't 0.0 or 1.0:" t "\n" datum))))) (let [u0 (- r0 (* 0.5 n0 (inc n0))) n1 (- (z/count data) n0) u1 (- (* n0 n1) u0)] (/ (Math/max u0 u1) (* n0 n1))))))) ;;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author ["wahpenayo at gmail dot com" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" ] :since "2016-11-15" :date "2017-11-29" :doc "Accuracy metrics designed for permutation importance measures." } taigabench.metrics (:require [clojure.string :as s] [clojure.java.io :as io] [zana.api :as z])) ;;---------------------------------------------------------------- (def ^{:private true :tag java.util.Random} auc-prng (z/mersenne-twister-generator "C589FB216CD402EC0A711C04E40801BE")) ;;---------------------------------------------------------------- (defn rmse "A [metric function](1metrics.html). Returns RMSE (root mean squared error): ``` (sqrt (/ (l2-distance2 y yhat) (count y))) ``` <dl> <dt><code>model</code></dt> <dd>a <code>clojure.lang.IFn$OOD</code> that takes an attribute map and a datum, one of the elements of <code>data</code>. </dd> <dt><code>attributes</code></dt><dd>a <code>java.util.Map</code> from keywords to functions that can be applied to the elements of <code>data</code>. Must contain <code>:ground-truth</code> and <code>:prediction</code> as a keys. </dd> <dt><code>data</code></dt><dd>an <code>Iterable</code></dd> </dl>" ^double [^clojure.lang.IFn$OD truth ^clojure.lang.IFn$OD prediction ^Iterable data] (z/rms-difference truth prediction data)) ;;------------------------------------------------------------------------------ (defn roc-auc "A [metric function](1metrics.html). Returns AUC, the area under the precision/recall curve for a classification model. https://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U_test <dl> <dt><code>model</code></dt> <dd>a <code>clojure.lang.IFn$OOD</code> that takes an attribute map and a datum, one of the elements of <code>data</code>. </dd> <dt><code>attributes</code></dt><dd>a <code>java.util.Map</code> from keywords to functions that can be applied to the elements of <code>data</code>. Must contain <code>:ground-truth</code> and <code>:prediction</code> as a keys. </dd> <dt><code>data</code></dt><dd>an <code>Iterable</code></dd> </dl>" ^double [^clojure.lang.IFn$OD truth ^clojure.lang.IFn$OD prediction ^Iterable data] (let [;; shuffle to avoid handling tied predictions ;; TODO: sort in place, or shuffle/sort iterators it (z/iterator (z/sort-by prediction (z/shuffle data auc-prng)))] (loop [i (int 1) n0 (int 0) r0 (double 0.0)] (if (z/has-next? it) (let [datum (z/next-item it) t (.invokePrim truth datum)] (cond (== 0.0 t) (recur (inc i) (inc n0) (+ r0 i)) (== 1.0 t) (recur (inc i) n0 r0) :else (throw (IllegalArgumentException. (print-str "Ground truth isn't 0.0 or 1.0:" t "\n" datum))))) (let [u0 (- r0 (* 0.5 n0 (inc n0))) n1 (- (z/count data) n0) u1 (- (* n0 n1) u0)] (/ (Math/max u0 u1) (* n0 n1))))))) ;;------------------------------------------------------------------------------
[ { "context": "(ns ^{:author \"Adam Berger\"} ulvm.project-test\n \"Project tests\"\n (:require", "end": 26, "score": 0.9998555183410645, "start": 15, "tag": "NAME", "value": "Adam Berger" } ]
test/ulvm/project_test.clj
abrgr/ulvm
0
(ns ^{:author "Adam Berger"} ulvm.project-test "Project tests" (:require [clojure.spec.test :as st] [ulvm.core :as ulvm] [ulvm.reader :as uread] [ulvm.project :as uprj] [ulvm.mod-combinators] [ulvm.re-loaders] [cats.core :as m] [cats.monad.either :as e]) (:use [clojure.test :only [is deftest]])) (def flowfile-example `[(ulvm/defmodcombinator :sync "Description of sync combinator" {:ulvm.core/runnable-env-ref {:ulvm.core/runnable-env-loader-name :ulvm.re-loaders/project-file :ulvm.core/runnable-env-descriptor {:path "mod-combinators/sync.ulvm"}}}) (ulvm/defrunnableenvloader :http {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.re-loaders/project-file :ulvm.core/runnable-env-descriptor {:path "re-loaders/http.ulvm"}}}) (ulvm/defscope :my-scope "Description of scope" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.core/project-file :ulvm.core/runnable-env-descriptor {:path "scopes/nodejs.ulvm"}} :ulvm.core/modules {:adder {:ulvm.core/mod-combinator-name :sync :ulvm.core/mod-descriptor {:name "my-adder"}} :db-saver {:ulvm.core/mod-combinator-name :sync :ulvm.core/mod-descriptor {:name "my-db-saver"}}} :ulvm.core/init ((adder {:v1 42} :as my-adder))}) (ulvm/defflow :simple [] ; this flow's result has g as its error value and c as its default return value {:ulvm.core/output-descriptor {:err [g], :ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; invoke module B in scope-2 with arg-1 set to the default return of a, result is named 'b ((:B scope-2) {:arg-1 a} :as b) ; invoke module C in scope-1 with val set to the default return of a, result is named 'c ((:C scope-1) {:val a} :as c) ; invoke module G in scope-1 with first-val set to the other-ret return of a ((:G scope-1) {:first-val (:other-ret a)}) ; invoke module D in scope-2 with v1 set to the default return of b and v2 set to the default return of c ((:D scope-2) {:v1 b, :v2 c})) (ulvm/defflow :err-handling [] ; this flow's result has g as its error value and c as its default return value {:ulvm.core/output-descriptor {:err [g], :ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; v1 and c are calculated iff a returns a default result ((:B scope-1) {:the-val a} :as v1) ((:C scope-1) {:val-1 a, :val-2 v1} :as c) ; g is calculated iff a returns an error ((:log-err scope-1) {:err (:err a)} :as g)) (ulvm/defflow :err-recovery [] ; this flow's result has c as its default return value {:ulvm.core/output-descriptor {:ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; log and b are calculated iff a returns an error ((:log-err scope-1) {:err (:err a)} :as log) ((:B scope-1) {} :as b :after log))]) (deftest get-mod-combinator (st/instrument (st/instrumentable-syms ['ulvm 'uprj])) (let [ents (uread/eval-ulvm-seq flowfile-example) prj {:entities ents :mod-combinators {} :renv-loaders {} :renvs {} :env {::ulvm/project-root "examples/toy"}} {p :prj} (uprj/get prj :mod-combinators :sync)] (is (= 1 (count (:mod-combinators p)))) (is (every? #(e/right? (second %)) (:mod-combinators p))) (is (= 1 (count (:renv-loaders p)))) (is (every? #(e/right? (second %)) (:renv-loaders p))) (is (= 1 (count (:renvs p)))) (is (every? #(e/right? (second %)) (:renvs p))))) (deftest resolve-env-refs-ok (st/instrument (st/instrumentable-syms ['ulvm 'uprj])) (let [prj {:entities {} :mod-combinators {} :renv-loaders {} :renvs {} :env {:my-val :wrong :my {:ctx (e/right {:my-val :right})}}} to-resolve {:a '(ulvm.core/from-env :my-val)} resolved (uprj/resolve-env-refs prj [[:my :ctx]] to-resolve)] (is (e/right? resolved)) (is (= {:a :right} (m/extract resolved))))) (deftest resolve-env-refs-err (st/instrument (st/instrumentable-syms ['ulvm 'uprj])) (let [prj {:entities {} :mod-combinators {} :renv-loaders {} :renvs {} :env {:my-val :wrong :my {:ctx (e/left 4)}}} to-resolve {:a '(ulvm.core/from-env :my-val)} resolved (uprj/resolve-env-refs prj [[:my :ctx]] to-resolve)] (is (e/left? resolved)))) (deftest selective-eval (st/instrument (st/instrumentable-syms ['ulvm 'uprj])) (let [to-eval {:a '(ulvm.core/eval (str "hello" " " "world"))} evaled (uprj/selective-eval to-eval)] (is (e/right? evaled)) (is (= {:a "hello world"} (m/extract evaled)))))
50423
(ns ^{:author "<NAME>"} ulvm.project-test "Project tests" (:require [clojure.spec.test :as st] [ulvm.core :as ulvm] [ulvm.reader :as uread] [ulvm.project :as uprj] [ulvm.mod-combinators] [ulvm.re-loaders] [cats.core :as m] [cats.monad.either :as e]) (:use [clojure.test :only [is deftest]])) (def flowfile-example `[(ulvm/defmodcombinator :sync "Description of sync combinator" {:ulvm.core/runnable-env-ref {:ulvm.core/runnable-env-loader-name :ulvm.re-loaders/project-file :ulvm.core/runnable-env-descriptor {:path "mod-combinators/sync.ulvm"}}}) (ulvm/defrunnableenvloader :http {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.re-loaders/project-file :ulvm.core/runnable-env-descriptor {:path "re-loaders/http.ulvm"}}}) (ulvm/defscope :my-scope "Description of scope" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.core/project-file :ulvm.core/runnable-env-descriptor {:path "scopes/nodejs.ulvm"}} :ulvm.core/modules {:adder {:ulvm.core/mod-combinator-name :sync :ulvm.core/mod-descriptor {:name "my-adder"}} :db-saver {:ulvm.core/mod-combinator-name :sync :ulvm.core/mod-descriptor {:name "my-db-saver"}}} :ulvm.core/init ((adder {:v1 42} :as my-adder))}) (ulvm/defflow :simple [] ; this flow's result has g as its error value and c as its default return value {:ulvm.core/output-descriptor {:err [g], :ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; invoke module B in scope-2 with arg-1 set to the default return of a, result is named 'b ((:B scope-2) {:arg-1 a} :as b) ; invoke module C in scope-1 with val set to the default return of a, result is named 'c ((:C scope-1) {:val a} :as c) ; invoke module G in scope-1 with first-val set to the other-ret return of a ((:G scope-1) {:first-val (:other-ret a)}) ; invoke module D in scope-2 with v1 set to the default return of b and v2 set to the default return of c ((:D scope-2) {:v1 b, :v2 c})) (ulvm/defflow :err-handling [] ; this flow's result has g as its error value and c as its default return value {:ulvm.core/output-descriptor {:err [g], :ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; v1 and c are calculated iff a returns a default result ((:B scope-1) {:the-val a} :as v1) ((:C scope-1) {:val-1 a, :val-2 v1} :as c) ; g is calculated iff a returns an error ((:log-err scope-1) {:err (:err a)} :as g)) (ulvm/defflow :err-recovery [] ; this flow's result has c as its default return value {:ulvm.core/output-descriptor {:ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; log and b are calculated iff a returns an error ((:log-err scope-1) {:err (:err a)} :as log) ((:B scope-1) {} :as b :after log))]) (deftest get-mod-combinator (st/instrument (st/instrumentable-syms ['ulvm 'uprj])) (let [ents (uread/eval-ulvm-seq flowfile-example) prj {:entities ents :mod-combinators {} :renv-loaders {} :renvs {} :env {::ulvm/project-root "examples/toy"}} {p :prj} (uprj/get prj :mod-combinators :sync)] (is (= 1 (count (:mod-combinators p)))) (is (every? #(e/right? (second %)) (:mod-combinators p))) (is (= 1 (count (:renv-loaders p)))) (is (every? #(e/right? (second %)) (:renv-loaders p))) (is (= 1 (count (:renvs p)))) (is (every? #(e/right? (second %)) (:renvs p))))) (deftest resolve-env-refs-ok (st/instrument (st/instrumentable-syms ['ulvm 'uprj])) (let [prj {:entities {} :mod-combinators {} :renv-loaders {} :renvs {} :env {:my-val :wrong :my {:ctx (e/right {:my-val :right})}}} to-resolve {:a '(ulvm.core/from-env :my-val)} resolved (uprj/resolve-env-refs prj [[:my :ctx]] to-resolve)] (is (e/right? resolved)) (is (= {:a :right} (m/extract resolved))))) (deftest resolve-env-refs-err (st/instrument (st/instrumentable-syms ['ulvm 'uprj])) (let [prj {:entities {} :mod-combinators {} :renv-loaders {} :renvs {} :env {:my-val :wrong :my {:ctx (e/left 4)}}} to-resolve {:a '(ulvm.core/from-env :my-val)} resolved (uprj/resolve-env-refs prj [[:my :ctx]] to-resolve)] (is (e/left? resolved)))) (deftest selective-eval (st/instrument (st/instrumentable-syms ['ulvm 'uprj])) (let [to-eval {:a '(ulvm.core/eval (str "hello" " " "world"))} evaled (uprj/selective-eval to-eval)] (is (e/right? evaled)) (is (= {:a "hello world"} (m/extract evaled)))))
true
(ns ^{:author "PI:NAME:<NAME>END_PI"} ulvm.project-test "Project tests" (:require [clojure.spec.test :as st] [ulvm.core :as ulvm] [ulvm.reader :as uread] [ulvm.project :as uprj] [ulvm.mod-combinators] [ulvm.re-loaders] [cats.core :as m] [cats.monad.either :as e]) (:use [clojure.test :only [is deftest]])) (def flowfile-example `[(ulvm/defmodcombinator :sync "Description of sync combinator" {:ulvm.core/runnable-env-ref {:ulvm.core/runnable-env-loader-name :ulvm.re-loaders/project-file :ulvm.core/runnable-env-descriptor {:path "mod-combinators/sync.ulvm"}}}) (ulvm/defrunnableenvloader :http {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.re-loaders/project-file :ulvm.core/runnable-env-descriptor {:path "re-loaders/http.ulvm"}}}) (ulvm/defscope :my-scope "Description of scope" {:ulvm.core/runnable-env-ref {:ulvm.core/builtin-runnable-env-loader-name :ulvm.core/project-file :ulvm.core/runnable-env-descriptor {:path "scopes/nodejs.ulvm"}} :ulvm.core/modules {:adder {:ulvm.core/mod-combinator-name :sync :ulvm.core/mod-descriptor {:name "my-adder"}} :db-saver {:ulvm.core/mod-combinator-name :sync :ulvm.core/mod-descriptor {:name "my-db-saver"}}} :ulvm.core/init ((adder {:v1 42} :as my-adder))}) (ulvm/defflow :simple [] ; this flow's result has g as its error value and c as its default return value {:ulvm.core/output-descriptor {:err [g], :ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; invoke module B in scope-2 with arg-1 set to the default return of a, result is named 'b ((:B scope-2) {:arg-1 a} :as b) ; invoke module C in scope-1 with val set to the default return of a, result is named 'c ((:C scope-1) {:val a} :as c) ; invoke module G in scope-1 with first-val set to the other-ret return of a ((:G scope-1) {:first-val (:other-ret a)}) ; invoke module D in scope-2 with v1 set to the default return of b and v2 set to the default return of c ((:D scope-2) {:v1 b, :v2 c})) (ulvm/defflow :err-handling [] ; this flow's result has g as its error value and c as its default return value {:ulvm.core/output-descriptor {:err [g], :ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; v1 and c are calculated iff a returns a default result ((:B scope-1) {:the-val a} :as v1) ((:C scope-1) {:val-1 a, :val-2 v1} :as c) ; g is calculated iff a returns an error ((:log-err scope-1) {:err (:err a)} :as g)) (ulvm/defflow :err-recovery [] ; this flow's result has c as its default return value {:ulvm.core/output-descriptor {:ret [c]}} ; invoke module A in scope-1 with no args, result is named 'a ((:A scope-1) {} :as a) ; log and b are calculated iff a returns an error ((:log-err scope-1) {:err (:err a)} :as log) ((:B scope-1) {} :as b :after log))]) (deftest get-mod-combinator (st/instrument (st/instrumentable-syms ['ulvm 'uprj])) (let [ents (uread/eval-ulvm-seq flowfile-example) prj {:entities ents :mod-combinators {} :renv-loaders {} :renvs {} :env {::ulvm/project-root "examples/toy"}} {p :prj} (uprj/get prj :mod-combinators :sync)] (is (= 1 (count (:mod-combinators p)))) (is (every? #(e/right? (second %)) (:mod-combinators p))) (is (= 1 (count (:renv-loaders p)))) (is (every? #(e/right? (second %)) (:renv-loaders p))) (is (= 1 (count (:renvs p)))) (is (every? #(e/right? (second %)) (:renvs p))))) (deftest resolve-env-refs-ok (st/instrument (st/instrumentable-syms ['ulvm 'uprj])) (let [prj {:entities {} :mod-combinators {} :renv-loaders {} :renvs {} :env {:my-val :wrong :my {:ctx (e/right {:my-val :right})}}} to-resolve {:a '(ulvm.core/from-env :my-val)} resolved (uprj/resolve-env-refs prj [[:my :ctx]] to-resolve)] (is (e/right? resolved)) (is (= {:a :right} (m/extract resolved))))) (deftest resolve-env-refs-err (st/instrument (st/instrumentable-syms ['ulvm 'uprj])) (let [prj {:entities {} :mod-combinators {} :renv-loaders {} :renvs {} :env {:my-val :wrong :my {:ctx (e/left 4)}}} to-resolve {:a '(ulvm.core/from-env :my-val)} resolved (uprj/resolve-env-refs prj [[:my :ctx]] to-resolve)] (is (e/left? resolved)))) (deftest selective-eval (st/instrument (st/instrumentable-syms ['ulvm 'uprj])) (let [to-eval {:a '(ulvm.core/eval (str "hello" " " "world"))} evaled (uprj/selective-eval to-eval)] (is (e/right? evaled)) (is (= {:a "hello world"} (m/extract evaled)))))
[ { "context": "thread local binding for *queue-simple*\n\n Author: Konstantin Skaburskas <konstantin.skaburskas@gmail.com>\n\n \"\n (:refer-", "end": 336, "score": 0.9998714923858643, "start": 315, "tag": "NAME", "value": "Konstantin Skaburskas" }, { "context": " *queue-simple*\n\n Author: Konstantin Skaburskas <konstantin.skaburskas@gmail.com>\n\n \"\n (:refer-clojure :exclude [count get remov", "end": 369, "score": 0.9999314546585083, "start": 338, "tag": "EMAIL", "value": "konstantin.skaburskas@gmail.com" } ]
src/clj_dirq/queue_simple.clj
konstan/clj-dirq
0
(ns clj-dirq.queue-simple " Simple queue system providing the same interface as the other directory queue implementations. Please refer to `clj-dirq.queue` for general information about directory based queues. TODO: - write documentation - write thread local binding for *queue-simple* Author: Konstantin Skaburskas <konstantin.skaburskas@gmail.com> " (:refer-clojure :exclude [count get remove]) (import (ch.cern.dirq QueueSimple))) (def ^:dynamic *queue-simple* nil) (defn init! ([path] (alter-var-root #'*queue-simple* (constantly (QueueSimple. path)))) ([path numask] (alter-var-root #'*queue-simple* (constantly (QueueSimple. path numask)))) ) (def locked-suffix ".lck") (defn queue-path [] (.getQueuePath *queue-simple*)) (defn id [] (.getId *queue-simple*)) (defn add [^String data] (.add *queue-simple* data)) (defn add-path [path] (.addPath *queue-simple* path)) ;(defn get ; [name] ; (.get *queue-simple* name)) ; ;(defn get-as-byte-array ; [^String name] ; (.getAsByteArray *queue-simple* name)) (defn path [path] (.getPath *queue-simple* path)) (defn lock ([name] (lock name true)) ([name permissive] (.lock *queue-simple* name permissive))) (defn unlock ([name] (.unlock *queue-simple* name)) ([name permissive] (.unlock *queue-simple* name permissive))) ;(defn remove [name] ; (.remove *queue-simple* name)) ; ;(defn count ; [] ; (.count *queue-simple*)) ; ;(defn purge ; ([] ; (.purge *queue-simple*)) ; ([max-lock] ; (.purge *queue-simple* max-lock)) ; ([max-lock max-temp] ; (.purge *queue-simple* max-lock max-temp)))
97493
(ns clj-dirq.queue-simple " Simple queue system providing the same interface as the other directory queue implementations. Please refer to `clj-dirq.queue` for general information about directory based queues. TODO: - write documentation - write thread local binding for *queue-simple* Author: <NAME> <<EMAIL>> " (:refer-clojure :exclude [count get remove]) (import (ch.cern.dirq QueueSimple))) (def ^:dynamic *queue-simple* nil) (defn init! ([path] (alter-var-root #'*queue-simple* (constantly (QueueSimple. path)))) ([path numask] (alter-var-root #'*queue-simple* (constantly (QueueSimple. path numask)))) ) (def locked-suffix ".lck") (defn queue-path [] (.getQueuePath *queue-simple*)) (defn id [] (.getId *queue-simple*)) (defn add [^String data] (.add *queue-simple* data)) (defn add-path [path] (.addPath *queue-simple* path)) ;(defn get ; [name] ; (.get *queue-simple* name)) ; ;(defn get-as-byte-array ; [^String name] ; (.getAsByteArray *queue-simple* name)) (defn path [path] (.getPath *queue-simple* path)) (defn lock ([name] (lock name true)) ([name permissive] (.lock *queue-simple* name permissive))) (defn unlock ([name] (.unlock *queue-simple* name)) ([name permissive] (.unlock *queue-simple* name permissive))) ;(defn remove [name] ; (.remove *queue-simple* name)) ; ;(defn count ; [] ; (.count *queue-simple*)) ; ;(defn purge ; ([] ; (.purge *queue-simple*)) ; ([max-lock] ; (.purge *queue-simple* max-lock)) ; ([max-lock max-temp] ; (.purge *queue-simple* max-lock max-temp)))
true
(ns clj-dirq.queue-simple " Simple queue system providing the same interface as the other directory queue implementations. Please refer to `clj-dirq.queue` for general information about directory based queues. TODO: - write documentation - write thread local binding for *queue-simple* Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> " (:refer-clojure :exclude [count get remove]) (import (ch.cern.dirq QueueSimple))) (def ^:dynamic *queue-simple* nil) (defn init! ([path] (alter-var-root #'*queue-simple* (constantly (QueueSimple. path)))) ([path numask] (alter-var-root #'*queue-simple* (constantly (QueueSimple. path numask)))) ) (def locked-suffix ".lck") (defn queue-path [] (.getQueuePath *queue-simple*)) (defn id [] (.getId *queue-simple*)) (defn add [^String data] (.add *queue-simple* data)) (defn add-path [path] (.addPath *queue-simple* path)) ;(defn get ; [name] ; (.get *queue-simple* name)) ; ;(defn get-as-byte-array ; [^String name] ; (.getAsByteArray *queue-simple* name)) (defn path [path] (.getPath *queue-simple* path)) (defn lock ([name] (lock name true)) ([name permissive] (.lock *queue-simple* name permissive))) (defn unlock ([name] (.unlock *queue-simple* name)) ([name permissive] (.unlock *queue-simple* name permissive))) ;(defn remove [name] ; (.remove *queue-simple* name)) ; ;(defn count ; [] ; (.count *queue-simple*)) ; ;(defn purge ; ([] ; (.purge *queue-simple*)) ; ([max-lock] ; (.purge *queue-simple* max-lock)) ; ([max-lock max-temp] ; (.purge *queue-simple* max-lock max-temp)))
[ { "context": "keeper Metrics Service\"\n :url \"http://github.com/puppetlabs/trapperkeeper-metrics\"\n\n :min-lein-version \"2.7.", "end": 145, "score": 0.9992709755897522, "start": 135, "tag": "USERNAME", "value": "puppetlabs" }, { "context": " :password :env/clojars_jenkins_password\n :sign-releas", "end": 1296, "score": 0.7808427214622498, "start": 1275, "tag": "PASSWORD", "value": "jars_jenkins_password" } ]
project.clj
pcarlisle/trapperkeeper-metrics
0
(defproject puppetlabs/trapperkeeper-metrics "1.2.4-SNAPSHOT" :description "Trapperkeeper Metrics Service" :url "http://github.com/puppetlabs/trapperkeeper-metrics" :min-lein-version "2.7.1" :pedantic? :abort :parent-project {:coords [puppetlabs/clj-parent "1.7.26"] :inherit [:managed-dependencies]} :dependencies [[org.clojure/clojure] [prismatic/schema] [puppetlabs/kitchensink] [puppetlabs/trapperkeeper] [puppetlabs/ring-middleware] [cheshire] [org.clojure/java.jmx] [ring/ring-defaults] [org.clojure/tools.logging] [io.dropwizard.metrics/metrics-core] [io.dropwizard.metrics/metrics-graphite] [org.jolokia/jolokia-core "1.6.2"] [puppetlabs/comidi] [puppetlabs/i18n]] :plugins [[puppetlabs/i18n "0.6.0"] [lein-parent "0.3.1"]] :source-paths ["src/clj"] :java-source-paths ["src/java"] :deploy-repositories [["releases" {:url "https://clojars.org/repo" :username :env/clojars_jenkins_username :password :env/clojars_jenkins_password :sign-releases false}]] :classifiers [["test" :testutils]] :profiles {:dev {:aliases {"ring-example" ["trampoline" "run" "-b" "./examples/ring_app/bootstrap.cfg" "-c" "./examples/ring_app/ring-example.conf"]} :source-paths ["examples/ring_app/src"] :dependencies [[puppetlabs/http-client] [puppetlabs/trapperkeeper :classifier "test"] [puppetlabs/trapperkeeper-webserver-jetty9] [puppetlabs/kitchensink :classifier "test"]]} :testutils {:source-paths ^:replace ["test"] :java-source-paths ^:replace []}} :repl-options {:init-ns examples.ring-app.repl} :main puppetlabs.trapperkeeper.main)
66944
(defproject puppetlabs/trapperkeeper-metrics "1.2.4-SNAPSHOT" :description "Trapperkeeper Metrics Service" :url "http://github.com/puppetlabs/trapperkeeper-metrics" :min-lein-version "2.7.1" :pedantic? :abort :parent-project {:coords [puppetlabs/clj-parent "1.7.26"] :inherit [:managed-dependencies]} :dependencies [[org.clojure/clojure] [prismatic/schema] [puppetlabs/kitchensink] [puppetlabs/trapperkeeper] [puppetlabs/ring-middleware] [cheshire] [org.clojure/java.jmx] [ring/ring-defaults] [org.clojure/tools.logging] [io.dropwizard.metrics/metrics-core] [io.dropwizard.metrics/metrics-graphite] [org.jolokia/jolokia-core "1.6.2"] [puppetlabs/comidi] [puppetlabs/i18n]] :plugins [[puppetlabs/i18n "0.6.0"] [lein-parent "0.3.1"]] :source-paths ["src/clj"] :java-source-paths ["src/java"] :deploy-repositories [["releases" {:url "https://clojars.org/repo" :username :env/clojars_jenkins_username :password :env/clo<PASSWORD> :sign-releases false}]] :classifiers [["test" :testutils]] :profiles {:dev {:aliases {"ring-example" ["trampoline" "run" "-b" "./examples/ring_app/bootstrap.cfg" "-c" "./examples/ring_app/ring-example.conf"]} :source-paths ["examples/ring_app/src"] :dependencies [[puppetlabs/http-client] [puppetlabs/trapperkeeper :classifier "test"] [puppetlabs/trapperkeeper-webserver-jetty9] [puppetlabs/kitchensink :classifier "test"]]} :testutils {:source-paths ^:replace ["test"] :java-source-paths ^:replace []}} :repl-options {:init-ns examples.ring-app.repl} :main puppetlabs.trapperkeeper.main)
true
(defproject puppetlabs/trapperkeeper-metrics "1.2.4-SNAPSHOT" :description "Trapperkeeper Metrics Service" :url "http://github.com/puppetlabs/trapperkeeper-metrics" :min-lein-version "2.7.1" :pedantic? :abort :parent-project {:coords [puppetlabs/clj-parent "1.7.26"] :inherit [:managed-dependencies]} :dependencies [[org.clojure/clojure] [prismatic/schema] [puppetlabs/kitchensink] [puppetlabs/trapperkeeper] [puppetlabs/ring-middleware] [cheshire] [org.clojure/java.jmx] [ring/ring-defaults] [org.clojure/tools.logging] [io.dropwizard.metrics/metrics-core] [io.dropwizard.metrics/metrics-graphite] [org.jolokia/jolokia-core "1.6.2"] [puppetlabs/comidi] [puppetlabs/i18n]] :plugins [[puppetlabs/i18n "0.6.0"] [lein-parent "0.3.1"]] :source-paths ["src/clj"] :java-source-paths ["src/java"] :deploy-repositories [["releases" {:url "https://clojars.org/repo" :username :env/clojars_jenkins_username :password :env/cloPI:PASSWORD:<PASSWORD>END_PI :sign-releases false}]] :classifiers [["test" :testutils]] :profiles {:dev {:aliases {"ring-example" ["trampoline" "run" "-b" "./examples/ring_app/bootstrap.cfg" "-c" "./examples/ring_app/ring-example.conf"]} :source-paths ["examples/ring_app/src"] :dependencies [[puppetlabs/http-client] [puppetlabs/trapperkeeper :classifier "test"] [puppetlabs/trapperkeeper-webserver-jetty9] [puppetlabs/kitchensink :classifier "test"]]} :testutils {:source-paths ^:replace ["test"] :java-source-paths ^:replace []}} :repl-options {:init-ns examples.ring-app.repl} :main puppetlabs.trapperkeeper.main)
[ { "context": ";;;\n;;; Copyright 2020 David Edwards\n;;;\n;;; Licensed under the Apache License, Versio", "end": 36, "score": 0.9998108744621277, "start": 23, "tag": "NAME", "value": "David Edwards" } ]
test/rpn/parser_test.clj
davidledwards/rpn-clojure
1
;;; ;;; Copyright 2020 David Edwards ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. ;;; (ns rpn.parser-test (:require [clojure.test :as test]) (:require [rpn.expressions :as expr]) (:require [rpn.lexer :as lexer]) (:require [rpn.parser :as parser])) (declare parser-tests) (test/deftest valid-randomized-expressions (doseq [[e ast] parser-tests] (test/is (= (parser/parser (lexer/lexer e)) ast)))) (test/deftest invalid-expressions (doseq [e ["" " " "a +" "+ a" "a 1" "(a + 1" "a + 1)" "(a + 1))" ")a" "()" "a + * 1" "a $ 1" "(a + 1)(b + 2)"]] (test/is (thrown? Exception (doall (parser/parser (lexer/lexer e))))))) (def ^:private parser-tests (list ["( 0.39 * ( 0.57 ) min 0.13 ) max 1.78 min 1.64 max ( nT ^ ( 0.47 % ( ( jQ max qh ^ PK % 1.01 ) ^ 1.24 max 0.50 max ( ( VU ^ 0.57 ) + qx ) ) - ( 1.71 ) max gx ) )" (rpn.ast/max-AST (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.39) (rpn.ast/min-AST (rpn.ast/number-AST 0.57) (rpn.ast/number-AST 0.13))) (rpn.ast/number-AST 1.78)) (rpn.ast/number-AST 1.64)) (rpn.ast/power-AST (rpn.ast/symbol-AST "nT") (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.47) (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "jQ") (rpn.ast/symbol-AST "qh")) (rpn.ast/symbol-AST "PK")) (rpn.ast/number-AST 1.01)) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.24) (rpn.ast/number-AST 0.5)) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "VU") (rpn.ast/number-AST 0.57)) (rpn.ast/symbol-AST "qx"))))) (rpn.ast/max-AST (rpn.ast/number-AST 1.71) (rpn.ast/symbol-AST "gx")))))] ["0.23 / XT + 0.08" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.23) (rpn.ast/symbol-AST "XT")) (rpn.ast/number-AST 0.08))] ["TM" (rpn.ast/symbol-AST "TM")] ["DM * ( RL ) / ( ( ( 1.30 min JJ * ( 1.02 max ( 0.61 * GQ / 0.64 ) max ( ( 1.45 ) * AB ^ ( ( ( 1.75 + 1.79 * ( tO + Lp max us min 1.67 ) ) * ( 0.10 min 0.32 ) min ( 0.01 ) ) * ( ( 1.73 ) ) - 0.16 ) * 0.85 ) ) ) % ( gY max oQ / ( 0.96 % 1.02 - 0.17 ) ) min gS * 1.05 ) ^ wW ) max ( ea min ( ( ( ( ( Ps ) ) / xr ) ) max 1.37 max 0.31 ) )" (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "DM") (rpn.ast/symbol-AST "RL")) (rpn.ast/max-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.3) (rpn.ast/symbol-AST "JJ")) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.02) (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.61) (rpn.ast/symbol-AST "GQ")) (rpn.ast/number-AST 0.64))) (rpn.ast/multiply-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.45) (rpn.ast/symbol-AST "AB")) (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.75) (rpn.ast/multiply-AST (rpn.ast/number-AST 1.79) (rpn.ast/add-AST (rpn.ast/symbol-AST "tO") (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Lp") (rpn.ast/symbol-AST "us")) (rpn.ast/number-AST 1.67))))) (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.1) (rpn.ast/number-AST 0.32)) (rpn.ast/number-AST 0.01))) (rpn.ast/number-AST 1.73)) (rpn.ast/number-AST 0.16))) (rpn.ast/number-AST 0.85)))) (rpn.ast/min-AST (rpn.ast/divide-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "gY") (rpn.ast/symbol-AST "oQ")) (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.96) (rpn.ast/number-AST 1.02)) (rpn.ast/number-AST 0.17))) (rpn.ast/symbol-AST "gS"))) (rpn.ast/number-AST 1.05)) (rpn.ast/symbol-AST "wW")) (rpn.ast/min-AST (rpn.ast/symbol-AST "ea") (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "Ps") (rpn.ast/symbol-AST "xr")) (rpn.ast/number-AST 1.37)) (rpn.ast/number-AST 0.31)))))] ["0.56 - ( ( ( ( ( ( ( 1.66 ) min 1.58 ) * ( 1.54 + ( 1.63 * ( Qu % qD % 0.34 ) ^ 1.48 + oY ) ) * ( 1.64 ^ 1.95 ^ ( 0.19 ^ ( lk max 1.48 ) ) ) ) max Ue + 0.46 ^ 1.67 ) % FT / Ni min ( Ls / zq + ( 0.07 / ( 0.17 ) min ( 0.25 ) ) ) ) max lY ) min ( Vv max 1.23 ) ) % rr" (rpn.ast/subtract-AST (rpn.ast/number-AST 0.56) (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.66) (rpn.ast/number-AST 1.58)) (rpn.ast/add-AST (rpn.ast/number-AST 1.54) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.63) (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Qu") (rpn.ast/symbol-AST "qD")) (rpn.ast/number-AST 0.34))) (rpn.ast/number-AST 1.48)) (rpn.ast/symbol-AST "oY")))) (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.64) (rpn.ast/number-AST 1.95)) (rpn.ast/power-AST (rpn.ast/number-AST 0.19) (rpn.ast/max-AST (rpn.ast/symbol-AST "lk") (rpn.ast/number-AST 1.48))))) (rpn.ast/symbol-AST "Ue")) (rpn.ast/power-AST (rpn.ast/number-AST 0.46) (rpn.ast/number-AST 1.67))) (rpn.ast/symbol-AST "FT")) (rpn.ast/min-AST (rpn.ast/symbol-AST "Ni") (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "Ls") (rpn.ast/symbol-AST "zq")) (rpn.ast/divide-AST (rpn.ast/number-AST 0.07) (rpn.ast/min-AST (rpn.ast/number-AST 0.17) (rpn.ast/number-AST 0.25)))))) (rpn.ast/symbol-AST "lY")) (rpn.ast/max-AST (rpn.ast/symbol-AST "Vv") (rpn.ast/number-AST 1.23))) (rpn.ast/symbol-AST "rr")))] ["0.78 ^ ( xm max 0.85 + mJ )" (rpn.ast/power-AST (rpn.ast/number-AST 0.78) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "xm") (rpn.ast/number-AST 0.85)) (rpn.ast/symbol-AST "mJ")))] ["xD * Iu" (rpn.ast/multiply-AST (rpn.ast/symbol-AST "xD") (rpn.ast/symbol-AST "Iu"))] ["dG * Xx / di" (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "dG") (rpn.ast/symbol-AST "Xx")) (rpn.ast/symbol-AST "di"))] ["Ur max TC - 0.10" (rpn.ast/subtract-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Ur") (rpn.ast/symbol-AST "TC")) (rpn.ast/number-AST 0.1))] ["( 1.30 ^ ( ( 1.01 min 1.95 min 1.15 ) * lp + kT ) ) % ( ( ( 0.91 ) ) - hv max ( Wu ) * 0.23 ) * 0.18" (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.3) (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.01) (rpn.ast/number-AST 1.95)) (rpn.ast/number-AST 1.15)) (rpn.ast/symbol-AST "lp")) (rpn.ast/symbol-AST "kT"))) (rpn.ast/subtract-AST (rpn.ast/number-AST 0.91) (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "hv") (rpn.ast/symbol-AST "Wu")) (rpn.ast/number-AST 0.23)))) (rpn.ast/number-AST 0.18))] ["YN - dl" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "YN") (rpn.ast/symbol-AST "dl"))] ["( Uv )" (rpn.ast/symbol-AST "Uv")] ["1.20 - ea min 1.61" (rpn.ast/subtract-AST (rpn.ast/number-AST 1.2) (rpn.ast/min-AST (rpn.ast/symbol-AST "ea") (rpn.ast/number-AST 1.61)))] ["xN * 0.06" (rpn.ast/multiply-AST (rpn.ast/symbol-AST "xN") (rpn.ast/number-AST 0.06))] ["LE ^ tg max nZ ^ XY" (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "LE") (rpn.ast/max-AST (rpn.ast/symbol-AST "tg") (rpn.ast/symbol-AST "nZ"))) (rpn.ast/symbol-AST "XY"))] ["( ( ( ( Dx ^ 0.48 ) % ( ( ZE ^ Fq - 1.64 % ( ya / Ea % 1.67 + ( 1.73 % fN ) ) ) ) min 0.26 ) max ( JI - ( ( Dq max ( 1.68 max UZ * HZ * 0.08 ) % 1.13 - 1.67 ) ) ) ) min ( 0.01 ) / aD * 0.61 )" (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "Dx") (rpn.ast/number-AST 0.48)) (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "ZE") (rpn.ast/symbol-AST "Fq")) (rpn.ast/modulo-AST (rpn.ast/number-AST 1.64) (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "ya") (rpn.ast/symbol-AST "Ea")) (rpn.ast/number-AST 1.67)) (rpn.ast/modulo-AST (rpn.ast/number-AST 1.73) (rpn.ast/symbol-AST "fN"))))) (rpn.ast/number-AST 0.26))) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "JI") (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Dq") (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.68) (rpn.ast/symbol-AST "UZ")) (rpn.ast/symbol-AST "HZ")) (rpn.ast/number-AST 0.08))) (rpn.ast/number-AST 1.13)) (rpn.ast/number-AST 1.67)))) (rpn.ast/number-AST 0.01)) (rpn.ast/symbol-AST "aD")) (rpn.ast/number-AST 0.61))] ["( ( ( ( ( ( ( 1.25 + 1.18 - ( ( ( 0.60 ) * ( ( 1.23 min yT * Xf ) / iA ) ) * JG + XB max Ma ) ) min ( 1.42 ) max ( ( 0.05 - ( Bb / so ) ) ) ) ) * gk ) ^ 0.09 max mq ) min gj ) % ( EA * uk min 0.77 ^ CY ) min ( ( Fi min 0.62 ) * 0.41 ) ^ 0.62 )" (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.25) (rpn.ast/number-AST 1.18)) (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.6) (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.23) (rpn.ast/symbol-AST "yT")) (rpn.ast/symbol-AST "Xf")) (rpn.ast/symbol-AST "iA"))) (rpn.ast/symbol-AST "JG")) (rpn.ast/max-AST (rpn.ast/symbol-AST "XB") (rpn.ast/symbol-AST "Ma")))) (rpn.ast/number-AST 1.42)) (rpn.ast/subtract-AST (rpn.ast/number-AST 0.05) (rpn.ast/divide-AST (rpn.ast/symbol-AST "Bb") (rpn.ast/symbol-AST "so")))) (rpn.ast/symbol-AST "gk")) (rpn.ast/max-AST (rpn.ast/number-AST 0.09) (rpn.ast/symbol-AST "mq"))) (rpn.ast/symbol-AST "gj")) (rpn.ast/min-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "EA") (rpn.ast/min-AST (rpn.ast/symbol-AST "uk") (rpn.ast/number-AST 0.77))) (rpn.ast/symbol-AST "CY")) (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "Fi") (rpn.ast/number-AST 0.62)) (rpn.ast/number-AST 0.41)))) (rpn.ast/number-AST 0.62))] ["aF * 1.36 max ( Gc * ( ( ( uv ) * 1.22 + 0.05 + ( ( 0.86 * ( ( 1.74 % 0.25 % 1.80 min ( CR ) ) max ( 0.26 / 1.36 * ( ( ( aO + 0.43 + bu min EX ) % ( ( 0.89 ) max LG ^ xe max We ) ) ^ ( ( 1.74 min 1.60 ) + Ut / ( ( KL * ( ( ( ( KZ ) ) ) / ( dp ^ 0.13 - 1.60 ) ) * ( ( ( oT ) % yz / 0.74 % KQ ) * 1.47 % 0.56 ) ) ) ) / ( 0.93 + 0.56 % ( ( cc % HE max cO ) ) * ( 1.18 + ( XA % hW ) - ( QT ) ) ) min 1.70 ) ) % ( st + 1.30 ) + 1.52 ) ) min ( OJ + 0.26 / sq max 1.09 ) min 1.16 ) ) ^ Xh ) ^ pR / kf )" (rpn.ast/multiply-AST (rpn.ast/symbol-AST "aF") (rpn.ast/max-AST (rpn.ast/number-AST 1.36) (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Gc") (rpn.ast/power-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "uv") (rpn.ast/number-AST 1.22)) (rpn.ast/number-AST 0.05)) (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.86) (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.74) (rpn.ast/number-AST 0.25)) (rpn.ast/min-AST (rpn.ast/number-AST 1.8) (rpn.ast/symbol-AST "CR"))) (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.26) (rpn.ast/number-AST 1.36)) (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "aO") (rpn.ast/number-AST 0.43)) (rpn.ast/min-AST (rpn.ast/symbol-AST "bu") (rpn.ast/symbol-AST "EX"))) (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/number-AST 0.89) (rpn.ast/symbol-AST "LG")) (rpn.ast/max-AST (rpn.ast/symbol-AST "xe") (rpn.ast/symbol-AST "We")))) (rpn.ast/add-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.74) (rpn.ast/number-AST 1.6)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "Ut") (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "KL") (rpn.ast/divide-AST (rpn.ast/symbol-AST "KZ") (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "dp") (rpn.ast/number-AST 0.13)) (rpn.ast/number-AST 1.6)))) (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "oT") (rpn.ast/symbol-AST "yz")) (rpn.ast/number-AST 0.74)) (rpn.ast/symbol-AST "KQ")) (rpn.ast/number-AST 1.47)) (rpn.ast/number-AST 0.56)))))) (rpn.ast/min-AST (rpn.ast/add-AST (rpn.ast/number-AST 0.93) (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.56) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "cc") (rpn.ast/max-AST (rpn.ast/symbol-AST "HE") (rpn.ast/symbol-AST "cO")))) (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.18) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "XA") (rpn.ast/symbol-AST "hW"))) (rpn.ast/symbol-AST "QT")))) (rpn.ast/number-AST 1.7))))) (rpn.ast/add-AST (rpn.ast/symbol-AST "st") (rpn.ast/number-AST 1.3))) (rpn.ast/number-AST 1.52))) (rpn.ast/add-AST (rpn.ast/symbol-AST "OJ") (rpn.ast/divide-AST (rpn.ast/number-AST 0.26) (rpn.ast/max-AST (rpn.ast/symbol-AST "sq") (rpn.ast/number-AST 1.09))))) (rpn.ast/number-AST 1.16))) (rpn.ast/symbol-AST "Xh"))) (rpn.ast/symbol-AST "pR")) (rpn.ast/symbol-AST "kf"))))] ["( ( ( qn ) - 0.72 * ( 1.24 ) max Hj ) + ( ( oe max ( VP / zC + 1.42 ) max 0.08 ^ 0.63 ) ) - ( ( zX % BE min 1.16 ) min ( zI ) ) ) ^ 1.75 max ( ( WZ ) max ( rm / ( BG min Pm / 1.65 ) max ( Ug ^ 0.74 ) ) + nC ) / ( 1.91 min 0.04 ^ 0.54 max ( ( 1.70 max 0.64 min kB / 0.51 ) * ( CU + 1.52 max 0.92 ^ ( ( 1.27 * Ey max ( Vm + vA % ( 1.24 - ( Eu max ( bK min Ny min ( uo min 0.24 - It ) * 1.10 ) ) ) ) ) * 1.94 + eN / 0.88 ) ) max 1.54 ^ 0.67 ) )" (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "qn") (rpn.ast/multiply-AST (rpn.ast/number-AST 0.72) (rpn.ast/max-AST (rpn.ast/number-AST 1.24) (rpn.ast/symbol-AST "Hj")))) (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "oe") (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "VP") (rpn.ast/symbol-AST "zC")) (rpn.ast/number-AST 1.42))) (rpn.ast/number-AST 0.08)) (rpn.ast/number-AST 0.63))) (rpn.ast/min-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "zX") (rpn.ast/min-AST (rpn.ast/symbol-AST "BE") (rpn.ast/number-AST 1.16))) (rpn.ast/symbol-AST "zI"))) (rpn.ast/max-AST (rpn.ast/number-AST 1.75) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "WZ") (rpn.ast/divide-AST (rpn.ast/symbol-AST "rm") (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "BG") (rpn.ast/symbol-AST "Pm")) (rpn.ast/number-AST 1.65)) (rpn.ast/power-AST (rpn.ast/symbol-AST "Ug") (rpn.ast/number-AST 0.74))))) (rpn.ast/symbol-AST "nC")))) (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.91) (rpn.ast/number-AST 0.04)) (rpn.ast/max-AST (rpn.ast/number-AST 0.54) (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.7) (rpn.ast/number-AST 0.64)) (rpn.ast/symbol-AST "kB")) (rpn.ast/number-AST 0.51)) (rpn.ast/max-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "CU") (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.52) (rpn.ast/number-AST 0.92)) (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.27) (rpn.ast/max-AST (rpn.ast/symbol-AST "Ey") (rpn.ast/add-AST (rpn.ast/symbol-AST "Vm") (rpn.ast/modulo-AST (rpn.ast/symbol-AST "vA") (rpn.ast/subtract-AST (rpn.ast/number-AST 1.24) (rpn.ast/max-AST (rpn.ast/symbol-AST "Eu") (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "bK") (rpn.ast/symbol-AST "Ny")) (rpn.ast/subtract-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "uo") (rpn.ast/number-AST 0.24)) (rpn.ast/symbol-AST "It"))) (rpn.ast/number-AST 1.1)))))))) (rpn.ast/number-AST 1.94)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "eN") (rpn.ast/number-AST 0.88))))) (rpn.ast/number-AST 1.54))) (rpn.ast/number-AST 0.67)))))] ["( NU ) - ( ( zL % FE + ( ( 0.80 min ( 1.26 * SP / ( ( 1.47 max 0.15 - NP + ( ( 1.34 - uU ) * 1.91 ) ) ) ) ) ) ^ 0.30 ) + 0.69 * Jw ^ 1.62 )" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "NU") (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "zL") (rpn.ast/symbol-AST "FE")) (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.8) (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.26) (rpn.ast/symbol-AST "SP")) (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.47) (rpn.ast/number-AST 0.15)) (rpn.ast/symbol-AST "NP")) (rpn.ast/multiply-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.34) (rpn.ast/symbol-AST "uU")) (rpn.ast/number-AST 1.91))))) (rpn.ast/number-AST 0.3))) (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.69) (rpn.ast/symbol-AST "Jw")) (rpn.ast/number-AST 1.62))))] ["xH % uU * 1.86 % 0.39" (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "xH") (rpn.ast/symbol-AST "uU")) (rpn.ast/number-AST 1.86)) (rpn.ast/number-AST 0.39))] ["jY" (rpn.ast/symbol-AST "jY")] ["QJ" (rpn.ast/symbol-AST "QJ")] ["( ( 1.92 + nR ) % lr - ( ( 1.94 * 1.34 min AQ ^ 1.98 ) + ( ( ( ( ( ( 1.82 min ( 1.00 + ( Ys - ( eE ^ ( jv + ( 1.52 ) * aO ) ) ^ oz ) ) * ( ( FF ) + tE ) min ( NB / Rz ) ) / 0.76 ) ^ TV max Fu min 0.46 ) * Cr + HR ^ Iv ) max 1.97 % ( ( 1.25 % ( 0.14 ) * ( Kc ) % 0.86 ) - 1.47 + ( ( 1.54 + 1.52 / ( FP - cp max ( 1.66 / zM ) min 1.47 ) * 1.01 ) ^ ( Ow ) min AY ) ) ^ ( ( 0.24 ) % ( ss ) ^ ( cL ^ Bm ) % 1.38 ) ) min 0.01 - 1.12 ) ) max 0.30 ) + ts % 1.72" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.92) (rpn.ast/symbol-AST "nR")) (rpn.ast/symbol-AST "lr")) (rpn.ast/max-AST (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.94) (rpn.ast/min-AST (rpn.ast/number-AST 1.34) (rpn.ast/symbol-AST "AQ"))) (rpn.ast/number-AST 1.98)) (rpn.ast/subtract-AST (rpn.ast/min-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.82) (rpn.ast/add-AST (rpn.ast/number-AST 1.0) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Ys") (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "eE") (rpn.ast/add-AST (rpn.ast/symbol-AST "jv") (rpn.ast/multiply-AST (rpn.ast/number-AST 1.52) (rpn.ast/symbol-AST "aO")))) (rpn.ast/symbol-AST "oz"))))) (rpn.ast/min-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "FF") (rpn.ast/symbol-AST "tE")) (rpn.ast/divide-AST (rpn.ast/symbol-AST "NB") (rpn.ast/symbol-AST "Rz")))) (rpn.ast/number-AST 0.76)) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "TV") (rpn.ast/symbol-AST "Fu")) (rpn.ast/number-AST 0.46))) (rpn.ast/symbol-AST "Cr")) (rpn.ast/power-AST (rpn.ast/symbol-AST "HR") (rpn.ast/symbol-AST "Iv"))) (rpn.ast/number-AST 1.97)) (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.25) (rpn.ast/number-AST 0.14)) (rpn.ast/symbol-AST "Kc")) (rpn.ast/number-AST 0.86)) (rpn.ast/number-AST 1.47)) (rpn.ast/power-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.54) (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.52) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "FP") (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "cp") (rpn.ast/divide-AST (rpn.ast/number-AST 1.66) (rpn.ast/symbol-AST "zM"))) (rpn.ast/number-AST 1.47)))) (rpn.ast/number-AST 1.01))) (rpn.ast/min-AST (rpn.ast/symbol-AST "Ow") (rpn.ast/symbol-AST "AY"))))) (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.24) (rpn.ast/symbol-AST "ss")) (rpn.ast/power-AST (rpn.ast/symbol-AST "cL") (rpn.ast/symbol-AST "Bm"))) (rpn.ast/number-AST 1.38))) (rpn.ast/number-AST 0.01)) (rpn.ast/number-AST 1.12))) (rpn.ast/number-AST 0.3))) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "ts") (rpn.ast/number-AST 1.72)))] ["0.29 ^ ( ( 1.11 / rH + Xa ^ 1.33 ) max oy max 1.45 max Xr ) + ( NL - 1.51 )" (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/number-AST 0.29) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.11) (rpn.ast/symbol-AST "rH")) (rpn.ast/power-AST (rpn.ast/symbol-AST "Xa") (rpn.ast/number-AST 1.33))) (rpn.ast/symbol-AST "oy")) (rpn.ast/number-AST 1.45)) (rpn.ast/symbol-AST "Xr"))) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "NL") (rpn.ast/number-AST 1.51)))] ["0.18 min 0.43 * 0.06" (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.18) (rpn.ast/number-AST 0.43)) (rpn.ast/number-AST 0.06))] ["( ( ( ( wW min to + 0.24 % Uv ) ^ Mg / 1.26 ) ) % ( 1.73 ) - Qr ) / ( HA - Pn - 0.75 ^ VW )" (rpn.ast/divide-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/add-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "wW") (rpn.ast/symbol-AST "to")) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.24) (rpn.ast/symbol-AST "Uv"))) (rpn.ast/symbol-AST "Mg")) (rpn.ast/number-AST 1.26)) (rpn.ast/number-AST 1.73)) (rpn.ast/symbol-AST "Qr")) (rpn.ast/subtract-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "HA") (rpn.ast/symbol-AST "Pn")) (rpn.ast/power-AST (rpn.ast/number-AST 0.75) (rpn.ast/symbol-AST "VW"))))] ["Jj" (rpn.ast/symbol-AST "Jj")] ["MI + ( 1.72 % ( Xj ^ ( 0.97 min 1.05 ^ gA ) % QA max Qq ) ^ zB + 1.46 )" (rpn.ast/add-AST (rpn.ast/symbol-AST "MI") (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.72) (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "Xj") (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.97) (rpn.ast/number-AST 1.05)) (rpn.ast/symbol-AST "gA"))) (rpn.ast/max-AST (rpn.ast/symbol-AST "QA") (rpn.ast/symbol-AST "Qq")))) (rpn.ast/symbol-AST "zB")) (rpn.ast/number-AST 1.46)))] ["( 1.54 max ( 1.47 min 1.21 + 1.04 ) % 1.51 + wO ) + gN ^ 1.71 * ge" (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.54) (rpn.ast/add-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.47) (rpn.ast/number-AST 1.21)) (rpn.ast/number-AST 1.04))) (rpn.ast/number-AST 1.51)) (rpn.ast/symbol-AST "wO")) (rpn.ast/multiply-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "gN") (rpn.ast/number-AST 1.71)) (rpn.ast/symbol-AST "ge")))] ["( 0.03 / ( ( 0.98 % hN - DI ) ) min od ) + 1.39 % ( ph min sX ) % 0.38" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.03) (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.98) (rpn.ast/symbol-AST "hN")) (rpn.ast/symbol-AST "DI")) (rpn.ast/symbol-AST "od"))) (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.39) (rpn.ast/min-AST (rpn.ast/symbol-AST "ph") (rpn.ast/symbol-AST "sX"))) (rpn.ast/number-AST 0.38)))] ["( WH ^ 1.85 )" (rpn.ast/power-AST (rpn.ast/symbol-AST "WH") (rpn.ast/number-AST 1.85))] ["( Gq % OA / ew )" (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Gq") (rpn.ast/symbol-AST "OA")) (rpn.ast/symbol-AST "ew"))] ["dO * ( 0.16 max 1.21 % QF ^ qa ) / BS" (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "dO") (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/number-AST 0.16) (rpn.ast/number-AST 1.21)) (rpn.ast/symbol-AST "QF")) (rpn.ast/symbol-AST "qa"))) (rpn.ast/symbol-AST "BS"))] ["wX - 0.77" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "wX") (rpn.ast/number-AST 0.77))] ["( ( Ay * ( 0.50 ) max BA ^ ( 1.80 ) ) - 0.64 ) * ( Ui / 1.69 - xC ) % ( UN + 1.70 min 0.02 min JR ) / 1.85" (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Ay") (rpn.ast/max-AST (rpn.ast/number-AST 0.5) (rpn.ast/symbol-AST "BA"))) (rpn.ast/number-AST 1.8)) (rpn.ast/number-AST 0.64)) (rpn.ast/subtract-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "Ui") (rpn.ast/number-AST 1.69)) (rpn.ast/symbol-AST "xC"))) (rpn.ast/add-AST (rpn.ast/symbol-AST "UN") (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.7) (rpn.ast/number-AST 0.02)) (rpn.ast/symbol-AST "JR")))) (rpn.ast/number-AST 1.85))] ["( it max FE / 0.73 - ( 0.33 % ( 0.15 * ( ( ( 0.01 max 1.21 + Bq % 1.69 ) - Ve ) - ( nY max 0.17 + vz / ( QC ) ) ) ) / ( 0.47 % 1.57 + ( 1.01 - 0.21 ) ) ) ) + 1.55 ^ ( 1.54 max SF + fB + ( ( ym ) ) ) - ln" (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/divide-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "it") (rpn.ast/symbol-AST "FE")) (rpn.ast/number-AST 0.73)) (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.33) (rpn.ast/multiply-AST (rpn.ast/number-AST 0.15) (rpn.ast/subtract-AST (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 0.01) (rpn.ast/number-AST 1.21)) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Bq") (rpn.ast/number-AST 1.69))) (rpn.ast/symbol-AST "Ve")) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "nY") (rpn.ast/number-AST 0.17)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "vz") (rpn.ast/symbol-AST "QC")))))) (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.47) (rpn.ast/number-AST 1.57)) (rpn.ast/subtract-AST (rpn.ast/number-AST 1.01) (rpn.ast/number-AST 0.21))))) (rpn.ast/power-AST (rpn.ast/number-AST 1.55) (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.54) (rpn.ast/symbol-AST "SF")) (rpn.ast/symbol-AST "fB")) (rpn.ast/symbol-AST "ym")))) (rpn.ast/symbol-AST "ln"))] ["0.90" (rpn.ast/number-AST 0.9)] ["OP" (rpn.ast/symbol-AST "OP")] ["0.38 / ( rU / uh % 0.25 )" (rpn.ast/divide-AST (rpn.ast/number-AST 0.38) (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "rU") (rpn.ast/symbol-AST "uh")) (rpn.ast/number-AST 0.25)))] ["( uz )" (rpn.ast/symbol-AST "uz")] ["vF ^ ( jw ) / kR" (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "vF") (rpn.ast/symbol-AST "jw")) (rpn.ast/symbol-AST "kR"))] ["gk" (rpn.ast/symbol-AST "gk")] ["( ( BU ) max ( lo ^ VY ) * ( ( ( 1.94 % 0.62 % ( 0.51 % Qy max ( ( Ag ^ wh - 0.19 ) ) min ( ( gP ^ ( 1.96 ) ) min Ur ) ) ) + ( 0.61 % ( HZ ) * ( 0.56 min dr ^ 0.64 ) ) ) * cu max OU min 1.62 ) + 1.74 )" (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "BU") (rpn.ast/power-AST (rpn.ast/symbol-AST "lo") (rpn.ast/symbol-AST "VY"))) (rpn.ast/multiply-AST (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.94) (rpn.ast/number-AST 0.62)) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.51) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Qy") (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "Ag") (rpn.ast/symbol-AST "wh")) (rpn.ast/number-AST 0.19))) (rpn.ast/min-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "gP") (rpn.ast/number-AST 1.96)) (rpn.ast/symbol-AST "Ur"))))) (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.61) (rpn.ast/symbol-AST "HZ")) (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.56) (rpn.ast/symbol-AST "dr")) (rpn.ast/number-AST 0.64)))) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "cu") (rpn.ast/symbol-AST "OU")) (rpn.ast/number-AST 1.62)))) (rpn.ast/number-AST 1.74))] ["( ft ) / Jh + Gt * AP" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "ft") (rpn.ast/symbol-AST "Jh")) (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Gt") (rpn.ast/symbol-AST "AP")))] ["Zw - CA + Co" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Zw") (rpn.ast/symbol-AST "CA")) (rpn.ast/symbol-AST "Co"))] ["( 1.27 ) - NT" (rpn.ast/subtract-AST (rpn.ast/number-AST 1.27) (rpn.ast/symbol-AST "NT"))] ["FI min KU % ( sQ * 1.84 )" (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "FI") (rpn.ast/symbol-AST "KU")) (rpn.ast/multiply-AST (rpn.ast/symbol-AST "sQ") (rpn.ast/number-AST 1.84)))] ["( 1.73 ) ^ cE / Uv" (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.73) (rpn.ast/symbol-AST "cE")) (rpn.ast/symbol-AST "Uv"))] ["0.98 / 1.19 / ( Wk - lG % ( 1.06 ^ Mv ) % xf ) + HS" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.98) (rpn.ast/number-AST 1.19)) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Wk") (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "lG") (rpn.ast/power-AST (rpn.ast/number-AST 1.06) (rpn.ast/symbol-AST "Mv"))) (rpn.ast/symbol-AST "xf")))) (rpn.ast/symbol-AST "HS"))] ["1.64 % dX" (rpn.ast/modulo-AST (rpn.ast/number-AST 1.64) (rpn.ast/symbol-AST "dX"))] ["( 1.04 max HD % nU )" (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.04) (rpn.ast/symbol-AST "HD")) (rpn.ast/symbol-AST "nU"))] ["0.39" (rpn.ast/number-AST 0.39)] ["1.15 - KG + 0.85 % ( ( 1.71 ^ 0.43 min uL min 0.73 ) / ( ( Mo ) - lJ % ( ( ( ( 1.20 % ip ) - ( au ) ) - 1.29 max AS max 1.21 ) ^ 1.02 ) ) - pQ )" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.15) (rpn.ast/symbol-AST "KG")) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.85) (rpn.ast/subtract-AST (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.71) (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.43) (rpn.ast/symbol-AST "uL")) (rpn.ast/number-AST 0.73))) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Mo") (rpn.ast/modulo-AST (rpn.ast/symbol-AST "lJ") (rpn.ast/power-AST (rpn.ast/subtract-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.2) (rpn.ast/symbol-AST "ip")) (rpn.ast/symbol-AST "au")) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.29) (rpn.ast/symbol-AST "AS")) (rpn.ast/number-AST 1.21))) (rpn.ast/number-AST 1.02))))) (rpn.ast/symbol-AST "pQ"))))] ["( ( ( dp - 0.16 / 1.23 ) - 1.54 min 0.82 % ( wI % uP ) ) )" (rpn.ast/subtract-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "dp") (rpn.ast/divide-AST (rpn.ast/number-AST 0.16) (rpn.ast/number-AST 1.23))) (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.54) (rpn.ast/number-AST 0.82)) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "wI") (rpn.ast/symbol-AST "uP"))))] ["( 1.15 max 1.04 + 1.15 ) - 1.86" (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.15) (rpn.ast/number-AST 1.04)) (rpn.ast/number-AST 1.15)) (rpn.ast/number-AST 1.86))] ["1.44 / 0.68" (rpn.ast/divide-AST (rpn.ast/number-AST 1.44) (rpn.ast/number-AST 0.68))] ["wO % NV" (rpn.ast/modulo-AST (rpn.ast/symbol-AST "wO") (rpn.ast/symbol-AST "NV"))] ["Wp * ys min 0.46 + ( ( ( ( 1.32 ^ Bw ) max 1.70 - ( ( KL min ( ( 1.23 / ( 1.92 ) / ( 0.30 ) % ( zq + bj ) ) - ( ( hO * Bz % ( Iv + ( ( YE ) % rI - 1.24 ) ) ) min IA ) % ( lO max ( ( nE ^ Mu + 1.53 ) - kl min 1.31 min hb ) * oX % ( ( 0.74 % 0.80 - aC ) ) ) ) * 1.06 ) ) min 1.68 ) / ( 0.83 - 1.71 * 0.45 ) max 0.84 min ( ( ( 1.30 % 1.50 - kb ) min 0.95 / ( 0.21 % hg ) ) max 0.20 ) ) / ( ( ( 1.83 * Ks - 0.29 ) * Ua % 1.92 % ( ( 0.24 + dL / Fn ) ) ) max 1.00 % 0.14 ) + 1.12 )" (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Wp") (rpn.ast/min-AST (rpn.ast/symbol-AST "ys") (rpn.ast/number-AST 0.46))) (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/subtract-AST (rpn.ast/max-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.32) (rpn.ast/symbol-AST "Bw")) (rpn.ast/number-AST 1.7)) (rpn.ast/min-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "KL") (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.23) (rpn.ast/number-AST 1.92)) (rpn.ast/number-AST 0.3)) (rpn.ast/add-AST (rpn.ast/symbol-AST "zq") (rpn.ast/symbol-AST "bj"))) (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "hO") (rpn.ast/symbol-AST "Bz")) (rpn.ast/add-AST (rpn.ast/symbol-AST "Iv") (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "YE") (rpn.ast/symbol-AST "rI")) (rpn.ast/number-AST 1.24)))) (rpn.ast/symbol-AST "IA")) (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "lO") (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "nE") (rpn.ast/symbol-AST "Mu")) (rpn.ast/number-AST 1.53)) (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "kl") (rpn.ast/number-AST 1.31)) (rpn.ast/symbol-AST "hb")))) (rpn.ast/symbol-AST "oX")) (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.74) (rpn.ast/number-AST 0.8)) (rpn.ast/symbol-AST "aC")))))) (rpn.ast/number-AST 1.06)) (rpn.ast/number-AST 1.68))) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 0.83) (rpn.ast/multiply-AST (rpn.ast/number-AST 1.71) (rpn.ast/number-AST 0.45))) (rpn.ast/number-AST 0.84)) (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.3) (rpn.ast/number-AST 1.5)) (rpn.ast/symbol-AST "kb")) (rpn.ast/number-AST 0.95)) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.21) (rpn.ast/symbol-AST "hg"))) (rpn.ast/number-AST 0.2)))) (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.83) (rpn.ast/symbol-AST "Ks")) (rpn.ast/number-AST 0.29)) (rpn.ast/symbol-AST "Ua")) (rpn.ast/number-AST 1.92)) (rpn.ast/add-AST (rpn.ast/number-AST 0.24) (rpn.ast/divide-AST (rpn.ast/symbol-AST "dL") (rpn.ast/symbol-AST "Fn")))) (rpn.ast/number-AST 1.0)) (rpn.ast/number-AST 0.14))) (rpn.ast/number-AST 1.12)))] ["JB" (rpn.ast/symbol-AST "JB")] ["aY" (rpn.ast/symbol-AST "aY")] ["0.92 * ( FX ) / Ml / ( 0.89 % ( Or max wM ) max 0.01 )" (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.92) (rpn.ast/symbol-AST "FX")) (rpn.ast/symbol-AST "Ml")) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.89) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Or") (rpn.ast/symbol-AST "wM")) (rpn.ast/number-AST 0.01))))] ["( tL + 1.37 ) + ( ( Pw + 0.87 - ( uC * Bb * no min ( 1.88 ^ ( 1.09 max ( ( 0.15 min ( 0.80 ) ^ uM max 1.99 ) * ( 0.17 ^ 0.54 min 0.24 + 0.27 ) - Ee * dd ) + 1.52 ^ vG ) + ( ( ( ( uU / tD ) * ( HT ^ 1.62 % cR - 0.14 ) ) min Ie / 1.84 ) * Zf % jO ) ) ) ) ) + ( CT min la * LH )" (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "tL") (rpn.ast/number-AST 1.37)) (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "Pw") (rpn.ast/number-AST 0.87)) (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "uC") (rpn.ast/symbol-AST "Bb")) (rpn.ast/min-AST (rpn.ast/symbol-AST "no") (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.88) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.09) (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.15) (rpn.ast/number-AST 0.8)) (rpn.ast/max-AST (rpn.ast/symbol-AST "uM") (rpn.ast/number-AST 1.99))) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/number-AST 0.17) (rpn.ast/min-AST (rpn.ast/number-AST 0.54) (rpn.ast/number-AST 0.24))) (rpn.ast/number-AST 0.27))) (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Ee") (rpn.ast/symbol-AST "dd")))) (rpn.ast/power-AST (rpn.ast/number-AST 1.52) (rpn.ast/symbol-AST "vG")))) (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "uU") (rpn.ast/symbol-AST "tD")) (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "HT") (rpn.ast/number-AST 1.62)) (rpn.ast/symbol-AST "cR")) (rpn.ast/number-AST 0.14))) (rpn.ast/symbol-AST "Ie")) (rpn.ast/number-AST 1.84)) (rpn.ast/symbol-AST "Zf")) (rpn.ast/symbol-AST "jO"))))))) (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "CT") (rpn.ast/symbol-AST "la")) (rpn.ast/symbol-AST "LH")))] ["Jo % Qs" (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Jo") (rpn.ast/symbol-AST "Qs"))] ["1.80 - ( Wj - 1.70 + ( TE / ( qi min ( ( sP / ( ( DM ) - 1.28 ) * 0.45 % 1.00 ) max 1.74 / 0.83 ^ ( ( ( ( 1.09 - ( ( ( ( ( 0.45 + tL + 1.20 ) ) ) + 1.30 * TC / ( ( ( ( Se ) - ( 1.19 ) ) ^ FQ / HI ^ 0.31 ) + 0.94 ) ) % Ih * 1.35 ^ ( 1.59 % 0.40 max ( ( 1.67 max bk ) max ( 0.24 % ( GF + 1.17 % qa ^ 1.28 ) ^ ( NY ^ 0.11 % ( Bg - 1.20 ) ) ) ) ) ) / Ia % ( ( 1.77 min gB / ( ( ( ( ( ov ) / 0.45 / LF - 1.50 ) min 0.57 ) min Tq ^ 0.68 ) ) ) max hd ) ) % 0.34 ^ ( 1.96 ) ) + 0.31 ) ) ) - tQ ^ XB ) ) ) ^ 0.40 + ( ( 0.30 / ( 0.66 max in + 1.90 ) * ( 1.99 / Sl % 1.62 ) / 0.47 ) ^ mc - 1.82 + 0.22 )" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.8) (rpn.ast/power-AST (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Wj") (rpn.ast/number-AST 1.7)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "TE") (rpn.ast/subtract-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "qi") (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/max-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "sP") (rpn.ast/subtract-AST (rpn.ast/symbol-AST "DM") (rpn.ast/number-AST 1.28))) (rpn.ast/number-AST 0.45)) (rpn.ast/number-AST 1.0)) (rpn.ast/number-AST 1.74)) (rpn.ast/number-AST 0.83)) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.09) (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/number-AST 0.45) (rpn.ast/symbol-AST "tL")) (rpn.ast/number-AST 1.2)) (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.3) (rpn.ast/symbol-AST "TC")) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Se") (rpn.ast/number-AST 1.19)) (rpn.ast/symbol-AST "FQ")) (rpn.ast/symbol-AST "HI")) (rpn.ast/number-AST 0.31)) (rpn.ast/number-AST 0.94)))) (rpn.ast/symbol-AST "Ih")) (rpn.ast/number-AST 1.35)) (rpn.ast/modulo-AST (rpn.ast/number-AST 1.59) (rpn.ast/max-AST (rpn.ast/number-AST 0.4) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.67) (rpn.ast/symbol-AST "bk")) (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.24) (rpn.ast/add-AST (rpn.ast/symbol-AST "GF") (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.17) (rpn.ast/symbol-AST "qa")) (rpn.ast/number-AST 1.28)))) (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "NY") (rpn.ast/number-AST 0.11)) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Bg") (rpn.ast/number-AST 1.2)))))))) (rpn.ast/symbol-AST "Ia")) (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.77) (rpn.ast/symbol-AST "gB")) (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "ov") (rpn.ast/number-AST 0.45)) (rpn.ast/symbol-AST "LF")) (rpn.ast/number-AST 1.5)) (rpn.ast/number-AST 0.57)) (rpn.ast/symbol-AST "Tq")) (rpn.ast/number-AST 0.68))) (rpn.ast/symbol-AST "hd")))) (rpn.ast/number-AST 0.34)) (rpn.ast/number-AST 1.96)) (rpn.ast/number-AST 0.31)))) (rpn.ast/power-AST (rpn.ast/symbol-AST "tQ") (rpn.ast/symbol-AST "XB"))))) (rpn.ast/number-AST 0.4))) (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.3) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 0.66) (rpn.ast/symbol-AST "in")) (rpn.ast/number-AST 1.9))) (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.99) (rpn.ast/symbol-AST "Sl")) (rpn.ast/number-AST 1.62))) (rpn.ast/number-AST 0.47)) (rpn.ast/symbol-AST "mc")) (rpn.ast/number-AST 1.82)) (rpn.ast/number-AST 0.22)))] ["( 1.23 * HT min 1.16 ) - Oc + 1.44" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.23) (rpn.ast/min-AST (rpn.ast/symbol-AST "HT") (rpn.ast/number-AST 1.16))) (rpn.ast/symbol-AST "Oc")) (rpn.ast/number-AST 1.44))] ["( 1.99 )" (rpn.ast/number-AST 1.99)] ["Zu" (rpn.ast/symbol-AST "Zu")] ["0.53" (rpn.ast/number-AST 0.53)] ["Nc - PW" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Nc") (rpn.ast/symbol-AST "PW"))] ["kl * ww - YI" (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "kl") (rpn.ast/symbol-AST "ww")) (rpn.ast/symbol-AST "YI"))] ["1.93 max 1.41 ^ ( ( ( 0.90 % ( 1.40 / 0.79 ^ 0.76 min vt ) ) - ( 0.96 ^ 0.18 ) ) / nl / ( cn % 1.22 ) )" (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.93) (rpn.ast/number-AST 1.41)) (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.9) (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.4) (rpn.ast/number-AST 0.79)) (rpn.ast/min-AST (rpn.ast/number-AST 0.76) (rpn.ast/symbol-AST "vt")))) (rpn.ast/power-AST (rpn.ast/number-AST 0.96) (rpn.ast/number-AST 0.18))) (rpn.ast/symbol-AST "nl")) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "cn") (rpn.ast/number-AST 1.22))))] ["wo / 0.35 + WT / oj" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "wo") (rpn.ast/number-AST 0.35)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "WT") (rpn.ast/symbol-AST "oj")))] ["( 1.42 % mL ) % iF max rI % ( Gb )" (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.42) (rpn.ast/symbol-AST "mL")) (rpn.ast/max-AST (rpn.ast/symbol-AST "iF") (rpn.ast/symbol-AST "rI"))) (rpn.ast/symbol-AST "Gb"))] ["0.08 ^ KU max 2.00" (rpn.ast/power-AST (rpn.ast/number-AST 0.08) (rpn.ast/max-AST (rpn.ast/symbol-AST "KU") (rpn.ast/number-AST 2.0)))] ["0.33 % 0.51 * 0.42" (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.33) (rpn.ast/number-AST 0.51)) (rpn.ast/number-AST 0.42))] ["rj % rw min ( Et )" (rpn.ast/modulo-AST (rpn.ast/symbol-AST "rj") (rpn.ast/min-AST (rpn.ast/symbol-AST "rw") (rpn.ast/symbol-AST "Et")))] ["( 1.17 ^ 1.70 ) % 0.60 - 1.33" (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.17) (rpn.ast/number-AST 1.7)) (rpn.ast/number-AST 0.6)) (rpn.ast/number-AST 1.33))] ["tp min 0.60" (rpn.ast/min-AST (rpn.ast/symbol-AST "tp") (rpn.ast/number-AST 0.6))] ["Zy" (rpn.ast/symbol-AST "Zy")] ["pT min qW ^ Ul" (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "pT") (rpn.ast/symbol-AST "qW")) (rpn.ast/symbol-AST "Ul"))] ["( 1.36 ^ ET ) ^ Uz" (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.36) (rpn.ast/symbol-AST "ET")) (rpn.ast/symbol-AST "Uz"))] ["( ( 0.16 - 0.44 / LC ) ) ^ vE" (rpn.ast/power-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 0.16) (rpn.ast/divide-AST (rpn.ast/number-AST 0.44) (rpn.ast/symbol-AST "LC"))) (rpn.ast/symbol-AST "vE"))] ["Es min Fl ^ 0.78 ^ 0.60" (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "Es") (rpn.ast/symbol-AST "Fl")) (rpn.ast/number-AST 0.78)) (rpn.ast/number-AST 0.6))] ["1.50" (rpn.ast/number-AST 1.5)] ["Tn + ( 0.64 ) min 0.62" (rpn.ast/add-AST (rpn.ast/symbol-AST "Tn") (rpn.ast/min-AST (rpn.ast/number-AST 0.64) (rpn.ast/number-AST 0.62)))] ["Pf" (rpn.ast/symbol-AST "Pf")] ["( ( ( 1.40 ) - ( 1.75 ) max Vq ) * ( UL * 1.74 min ( FP min mV max PQ ) ) / NJ + 1.61 ) / 0.72 % 0.34 max fQ" (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.4) (rpn.ast/max-AST (rpn.ast/number-AST 1.75) (rpn.ast/symbol-AST "Vq"))) (rpn.ast/multiply-AST (rpn.ast/symbol-AST "UL") (rpn.ast/min-AST (rpn.ast/number-AST 1.74) (rpn.ast/max-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "FP") (rpn.ast/symbol-AST "mV")) (rpn.ast/symbol-AST "PQ"))))) (rpn.ast/symbol-AST "NJ")) (rpn.ast/number-AST 1.61)) (rpn.ast/number-AST 0.72)) (rpn.ast/max-AST (rpn.ast/number-AST 0.34) (rpn.ast/symbol-AST "fQ")))] ["( 0.42 * ( 0.23 ^ ( fK min bR - ii % ( 1.80 / 1.83 ) ) ) )" (rpn.ast/multiply-AST (rpn.ast/number-AST 0.42) (rpn.ast/power-AST (rpn.ast/number-AST 0.23) (rpn.ast/subtract-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "fK") (rpn.ast/symbol-AST "bR")) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "ii") (rpn.ast/divide-AST (rpn.ast/number-AST 1.8) (rpn.ast/number-AST 1.83))))))] ["( 1.82 / 1.28 ) max ( Hj - 1.41 )" (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.82) (rpn.ast/number-AST 1.28)) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Hj") (rpn.ast/number-AST 1.41)))] ["0.07 % 1.08 * 1.14" (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.07) (rpn.ast/number-AST 1.08)) (rpn.ast/number-AST 1.14))] ["Nt % ( 0.11 ^ LM ) * Pj" (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Nt") (rpn.ast/power-AST (rpn.ast/number-AST 0.11) (rpn.ast/symbol-AST "LM"))) (rpn.ast/symbol-AST "Pj"))] ["dD - ( ( 1.93 + ( 1.19 % ZV ^ ( 1.43 * nV * mK ) ) ^ 1.09 ) + ( 0.62 ) % ( ( 1.69 / 1.52 max tJ ) + ( 0.62 ) ) - ( 1.77 / 1.64 max ND min qK ) ) / 1.28 min rN" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "dD") (rpn.ast/divide-AST (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.93) (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.19) (rpn.ast/symbol-AST "ZV")) (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.43) (rpn.ast/symbol-AST "nV")) (rpn.ast/symbol-AST "mK"))) (rpn.ast/number-AST 1.09))) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.62) (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.69) (rpn.ast/max-AST (rpn.ast/number-AST 1.52) (rpn.ast/symbol-AST "tJ"))) (rpn.ast/number-AST 0.62)))) (rpn.ast/divide-AST (rpn.ast/number-AST 1.77) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.64) (rpn.ast/symbol-AST "ND")) (rpn.ast/symbol-AST "qK")))) (rpn.ast/min-AST (rpn.ast/number-AST 1.28) (rpn.ast/symbol-AST "rN"))))] ["lu" (rpn.ast/symbol-AST "lu")] ["( 0.79 )" (rpn.ast/number-AST 0.79)] ["( ( ( 1.01 ) + 1.63 % Wg / no ) * lY )" (rpn.ast/multiply-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.01) (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.63) (rpn.ast/symbol-AST "Wg")) (rpn.ast/symbol-AST "no"))) (rpn.ast/symbol-AST "lY"))] ["( ( Rq ) ) ^ 1.64" (rpn.ast/power-AST (rpn.ast/symbol-AST "Rq") (rpn.ast/number-AST 1.64))] ["1.61" (rpn.ast/number-AST 1.61)] ["1.74 * 0.16 * ( 1.96 ^ 0.58 % 0.85 * oc ) / ( 0.52 )" (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.74) (rpn.ast/number-AST 0.16)) (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.96) (rpn.ast/number-AST 0.58)) (rpn.ast/number-AST 0.85)) (rpn.ast/symbol-AST "oc"))) (rpn.ast/number-AST 0.52))] ["0.22" (rpn.ast/number-AST 0.22)]))
48222
;;; ;;; Copyright 2020 <NAME> ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. ;;; (ns rpn.parser-test (:require [clojure.test :as test]) (:require [rpn.expressions :as expr]) (:require [rpn.lexer :as lexer]) (:require [rpn.parser :as parser])) (declare parser-tests) (test/deftest valid-randomized-expressions (doseq [[e ast] parser-tests] (test/is (= (parser/parser (lexer/lexer e)) ast)))) (test/deftest invalid-expressions (doseq [e ["" " " "a +" "+ a" "a 1" "(a + 1" "a + 1)" "(a + 1))" ")a" "()" "a + * 1" "a $ 1" "(a + 1)(b + 2)"]] (test/is (thrown? Exception (doall (parser/parser (lexer/lexer e))))))) (def ^:private parser-tests (list ["( 0.39 * ( 0.57 ) min 0.13 ) max 1.78 min 1.64 max ( nT ^ ( 0.47 % ( ( jQ max qh ^ PK % 1.01 ) ^ 1.24 max 0.50 max ( ( VU ^ 0.57 ) + qx ) ) - ( 1.71 ) max gx ) )" (rpn.ast/max-AST (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.39) (rpn.ast/min-AST (rpn.ast/number-AST 0.57) (rpn.ast/number-AST 0.13))) (rpn.ast/number-AST 1.78)) (rpn.ast/number-AST 1.64)) (rpn.ast/power-AST (rpn.ast/symbol-AST "nT") (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.47) (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "jQ") (rpn.ast/symbol-AST "qh")) (rpn.ast/symbol-AST "PK")) (rpn.ast/number-AST 1.01)) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.24) (rpn.ast/number-AST 0.5)) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "VU") (rpn.ast/number-AST 0.57)) (rpn.ast/symbol-AST "qx"))))) (rpn.ast/max-AST (rpn.ast/number-AST 1.71) (rpn.ast/symbol-AST "gx")))))] ["0.23 / XT + 0.08" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.23) (rpn.ast/symbol-AST "XT")) (rpn.ast/number-AST 0.08))] ["TM" (rpn.ast/symbol-AST "TM")] ["DM * ( RL ) / ( ( ( 1.30 min JJ * ( 1.02 max ( 0.61 * GQ / 0.64 ) max ( ( 1.45 ) * AB ^ ( ( ( 1.75 + 1.79 * ( tO + Lp max us min 1.67 ) ) * ( 0.10 min 0.32 ) min ( 0.01 ) ) * ( ( 1.73 ) ) - 0.16 ) * 0.85 ) ) ) % ( gY max oQ / ( 0.96 % 1.02 - 0.17 ) ) min gS * 1.05 ) ^ wW ) max ( ea min ( ( ( ( ( Ps ) ) / xr ) ) max 1.37 max 0.31 ) )" (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "DM") (rpn.ast/symbol-AST "RL")) (rpn.ast/max-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.3) (rpn.ast/symbol-AST "JJ")) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.02) (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.61) (rpn.ast/symbol-AST "GQ")) (rpn.ast/number-AST 0.64))) (rpn.ast/multiply-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.45) (rpn.ast/symbol-AST "AB")) (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.75) (rpn.ast/multiply-AST (rpn.ast/number-AST 1.79) (rpn.ast/add-AST (rpn.ast/symbol-AST "tO") (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Lp") (rpn.ast/symbol-AST "us")) (rpn.ast/number-AST 1.67))))) (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.1) (rpn.ast/number-AST 0.32)) (rpn.ast/number-AST 0.01))) (rpn.ast/number-AST 1.73)) (rpn.ast/number-AST 0.16))) (rpn.ast/number-AST 0.85)))) (rpn.ast/min-AST (rpn.ast/divide-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "gY") (rpn.ast/symbol-AST "oQ")) (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.96) (rpn.ast/number-AST 1.02)) (rpn.ast/number-AST 0.17))) (rpn.ast/symbol-AST "gS"))) (rpn.ast/number-AST 1.05)) (rpn.ast/symbol-AST "wW")) (rpn.ast/min-AST (rpn.ast/symbol-AST "ea") (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "Ps") (rpn.ast/symbol-AST "xr")) (rpn.ast/number-AST 1.37)) (rpn.ast/number-AST 0.31)))))] ["0.56 - ( ( ( ( ( ( ( 1.66 ) min 1.58 ) * ( 1.54 + ( 1.63 * ( Qu % qD % 0.34 ) ^ 1.48 + oY ) ) * ( 1.64 ^ 1.95 ^ ( 0.19 ^ ( lk max 1.48 ) ) ) ) max Ue + 0.46 ^ 1.67 ) % FT / Ni min ( Ls / zq + ( 0.07 / ( 0.17 ) min ( 0.25 ) ) ) ) max lY ) min ( Vv max 1.23 ) ) % rr" (rpn.ast/subtract-AST (rpn.ast/number-AST 0.56) (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.66) (rpn.ast/number-AST 1.58)) (rpn.ast/add-AST (rpn.ast/number-AST 1.54) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.63) (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Qu") (rpn.ast/symbol-AST "qD")) (rpn.ast/number-AST 0.34))) (rpn.ast/number-AST 1.48)) (rpn.ast/symbol-AST "oY")))) (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.64) (rpn.ast/number-AST 1.95)) (rpn.ast/power-AST (rpn.ast/number-AST 0.19) (rpn.ast/max-AST (rpn.ast/symbol-AST "lk") (rpn.ast/number-AST 1.48))))) (rpn.ast/symbol-AST "Ue")) (rpn.ast/power-AST (rpn.ast/number-AST 0.46) (rpn.ast/number-AST 1.67))) (rpn.ast/symbol-AST "FT")) (rpn.ast/min-AST (rpn.ast/symbol-AST "Ni") (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "Ls") (rpn.ast/symbol-AST "zq")) (rpn.ast/divide-AST (rpn.ast/number-AST 0.07) (rpn.ast/min-AST (rpn.ast/number-AST 0.17) (rpn.ast/number-AST 0.25)))))) (rpn.ast/symbol-AST "lY")) (rpn.ast/max-AST (rpn.ast/symbol-AST "Vv") (rpn.ast/number-AST 1.23))) (rpn.ast/symbol-AST "rr")))] ["0.78 ^ ( xm max 0.85 + mJ )" (rpn.ast/power-AST (rpn.ast/number-AST 0.78) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "xm") (rpn.ast/number-AST 0.85)) (rpn.ast/symbol-AST "mJ")))] ["xD * Iu" (rpn.ast/multiply-AST (rpn.ast/symbol-AST "xD") (rpn.ast/symbol-AST "Iu"))] ["dG * Xx / di" (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "dG") (rpn.ast/symbol-AST "Xx")) (rpn.ast/symbol-AST "di"))] ["Ur max TC - 0.10" (rpn.ast/subtract-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Ur") (rpn.ast/symbol-AST "TC")) (rpn.ast/number-AST 0.1))] ["( 1.30 ^ ( ( 1.01 min 1.95 min 1.15 ) * lp + kT ) ) % ( ( ( 0.91 ) ) - hv max ( Wu ) * 0.23 ) * 0.18" (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.3) (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.01) (rpn.ast/number-AST 1.95)) (rpn.ast/number-AST 1.15)) (rpn.ast/symbol-AST "lp")) (rpn.ast/symbol-AST "kT"))) (rpn.ast/subtract-AST (rpn.ast/number-AST 0.91) (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "hv") (rpn.ast/symbol-AST "Wu")) (rpn.ast/number-AST 0.23)))) (rpn.ast/number-AST 0.18))] ["YN - dl" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "YN") (rpn.ast/symbol-AST "dl"))] ["( Uv )" (rpn.ast/symbol-AST "Uv")] ["1.20 - ea min 1.61" (rpn.ast/subtract-AST (rpn.ast/number-AST 1.2) (rpn.ast/min-AST (rpn.ast/symbol-AST "ea") (rpn.ast/number-AST 1.61)))] ["xN * 0.06" (rpn.ast/multiply-AST (rpn.ast/symbol-AST "xN") (rpn.ast/number-AST 0.06))] ["LE ^ tg max nZ ^ XY" (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "LE") (rpn.ast/max-AST (rpn.ast/symbol-AST "tg") (rpn.ast/symbol-AST "nZ"))) (rpn.ast/symbol-AST "XY"))] ["( ( ( ( Dx ^ 0.48 ) % ( ( ZE ^ Fq - 1.64 % ( ya / Ea % 1.67 + ( 1.73 % fN ) ) ) ) min 0.26 ) max ( JI - ( ( Dq max ( 1.68 max UZ * HZ * 0.08 ) % 1.13 - 1.67 ) ) ) ) min ( 0.01 ) / aD * 0.61 )" (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "Dx") (rpn.ast/number-AST 0.48)) (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "ZE") (rpn.ast/symbol-AST "Fq")) (rpn.ast/modulo-AST (rpn.ast/number-AST 1.64) (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "ya") (rpn.ast/symbol-AST "Ea")) (rpn.ast/number-AST 1.67)) (rpn.ast/modulo-AST (rpn.ast/number-AST 1.73) (rpn.ast/symbol-AST "fN"))))) (rpn.ast/number-AST 0.26))) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "JI") (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Dq") (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.68) (rpn.ast/symbol-AST "UZ")) (rpn.ast/symbol-AST "HZ")) (rpn.ast/number-AST 0.08))) (rpn.ast/number-AST 1.13)) (rpn.ast/number-AST 1.67)))) (rpn.ast/number-AST 0.01)) (rpn.ast/symbol-AST "aD")) (rpn.ast/number-AST 0.61))] ["( ( ( ( ( ( ( 1.25 + 1.18 - ( ( ( 0.60 ) * ( ( 1.23 min yT * Xf ) / iA ) ) * JG + XB max Ma ) ) min ( 1.42 ) max ( ( 0.05 - ( Bb / so ) ) ) ) ) * gk ) ^ 0.09 max mq ) min gj ) % ( EA * uk min 0.77 ^ CY ) min ( ( Fi min 0.62 ) * 0.41 ) ^ 0.62 )" (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.25) (rpn.ast/number-AST 1.18)) (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.6) (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.23) (rpn.ast/symbol-AST "yT")) (rpn.ast/symbol-AST "Xf")) (rpn.ast/symbol-AST "iA"))) (rpn.ast/symbol-AST "JG")) (rpn.ast/max-AST (rpn.ast/symbol-AST "XB") (rpn.ast/symbol-AST "Ma")))) (rpn.ast/number-AST 1.42)) (rpn.ast/subtract-AST (rpn.ast/number-AST 0.05) (rpn.ast/divide-AST (rpn.ast/symbol-AST "Bb") (rpn.ast/symbol-AST "so")))) (rpn.ast/symbol-AST "gk")) (rpn.ast/max-AST (rpn.ast/number-AST 0.09) (rpn.ast/symbol-AST "mq"))) (rpn.ast/symbol-AST "gj")) (rpn.ast/min-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "EA") (rpn.ast/min-AST (rpn.ast/symbol-AST "uk") (rpn.ast/number-AST 0.77))) (rpn.ast/symbol-AST "CY")) (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "Fi") (rpn.ast/number-AST 0.62)) (rpn.ast/number-AST 0.41)))) (rpn.ast/number-AST 0.62))] ["aF * 1.36 max ( Gc * ( ( ( uv ) * 1.22 + 0.05 + ( ( 0.86 * ( ( 1.74 % 0.25 % 1.80 min ( CR ) ) max ( 0.26 / 1.36 * ( ( ( aO + 0.43 + bu min EX ) % ( ( 0.89 ) max LG ^ xe max We ) ) ^ ( ( 1.74 min 1.60 ) + Ut / ( ( KL * ( ( ( ( KZ ) ) ) / ( dp ^ 0.13 - 1.60 ) ) * ( ( ( oT ) % yz / 0.74 % KQ ) * 1.47 % 0.56 ) ) ) ) / ( 0.93 + 0.56 % ( ( cc % HE max cO ) ) * ( 1.18 + ( XA % hW ) - ( QT ) ) ) min 1.70 ) ) % ( st + 1.30 ) + 1.52 ) ) min ( OJ + 0.26 / sq max 1.09 ) min 1.16 ) ) ^ Xh ) ^ pR / kf )" (rpn.ast/multiply-AST (rpn.ast/symbol-AST "aF") (rpn.ast/max-AST (rpn.ast/number-AST 1.36) (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Gc") (rpn.ast/power-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "uv") (rpn.ast/number-AST 1.22)) (rpn.ast/number-AST 0.05)) (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.86) (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.74) (rpn.ast/number-AST 0.25)) (rpn.ast/min-AST (rpn.ast/number-AST 1.8) (rpn.ast/symbol-AST "CR"))) (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.26) (rpn.ast/number-AST 1.36)) (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "aO") (rpn.ast/number-AST 0.43)) (rpn.ast/min-AST (rpn.ast/symbol-AST "bu") (rpn.ast/symbol-AST "EX"))) (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/number-AST 0.89) (rpn.ast/symbol-AST "LG")) (rpn.ast/max-AST (rpn.ast/symbol-AST "xe") (rpn.ast/symbol-AST "We")))) (rpn.ast/add-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.74) (rpn.ast/number-AST 1.6)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "Ut") (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "KL") (rpn.ast/divide-AST (rpn.ast/symbol-AST "KZ") (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "dp") (rpn.ast/number-AST 0.13)) (rpn.ast/number-AST 1.6)))) (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "oT") (rpn.ast/symbol-AST "yz")) (rpn.ast/number-AST 0.74)) (rpn.ast/symbol-AST "KQ")) (rpn.ast/number-AST 1.47)) (rpn.ast/number-AST 0.56)))))) (rpn.ast/min-AST (rpn.ast/add-AST (rpn.ast/number-AST 0.93) (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.56) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "cc") (rpn.ast/max-AST (rpn.ast/symbol-AST "HE") (rpn.ast/symbol-AST "cO")))) (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.18) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "XA") (rpn.ast/symbol-AST "hW"))) (rpn.ast/symbol-AST "QT")))) (rpn.ast/number-AST 1.7))))) (rpn.ast/add-AST (rpn.ast/symbol-AST "st") (rpn.ast/number-AST 1.3))) (rpn.ast/number-AST 1.52))) (rpn.ast/add-AST (rpn.ast/symbol-AST "OJ") (rpn.ast/divide-AST (rpn.ast/number-AST 0.26) (rpn.ast/max-AST (rpn.ast/symbol-AST "sq") (rpn.ast/number-AST 1.09))))) (rpn.ast/number-AST 1.16))) (rpn.ast/symbol-AST "Xh"))) (rpn.ast/symbol-AST "pR")) (rpn.ast/symbol-AST "kf"))))] ["( ( ( qn ) - 0.72 * ( 1.24 ) max Hj ) + ( ( oe max ( VP / zC + 1.42 ) max 0.08 ^ 0.63 ) ) - ( ( zX % BE min 1.16 ) min ( zI ) ) ) ^ 1.75 max ( ( WZ ) max ( rm / ( BG min Pm / 1.65 ) max ( Ug ^ 0.74 ) ) + nC ) / ( 1.91 min 0.04 ^ 0.54 max ( ( 1.70 max 0.64 min kB / 0.51 ) * ( CU + 1.52 max 0.92 ^ ( ( 1.27 * Ey max ( Vm + vA % ( 1.24 - ( Eu max ( bK min Ny min ( uo min 0.24 - It ) * 1.10 ) ) ) ) ) * 1.94 + eN / 0.88 ) ) max 1.54 ^ 0.67 ) )" (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "qn") (rpn.ast/multiply-AST (rpn.ast/number-AST 0.72) (rpn.ast/max-AST (rpn.ast/number-AST 1.24) (rpn.ast/symbol-AST "Hj")))) (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "oe") (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "VP") (rpn.ast/symbol-AST "zC")) (rpn.ast/number-AST 1.42))) (rpn.ast/number-AST 0.08)) (rpn.ast/number-AST 0.63))) (rpn.ast/min-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "zX") (rpn.ast/min-AST (rpn.ast/symbol-AST "BE") (rpn.ast/number-AST 1.16))) (rpn.ast/symbol-AST "zI"))) (rpn.ast/max-AST (rpn.ast/number-AST 1.75) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "WZ") (rpn.ast/divide-AST (rpn.ast/symbol-AST "rm") (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "BG") (rpn.ast/symbol-AST "Pm")) (rpn.ast/number-AST 1.65)) (rpn.ast/power-AST (rpn.ast/symbol-AST "Ug") (rpn.ast/number-AST 0.74))))) (rpn.ast/symbol-AST "nC")))) (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.91) (rpn.ast/number-AST 0.04)) (rpn.ast/max-AST (rpn.ast/number-AST 0.54) (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.7) (rpn.ast/number-AST 0.64)) (rpn.ast/symbol-AST "kB")) (rpn.ast/number-AST 0.51)) (rpn.ast/max-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "CU") (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.52) (rpn.ast/number-AST 0.92)) (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.27) (rpn.ast/max-AST (rpn.ast/symbol-AST "Ey") (rpn.ast/add-AST (rpn.ast/symbol-AST "Vm") (rpn.ast/modulo-AST (rpn.ast/symbol-AST "vA") (rpn.ast/subtract-AST (rpn.ast/number-AST 1.24) (rpn.ast/max-AST (rpn.ast/symbol-AST "Eu") (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "bK") (rpn.ast/symbol-AST "Ny")) (rpn.ast/subtract-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "uo") (rpn.ast/number-AST 0.24)) (rpn.ast/symbol-AST "It"))) (rpn.ast/number-AST 1.1)))))))) (rpn.ast/number-AST 1.94)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "eN") (rpn.ast/number-AST 0.88))))) (rpn.ast/number-AST 1.54))) (rpn.ast/number-AST 0.67)))))] ["( NU ) - ( ( zL % FE + ( ( 0.80 min ( 1.26 * SP / ( ( 1.47 max 0.15 - NP + ( ( 1.34 - uU ) * 1.91 ) ) ) ) ) ) ^ 0.30 ) + 0.69 * Jw ^ 1.62 )" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "NU") (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "zL") (rpn.ast/symbol-AST "FE")) (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.8) (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.26) (rpn.ast/symbol-AST "SP")) (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.47) (rpn.ast/number-AST 0.15)) (rpn.ast/symbol-AST "NP")) (rpn.ast/multiply-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.34) (rpn.ast/symbol-AST "uU")) (rpn.ast/number-AST 1.91))))) (rpn.ast/number-AST 0.3))) (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.69) (rpn.ast/symbol-AST "Jw")) (rpn.ast/number-AST 1.62))))] ["xH % uU * 1.86 % 0.39" (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "xH") (rpn.ast/symbol-AST "uU")) (rpn.ast/number-AST 1.86)) (rpn.ast/number-AST 0.39))] ["jY" (rpn.ast/symbol-AST "jY")] ["QJ" (rpn.ast/symbol-AST "QJ")] ["( ( 1.92 + nR ) % lr - ( ( 1.94 * 1.34 min AQ ^ 1.98 ) + ( ( ( ( ( ( 1.82 min ( 1.00 + ( Ys - ( eE ^ ( jv + ( 1.52 ) * aO ) ) ^ oz ) ) * ( ( FF ) + tE ) min ( NB / Rz ) ) / 0.76 ) ^ TV max Fu min 0.46 ) * Cr + HR ^ Iv ) max 1.97 % ( ( 1.25 % ( 0.14 ) * ( Kc ) % 0.86 ) - 1.47 + ( ( 1.54 + 1.52 / ( FP - cp max ( 1.66 / zM ) min 1.47 ) * 1.01 ) ^ ( Ow ) min AY ) ) ^ ( ( 0.24 ) % ( ss ) ^ ( cL ^ Bm ) % 1.38 ) ) min 0.01 - 1.12 ) ) max 0.30 ) + ts % 1.72" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.92) (rpn.ast/symbol-AST "nR")) (rpn.ast/symbol-AST "lr")) (rpn.ast/max-AST (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.94) (rpn.ast/min-AST (rpn.ast/number-AST 1.34) (rpn.ast/symbol-AST "AQ"))) (rpn.ast/number-AST 1.98)) (rpn.ast/subtract-AST (rpn.ast/min-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.82) (rpn.ast/add-AST (rpn.ast/number-AST 1.0) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Ys") (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "eE") (rpn.ast/add-AST (rpn.ast/symbol-AST "jv") (rpn.ast/multiply-AST (rpn.ast/number-AST 1.52) (rpn.ast/symbol-AST "aO")))) (rpn.ast/symbol-AST "oz"))))) (rpn.ast/min-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "FF") (rpn.ast/symbol-AST "tE")) (rpn.ast/divide-AST (rpn.ast/symbol-AST "NB") (rpn.ast/symbol-AST "Rz")))) (rpn.ast/number-AST 0.76)) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "TV") (rpn.ast/symbol-AST "Fu")) (rpn.ast/number-AST 0.46))) (rpn.ast/symbol-AST "Cr")) (rpn.ast/power-AST (rpn.ast/symbol-AST "HR") (rpn.ast/symbol-AST "Iv"))) (rpn.ast/number-AST 1.97)) (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.25) (rpn.ast/number-AST 0.14)) (rpn.ast/symbol-AST "Kc")) (rpn.ast/number-AST 0.86)) (rpn.ast/number-AST 1.47)) (rpn.ast/power-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.54) (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.52) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "FP") (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "cp") (rpn.ast/divide-AST (rpn.ast/number-AST 1.66) (rpn.ast/symbol-AST "zM"))) (rpn.ast/number-AST 1.47)))) (rpn.ast/number-AST 1.01))) (rpn.ast/min-AST (rpn.ast/symbol-AST "Ow") (rpn.ast/symbol-AST "AY"))))) (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.24) (rpn.ast/symbol-AST "ss")) (rpn.ast/power-AST (rpn.ast/symbol-AST "cL") (rpn.ast/symbol-AST "Bm"))) (rpn.ast/number-AST 1.38))) (rpn.ast/number-AST 0.01)) (rpn.ast/number-AST 1.12))) (rpn.ast/number-AST 0.3))) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "ts") (rpn.ast/number-AST 1.72)))] ["0.29 ^ ( ( 1.11 / rH + Xa ^ 1.33 ) max oy max 1.45 max Xr ) + ( NL - 1.51 )" (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/number-AST 0.29) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.11) (rpn.ast/symbol-AST "rH")) (rpn.ast/power-AST (rpn.ast/symbol-AST "Xa") (rpn.ast/number-AST 1.33))) (rpn.ast/symbol-AST "oy")) (rpn.ast/number-AST 1.45)) (rpn.ast/symbol-AST "Xr"))) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "NL") (rpn.ast/number-AST 1.51)))] ["0.18 min 0.43 * 0.06" (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.18) (rpn.ast/number-AST 0.43)) (rpn.ast/number-AST 0.06))] ["( ( ( ( wW min to + 0.24 % Uv ) ^ Mg / 1.26 ) ) % ( 1.73 ) - Qr ) / ( HA - Pn - 0.75 ^ VW )" (rpn.ast/divide-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/add-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "wW") (rpn.ast/symbol-AST "to")) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.24) (rpn.ast/symbol-AST "Uv"))) (rpn.ast/symbol-AST "Mg")) (rpn.ast/number-AST 1.26)) (rpn.ast/number-AST 1.73)) (rpn.ast/symbol-AST "Qr")) (rpn.ast/subtract-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "HA") (rpn.ast/symbol-AST "Pn")) (rpn.ast/power-AST (rpn.ast/number-AST 0.75) (rpn.ast/symbol-AST "VW"))))] ["Jj" (rpn.ast/symbol-AST "Jj")] ["MI + ( 1.72 % ( Xj ^ ( 0.97 min 1.05 ^ gA ) % QA max Qq ) ^ zB + 1.46 )" (rpn.ast/add-AST (rpn.ast/symbol-AST "MI") (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.72) (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "Xj") (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.97) (rpn.ast/number-AST 1.05)) (rpn.ast/symbol-AST "gA"))) (rpn.ast/max-AST (rpn.ast/symbol-AST "QA") (rpn.ast/symbol-AST "Qq")))) (rpn.ast/symbol-AST "zB")) (rpn.ast/number-AST 1.46)))] ["( 1.54 max ( 1.47 min 1.21 + 1.04 ) % 1.51 + wO ) + gN ^ 1.71 * ge" (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.54) (rpn.ast/add-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.47) (rpn.ast/number-AST 1.21)) (rpn.ast/number-AST 1.04))) (rpn.ast/number-AST 1.51)) (rpn.ast/symbol-AST "wO")) (rpn.ast/multiply-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "gN") (rpn.ast/number-AST 1.71)) (rpn.ast/symbol-AST "ge")))] ["( 0.03 / ( ( 0.98 % hN - DI ) ) min od ) + 1.39 % ( ph min sX ) % 0.38" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.03) (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.98) (rpn.ast/symbol-AST "hN")) (rpn.ast/symbol-AST "DI")) (rpn.ast/symbol-AST "od"))) (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.39) (rpn.ast/min-AST (rpn.ast/symbol-AST "ph") (rpn.ast/symbol-AST "sX"))) (rpn.ast/number-AST 0.38)))] ["( WH ^ 1.85 )" (rpn.ast/power-AST (rpn.ast/symbol-AST "WH") (rpn.ast/number-AST 1.85))] ["( Gq % OA / ew )" (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Gq") (rpn.ast/symbol-AST "OA")) (rpn.ast/symbol-AST "ew"))] ["dO * ( 0.16 max 1.21 % QF ^ qa ) / BS" (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "dO") (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/number-AST 0.16) (rpn.ast/number-AST 1.21)) (rpn.ast/symbol-AST "QF")) (rpn.ast/symbol-AST "qa"))) (rpn.ast/symbol-AST "BS"))] ["wX - 0.77" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "wX") (rpn.ast/number-AST 0.77))] ["( ( Ay * ( 0.50 ) max BA ^ ( 1.80 ) ) - 0.64 ) * ( Ui / 1.69 - xC ) % ( UN + 1.70 min 0.02 min JR ) / 1.85" (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Ay") (rpn.ast/max-AST (rpn.ast/number-AST 0.5) (rpn.ast/symbol-AST "BA"))) (rpn.ast/number-AST 1.8)) (rpn.ast/number-AST 0.64)) (rpn.ast/subtract-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "Ui") (rpn.ast/number-AST 1.69)) (rpn.ast/symbol-AST "xC"))) (rpn.ast/add-AST (rpn.ast/symbol-AST "UN") (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.7) (rpn.ast/number-AST 0.02)) (rpn.ast/symbol-AST "JR")))) (rpn.ast/number-AST 1.85))] ["( it max FE / 0.73 - ( 0.33 % ( 0.15 * ( ( ( 0.01 max 1.21 + Bq % 1.69 ) - Ve ) - ( nY max 0.17 + vz / ( QC ) ) ) ) / ( 0.47 % 1.57 + ( 1.01 - 0.21 ) ) ) ) + 1.55 ^ ( 1.54 max SF + fB + ( ( ym ) ) ) - ln" (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/divide-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "it") (rpn.ast/symbol-AST "FE")) (rpn.ast/number-AST 0.73)) (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.33) (rpn.ast/multiply-AST (rpn.ast/number-AST 0.15) (rpn.ast/subtract-AST (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 0.01) (rpn.ast/number-AST 1.21)) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Bq") (rpn.ast/number-AST 1.69))) (rpn.ast/symbol-AST "Ve")) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "nY") (rpn.ast/number-AST 0.17)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "vz") (rpn.ast/symbol-AST "QC")))))) (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.47) (rpn.ast/number-AST 1.57)) (rpn.ast/subtract-AST (rpn.ast/number-AST 1.01) (rpn.ast/number-AST 0.21))))) (rpn.ast/power-AST (rpn.ast/number-AST 1.55) (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.54) (rpn.ast/symbol-AST "SF")) (rpn.ast/symbol-AST "fB")) (rpn.ast/symbol-AST "ym")))) (rpn.ast/symbol-AST "ln"))] ["0.90" (rpn.ast/number-AST 0.9)] ["OP" (rpn.ast/symbol-AST "OP")] ["0.38 / ( rU / uh % 0.25 )" (rpn.ast/divide-AST (rpn.ast/number-AST 0.38) (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "rU") (rpn.ast/symbol-AST "uh")) (rpn.ast/number-AST 0.25)))] ["( uz )" (rpn.ast/symbol-AST "uz")] ["vF ^ ( jw ) / kR" (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "vF") (rpn.ast/symbol-AST "jw")) (rpn.ast/symbol-AST "kR"))] ["gk" (rpn.ast/symbol-AST "gk")] ["( ( BU ) max ( lo ^ VY ) * ( ( ( 1.94 % 0.62 % ( 0.51 % Qy max ( ( Ag ^ wh - 0.19 ) ) min ( ( gP ^ ( 1.96 ) ) min Ur ) ) ) + ( 0.61 % ( HZ ) * ( 0.56 min dr ^ 0.64 ) ) ) * cu max OU min 1.62 ) + 1.74 )" (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "BU") (rpn.ast/power-AST (rpn.ast/symbol-AST "lo") (rpn.ast/symbol-AST "VY"))) (rpn.ast/multiply-AST (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.94) (rpn.ast/number-AST 0.62)) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.51) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Qy") (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "Ag") (rpn.ast/symbol-AST "wh")) (rpn.ast/number-AST 0.19))) (rpn.ast/min-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "gP") (rpn.ast/number-AST 1.96)) (rpn.ast/symbol-AST "Ur"))))) (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.61) (rpn.ast/symbol-AST "HZ")) (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.56) (rpn.ast/symbol-AST "dr")) (rpn.ast/number-AST 0.64)))) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "cu") (rpn.ast/symbol-AST "OU")) (rpn.ast/number-AST 1.62)))) (rpn.ast/number-AST 1.74))] ["( ft ) / Jh + Gt * AP" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "ft") (rpn.ast/symbol-AST "Jh")) (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Gt") (rpn.ast/symbol-AST "AP")))] ["Zw - CA + Co" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Zw") (rpn.ast/symbol-AST "CA")) (rpn.ast/symbol-AST "Co"))] ["( 1.27 ) - NT" (rpn.ast/subtract-AST (rpn.ast/number-AST 1.27) (rpn.ast/symbol-AST "NT"))] ["FI min KU % ( sQ * 1.84 )" (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "FI") (rpn.ast/symbol-AST "KU")) (rpn.ast/multiply-AST (rpn.ast/symbol-AST "sQ") (rpn.ast/number-AST 1.84)))] ["( 1.73 ) ^ cE / Uv" (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.73) (rpn.ast/symbol-AST "cE")) (rpn.ast/symbol-AST "Uv"))] ["0.98 / 1.19 / ( Wk - lG % ( 1.06 ^ Mv ) % xf ) + HS" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.98) (rpn.ast/number-AST 1.19)) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Wk") (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "lG") (rpn.ast/power-AST (rpn.ast/number-AST 1.06) (rpn.ast/symbol-AST "Mv"))) (rpn.ast/symbol-AST "xf")))) (rpn.ast/symbol-AST "HS"))] ["1.64 % dX" (rpn.ast/modulo-AST (rpn.ast/number-AST 1.64) (rpn.ast/symbol-AST "dX"))] ["( 1.04 max HD % nU )" (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.04) (rpn.ast/symbol-AST "HD")) (rpn.ast/symbol-AST "nU"))] ["0.39" (rpn.ast/number-AST 0.39)] ["1.15 - KG + 0.85 % ( ( 1.71 ^ 0.43 min uL min 0.73 ) / ( ( Mo ) - lJ % ( ( ( ( 1.20 % ip ) - ( au ) ) - 1.29 max AS max 1.21 ) ^ 1.02 ) ) - pQ )" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.15) (rpn.ast/symbol-AST "KG")) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.85) (rpn.ast/subtract-AST (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.71) (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.43) (rpn.ast/symbol-AST "uL")) (rpn.ast/number-AST 0.73))) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Mo") (rpn.ast/modulo-AST (rpn.ast/symbol-AST "lJ") (rpn.ast/power-AST (rpn.ast/subtract-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.2) (rpn.ast/symbol-AST "ip")) (rpn.ast/symbol-AST "au")) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.29) (rpn.ast/symbol-AST "AS")) (rpn.ast/number-AST 1.21))) (rpn.ast/number-AST 1.02))))) (rpn.ast/symbol-AST "pQ"))))] ["( ( ( dp - 0.16 / 1.23 ) - 1.54 min 0.82 % ( wI % uP ) ) )" (rpn.ast/subtract-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "dp") (rpn.ast/divide-AST (rpn.ast/number-AST 0.16) (rpn.ast/number-AST 1.23))) (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.54) (rpn.ast/number-AST 0.82)) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "wI") (rpn.ast/symbol-AST "uP"))))] ["( 1.15 max 1.04 + 1.15 ) - 1.86" (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.15) (rpn.ast/number-AST 1.04)) (rpn.ast/number-AST 1.15)) (rpn.ast/number-AST 1.86))] ["1.44 / 0.68" (rpn.ast/divide-AST (rpn.ast/number-AST 1.44) (rpn.ast/number-AST 0.68))] ["wO % NV" (rpn.ast/modulo-AST (rpn.ast/symbol-AST "wO") (rpn.ast/symbol-AST "NV"))] ["Wp * ys min 0.46 + ( ( ( ( 1.32 ^ Bw ) max 1.70 - ( ( KL min ( ( 1.23 / ( 1.92 ) / ( 0.30 ) % ( zq + bj ) ) - ( ( hO * Bz % ( Iv + ( ( YE ) % rI - 1.24 ) ) ) min IA ) % ( lO max ( ( nE ^ Mu + 1.53 ) - kl min 1.31 min hb ) * oX % ( ( 0.74 % 0.80 - aC ) ) ) ) * 1.06 ) ) min 1.68 ) / ( 0.83 - 1.71 * 0.45 ) max 0.84 min ( ( ( 1.30 % 1.50 - kb ) min 0.95 / ( 0.21 % hg ) ) max 0.20 ) ) / ( ( ( 1.83 * Ks - 0.29 ) * Ua % 1.92 % ( ( 0.24 + dL / Fn ) ) ) max 1.00 % 0.14 ) + 1.12 )" (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Wp") (rpn.ast/min-AST (rpn.ast/symbol-AST "ys") (rpn.ast/number-AST 0.46))) (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/subtract-AST (rpn.ast/max-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.32) (rpn.ast/symbol-AST "Bw")) (rpn.ast/number-AST 1.7)) (rpn.ast/min-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "KL") (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.23) (rpn.ast/number-AST 1.92)) (rpn.ast/number-AST 0.3)) (rpn.ast/add-AST (rpn.ast/symbol-AST "zq") (rpn.ast/symbol-AST "bj"))) (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "hO") (rpn.ast/symbol-AST "Bz")) (rpn.ast/add-AST (rpn.ast/symbol-AST "Iv") (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "YE") (rpn.ast/symbol-AST "rI")) (rpn.ast/number-AST 1.24)))) (rpn.ast/symbol-AST "IA")) (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "lO") (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "nE") (rpn.ast/symbol-AST "Mu")) (rpn.ast/number-AST 1.53)) (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "kl") (rpn.ast/number-AST 1.31)) (rpn.ast/symbol-AST "hb")))) (rpn.ast/symbol-AST "oX")) (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.74) (rpn.ast/number-AST 0.8)) (rpn.ast/symbol-AST "aC")))))) (rpn.ast/number-AST 1.06)) (rpn.ast/number-AST 1.68))) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 0.83) (rpn.ast/multiply-AST (rpn.ast/number-AST 1.71) (rpn.ast/number-AST 0.45))) (rpn.ast/number-AST 0.84)) (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.3) (rpn.ast/number-AST 1.5)) (rpn.ast/symbol-AST "kb")) (rpn.ast/number-AST 0.95)) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.21) (rpn.ast/symbol-AST "hg"))) (rpn.ast/number-AST 0.2)))) (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.83) (rpn.ast/symbol-AST "Ks")) (rpn.ast/number-AST 0.29)) (rpn.ast/symbol-AST "Ua")) (rpn.ast/number-AST 1.92)) (rpn.ast/add-AST (rpn.ast/number-AST 0.24) (rpn.ast/divide-AST (rpn.ast/symbol-AST "dL") (rpn.ast/symbol-AST "Fn")))) (rpn.ast/number-AST 1.0)) (rpn.ast/number-AST 0.14))) (rpn.ast/number-AST 1.12)))] ["JB" (rpn.ast/symbol-AST "JB")] ["aY" (rpn.ast/symbol-AST "aY")] ["0.92 * ( FX ) / Ml / ( 0.89 % ( Or max wM ) max 0.01 )" (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.92) (rpn.ast/symbol-AST "FX")) (rpn.ast/symbol-AST "Ml")) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.89) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Or") (rpn.ast/symbol-AST "wM")) (rpn.ast/number-AST 0.01))))] ["( tL + 1.37 ) + ( ( Pw + 0.87 - ( uC * Bb * no min ( 1.88 ^ ( 1.09 max ( ( 0.15 min ( 0.80 ) ^ uM max 1.99 ) * ( 0.17 ^ 0.54 min 0.24 + 0.27 ) - Ee * dd ) + 1.52 ^ vG ) + ( ( ( ( uU / tD ) * ( HT ^ 1.62 % cR - 0.14 ) ) min Ie / 1.84 ) * Zf % jO ) ) ) ) ) + ( CT min la * LH )" (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "tL") (rpn.ast/number-AST 1.37)) (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "Pw") (rpn.ast/number-AST 0.87)) (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "uC") (rpn.ast/symbol-AST "Bb")) (rpn.ast/min-AST (rpn.ast/symbol-AST "no") (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.88) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.09) (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.15) (rpn.ast/number-AST 0.8)) (rpn.ast/max-AST (rpn.ast/symbol-AST "uM") (rpn.ast/number-AST 1.99))) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/number-AST 0.17) (rpn.ast/min-AST (rpn.ast/number-AST 0.54) (rpn.ast/number-AST 0.24))) (rpn.ast/number-AST 0.27))) (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Ee") (rpn.ast/symbol-AST "dd")))) (rpn.ast/power-AST (rpn.ast/number-AST 1.52) (rpn.ast/symbol-AST "vG")))) (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "uU") (rpn.ast/symbol-AST "tD")) (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "HT") (rpn.ast/number-AST 1.62)) (rpn.ast/symbol-AST "cR")) (rpn.ast/number-AST 0.14))) (rpn.ast/symbol-AST "Ie")) (rpn.ast/number-AST 1.84)) (rpn.ast/symbol-AST "Zf")) (rpn.ast/symbol-AST "jO"))))))) (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "CT") (rpn.ast/symbol-AST "la")) (rpn.ast/symbol-AST "LH")))] ["Jo % Qs" (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Jo") (rpn.ast/symbol-AST "Qs"))] ["1.80 - ( Wj - 1.70 + ( TE / ( qi min ( ( sP / ( ( DM ) - 1.28 ) * 0.45 % 1.00 ) max 1.74 / 0.83 ^ ( ( ( ( 1.09 - ( ( ( ( ( 0.45 + tL + 1.20 ) ) ) + 1.30 * TC / ( ( ( ( Se ) - ( 1.19 ) ) ^ FQ / HI ^ 0.31 ) + 0.94 ) ) % Ih * 1.35 ^ ( 1.59 % 0.40 max ( ( 1.67 max bk ) max ( 0.24 % ( GF + 1.17 % qa ^ 1.28 ) ^ ( NY ^ 0.11 % ( Bg - 1.20 ) ) ) ) ) ) / Ia % ( ( 1.77 min gB / ( ( ( ( ( ov ) / 0.45 / LF - 1.50 ) min 0.57 ) min Tq ^ 0.68 ) ) ) max hd ) ) % 0.34 ^ ( 1.96 ) ) + 0.31 ) ) ) - tQ ^ XB ) ) ) ^ 0.40 + ( ( 0.30 / ( 0.66 max in + 1.90 ) * ( 1.99 / Sl % 1.62 ) / 0.47 ) ^ mc - 1.82 + 0.22 )" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.8) (rpn.ast/power-AST (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Wj") (rpn.ast/number-AST 1.7)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "TE") (rpn.ast/subtract-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "qi") (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/max-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "sP") (rpn.ast/subtract-AST (rpn.ast/symbol-AST "DM") (rpn.ast/number-AST 1.28))) (rpn.ast/number-AST 0.45)) (rpn.ast/number-AST 1.0)) (rpn.ast/number-AST 1.74)) (rpn.ast/number-AST 0.83)) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.09) (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/number-AST 0.45) (rpn.ast/symbol-AST "tL")) (rpn.ast/number-AST 1.2)) (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.3) (rpn.ast/symbol-AST "TC")) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Se") (rpn.ast/number-AST 1.19)) (rpn.ast/symbol-AST "FQ")) (rpn.ast/symbol-AST "HI")) (rpn.ast/number-AST 0.31)) (rpn.ast/number-AST 0.94)))) (rpn.ast/symbol-AST "Ih")) (rpn.ast/number-AST 1.35)) (rpn.ast/modulo-AST (rpn.ast/number-AST 1.59) (rpn.ast/max-AST (rpn.ast/number-AST 0.4) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.67) (rpn.ast/symbol-AST "bk")) (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.24) (rpn.ast/add-AST (rpn.ast/symbol-AST "GF") (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.17) (rpn.ast/symbol-AST "qa")) (rpn.ast/number-AST 1.28)))) (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "NY") (rpn.ast/number-AST 0.11)) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Bg") (rpn.ast/number-AST 1.2)))))))) (rpn.ast/symbol-AST "Ia")) (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.77) (rpn.ast/symbol-AST "gB")) (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "ov") (rpn.ast/number-AST 0.45)) (rpn.ast/symbol-AST "LF")) (rpn.ast/number-AST 1.5)) (rpn.ast/number-AST 0.57)) (rpn.ast/symbol-AST "Tq")) (rpn.ast/number-AST 0.68))) (rpn.ast/symbol-AST "hd")))) (rpn.ast/number-AST 0.34)) (rpn.ast/number-AST 1.96)) (rpn.ast/number-AST 0.31)))) (rpn.ast/power-AST (rpn.ast/symbol-AST "tQ") (rpn.ast/symbol-AST "XB"))))) (rpn.ast/number-AST 0.4))) (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.3) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 0.66) (rpn.ast/symbol-AST "in")) (rpn.ast/number-AST 1.9))) (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.99) (rpn.ast/symbol-AST "Sl")) (rpn.ast/number-AST 1.62))) (rpn.ast/number-AST 0.47)) (rpn.ast/symbol-AST "mc")) (rpn.ast/number-AST 1.82)) (rpn.ast/number-AST 0.22)))] ["( 1.23 * HT min 1.16 ) - Oc + 1.44" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.23) (rpn.ast/min-AST (rpn.ast/symbol-AST "HT") (rpn.ast/number-AST 1.16))) (rpn.ast/symbol-AST "Oc")) (rpn.ast/number-AST 1.44))] ["( 1.99 )" (rpn.ast/number-AST 1.99)] ["Zu" (rpn.ast/symbol-AST "Zu")] ["0.53" (rpn.ast/number-AST 0.53)] ["Nc - PW" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Nc") (rpn.ast/symbol-AST "PW"))] ["kl * ww - YI" (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "kl") (rpn.ast/symbol-AST "ww")) (rpn.ast/symbol-AST "YI"))] ["1.93 max 1.41 ^ ( ( ( 0.90 % ( 1.40 / 0.79 ^ 0.76 min vt ) ) - ( 0.96 ^ 0.18 ) ) / nl / ( cn % 1.22 ) )" (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.93) (rpn.ast/number-AST 1.41)) (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.9) (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.4) (rpn.ast/number-AST 0.79)) (rpn.ast/min-AST (rpn.ast/number-AST 0.76) (rpn.ast/symbol-AST "vt")))) (rpn.ast/power-AST (rpn.ast/number-AST 0.96) (rpn.ast/number-AST 0.18))) (rpn.ast/symbol-AST "nl")) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "cn") (rpn.ast/number-AST 1.22))))] ["wo / 0.35 + WT / oj" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "wo") (rpn.ast/number-AST 0.35)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "WT") (rpn.ast/symbol-AST "oj")))] ["( 1.42 % mL ) % iF max rI % ( Gb )" (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.42) (rpn.ast/symbol-AST "mL")) (rpn.ast/max-AST (rpn.ast/symbol-AST "iF") (rpn.ast/symbol-AST "rI"))) (rpn.ast/symbol-AST "Gb"))] ["0.08 ^ KU max 2.00" (rpn.ast/power-AST (rpn.ast/number-AST 0.08) (rpn.ast/max-AST (rpn.ast/symbol-AST "KU") (rpn.ast/number-AST 2.0)))] ["0.33 % 0.51 * 0.42" (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.33) (rpn.ast/number-AST 0.51)) (rpn.ast/number-AST 0.42))] ["rj % rw min ( Et )" (rpn.ast/modulo-AST (rpn.ast/symbol-AST "rj") (rpn.ast/min-AST (rpn.ast/symbol-AST "rw") (rpn.ast/symbol-AST "Et")))] ["( 1.17 ^ 1.70 ) % 0.60 - 1.33" (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.17) (rpn.ast/number-AST 1.7)) (rpn.ast/number-AST 0.6)) (rpn.ast/number-AST 1.33))] ["tp min 0.60" (rpn.ast/min-AST (rpn.ast/symbol-AST "tp") (rpn.ast/number-AST 0.6))] ["Zy" (rpn.ast/symbol-AST "Zy")] ["pT min qW ^ Ul" (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "pT") (rpn.ast/symbol-AST "qW")) (rpn.ast/symbol-AST "Ul"))] ["( 1.36 ^ ET ) ^ Uz" (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.36) (rpn.ast/symbol-AST "ET")) (rpn.ast/symbol-AST "Uz"))] ["( ( 0.16 - 0.44 / LC ) ) ^ vE" (rpn.ast/power-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 0.16) (rpn.ast/divide-AST (rpn.ast/number-AST 0.44) (rpn.ast/symbol-AST "LC"))) (rpn.ast/symbol-AST "vE"))] ["Es min Fl ^ 0.78 ^ 0.60" (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "Es") (rpn.ast/symbol-AST "Fl")) (rpn.ast/number-AST 0.78)) (rpn.ast/number-AST 0.6))] ["1.50" (rpn.ast/number-AST 1.5)] ["Tn + ( 0.64 ) min 0.62" (rpn.ast/add-AST (rpn.ast/symbol-AST "Tn") (rpn.ast/min-AST (rpn.ast/number-AST 0.64) (rpn.ast/number-AST 0.62)))] ["Pf" (rpn.ast/symbol-AST "Pf")] ["( ( ( 1.40 ) - ( 1.75 ) max Vq ) * ( UL * 1.74 min ( FP min mV max PQ ) ) / NJ + 1.61 ) / 0.72 % 0.34 max fQ" (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.4) (rpn.ast/max-AST (rpn.ast/number-AST 1.75) (rpn.ast/symbol-AST "Vq"))) (rpn.ast/multiply-AST (rpn.ast/symbol-AST "UL") (rpn.ast/min-AST (rpn.ast/number-AST 1.74) (rpn.ast/max-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "FP") (rpn.ast/symbol-AST "mV")) (rpn.ast/symbol-AST "PQ"))))) (rpn.ast/symbol-AST "NJ")) (rpn.ast/number-AST 1.61)) (rpn.ast/number-AST 0.72)) (rpn.ast/max-AST (rpn.ast/number-AST 0.34) (rpn.ast/symbol-AST "fQ")))] ["( 0.42 * ( 0.23 ^ ( fK min bR - ii % ( 1.80 / 1.83 ) ) ) )" (rpn.ast/multiply-AST (rpn.ast/number-AST 0.42) (rpn.ast/power-AST (rpn.ast/number-AST 0.23) (rpn.ast/subtract-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "fK") (rpn.ast/symbol-AST "bR")) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "ii") (rpn.ast/divide-AST (rpn.ast/number-AST 1.8) (rpn.ast/number-AST 1.83))))))] ["( 1.82 / 1.28 ) max ( Hj - 1.41 )" (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.82) (rpn.ast/number-AST 1.28)) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Hj") (rpn.ast/number-AST 1.41)))] ["0.07 % 1.08 * 1.14" (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.07) (rpn.ast/number-AST 1.08)) (rpn.ast/number-AST 1.14))] ["Nt % ( 0.11 ^ LM ) * Pj" (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Nt") (rpn.ast/power-AST (rpn.ast/number-AST 0.11) (rpn.ast/symbol-AST "LM"))) (rpn.ast/symbol-AST "Pj"))] ["dD - ( ( 1.93 + ( 1.19 % ZV ^ ( 1.43 * nV * mK ) ) ^ 1.09 ) + ( 0.62 ) % ( ( 1.69 / 1.52 max tJ ) + ( 0.62 ) ) - ( 1.77 / 1.64 max ND min qK ) ) / 1.28 min rN" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "dD") (rpn.ast/divide-AST (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.93) (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.19) (rpn.ast/symbol-AST "ZV")) (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.43) (rpn.ast/symbol-AST "nV")) (rpn.ast/symbol-AST "mK"))) (rpn.ast/number-AST 1.09))) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.62) (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.69) (rpn.ast/max-AST (rpn.ast/number-AST 1.52) (rpn.ast/symbol-AST "tJ"))) (rpn.ast/number-AST 0.62)))) (rpn.ast/divide-AST (rpn.ast/number-AST 1.77) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.64) (rpn.ast/symbol-AST "ND")) (rpn.ast/symbol-AST "qK")))) (rpn.ast/min-AST (rpn.ast/number-AST 1.28) (rpn.ast/symbol-AST "rN"))))] ["lu" (rpn.ast/symbol-AST "lu")] ["( 0.79 )" (rpn.ast/number-AST 0.79)] ["( ( ( 1.01 ) + 1.63 % Wg / no ) * lY )" (rpn.ast/multiply-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.01) (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.63) (rpn.ast/symbol-AST "Wg")) (rpn.ast/symbol-AST "no"))) (rpn.ast/symbol-AST "lY"))] ["( ( Rq ) ) ^ 1.64" (rpn.ast/power-AST (rpn.ast/symbol-AST "Rq") (rpn.ast/number-AST 1.64))] ["1.61" (rpn.ast/number-AST 1.61)] ["1.74 * 0.16 * ( 1.96 ^ 0.58 % 0.85 * oc ) / ( 0.52 )" (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.74) (rpn.ast/number-AST 0.16)) (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.96) (rpn.ast/number-AST 0.58)) (rpn.ast/number-AST 0.85)) (rpn.ast/symbol-AST "oc"))) (rpn.ast/number-AST 0.52))] ["0.22" (rpn.ast/number-AST 0.22)]))
true
;;; ;;; Copyright 2020 PI:NAME:<NAME>END_PI ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. ;;; (ns rpn.parser-test (:require [clojure.test :as test]) (:require [rpn.expressions :as expr]) (:require [rpn.lexer :as lexer]) (:require [rpn.parser :as parser])) (declare parser-tests) (test/deftest valid-randomized-expressions (doseq [[e ast] parser-tests] (test/is (= (parser/parser (lexer/lexer e)) ast)))) (test/deftest invalid-expressions (doseq [e ["" " " "a +" "+ a" "a 1" "(a + 1" "a + 1)" "(a + 1))" ")a" "()" "a + * 1" "a $ 1" "(a + 1)(b + 2)"]] (test/is (thrown? Exception (doall (parser/parser (lexer/lexer e))))))) (def ^:private parser-tests (list ["( 0.39 * ( 0.57 ) min 0.13 ) max 1.78 min 1.64 max ( nT ^ ( 0.47 % ( ( jQ max qh ^ PK % 1.01 ) ^ 1.24 max 0.50 max ( ( VU ^ 0.57 ) + qx ) ) - ( 1.71 ) max gx ) )" (rpn.ast/max-AST (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.39) (rpn.ast/min-AST (rpn.ast/number-AST 0.57) (rpn.ast/number-AST 0.13))) (rpn.ast/number-AST 1.78)) (rpn.ast/number-AST 1.64)) (rpn.ast/power-AST (rpn.ast/symbol-AST "nT") (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.47) (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "jQ") (rpn.ast/symbol-AST "qh")) (rpn.ast/symbol-AST "PK")) (rpn.ast/number-AST 1.01)) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.24) (rpn.ast/number-AST 0.5)) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "VU") (rpn.ast/number-AST 0.57)) (rpn.ast/symbol-AST "qx"))))) (rpn.ast/max-AST (rpn.ast/number-AST 1.71) (rpn.ast/symbol-AST "gx")))))] ["0.23 / XT + 0.08" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.23) (rpn.ast/symbol-AST "XT")) (rpn.ast/number-AST 0.08))] ["TM" (rpn.ast/symbol-AST "TM")] ["DM * ( RL ) / ( ( ( 1.30 min JJ * ( 1.02 max ( 0.61 * GQ / 0.64 ) max ( ( 1.45 ) * AB ^ ( ( ( 1.75 + 1.79 * ( tO + Lp max us min 1.67 ) ) * ( 0.10 min 0.32 ) min ( 0.01 ) ) * ( ( 1.73 ) ) - 0.16 ) * 0.85 ) ) ) % ( gY max oQ / ( 0.96 % 1.02 - 0.17 ) ) min gS * 1.05 ) ^ wW ) max ( ea min ( ( ( ( ( Ps ) ) / xr ) ) max 1.37 max 0.31 ) )" (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "DM") (rpn.ast/symbol-AST "RL")) (rpn.ast/max-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.3) (rpn.ast/symbol-AST "JJ")) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.02) (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.61) (rpn.ast/symbol-AST "GQ")) (rpn.ast/number-AST 0.64))) (rpn.ast/multiply-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.45) (rpn.ast/symbol-AST "AB")) (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.75) (rpn.ast/multiply-AST (rpn.ast/number-AST 1.79) (rpn.ast/add-AST (rpn.ast/symbol-AST "tO") (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Lp") (rpn.ast/symbol-AST "us")) (rpn.ast/number-AST 1.67))))) (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.1) (rpn.ast/number-AST 0.32)) (rpn.ast/number-AST 0.01))) (rpn.ast/number-AST 1.73)) (rpn.ast/number-AST 0.16))) (rpn.ast/number-AST 0.85)))) (rpn.ast/min-AST (rpn.ast/divide-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "gY") (rpn.ast/symbol-AST "oQ")) (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.96) (rpn.ast/number-AST 1.02)) (rpn.ast/number-AST 0.17))) (rpn.ast/symbol-AST "gS"))) (rpn.ast/number-AST 1.05)) (rpn.ast/symbol-AST "wW")) (rpn.ast/min-AST (rpn.ast/symbol-AST "ea") (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "Ps") (rpn.ast/symbol-AST "xr")) (rpn.ast/number-AST 1.37)) (rpn.ast/number-AST 0.31)))))] ["0.56 - ( ( ( ( ( ( ( 1.66 ) min 1.58 ) * ( 1.54 + ( 1.63 * ( Qu % qD % 0.34 ) ^ 1.48 + oY ) ) * ( 1.64 ^ 1.95 ^ ( 0.19 ^ ( lk max 1.48 ) ) ) ) max Ue + 0.46 ^ 1.67 ) % FT / Ni min ( Ls / zq + ( 0.07 / ( 0.17 ) min ( 0.25 ) ) ) ) max lY ) min ( Vv max 1.23 ) ) % rr" (rpn.ast/subtract-AST (rpn.ast/number-AST 0.56) (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.66) (rpn.ast/number-AST 1.58)) (rpn.ast/add-AST (rpn.ast/number-AST 1.54) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.63) (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Qu") (rpn.ast/symbol-AST "qD")) (rpn.ast/number-AST 0.34))) (rpn.ast/number-AST 1.48)) (rpn.ast/symbol-AST "oY")))) (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.64) (rpn.ast/number-AST 1.95)) (rpn.ast/power-AST (rpn.ast/number-AST 0.19) (rpn.ast/max-AST (rpn.ast/symbol-AST "lk") (rpn.ast/number-AST 1.48))))) (rpn.ast/symbol-AST "Ue")) (rpn.ast/power-AST (rpn.ast/number-AST 0.46) (rpn.ast/number-AST 1.67))) (rpn.ast/symbol-AST "FT")) (rpn.ast/min-AST (rpn.ast/symbol-AST "Ni") (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "Ls") (rpn.ast/symbol-AST "zq")) (rpn.ast/divide-AST (rpn.ast/number-AST 0.07) (rpn.ast/min-AST (rpn.ast/number-AST 0.17) (rpn.ast/number-AST 0.25)))))) (rpn.ast/symbol-AST "lY")) (rpn.ast/max-AST (rpn.ast/symbol-AST "Vv") (rpn.ast/number-AST 1.23))) (rpn.ast/symbol-AST "rr")))] ["0.78 ^ ( xm max 0.85 + mJ )" (rpn.ast/power-AST (rpn.ast/number-AST 0.78) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "xm") (rpn.ast/number-AST 0.85)) (rpn.ast/symbol-AST "mJ")))] ["xD * Iu" (rpn.ast/multiply-AST (rpn.ast/symbol-AST "xD") (rpn.ast/symbol-AST "Iu"))] ["dG * Xx / di" (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "dG") (rpn.ast/symbol-AST "Xx")) (rpn.ast/symbol-AST "di"))] ["Ur max TC - 0.10" (rpn.ast/subtract-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Ur") (rpn.ast/symbol-AST "TC")) (rpn.ast/number-AST 0.1))] ["( 1.30 ^ ( ( 1.01 min 1.95 min 1.15 ) * lp + kT ) ) % ( ( ( 0.91 ) ) - hv max ( Wu ) * 0.23 ) * 0.18" (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.3) (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.01) (rpn.ast/number-AST 1.95)) (rpn.ast/number-AST 1.15)) (rpn.ast/symbol-AST "lp")) (rpn.ast/symbol-AST "kT"))) (rpn.ast/subtract-AST (rpn.ast/number-AST 0.91) (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "hv") (rpn.ast/symbol-AST "Wu")) (rpn.ast/number-AST 0.23)))) (rpn.ast/number-AST 0.18))] ["YN - dl" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "YN") (rpn.ast/symbol-AST "dl"))] ["( Uv )" (rpn.ast/symbol-AST "Uv")] ["1.20 - ea min 1.61" (rpn.ast/subtract-AST (rpn.ast/number-AST 1.2) (rpn.ast/min-AST (rpn.ast/symbol-AST "ea") (rpn.ast/number-AST 1.61)))] ["xN * 0.06" (rpn.ast/multiply-AST (rpn.ast/symbol-AST "xN") (rpn.ast/number-AST 0.06))] ["LE ^ tg max nZ ^ XY" (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "LE") (rpn.ast/max-AST (rpn.ast/symbol-AST "tg") (rpn.ast/symbol-AST "nZ"))) (rpn.ast/symbol-AST "XY"))] ["( ( ( ( Dx ^ 0.48 ) % ( ( ZE ^ Fq - 1.64 % ( ya / Ea % 1.67 + ( 1.73 % fN ) ) ) ) min 0.26 ) max ( JI - ( ( Dq max ( 1.68 max UZ * HZ * 0.08 ) % 1.13 - 1.67 ) ) ) ) min ( 0.01 ) / aD * 0.61 )" (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "Dx") (rpn.ast/number-AST 0.48)) (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "ZE") (rpn.ast/symbol-AST "Fq")) (rpn.ast/modulo-AST (rpn.ast/number-AST 1.64) (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "ya") (rpn.ast/symbol-AST "Ea")) (rpn.ast/number-AST 1.67)) (rpn.ast/modulo-AST (rpn.ast/number-AST 1.73) (rpn.ast/symbol-AST "fN"))))) (rpn.ast/number-AST 0.26))) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "JI") (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Dq") (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.68) (rpn.ast/symbol-AST "UZ")) (rpn.ast/symbol-AST "HZ")) (rpn.ast/number-AST 0.08))) (rpn.ast/number-AST 1.13)) (rpn.ast/number-AST 1.67)))) (rpn.ast/number-AST 0.01)) (rpn.ast/symbol-AST "aD")) (rpn.ast/number-AST 0.61))] ["( ( ( ( ( ( ( 1.25 + 1.18 - ( ( ( 0.60 ) * ( ( 1.23 min yT * Xf ) / iA ) ) * JG + XB max Ma ) ) min ( 1.42 ) max ( ( 0.05 - ( Bb / so ) ) ) ) ) * gk ) ^ 0.09 max mq ) min gj ) % ( EA * uk min 0.77 ^ CY ) min ( ( Fi min 0.62 ) * 0.41 ) ^ 0.62 )" (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.25) (rpn.ast/number-AST 1.18)) (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.6) (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.23) (rpn.ast/symbol-AST "yT")) (rpn.ast/symbol-AST "Xf")) (rpn.ast/symbol-AST "iA"))) (rpn.ast/symbol-AST "JG")) (rpn.ast/max-AST (rpn.ast/symbol-AST "XB") (rpn.ast/symbol-AST "Ma")))) (rpn.ast/number-AST 1.42)) (rpn.ast/subtract-AST (rpn.ast/number-AST 0.05) (rpn.ast/divide-AST (rpn.ast/symbol-AST "Bb") (rpn.ast/symbol-AST "so")))) (rpn.ast/symbol-AST "gk")) (rpn.ast/max-AST (rpn.ast/number-AST 0.09) (rpn.ast/symbol-AST "mq"))) (rpn.ast/symbol-AST "gj")) (rpn.ast/min-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "EA") (rpn.ast/min-AST (rpn.ast/symbol-AST "uk") (rpn.ast/number-AST 0.77))) (rpn.ast/symbol-AST "CY")) (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "Fi") (rpn.ast/number-AST 0.62)) (rpn.ast/number-AST 0.41)))) (rpn.ast/number-AST 0.62))] ["aF * 1.36 max ( Gc * ( ( ( uv ) * 1.22 + 0.05 + ( ( 0.86 * ( ( 1.74 % 0.25 % 1.80 min ( CR ) ) max ( 0.26 / 1.36 * ( ( ( aO + 0.43 + bu min EX ) % ( ( 0.89 ) max LG ^ xe max We ) ) ^ ( ( 1.74 min 1.60 ) + Ut / ( ( KL * ( ( ( ( KZ ) ) ) / ( dp ^ 0.13 - 1.60 ) ) * ( ( ( oT ) % yz / 0.74 % KQ ) * 1.47 % 0.56 ) ) ) ) / ( 0.93 + 0.56 % ( ( cc % HE max cO ) ) * ( 1.18 + ( XA % hW ) - ( QT ) ) ) min 1.70 ) ) % ( st + 1.30 ) + 1.52 ) ) min ( OJ + 0.26 / sq max 1.09 ) min 1.16 ) ) ^ Xh ) ^ pR / kf )" (rpn.ast/multiply-AST (rpn.ast/symbol-AST "aF") (rpn.ast/max-AST (rpn.ast/number-AST 1.36) (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Gc") (rpn.ast/power-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "uv") (rpn.ast/number-AST 1.22)) (rpn.ast/number-AST 0.05)) (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.86) (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.74) (rpn.ast/number-AST 0.25)) (rpn.ast/min-AST (rpn.ast/number-AST 1.8) (rpn.ast/symbol-AST "CR"))) (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.26) (rpn.ast/number-AST 1.36)) (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "aO") (rpn.ast/number-AST 0.43)) (rpn.ast/min-AST (rpn.ast/symbol-AST "bu") (rpn.ast/symbol-AST "EX"))) (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/number-AST 0.89) (rpn.ast/symbol-AST "LG")) (rpn.ast/max-AST (rpn.ast/symbol-AST "xe") (rpn.ast/symbol-AST "We")))) (rpn.ast/add-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.74) (rpn.ast/number-AST 1.6)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "Ut") (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "KL") (rpn.ast/divide-AST (rpn.ast/symbol-AST "KZ") (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "dp") (rpn.ast/number-AST 0.13)) (rpn.ast/number-AST 1.6)))) (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "oT") (rpn.ast/symbol-AST "yz")) (rpn.ast/number-AST 0.74)) (rpn.ast/symbol-AST "KQ")) (rpn.ast/number-AST 1.47)) (rpn.ast/number-AST 0.56)))))) (rpn.ast/min-AST (rpn.ast/add-AST (rpn.ast/number-AST 0.93) (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.56) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "cc") (rpn.ast/max-AST (rpn.ast/symbol-AST "HE") (rpn.ast/symbol-AST "cO")))) (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.18) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "XA") (rpn.ast/symbol-AST "hW"))) (rpn.ast/symbol-AST "QT")))) (rpn.ast/number-AST 1.7))))) (rpn.ast/add-AST (rpn.ast/symbol-AST "st") (rpn.ast/number-AST 1.3))) (rpn.ast/number-AST 1.52))) (rpn.ast/add-AST (rpn.ast/symbol-AST "OJ") (rpn.ast/divide-AST (rpn.ast/number-AST 0.26) (rpn.ast/max-AST (rpn.ast/symbol-AST "sq") (rpn.ast/number-AST 1.09))))) (rpn.ast/number-AST 1.16))) (rpn.ast/symbol-AST "Xh"))) (rpn.ast/symbol-AST "pR")) (rpn.ast/symbol-AST "kf"))))] ["( ( ( qn ) - 0.72 * ( 1.24 ) max Hj ) + ( ( oe max ( VP / zC + 1.42 ) max 0.08 ^ 0.63 ) ) - ( ( zX % BE min 1.16 ) min ( zI ) ) ) ^ 1.75 max ( ( WZ ) max ( rm / ( BG min Pm / 1.65 ) max ( Ug ^ 0.74 ) ) + nC ) / ( 1.91 min 0.04 ^ 0.54 max ( ( 1.70 max 0.64 min kB / 0.51 ) * ( CU + 1.52 max 0.92 ^ ( ( 1.27 * Ey max ( Vm + vA % ( 1.24 - ( Eu max ( bK min Ny min ( uo min 0.24 - It ) * 1.10 ) ) ) ) ) * 1.94 + eN / 0.88 ) ) max 1.54 ^ 0.67 ) )" (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "qn") (rpn.ast/multiply-AST (rpn.ast/number-AST 0.72) (rpn.ast/max-AST (rpn.ast/number-AST 1.24) (rpn.ast/symbol-AST "Hj")))) (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "oe") (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "VP") (rpn.ast/symbol-AST "zC")) (rpn.ast/number-AST 1.42))) (rpn.ast/number-AST 0.08)) (rpn.ast/number-AST 0.63))) (rpn.ast/min-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "zX") (rpn.ast/min-AST (rpn.ast/symbol-AST "BE") (rpn.ast/number-AST 1.16))) (rpn.ast/symbol-AST "zI"))) (rpn.ast/max-AST (rpn.ast/number-AST 1.75) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "WZ") (rpn.ast/divide-AST (rpn.ast/symbol-AST "rm") (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "BG") (rpn.ast/symbol-AST "Pm")) (rpn.ast/number-AST 1.65)) (rpn.ast/power-AST (rpn.ast/symbol-AST "Ug") (rpn.ast/number-AST 0.74))))) (rpn.ast/symbol-AST "nC")))) (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.91) (rpn.ast/number-AST 0.04)) (rpn.ast/max-AST (rpn.ast/number-AST 0.54) (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.7) (rpn.ast/number-AST 0.64)) (rpn.ast/symbol-AST "kB")) (rpn.ast/number-AST 0.51)) (rpn.ast/max-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "CU") (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.52) (rpn.ast/number-AST 0.92)) (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.27) (rpn.ast/max-AST (rpn.ast/symbol-AST "Ey") (rpn.ast/add-AST (rpn.ast/symbol-AST "Vm") (rpn.ast/modulo-AST (rpn.ast/symbol-AST "vA") (rpn.ast/subtract-AST (rpn.ast/number-AST 1.24) (rpn.ast/max-AST (rpn.ast/symbol-AST "Eu") (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "bK") (rpn.ast/symbol-AST "Ny")) (rpn.ast/subtract-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "uo") (rpn.ast/number-AST 0.24)) (rpn.ast/symbol-AST "It"))) (rpn.ast/number-AST 1.1)))))))) (rpn.ast/number-AST 1.94)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "eN") (rpn.ast/number-AST 0.88))))) (rpn.ast/number-AST 1.54))) (rpn.ast/number-AST 0.67)))))] ["( NU ) - ( ( zL % FE + ( ( 0.80 min ( 1.26 * SP / ( ( 1.47 max 0.15 - NP + ( ( 1.34 - uU ) * 1.91 ) ) ) ) ) ) ^ 0.30 ) + 0.69 * Jw ^ 1.62 )" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "NU") (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "zL") (rpn.ast/symbol-AST "FE")) (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.8) (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.26) (rpn.ast/symbol-AST "SP")) (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.47) (rpn.ast/number-AST 0.15)) (rpn.ast/symbol-AST "NP")) (rpn.ast/multiply-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.34) (rpn.ast/symbol-AST "uU")) (rpn.ast/number-AST 1.91))))) (rpn.ast/number-AST 0.3))) (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.69) (rpn.ast/symbol-AST "Jw")) (rpn.ast/number-AST 1.62))))] ["xH % uU * 1.86 % 0.39" (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "xH") (rpn.ast/symbol-AST "uU")) (rpn.ast/number-AST 1.86)) (rpn.ast/number-AST 0.39))] ["jY" (rpn.ast/symbol-AST "jY")] ["QJ" (rpn.ast/symbol-AST "QJ")] ["( ( 1.92 + nR ) % lr - ( ( 1.94 * 1.34 min AQ ^ 1.98 ) + ( ( ( ( ( ( 1.82 min ( 1.00 + ( Ys - ( eE ^ ( jv + ( 1.52 ) * aO ) ) ^ oz ) ) * ( ( FF ) + tE ) min ( NB / Rz ) ) / 0.76 ) ^ TV max Fu min 0.46 ) * Cr + HR ^ Iv ) max 1.97 % ( ( 1.25 % ( 0.14 ) * ( Kc ) % 0.86 ) - 1.47 + ( ( 1.54 + 1.52 / ( FP - cp max ( 1.66 / zM ) min 1.47 ) * 1.01 ) ^ ( Ow ) min AY ) ) ^ ( ( 0.24 ) % ( ss ) ^ ( cL ^ Bm ) % 1.38 ) ) min 0.01 - 1.12 ) ) max 0.30 ) + ts % 1.72" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.92) (rpn.ast/symbol-AST "nR")) (rpn.ast/symbol-AST "lr")) (rpn.ast/max-AST (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.94) (rpn.ast/min-AST (rpn.ast/number-AST 1.34) (rpn.ast/symbol-AST "AQ"))) (rpn.ast/number-AST 1.98)) (rpn.ast/subtract-AST (rpn.ast/min-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.82) (rpn.ast/add-AST (rpn.ast/number-AST 1.0) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Ys") (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "eE") (rpn.ast/add-AST (rpn.ast/symbol-AST "jv") (rpn.ast/multiply-AST (rpn.ast/number-AST 1.52) (rpn.ast/symbol-AST "aO")))) (rpn.ast/symbol-AST "oz"))))) (rpn.ast/min-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "FF") (rpn.ast/symbol-AST "tE")) (rpn.ast/divide-AST (rpn.ast/symbol-AST "NB") (rpn.ast/symbol-AST "Rz")))) (rpn.ast/number-AST 0.76)) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "TV") (rpn.ast/symbol-AST "Fu")) (rpn.ast/number-AST 0.46))) (rpn.ast/symbol-AST "Cr")) (rpn.ast/power-AST (rpn.ast/symbol-AST "HR") (rpn.ast/symbol-AST "Iv"))) (rpn.ast/number-AST 1.97)) (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.25) (rpn.ast/number-AST 0.14)) (rpn.ast/symbol-AST "Kc")) (rpn.ast/number-AST 0.86)) (rpn.ast/number-AST 1.47)) (rpn.ast/power-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.54) (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.52) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "FP") (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "cp") (rpn.ast/divide-AST (rpn.ast/number-AST 1.66) (rpn.ast/symbol-AST "zM"))) (rpn.ast/number-AST 1.47)))) (rpn.ast/number-AST 1.01))) (rpn.ast/min-AST (rpn.ast/symbol-AST "Ow") (rpn.ast/symbol-AST "AY"))))) (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.24) (rpn.ast/symbol-AST "ss")) (rpn.ast/power-AST (rpn.ast/symbol-AST "cL") (rpn.ast/symbol-AST "Bm"))) (rpn.ast/number-AST 1.38))) (rpn.ast/number-AST 0.01)) (rpn.ast/number-AST 1.12))) (rpn.ast/number-AST 0.3))) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "ts") (rpn.ast/number-AST 1.72)))] ["0.29 ^ ( ( 1.11 / rH + Xa ^ 1.33 ) max oy max 1.45 max Xr ) + ( NL - 1.51 )" (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/number-AST 0.29) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.11) (rpn.ast/symbol-AST "rH")) (rpn.ast/power-AST (rpn.ast/symbol-AST "Xa") (rpn.ast/number-AST 1.33))) (rpn.ast/symbol-AST "oy")) (rpn.ast/number-AST 1.45)) (rpn.ast/symbol-AST "Xr"))) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "NL") (rpn.ast/number-AST 1.51)))] ["0.18 min 0.43 * 0.06" (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.18) (rpn.ast/number-AST 0.43)) (rpn.ast/number-AST 0.06))] ["( ( ( ( wW min to + 0.24 % Uv ) ^ Mg / 1.26 ) ) % ( 1.73 ) - Qr ) / ( HA - Pn - 0.75 ^ VW )" (rpn.ast/divide-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/add-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "wW") (rpn.ast/symbol-AST "to")) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.24) (rpn.ast/symbol-AST "Uv"))) (rpn.ast/symbol-AST "Mg")) (rpn.ast/number-AST 1.26)) (rpn.ast/number-AST 1.73)) (rpn.ast/symbol-AST "Qr")) (rpn.ast/subtract-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "HA") (rpn.ast/symbol-AST "Pn")) (rpn.ast/power-AST (rpn.ast/number-AST 0.75) (rpn.ast/symbol-AST "VW"))))] ["Jj" (rpn.ast/symbol-AST "Jj")] ["MI + ( 1.72 % ( Xj ^ ( 0.97 min 1.05 ^ gA ) % QA max Qq ) ^ zB + 1.46 )" (rpn.ast/add-AST (rpn.ast/symbol-AST "MI") (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.72) (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "Xj") (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.97) (rpn.ast/number-AST 1.05)) (rpn.ast/symbol-AST "gA"))) (rpn.ast/max-AST (rpn.ast/symbol-AST "QA") (rpn.ast/symbol-AST "Qq")))) (rpn.ast/symbol-AST "zB")) (rpn.ast/number-AST 1.46)))] ["( 1.54 max ( 1.47 min 1.21 + 1.04 ) % 1.51 + wO ) + gN ^ 1.71 * ge" (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.54) (rpn.ast/add-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.47) (rpn.ast/number-AST 1.21)) (rpn.ast/number-AST 1.04))) (rpn.ast/number-AST 1.51)) (rpn.ast/symbol-AST "wO")) (rpn.ast/multiply-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "gN") (rpn.ast/number-AST 1.71)) (rpn.ast/symbol-AST "ge")))] ["( 0.03 / ( ( 0.98 % hN - DI ) ) min od ) + 1.39 % ( ph min sX ) % 0.38" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.03) (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.98) (rpn.ast/symbol-AST "hN")) (rpn.ast/symbol-AST "DI")) (rpn.ast/symbol-AST "od"))) (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.39) (rpn.ast/min-AST (rpn.ast/symbol-AST "ph") (rpn.ast/symbol-AST "sX"))) (rpn.ast/number-AST 0.38)))] ["( WH ^ 1.85 )" (rpn.ast/power-AST (rpn.ast/symbol-AST "WH") (rpn.ast/number-AST 1.85))] ["( Gq % OA / ew )" (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Gq") (rpn.ast/symbol-AST "OA")) (rpn.ast/symbol-AST "ew"))] ["dO * ( 0.16 max 1.21 % QF ^ qa ) / BS" (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "dO") (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/number-AST 0.16) (rpn.ast/number-AST 1.21)) (rpn.ast/symbol-AST "QF")) (rpn.ast/symbol-AST "qa"))) (rpn.ast/symbol-AST "BS"))] ["wX - 0.77" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "wX") (rpn.ast/number-AST 0.77))] ["( ( Ay * ( 0.50 ) max BA ^ ( 1.80 ) ) - 0.64 ) * ( Ui / 1.69 - xC ) % ( UN + 1.70 min 0.02 min JR ) / 1.85" (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Ay") (rpn.ast/max-AST (rpn.ast/number-AST 0.5) (rpn.ast/symbol-AST "BA"))) (rpn.ast/number-AST 1.8)) (rpn.ast/number-AST 0.64)) (rpn.ast/subtract-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "Ui") (rpn.ast/number-AST 1.69)) (rpn.ast/symbol-AST "xC"))) (rpn.ast/add-AST (rpn.ast/symbol-AST "UN") (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.7) (rpn.ast/number-AST 0.02)) (rpn.ast/symbol-AST "JR")))) (rpn.ast/number-AST 1.85))] ["( it max FE / 0.73 - ( 0.33 % ( 0.15 * ( ( ( 0.01 max 1.21 + Bq % 1.69 ) - Ve ) - ( nY max 0.17 + vz / ( QC ) ) ) ) / ( 0.47 % 1.57 + ( 1.01 - 0.21 ) ) ) ) + 1.55 ^ ( 1.54 max SF + fB + ( ( ym ) ) ) - ln" (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/divide-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "it") (rpn.ast/symbol-AST "FE")) (rpn.ast/number-AST 0.73)) (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.33) (rpn.ast/multiply-AST (rpn.ast/number-AST 0.15) (rpn.ast/subtract-AST (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 0.01) (rpn.ast/number-AST 1.21)) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Bq") (rpn.ast/number-AST 1.69))) (rpn.ast/symbol-AST "Ve")) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "nY") (rpn.ast/number-AST 0.17)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "vz") (rpn.ast/symbol-AST "QC")))))) (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.47) (rpn.ast/number-AST 1.57)) (rpn.ast/subtract-AST (rpn.ast/number-AST 1.01) (rpn.ast/number-AST 0.21))))) (rpn.ast/power-AST (rpn.ast/number-AST 1.55) (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.54) (rpn.ast/symbol-AST "SF")) (rpn.ast/symbol-AST "fB")) (rpn.ast/symbol-AST "ym")))) (rpn.ast/symbol-AST "ln"))] ["0.90" (rpn.ast/number-AST 0.9)] ["OP" (rpn.ast/symbol-AST "OP")] ["0.38 / ( rU / uh % 0.25 )" (rpn.ast/divide-AST (rpn.ast/number-AST 0.38) (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "rU") (rpn.ast/symbol-AST "uh")) (rpn.ast/number-AST 0.25)))] ["( uz )" (rpn.ast/symbol-AST "uz")] ["vF ^ ( jw ) / kR" (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "vF") (rpn.ast/symbol-AST "jw")) (rpn.ast/symbol-AST "kR"))] ["gk" (rpn.ast/symbol-AST "gk")] ["( ( BU ) max ( lo ^ VY ) * ( ( ( 1.94 % 0.62 % ( 0.51 % Qy max ( ( Ag ^ wh - 0.19 ) ) min ( ( gP ^ ( 1.96 ) ) min Ur ) ) ) + ( 0.61 % ( HZ ) * ( 0.56 min dr ^ 0.64 ) ) ) * cu max OU min 1.62 ) + 1.74 )" (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "BU") (rpn.ast/power-AST (rpn.ast/symbol-AST "lo") (rpn.ast/symbol-AST "VY"))) (rpn.ast/multiply-AST (rpn.ast/add-AST (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.94) (rpn.ast/number-AST 0.62)) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.51) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Qy") (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "Ag") (rpn.ast/symbol-AST "wh")) (rpn.ast/number-AST 0.19))) (rpn.ast/min-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "gP") (rpn.ast/number-AST 1.96)) (rpn.ast/symbol-AST "Ur"))))) (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.61) (rpn.ast/symbol-AST "HZ")) (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.56) (rpn.ast/symbol-AST "dr")) (rpn.ast/number-AST 0.64)))) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "cu") (rpn.ast/symbol-AST "OU")) (rpn.ast/number-AST 1.62)))) (rpn.ast/number-AST 1.74))] ["( ft ) / Jh + Gt * AP" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "ft") (rpn.ast/symbol-AST "Jh")) (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Gt") (rpn.ast/symbol-AST "AP")))] ["Zw - CA + Co" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Zw") (rpn.ast/symbol-AST "CA")) (rpn.ast/symbol-AST "Co"))] ["( 1.27 ) - NT" (rpn.ast/subtract-AST (rpn.ast/number-AST 1.27) (rpn.ast/symbol-AST "NT"))] ["FI min KU % ( sQ * 1.84 )" (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "FI") (rpn.ast/symbol-AST "KU")) (rpn.ast/multiply-AST (rpn.ast/symbol-AST "sQ") (rpn.ast/number-AST 1.84)))] ["( 1.73 ) ^ cE / Uv" (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.73) (rpn.ast/symbol-AST "cE")) (rpn.ast/symbol-AST "Uv"))] ["0.98 / 1.19 / ( Wk - lG % ( 1.06 ^ Mv ) % xf ) + HS" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.98) (rpn.ast/number-AST 1.19)) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Wk") (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "lG") (rpn.ast/power-AST (rpn.ast/number-AST 1.06) (rpn.ast/symbol-AST "Mv"))) (rpn.ast/symbol-AST "xf")))) (rpn.ast/symbol-AST "HS"))] ["1.64 % dX" (rpn.ast/modulo-AST (rpn.ast/number-AST 1.64) (rpn.ast/symbol-AST "dX"))] ["( 1.04 max HD % nU )" (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.04) (rpn.ast/symbol-AST "HD")) (rpn.ast/symbol-AST "nU"))] ["0.39" (rpn.ast/number-AST 0.39)] ["1.15 - KG + 0.85 % ( ( 1.71 ^ 0.43 min uL min 0.73 ) / ( ( Mo ) - lJ % ( ( ( ( 1.20 % ip ) - ( au ) ) - 1.29 max AS max 1.21 ) ^ 1.02 ) ) - pQ )" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.15) (rpn.ast/symbol-AST "KG")) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.85) (rpn.ast/subtract-AST (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.71) (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.43) (rpn.ast/symbol-AST "uL")) (rpn.ast/number-AST 0.73))) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Mo") (rpn.ast/modulo-AST (rpn.ast/symbol-AST "lJ") (rpn.ast/power-AST (rpn.ast/subtract-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.2) (rpn.ast/symbol-AST "ip")) (rpn.ast/symbol-AST "au")) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.29) (rpn.ast/symbol-AST "AS")) (rpn.ast/number-AST 1.21))) (rpn.ast/number-AST 1.02))))) (rpn.ast/symbol-AST "pQ"))))] ["( ( ( dp - 0.16 / 1.23 ) - 1.54 min 0.82 % ( wI % uP ) ) )" (rpn.ast/subtract-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "dp") (rpn.ast/divide-AST (rpn.ast/number-AST 0.16) (rpn.ast/number-AST 1.23))) (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.54) (rpn.ast/number-AST 0.82)) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "wI") (rpn.ast/symbol-AST "uP"))))] ["( 1.15 max 1.04 + 1.15 ) - 1.86" (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.15) (rpn.ast/number-AST 1.04)) (rpn.ast/number-AST 1.15)) (rpn.ast/number-AST 1.86))] ["1.44 / 0.68" (rpn.ast/divide-AST (rpn.ast/number-AST 1.44) (rpn.ast/number-AST 0.68))] ["wO % NV" (rpn.ast/modulo-AST (rpn.ast/symbol-AST "wO") (rpn.ast/symbol-AST "NV"))] ["Wp * ys min 0.46 + ( ( ( ( 1.32 ^ Bw ) max 1.70 - ( ( KL min ( ( 1.23 / ( 1.92 ) / ( 0.30 ) % ( zq + bj ) ) - ( ( hO * Bz % ( Iv + ( ( YE ) % rI - 1.24 ) ) ) min IA ) % ( lO max ( ( nE ^ Mu + 1.53 ) - kl min 1.31 min hb ) * oX % ( ( 0.74 % 0.80 - aC ) ) ) ) * 1.06 ) ) min 1.68 ) / ( 0.83 - 1.71 * 0.45 ) max 0.84 min ( ( ( 1.30 % 1.50 - kb ) min 0.95 / ( 0.21 % hg ) ) max 0.20 ) ) / ( ( ( 1.83 * Ks - 0.29 ) * Ua % 1.92 % ( ( 0.24 + dL / Fn ) ) ) max 1.00 % 0.14 ) + 1.12 )" (rpn.ast/add-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Wp") (rpn.ast/min-AST (rpn.ast/symbol-AST "ys") (rpn.ast/number-AST 0.46))) (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/subtract-AST (rpn.ast/max-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.32) (rpn.ast/symbol-AST "Bw")) (rpn.ast/number-AST 1.7)) (rpn.ast/min-AST (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "KL") (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.23) (rpn.ast/number-AST 1.92)) (rpn.ast/number-AST 0.3)) (rpn.ast/add-AST (rpn.ast/symbol-AST "zq") (rpn.ast/symbol-AST "bj"))) (rpn.ast/modulo-AST (rpn.ast/min-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "hO") (rpn.ast/symbol-AST "Bz")) (rpn.ast/add-AST (rpn.ast/symbol-AST "Iv") (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "YE") (rpn.ast/symbol-AST "rI")) (rpn.ast/number-AST 1.24)))) (rpn.ast/symbol-AST "IA")) (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "lO") (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "nE") (rpn.ast/symbol-AST "Mu")) (rpn.ast/number-AST 1.53)) (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "kl") (rpn.ast/number-AST 1.31)) (rpn.ast/symbol-AST "hb")))) (rpn.ast/symbol-AST "oX")) (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.74) (rpn.ast/number-AST 0.8)) (rpn.ast/symbol-AST "aC")))))) (rpn.ast/number-AST 1.06)) (rpn.ast/number-AST 1.68))) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 0.83) (rpn.ast/multiply-AST (rpn.ast/number-AST 1.71) (rpn.ast/number-AST 0.45))) (rpn.ast/number-AST 0.84)) (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.3) (rpn.ast/number-AST 1.5)) (rpn.ast/symbol-AST "kb")) (rpn.ast/number-AST 0.95)) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.21) (rpn.ast/symbol-AST "hg"))) (rpn.ast/number-AST 0.2)))) (rpn.ast/modulo-AST (rpn.ast/max-AST (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.83) (rpn.ast/symbol-AST "Ks")) (rpn.ast/number-AST 0.29)) (rpn.ast/symbol-AST "Ua")) (rpn.ast/number-AST 1.92)) (rpn.ast/add-AST (rpn.ast/number-AST 0.24) (rpn.ast/divide-AST (rpn.ast/symbol-AST "dL") (rpn.ast/symbol-AST "Fn")))) (rpn.ast/number-AST 1.0)) (rpn.ast/number-AST 0.14))) (rpn.ast/number-AST 1.12)))] ["JB" (rpn.ast/symbol-AST "JB")] ["aY" (rpn.ast/symbol-AST "aY")] ["0.92 * ( FX ) / Ml / ( 0.89 % ( Or max wM ) max 0.01 )" (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 0.92) (rpn.ast/symbol-AST "FX")) (rpn.ast/symbol-AST "Ml")) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.89) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/symbol-AST "Or") (rpn.ast/symbol-AST "wM")) (rpn.ast/number-AST 0.01))))] ["( tL + 1.37 ) + ( ( Pw + 0.87 - ( uC * Bb * no min ( 1.88 ^ ( 1.09 max ( ( 0.15 min ( 0.80 ) ^ uM max 1.99 ) * ( 0.17 ^ 0.54 min 0.24 + 0.27 ) - Ee * dd ) + 1.52 ^ vG ) + ( ( ( ( uU / tD ) * ( HT ^ 1.62 % cR - 0.14 ) ) min Ie / 1.84 ) * Zf % jO ) ) ) ) ) + ( CT min la * LH )" (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "tL") (rpn.ast/number-AST 1.37)) (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/symbol-AST "Pw") (rpn.ast/number-AST 0.87)) (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "uC") (rpn.ast/symbol-AST "Bb")) (rpn.ast/min-AST (rpn.ast/symbol-AST "no") (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.88) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.09) (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/number-AST 0.15) (rpn.ast/number-AST 0.8)) (rpn.ast/max-AST (rpn.ast/symbol-AST "uM") (rpn.ast/number-AST 1.99))) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/number-AST 0.17) (rpn.ast/min-AST (rpn.ast/number-AST 0.54) (rpn.ast/number-AST 0.24))) (rpn.ast/number-AST 0.27))) (rpn.ast/multiply-AST (rpn.ast/symbol-AST "Ee") (rpn.ast/symbol-AST "dd")))) (rpn.ast/power-AST (rpn.ast/number-AST 1.52) (rpn.ast/symbol-AST "vG")))) (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "uU") (rpn.ast/symbol-AST "tD")) (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "HT") (rpn.ast/number-AST 1.62)) (rpn.ast/symbol-AST "cR")) (rpn.ast/number-AST 0.14))) (rpn.ast/symbol-AST "Ie")) (rpn.ast/number-AST 1.84)) (rpn.ast/symbol-AST "Zf")) (rpn.ast/symbol-AST "jO"))))))) (rpn.ast/multiply-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "CT") (rpn.ast/symbol-AST "la")) (rpn.ast/symbol-AST "LH")))] ["Jo % Qs" (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Jo") (rpn.ast/symbol-AST "Qs"))] ["1.80 - ( Wj - 1.70 + ( TE / ( qi min ( ( sP / ( ( DM ) - 1.28 ) * 0.45 % 1.00 ) max 1.74 / 0.83 ^ ( ( ( ( 1.09 - ( ( ( ( ( 0.45 + tL + 1.20 ) ) ) + 1.30 * TC / ( ( ( ( Se ) - ( 1.19 ) ) ^ FQ / HI ^ 0.31 ) + 0.94 ) ) % Ih * 1.35 ^ ( 1.59 % 0.40 max ( ( 1.67 max bk ) max ( 0.24 % ( GF + 1.17 % qa ^ 1.28 ) ^ ( NY ^ 0.11 % ( Bg - 1.20 ) ) ) ) ) ) / Ia % ( ( 1.77 min gB / ( ( ( ( ( ov ) / 0.45 / LF - 1.50 ) min 0.57 ) min Tq ^ 0.68 ) ) ) max hd ) ) % 0.34 ^ ( 1.96 ) ) + 0.31 ) ) ) - tQ ^ XB ) ) ) ^ 0.40 + ( ( 0.30 / ( 0.66 max in + 1.90 ) * ( 1.99 / Sl % 1.62 ) / 0.47 ) ^ mc - 1.82 + 0.22 )" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.8) (rpn.ast/power-AST (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Wj") (rpn.ast/number-AST 1.7)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "TE") (rpn.ast/subtract-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "qi") (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/max-AST (rpn.ast/modulo-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "sP") (rpn.ast/subtract-AST (rpn.ast/symbol-AST "DM") (rpn.ast/number-AST 1.28))) (rpn.ast/number-AST 0.45)) (rpn.ast/number-AST 1.0)) (rpn.ast/number-AST 1.74)) (rpn.ast/number-AST 0.83)) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.09) (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/number-AST 0.45) (rpn.ast/symbol-AST "tL")) (rpn.ast/number-AST 1.2)) (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.3) (rpn.ast/symbol-AST "TC")) (rpn.ast/add-AST (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/power-AST (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Se") (rpn.ast/number-AST 1.19)) (rpn.ast/symbol-AST "FQ")) (rpn.ast/symbol-AST "HI")) (rpn.ast/number-AST 0.31)) (rpn.ast/number-AST 0.94)))) (rpn.ast/symbol-AST "Ih")) (rpn.ast/number-AST 1.35)) (rpn.ast/modulo-AST (rpn.ast/number-AST 1.59) (rpn.ast/max-AST (rpn.ast/number-AST 0.4) (rpn.ast/max-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.67) (rpn.ast/symbol-AST "bk")) (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.24) (rpn.ast/add-AST (rpn.ast/symbol-AST "GF") (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.17) (rpn.ast/symbol-AST "qa")) (rpn.ast/number-AST 1.28)))) (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/symbol-AST "NY") (rpn.ast/number-AST 0.11)) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Bg") (rpn.ast/number-AST 1.2)))))))) (rpn.ast/symbol-AST "Ia")) (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/min-AST (rpn.ast/number-AST 1.77) (rpn.ast/symbol-AST "gB")) (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/min-AST (rpn.ast/subtract-AST (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "ov") (rpn.ast/number-AST 0.45)) (rpn.ast/symbol-AST "LF")) (rpn.ast/number-AST 1.5)) (rpn.ast/number-AST 0.57)) (rpn.ast/symbol-AST "Tq")) (rpn.ast/number-AST 0.68))) (rpn.ast/symbol-AST "hd")))) (rpn.ast/number-AST 0.34)) (rpn.ast/number-AST 1.96)) (rpn.ast/number-AST 0.31)))) (rpn.ast/power-AST (rpn.ast/symbol-AST "tQ") (rpn.ast/symbol-AST "XB"))))) (rpn.ast/number-AST 0.4))) (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/divide-AST (rpn.ast/number-AST 0.3) (rpn.ast/add-AST (rpn.ast/max-AST (rpn.ast/number-AST 0.66) (rpn.ast/symbol-AST "in")) (rpn.ast/number-AST 1.9))) (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.99) (rpn.ast/symbol-AST "Sl")) (rpn.ast/number-AST 1.62))) (rpn.ast/number-AST 0.47)) (rpn.ast/symbol-AST "mc")) (rpn.ast/number-AST 1.82)) (rpn.ast/number-AST 0.22)))] ["( 1.23 * HT min 1.16 ) - Oc + 1.44" (rpn.ast/add-AST (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.23) (rpn.ast/min-AST (rpn.ast/symbol-AST "HT") (rpn.ast/number-AST 1.16))) (rpn.ast/symbol-AST "Oc")) (rpn.ast/number-AST 1.44))] ["( 1.99 )" (rpn.ast/number-AST 1.99)] ["Zu" (rpn.ast/symbol-AST "Zu")] ["0.53" (rpn.ast/number-AST 0.53)] ["Nc - PW" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Nc") (rpn.ast/symbol-AST "PW"))] ["kl * ww - YI" (rpn.ast/subtract-AST (rpn.ast/multiply-AST (rpn.ast/symbol-AST "kl") (rpn.ast/symbol-AST "ww")) (rpn.ast/symbol-AST "YI"))] ["1.93 max 1.41 ^ ( ( ( 0.90 % ( 1.40 / 0.79 ^ 0.76 min vt ) ) - ( 0.96 ^ 0.18 ) ) / nl / ( cn % 1.22 ) )" (rpn.ast/power-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.93) (rpn.ast/number-AST 1.41)) (rpn.ast/divide-AST (rpn.ast/divide-AST (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.9) (rpn.ast/power-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.4) (rpn.ast/number-AST 0.79)) (rpn.ast/min-AST (rpn.ast/number-AST 0.76) (rpn.ast/symbol-AST "vt")))) (rpn.ast/power-AST (rpn.ast/number-AST 0.96) (rpn.ast/number-AST 0.18))) (rpn.ast/symbol-AST "nl")) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "cn") (rpn.ast/number-AST 1.22))))] ["wo / 0.35 + WT / oj" (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/symbol-AST "wo") (rpn.ast/number-AST 0.35)) (rpn.ast/divide-AST (rpn.ast/symbol-AST "WT") (rpn.ast/symbol-AST "oj")))] ["( 1.42 % mL ) % iF max rI % ( Gb )" (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.42) (rpn.ast/symbol-AST "mL")) (rpn.ast/max-AST (rpn.ast/symbol-AST "iF") (rpn.ast/symbol-AST "rI"))) (rpn.ast/symbol-AST "Gb"))] ["0.08 ^ KU max 2.00" (rpn.ast/power-AST (rpn.ast/number-AST 0.08) (rpn.ast/max-AST (rpn.ast/symbol-AST "KU") (rpn.ast/number-AST 2.0)))] ["0.33 % 0.51 * 0.42" (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.33) (rpn.ast/number-AST 0.51)) (rpn.ast/number-AST 0.42))] ["rj % rw min ( Et )" (rpn.ast/modulo-AST (rpn.ast/symbol-AST "rj") (rpn.ast/min-AST (rpn.ast/symbol-AST "rw") (rpn.ast/symbol-AST "Et")))] ["( 1.17 ^ 1.70 ) % 0.60 - 1.33" (rpn.ast/subtract-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.17) (rpn.ast/number-AST 1.7)) (rpn.ast/number-AST 0.6)) (rpn.ast/number-AST 1.33))] ["tp min 0.60" (rpn.ast/min-AST (rpn.ast/symbol-AST "tp") (rpn.ast/number-AST 0.6))] ["Zy" (rpn.ast/symbol-AST "Zy")] ["pT min qW ^ Ul" (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "pT") (rpn.ast/symbol-AST "qW")) (rpn.ast/symbol-AST "Ul"))] ["( 1.36 ^ ET ) ^ Uz" (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.36) (rpn.ast/symbol-AST "ET")) (rpn.ast/symbol-AST "Uz"))] ["( ( 0.16 - 0.44 / LC ) ) ^ vE" (rpn.ast/power-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 0.16) (rpn.ast/divide-AST (rpn.ast/number-AST 0.44) (rpn.ast/symbol-AST "LC"))) (rpn.ast/symbol-AST "vE"))] ["Es min Fl ^ 0.78 ^ 0.60" (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "Es") (rpn.ast/symbol-AST "Fl")) (rpn.ast/number-AST 0.78)) (rpn.ast/number-AST 0.6))] ["1.50" (rpn.ast/number-AST 1.5)] ["Tn + ( 0.64 ) min 0.62" (rpn.ast/add-AST (rpn.ast/symbol-AST "Tn") (rpn.ast/min-AST (rpn.ast/number-AST 0.64) (rpn.ast/number-AST 0.62)))] ["Pf" (rpn.ast/symbol-AST "Pf")] ["( ( ( 1.40 ) - ( 1.75 ) max Vq ) * ( UL * 1.74 min ( FP min mV max PQ ) ) / NJ + 1.61 ) / 0.72 % 0.34 max fQ" (rpn.ast/modulo-AST (rpn.ast/divide-AST (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/subtract-AST (rpn.ast/number-AST 1.4) (rpn.ast/max-AST (rpn.ast/number-AST 1.75) (rpn.ast/symbol-AST "Vq"))) (rpn.ast/multiply-AST (rpn.ast/symbol-AST "UL") (rpn.ast/min-AST (rpn.ast/number-AST 1.74) (rpn.ast/max-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "FP") (rpn.ast/symbol-AST "mV")) (rpn.ast/symbol-AST "PQ"))))) (rpn.ast/symbol-AST "NJ")) (rpn.ast/number-AST 1.61)) (rpn.ast/number-AST 0.72)) (rpn.ast/max-AST (rpn.ast/number-AST 0.34) (rpn.ast/symbol-AST "fQ")))] ["( 0.42 * ( 0.23 ^ ( fK min bR - ii % ( 1.80 / 1.83 ) ) ) )" (rpn.ast/multiply-AST (rpn.ast/number-AST 0.42) (rpn.ast/power-AST (rpn.ast/number-AST 0.23) (rpn.ast/subtract-AST (rpn.ast/min-AST (rpn.ast/symbol-AST "fK") (rpn.ast/symbol-AST "bR")) (rpn.ast/modulo-AST (rpn.ast/symbol-AST "ii") (rpn.ast/divide-AST (rpn.ast/number-AST 1.8) (rpn.ast/number-AST 1.83))))))] ["( 1.82 / 1.28 ) max ( Hj - 1.41 )" (rpn.ast/max-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.82) (rpn.ast/number-AST 1.28)) (rpn.ast/subtract-AST (rpn.ast/symbol-AST "Hj") (rpn.ast/number-AST 1.41)))] ["0.07 % 1.08 * 1.14" (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 0.07) (rpn.ast/number-AST 1.08)) (rpn.ast/number-AST 1.14))] ["Nt % ( 0.11 ^ LM ) * Pj" (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/symbol-AST "Nt") (rpn.ast/power-AST (rpn.ast/number-AST 0.11) (rpn.ast/symbol-AST "LM"))) (rpn.ast/symbol-AST "Pj"))] ["dD - ( ( 1.93 + ( 1.19 % ZV ^ ( 1.43 * nV * mK ) ) ^ 1.09 ) + ( 0.62 ) % ( ( 1.69 / 1.52 max tJ ) + ( 0.62 ) ) - ( 1.77 / 1.64 max ND min qK ) ) / 1.28 min rN" (rpn.ast/subtract-AST (rpn.ast/symbol-AST "dD") (rpn.ast/divide-AST (rpn.ast/subtract-AST (rpn.ast/add-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.93) (rpn.ast/power-AST (rpn.ast/power-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.19) (rpn.ast/symbol-AST "ZV")) (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.43) (rpn.ast/symbol-AST "nV")) (rpn.ast/symbol-AST "mK"))) (rpn.ast/number-AST 1.09))) (rpn.ast/modulo-AST (rpn.ast/number-AST 0.62) (rpn.ast/add-AST (rpn.ast/divide-AST (rpn.ast/number-AST 1.69) (rpn.ast/max-AST (rpn.ast/number-AST 1.52) (rpn.ast/symbol-AST "tJ"))) (rpn.ast/number-AST 0.62)))) (rpn.ast/divide-AST (rpn.ast/number-AST 1.77) (rpn.ast/min-AST (rpn.ast/max-AST (rpn.ast/number-AST 1.64) (rpn.ast/symbol-AST "ND")) (rpn.ast/symbol-AST "qK")))) (rpn.ast/min-AST (rpn.ast/number-AST 1.28) (rpn.ast/symbol-AST "rN"))))] ["lu" (rpn.ast/symbol-AST "lu")] ["( 0.79 )" (rpn.ast/number-AST 0.79)] ["( ( ( 1.01 ) + 1.63 % Wg / no ) * lY )" (rpn.ast/multiply-AST (rpn.ast/add-AST (rpn.ast/number-AST 1.01) (rpn.ast/divide-AST (rpn.ast/modulo-AST (rpn.ast/number-AST 1.63) (rpn.ast/symbol-AST "Wg")) (rpn.ast/symbol-AST "no"))) (rpn.ast/symbol-AST "lY"))] ["( ( Rq ) ) ^ 1.64" (rpn.ast/power-AST (rpn.ast/symbol-AST "Rq") (rpn.ast/number-AST 1.64))] ["1.61" (rpn.ast/number-AST 1.61)] ["1.74 * 0.16 * ( 1.96 ^ 0.58 % 0.85 * oc ) / ( 0.52 )" (rpn.ast/divide-AST (rpn.ast/multiply-AST (rpn.ast/multiply-AST (rpn.ast/number-AST 1.74) (rpn.ast/number-AST 0.16)) (rpn.ast/multiply-AST (rpn.ast/modulo-AST (rpn.ast/power-AST (rpn.ast/number-AST 1.96) (rpn.ast/number-AST 0.58)) (rpn.ast/number-AST 0.85)) (rpn.ast/symbol-AST "oc"))) (rpn.ast/number-AST 0.52))] ["0.22" (rpn.ast/number-AST 0.22)]))
[ { "context": ";;;;;;;;;;;;;;\n\n\n(def config {:user \"machtest\"\n :database \"machtest_dev\"\n ", "end": 403, "score": 0.9966129660606384, "start": 395, "tag": "USERNAME", "value": "machtest" }, { "context": " \"machtest_dev\"\n :password \"testdb\"\n :host \"localhost\"\n ", "end": 491, "score": 0.9992709159851074, "start": 485, "tag": "PASSWORD", "value": "testdb" }, { "context": "base (:db-name env)\n :password (:db-password env)\n :host (:db-host env)\n :port ", "end": 818, "score": 0.9411934018135071, "start": 801, "tag": "PASSWORD", "value": "(:db-password env" }, { "context": " coercion using node-pg-types (https://github.com/brianc/node-pg-types)\n;;\n;; This depends on Postgres' da", "end": 1102, "score": 0.9992650151252747, "start": 1096, "tag": "USERNAME", "value": "brianc" } ]
src/machtest/db.cljs
macchiato-framework/macchiato-db-scratchpad
2
(ns machtest.db (:require [machtest.config :refer [env]] [macchiato.async.futures :refer [wait wrap-future]] [mount.core :as mount :refer [defstate]])) ;;;;;;;;;;;;;;;;;;;;; ;;;; Requires ;;;;;;;;;;;;;;;;;;;;; (def pg (js/require "pg")) (def pg-types (.-types pg)) ;;;;;;;;;;;;;;;;;;;;; ;;;; Configuration ;;;;;;;;;;;;;;;;;;;;; (def config {:user "machtest" :database "machtest_dev" :password "testdb" :host "localhost" :port 5432 :max 20 :idleTimeoutMillis 10000}) ; Need to still load env settings into the environment #_{:user (:db-user env) :database (:db-name env) :password (:db-password env) :host (:db-host env) :port (or (:db-port env) 5432) :max (or (:db-max-connections env) 20) :idleTimeoutMillis (or (:db-idle-timeout env) 10000)} ;; Going to configure type coercion using node-pg-types (https://github.com/brianc/node-pg-types) ;; ;; This depends on Postgres' data type ids: https://doxygen.postgresql.org/include_2catalog_2pg__type_8h.html (def TYPANALYZE 20) (.setTypeParser pg-types TYPANALYZE (fn [val] (let [as-float (js/parseFloat val)] ;; The reason I need to do this now is that querying for a "count" is ;; returning a string. Looking at the metadata it's a data type of 20, ;; which is "analyze". ;; ;; https://doxygen.postgresql.org/include_2catalog_2pg__type_8h.html#ab5abe002baf3cb0ccf3f98008c72ca8a ;; ;; Javascript numeric parsing is wonky, though. ;; ;; (js/parseInt "8Ricardo") is 8. ;; (js/parseFloat "8.5.9Tomato") is 8.5 ;; ;; ಠ_ಠ ;; ;; Hopefully we won't get back any TYPANALYZE result that starts with a ;; number but is not actually numeric. Requires more experimentation. (cond (nil? val) nil (js/isNaN as-float) val (number? as-float) as-float :default val)))) (def TYPUUIDOID 2950) (.setTypeParser pg-types TYPUUIDOID #(cljs.core/uuid %)) ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Functions and state ;;;;;;;;;;;;;;;;;;;;;;;;;;; (defstate ^:dynamic db-pool :start (wrap-future (doto (pg.Pool. (clj->js config)) (.on "error" #(.error js/console "Conn error" %1 %2)) (.on "connect" #(.log js/console "Connection!")) (.on "acquire" #(.log js/console "Acquired!")))) :end (.end @db-pool)) (defn query-no-pool [query-string] (.wait (.query @db-pool query-string))) (defn with-transaction "Will initialize a client from the database pool, obtain a query-fn, and then invoke the function it receives with the query-fn as its argument. Every call to the query function will be waited on, to ensure we are executing them sequentially. The functions will be executed in a transaction, which will be rolled back in case of an exception. Any exception caught will be re-thrown. Returns the result of releasing the client." [f] (let [client (wait (.connect @db-pool)) ;; Wrapping the entire client causes an issue on repeated requests, ;; because it loses some references. Looks like what we get back from ;; the wrapping is a proxy. It's probably meant for wrapping modules ;; and not instances, but wrapping a single function works well. ;; ;; I'm thinking this might be doable in a single step with a ;; function called `wrap-future-method`, which returns not ;; just a future, but a function that invokes the future on a specific ;; object. Similar to the ;; ;; (.call q-future client qs (clj->js rest)) ;; ;; invocation below. I'd probably need a to pass both the object to ;; invoke it on and the method being future-ified, though, since ;; I don't think there's a way to get the object a function originally ;; came from. ;; ;; For now I'm keeping the semantics transparent. q-future (wrap-future client.query) query (fn [qs & rest] (wait (.call q-future client qs (clj->js rest))))] (try (query "BEGIN") (let [r (f query)] (query "COMMIT") r) (catch js/Error e (query "ROLLBACK") (throw e)) (finally (.release client))))) (defn single-query "Runs a single query in a transaction." [& rest] (with-transaction #(apply % rest)))
17165
(ns machtest.db (:require [machtest.config :refer [env]] [macchiato.async.futures :refer [wait wrap-future]] [mount.core :as mount :refer [defstate]])) ;;;;;;;;;;;;;;;;;;;;; ;;;; Requires ;;;;;;;;;;;;;;;;;;;;; (def pg (js/require "pg")) (def pg-types (.-types pg)) ;;;;;;;;;;;;;;;;;;;;; ;;;; Configuration ;;;;;;;;;;;;;;;;;;;;; (def config {:user "machtest" :database "machtest_dev" :password "<PASSWORD>" :host "localhost" :port 5432 :max 20 :idleTimeoutMillis 10000}) ; Need to still load env settings into the environment #_{:user (:db-user env) :database (:db-name env) :password <PASSWORD>) :host (:db-host env) :port (or (:db-port env) 5432) :max (or (:db-max-connections env) 20) :idleTimeoutMillis (or (:db-idle-timeout env) 10000)} ;; Going to configure type coercion using node-pg-types (https://github.com/brianc/node-pg-types) ;; ;; This depends on Postgres' data type ids: https://doxygen.postgresql.org/include_2catalog_2pg__type_8h.html (def TYPANALYZE 20) (.setTypeParser pg-types TYPANALYZE (fn [val] (let [as-float (js/parseFloat val)] ;; The reason I need to do this now is that querying for a "count" is ;; returning a string. Looking at the metadata it's a data type of 20, ;; which is "analyze". ;; ;; https://doxygen.postgresql.org/include_2catalog_2pg__type_8h.html#ab5abe002baf3cb0ccf3f98008c72ca8a ;; ;; Javascript numeric parsing is wonky, though. ;; ;; (js/parseInt "8Ricardo") is 8. ;; (js/parseFloat "8.5.9Tomato") is 8.5 ;; ;; ಠ_ಠ ;; ;; Hopefully we won't get back any TYPANALYZE result that starts with a ;; number but is not actually numeric. Requires more experimentation. (cond (nil? val) nil (js/isNaN as-float) val (number? as-float) as-float :default val)))) (def TYPUUIDOID 2950) (.setTypeParser pg-types TYPUUIDOID #(cljs.core/uuid %)) ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Functions and state ;;;;;;;;;;;;;;;;;;;;;;;;;;; (defstate ^:dynamic db-pool :start (wrap-future (doto (pg.Pool. (clj->js config)) (.on "error" #(.error js/console "Conn error" %1 %2)) (.on "connect" #(.log js/console "Connection!")) (.on "acquire" #(.log js/console "Acquired!")))) :end (.end @db-pool)) (defn query-no-pool [query-string] (.wait (.query @db-pool query-string))) (defn with-transaction "Will initialize a client from the database pool, obtain a query-fn, and then invoke the function it receives with the query-fn as its argument. Every call to the query function will be waited on, to ensure we are executing them sequentially. The functions will be executed in a transaction, which will be rolled back in case of an exception. Any exception caught will be re-thrown. Returns the result of releasing the client." [f] (let [client (wait (.connect @db-pool)) ;; Wrapping the entire client causes an issue on repeated requests, ;; because it loses some references. Looks like what we get back from ;; the wrapping is a proxy. It's probably meant for wrapping modules ;; and not instances, but wrapping a single function works well. ;; ;; I'm thinking this might be doable in a single step with a ;; function called `wrap-future-method`, which returns not ;; just a future, but a function that invokes the future on a specific ;; object. Similar to the ;; ;; (.call q-future client qs (clj->js rest)) ;; ;; invocation below. I'd probably need a to pass both the object to ;; invoke it on and the method being future-ified, though, since ;; I don't think there's a way to get the object a function originally ;; came from. ;; ;; For now I'm keeping the semantics transparent. q-future (wrap-future client.query) query (fn [qs & rest] (wait (.call q-future client qs (clj->js rest))))] (try (query "BEGIN") (let [r (f query)] (query "COMMIT") r) (catch js/Error e (query "ROLLBACK") (throw e)) (finally (.release client))))) (defn single-query "Runs a single query in a transaction." [& rest] (with-transaction #(apply % rest)))
true
(ns machtest.db (:require [machtest.config :refer [env]] [macchiato.async.futures :refer [wait wrap-future]] [mount.core :as mount :refer [defstate]])) ;;;;;;;;;;;;;;;;;;;;; ;;;; Requires ;;;;;;;;;;;;;;;;;;;;; (def pg (js/require "pg")) (def pg-types (.-types pg)) ;;;;;;;;;;;;;;;;;;;;; ;;;; Configuration ;;;;;;;;;;;;;;;;;;;;; (def config {:user "machtest" :database "machtest_dev" :password "PI:PASSWORD:<PASSWORD>END_PI" :host "localhost" :port 5432 :max 20 :idleTimeoutMillis 10000}) ; Need to still load env settings into the environment #_{:user (:db-user env) :database (:db-name env) :password PI:PASSWORD:<PASSWORD>END_PI) :host (:db-host env) :port (or (:db-port env) 5432) :max (or (:db-max-connections env) 20) :idleTimeoutMillis (or (:db-idle-timeout env) 10000)} ;; Going to configure type coercion using node-pg-types (https://github.com/brianc/node-pg-types) ;; ;; This depends on Postgres' data type ids: https://doxygen.postgresql.org/include_2catalog_2pg__type_8h.html (def TYPANALYZE 20) (.setTypeParser pg-types TYPANALYZE (fn [val] (let [as-float (js/parseFloat val)] ;; The reason I need to do this now is that querying for a "count" is ;; returning a string. Looking at the metadata it's a data type of 20, ;; which is "analyze". ;; ;; https://doxygen.postgresql.org/include_2catalog_2pg__type_8h.html#ab5abe002baf3cb0ccf3f98008c72ca8a ;; ;; Javascript numeric parsing is wonky, though. ;; ;; (js/parseInt "8Ricardo") is 8. ;; (js/parseFloat "8.5.9Tomato") is 8.5 ;; ;; ಠ_ಠ ;; ;; Hopefully we won't get back any TYPANALYZE result that starts with a ;; number but is not actually numeric. Requires more experimentation. (cond (nil? val) nil (js/isNaN as-float) val (number? as-float) as-float :default val)))) (def TYPUUIDOID 2950) (.setTypeParser pg-types TYPUUIDOID #(cljs.core/uuid %)) ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Functions and state ;;;;;;;;;;;;;;;;;;;;;;;;;;; (defstate ^:dynamic db-pool :start (wrap-future (doto (pg.Pool. (clj->js config)) (.on "error" #(.error js/console "Conn error" %1 %2)) (.on "connect" #(.log js/console "Connection!")) (.on "acquire" #(.log js/console "Acquired!")))) :end (.end @db-pool)) (defn query-no-pool [query-string] (.wait (.query @db-pool query-string))) (defn with-transaction "Will initialize a client from the database pool, obtain a query-fn, and then invoke the function it receives with the query-fn as its argument. Every call to the query function will be waited on, to ensure we are executing them sequentially. The functions will be executed in a transaction, which will be rolled back in case of an exception. Any exception caught will be re-thrown. Returns the result of releasing the client." [f] (let [client (wait (.connect @db-pool)) ;; Wrapping the entire client causes an issue on repeated requests, ;; because it loses some references. Looks like what we get back from ;; the wrapping is a proxy. It's probably meant for wrapping modules ;; and not instances, but wrapping a single function works well. ;; ;; I'm thinking this might be doable in a single step with a ;; function called `wrap-future-method`, which returns not ;; just a future, but a function that invokes the future on a specific ;; object. Similar to the ;; ;; (.call q-future client qs (clj->js rest)) ;; ;; invocation below. I'd probably need a to pass both the object to ;; invoke it on and the method being future-ified, though, since ;; I don't think there's a way to get the object a function originally ;; came from. ;; ;; For now I'm keeping the semantics transparent. q-future (wrap-future client.query) query (fn [qs & rest] (wait (.call q-future client qs (clj->js rest))))] (try (query "BEGIN") (let [r (f query)] (query "COMMIT") r) (catch js/Error e (query "ROLLBACK") (throw e)) (finally (.release client))))) (defn single-query "Runs a single query in a transaction." [& rest] (with-transaction #(apply % rest)))
[ { "context": ";-\n; Copyright 2015 © Meikel Brandmeyer.\n; All rights reserved.\n;\n; Licensed under the EU", "end": 39, "score": 0.9998752474784851, "start": 22, "tag": "NAME", "value": "Meikel Brandmeyer" } ]
src/main/clojure/hay/compiler.clj
pinky-editor/hay
2
;- ; Copyright 2015 © Meikel Brandmeyer. ; All rights reserved. ; ; Licensed under the EUPL V.1.1 (cf. file EUPL-1.1 distributed with the ; source code.) Translations in other european languages available at ; https://joinup.ec.europa.eu/software/page/eupl. ; ; Alternatively, you may choose to use the software under the MIT license ; (cf. file MIT distributed with the source code). (ns hay.compiler (:refer-clojure :exclude [compile]) (:require hay.grammar) (:import clojure.lang.AFunction clojure.lang.Symbol clojure.lang.Var hay.grammar.Block hay.grammar.QualifiedKeyword)) (def CALL [:CALL]) (def NO-OP [:NO-OP]) (def PUSH [:PUSH]) (def PUSH-ALL [:PUSH-ALL]) (def POP [:POP]) (defprotocol Compileable (-compile [this])) (defrecord Compilate [instructions]) (defn ^:private compile-signature [sig] (let [n (count sig) to-pop (or (some (fn [[idx sym]] (when (= sym '--) idx)) (map-indexed vector sig)) n) to-push (max (- n to-pop 1) 0)] [to-pop to-push])) (defn ^:private compile-fn [f] (let [signature (:hay/signature (meta f))] (cond (= signature :thread) [[:THREAD-CALL f]] (vector? signature) (let [[to-pop to-push] (compile-signature signature)] [[:POP to-pop] [:WORD f] CALL (case to-push 0 NO-OP 1 PUSH PUSH-ALL)]) (nil? signature) (throw (ex-info "cannot compile clojure function without signature" {:fn f})) :else (throw (ex-info "cannot compile clojure function with invalid signature" {:fn f :signature signature}))))) (extend-protocol Compileable Compilate (-compile [this] (:instructions this)) Object (-compile [this] [[:VALUE this] PUSH]) nil (-compile [this] [[:VALUE nil] PUSH]) AFunction (-compile [this] (compile-fn this)) Var (-compile [this] (if (fn? @this) (let [sig (:hay/signature (meta this))] (compile-fn (vary-meta @this assoc :hay/signature sig))) [[:VALUE @this] [:PUSH]])) Block (-compile [this] [[:VALUE (->Compilate (reduce into [] (map -compile (:words this))))] PUSH]) QualifiedKeyword (-compile [this] [[:VALUE (:kw this)] PUSH]) Symbol (-compile [this] [[:LOOKUP this]])) (defn compile [word] (->Compilate (-compile word))) (defn expose-var [v] (letfn [(compile-var [] (alter-meta! v assoc :hay/compilate (compile v)))] (compile-var) (add-watch v :hay/recompile (fn [_ _ _ _] (compile-var))) v))
9984
;- ; Copyright 2015 © <NAME>. ; All rights reserved. ; ; Licensed under the EUPL V.1.1 (cf. file EUPL-1.1 distributed with the ; source code.) Translations in other european languages available at ; https://joinup.ec.europa.eu/software/page/eupl. ; ; Alternatively, you may choose to use the software under the MIT license ; (cf. file MIT distributed with the source code). (ns hay.compiler (:refer-clojure :exclude [compile]) (:require hay.grammar) (:import clojure.lang.AFunction clojure.lang.Symbol clojure.lang.Var hay.grammar.Block hay.grammar.QualifiedKeyword)) (def CALL [:CALL]) (def NO-OP [:NO-OP]) (def PUSH [:PUSH]) (def PUSH-ALL [:PUSH-ALL]) (def POP [:POP]) (defprotocol Compileable (-compile [this])) (defrecord Compilate [instructions]) (defn ^:private compile-signature [sig] (let [n (count sig) to-pop (or (some (fn [[idx sym]] (when (= sym '--) idx)) (map-indexed vector sig)) n) to-push (max (- n to-pop 1) 0)] [to-pop to-push])) (defn ^:private compile-fn [f] (let [signature (:hay/signature (meta f))] (cond (= signature :thread) [[:THREAD-CALL f]] (vector? signature) (let [[to-pop to-push] (compile-signature signature)] [[:POP to-pop] [:WORD f] CALL (case to-push 0 NO-OP 1 PUSH PUSH-ALL)]) (nil? signature) (throw (ex-info "cannot compile clojure function without signature" {:fn f})) :else (throw (ex-info "cannot compile clojure function with invalid signature" {:fn f :signature signature}))))) (extend-protocol Compileable Compilate (-compile [this] (:instructions this)) Object (-compile [this] [[:VALUE this] PUSH]) nil (-compile [this] [[:VALUE nil] PUSH]) AFunction (-compile [this] (compile-fn this)) Var (-compile [this] (if (fn? @this) (let [sig (:hay/signature (meta this))] (compile-fn (vary-meta @this assoc :hay/signature sig))) [[:VALUE @this] [:PUSH]])) Block (-compile [this] [[:VALUE (->Compilate (reduce into [] (map -compile (:words this))))] PUSH]) QualifiedKeyword (-compile [this] [[:VALUE (:kw this)] PUSH]) Symbol (-compile [this] [[:LOOKUP this]])) (defn compile [word] (->Compilate (-compile word))) (defn expose-var [v] (letfn [(compile-var [] (alter-meta! v assoc :hay/compilate (compile v)))] (compile-var) (add-watch v :hay/recompile (fn [_ _ _ _] (compile-var))) v))
true
;- ; Copyright 2015 © PI:NAME:<NAME>END_PI. ; All rights reserved. ; ; Licensed under the EUPL V.1.1 (cf. file EUPL-1.1 distributed with the ; source code.) Translations in other european languages available at ; https://joinup.ec.europa.eu/software/page/eupl. ; ; Alternatively, you may choose to use the software under the MIT license ; (cf. file MIT distributed with the source code). (ns hay.compiler (:refer-clojure :exclude [compile]) (:require hay.grammar) (:import clojure.lang.AFunction clojure.lang.Symbol clojure.lang.Var hay.grammar.Block hay.grammar.QualifiedKeyword)) (def CALL [:CALL]) (def NO-OP [:NO-OP]) (def PUSH [:PUSH]) (def PUSH-ALL [:PUSH-ALL]) (def POP [:POP]) (defprotocol Compileable (-compile [this])) (defrecord Compilate [instructions]) (defn ^:private compile-signature [sig] (let [n (count sig) to-pop (or (some (fn [[idx sym]] (when (= sym '--) idx)) (map-indexed vector sig)) n) to-push (max (- n to-pop 1) 0)] [to-pop to-push])) (defn ^:private compile-fn [f] (let [signature (:hay/signature (meta f))] (cond (= signature :thread) [[:THREAD-CALL f]] (vector? signature) (let [[to-pop to-push] (compile-signature signature)] [[:POP to-pop] [:WORD f] CALL (case to-push 0 NO-OP 1 PUSH PUSH-ALL)]) (nil? signature) (throw (ex-info "cannot compile clojure function without signature" {:fn f})) :else (throw (ex-info "cannot compile clojure function with invalid signature" {:fn f :signature signature}))))) (extend-protocol Compileable Compilate (-compile [this] (:instructions this)) Object (-compile [this] [[:VALUE this] PUSH]) nil (-compile [this] [[:VALUE nil] PUSH]) AFunction (-compile [this] (compile-fn this)) Var (-compile [this] (if (fn? @this) (let [sig (:hay/signature (meta this))] (compile-fn (vary-meta @this assoc :hay/signature sig))) [[:VALUE @this] [:PUSH]])) Block (-compile [this] [[:VALUE (->Compilate (reduce into [] (map -compile (:words this))))] PUSH]) QualifiedKeyword (-compile [this] [[:VALUE (:kw this)] PUSH]) Symbol (-compile [this] [[:LOOKUP this]])) (defn compile [word] (->Compilate (-compile word))) (defn expose-var [v] (letfn [(compile-var [] (alter-meta! v assoc :hay/compilate (compile v)))] (compile-var) (add-watch v :hay/recompile (fn [_ _ _ _] (compile-var))) v))
[ { "context": ";; Copyright (c) Craig McDaniel, Jan 2009. All rights reserved.\n;; The use and d", "end": 32, "score": 0.9998887181282043, "start": 18, "tag": "NAME", "value": "Craig McDaniel" }, { "context": ";; Copyright (c) Craig McDaniel, Jan 2009. All rights reserved.\n;; The use and distri", "end": 37, "score": 0.9667391777038574, "start": 34, "tag": "NAME", "value": "Jan" }, { "context": "ary - includes REPL on socket\n\n(ns \n #^{:author \"Craig McDaniel\",\n :doc \"Server socket library - includes REP", "end": 563, "score": 0.9998288154602051, "start": 549, "tag": "NAME", "value": "Craig McDaniel" } ]
ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/server_socket.clj
allertonm/Couverjure
3
;; Copyright (c) Craig McDaniel, Jan 2009. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. ;; Server socket library - includes REPL on socket (ns #^{:author "Craig McDaniel", :doc "Server socket library - includes REPL on socket"} clojure.contrib.server-socket (:import (java.net InetAddress ServerSocket Socket SocketException) (java.io InputStreamReader OutputStream OutputStreamWriter PrintWriter) (clojure.lang LineNumberingPushbackReader)) (:use [clojure.main :only (repl)])) (defn- on-thread [f] (doto (Thread. #^Runnable f) (.start))) (defn- close-socket [#^Socket s] (when-not (.isClosed s) (doto s (.shutdownInput) (.shutdownOutput) (.close)))) (defn- accept-fn [#^Socket s connections fun] (let [ins (.getInputStream s) outs (.getOutputStream s)] (on-thread #(do (dosync (commute connections conj s)) (try (fun ins outs) (catch SocketException e)) (close-socket s) (dosync (commute connections disj s)))))) (defstruct server-def :server-socket :connections) (defn- create-server-aux [fun #^ServerSocket ss] (let [connections (ref #{})] (on-thread #(when-not (.isClosed ss) (try (accept-fn (.accept ss) connections fun) (catch SocketException e)) (recur))) (struct-map server-def :server-socket ss :connections connections))) (defn create-server "Creates a server socket on port. Upon accept, a new thread is created which calls: (fun input-stream output-stream) Optional arguments support specifying a listen backlog and binding to a specific endpoint." ([port fun backlog #^InetAddress bind-addr] (create-server-aux fun (ServerSocket. port backlog bind-addr))) ([port fun backlog] (create-server-aux fun (ServerSocket. port backlog))) ([port fun] (create-server-aux fun (ServerSocket. port)))) (defn close-server [server] (doseq [s @(:connections server)] (close-socket s)) (dosync (ref-set (:connections server) #{})) (.close #^ServerSocket (:server-socket server))) (defn connection-count [server] (count @(:connections server))) ;;;; ;;;; REPL on a socket ;;;; (defn- socket-repl [ins outs] (binding [*in* (LineNumberingPushbackReader. (InputStreamReader. ins)) *out* (OutputStreamWriter. outs) *err* (PrintWriter. #^OutputStream outs true)] (repl))) (defn create-repl-server "create a repl on a socket" ([port backlog #^InetAddress bind-addr] (create-server port socket-repl backlog bind-addr)) ([port backlog] (create-server port socket-repl backlog)) ([port] (create-server port socket-repl)))
119093
;; Copyright (c) <NAME>, <NAME> 2009. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. ;; Server socket library - includes REPL on socket (ns #^{:author "<NAME>", :doc "Server socket library - includes REPL on socket"} clojure.contrib.server-socket (:import (java.net InetAddress ServerSocket Socket SocketException) (java.io InputStreamReader OutputStream OutputStreamWriter PrintWriter) (clojure.lang LineNumberingPushbackReader)) (:use [clojure.main :only (repl)])) (defn- on-thread [f] (doto (Thread. #^Runnable f) (.start))) (defn- close-socket [#^Socket s] (when-not (.isClosed s) (doto s (.shutdownInput) (.shutdownOutput) (.close)))) (defn- accept-fn [#^Socket s connections fun] (let [ins (.getInputStream s) outs (.getOutputStream s)] (on-thread #(do (dosync (commute connections conj s)) (try (fun ins outs) (catch SocketException e)) (close-socket s) (dosync (commute connections disj s)))))) (defstruct server-def :server-socket :connections) (defn- create-server-aux [fun #^ServerSocket ss] (let [connections (ref #{})] (on-thread #(when-not (.isClosed ss) (try (accept-fn (.accept ss) connections fun) (catch SocketException e)) (recur))) (struct-map server-def :server-socket ss :connections connections))) (defn create-server "Creates a server socket on port. Upon accept, a new thread is created which calls: (fun input-stream output-stream) Optional arguments support specifying a listen backlog and binding to a specific endpoint." ([port fun backlog #^InetAddress bind-addr] (create-server-aux fun (ServerSocket. port backlog bind-addr))) ([port fun backlog] (create-server-aux fun (ServerSocket. port backlog))) ([port fun] (create-server-aux fun (ServerSocket. port)))) (defn close-server [server] (doseq [s @(:connections server)] (close-socket s)) (dosync (ref-set (:connections server) #{})) (.close #^ServerSocket (:server-socket server))) (defn connection-count [server] (count @(:connections server))) ;;;; ;;;; REPL on a socket ;;;; (defn- socket-repl [ins outs] (binding [*in* (LineNumberingPushbackReader. (InputStreamReader. ins)) *out* (OutputStreamWriter. outs) *err* (PrintWriter. #^OutputStream outs true)] (repl))) (defn create-repl-server "create a repl on a socket" ([port backlog #^InetAddress bind-addr] (create-server port socket-repl backlog bind-addr)) ([port backlog] (create-server port socket-repl backlog)) ([port] (create-server port socket-repl)))
true
;; Copyright (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI 2009. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. ;; Server socket library - includes REPL on socket (ns #^{:author "PI:NAME:<NAME>END_PI", :doc "Server socket library - includes REPL on socket"} clojure.contrib.server-socket (:import (java.net InetAddress ServerSocket Socket SocketException) (java.io InputStreamReader OutputStream OutputStreamWriter PrintWriter) (clojure.lang LineNumberingPushbackReader)) (:use [clojure.main :only (repl)])) (defn- on-thread [f] (doto (Thread. #^Runnable f) (.start))) (defn- close-socket [#^Socket s] (when-not (.isClosed s) (doto s (.shutdownInput) (.shutdownOutput) (.close)))) (defn- accept-fn [#^Socket s connections fun] (let [ins (.getInputStream s) outs (.getOutputStream s)] (on-thread #(do (dosync (commute connections conj s)) (try (fun ins outs) (catch SocketException e)) (close-socket s) (dosync (commute connections disj s)))))) (defstruct server-def :server-socket :connections) (defn- create-server-aux [fun #^ServerSocket ss] (let [connections (ref #{})] (on-thread #(when-not (.isClosed ss) (try (accept-fn (.accept ss) connections fun) (catch SocketException e)) (recur))) (struct-map server-def :server-socket ss :connections connections))) (defn create-server "Creates a server socket on port. Upon accept, a new thread is created which calls: (fun input-stream output-stream) Optional arguments support specifying a listen backlog and binding to a specific endpoint." ([port fun backlog #^InetAddress bind-addr] (create-server-aux fun (ServerSocket. port backlog bind-addr))) ([port fun backlog] (create-server-aux fun (ServerSocket. port backlog))) ([port fun] (create-server-aux fun (ServerSocket. port)))) (defn close-server [server] (doseq [s @(:connections server)] (close-socket s)) (dosync (ref-set (:connections server) #{})) (.close #^ServerSocket (:server-socket server))) (defn connection-count [server] (count @(:connections server))) ;;;; ;;;; REPL on a socket ;;;; (defn- socket-repl [ins outs] (binding [*in* (LineNumberingPushbackReader. (InputStreamReader. ins)) *out* (OutputStreamWriter. outs) *err* (PrintWriter. #^OutputStream outs true)] (repl))) (defn create-repl-server "create a repl on a socket" ([port backlog #^InetAddress bind-addr] (create-server port socket-repl backlog bind-addr)) ([port backlog] (create-server port socket-repl backlog)) ([port] (create-server port socket-repl)))
[ { "context": "convert a single file\"\n (is (= \"{\n\\\"name\\\" : \\\"foo\\\",\n\\\"weight\\\" : \\\"5\\\",\n\\\"size\\\" : \\\"7\\\"\n}\n\" (conv", "end": 223, "score": 0.8378406763076782, "start": 220, "tag": "NAME", "value": "foo" }, { "context": "name\\\" : \\\"foo\\\",\n\\\"children\\\" : [\n{\n\\\"name\\\" : \\\"bar\\\",\n\\\"weight\\\" : \\\"3\\\",\n\\\"size\\\" : \\\"2\\\"\n}\n]\n}\n\" (", "end": 428, "score": 0.735515296459198, "start": 425, "tag": "NAME", "value": "bar" }, { "context": " unimmaginable things\"\n (is (= \"{\n\\\"name\\\" : \\\"foo\\\",\n\\\"children\\\" : [\n{\n\\\"name\\\" : \\\"bar\\\",\n\\\"weigh", "end": 610, "score": 0.7234317660331726, "start": 607, "tag": "NAME", "value": "foo" }, { "context": "name\\\" : \\\"foo\\\",\n\\\"children\\\" : [\n{\n\\\"name\\\" : \\\"bar\\\",\n\\\"weight\\\" : \\\"3\\\",\n\\\"size\\\" : \\\"2\\\"\n}\n,{\n\\\"na", "end": 649, "score": 0.7811236381530762, "start": 646, "tag": "NAME", "value": "bar" }, { "context": "ght\\\" : \\\"3\\\",\n\\\"size\\\" : \\\"2\\\"\n}\n,{\n\\\"name\\\" : \\\"baz\\\",\n\\\"children\\\" : [\n{\n\\\"name\\\" : \\\"foobar\\\",\n\\\"ch", "end": 711, "score": 0.8296424150466919, "start": 708, "tag": "NAME", "value": "baz" }, { "context": "e\\\" : \\\"foobar\\\",\n\\\"children\\\" : [\n{\n\\\"name\\\" : \\\"baz\\\",\n\\\"weight\\\" : \\\"-1\\\",\n\\\"size\\\" : \\\"-2\\\"\n}\n]\n}\n]", "end": 792, "score": 0.7968280911445618, "start": 789, "tag": "NAME", "value": "baz" } ]
json-conversion/test/json_conversion/jsonify_test.clj
R1ck77/codemaat-scripts
0
(ns json-conversion.jsonify-test (:require [clojure.test :refer :all] [json-conversion.jsonify :refer :all])) (deftest test-branch-to-json (testing "can convert a single file" (is (= "{ \"name\" : \"foo\", \"weight\" : \"5\", \"size\" : \"7\" } " (convert-hierarchy ["foo" {:weight 5, :size 7}])))) (testing "can convert a nested file" (is (= "{ \"name\" : \"foo\", \"children\" : [ { \"name\" : \"bar\", \"weight\" : \"3\", \"size\" : \"2\" } ] } " (convert-hierarchy ["foo" { "bar" { :weight 3, :size 2}}])))) (testing "can do unimmaginable things" (is (= "{ \"name\" : \"foo\", \"children\" : [ { \"name\" : \"bar\", \"weight\" : \"3\", \"size\" : \"2\" } ,{ \"name\" : \"baz\", \"children\" : [ { \"name\" : \"foobar\", \"children\" : [ { \"name\" : \"baz\", \"weight\" : \"-1\", \"size\" : \"-2\" } ] } ] } ] } " (convert-hierarchy ["foo" { "bar" { :weight 3, :size 2} "baz" { "foobar" {"baz" {:weight -1, :size -2}}}}])))))
31305
(ns json-conversion.jsonify-test (:require [clojure.test :refer :all] [json-conversion.jsonify :refer :all])) (deftest test-branch-to-json (testing "can convert a single file" (is (= "{ \"name\" : \"<NAME>\", \"weight\" : \"5\", \"size\" : \"7\" } " (convert-hierarchy ["foo" {:weight 5, :size 7}])))) (testing "can convert a nested file" (is (= "{ \"name\" : \"foo\", \"children\" : [ { \"name\" : \"<NAME>\", \"weight\" : \"3\", \"size\" : \"2\" } ] } " (convert-hierarchy ["foo" { "bar" { :weight 3, :size 2}}])))) (testing "can do unimmaginable things" (is (= "{ \"name\" : \"<NAME>\", \"children\" : [ { \"name\" : \"<NAME>\", \"weight\" : \"3\", \"size\" : \"2\" } ,{ \"name\" : \"<NAME>\", \"children\" : [ { \"name\" : \"foobar\", \"children\" : [ { \"name\" : \"<NAME>\", \"weight\" : \"-1\", \"size\" : \"-2\" } ] } ] } ] } " (convert-hierarchy ["foo" { "bar" { :weight 3, :size 2} "baz" { "foobar" {"baz" {:weight -1, :size -2}}}}])))))
true
(ns json-conversion.jsonify-test (:require [clojure.test :refer :all] [json-conversion.jsonify :refer :all])) (deftest test-branch-to-json (testing "can convert a single file" (is (= "{ \"name\" : \"PI:NAME:<NAME>END_PI\", \"weight\" : \"5\", \"size\" : \"7\" } " (convert-hierarchy ["foo" {:weight 5, :size 7}])))) (testing "can convert a nested file" (is (= "{ \"name\" : \"foo\", \"children\" : [ { \"name\" : \"PI:NAME:<NAME>END_PI\", \"weight\" : \"3\", \"size\" : \"2\" } ] } " (convert-hierarchy ["foo" { "bar" { :weight 3, :size 2}}])))) (testing "can do unimmaginable things" (is (= "{ \"name\" : \"PI:NAME:<NAME>END_PI\", \"children\" : [ { \"name\" : \"PI:NAME:<NAME>END_PI\", \"weight\" : \"3\", \"size\" : \"2\" } ,{ \"name\" : \"PI:NAME:<NAME>END_PI\", \"children\" : [ { \"name\" : \"foobar\", \"children\" : [ { \"name\" : \"PI:NAME:<NAME>END_PI\", \"weight\" : \"-1\", \"size\" : \"-2\" } ] } ] } ] } " (convert-hierarchy ["foo" { "bar" { :weight 3, :size 2} "baz" { "foobar" {"baz" {:weight -1, :size -2}}}}])))))
[ { "context": "t\"]\n [:a.header__link {:href \"mailto:hello@xtdb.com\" :target \"_blank\"} \"Email Support\"]]]\n ", "end": 6282, "score": 0.9999086856842041, "start": 6268, "tag": "EMAIL", "value": "hello@xtdb.com" } ]
modules/http-server/src/xtdb/http_server/util.clj
aleksandersumowski/xtdb
1,500
(ns xtdb.http-server.util (:require [clojure.java.io :as io] [clojure.pprint :as pp] [clojure.spec.alpha :as s] [cognitect.transit :as transit] [xtdb.api :as xt] [xtdb.codec :as c] [xtdb.http-server.json :as http-json] [xtdb.io :as xio] [juxt.clojars-mirrors.hiccup.v2v0v0-alpha2.hiccup2.core :as hiccup2] [juxt.clojars-mirrors.muuntaja.v0v6v8.muuntaja.core :as m] [juxt.clojars-mirrors.muuntaja.v0v6v8.muuntaja.format.core :as mfc] [juxt.clojars-mirrors.muuntaja.v0v6v8.muuntaja.format.edn :as mfe] [juxt.clojars-mirrors.muuntaja.v0v6v8.muuntaja.format.transit :as mft] [juxt.clojars-mirrors.spec-tools.v0v10v5.spec-tools.core :as st] [xtdb.http-server.entity-ref :as entity-ref] [clojure.instant :as inst]) (:import [xtdb.api IXtdbDatasource] [xtdb.codec EDNId Id] xtdb.http_server.entity_ref.EntityRef [java.io ByteArrayOutputStream OutputStream] (java.util Date Map))) (s/def ::eid (and string? c/valid-id?)) (s/def ::date (st/spec {:spec #(instance? Date %) :decode/string (fn [_ d] (inst/read-instant-date d))})) (defn try-decode-edn [edn] (try (cond-> edn (string? edn) c/read-edn-string-with-readers) (catch Exception _e ::s/invalid))) (s/def ::eid-edn (st/spec {:spec c/valid-id? :description "EDN formatted entity ID" :decode/string (fn [_ eid] (try-decode-edn eid))})) (s/def ::eid-json (st/spec {:spec c/valid-id? :description "JSON formatted entity ID" :decode/string (fn [_ json] (http-json/try-decode-json json))})) (s/def ::link-entities? boolean?) (s/def ::valid-time ::date) (s/def ::tx-time ::date) (s/def ::timeout int?) (s/def ::tx-id int?) (defn ->edn-encoder [_] (reify mfc/EncodeToBytes (encode-to-bytes [_ data _] (binding [*print-length* nil, *print-level* nil] (.getBytes (pr-str data) "UTF-8"))) mfc/EncodeToOutputStream (encode-to-output-stream [_ {:keys [^Cursor results] :as data} _] (fn [^OutputStream output-stream] (binding [*print-length* nil, *print-level* nil] (with-open [w (io/writer output-stream)] (try (if results (print-method (or (iterator-seq results) '()) w) (.write w ^String (pr-str data))) (finally (xio/try-close results))))))))) (def tj-write-handlers {EntityRef entity-ref/ref-write-handler Id (transit/write-handler "xtdb/oid" str) EDNId (transit/write-handler "xtdb/oid" str) (Class/forName "[B") (transit/write-handler "xtdb/base64" c/base64-writer)}) (defn ->tj-encoder [_] (let [options {:handlers tj-write-handlers}] (reify mfc/EncodeToBytes (encode-to-bytes [_ data _] (let [baos (ByteArrayOutputStream.) writer (transit/writer baos :json options)] (transit/write writer data) (.toByteArray baos))) mfc/EncodeToOutputStream (encode-to-output-stream [_ {:keys [^Cursor results] :as data} _] (fn [^OutputStream output-stream] (let [writer (transit/writer output-stream :json options)] (try (if results (transit/write writer (or (iterator-seq results) '())) (transit/write writer data)) (finally (xio/try-close results))))))))) (defn ->default-muuntaja ([] (->default-muuntaja {})) ([opts] (-> m/default-options (dissoc :formats) (assoc :default-format "application/edn") (m/install {:name "application/transit+json" :encoder [->tj-encoder] :decoder [(partial mft/decoder :json)]}) (m/install {:name "application/edn" :encoder [->edn-encoder] :decoder [mfe/decoder]}) (m/install {:name "application/json" :encoder [http-json/->json-encoder opts]})))) (defn db-for-request ^IXtdbDatasource [xtdb-node {:keys [valid-time tx-time tx-id]}] (let [^Map db-basis {::xt/valid-time valid-time ::xt/tx-time tx-time ::xt/tx-id tx-id}] (xt/db xtdb-node db-basis))) (defn raw-html [{:keys [title xtdb-node http-options results]}] (let [latest-completed-tx (xt/latest-completed-tx xtdb-node)] (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"}] [:meta {:title "options" :content (pr-str {:http-options http-options :latest-completed-tx latest-completed-tx})}] (when results [:meta {:title "results", :content (pr-str results)}]) [: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/react-datetime.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 "XTDB Console"]] [:body [:nav.header [:div.xtdb-logo [:a {:href "/_xtdb/query"} [:img.xtdb-logo__img {:src "/crux-horizontal-bw.svg.png" }]]] [:span.mobile-hidden [:b (:server-label http-options)]] [:div.header__links [:a.header__link {:href "https://xtdb.com/reference/get-started.html" :target "_blank"} "Documentation"] [:a.header__link {:href "https://juxt-oss.zulipchat.com/#narrow/stream/194466-xtdb-users" :target "_blank"} "Zulip Chat"] [:a.header__link {:href "mailto:hello@xtdb.com" :target "_blank"} "Email Support"]]] [:div.console [:div#app [:noscript [:pre.noscript-content (with-out-str (pp/pprint results))]]]] [:script {:src "/cljs-out/dev-main.js" :type "text/javascript"}]]]))))
20320
(ns xtdb.http-server.util (:require [clojure.java.io :as io] [clojure.pprint :as pp] [clojure.spec.alpha :as s] [cognitect.transit :as transit] [xtdb.api :as xt] [xtdb.codec :as c] [xtdb.http-server.json :as http-json] [xtdb.io :as xio] [juxt.clojars-mirrors.hiccup.v2v0v0-alpha2.hiccup2.core :as hiccup2] [juxt.clojars-mirrors.muuntaja.v0v6v8.muuntaja.core :as m] [juxt.clojars-mirrors.muuntaja.v0v6v8.muuntaja.format.core :as mfc] [juxt.clojars-mirrors.muuntaja.v0v6v8.muuntaja.format.edn :as mfe] [juxt.clojars-mirrors.muuntaja.v0v6v8.muuntaja.format.transit :as mft] [juxt.clojars-mirrors.spec-tools.v0v10v5.spec-tools.core :as st] [xtdb.http-server.entity-ref :as entity-ref] [clojure.instant :as inst]) (:import [xtdb.api IXtdbDatasource] [xtdb.codec EDNId Id] xtdb.http_server.entity_ref.EntityRef [java.io ByteArrayOutputStream OutputStream] (java.util Date Map))) (s/def ::eid (and string? c/valid-id?)) (s/def ::date (st/spec {:spec #(instance? Date %) :decode/string (fn [_ d] (inst/read-instant-date d))})) (defn try-decode-edn [edn] (try (cond-> edn (string? edn) c/read-edn-string-with-readers) (catch Exception _e ::s/invalid))) (s/def ::eid-edn (st/spec {:spec c/valid-id? :description "EDN formatted entity ID" :decode/string (fn [_ eid] (try-decode-edn eid))})) (s/def ::eid-json (st/spec {:spec c/valid-id? :description "JSON formatted entity ID" :decode/string (fn [_ json] (http-json/try-decode-json json))})) (s/def ::link-entities? boolean?) (s/def ::valid-time ::date) (s/def ::tx-time ::date) (s/def ::timeout int?) (s/def ::tx-id int?) (defn ->edn-encoder [_] (reify mfc/EncodeToBytes (encode-to-bytes [_ data _] (binding [*print-length* nil, *print-level* nil] (.getBytes (pr-str data) "UTF-8"))) mfc/EncodeToOutputStream (encode-to-output-stream [_ {:keys [^Cursor results] :as data} _] (fn [^OutputStream output-stream] (binding [*print-length* nil, *print-level* nil] (with-open [w (io/writer output-stream)] (try (if results (print-method (or (iterator-seq results) '()) w) (.write w ^String (pr-str data))) (finally (xio/try-close results))))))))) (def tj-write-handlers {EntityRef entity-ref/ref-write-handler Id (transit/write-handler "xtdb/oid" str) EDNId (transit/write-handler "xtdb/oid" str) (Class/forName "[B") (transit/write-handler "xtdb/base64" c/base64-writer)}) (defn ->tj-encoder [_] (let [options {:handlers tj-write-handlers}] (reify mfc/EncodeToBytes (encode-to-bytes [_ data _] (let [baos (ByteArrayOutputStream.) writer (transit/writer baos :json options)] (transit/write writer data) (.toByteArray baos))) mfc/EncodeToOutputStream (encode-to-output-stream [_ {:keys [^Cursor results] :as data} _] (fn [^OutputStream output-stream] (let [writer (transit/writer output-stream :json options)] (try (if results (transit/write writer (or (iterator-seq results) '())) (transit/write writer data)) (finally (xio/try-close results))))))))) (defn ->default-muuntaja ([] (->default-muuntaja {})) ([opts] (-> m/default-options (dissoc :formats) (assoc :default-format "application/edn") (m/install {:name "application/transit+json" :encoder [->tj-encoder] :decoder [(partial mft/decoder :json)]}) (m/install {:name "application/edn" :encoder [->edn-encoder] :decoder [mfe/decoder]}) (m/install {:name "application/json" :encoder [http-json/->json-encoder opts]})))) (defn db-for-request ^IXtdbDatasource [xtdb-node {:keys [valid-time tx-time tx-id]}] (let [^Map db-basis {::xt/valid-time valid-time ::xt/tx-time tx-time ::xt/tx-id tx-id}] (xt/db xtdb-node db-basis))) (defn raw-html [{:keys [title xtdb-node http-options results]}] (let [latest-completed-tx (xt/latest-completed-tx xtdb-node)] (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"}] [:meta {:title "options" :content (pr-str {:http-options http-options :latest-completed-tx latest-completed-tx})}] (when results [:meta {:title "results", :content (pr-str results)}]) [: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/react-datetime.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 "XTDB Console"]] [:body [:nav.header [:div.xtdb-logo [:a {:href "/_xtdb/query"} [:img.xtdb-logo__img {:src "/crux-horizontal-bw.svg.png" }]]] [:span.mobile-hidden [:b (:server-label http-options)]] [:div.header__links [:a.header__link {:href "https://xtdb.com/reference/get-started.html" :target "_blank"} "Documentation"] [:a.header__link {:href "https://juxt-oss.zulipchat.com/#narrow/stream/194466-xtdb-users" :target "_blank"} "Zulip Chat"] [:a.header__link {:href "mailto:<EMAIL>" :target "_blank"} "Email Support"]]] [:div.console [:div#app [:noscript [:pre.noscript-content (with-out-str (pp/pprint results))]]]] [:script {:src "/cljs-out/dev-main.js" :type "text/javascript"}]]]))))
true
(ns xtdb.http-server.util (:require [clojure.java.io :as io] [clojure.pprint :as pp] [clojure.spec.alpha :as s] [cognitect.transit :as transit] [xtdb.api :as xt] [xtdb.codec :as c] [xtdb.http-server.json :as http-json] [xtdb.io :as xio] [juxt.clojars-mirrors.hiccup.v2v0v0-alpha2.hiccup2.core :as hiccup2] [juxt.clojars-mirrors.muuntaja.v0v6v8.muuntaja.core :as m] [juxt.clojars-mirrors.muuntaja.v0v6v8.muuntaja.format.core :as mfc] [juxt.clojars-mirrors.muuntaja.v0v6v8.muuntaja.format.edn :as mfe] [juxt.clojars-mirrors.muuntaja.v0v6v8.muuntaja.format.transit :as mft] [juxt.clojars-mirrors.spec-tools.v0v10v5.spec-tools.core :as st] [xtdb.http-server.entity-ref :as entity-ref] [clojure.instant :as inst]) (:import [xtdb.api IXtdbDatasource] [xtdb.codec EDNId Id] xtdb.http_server.entity_ref.EntityRef [java.io ByteArrayOutputStream OutputStream] (java.util Date Map))) (s/def ::eid (and string? c/valid-id?)) (s/def ::date (st/spec {:spec #(instance? Date %) :decode/string (fn [_ d] (inst/read-instant-date d))})) (defn try-decode-edn [edn] (try (cond-> edn (string? edn) c/read-edn-string-with-readers) (catch Exception _e ::s/invalid))) (s/def ::eid-edn (st/spec {:spec c/valid-id? :description "EDN formatted entity ID" :decode/string (fn [_ eid] (try-decode-edn eid))})) (s/def ::eid-json (st/spec {:spec c/valid-id? :description "JSON formatted entity ID" :decode/string (fn [_ json] (http-json/try-decode-json json))})) (s/def ::link-entities? boolean?) (s/def ::valid-time ::date) (s/def ::tx-time ::date) (s/def ::timeout int?) (s/def ::tx-id int?) (defn ->edn-encoder [_] (reify mfc/EncodeToBytes (encode-to-bytes [_ data _] (binding [*print-length* nil, *print-level* nil] (.getBytes (pr-str data) "UTF-8"))) mfc/EncodeToOutputStream (encode-to-output-stream [_ {:keys [^Cursor results] :as data} _] (fn [^OutputStream output-stream] (binding [*print-length* nil, *print-level* nil] (with-open [w (io/writer output-stream)] (try (if results (print-method (or (iterator-seq results) '()) w) (.write w ^String (pr-str data))) (finally (xio/try-close results))))))))) (def tj-write-handlers {EntityRef entity-ref/ref-write-handler Id (transit/write-handler "xtdb/oid" str) EDNId (transit/write-handler "xtdb/oid" str) (Class/forName "[B") (transit/write-handler "xtdb/base64" c/base64-writer)}) (defn ->tj-encoder [_] (let [options {:handlers tj-write-handlers}] (reify mfc/EncodeToBytes (encode-to-bytes [_ data _] (let [baos (ByteArrayOutputStream.) writer (transit/writer baos :json options)] (transit/write writer data) (.toByteArray baos))) mfc/EncodeToOutputStream (encode-to-output-stream [_ {:keys [^Cursor results] :as data} _] (fn [^OutputStream output-stream] (let [writer (transit/writer output-stream :json options)] (try (if results (transit/write writer (or (iterator-seq results) '())) (transit/write writer data)) (finally (xio/try-close results))))))))) (defn ->default-muuntaja ([] (->default-muuntaja {})) ([opts] (-> m/default-options (dissoc :formats) (assoc :default-format "application/edn") (m/install {:name "application/transit+json" :encoder [->tj-encoder] :decoder [(partial mft/decoder :json)]}) (m/install {:name "application/edn" :encoder [->edn-encoder] :decoder [mfe/decoder]}) (m/install {:name "application/json" :encoder [http-json/->json-encoder opts]})))) (defn db-for-request ^IXtdbDatasource [xtdb-node {:keys [valid-time tx-time tx-id]}] (let [^Map db-basis {::xt/valid-time valid-time ::xt/tx-time tx-time ::xt/tx-id tx-id}] (xt/db xtdb-node db-basis))) (defn raw-html [{:keys [title xtdb-node http-options results]}] (let [latest-completed-tx (xt/latest-completed-tx xtdb-node)] (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"}] [:meta {:title "options" :content (pr-str {:http-options http-options :latest-completed-tx latest-completed-tx})}] (when results [:meta {:title "results", :content (pr-str results)}]) [: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/react-datetime.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 "XTDB Console"]] [:body [:nav.header [:div.xtdb-logo [:a {:href "/_xtdb/query"} [:img.xtdb-logo__img {:src "/crux-horizontal-bw.svg.png" }]]] [:span.mobile-hidden [:b (:server-label http-options)]] [:div.header__links [:a.header__link {:href "https://xtdb.com/reference/get-started.html" :target "_blank"} "Documentation"] [:a.header__link {:href "https://juxt-oss.zulipchat.com/#narrow/stream/194466-xtdb-users" :target "_blank"} "Zulip Chat"] [:a.header__link {:href "mailto:PI:EMAIL:<EMAIL>END_PI" :target "_blank"} "Email Support"]]] [:div.console [:div#app [:noscript [:pre.noscript-content (with-out-str (pp/pprint results))]]]] [:script {:src "/cljs-out/dev-main.js" :type "text/javascript"}]]]))))
[ { "context": "(ns\n ^{:author \"Brian Craft\"\n :doc \"Protocol for xena operations on a data", "end": 28, "score": 0.9998757839202881, "start": 17, "tag": "NAME", "value": "Brian Craft" } ]
src/cavm/db.clj
ucscXena/ucsc-xena-server
8
(ns ^{:author "Brian Craft" :doc "Protocol for xena operations on a database."} cavm.db) (defprotocol XenaDb "Xena database protocol" (write-matrix [this mname files metadata data-fn features always] "Write a dataset to the database. <mname> --- the (unique) name of the dataset. <files> --- a vector of file names that were read for the dataset. <metadata> --- a map of metadata to be associated with the dataset. <data-fn> --- a function returning the data of each field in the dataset. <features> --- a map of metadata describing the fields. <always> --- force update of database, even if the files are unchanged since the last load of this dataset.") (delete-matrix [this mname] "Remove a dataset from the database. <mname> --- the (unique) name of the dataset.") (run-query [this query] "Execute a sql query. <query> is a honeysql map.") (column-query [this query] "Execute a sql query against abstract column store. <query> is a honeysql map.") (fetch [this reqs] "Retrieve rows from specified fields in a dataset, matching a list of sampleIDs, as an array of floats. reqs is an array of maps [{:table <dataset_name> :columns [<field_name>, ...] :samples [<sampleID>, <sampleID>, ..]}, ...]") (close [this] "Close the database."))
15063
(ns ^{:author "<NAME>" :doc "Protocol for xena operations on a database."} cavm.db) (defprotocol XenaDb "Xena database protocol" (write-matrix [this mname files metadata data-fn features always] "Write a dataset to the database. <mname> --- the (unique) name of the dataset. <files> --- a vector of file names that were read for the dataset. <metadata> --- a map of metadata to be associated with the dataset. <data-fn> --- a function returning the data of each field in the dataset. <features> --- a map of metadata describing the fields. <always> --- force update of database, even if the files are unchanged since the last load of this dataset.") (delete-matrix [this mname] "Remove a dataset from the database. <mname> --- the (unique) name of the dataset.") (run-query [this query] "Execute a sql query. <query> is a honeysql map.") (column-query [this query] "Execute a sql query against abstract column store. <query> is a honeysql map.") (fetch [this reqs] "Retrieve rows from specified fields in a dataset, matching a list of sampleIDs, as an array of floats. reqs is an array of maps [{:table <dataset_name> :columns [<field_name>, ...] :samples [<sampleID>, <sampleID>, ..]}, ...]") (close [this] "Close the database."))
true
(ns ^{:author "PI:NAME:<NAME>END_PI" :doc "Protocol for xena operations on a database."} cavm.db) (defprotocol XenaDb "Xena database protocol" (write-matrix [this mname files metadata data-fn features always] "Write a dataset to the database. <mname> --- the (unique) name of the dataset. <files> --- a vector of file names that were read for the dataset. <metadata> --- a map of metadata to be associated with the dataset. <data-fn> --- a function returning the data of each field in the dataset. <features> --- a map of metadata describing the fields. <always> --- force update of database, even if the files are unchanged since the last load of this dataset.") (delete-matrix [this mname] "Remove a dataset from the database. <mname> --- the (unique) name of the dataset.") (run-query [this query] "Execute a sql query. <query> is a honeysql map.") (column-query [this query] "Execute a sql query against abstract column store. <query> is a honeysql map.") (fetch [this reqs] "Retrieve rows from specified fields in a dataset, matching a list of sampleIDs, as an array of floats. reqs is an array of maps [{:table <dataset_name> :columns [<field_name>, ...] :samples [<sampleID>, <sampleID>, ..]}, ...]") (close [this] "Close the database."))
[ { "context": "))\n '(\"Various Artists\"\n \"Bob Dylan\"\n \"Ray Charles\"\n \"Muddy", "end": 4618, "score": 0.9998834133148193, "start": 4609, "tag": "NAME", "value": "Bob Dylan" }, { "context": "Artists\"\n \"Bob Dylan\"\n \"Ray Charles\"\n \"Muddy Waters\"\n \"Talk", "end": 4646, "score": 0.9998795986175537, "start": 4635, "tag": "NAME", "value": "Ray Charles" }, { "context": "Dylan\"\n \"Ray Charles\"\n \"Muddy Waters\"\n \"Talking Heads\")))\n\n\n\n(defn find-p", "end": 4675, "score": 0.9998807311058044, "start": 4663, "tag": "NAME", "value": "Muddy Waters" }, { "context": "\n '([\"The Beatles\" 10]\n [\"Bob Dylan\" 10]\n [\"The Rolling Stones\" 9]\n ", "end": 5259, "score": 0.999880313873291, "start": 5250, "tag": "NAME", "value": "Bob Dylan" }, { "context": " [\"The Rolling Stones\" 9]\n [\"Bruce Springsteen\" 7]\n [\"The Who\" 7])))\n\n\n;; We can tr", "end": 5337, "score": 0.9998851418495178, "start": 5320, "tag": "NAME", "value": "Bruce Springsteen" } ]
src/icw/data/process.clj
akshar314/InClojure2019-workshop
0
(ns icw.data.process (:require [clojure.string :as cs] [icw.java-interop.jdbc :as jdbc] [clojure.data.csv :as csv] [clojure.string :as cs] [icw.data.gen :as data-gen] [clojure.string :as str])) ;; Reading and processing data from resources/data/albumlist.csv (defonce album-lines (drop 1 (line-seq (clojure.java.io/reader "resources/data/albumlist.csv")))) (comment (first album-lines)) ;; Parsing (defn parse-line "Input line -> \"1,1967,Sgt. Pepper's Lonely Hearts Club Band,The Beatles,Rock,\"Rock & Roll, Psychedelic Rock\" Output [\"1\" \"1967\" \"Sgt. Pepper's Lonely Hearts Club BandThe Beatles\" \"The Beatles\" \"Rock\" [\"Rock & Roll\" \"Psychedelic Rock\"]" [line] (let [foo (str/split line #"," 6)] (concat (butlast foo) [(map #(str/replace % "\"" "") (str/split (last foo) #","))]))) (comment (= (parse-line "1,1967,Sgt. Pepper's Lonely Hearts Club Band,The Beatles,Rock,\"Rock & Roll,Psychedelic Rock\"") ["1" "1967" "Sgt. Pepper's Lonely Hearts Club Band" "The Beatles" "Rock" ["Rock & Roll" "Psychedelic Rock"]])) (comment (take 2 (map parse-line album-lines))) (defn line-vec->line-map "xs -> [\"1\" \"1967\" \"Sgt. Pepper's Lonely Hearts Club BandThe Beatles\" \"The beatles\" \"Rock\" [\"Rock & Roll\" \"Psychedelic Rock\"]] Output {:number \"1\" :year \"1967\" :artist \"The beatles\"p :album \"Sgt. Pepper's Lonely Hearts Club BandThe Beatles\" :genre \"Rock\" :subgenre-xs [\"Rock & Roll\" \"Psychedelic Rock\"]}" [xs] (let [[id year album artist genre subgenre-xs] xs] {:number id :year year :artist artist :album album :genre genre :subgenre subgenre-xs })) (comment (= (line-vec->line-map ["1" "1967" "Sgt. Pepper's Lonely Hearts Club BandThe Beatles" "The Beatles" "Rock" ["Rock & Roll" "Psychedelic Rock"]]) {:number "1" :year "1967" :artist "The Beatles" :album "Sgt. Pepper's Lonely Hearts Club BandThe Beatles" :genre "Rock" :subgenre ["Rock & Roll" "Psychedelic Rock"]})) (comment (take 10 (map line-vec->line-map (map parse-line album-lines)))) (defn line-xs->album-xs [album-lines] (map line-vec->line-map (map parse-line album-lines))) (defn populate-db [] (jdbc/init-db) (let [albums (line-xs->album-xs album-lines)] (doseq [album albums] (jdbc/insert! (update-in album [:subgenre] #(cs/join "," %)))))) ;; Check http://localhost:6789/albums ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Some more exploration with sequences ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn line-xs->rock-albums-xs [line-xs] (comment (map #_FIXME (filter #_FIXME #_FIXME)))) (comment (= (take 5 (line-xs->rock-albums-xs album-lines)) '("Sgt. Pepper's Lonely Hearts Club Band" "Pet Sounds" "Revolver" "Highway 61 Revisited" "Exile on Main St."))) (defn line-xs->albums-xs-before "Lists all albums before 'year'" [line-xs year] (comment (filter #_FIXME (map #_FIXME #_FIXME)))) (comment (= (take 5 (map (juxt :year :album) (line-xs->albums-xs-before 1987 album-lines))) '([1967 "Sgt. Pepper's Lonely Hearts Club Band"] [1966 "Pet Sounds"] [1966 "Revolver"] [1965 "Highway 61 Revisited"] [1965 "Rubber Soul"]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Some more exploration with reduce ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn artists-with-range "Artists who have most genres" [line-xs] (map #_FIXME (sort-by #_FIXME (reduce #_FIXME {} (map #_FIXME line-xs))))) (comment (= (take 5 (artists-with-range album-lines)) '("Various Artists" "Bob Dylan" "Ray Charles" "Muddy Waters" "Talking Heads"))) (defn find-popular-year ;; Find top years for album releases [line-xs] (sort-by #_FIXME (reduce #_FIXME {} (map #_ME line-xs)))) (comment (= (take 5 (find-popular-year album-lines)) '(["1970" 26] ["1972" 24] ["1973" 23] ["1969" 22] ["1971" 21]))) (defn find-popular-artists [line-xs] ) (comment (= (find-popular-artists album-lines) '(["The Beatles" 10] ["Bob Dylan" 10] ["The Rolling Stones" 9] ["Bruce Springsteen" 7] ["The Who" 7]))) ;; We can transform data a great deal with just map, reduce and filter ;; Generally there are three patterns ;; Seq of N -> Seq of N (map) ;; Seq of N -> Seq of M (N > M) (filter) ;; Seq of N -> Any data structure (reduce) ;; This is great but what about lazy sequences all we processed till now was in-memory data ;; A stream from future timeline from 2040 data-gen/get-albums-xs ;; DONT evaluate the function in REPL it's a lazy sequence. ;; It's a list of albums generated from 2040 till infinity (take 10 (data-gen/get-albums-xs)) ;; Let's some of the functions we created till now (take 10 (line-xs->rock-albums-xs (data-gen/get-albums-xs))) ;; We can use line-xs->albums-xs-before to just get limited set ;; Right? (comment ;; This will evaluate for infinity since filter does not stop evaluation ;; We will just get infinite list of nils after year 2045 (line-xs->albums-xs-before (data-gen/get-albums-xs) 2045)) ;; https://clojure.org/api/cheatsheet ;; Espeically look for seq in and seq out (#_FIXME identity (line-xs->albums-xs-before (data-gen/get-albums-xs) 2045)) ;; Try applying functions we have created till now ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; END of chapter 1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Jump back to icw.core
116215
(ns icw.data.process (:require [clojure.string :as cs] [icw.java-interop.jdbc :as jdbc] [clojure.data.csv :as csv] [clojure.string :as cs] [icw.data.gen :as data-gen] [clojure.string :as str])) ;; Reading and processing data from resources/data/albumlist.csv (defonce album-lines (drop 1 (line-seq (clojure.java.io/reader "resources/data/albumlist.csv")))) (comment (first album-lines)) ;; Parsing (defn parse-line "Input line -> \"1,1967,Sgt. Pepper's Lonely Hearts Club Band,The Beatles,Rock,\"Rock & Roll, Psychedelic Rock\" Output [\"1\" \"1967\" \"Sgt. Pepper's Lonely Hearts Club BandThe Beatles\" \"The Beatles\" \"Rock\" [\"Rock & Roll\" \"Psychedelic Rock\"]" [line] (let [foo (str/split line #"," 6)] (concat (butlast foo) [(map #(str/replace % "\"" "") (str/split (last foo) #","))]))) (comment (= (parse-line "1,1967,Sgt. Pepper's Lonely Hearts Club Band,The Beatles,Rock,\"Rock & Roll,Psychedelic Rock\"") ["1" "1967" "Sgt. Pepper's Lonely Hearts Club Band" "The Beatles" "Rock" ["Rock & Roll" "Psychedelic Rock"]])) (comment (take 2 (map parse-line album-lines))) (defn line-vec->line-map "xs -> [\"1\" \"1967\" \"Sgt. Pepper's Lonely Hearts Club BandThe Beatles\" \"The beatles\" \"Rock\" [\"Rock & Roll\" \"Psychedelic Rock\"]] Output {:number \"1\" :year \"1967\" :artist \"The beatles\"p :album \"Sgt. Pepper's Lonely Hearts Club BandThe Beatles\" :genre \"Rock\" :subgenre-xs [\"Rock & Roll\" \"Psychedelic Rock\"]}" [xs] (let [[id year album artist genre subgenre-xs] xs] {:number id :year year :artist artist :album album :genre genre :subgenre subgenre-xs })) (comment (= (line-vec->line-map ["1" "1967" "Sgt. Pepper's Lonely Hearts Club BandThe Beatles" "The Beatles" "Rock" ["Rock & Roll" "Psychedelic Rock"]]) {:number "1" :year "1967" :artist "The Beatles" :album "Sgt. Pepper's Lonely Hearts Club BandThe Beatles" :genre "Rock" :subgenre ["Rock & Roll" "Psychedelic Rock"]})) (comment (take 10 (map line-vec->line-map (map parse-line album-lines)))) (defn line-xs->album-xs [album-lines] (map line-vec->line-map (map parse-line album-lines))) (defn populate-db [] (jdbc/init-db) (let [albums (line-xs->album-xs album-lines)] (doseq [album albums] (jdbc/insert! (update-in album [:subgenre] #(cs/join "," %)))))) ;; Check http://localhost:6789/albums ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Some more exploration with sequences ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn line-xs->rock-albums-xs [line-xs] (comment (map #_FIXME (filter #_FIXME #_FIXME)))) (comment (= (take 5 (line-xs->rock-albums-xs album-lines)) '("Sgt. Pepper's Lonely Hearts Club Band" "Pet Sounds" "Revolver" "Highway 61 Revisited" "Exile on Main St."))) (defn line-xs->albums-xs-before "Lists all albums before 'year'" [line-xs year] (comment (filter #_FIXME (map #_FIXME #_FIXME)))) (comment (= (take 5 (map (juxt :year :album) (line-xs->albums-xs-before 1987 album-lines))) '([1967 "Sgt. Pepper's Lonely Hearts Club Band"] [1966 "Pet Sounds"] [1966 "Revolver"] [1965 "Highway 61 Revisited"] [1965 "Rubber Soul"]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Some more exploration with reduce ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn artists-with-range "Artists who have most genres" [line-xs] (map #_FIXME (sort-by #_FIXME (reduce #_FIXME {} (map #_FIXME line-xs))))) (comment (= (take 5 (artists-with-range album-lines)) '("Various Artists" "<NAME>" "<NAME>" "<NAME>" "Talking Heads"))) (defn find-popular-year ;; Find top years for album releases [line-xs] (sort-by #_FIXME (reduce #_FIXME {} (map #_ME line-xs)))) (comment (= (take 5 (find-popular-year album-lines)) '(["1970" 26] ["1972" 24] ["1973" 23] ["1969" 22] ["1971" 21]))) (defn find-popular-artists [line-xs] ) (comment (= (find-popular-artists album-lines) '(["The Beatles" 10] ["<NAME>" 10] ["The Rolling Stones" 9] ["<NAME>" 7] ["The Who" 7]))) ;; We can transform data a great deal with just map, reduce and filter ;; Generally there are three patterns ;; Seq of N -> Seq of N (map) ;; Seq of N -> Seq of M (N > M) (filter) ;; Seq of N -> Any data structure (reduce) ;; This is great but what about lazy sequences all we processed till now was in-memory data ;; A stream from future timeline from 2040 data-gen/get-albums-xs ;; DONT evaluate the function in REPL it's a lazy sequence. ;; It's a list of albums generated from 2040 till infinity (take 10 (data-gen/get-albums-xs)) ;; Let's some of the functions we created till now (take 10 (line-xs->rock-albums-xs (data-gen/get-albums-xs))) ;; We can use line-xs->albums-xs-before to just get limited set ;; Right? (comment ;; This will evaluate for infinity since filter does not stop evaluation ;; We will just get infinite list of nils after year 2045 (line-xs->albums-xs-before (data-gen/get-albums-xs) 2045)) ;; https://clojure.org/api/cheatsheet ;; Espeically look for seq in and seq out (#_FIXME identity (line-xs->albums-xs-before (data-gen/get-albums-xs) 2045)) ;; Try applying functions we have created till now ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; END of chapter 1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Jump back to icw.core
true
(ns icw.data.process (:require [clojure.string :as cs] [icw.java-interop.jdbc :as jdbc] [clojure.data.csv :as csv] [clojure.string :as cs] [icw.data.gen :as data-gen] [clojure.string :as str])) ;; Reading and processing data from resources/data/albumlist.csv (defonce album-lines (drop 1 (line-seq (clojure.java.io/reader "resources/data/albumlist.csv")))) (comment (first album-lines)) ;; Parsing (defn parse-line "Input line -> \"1,1967,Sgt. Pepper's Lonely Hearts Club Band,The Beatles,Rock,\"Rock & Roll, Psychedelic Rock\" Output [\"1\" \"1967\" \"Sgt. Pepper's Lonely Hearts Club BandThe Beatles\" \"The Beatles\" \"Rock\" [\"Rock & Roll\" \"Psychedelic Rock\"]" [line] (let [foo (str/split line #"," 6)] (concat (butlast foo) [(map #(str/replace % "\"" "") (str/split (last foo) #","))]))) (comment (= (parse-line "1,1967,Sgt. Pepper's Lonely Hearts Club Band,The Beatles,Rock,\"Rock & Roll,Psychedelic Rock\"") ["1" "1967" "Sgt. Pepper's Lonely Hearts Club Band" "The Beatles" "Rock" ["Rock & Roll" "Psychedelic Rock"]])) (comment (take 2 (map parse-line album-lines))) (defn line-vec->line-map "xs -> [\"1\" \"1967\" \"Sgt. Pepper's Lonely Hearts Club BandThe Beatles\" \"The beatles\" \"Rock\" [\"Rock & Roll\" \"Psychedelic Rock\"]] Output {:number \"1\" :year \"1967\" :artist \"The beatles\"p :album \"Sgt. Pepper's Lonely Hearts Club BandThe Beatles\" :genre \"Rock\" :subgenre-xs [\"Rock & Roll\" \"Psychedelic Rock\"]}" [xs] (let [[id year album artist genre subgenre-xs] xs] {:number id :year year :artist artist :album album :genre genre :subgenre subgenre-xs })) (comment (= (line-vec->line-map ["1" "1967" "Sgt. Pepper's Lonely Hearts Club BandThe Beatles" "The Beatles" "Rock" ["Rock & Roll" "Psychedelic Rock"]]) {:number "1" :year "1967" :artist "The Beatles" :album "Sgt. Pepper's Lonely Hearts Club BandThe Beatles" :genre "Rock" :subgenre ["Rock & Roll" "Psychedelic Rock"]})) (comment (take 10 (map line-vec->line-map (map parse-line album-lines)))) (defn line-xs->album-xs [album-lines] (map line-vec->line-map (map parse-line album-lines))) (defn populate-db [] (jdbc/init-db) (let [albums (line-xs->album-xs album-lines)] (doseq [album albums] (jdbc/insert! (update-in album [:subgenre] #(cs/join "," %)))))) ;; Check http://localhost:6789/albums ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Some more exploration with sequences ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn line-xs->rock-albums-xs [line-xs] (comment (map #_FIXME (filter #_FIXME #_FIXME)))) (comment (= (take 5 (line-xs->rock-albums-xs album-lines)) '("Sgt. Pepper's Lonely Hearts Club Band" "Pet Sounds" "Revolver" "Highway 61 Revisited" "Exile on Main St."))) (defn line-xs->albums-xs-before "Lists all albums before 'year'" [line-xs year] (comment (filter #_FIXME (map #_FIXME #_FIXME)))) (comment (= (take 5 (map (juxt :year :album) (line-xs->albums-xs-before 1987 album-lines))) '([1967 "Sgt. Pepper's Lonely Hearts Club Band"] [1966 "Pet Sounds"] [1966 "Revolver"] [1965 "Highway 61 Revisited"] [1965 "Rubber Soul"]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Some more exploration with reduce ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn artists-with-range "Artists who have most genres" [line-xs] (map #_FIXME (sort-by #_FIXME (reduce #_FIXME {} (map #_FIXME line-xs))))) (comment (= (take 5 (artists-with-range album-lines)) '("Various Artists" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "Talking Heads"))) (defn find-popular-year ;; Find top years for album releases [line-xs] (sort-by #_FIXME (reduce #_FIXME {} (map #_ME line-xs)))) (comment (= (take 5 (find-popular-year album-lines)) '(["1970" 26] ["1972" 24] ["1973" 23] ["1969" 22] ["1971" 21]))) (defn find-popular-artists [line-xs] ) (comment (= (find-popular-artists album-lines) '(["The Beatles" 10] ["PI:NAME:<NAME>END_PI" 10] ["The Rolling Stones" 9] ["PI:NAME:<NAME>END_PI" 7] ["The Who" 7]))) ;; We can transform data a great deal with just map, reduce and filter ;; Generally there are three patterns ;; Seq of N -> Seq of N (map) ;; Seq of N -> Seq of M (N > M) (filter) ;; Seq of N -> Any data structure (reduce) ;; This is great but what about lazy sequences all we processed till now was in-memory data ;; A stream from future timeline from 2040 data-gen/get-albums-xs ;; DONT evaluate the function in REPL it's a lazy sequence. ;; It's a list of albums generated from 2040 till infinity (take 10 (data-gen/get-albums-xs)) ;; Let's some of the functions we created till now (take 10 (line-xs->rock-albums-xs (data-gen/get-albums-xs))) ;; We can use line-xs->albums-xs-before to just get limited set ;; Right? (comment ;; This will evaluate for infinity since filter does not stop evaluation ;; We will just get infinite list of nils after year 2045 (line-xs->albums-xs-before (data-gen/get-albums-xs) 2045)) ;; https://clojure.org/api/cheatsheet ;; Espeically look for seq in and seq out (#_FIXME identity (line-xs->albums-xs-before (data-gen/get-albums-xs) 2045)) ;; Try applying functions we have created till now ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; END of chapter 1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Jump back to icw.core
[ { "context": " [:h1 title]\n body\n [:hr]\n :&copy \" 2011 Howard M. Lewis Ship \"\n [:a.btn {:href \"https://github.com/hlship/c", "end": 668, "score": 0.999824047088623, "start": 648, "tag": "NAME", "value": "Howard M. Lewis Ship" }, { "context": "wis Ship \"\n [:a.btn {:href \"https://github.com/hlship/cascade\"} \"Cascade at GitHub\"]\n ]\n ])\n\n(defn", "end": 716, "score": 0.9951333999633789, "start": 710, "tag": "USERNAME", "value": "hlship" }, { "context": "[:h1 title]\n body\n [:hr]\n \"&copy; 2011 Howard M. Lewis Ship\"\n ]\n ]])\n\n(defn hgrid-url\n [width height]", "end": 3476, "score": 0.9998841285705566, "start": 3456, "tag": "NAME", "value": "Howard M. Lewis Ship" } ]
src/test_app.clj
hlship/cascade
8
; This is a temporary file that allows the use of "lein ring server" ; to test the framework with a sample app. (set! *warn-on-reflection* true) (ns test-app (:use compojure.core cascade cascade.asset cascade.import [hiccup core page-helpers]) (:require [cascade.request :as cr] [ring.util.response :as response] [compojure.route :as route] [compojure.handler :as handler])) (defragment layout [title body] (import-stylesheet classpath-asset "cascade/bootstrap.css") (import-stylesheet file-asset "app.css") [:html [:head>title title] [:body>div.container [:h1 title] body [:hr] :&copy " 2011 Howard M. Lewis Ship " [:a.btn {:href "https://github.com/hlship/cascade"} "Cascade at GitHub"] ] ]) (defn alert-message [level body] (javascript-invoke ["cascade/bootstrap-alerts"] ".alert-message" "alert") (markup [:div {:class [:alert-message level] :data-alert :alert} [:a.close {:href "#"} "x"] [:p body] ]) ) (defview hello-world [req] (javascript-invoke ["cascade/bootstrap-twipsy" "cascade/bootstrap-popover"] "#force-failure" "popover") (layout "Cascade Hello World" (markup (alert-message :warning (markup [:p "This page rendered at " [:strong (str (java.util.Date.))] "." ])) [:div.well [:a.btn.primary.large {:href "/hello"} "Refresh"] " " [:a.btn {:href "/cascade/grid"} "Cascade Grid Demo"] " " [:a.btn {:href "/hiccup/grid"} "Hiccup Grid Demo"] " " [:a.btn.danger#force-failure {:href "/hello/fail" :title "Caution!" :data-content "We force a divide by zero error to see Cascade's exception report."} "Force Failure"] ]))) (defn grid-url [width height] (format "/cascade/grid/%d/%d" width height)) (defragment add-button [width height] [:a.btn {:href (grid-url width height)} "+"]) (defview grid [width height] (layout "Grid Demo" (markup [:div.well>a.btn.primary.large {:href "/hello"} "Main"] [:h2 width "x" height " Grid"] [:table.bordered-table.zebra-striped [:thead>tr [:th] (markup-for [column (range 1 (inc width))] [:th "Column " column]) [:th (add-button (inc width) height)] ] [:tbody (markup-for [row (range 1 (inc height))] [:tr [:td "# " row] (markup-for [column (range 1 (inc width))] [:td>a {:href (grid-url column row)} "Cell " column "x" row]) [:td :&nbsp] ]) ] [:tfoot>tr [:td (add-button width (inc height))] (markup-for [column (range (inc width))] [:td :&nbsp]) ] ]))) (defn hiccup-layout [title & body] ; (import-stylesheet classpath-asset "cascade/bootstrap.css") ; (import-stylesheet file-asset "app.css") [:html [:head (include-css "/assets/1.0/classpath/cascade/bootstrap.css") [:title title]] [:body [:div.container [:h1 title] body [:hr] "&copy; 2011 Howard M. Lewis Ship" ] ]]) (defn hgrid-url [width height] (format "/hiccup/grid/%d/%d" width height)) (defn hadd-button [ width height] [:a.btn {:href (hgrid-url width height)} "+"]) (defhtml hiccup-grid [width height] (html (hiccup-layout "Hiccup Grid Demo" [:div.well [:a.btn.primary.large {:href "/hello"} "Main"]] [:h2 width "x" height " Grid"] [:table.bordered-table.zebra-striped [:thead [:tr [:th (for [column (range 1 (inc width))] [:th "Column " column]) [:th (hadd-button (inc width) height)] ] ] ] [:tbody (for [row (range 1 (inc height))] [:tr [:td "# " row] (for [column (range 1 (inc width))] [:td [:a {:href (hgrid-url column row)} "Cell " column "x" row]]) [:td "&nbsp;"] ]) ] [:tfoot [:tr [:td (hadd-button width (inc height))] (for [column (range (inc width))] [:td "&nbsp;"]) ]] ]))) (defn parse-int [string] (Integer/parseInt string)) (defroutes html-routes (GET "/hello" [] hello-world) (GET "/cascade/grid" [] (grid 3 5)) (GET "/cascade/grid/:width/:height" [width height] (grid (parse-int width) (parse-int height))) ; /hello/fail provokes an exception: (GET "/hello/fail" [] (try (/ 0 0) (catch Exception e (throw (RuntimeException. "Failure dividing by zero." e)))))) (defroutes master-routes (GET "/hiccup/grid" [] (hiccup-grid 3 5)) (GET "/hiccup/grid/:width/:height" [width height] (hiccup-grid (parse-int width) (parse-int height))) (cr/initialize "1.0" :public-folder "webapp" :html-routes html-routes) (ANY "/" [] (response/redirect "/hello")) (route/not-found "Cascade Demo: No such resource")) (def app (handler/site master-routes))
14455
; This is a temporary file that allows the use of "lein ring server" ; to test the framework with a sample app. (set! *warn-on-reflection* true) (ns test-app (:use compojure.core cascade cascade.asset cascade.import [hiccup core page-helpers]) (:require [cascade.request :as cr] [ring.util.response :as response] [compojure.route :as route] [compojure.handler :as handler])) (defragment layout [title body] (import-stylesheet classpath-asset "cascade/bootstrap.css") (import-stylesheet file-asset "app.css") [:html [:head>title title] [:body>div.container [:h1 title] body [:hr] :&copy " 2011 <NAME> " [:a.btn {:href "https://github.com/hlship/cascade"} "Cascade at GitHub"] ] ]) (defn alert-message [level body] (javascript-invoke ["cascade/bootstrap-alerts"] ".alert-message" "alert") (markup [:div {:class [:alert-message level] :data-alert :alert} [:a.close {:href "#"} "x"] [:p body] ]) ) (defview hello-world [req] (javascript-invoke ["cascade/bootstrap-twipsy" "cascade/bootstrap-popover"] "#force-failure" "popover") (layout "Cascade Hello World" (markup (alert-message :warning (markup [:p "This page rendered at " [:strong (str (java.util.Date.))] "." ])) [:div.well [:a.btn.primary.large {:href "/hello"} "Refresh"] " " [:a.btn {:href "/cascade/grid"} "Cascade Grid Demo"] " " [:a.btn {:href "/hiccup/grid"} "Hiccup Grid Demo"] " " [:a.btn.danger#force-failure {:href "/hello/fail" :title "Caution!" :data-content "We force a divide by zero error to see Cascade's exception report."} "Force Failure"] ]))) (defn grid-url [width height] (format "/cascade/grid/%d/%d" width height)) (defragment add-button [width height] [:a.btn {:href (grid-url width height)} "+"]) (defview grid [width height] (layout "Grid Demo" (markup [:div.well>a.btn.primary.large {:href "/hello"} "Main"] [:h2 width "x" height " Grid"] [:table.bordered-table.zebra-striped [:thead>tr [:th] (markup-for [column (range 1 (inc width))] [:th "Column " column]) [:th (add-button (inc width) height)] ] [:tbody (markup-for [row (range 1 (inc height))] [:tr [:td "# " row] (markup-for [column (range 1 (inc width))] [:td>a {:href (grid-url column row)} "Cell " column "x" row]) [:td :&nbsp] ]) ] [:tfoot>tr [:td (add-button width (inc height))] (markup-for [column (range (inc width))] [:td :&nbsp]) ] ]))) (defn hiccup-layout [title & body] ; (import-stylesheet classpath-asset "cascade/bootstrap.css") ; (import-stylesheet file-asset "app.css") [:html [:head (include-css "/assets/1.0/classpath/cascade/bootstrap.css") [:title title]] [:body [:div.container [:h1 title] body [:hr] "&copy; 2011 <NAME>" ] ]]) (defn hgrid-url [width height] (format "/hiccup/grid/%d/%d" width height)) (defn hadd-button [ width height] [:a.btn {:href (hgrid-url width height)} "+"]) (defhtml hiccup-grid [width height] (html (hiccup-layout "Hiccup Grid Demo" [:div.well [:a.btn.primary.large {:href "/hello"} "Main"]] [:h2 width "x" height " Grid"] [:table.bordered-table.zebra-striped [:thead [:tr [:th (for [column (range 1 (inc width))] [:th "Column " column]) [:th (hadd-button (inc width) height)] ] ] ] [:tbody (for [row (range 1 (inc height))] [:tr [:td "# " row] (for [column (range 1 (inc width))] [:td [:a {:href (hgrid-url column row)} "Cell " column "x" row]]) [:td "&nbsp;"] ]) ] [:tfoot [:tr [:td (hadd-button width (inc height))] (for [column (range (inc width))] [:td "&nbsp;"]) ]] ]))) (defn parse-int [string] (Integer/parseInt string)) (defroutes html-routes (GET "/hello" [] hello-world) (GET "/cascade/grid" [] (grid 3 5)) (GET "/cascade/grid/:width/:height" [width height] (grid (parse-int width) (parse-int height))) ; /hello/fail provokes an exception: (GET "/hello/fail" [] (try (/ 0 0) (catch Exception e (throw (RuntimeException. "Failure dividing by zero." e)))))) (defroutes master-routes (GET "/hiccup/grid" [] (hiccup-grid 3 5)) (GET "/hiccup/grid/:width/:height" [width height] (hiccup-grid (parse-int width) (parse-int height))) (cr/initialize "1.0" :public-folder "webapp" :html-routes html-routes) (ANY "/" [] (response/redirect "/hello")) (route/not-found "Cascade Demo: No such resource")) (def app (handler/site master-routes))
true
; This is a temporary file that allows the use of "lein ring server" ; to test the framework with a sample app. (set! *warn-on-reflection* true) (ns test-app (:use compojure.core cascade cascade.asset cascade.import [hiccup core page-helpers]) (:require [cascade.request :as cr] [ring.util.response :as response] [compojure.route :as route] [compojure.handler :as handler])) (defragment layout [title body] (import-stylesheet classpath-asset "cascade/bootstrap.css") (import-stylesheet file-asset "app.css") [:html [:head>title title] [:body>div.container [:h1 title] body [:hr] :&copy " 2011 PI:NAME:<NAME>END_PI " [:a.btn {:href "https://github.com/hlship/cascade"} "Cascade at GitHub"] ] ]) (defn alert-message [level body] (javascript-invoke ["cascade/bootstrap-alerts"] ".alert-message" "alert") (markup [:div {:class [:alert-message level] :data-alert :alert} [:a.close {:href "#"} "x"] [:p body] ]) ) (defview hello-world [req] (javascript-invoke ["cascade/bootstrap-twipsy" "cascade/bootstrap-popover"] "#force-failure" "popover") (layout "Cascade Hello World" (markup (alert-message :warning (markup [:p "This page rendered at " [:strong (str (java.util.Date.))] "." ])) [:div.well [:a.btn.primary.large {:href "/hello"} "Refresh"] " " [:a.btn {:href "/cascade/grid"} "Cascade Grid Demo"] " " [:a.btn {:href "/hiccup/grid"} "Hiccup Grid Demo"] " " [:a.btn.danger#force-failure {:href "/hello/fail" :title "Caution!" :data-content "We force a divide by zero error to see Cascade's exception report."} "Force Failure"] ]))) (defn grid-url [width height] (format "/cascade/grid/%d/%d" width height)) (defragment add-button [width height] [:a.btn {:href (grid-url width height)} "+"]) (defview grid [width height] (layout "Grid Demo" (markup [:div.well>a.btn.primary.large {:href "/hello"} "Main"] [:h2 width "x" height " Grid"] [:table.bordered-table.zebra-striped [:thead>tr [:th] (markup-for [column (range 1 (inc width))] [:th "Column " column]) [:th (add-button (inc width) height)] ] [:tbody (markup-for [row (range 1 (inc height))] [:tr [:td "# " row] (markup-for [column (range 1 (inc width))] [:td>a {:href (grid-url column row)} "Cell " column "x" row]) [:td :&nbsp] ]) ] [:tfoot>tr [:td (add-button width (inc height))] (markup-for [column (range (inc width))] [:td :&nbsp]) ] ]))) (defn hiccup-layout [title & body] ; (import-stylesheet classpath-asset "cascade/bootstrap.css") ; (import-stylesheet file-asset "app.css") [:html [:head (include-css "/assets/1.0/classpath/cascade/bootstrap.css") [:title title]] [:body [:div.container [:h1 title] body [:hr] "&copy; 2011 PI:NAME:<NAME>END_PI" ] ]]) (defn hgrid-url [width height] (format "/hiccup/grid/%d/%d" width height)) (defn hadd-button [ width height] [:a.btn {:href (hgrid-url width height)} "+"]) (defhtml hiccup-grid [width height] (html (hiccup-layout "Hiccup Grid Demo" [:div.well [:a.btn.primary.large {:href "/hello"} "Main"]] [:h2 width "x" height " Grid"] [:table.bordered-table.zebra-striped [:thead [:tr [:th (for [column (range 1 (inc width))] [:th "Column " column]) [:th (hadd-button (inc width) height)] ] ] ] [:tbody (for [row (range 1 (inc height))] [:tr [:td "# " row] (for [column (range 1 (inc width))] [:td [:a {:href (hgrid-url column row)} "Cell " column "x" row]]) [:td "&nbsp;"] ]) ] [:tfoot [:tr [:td (hadd-button width (inc height))] (for [column (range (inc width))] [:td "&nbsp;"]) ]] ]))) (defn parse-int [string] (Integer/parseInt string)) (defroutes html-routes (GET "/hello" [] hello-world) (GET "/cascade/grid" [] (grid 3 5)) (GET "/cascade/grid/:width/:height" [width height] (grid (parse-int width) (parse-int height))) ; /hello/fail provokes an exception: (GET "/hello/fail" [] (try (/ 0 0) (catch Exception e (throw (RuntimeException. "Failure dividing by zero." e)))))) (defroutes master-routes (GET "/hiccup/grid" [] (hiccup-grid 3 5)) (GET "/hiccup/grid/:width/:height" [width height] (hiccup-grid (parse-int width) (parse-int height))) (cr/initialize "1.0" :public-folder "webapp" :html-routes html-routes) (ANY "/" [] (response/redirect "/hello")) (route/not-found "Cascade Demo: No such resource")) (def app (handler/site master-routes))
[ { "context": ";; The MIT License (MIT)\n;;\n;; Copyright (c) 2015 Richard Hull\n;;\n;; Permission is hereby granted, free of charg", "end": 62, "score": 0.9997708201408386, "start": 50, "tag": "NAME", "value": "Richard Hull" } ]
src/wam/store.clj
rm-hull/wam
23
;; The MIT License (MIT) ;; ;; Copyright (c) 2015 Richard Hull ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in all ;; copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns wam.store (:require [table.core :refer [table table-str]] [clojure.string :refer [join split-lines]])) (def ^:private supported-modes #{:read :write}) (def ^:private supported-pointers #{:p :np :h :s}) (def program-pointer-start 0) (def heap-start 1000) (def heap-size 1000) (def heap-end (+ heap-start heap-size)) (def register-start (inc heap-end)) (def register-size 30) (def register-end (+ register-start register-size)) (def register-address (memoize (fn [Xi] (let [offset (->> Xi str (re-find #"\d+") Integer/parseInt)] (if (> offset register-size) (throw (IllegalArgumentException.)) (+ register-start offset)))))) (defn pointer [ctx ptr] (if (supported-pointers ptr) (get-in ctx [:pointer ptr]) (throw (IllegalArgumentException. (str "Unsuported pointer " ptr))))) (defn increment [ctx ptr] (if (supported-pointers ptr) (update-in ctx [:pointer ptr] inc) (throw (IllegalArgumentException. (str "Unsuported pointer " ptr))))) (defn program-address [ctx p|N] (:start-addr (get-in ctx [:program-offsets p|N]))) (defn get-store [ctx addr] (get-in ctx [:store addr])) (defn get-register [ctx Xi] (let [addr (register-address Xi)] (get-store ctx addr))) (defn set-store [ctx addr v] (assoc-in ctx [:store addr] v)) (defn set-register [ctx Xi v] (let [addr (register-address Xi)] (set-store ctx addr v))) (defn make-context [] {:fail false :mode :read :pointer {:p program-pointer-start ;; Program pointer :np program-pointer-start ;; next instr pointer :h heap-start ;; Top of heap :s heap-start ;; Structure pointer } :store {} :program-offsets {}}) (defn load [ctx p|N instrs] (let [len (count instrs) np (pointer ctx :np) ctx (-> ctx (assoc-in [:program-offsets p|N] {:start-addr np :size len}) (update-in [:pointer :np] (partial + len)))] (loop [ctx ctx i np [instr & more] instrs] (if (nil? instr) ctx (recur (set-store ctx i instr) (inc i) more))))) (defn fail ([ctx] (fail ctx true)) ([ctx status] (assoc ctx :fail status))) (defn mode [ctx new-mode] (if (supported-modes new-mode) (assoc ctx :mode new-mode) (throw (IllegalArgumentException. (str "Unsupported mode " new-mode))))) ;; == Diagnostic tools == ;; move out into a separate namespace (defn ^:private extract-from-store ([ctx start end] (extract-from-store ctx start end identity)) ([ctx start end row-mapper] (->> ctx :store (filter (fn [[k v]] (<= start k end))) (map row-mapper) (into (sorted-map))))) (defn heap [ctx] (extract-from-store ctx heap-start heap-end)) (defn registers [ctx] (extract-from-store ctx register-start register-end (fn [[k v]] [(symbol (str "X" (- k register-start))) v]))) (defn variables [ctx] (->> ctx :variables (into (sorted-map)))) (defn func-name [func] (second (re-find #"\$(.*)@" (str func)))) (defn friendly [[instr & args]] (str (func-name instr) " " (join ", " args))) (defn program [ctx p|N] (if-let [prog (get-in ctx [:program-offsets p|N])] (extract-from-store ctx (:start-addr prog) (+ (:start-addr prog) (:size prog)) (fn [[k v]] [k (friendly v)])))) (defn diag [ctx] (let [inflate (fn [data] (lazy-cat data (repeat nil))) heap (split-lines (table-str (heap ctx) :style :unicode)) regs (inflate (split-lines (table-str (registers ctx) :style :unicode))) vars (inflate (split-lines (table-str (variables ctx) :style :unicode))) data (map list heap regs vars)] (when (:fail ctx) (println "FAILED")) (table (cons ["Heap" "Registers" "Variables"] data) :style :borderless)) ctx)
8968
;; The MIT License (MIT) ;; ;; Copyright (c) 2015 <NAME> ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in all ;; copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns wam.store (:require [table.core :refer [table table-str]] [clojure.string :refer [join split-lines]])) (def ^:private supported-modes #{:read :write}) (def ^:private supported-pointers #{:p :np :h :s}) (def program-pointer-start 0) (def heap-start 1000) (def heap-size 1000) (def heap-end (+ heap-start heap-size)) (def register-start (inc heap-end)) (def register-size 30) (def register-end (+ register-start register-size)) (def register-address (memoize (fn [Xi] (let [offset (->> Xi str (re-find #"\d+") Integer/parseInt)] (if (> offset register-size) (throw (IllegalArgumentException.)) (+ register-start offset)))))) (defn pointer [ctx ptr] (if (supported-pointers ptr) (get-in ctx [:pointer ptr]) (throw (IllegalArgumentException. (str "Unsuported pointer " ptr))))) (defn increment [ctx ptr] (if (supported-pointers ptr) (update-in ctx [:pointer ptr] inc) (throw (IllegalArgumentException. (str "Unsuported pointer " ptr))))) (defn program-address [ctx p|N] (:start-addr (get-in ctx [:program-offsets p|N]))) (defn get-store [ctx addr] (get-in ctx [:store addr])) (defn get-register [ctx Xi] (let [addr (register-address Xi)] (get-store ctx addr))) (defn set-store [ctx addr v] (assoc-in ctx [:store addr] v)) (defn set-register [ctx Xi v] (let [addr (register-address Xi)] (set-store ctx addr v))) (defn make-context [] {:fail false :mode :read :pointer {:p program-pointer-start ;; Program pointer :np program-pointer-start ;; next instr pointer :h heap-start ;; Top of heap :s heap-start ;; Structure pointer } :store {} :program-offsets {}}) (defn load [ctx p|N instrs] (let [len (count instrs) np (pointer ctx :np) ctx (-> ctx (assoc-in [:program-offsets p|N] {:start-addr np :size len}) (update-in [:pointer :np] (partial + len)))] (loop [ctx ctx i np [instr & more] instrs] (if (nil? instr) ctx (recur (set-store ctx i instr) (inc i) more))))) (defn fail ([ctx] (fail ctx true)) ([ctx status] (assoc ctx :fail status))) (defn mode [ctx new-mode] (if (supported-modes new-mode) (assoc ctx :mode new-mode) (throw (IllegalArgumentException. (str "Unsupported mode " new-mode))))) ;; == Diagnostic tools == ;; move out into a separate namespace (defn ^:private extract-from-store ([ctx start end] (extract-from-store ctx start end identity)) ([ctx start end row-mapper] (->> ctx :store (filter (fn [[k v]] (<= start k end))) (map row-mapper) (into (sorted-map))))) (defn heap [ctx] (extract-from-store ctx heap-start heap-end)) (defn registers [ctx] (extract-from-store ctx register-start register-end (fn [[k v]] [(symbol (str "X" (- k register-start))) v]))) (defn variables [ctx] (->> ctx :variables (into (sorted-map)))) (defn func-name [func] (second (re-find #"\$(.*)@" (str func)))) (defn friendly [[instr & args]] (str (func-name instr) " " (join ", " args))) (defn program [ctx p|N] (if-let [prog (get-in ctx [:program-offsets p|N])] (extract-from-store ctx (:start-addr prog) (+ (:start-addr prog) (:size prog)) (fn [[k v]] [k (friendly v)])))) (defn diag [ctx] (let [inflate (fn [data] (lazy-cat data (repeat nil))) heap (split-lines (table-str (heap ctx) :style :unicode)) regs (inflate (split-lines (table-str (registers ctx) :style :unicode))) vars (inflate (split-lines (table-str (variables ctx) :style :unicode))) data (map list heap regs vars)] (when (:fail ctx) (println "FAILED")) (table (cons ["Heap" "Registers" "Variables"] data) :style :borderless)) ctx)
true
;; The MIT License (MIT) ;; ;; Copyright (c) 2015 PI:NAME:<NAME>END_PI ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in all ;; copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns wam.store (:require [table.core :refer [table table-str]] [clojure.string :refer [join split-lines]])) (def ^:private supported-modes #{:read :write}) (def ^:private supported-pointers #{:p :np :h :s}) (def program-pointer-start 0) (def heap-start 1000) (def heap-size 1000) (def heap-end (+ heap-start heap-size)) (def register-start (inc heap-end)) (def register-size 30) (def register-end (+ register-start register-size)) (def register-address (memoize (fn [Xi] (let [offset (->> Xi str (re-find #"\d+") Integer/parseInt)] (if (> offset register-size) (throw (IllegalArgumentException.)) (+ register-start offset)))))) (defn pointer [ctx ptr] (if (supported-pointers ptr) (get-in ctx [:pointer ptr]) (throw (IllegalArgumentException. (str "Unsuported pointer " ptr))))) (defn increment [ctx ptr] (if (supported-pointers ptr) (update-in ctx [:pointer ptr] inc) (throw (IllegalArgumentException. (str "Unsuported pointer " ptr))))) (defn program-address [ctx p|N] (:start-addr (get-in ctx [:program-offsets p|N]))) (defn get-store [ctx addr] (get-in ctx [:store addr])) (defn get-register [ctx Xi] (let [addr (register-address Xi)] (get-store ctx addr))) (defn set-store [ctx addr v] (assoc-in ctx [:store addr] v)) (defn set-register [ctx Xi v] (let [addr (register-address Xi)] (set-store ctx addr v))) (defn make-context [] {:fail false :mode :read :pointer {:p program-pointer-start ;; Program pointer :np program-pointer-start ;; next instr pointer :h heap-start ;; Top of heap :s heap-start ;; Structure pointer } :store {} :program-offsets {}}) (defn load [ctx p|N instrs] (let [len (count instrs) np (pointer ctx :np) ctx (-> ctx (assoc-in [:program-offsets p|N] {:start-addr np :size len}) (update-in [:pointer :np] (partial + len)))] (loop [ctx ctx i np [instr & more] instrs] (if (nil? instr) ctx (recur (set-store ctx i instr) (inc i) more))))) (defn fail ([ctx] (fail ctx true)) ([ctx status] (assoc ctx :fail status))) (defn mode [ctx new-mode] (if (supported-modes new-mode) (assoc ctx :mode new-mode) (throw (IllegalArgumentException. (str "Unsupported mode " new-mode))))) ;; == Diagnostic tools == ;; move out into a separate namespace (defn ^:private extract-from-store ([ctx start end] (extract-from-store ctx start end identity)) ([ctx start end row-mapper] (->> ctx :store (filter (fn [[k v]] (<= start k end))) (map row-mapper) (into (sorted-map))))) (defn heap [ctx] (extract-from-store ctx heap-start heap-end)) (defn registers [ctx] (extract-from-store ctx register-start register-end (fn [[k v]] [(symbol (str "X" (- k register-start))) v]))) (defn variables [ctx] (->> ctx :variables (into (sorted-map)))) (defn func-name [func] (second (re-find #"\$(.*)@" (str func)))) (defn friendly [[instr & args]] (str (func-name instr) " " (join ", " args))) (defn program [ctx p|N] (if-let [prog (get-in ctx [:program-offsets p|N])] (extract-from-store ctx (:start-addr prog) (+ (:start-addr prog) (:size prog)) (fn [[k v]] [k (friendly v)])))) (defn diag [ctx] (let [inflate (fn [data] (lazy-cat data (repeat nil))) heap (split-lines (table-str (heap ctx) :style :unicode)) regs (inflate (split-lines (table-str (registers ctx) :style :unicode))) vars (inflate (split-lines (table-str (variables ctx) :style :unicode))) data (map list heap regs vars)] (when (:fail ctx) (println "FAILED")) (table (cons ["Heap" "Registers" "Variables"] data) :style :borderless)) ctx)
[ { "context": ";; Ben Fry's Visualizing Data, Chapter 6, figure 6-2\n;; Select", "end": 12, "score": 0.9426079988479614, "start": 3, "tag": "NAME", "value": "Ben Fry's" }, { "context": "erted from Processing to Clojure as an exercise by Dave Liepmann\n\n(ns vdquil.chapter6.figure6-2\n (:use [quil.core", "end": 159, "score": 0.9998408555984497, "start": 146, "tag": "NAME", "value": "Dave Liepmann" }, { "context": "hars 40 (- (height) 40))))\n\n(def deletion-key? #{\\backspace}) ;; TODO test this key on a Windows machine\n(def", "end": 2054, "score": 0.9191820621490479, "start": 2045, "tag": "KEY", "value": "backspace" } ]
data/test/clojure/24ac2108e50645c291b569928954c32b96150f23figure6-2.clj
harshp8l/deep-learning-lang-detection
84
;; Ben Fry's Visualizing Data, Chapter 6, figure 6-2 ;; Selecting a region of zip codes ;; Converted from Processing to Clojure as an exercise by Dave Liepmann (ns vdquil.chapter6.figure6-2 (:use [quil.core] [vdquil.util]) (:require [clojure.java.io :as io] [clojure.string :as string])) (def canvas-height 453) (def canvas-width 720) (defn setup [] (text-font (load-font "ScalaSans-Regular-14.vlw")) (text-mode :screen)) ;; First line of the data is record count / minX / maxX / minY / maxY ;; I just manually pulled it in--let's not overcomplicate things. ;; # 41556,-0.3667764,0.35192886,0.4181981,0.87044954 ;; From the first line of the original zips.tsv: (def min-longitude -0.3667764) (def min-latitude 0.4181981) (def max-longitude 0.35192886) (def max-latitude 0.87044954) (def typed-chars (atom "")) ;; TODO pull in performance improvements from zoomable version (defn draw [] (smooth) (background (hex-to-color "#333333")) (with-open [zips (io/reader "data/zips-modified.tsv")] (doseq [line (line-seq zips)] (let [l (string/split line #"\t") clr (if (= 0 (count @typed-chars)) "#999966" ;; dormant color, since we have selected no zips (if (= (subs (first l) 0 (count @typed-chars)) @typed-chars) "#CBCBCB" ;; highlight color, since this matches what the user entered "#66664C"))] ;; unhighlight color, since this point is not selected (set-pixel (map-range (read-string (second l)) min-longitude max-longitude 30 (- canvas-width 30)) (map-range (read-string (nth l 2)) min-latitude max-latitude (- canvas-height 20) 20) (hex-to-color clr))))) ;; solicit user input (fill (hex-to-color "#CBCBCB")) (if (= @typed-chars "") (text "type the digits of a zip code" 40 (- (height) 40)) (text @typed-chars 40 (- (height) 40)))) (def deletion-key? #{\backspace}) ;; TODO test this key on a Windows machine (def number-key? (set (map char (range 48 58)))) (defn key-handler "Manage keyboard input of 0 to 5 digits" [] (let [key (if (= processing.core.PConstants/CODED (int (raw-key))) (key-code) (raw-key))] (cond (and (deletion-key? key) (> (count @typed-chars) 0)) (swap! typed-chars #(apply str (butlast %))) (and (number-key? key) (< (count @typed-chars) 5)) (swap! typed-chars #(str % key))))) (defsketch zips :title "Figure 6-2: selecting a region of zip codes" :setup setup :draw draw :size [canvas-width canvas-height] :renderer :p2d :key-pressed key-handler)
124981
;; <NAME> Visualizing Data, Chapter 6, figure 6-2 ;; Selecting a region of zip codes ;; Converted from Processing to Clojure as an exercise by <NAME> (ns vdquil.chapter6.figure6-2 (:use [quil.core] [vdquil.util]) (:require [clojure.java.io :as io] [clojure.string :as string])) (def canvas-height 453) (def canvas-width 720) (defn setup [] (text-font (load-font "ScalaSans-Regular-14.vlw")) (text-mode :screen)) ;; First line of the data is record count / minX / maxX / minY / maxY ;; I just manually pulled it in--let's not overcomplicate things. ;; # 41556,-0.3667764,0.35192886,0.4181981,0.87044954 ;; From the first line of the original zips.tsv: (def min-longitude -0.3667764) (def min-latitude 0.4181981) (def max-longitude 0.35192886) (def max-latitude 0.87044954) (def typed-chars (atom "")) ;; TODO pull in performance improvements from zoomable version (defn draw [] (smooth) (background (hex-to-color "#333333")) (with-open [zips (io/reader "data/zips-modified.tsv")] (doseq [line (line-seq zips)] (let [l (string/split line #"\t") clr (if (= 0 (count @typed-chars)) "#999966" ;; dormant color, since we have selected no zips (if (= (subs (first l) 0 (count @typed-chars)) @typed-chars) "#CBCBCB" ;; highlight color, since this matches what the user entered "#66664C"))] ;; unhighlight color, since this point is not selected (set-pixel (map-range (read-string (second l)) min-longitude max-longitude 30 (- canvas-width 30)) (map-range (read-string (nth l 2)) min-latitude max-latitude (- canvas-height 20) 20) (hex-to-color clr))))) ;; solicit user input (fill (hex-to-color "#CBCBCB")) (if (= @typed-chars "") (text "type the digits of a zip code" 40 (- (height) 40)) (text @typed-chars 40 (- (height) 40)))) (def deletion-key? #{\<KEY>}) ;; TODO test this key on a Windows machine (def number-key? (set (map char (range 48 58)))) (defn key-handler "Manage keyboard input of 0 to 5 digits" [] (let [key (if (= processing.core.PConstants/CODED (int (raw-key))) (key-code) (raw-key))] (cond (and (deletion-key? key) (> (count @typed-chars) 0)) (swap! typed-chars #(apply str (butlast %))) (and (number-key? key) (< (count @typed-chars) 5)) (swap! typed-chars #(str % key))))) (defsketch zips :title "Figure 6-2: selecting a region of zip codes" :setup setup :draw draw :size [canvas-width canvas-height] :renderer :p2d :key-pressed key-handler)
true
;; PI:NAME:<NAME>END_PI Visualizing Data, Chapter 6, figure 6-2 ;; Selecting a region of zip codes ;; Converted from Processing to Clojure as an exercise by PI:NAME:<NAME>END_PI (ns vdquil.chapter6.figure6-2 (:use [quil.core] [vdquil.util]) (:require [clojure.java.io :as io] [clojure.string :as string])) (def canvas-height 453) (def canvas-width 720) (defn setup [] (text-font (load-font "ScalaSans-Regular-14.vlw")) (text-mode :screen)) ;; First line of the data is record count / minX / maxX / minY / maxY ;; I just manually pulled it in--let's not overcomplicate things. ;; # 41556,-0.3667764,0.35192886,0.4181981,0.87044954 ;; From the first line of the original zips.tsv: (def min-longitude -0.3667764) (def min-latitude 0.4181981) (def max-longitude 0.35192886) (def max-latitude 0.87044954) (def typed-chars (atom "")) ;; TODO pull in performance improvements from zoomable version (defn draw [] (smooth) (background (hex-to-color "#333333")) (with-open [zips (io/reader "data/zips-modified.tsv")] (doseq [line (line-seq zips)] (let [l (string/split line #"\t") clr (if (= 0 (count @typed-chars)) "#999966" ;; dormant color, since we have selected no zips (if (= (subs (first l) 0 (count @typed-chars)) @typed-chars) "#CBCBCB" ;; highlight color, since this matches what the user entered "#66664C"))] ;; unhighlight color, since this point is not selected (set-pixel (map-range (read-string (second l)) min-longitude max-longitude 30 (- canvas-width 30)) (map-range (read-string (nth l 2)) min-latitude max-latitude (- canvas-height 20) 20) (hex-to-color clr))))) ;; solicit user input (fill (hex-to-color "#CBCBCB")) (if (= @typed-chars "") (text "type the digits of a zip code" 40 (- (height) 40)) (text @typed-chars 40 (- (height) 40)))) (def deletion-key? #{\PI:KEY:<KEY>END_PI}) ;; TODO test this key on a Windows machine (def number-key? (set (map char (range 48 58)))) (defn key-handler "Manage keyboard input of 0 to 5 digits" [] (let [key (if (= processing.core.PConstants/CODED (int (raw-key))) (key-code) (raw-key))] (cond (and (deletion-key? key) (> (count @typed-chars) 0)) (swap! typed-chars #(apply str (butlast %))) (and (number-key? key) (< (count @typed-chars) 5)) (swap! typed-chars #(str % key))))) (defsketch zips :title "Figure 6-2: selecting a region of zip codes" :setup setup :draw draw :size [canvas-width canvas-height] :renderer :p2d :key-pressed key-handler)
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-09-09\"\n :doc \"Tests for zana.co", "end": 105, "score": 0.9998774528503418, "start": 87, "tag": "NAME", "value": "John Alan McDonald" } ]
src/test/clojure/zana/test/collections/cube.clj
wahpenayo/zana
2
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "John Alan McDonald" :date "2016-09-09" :doc "Tests for zana.collections.cube" } zana.test.collections.cube (:require [clojure.test :as test] [clojure.pprint :as pp] [zana.test.defs.data.empty :as empty] [zana.test.defs.data.primitive :as primitive] [zana.test.defs.data.typical :as typical] [zana.test.defs.data.change :as change] [zana.test.data.setup :as setup] [zana.api :as z])) ;; mvn -Dtest=zana.test.collections.cube clojure:test ;;------------------------------------------------------------------------------ ;; no recursion ;; TODO: test something (test/deftest primitive (let [data (setup/primitives) cube (z/cube primitive/non-numerical-attributes data)] ; (println cube) ; (println) ; (println (z/pprint-str cube)) ; (println) ; (println (z/pprint-str (into {} cube))) ; (println) ; (println ; (z/pprint-str ; (z/map (fn [k v] (z/count v)) cube))) )) ;;------------------------------------------------------------------------------
122216
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>" :date "2016-09-09" :doc "Tests for zana.collections.cube" } zana.test.collections.cube (:require [clojure.test :as test] [clojure.pprint :as pp] [zana.test.defs.data.empty :as empty] [zana.test.defs.data.primitive :as primitive] [zana.test.defs.data.typical :as typical] [zana.test.defs.data.change :as change] [zana.test.data.setup :as setup] [zana.api :as z])) ;; mvn -Dtest=zana.test.collections.cube clojure:test ;;------------------------------------------------------------------------------ ;; no recursion ;; TODO: test something (test/deftest primitive (let [data (setup/primitives) cube (z/cube primitive/non-numerical-attributes data)] ; (println cube) ; (println) ; (println (z/pprint-str cube)) ; (println) ; (println (z/pprint-str (into {} cube))) ; (println) ; (println ; (z/pprint-str ; (z/map (fn [k v] (z/count v)) cube))) )) ;;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-09-09" :doc "Tests for zana.collections.cube" } zana.test.collections.cube (:require [clojure.test :as test] [clojure.pprint :as pp] [zana.test.defs.data.empty :as empty] [zana.test.defs.data.primitive :as primitive] [zana.test.defs.data.typical :as typical] [zana.test.defs.data.change :as change] [zana.test.data.setup :as setup] [zana.api :as z])) ;; mvn -Dtest=zana.test.collections.cube clojure:test ;;------------------------------------------------------------------------------ ;; no recursion ;; TODO: test something (test/deftest primitive (let [data (setup/primitives) cube (z/cube primitive/non-numerical-attributes data)] ; (println cube) ; (println) ; (println (z/pprint-str cube)) ; (println) ; (println (z/pprint-str (into {} cube))) ; (println) ; (println ; (z/pprint-str ; (z/map (fn [k v] (z/count v)) cube))) )) ;;------------------------------------------------------------------------------
[ { "context": "NSE-2.0\"\n :year 2021\n :key \"apache-2.0\"}\n :dependencies [[org.clojure/clojure \"1.10.3\"]", "end": 277, "score": 0.9716542959213257, "start": 267, "tag": "KEY", "value": "apache-2.0" } ]
client/project.clj
runopsio/demo-grpc
0
(defproject protojure-tutorial "0.0.1-SNAPSHOT" :description "FIXME: write description" :url "http://example.com/FIXME" :license {:name "Apache License 2.0" :url "https://www.apache.org/licenses/LICENSE-2.0" :year 2021 :key "apache-2.0"} :dependencies [[org.clojure/clojure "1.10.3"] ;; logging [com.taoensso/timbre "5.1.2"] [com.fzakaria/slf4j-timbre "0.3.21"] [ch.qos.logback/logback-classic "1.2.3" :exclusions [org.slf4j/slf4j-api]] [org.slf4j/jul-to-slf4j "1.7.30"] [org.slf4j/jcl-over-slf4j "1.7.30"] [org.slf4j/log4j-over-slf4j "1.7.30"] ;; -- PROTOC-GEN-CLOJURE -- [protojure "1.5.14"] [protojure/google.protobuf "0.9.1"] [com.google.protobuf/protobuf-java "3.13.0"] ;; -- PROTOC-GEN-CLOJURE HTTP/2 Client Lib Dependencies -- [org.eclipse.jetty.http2/http2-client "9.4.20.v20190813"] [org.eclipse.jetty/jetty-alpn-java-client "9.4.28.v20200408"] ;; -- Jetty Client Dep -- [org.ow2.asm/asm "8.0.1"]] :source-paths ["src"] :resource-paths ["resources"] :aliases {"run-client" ["trampoline" "run" "-m" "grpccli.core/run-client"]} :main ^{:skip-aot true} grpccli.core)
12607
(defproject protojure-tutorial "0.0.1-SNAPSHOT" :description "FIXME: write description" :url "http://example.com/FIXME" :license {:name "Apache License 2.0" :url "https://www.apache.org/licenses/LICENSE-2.0" :year 2021 :key "<KEY>"} :dependencies [[org.clojure/clojure "1.10.3"] ;; logging [com.taoensso/timbre "5.1.2"] [com.fzakaria/slf4j-timbre "0.3.21"] [ch.qos.logback/logback-classic "1.2.3" :exclusions [org.slf4j/slf4j-api]] [org.slf4j/jul-to-slf4j "1.7.30"] [org.slf4j/jcl-over-slf4j "1.7.30"] [org.slf4j/log4j-over-slf4j "1.7.30"] ;; -- PROTOC-GEN-CLOJURE -- [protojure "1.5.14"] [protojure/google.protobuf "0.9.1"] [com.google.protobuf/protobuf-java "3.13.0"] ;; -- PROTOC-GEN-CLOJURE HTTP/2 Client Lib Dependencies -- [org.eclipse.jetty.http2/http2-client "9.4.20.v20190813"] [org.eclipse.jetty/jetty-alpn-java-client "9.4.28.v20200408"] ;; -- Jetty Client Dep -- [org.ow2.asm/asm "8.0.1"]] :source-paths ["src"] :resource-paths ["resources"] :aliases {"run-client" ["trampoline" "run" "-m" "grpccli.core/run-client"]} :main ^{:skip-aot true} grpccli.core)
true
(defproject protojure-tutorial "0.0.1-SNAPSHOT" :description "FIXME: write description" :url "http://example.com/FIXME" :license {:name "Apache License 2.0" :url "https://www.apache.org/licenses/LICENSE-2.0" :year 2021 :key "PI:KEY:<KEY>END_PI"} :dependencies [[org.clojure/clojure "1.10.3"] ;; logging [com.taoensso/timbre "5.1.2"] [com.fzakaria/slf4j-timbre "0.3.21"] [ch.qos.logback/logback-classic "1.2.3" :exclusions [org.slf4j/slf4j-api]] [org.slf4j/jul-to-slf4j "1.7.30"] [org.slf4j/jcl-over-slf4j "1.7.30"] [org.slf4j/log4j-over-slf4j "1.7.30"] ;; -- PROTOC-GEN-CLOJURE -- [protojure "1.5.14"] [protojure/google.protobuf "0.9.1"] [com.google.protobuf/protobuf-java "3.13.0"] ;; -- PROTOC-GEN-CLOJURE HTTP/2 Client Lib Dependencies -- [org.eclipse.jetty.http2/http2-client "9.4.20.v20190813"] [org.eclipse.jetty/jetty-alpn-java-client "9.4.28.v20200408"] ;; -- Jetty Client Dep -- [org.ow2.asm/asm "8.0.1"]] :source-paths ["src"] :resource-paths ["resources"] :aliases {"run-client" ["trampoline" "run" "-m" "grpccli.core/run-client"]} :main ^{:skip-aot true} grpccli.core)
[ { "context": "al]]])))\n\n(defn simple-example []\n [:div\n [:p \"Merhaba\"]\n [counting-component]\n [timer-component]\n ", "end": 871, "score": 0.9984667897224426, "start": 864, "tag": "NAME", "value": "Merhaba" } ]
clj/ex/study_reagent/ex04/src/simpleexample/core.cljs
mertnuhoglu/study
1
(ns simpleexample.core (:require [reagent.core :as r] [reagent.dom :as rdom])) (defn timer-component [] (let [seconds-elapsed (r/atom 0)] (fn [] (js/setTimeout #(swap! seconds-elapsed inc) 1000) [:div "Seconds Elapsed: " @seconds-elapsed]))) (def click-count (r/atom 0)) (defn counting-component [] [:div "The atom " [:code "click-count"] " has value: " @click-count ". " [:input {:type "button" :value "Click me!" :on-click #(swap! click-count inc)}]]) (defn atom-input [value] [:input {:type "text" :value @value :on-change #(reset! value (-> % .-target .-value))}]) (defn shared-state [] (let [val (r/atom "foo")] (fn [] [:div [:p "The value is now: " @val] [:p "Change it here: " [atom-input val]]]))) (defn simple-example [] [:div [:p "Merhaba"] [counting-component] [timer-component] [shared-state] ]) (defn ^:export run [] (rdom/render [simple-example] (js/document.getElementById "app")))
78667
(ns simpleexample.core (:require [reagent.core :as r] [reagent.dom :as rdom])) (defn timer-component [] (let [seconds-elapsed (r/atom 0)] (fn [] (js/setTimeout #(swap! seconds-elapsed inc) 1000) [:div "Seconds Elapsed: " @seconds-elapsed]))) (def click-count (r/atom 0)) (defn counting-component [] [:div "The atom " [:code "click-count"] " has value: " @click-count ". " [:input {:type "button" :value "Click me!" :on-click #(swap! click-count inc)}]]) (defn atom-input [value] [:input {:type "text" :value @value :on-change #(reset! value (-> % .-target .-value))}]) (defn shared-state [] (let [val (r/atom "foo")] (fn [] [:div [:p "The value is now: " @val] [:p "Change it here: " [atom-input val]]]))) (defn simple-example [] [:div [:p "<NAME>"] [counting-component] [timer-component] [shared-state] ]) (defn ^:export run [] (rdom/render [simple-example] (js/document.getElementById "app")))
true
(ns simpleexample.core (:require [reagent.core :as r] [reagent.dom :as rdom])) (defn timer-component [] (let [seconds-elapsed (r/atom 0)] (fn [] (js/setTimeout #(swap! seconds-elapsed inc) 1000) [:div "Seconds Elapsed: " @seconds-elapsed]))) (def click-count (r/atom 0)) (defn counting-component [] [:div "The atom " [:code "click-count"] " has value: " @click-count ". " [:input {:type "button" :value "Click me!" :on-click #(swap! click-count inc)}]]) (defn atom-input [value] [:input {:type "text" :value @value :on-change #(reset! value (-> % .-target .-value))}]) (defn shared-state [] (let [val (r/atom "foo")] (fn [] [:div [:p "The value is now: " @val] [:p "Change it here: " [atom-input val]]]))) (defn simple-example [] [:div [:p "PI:NAME:<NAME>END_PI"] [counting-component] [timer-component] [shared-state] ]) (defn ^:export run [] (rdom/render [simple-example] (js/document.getElementById "app")))
[ { "context": "]\n :billing-address {:first-name \"Tamizhvendan\"\n :last-name \"", "end": 2343, "score": 0.9998260140419006, "start": 2331, "tag": "NAME", "value": "Tamizhvendan" }, { "context": "\"\n :last-name \"Sembiyan\"\n :line1 \"", "end": 2401, "score": 0.999814510345459, "start": 2393, "tag": "NAME", "value": "Sembiyan" }, { "context": "}\n :shipping-address {:first-name \"Tamizhvendan\"\n :last-name \"", "end": 2768, "score": 0.999809205532074, "start": 2756, "tag": "NAME", "value": "Tamizhvendan" }, { "context": "\"\n :last-name \"Sembiyan\"\n :line1 \"", "end": 2826, "score": 0.9998166561126709, "start": 2818, "tag": "NAME", "value": "Sembiyan" } ]
clojure/wheel/src/wheel/oms/order.clj
demystifyfp/BlogSamples
30
(ns wheel.oms.order (:require [clojure.spec.alpha :as s] [wheel.oms.address :as addr] [wheel.oms.payment :as payment] [wheel.oms.order-line :as order-line] [wheel.string :as w-str] [clojure.data.xml :as xml])) (s/def ::order-no w-str/not-blank?) (s/def ::payments (s/coll-of ::payment/payment :min-count 1)) (s/def ::order-lines (s/coll-of ::order-line/order-line :min-count 1)) (s/def ::billing-address ::addr/address) (s/def ::shipping-address ::addr/address) (s/def ::order (s/keys :req-un [::order-no ::shipping-address ::billing-address ::payments ::order-lines])) (defn address-to-xml [{:keys [first-name last-name line1 line2 city state pincode]}] {:attrs {:FirstName first-name :LastName last-name :State state :City city :Pincode pincode} :ext [:Extn {:IRLAddressLine1 line1 :IRLAddressLine2 line2}]}) (defn to-xml [order] {:pre [(s/assert ::order order)]} (let [{:keys [order-no billing-address order-lines shipping-address payments]} order {bill-to-attrs :attrs bill-to-ext :ext} (address-to-xml billing-address) {ship-to-attrs :attrs ship-to-ext :ext} (address-to-xml shipping-address)] (-> [:Order {:OrderNo order-no} [:PersonInfoBillTo bill-to-attrs bill-to-ext] [:PersonInfoShipTo ship-to-attrs ship-to-ext] [:PaymentDetailsList (map (fn [{:keys [amount reference-id]}] [:PaymentDetails {:ProcessedAmount amount :Reference1 reference-id}]) payments)] [:OrderLines (map (fn [{:keys [id sale-price]}] [:OrderLine [:Item {:ItemID id}] [:LinePriceInfo {:LineTotal sale-price}]]) order-lines)]] xml/sexp-as-element xml/indent-str))) (comment (s/check-asserts true) (spit "test.xml" (to-xml {:order-no "181219-001-345786" :payments [{:amount 900M :reference-id "000000-1545216772601"}] :order-lines [{:id "200374" :sale-price 900M}] :billing-address {:first-name "Tamizhvendan" :last-name "Sembiyan" :line1 "Plot No 222" :line2 "Ashok Nagar 42nd Street" :city "Chennai" :state "TamilNadu" :pincode 600001} :shipping-address {:first-name "Tamizhvendan" :last-name "Sembiyan" :line1 "Plot No 222" :line2 "Ashok Nagar 42nd Street" :city "Chennai" :state "TamilNadu" :pincode 600001}})))
85652
(ns wheel.oms.order (:require [clojure.spec.alpha :as s] [wheel.oms.address :as addr] [wheel.oms.payment :as payment] [wheel.oms.order-line :as order-line] [wheel.string :as w-str] [clojure.data.xml :as xml])) (s/def ::order-no w-str/not-blank?) (s/def ::payments (s/coll-of ::payment/payment :min-count 1)) (s/def ::order-lines (s/coll-of ::order-line/order-line :min-count 1)) (s/def ::billing-address ::addr/address) (s/def ::shipping-address ::addr/address) (s/def ::order (s/keys :req-un [::order-no ::shipping-address ::billing-address ::payments ::order-lines])) (defn address-to-xml [{:keys [first-name last-name line1 line2 city state pincode]}] {:attrs {:FirstName first-name :LastName last-name :State state :City city :Pincode pincode} :ext [:Extn {:IRLAddressLine1 line1 :IRLAddressLine2 line2}]}) (defn to-xml [order] {:pre [(s/assert ::order order)]} (let [{:keys [order-no billing-address order-lines shipping-address payments]} order {bill-to-attrs :attrs bill-to-ext :ext} (address-to-xml billing-address) {ship-to-attrs :attrs ship-to-ext :ext} (address-to-xml shipping-address)] (-> [:Order {:OrderNo order-no} [:PersonInfoBillTo bill-to-attrs bill-to-ext] [:PersonInfoShipTo ship-to-attrs ship-to-ext] [:PaymentDetailsList (map (fn [{:keys [amount reference-id]}] [:PaymentDetails {:ProcessedAmount amount :Reference1 reference-id}]) payments)] [:OrderLines (map (fn [{:keys [id sale-price]}] [:OrderLine [:Item {:ItemID id}] [:LinePriceInfo {:LineTotal sale-price}]]) order-lines)]] xml/sexp-as-element xml/indent-str))) (comment (s/check-asserts true) (spit "test.xml" (to-xml {:order-no "181219-001-345786" :payments [{:amount 900M :reference-id "000000-1545216772601"}] :order-lines [{:id "200374" :sale-price 900M}] :billing-address {:first-name "<NAME>" :last-name "<NAME>" :line1 "Plot No 222" :line2 "Ashok Nagar 42nd Street" :city "Chennai" :state "TamilNadu" :pincode 600001} :shipping-address {:first-name "<NAME>" :last-name "<NAME>" :line1 "Plot No 222" :line2 "Ashok Nagar 42nd Street" :city "Chennai" :state "TamilNadu" :pincode 600001}})))
true
(ns wheel.oms.order (:require [clojure.spec.alpha :as s] [wheel.oms.address :as addr] [wheel.oms.payment :as payment] [wheel.oms.order-line :as order-line] [wheel.string :as w-str] [clojure.data.xml :as xml])) (s/def ::order-no w-str/not-blank?) (s/def ::payments (s/coll-of ::payment/payment :min-count 1)) (s/def ::order-lines (s/coll-of ::order-line/order-line :min-count 1)) (s/def ::billing-address ::addr/address) (s/def ::shipping-address ::addr/address) (s/def ::order (s/keys :req-un [::order-no ::shipping-address ::billing-address ::payments ::order-lines])) (defn address-to-xml [{:keys [first-name last-name line1 line2 city state pincode]}] {:attrs {:FirstName first-name :LastName last-name :State state :City city :Pincode pincode} :ext [:Extn {:IRLAddressLine1 line1 :IRLAddressLine2 line2}]}) (defn to-xml [order] {:pre [(s/assert ::order order)]} (let [{:keys [order-no billing-address order-lines shipping-address payments]} order {bill-to-attrs :attrs bill-to-ext :ext} (address-to-xml billing-address) {ship-to-attrs :attrs ship-to-ext :ext} (address-to-xml shipping-address)] (-> [:Order {:OrderNo order-no} [:PersonInfoBillTo bill-to-attrs bill-to-ext] [:PersonInfoShipTo ship-to-attrs ship-to-ext] [:PaymentDetailsList (map (fn [{:keys [amount reference-id]}] [:PaymentDetails {:ProcessedAmount amount :Reference1 reference-id}]) payments)] [:OrderLines (map (fn [{:keys [id sale-price]}] [:OrderLine [:Item {:ItemID id}] [:LinePriceInfo {:LineTotal sale-price}]]) order-lines)]] xml/sexp-as-element xml/indent-str))) (comment (s/check-asserts true) (spit "test.xml" (to-xml {:order-no "181219-001-345786" :payments [{:amount 900M :reference-id "000000-1545216772601"}] :order-lines [{:id "200374" :sale-price 900M}] :billing-address {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :line1 "Plot No 222" :line2 "Ashok Nagar 42nd Street" :city "Chennai" :state "TamilNadu" :pincode 600001} :shipping-address {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :line1 "Plot No 222" :line2 "Ashok Nagar 42nd Street" :city "Chennai" :state "TamilNadu" :pincode 600001}})))
[ { "context": "and (is-type? % \"Character\") (revealed? %))}}\n \"Heritage Forsaken\"\n {:hosting {:req #(and (is-type? % \"Character\"", "end": 9009, "score": 0.7779531478881836, "start": 8992, "tag": "NAME", "value": "Heritage Forsaken" }, { "context": "nd (is-type? % \"Character\") (revealed? %))}}\n \"Icy Touch\"\n {:hosting {:req #(and (is-type? % \"Char", "end": 9085, "score": 0.6895137429237366, "start": 9083, "tag": "NAME", "value": "cy" }, { "context": "and (is-type? % \"Character\") (revealed? %))}}\n \"Ransom\"\n {:hosting {:req #(and (is-type? % \"Character\"", "end": 11453, "score": 0.5725590586662292, "start": 11447, "tag": "NAME", "value": "Ransom" } ]
src/clj/game/cards/hazard.clj
SylvanSign/cardnum
0
(ns game.cards.hazard (:require [game.core :refer :all] [game.utils :refer :all] [game.macros :refer [effect req msg wait-for continue-ability]] [clojure.string :refer [split-lines split join lower-case includes? starts-with?]] [clojure.stacktrace :refer [print-stack-trace]] [cardnum.utils :refer [str->int]] [cardnum.cards :refer [all-cards]])) (def card-definitions { "Alone and Unadvised" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Aware of Their Ways" {:abilities [{:label "Four" :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) kount (count (get-in @state [opp-side :discard]))] (loop [k (if (< kount 4) kount 4)] (when (> k 0) (move state opp-side (rand-nth (get-in @state [opp-side :discard])) :play-area) (recur (- k 1)))) (resolve-ability state side {:prompt "Select a card to remove from the game" :choices {:req (fn [t] (card-is? t :side opp-side))} :effect (req (doseq [c (get-in @state [opp-side :play-area])] (if (= c target) (move state opp-side c :rfg) (move state opp-side c :discard) )))} nil nil)))} {:label "Six" :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) kount (count (get-in @state [opp-side :discard]))] (loop [k (if (< kount 6) kount 6)] (when (> k 0) (move state opp-side (rand-nth (get-in @state [opp-side :discard])) :play-area) (recur (- k 1)))) (resolve-ability state side {:prompt "Select a card to remove from the game" :choices {:req (fn [t] (card-is? t :side opp-side))} :effect (req (doseq [c (get-in @state [opp-side :play-area])] (if (= c target) (move state opp-side c :rfg) (move state opp-side c :discard) )))} nil nil)))}]} "Bring Our Curses Home" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Cast from the Order" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Covetous Thoughts" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Cruel Claw Perceived" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Despair of the Heart" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Diminish and Depart" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Dragons Curse" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Enchanted Stream" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Fear of Kin" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Fled into Darkness" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Flies and Spiders" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Foes Shall Fall" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Fools Bane" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Foolish Words" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Grasping and Ungracious" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Great Secrets Buried There" {:abilities [{:label "as Resource" :effect (req (let [kount (count (get-in @state [side :deck])) secrets (get-card state card)] (loop [k (if (< kount 10) 0 10)] (when (> k 0) (move state side (first (get-in @state [side :deck])) :current) (recur (- k 1)))) (resolve-ability state side {:prompt "Select an item for Great Secrets..." :choices {:req (fn [t] (card-is? t :side side))} :effect (req (doseq [c (get-in @state [side :current])] (if (= c target) (host state side secrets c) (move state side c :deck))) (shuffle! state side :deck)) } nil nil)))} {:label "as Hazard" :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) secrets (get-card state card) kount (count (get-in @state [opp-side :deck]))] (loop [k (if (< kount 10) 0 10)] (when (> k 0) (move state opp-side (first (get-in @state [opp-side :deck])) :current) (recur (- k 1)))) (resolve-ability state opp-side {:prompt "Select an item for Great Secrets..." :choices {:req (fn [t] (card-is? t :side opp-side))} :effect (req (doseq [c (get-in @state [opp-side :current])] (if (= c target) (host state opp-side secrets c) (move state opp-side c :deck))) (shuffle! state opp-side :deck)) } nil nil)))} {:label "No item" ;; reveal to opponent :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) the-side (if (= 0 (count (get-in @state [side :current]))) opp-side side)] (resolve-ability state the-side {:effect (req (doseq [c (get-in @state [the-side :current])] (move state the-side c :play-area))) } nil nil)))} {:label "Shuffle" :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) the-side (if (= 0 (count (get-in @state [side :play-area]))) opp-side side)] (resolve-ability state the-side {:effect (req (doseq [c (get-in @state [the-side :play-area])] (move state the-side c :deck)) (shuffle! state the-side :deck)) } nil nil)))} ]} "He is Lost to Us" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Heritage Forsaken" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Icy Touch" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "In the Grip of Ambition" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Inner Rot" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Long Dark Reach" {:abilities [{:label "Top seven" :effect (req (if (< 9 (count (get-in @state [side :deck]))) (loop [k 7] (when (> k 0) (move state side (first (get-in @state [side :deck])) :play-area) (recur (- k 1))))) )} {:label "Top shuffle" :effect (req (move state side card :discard) (loop [k (count (get-in @state [side :play-area]))] (when (> k 0) (move state side (rand-nth (get-in @state [side :play-area])) :deck {:front true}) (recur (- k 1)))) )}]} "Longing for the West" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Lure of Creation" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Lure of Expedience" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Lure of Nature" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Lure of the Senses" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Many Burdens" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Memories Stolen" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Morgul-knife" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Nothing to Eat or Drink" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Out of Practice" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Pale Dream-maker" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Plague" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Politics" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Power Relinquished to Artifice" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Ransom" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Rebel-talk" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Revealed to all Watchers" {:abilities [{:label "Revealed" :effect (req (resolve-ability state side {:msg (msg "reveal hand") :effect (req (doseq [c (get-in @state [side :hand])] (move state side c :play-area))) } nil nil))} {:label "Hide" :effect (req (resolve-ability state side {:msg (msg "stack deck") :effect (req (doseq [c (get-in @state [side :play-area])] (move state side c :current))) } nil nil))} ]} "Shut Yer Mouth" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "So Youve Come Back" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Something Else at Work" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Something Has Slipped" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Spells of the Barrow-wights" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Taint of Glory" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "The Burden of Time" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "The Pale Sword" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Tookish Blood" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Wielders Curse" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Will You Not Come Down?" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Wound of Long Burden" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} })
112799
(ns game.cards.hazard (:require [game.core :refer :all] [game.utils :refer :all] [game.macros :refer [effect req msg wait-for continue-ability]] [clojure.string :refer [split-lines split join lower-case includes? starts-with?]] [clojure.stacktrace :refer [print-stack-trace]] [cardnum.utils :refer [str->int]] [cardnum.cards :refer [all-cards]])) (def card-definitions { "Alone and Unadvised" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Aware of Their Ways" {:abilities [{:label "Four" :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) kount (count (get-in @state [opp-side :discard]))] (loop [k (if (< kount 4) kount 4)] (when (> k 0) (move state opp-side (rand-nth (get-in @state [opp-side :discard])) :play-area) (recur (- k 1)))) (resolve-ability state side {:prompt "Select a card to remove from the game" :choices {:req (fn [t] (card-is? t :side opp-side))} :effect (req (doseq [c (get-in @state [opp-side :play-area])] (if (= c target) (move state opp-side c :rfg) (move state opp-side c :discard) )))} nil nil)))} {:label "Six" :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) kount (count (get-in @state [opp-side :discard]))] (loop [k (if (< kount 6) kount 6)] (when (> k 0) (move state opp-side (rand-nth (get-in @state [opp-side :discard])) :play-area) (recur (- k 1)))) (resolve-ability state side {:prompt "Select a card to remove from the game" :choices {:req (fn [t] (card-is? t :side opp-side))} :effect (req (doseq [c (get-in @state [opp-side :play-area])] (if (= c target) (move state opp-side c :rfg) (move state opp-side c :discard) )))} nil nil)))}]} "Bring Our Curses Home" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Cast from the Order" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Covetous Thoughts" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Cruel Claw Perceived" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Despair of the Heart" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Diminish and Depart" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Dragons Curse" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Enchanted Stream" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Fear of Kin" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Fled into Darkness" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Flies and Spiders" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Foes Shall Fall" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Fools Bane" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Foolish Words" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Grasping and Ungracious" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Great Secrets Buried There" {:abilities [{:label "as Resource" :effect (req (let [kount (count (get-in @state [side :deck])) secrets (get-card state card)] (loop [k (if (< kount 10) 0 10)] (when (> k 0) (move state side (first (get-in @state [side :deck])) :current) (recur (- k 1)))) (resolve-ability state side {:prompt "Select an item for Great Secrets..." :choices {:req (fn [t] (card-is? t :side side))} :effect (req (doseq [c (get-in @state [side :current])] (if (= c target) (host state side secrets c) (move state side c :deck))) (shuffle! state side :deck)) } nil nil)))} {:label "as Hazard" :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) secrets (get-card state card) kount (count (get-in @state [opp-side :deck]))] (loop [k (if (< kount 10) 0 10)] (when (> k 0) (move state opp-side (first (get-in @state [opp-side :deck])) :current) (recur (- k 1)))) (resolve-ability state opp-side {:prompt "Select an item for Great Secrets..." :choices {:req (fn [t] (card-is? t :side opp-side))} :effect (req (doseq [c (get-in @state [opp-side :current])] (if (= c target) (host state opp-side secrets c) (move state opp-side c :deck))) (shuffle! state opp-side :deck)) } nil nil)))} {:label "No item" ;; reveal to opponent :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) the-side (if (= 0 (count (get-in @state [side :current]))) opp-side side)] (resolve-ability state the-side {:effect (req (doseq [c (get-in @state [the-side :current])] (move state the-side c :play-area))) } nil nil)))} {:label "Shuffle" :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) the-side (if (= 0 (count (get-in @state [side :play-area]))) opp-side side)] (resolve-ability state the-side {:effect (req (doseq [c (get-in @state [the-side :play-area])] (move state the-side c :deck)) (shuffle! state the-side :deck)) } nil nil)))} ]} "He is Lost to Us" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "<NAME>" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "I<NAME> Touch" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "In the Grip of Ambition" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Inner Rot" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Long Dark Reach" {:abilities [{:label "Top seven" :effect (req (if (< 9 (count (get-in @state [side :deck]))) (loop [k 7] (when (> k 0) (move state side (first (get-in @state [side :deck])) :play-area) (recur (- k 1))))) )} {:label "Top shuffle" :effect (req (move state side card :discard) (loop [k (count (get-in @state [side :play-area]))] (when (> k 0) (move state side (rand-nth (get-in @state [side :play-area])) :deck {:front true}) (recur (- k 1)))) )}]} "Longing for the West" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Lure of Creation" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Lure of Expedience" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Lure of Nature" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Lure of the Senses" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Many Burdens" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Memories Stolen" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Morgul-knife" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Nothing to Eat or Drink" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Out of Practice" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Pale Dream-maker" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Plague" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Politics" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Power Relinquished to Artifice" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "<NAME>" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Rebel-talk" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Revealed to all Watchers" {:abilities [{:label "Revealed" :effect (req (resolve-ability state side {:msg (msg "reveal hand") :effect (req (doseq [c (get-in @state [side :hand])] (move state side c :play-area))) } nil nil))} {:label "Hide" :effect (req (resolve-ability state side {:msg (msg "stack deck") :effect (req (doseq [c (get-in @state [side :play-area])] (move state side c :current))) } nil nil))} ]} "Shut Yer Mouth" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "So Youve Come Back" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Something Else at Work" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Something Has Slipped" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Spells of the Barrow-wights" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Taint of Glory" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "The Burden of Time" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "The Pale Sword" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Tookish Blood" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Wielders Curse" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Will You Not Come Down?" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Wound of Long Burden" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} })
true
(ns game.cards.hazard (:require [game.core :refer :all] [game.utils :refer :all] [game.macros :refer [effect req msg wait-for continue-ability]] [clojure.string :refer [split-lines split join lower-case includes? starts-with?]] [clojure.stacktrace :refer [print-stack-trace]] [cardnum.utils :refer [str->int]] [cardnum.cards :refer [all-cards]])) (def card-definitions { "Alone and Unadvised" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Aware of Their Ways" {:abilities [{:label "Four" :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) kount (count (get-in @state [opp-side :discard]))] (loop [k (if (< kount 4) kount 4)] (when (> k 0) (move state opp-side (rand-nth (get-in @state [opp-side :discard])) :play-area) (recur (- k 1)))) (resolve-ability state side {:prompt "Select a card to remove from the game" :choices {:req (fn [t] (card-is? t :side opp-side))} :effect (req (doseq [c (get-in @state [opp-side :play-area])] (if (= c target) (move state opp-side c :rfg) (move state opp-side c :discard) )))} nil nil)))} {:label "Six" :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) kount (count (get-in @state [opp-side :discard]))] (loop [k (if (< kount 6) kount 6)] (when (> k 0) (move state opp-side (rand-nth (get-in @state [opp-side :discard])) :play-area) (recur (- k 1)))) (resolve-ability state side {:prompt "Select a card to remove from the game" :choices {:req (fn [t] (card-is? t :side opp-side))} :effect (req (doseq [c (get-in @state [opp-side :play-area])] (if (= c target) (move state opp-side c :rfg) (move state opp-side c :discard) )))} nil nil)))}]} "Bring Our Curses Home" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Cast from the Order" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Covetous Thoughts" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Cruel Claw Perceived" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Despair of the Heart" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Diminish and Depart" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Dragons Curse" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Enchanted Stream" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Fear of Kin" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Fled into Darkness" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Flies and Spiders" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Foes Shall Fall" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Fools Bane" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Foolish Words" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Grasping and Ungracious" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Great Secrets Buried There" {:abilities [{:label "as Resource" :effect (req (let [kount (count (get-in @state [side :deck])) secrets (get-card state card)] (loop [k (if (< kount 10) 0 10)] (when (> k 0) (move state side (first (get-in @state [side :deck])) :current) (recur (- k 1)))) (resolve-ability state side {:prompt "Select an item for Great Secrets..." :choices {:req (fn [t] (card-is? t :side side))} :effect (req (doseq [c (get-in @state [side :current])] (if (= c target) (host state side secrets c) (move state side c :deck))) (shuffle! state side :deck)) } nil nil)))} {:label "as Hazard" :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) secrets (get-card state card) kount (count (get-in @state [opp-side :deck]))] (loop [k (if (< kount 10) 0 10)] (when (> k 0) (move state opp-side (first (get-in @state [opp-side :deck])) :current) (recur (- k 1)))) (resolve-ability state opp-side {:prompt "Select an item for Great Secrets..." :choices {:req (fn [t] (card-is? t :side opp-side))} :effect (req (doseq [c (get-in @state [opp-side :current])] (if (= c target) (host state opp-side secrets c) (move state opp-side c :deck))) (shuffle! state opp-side :deck)) } nil nil)))} {:label "No item" ;; reveal to opponent :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) the-side (if (= 0 (count (get-in @state [side :current]))) opp-side side)] (resolve-ability state the-side {:effect (req (doseq [c (get-in @state [the-side :current])] (move state the-side c :play-area))) } nil nil)))} {:label "Shuffle" :effect (req (let [opp-side (if (= side :contestant) :challenger :contestant) the-side (if (= 0 (count (get-in @state [side :play-area]))) opp-side side)] (resolve-ability state the-side {:effect (req (doseq [c (get-in @state [the-side :play-area])] (move state the-side c :deck)) (shuffle! state the-side :deck)) } nil nil)))} ]} "He is Lost to Us" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "PI:NAME:<NAME>END_PI" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "IPI:NAME:<NAME>END_PI Touch" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "In the Grip of Ambition" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Inner Rot" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Long Dark Reach" {:abilities [{:label "Top seven" :effect (req (if (< 9 (count (get-in @state [side :deck]))) (loop [k 7] (when (> k 0) (move state side (first (get-in @state [side :deck])) :play-area) (recur (- k 1))))) )} {:label "Top shuffle" :effect (req (move state side card :discard) (loop [k (count (get-in @state [side :play-area]))] (when (> k 0) (move state side (rand-nth (get-in @state [side :play-area])) :deck {:front true}) (recur (- k 1)))) )}]} "Longing for the West" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Lure of Creation" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Lure of Expedience" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Lure of Nature" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Lure of the Senses" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Many Burdens" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Memories Stolen" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Morgul-knife" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Nothing to Eat or Drink" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Out of Practice" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Pale Dream-maker" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Plague" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Politics" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Power Relinquished to Artifice" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "PI:NAME:<NAME>END_PI" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Rebel-talk" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Revealed to all Watchers" {:abilities [{:label "Revealed" :effect (req (resolve-ability state side {:msg (msg "reveal hand") :effect (req (doseq [c (get-in @state [side :hand])] (move state side c :play-area))) } nil nil))} {:label "Hide" :effect (req (resolve-ability state side {:msg (msg "stack deck") :effect (req (doseq [c (get-in @state [side :play-area])] (move state side c :current))) } nil nil))} ]} "Shut Yer Mouth" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "So Youve Come Back" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Something Else at Work" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Something Has Slipped" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Spells of the Barrow-wights" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Taint of Glory" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "The Burden of Time" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "The Pale Sword" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Tookish Blood" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Wielders Curse" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Will You Not Come Down?" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} "Wound of Long Burden" {:hosting {:req #(and (is-type? % "Character") (revealed? %))}} })
[ { "context": "id fid\n :name name\n :perm perm\n", "end": 28193, "score": 0.8536332845687866, "start": 28189, "tag": "NAME", "value": "name" } ]
src/cognitect/clj9p/io.clj
cognitect-labs/clj9p
18
; Copyright 2019 Cognitect. All Rights Reserved. ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS-IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns cognitect.clj9p.io (:require [cognitect.clj9p.9p :as n9p] [cognitect.clj9p.proto :as proto] [cognitect.clj9p.buffer :as buff] [clojure.core.async :as async]) (:import (cognitect.clj9p.buffer Buffer) (java.nio ByteOrder) (io.netty.buffer ;Unpooled ByteBuf ByteBufUtil) (io.netty.buffer PooledByteBufAllocator) (java.nio ByteBuffer) (java.nio.channels ByteChannel) (io.netty.channel ChannelHandlerContext) (java.util Date))) ;; 9P Protocol implementation notes ;; -------------------------------- ;; At the bottom level, 9P operates on calls sent to file descriptors (files, sockets, channels). ;; In this implementation, calls are constructed using Clojure maps. ;; Many benefits fall out of this choice (they can be serialized with JSON or ;; Transit, they can be stored on a file or database and read in, etc.). When ;; a message/call is sent to the fd, it is encoded into binary and packed on a ;; buffer. Buffers are programmed against an interface and the default ;; implementation uses a Netty ByteBuf (DirectBuffer). Buffers are also used ;; to unpack calls/messages and turn them back into maps. (defn default-buffer "This creates a Buffer suitable for use with encoding/decoding fcalls, but one should prefer using PooledByteBufAllocator from Netty (with direct Buffers only)" ([] (buff/ensure-little-endian (.directBuffer PooledByteBufAllocator/DEFAULT))) ([initial-byte-array] (if (instance? ByteBuf initial-byte-array) (buff/ensure-little-endian initial-byte-array) ;; Caller assumed Byte Arrays, but was operating in-place (buff/write-byte-array (buff/ensure-little-endian (.directBuffer PooledByteBufAllocator/DEFAULT)) initial-byte-array)))) (extend-protocol buff/Length ByteBuf (length [t] (.readableBytes t)) String (length [t] (.length t)) nil (length [t] 0)) (extend-protocol buff/Buffer ByteBuf (write-string [t s] (ByteBufUtil/writeUtf8 t ^String s) t) (write-byte-array [t ba] (.writeBytes t ^bytes ba)) (write-bytes [t bb] (.writeBytes t ^ByteBuf bb) t) (write-nio-bytes [t byte-buffer] (.writeBytes t ^ByteBuffer byte-buffer)) (write-zero [t n] (.writeZero t n) t) (write-byte [t b] (.writeByte t b) t) (write-short [t s] (.writeShort t s) t) (write-int [t i] (.writeInt t i) t) (write-long [t l] (.writeLong t l) t) (writer-index [t] (.writerIndex t)) (move-writer-index [t n] (.writerIndex t n) t) (read-string [t n] (let [ba (byte-array n)] (.readBytes t ba) (String. ba "UTF-8"))) (read-bytes [t n] (let [ba (byte-array n)] (.readBytes t ba) ba)) (read-byte [t] (.readUnsignedByte t)) (read-short [t] (.readUnsignedShort t)) (read-int [t] (.readUnsignedInt t)) (read-long [t] (.readLong t)) ;; TODO: Should the appropriate shift be done here (readable-bytes [t] (.readableBytes t)) (reset-read-index [t] (.readerIndex t 0) t) (as-byte-array [t] (.array t)) (as-byte-buffer [t] (.nioBuffer t)) ;; Note: This will share content with the underlying Buffer (ensure-little-endian [t] (.order t ByteOrder/LITTLE_ENDIAN)) (slice [t index length] (.slice t index length)) (clear [t] (.clear t) t)) (defn slice ([t offset] (buff/slice t offset (- (buff/length t) offset))) ([t offset length] (buff/slice t offset length))) (def little-endian buff/ensure-little-endian) (def length buff/length) ;; Auxiliary functions ;; ------------------- (defn path-hash [path] (if (string? path) (Math/abs ^int (hash path)) path)) (defn write-qid [^Buffer buffer qid-map] (buff/write-byte buffer (:type qid-map)) (buff/write-int buffer (:version qid-map)) (buff/write-long buffer (path-hash (:path qid-map))) buffer) (defn read-qid [^Buffer buffer] {:type (buff/read-byte buffer) :version (buff/read-int buffer) :path (buff/read-long buffer)}) ;; 9P Doesn't allow for any NUL characters at all. ;; Instead of null-terminated strings, all free-form data is prepended ;; by the length of bytes to read - as a short [2] or int [4]. ;; This design choice means you can always safely read 9P "front" to "back". ;; All strings are always UTF-8 (originally designed for Plan 9 and the 9P protocol). (defn write-2-piece [^Buffer buffer x] (buff/write-short buffer (buff/length x)) (if (string? x) (buff/write-string buffer x) (buff/write-bytes buffer x)) buffer) (def write-len-string write-2-piece) (defn write-4-piece [^Buffer buffer x] (buff/write-int buffer (buff/length x)) (if (string? x) (buff/write-string buffer x) (buff/write-bytes buffer x)) buffer) (defn read-2-piece [^Buffer buffer] (let [n (buff/read-short buffer)] (buff/read-bytes buffer n))) (defn read-len-string [^Buffer buffer] (let [n (buff/read-short buffer)] (buff/read-string buffer n))) (defn read-4-piece [^Buffer buffer] (let [n (buff/read-int buffer)] (buff/read-bytes buffer n))) (defn write-stats [^Buffer buffer stats encode-length?] (let [buffer (buff/ensure-little-endian buffer) statsz-processed (reduce (fn [{:keys [stats statsz-total]} {:keys [name uid gid muid extension] :as stat}] (let [stat-sz (apply + (if extension 61 47) ;; base size values for standard vs dot-u (if extension (count extension) 0) ;; If we're :dot-u, we'll have an extension (map count [name uid gid muid]))] {:stats (conj stats (assoc stat :statsz stat-sz)) :statsz-total (+ ^long statsz-total ^long stat-sz)})) {:stats [] :statsz-total 0} stats)] (when encode-length? (buff/write-short buffer (+ ^long (:statsz-total statsz-processed) 2))) (doseq [stat (:stats statsz-processed)] (buff/write-short buffer (:statsz stat)) (buff/write-short buffer (:type stat)) (buff/write-int buffer (:dev stat)) (write-qid buffer (:qid stat)) (buff/write-int buffer (:mode stat)) (buff/write-int buffer (:atime stat)) (buff/write-int buffer (:mtime stat)) (buff/write-long buffer (:length stat)) (write-len-string buffer (:name stat)) (write-len-string buffer (:uid stat)) (write-len-string buffer (:gid stat)) (write-len-string buffer (:muid stat)) (when (:extension stat) ;; when dot-u (write-len-string buffer (:extension stat)) (buff/write-int buffer (:uidnum stat)) (buff/write-int buffer (:gidnum stat)) (buff/write-int buffer (:muidnum stat)))) buffer)) (defn read-stats [^Buffer buffer decode-length? dot-u?] (when decode-length? (buff/read-short buffer)) (loop [stats (transient []) initial-bytes ^long (buff/readable-bytes buffer)] (if (pos? initial-bytes) (let [statsz (buff/read-short buffer) stype (buff/read-short buffer) dev (buff/read-int buffer) qid (read-qid buffer) mode (buff/read-int buffer) atime (buff/read-int buffer) mtime (buff/read-int buffer) slen (buff/read-long buffer) sname (read-len-string buffer) uid (read-len-string buffer) gid (read-len-string buffer) muid (read-len-string buffer) ;;(if (or dot-u? ;; (> statsz (- initial-bytes (buff/readable-bytes buffer))) ;; (read-len-string buffer) ;; "")) extension (if dot-u? (read-len-string buffer) "") uidnum (if dot-u? (buff/read-int buffer) 0) gidnum (if dot-u? (buff/read-int buffer) 0) muidnum (if dot-u? (buff/read-int buffer) 0)] (recur (conj! stats (merge {:statsz statsz :type stype :dev dev :qid qid :mode mode :atime atime :mtime mtime :length slen :name sname :uid uid :gid gid :muid muid} (when dot-u? {:extension extension :uidnum uidnum :gidnum gidnum :muidnum muidnum}))) ^long (buff/readable-bytes buffer))) (persistent! stats)))) (defn ensure! ([pred x] (ensure! pred x (str "Value failed predicate contract: " x))) ([pred x message] (if (pred x) x (throw (ex-info message {:type :ensure-violation :predicate pred :value x}))))) (defn now [] (.getTime ^Date (Date.))) (def mode-bits ["---" "--x" "-w-" "-wx" "r--" "r-x" "rw-" "rwx"]) (defn mode-str [mode-num] (let [mode-fn (fn [shift-num] ; Just numbers... ;(bit-and (bit-shift-right mode-num shift-num) 7) (get mode-bits (bit-and (bit-shift-right mode-num shift-num) 7))) mode-bit (cond (pos? (bit-and mode-num proto/DMDIR)) "d" (pos? (bit-and mode-num proto/DMAPPEND)) "a" :else "-")] (str mode-bit (mode-fn 6) (mode-fn 3) (mode-fn 0)))) (def default-message-size-bytes 8192) (defn numeric-fcall "Replace all fcall map values with the ensured numeric values for the protocol" [fcall-map] (merge fcall-map {:type (let [call-type (:type fcall-map)] (ensure! proto/v2-codes (if (keyword? call-type) (proto/v2 call-type) call-type) (str "Invalid type value: " call-type))) :tag (ensure! number? (:tag fcall-map) (str "Invalid tag value: " (:tag fcall-map)))})) (defn valid-fcall? [fcall-map] (every? identity (some-> fcall-map (select-keys [:type :tag]) vals))) (defn fcall "Create a valid fcall-map with defaults set. Can accept a base map, or kv-args" ([base-map] {:pre [(map? base-map)] :post [valid-fcall?]} (merge {:tag (rand-int 32000) ;; Random short generation takes ~0.05ms :fid proto/NOFID :afid proto/NOFID :uname (System/getProperty "user.name") :aname "" :stat [] :iounit default-message-size-bytes :wqid [] :msize default-message-size-bytes ;; Can be as large as 65512 :version (if (:dot-u base-map) proto/versionu proto/version) :uidnum proto/UIDUNDEF :gidnum proto/UIDUNDEF :muidnum proto/UIDUNDEF} base-map)) ([k & vkv-pairs] {:pre [(keyword? k)]} (fcall (apply hash-map k vkv-pairs)))) (defn stat "Generate a close-to-complete stat map" [base-map] (merge {:type 0 :dev 0 :statsz 0 :mode 0644 :length 0 ;; 0 Length is used for directories and devices/services :name "" :uid "user" :gid "user" :muid "user"} base-map)) ;; Encoding and decoding ;; ---------------------- ;; Messages are defined in the [RFC Message Section](http://9p.cat-v.org/documentation/rfc/#msgs) ;; fcalls/message are based on the following struct: ;; type Fcall struct { ;; Size uint32 // size of the message (4 - int) ;; Type uint8 // message type (1 - byte) ;; Fid uint32 // file identifier (4 - int) ;; Tag uint16 // message tag (2 - short) ;; Msize uint32 // maximum message size (used by Tversion, Rversion) (4 - int) ;; Version string // protocol version (used by Tversion, Rversion) (string) ;; Oldtag uint16 // tag of the message to flush (used by Tflush) (2 - short) ;; Error string // error (used by Rerror) (string) ;; Qid // file Qid (used by Rauth, Rattach, Ropen, Rcreate) (struct - 1, 4, 8 - type, version, path) ;; Iounit uint32 // maximum bytes read without breaking in multiple messages (used by Ropen, Rcreate) (4 - int) ;; Afid uint32 // authentication fid (used by Tauth, Tattach) (4 - int) ;; Uname string // user name (used by Tauth, Tattach) (string) ;; Aname string // attach name (used by Tauth, Tattach) (string) ;; Perm uint32 // file permission (mode) (used by Tcreate) (4 - int) ;; Name string // file name (used by Tcreate) (string) ;; Mode uint8 // open mode (used by Topen, Tcreate) (1 - byte) ;; Newfid uint32 // the fid that represents the file walked to (used by Twalk) (4 - int) ;; Wname []string // list of names to walk (used by Twalk) (vector of strings) ;; Wqid []Qid // list of Qids for the walked files (used by Rwalk) (vector of Qids) ;; Offset uint64 // offset in the file to read/write from/to (used by Tread, Twrite) (8 - long) ;; Count uint32 // number of bytes read/written (used by Tread, Rread, Twrite, Rwrite) (4 - int) ;; Dir // file description (used by Rstat, Twstat) ;; ;; /* 9P2000.u extensions */ ;; Errornum uint32 // error code, 9P2000.u only (used by Rerror) (4 - int) ;; Extension string // special file description, 9P2000.u only (used by Tcreate) (string) ;; Unamenum uint32 // user ID, 9P2000.u only (used by Tauth, Tattach) (4 - int) ;; } (def valid-fcall-keys #{:msize ; Tversion, Rversion :version ; Tversion, Rversion :oldtag ; Tflush :ename ; Rerror :qid ; Rattach, Ropen, Rcreate :iounit ; Ropen, Rcreate :aqid ; Rauth :afid ; Tauth, Tattach :uname ; Tauth, Tattach :aname ; Tauth, Tattach :perm ; Tcreate :name ; Tcreate :mode ; Tcreate, Topen :newfid ; Twalk :wname ; Twalk, array :wqid ; Rwalk, array :offset ; Tread, Twrite :count ; Tread, Twrite :data ; Twrite, Rread :nstat ; Twstat, Rstat :stat ; Twstat, Rstat ; dotu extensions: :errno ; Rerror ; Tcreate :extension}) (def fcall-keys {:tversion [:type :tag :msize :version] :rversion [:type :tag :msize :version] :tauth [:type :tag :afid :uname :aname] :rauth [:type :tag :aqid] :rerror [:type :tag :ename] :tflush [:type :tag :oldtag] :rflush [:type :tag] :tattach [:type :tag :afid :uname :aname] :rattach [:type :tag :qid] :twalk [:type :tag :fid :newfid :wname] :rwalk [:type :tag :wqid] :topen [:type :tag :fid :mode] :ropen [:type :tag :qid :iounit] :topenfd [:type :tag :fid :mode] :ropenfd [:type :tag :qid :iounit :unixfd] :tcreate [:type :tag :fid :name :perm :mode] :rcreate [:type :tag :qid :iounit] :tread [:type :tag :fid :offset :count] :rread [:type :tag :count :data] :twrite [:type :tag :fid :offset :count :data] :rwrite [:type :tag :count] :tclunk [:type :tag :fid] :rclunk [:type :tag] :tremove [:type :tag :fid] :rremove [:type :tag] :tstat [:type :tag :fid] :rstat [:type :tag :stat] :twstat [:type :tag :fid :stat] :rwstat [:type :tag]}) (defn show-fcall [fcall-map] (pr-str (select-keys fcall-map (get fcall-keys (:type fcall-map) [:type :tag])))) ;; 9P has two types of messages: T-Messages and R-Messages. ;; From the RFC/Intro: ;; The Plan 9 File Protocol, 9P, is used for messages between clients and servers. ;; A client transmits *requests* (T-messages) to a server, which subsequently returns *replies* (R-messages) to the client. ;; The combined acts of transmitting (receiving) a request of a particular type, and receiving (transmitting) its reply ;; is called a transaction of that type. ;; Each message consists of a sequence of bytes. Two-, four-, and eight-byte fields ;; hold unsigned integers represented in little-endian order (least significant byte first). ;; Data items of larger or variable lengths are represented by a two-byte field specifying a count, n, followed by n bytes of data. ;; Text strings are represented this way, with the text itself stored as a UTF-8 encoded sequence of Unicode characters. ;; Text strings in 9P messages are not NUL-terminated: n counts the bytes of UTF-8 data, which include no final zero byte. ;; The NUL character is illegal in all text strings in 9P, and is therefore excluded from file names, user names, and so on. ;; Messages are transported in byte form to allow for machine independence. (defn encode-fcall! "Given an fcall map and a Buffer, encode the fcall onto the buffer and return the buffer NOTE: This will reset/clear the buffer" [fcall-map ^Buffer buffer] (let [;; Return a little endian buffer buffer (buff/ensure-little-endian buffer) fcall (numeric-fcall fcall-map) ;; We'll match the type based on a keyword... fcall-type (if (keyword? (:type fcall-map)) (:type fcall-map) (proto/v2-codes (:type fcall)))] (buff/clear buffer) ;; TODO: This may have to be `write-int 0` (buff/write-zero buffer 4) ; "0000" - which will be used for total msg len when we're done ;; Imperatively pack the buffer (buff/write-byte buffer (:type fcall)) (buff/write-short buffer (:tag fcall)) ;; TODO: Consider replacing this cond with a dispatch map (cond (#{:tversion :rversion} fcall-type) (do (buff/write-int buffer (:msize fcall)) (write-len-string buffer (:version fcall))) (= fcall-type :tauth) (do (buff/write-int buffer (:afid fcall)) (write-len-string buffer (:uname fcall)) (write-len-string buffer (:aname fcall)) (when (:dot-u fcall) (buff/write-int buffer (:uidnum fcall)))) (= fcall-type :rauth) (write-qid buffer (:aqid fcall)) (= fcall-type :rerror) (do (write-len-string buffer (:ename fcall "General Error")) (when (:dot-u fcall) (buff/write-int buffer (:errno fcall)))) (= fcall-type :tflush) (buff/write-short buffer (:oldtag fcall)) (= fcall-type :tattach) (do (buff/write-int buffer (:fid fcall)) (buff/write-int buffer (:afid fcall)) (write-len-string buffer (:uname fcall)) (write-len-string buffer (:aname fcall)) (when (:dot-u fcall) (buff/write-int buffer (:uidnum fcall)))) (= fcall-type :rattach) (write-qid buffer (:qid fcall)) (= fcall-type :twalk) (do (buff/write-int buffer (:fid fcall)) (buff/write-int buffer (:newfid fcall)) (buff/write-short buffer (count (:wname fcall))) (doseq [node-name (:wname fcall)] (write-len-string buffer node-name))) (= fcall-type :rwalk) (do (buff/write-short buffer (count (:wqid fcall))) (doseq [qid (:wqid fcall)] (write-qid buffer qid))) (= fcall-type :topen) (do (buff/write-int buffer (:fid fcall)) (buff/write-byte buffer (:mode fcall))) (#{:ropen :rcreate} fcall-type) (do (write-qid buffer (:qid fcall)) (buff/write-int buffer (:iounit fcall))) (= fcall-type :tcreate) (do (buff/write-int buffer (:fid fcall)) (write-len-string buffer (:name fcall)) (buff/write-int buffer (:perm fcall)) (buff/write-byte buffer (:mode fcall)) (when (:dot-u fcall) (write-len-string (:extension fcall)))) (= fcall-type :tread) (do (buff/write-int buffer (:fid fcall)) (buff/write-long buffer (:offset fcall)) (buff/write-int buffer (:count fcall))) (= fcall-type :rread) (write-4-piece buffer (:data fcall)) (= fcall-type :twrite) (do (buff/write-int buffer (:fid fcall)) (buff/write-long buffer (:offset fcall)) (write-4-piece buffer (:data fcall))) (= fcall-type :rwrite) (buff/write-int buffer (:count fcall)) (#{:tclunk :tremove :tstat} fcall-type) (buff/write-int buffer (:fid fcall)) (#{:rstat :twstat} fcall-type) (do (when (= fcall-type :twstat) (buff/write-int buffer (:fid fcall))) (write-stats buffer (:stat fcall) true)) :else buffer) ;; Patch up the size of the message (let [length (buff/length buffer)] (buff/move-writer-index buffer 0) (buff/write-int buffer length) (buff/move-writer-index buffer length)))) (def ^{:doc "Return a transducer that encodes an fcall into a Buffer"} encode-fcall-xf (map (fn [fcall] (encode-fcall! fcall (.directBuffer PooledByteBufAllocator/DEFAULT))))) (defn decode-fcall! "Given a buffer (full of bytes) and optionally a base fcall map, decode the bytes into a full fcall map. Returns the decoded/complete fcall-map. Note: This resets the read index on the buffer on entry and exhausts it by exit." ([^Buffer base-buffer] (decode-fcall! base-buffer {})) ([^Buffer base-buffer base-fcall-map] (let [buffer (buff/ensure-little-endian base-buffer) _ (buff/reset-read-index buffer) buffer-size (buff/length buffer) size (buff/read-int buffer) _ (when (not= buffer-size size) (throw (ex-info (str "Reported message size and actual size differ: " size "; actual: " buffer-size) {:reported-size size :buffer-size buffer-size :fcall-map base-fcall-map}))) _ (when-not (<= 7 size 0xffffffff) (throw (ex-info (str "Bad fcall message size on decode: " size) {:size size :fcall-map base-fcall-map}))) ftype (buff/read-byte buffer) ftag (buff/read-short buffer) fcall-type (ensure! identity (proto/v2-codes ftype) (str "Decoded invalid type numeric: " ftype)) fcall-map (fcall {:type fcall-type :tag ftag :original-size size})] ;; TODO: Consider replacing this cond with a dispatch map (cond (#{:tversion :rversion} fcall-type) (assoc fcall-map :msize (buff/read-int buffer) :version (read-len-string buffer)) (= fcall-type :tauth) (let [afid (buff/read-int buffer) uname (read-len-string buffer) aname (read-len-string buffer)] (merge fcall-map {:afid afid :uname uname :aname aname} (when (:dot-u fcall-map) {:uidnum (buff/read-int buffer)}))) (= fcall-type :rauth) (assoc fcall-map :aqid (read-qid buffer)) (= fcall-type :rerror) (merge fcall-map {:ename (read-len-string buffer)} (when (:dot-u fcall-map) {:errno (buff/read-int buffer)})) (= fcall-type :tflush) (assoc fcall-map :oldtag (buff/read-short buffer)) (= fcall-type :tattach) (let [fid (buff/read-int buffer) afid (buff/read-int buffer) uname (read-len-string buffer) aname (read-len-string buffer)] (merge fcall-map {:fid fid :afid afid :uname uname :aname aname} (when (:dot-u fcall-map) {:uidnum (buff/read-int buffer)}))) (= fcall-type :rattach) (assoc fcall-map :qid (read-qid buffer)) (= fcall-type :twalk) (let [fid (buff/read-int buffer) newfid (buff/read-int buffer) n (buff/read-short buffer)] (assoc fcall-map :fid fid :newfid newfid :wname (mapv (fn [name-n] (read-len-string buffer)) (range n)))) (= fcall-type :rwalk) (let [n (buff/read-short buffer)] (assoc fcall-map :wqid (mapv (fn [name-n] (read-qid buffer)) (range n)))) (= fcall-type :topen) (assoc fcall-map :fid (buff/read-int buffer) :mode (buff/read-byte buffer)) (#{:ropen :rcreate} fcall-type) (assoc fcall-map :qid (read-qid buffer) :iounit (buff/read-int buffer)) (= fcall-type :tcreate) (let [fid (buff/read-int buffer) name (read-len-string buffer) perm (buff/read-int buffer) mode (buff/read-byte buffer)] (merge fcall-map {:fid fid :name name :perm perm :mode mode} (when (:dot-u fcall-map) {:extension (read-len-string buffer)}))) (= fcall-type :tread) (assoc fcall-map :fid (buff/read-int buffer) :offset (buff/read-long buffer) :count (buff/read-int buffer)) (= fcall-type :rread) (assoc fcall-map :data (read-4-piece buffer)) (= fcall-type :twrite) (let [fid (buff/read-int buffer) offset (buff/read-long buffer) cnt (buff/read-int buffer)] (assoc fcall-map :fid fid :offset offset :count cnt :data (buff/read-bytes buffer cnt))) (= fcall-type :rwrite) (assoc fcall-map :count (buff/read-int buffer)) (#{:tclunk :tremove :tstat} fcall-type) (assoc fcall-map :fid (buff/read-int buffer)) (#{:rstat :twstat} fcall-type) (merge fcall-map (when (= fcall-type :twstat) {:fid (buff/read-int buffer)}) {:stat (read-stats buffer true (:dot-u fcall-map))}) :else fcall-map)))) (def ^{:doc "A transducer that converts Buffers into fcall maps"} decode-fcall-xf (map (fn [^Buffer buffer] (decode-fcall! buffer)))) (defn directory? [qid-type] (if (map? qid-type) (directory? (:type qid-type)) (pos? (bit-and qid-type proto/QTDIR)))) (defn file? [qid-type] (if (map? qid-type) (file? (:type qid-type)) (or (= qid-type proto/QTFILE) ;; Protect against mode bit '0' (pos? (bit-and qid-type proto/QTFILE)) (pos? (bit-and qid-type proto/QTAPPEND)) (pos? (bit-and qid-type proto/QTTMP))))) (defn symlink? [qid-type] (if (map? qid-type) (symlink? (:type qid-type)) (pos? (bit-and qid-type proto/QTSYMLINK)))) (defn permission? "Return true if some stat-like map allows some specific permission for uid, otherwise false. Target-perm is expect to be an Access-type permission" [fd-stat uid target-perm] ;; Shield your eyes - we need to bash m as we conditionally check chunks of the perm bits (let [mode (:mode fd-stat) m (volatile! (bit-and mode 7))] (cond (= target-perm (bit-and target-perm @m)) true (and (= (:uid fd-stat) uid) (do (vreset! m (bit-or @m (bit-and (bit-shift-right mode 6) 7))) (= target-perm (bit-and target-perm @m)))) true (and (= (:gid fd-stat) uid) (do (vreset! m (bit-or @m (bit-and (bit-shift-right mode 3) 7))) (= target-perm (bit-and target-perm @m)))) true :else false))) (defn apply-permissions [initial-mode additional-modes] (apply bit-or initial-mode additional-modes)) (defn open->access "Convert an Open-style permission into an Access-style permission" [target-perm] (let [np (bit-and target-perm 3) access-perm (proto/perm-translation np)] (if (pos? (bit-and target-perm proto/OTRUNC)) (bit-or access-perm proto/AWRITE) access-perm))) (defn mode->stat [mode] (bit-or (bit-and mode 0777) (bit-shift-right (bit-xor (bit-and mode proto/DMDIR) proto/DMDIR) 16) (bit-shift-right (bit-and mode proto/DMDIR) 17) (bit-shift-right (bit-and mode proto/DMSYMLINK) 10) (bit-shift-right (bit-and mode proto/DMSYMLINK) 12) (bit-shift-right (bit-and mode proto/DMSETUID) 8) (bit-shift-right (bit-and mode proto/DMSETGID) 8) (bit-shift-right (bit-and mode proto/DMSTICKY) 7))) (comment (mode->stat 0664) )
76276
; Copyright 2019 Cognitect. All Rights Reserved. ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS-IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns cognitect.clj9p.io (:require [cognitect.clj9p.9p :as n9p] [cognitect.clj9p.proto :as proto] [cognitect.clj9p.buffer :as buff] [clojure.core.async :as async]) (:import (cognitect.clj9p.buffer Buffer) (java.nio ByteOrder) (io.netty.buffer ;Unpooled ByteBuf ByteBufUtil) (io.netty.buffer PooledByteBufAllocator) (java.nio ByteBuffer) (java.nio.channels ByteChannel) (io.netty.channel ChannelHandlerContext) (java.util Date))) ;; 9P Protocol implementation notes ;; -------------------------------- ;; At the bottom level, 9P operates on calls sent to file descriptors (files, sockets, channels). ;; In this implementation, calls are constructed using Clojure maps. ;; Many benefits fall out of this choice (they can be serialized with JSON or ;; Transit, they can be stored on a file or database and read in, etc.). When ;; a message/call is sent to the fd, it is encoded into binary and packed on a ;; buffer. Buffers are programmed against an interface and the default ;; implementation uses a Netty ByteBuf (DirectBuffer). Buffers are also used ;; to unpack calls/messages and turn them back into maps. (defn default-buffer "This creates a Buffer suitable for use with encoding/decoding fcalls, but one should prefer using PooledByteBufAllocator from Netty (with direct Buffers only)" ([] (buff/ensure-little-endian (.directBuffer PooledByteBufAllocator/DEFAULT))) ([initial-byte-array] (if (instance? ByteBuf initial-byte-array) (buff/ensure-little-endian initial-byte-array) ;; Caller assumed Byte Arrays, but was operating in-place (buff/write-byte-array (buff/ensure-little-endian (.directBuffer PooledByteBufAllocator/DEFAULT)) initial-byte-array)))) (extend-protocol buff/Length ByteBuf (length [t] (.readableBytes t)) String (length [t] (.length t)) nil (length [t] 0)) (extend-protocol buff/Buffer ByteBuf (write-string [t s] (ByteBufUtil/writeUtf8 t ^String s) t) (write-byte-array [t ba] (.writeBytes t ^bytes ba)) (write-bytes [t bb] (.writeBytes t ^ByteBuf bb) t) (write-nio-bytes [t byte-buffer] (.writeBytes t ^ByteBuffer byte-buffer)) (write-zero [t n] (.writeZero t n) t) (write-byte [t b] (.writeByte t b) t) (write-short [t s] (.writeShort t s) t) (write-int [t i] (.writeInt t i) t) (write-long [t l] (.writeLong t l) t) (writer-index [t] (.writerIndex t)) (move-writer-index [t n] (.writerIndex t n) t) (read-string [t n] (let [ba (byte-array n)] (.readBytes t ba) (String. ba "UTF-8"))) (read-bytes [t n] (let [ba (byte-array n)] (.readBytes t ba) ba)) (read-byte [t] (.readUnsignedByte t)) (read-short [t] (.readUnsignedShort t)) (read-int [t] (.readUnsignedInt t)) (read-long [t] (.readLong t)) ;; TODO: Should the appropriate shift be done here (readable-bytes [t] (.readableBytes t)) (reset-read-index [t] (.readerIndex t 0) t) (as-byte-array [t] (.array t)) (as-byte-buffer [t] (.nioBuffer t)) ;; Note: This will share content with the underlying Buffer (ensure-little-endian [t] (.order t ByteOrder/LITTLE_ENDIAN)) (slice [t index length] (.slice t index length)) (clear [t] (.clear t) t)) (defn slice ([t offset] (buff/slice t offset (- (buff/length t) offset))) ([t offset length] (buff/slice t offset length))) (def little-endian buff/ensure-little-endian) (def length buff/length) ;; Auxiliary functions ;; ------------------- (defn path-hash [path] (if (string? path) (Math/abs ^int (hash path)) path)) (defn write-qid [^Buffer buffer qid-map] (buff/write-byte buffer (:type qid-map)) (buff/write-int buffer (:version qid-map)) (buff/write-long buffer (path-hash (:path qid-map))) buffer) (defn read-qid [^Buffer buffer] {:type (buff/read-byte buffer) :version (buff/read-int buffer) :path (buff/read-long buffer)}) ;; 9P Doesn't allow for any NUL characters at all. ;; Instead of null-terminated strings, all free-form data is prepended ;; by the length of bytes to read - as a short [2] or int [4]. ;; This design choice means you can always safely read 9P "front" to "back". ;; All strings are always UTF-8 (originally designed for Plan 9 and the 9P protocol). (defn write-2-piece [^Buffer buffer x] (buff/write-short buffer (buff/length x)) (if (string? x) (buff/write-string buffer x) (buff/write-bytes buffer x)) buffer) (def write-len-string write-2-piece) (defn write-4-piece [^Buffer buffer x] (buff/write-int buffer (buff/length x)) (if (string? x) (buff/write-string buffer x) (buff/write-bytes buffer x)) buffer) (defn read-2-piece [^Buffer buffer] (let [n (buff/read-short buffer)] (buff/read-bytes buffer n))) (defn read-len-string [^Buffer buffer] (let [n (buff/read-short buffer)] (buff/read-string buffer n))) (defn read-4-piece [^Buffer buffer] (let [n (buff/read-int buffer)] (buff/read-bytes buffer n))) (defn write-stats [^Buffer buffer stats encode-length?] (let [buffer (buff/ensure-little-endian buffer) statsz-processed (reduce (fn [{:keys [stats statsz-total]} {:keys [name uid gid muid extension] :as stat}] (let [stat-sz (apply + (if extension 61 47) ;; base size values for standard vs dot-u (if extension (count extension) 0) ;; If we're :dot-u, we'll have an extension (map count [name uid gid muid]))] {:stats (conj stats (assoc stat :statsz stat-sz)) :statsz-total (+ ^long statsz-total ^long stat-sz)})) {:stats [] :statsz-total 0} stats)] (when encode-length? (buff/write-short buffer (+ ^long (:statsz-total statsz-processed) 2))) (doseq [stat (:stats statsz-processed)] (buff/write-short buffer (:statsz stat)) (buff/write-short buffer (:type stat)) (buff/write-int buffer (:dev stat)) (write-qid buffer (:qid stat)) (buff/write-int buffer (:mode stat)) (buff/write-int buffer (:atime stat)) (buff/write-int buffer (:mtime stat)) (buff/write-long buffer (:length stat)) (write-len-string buffer (:name stat)) (write-len-string buffer (:uid stat)) (write-len-string buffer (:gid stat)) (write-len-string buffer (:muid stat)) (when (:extension stat) ;; when dot-u (write-len-string buffer (:extension stat)) (buff/write-int buffer (:uidnum stat)) (buff/write-int buffer (:gidnum stat)) (buff/write-int buffer (:muidnum stat)))) buffer)) (defn read-stats [^Buffer buffer decode-length? dot-u?] (when decode-length? (buff/read-short buffer)) (loop [stats (transient []) initial-bytes ^long (buff/readable-bytes buffer)] (if (pos? initial-bytes) (let [statsz (buff/read-short buffer) stype (buff/read-short buffer) dev (buff/read-int buffer) qid (read-qid buffer) mode (buff/read-int buffer) atime (buff/read-int buffer) mtime (buff/read-int buffer) slen (buff/read-long buffer) sname (read-len-string buffer) uid (read-len-string buffer) gid (read-len-string buffer) muid (read-len-string buffer) ;;(if (or dot-u? ;; (> statsz (- initial-bytes (buff/readable-bytes buffer))) ;; (read-len-string buffer) ;; "")) extension (if dot-u? (read-len-string buffer) "") uidnum (if dot-u? (buff/read-int buffer) 0) gidnum (if dot-u? (buff/read-int buffer) 0) muidnum (if dot-u? (buff/read-int buffer) 0)] (recur (conj! stats (merge {:statsz statsz :type stype :dev dev :qid qid :mode mode :atime atime :mtime mtime :length slen :name sname :uid uid :gid gid :muid muid} (when dot-u? {:extension extension :uidnum uidnum :gidnum gidnum :muidnum muidnum}))) ^long (buff/readable-bytes buffer))) (persistent! stats)))) (defn ensure! ([pred x] (ensure! pred x (str "Value failed predicate contract: " x))) ([pred x message] (if (pred x) x (throw (ex-info message {:type :ensure-violation :predicate pred :value x}))))) (defn now [] (.getTime ^Date (Date.))) (def mode-bits ["---" "--x" "-w-" "-wx" "r--" "r-x" "rw-" "rwx"]) (defn mode-str [mode-num] (let [mode-fn (fn [shift-num] ; Just numbers... ;(bit-and (bit-shift-right mode-num shift-num) 7) (get mode-bits (bit-and (bit-shift-right mode-num shift-num) 7))) mode-bit (cond (pos? (bit-and mode-num proto/DMDIR)) "d" (pos? (bit-and mode-num proto/DMAPPEND)) "a" :else "-")] (str mode-bit (mode-fn 6) (mode-fn 3) (mode-fn 0)))) (def default-message-size-bytes 8192) (defn numeric-fcall "Replace all fcall map values with the ensured numeric values for the protocol" [fcall-map] (merge fcall-map {:type (let [call-type (:type fcall-map)] (ensure! proto/v2-codes (if (keyword? call-type) (proto/v2 call-type) call-type) (str "Invalid type value: " call-type))) :tag (ensure! number? (:tag fcall-map) (str "Invalid tag value: " (:tag fcall-map)))})) (defn valid-fcall? [fcall-map] (every? identity (some-> fcall-map (select-keys [:type :tag]) vals))) (defn fcall "Create a valid fcall-map with defaults set. Can accept a base map, or kv-args" ([base-map] {:pre [(map? base-map)] :post [valid-fcall?]} (merge {:tag (rand-int 32000) ;; Random short generation takes ~0.05ms :fid proto/NOFID :afid proto/NOFID :uname (System/getProperty "user.name") :aname "" :stat [] :iounit default-message-size-bytes :wqid [] :msize default-message-size-bytes ;; Can be as large as 65512 :version (if (:dot-u base-map) proto/versionu proto/version) :uidnum proto/UIDUNDEF :gidnum proto/UIDUNDEF :muidnum proto/UIDUNDEF} base-map)) ([k & vkv-pairs] {:pre [(keyword? k)]} (fcall (apply hash-map k vkv-pairs)))) (defn stat "Generate a close-to-complete stat map" [base-map] (merge {:type 0 :dev 0 :statsz 0 :mode 0644 :length 0 ;; 0 Length is used for directories and devices/services :name "" :uid "user" :gid "user" :muid "user"} base-map)) ;; Encoding and decoding ;; ---------------------- ;; Messages are defined in the [RFC Message Section](http://9p.cat-v.org/documentation/rfc/#msgs) ;; fcalls/message are based on the following struct: ;; type Fcall struct { ;; Size uint32 // size of the message (4 - int) ;; Type uint8 // message type (1 - byte) ;; Fid uint32 // file identifier (4 - int) ;; Tag uint16 // message tag (2 - short) ;; Msize uint32 // maximum message size (used by Tversion, Rversion) (4 - int) ;; Version string // protocol version (used by Tversion, Rversion) (string) ;; Oldtag uint16 // tag of the message to flush (used by Tflush) (2 - short) ;; Error string // error (used by Rerror) (string) ;; Qid // file Qid (used by Rauth, Rattach, Ropen, Rcreate) (struct - 1, 4, 8 - type, version, path) ;; Iounit uint32 // maximum bytes read without breaking in multiple messages (used by Ropen, Rcreate) (4 - int) ;; Afid uint32 // authentication fid (used by Tauth, Tattach) (4 - int) ;; Uname string // user name (used by Tauth, Tattach) (string) ;; Aname string // attach name (used by Tauth, Tattach) (string) ;; Perm uint32 // file permission (mode) (used by Tcreate) (4 - int) ;; Name string // file name (used by Tcreate) (string) ;; Mode uint8 // open mode (used by Topen, Tcreate) (1 - byte) ;; Newfid uint32 // the fid that represents the file walked to (used by Twalk) (4 - int) ;; Wname []string // list of names to walk (used by Twalk) (vector of strings) ;; Wqid []Qid // list of Qids for the walked files (used by Rwalk) (vector of Qids) ;; Offset uint64 // offset in the file to read/write from/to (used by Tread, Twrite) (8 - long) ;; Count uint32 // number of bytes read/written (used by Tread, Rread, Twrite, Rwrite) (4 - int) ;; Dir // file description (used by Rstat, Twstat) ;; ;; /* 9P2000.u extensions */ ;; Errornum uint32 // error code, 9P2000.u only (used by Rerror) (4 - int) ;; Extension string // special file description, 9P2000.u only (used by Tcreate) (string) ;; Unamenum uint32 // user ID, 9P2000.u only (used by Tauth, Tattach) (4 - int) ;; } (def valid-fcall-keys #{:msize ; Tversion, Rversion :version ; Tversion, Rversion :oldtag ; Tflush :ename ; Rerror :qid ; Rattach, Ropen, Rcreate :iounit ; Ropen, Rcreate :aqid ; Rauth :afid ; Tauth, Tattach :uname ; Tauth, Tattach :aname ; Tauth, Tattach :perm ; Tcreate :name ; Tcreate :mode ; Tcreate, Topen :newfid ; Twalk :wname ; Twalk, array :wqid ; Rwalk, array :offset ; Tread, Twrite :count ; Tread, Twrite :data ; Twrite, Rread :nstat ; Twstat, Rstat :stat ; Twstat, Rstat ; dotu extensions: :errno ; Rerror ; Tcreate :extension}) (def fcall-keys {:tversion [:type :tag :msize :version] :rversion [:type :tag :msize :version] :tauth [:type :tag :afid :uname :aname] :rauth [:type :tag :aqid] :rerror [:type :tag :ename] :tflush [:type :tag :oldtag] :rflush [:type :tag] :tattach [:type :tag :afid :uname :aname] :rattach [:type :tag :qid] :twalk [:type :tag :fid :newfid :wname] :rwalk [:type :tag :wqid] :topen [:type :tag :fid :mode] :ropen [:type :tag :qid :iounit] :topenfd [:type :tag :fid :mode] :ropenfd [:type :tag :qid :iounit :unixfd] :tcreate [:type :tag :fid :name :perm :mode] :rcreate [:type :tag :qid :iounit] :tread [:type :tag :fid :offset :count] :rread [:type :tag :count :data] :twrite [:type :tag :fid :offset :count :data] :rwrite [:type :tag :count] :tclunk [:type :tag :fid] :rclunk [:type :tag] :tremove [:type :tag :fid] :rremove [:type :tag] :tstat [:type :tag :fid] :rstat [:type :tag :stat] :twstat [:type :tag :fid :stat] :rwstat [:type :tag]}) (defn show-fcall [fcall-map] (pr-str (select-keys fcall-map (get fcall-keys (:type fcall-map) [:type :tag])))) ;; 9P has two types of messages: T-Messages and R-Messages. ;; From the RFC/Intro: ;; The Plan 9 File Protocol, 9P, is used for messages between clients and servers. ;; A client transmits *requests* (T-messages) to a server, which subsequently returns *replies* (R-messages) to the client. ;; The combined acts of transmitting (receiving) a request of a particular type, and receiving (transmitting) its reply ;; is called a transaction of that type. ;; Each message consists of a sequence of bytes. Two-, four-, and eight-byte fields ;; hold unsigned integers represented in little-endian order (least significant byte first). ;; Data items of larger or variable lengths are represented by a two-byte field specifying a count, n, followed by n bytes of data. ;; Text strings are represented this way, with the text itself stored as a UTF-8 encoded sequence of Unicode characters. ;; Text strings in 9P messages are not NUL-terminated: n counts the bytes of UTF-8 data, which include no final zero byte. ;; The NUL character is illegal in all text strings in 9P, and is therefore excluded from file names, user names, and so on. ;; Messages are transported in byte form to allow for machine independence. (defn encode-fcall! "Given an fcall map and a Buffer, encode the fcall onto the buffer and return the buffer NOTE: This will reset/clear the buffer" [fcall-map ^Buffer buffer] (let [;; Return a little endian buffer buffer (buff/ensure-little-endian buffer) fcall (numeric-fcall fcall-map) ;; We'll match the type based on a keyword... fcall-type (if (keyword? (:type fcall-map)) (:type fcall-map) (proto/v2-codes (:type fcall)))] (buff/clear buffer) ;; TODO: This may have to be `write-int 0` (buff/write-zero buffer 4) ; "0000" - which will be used for total msg len when we're done ;; Imperatively pack the buffer (buff/write-byte buffer (:type fcall)) (buff/write-short buffer (:tag fcall)) ;; TODO: Consider replacing this cond with a dispatch map (cond (#{:tversion :rversion} fcall-type) (do (buff/write-int buffer (:msize fcall)) (write-len-string buffer (:version fcall))) (= fcall-type :tauth) (do (buff/write-int buffer (:afid fcall)) (write-len-string buffer (:uname fcall)) (write-len-string buffer (:aname fcall)) (when (:dot-u fcall) (buff/write-int buffer (:uidnum fcall)))) (= fcall-type :rauth) (write-qid buffer (:aqid fcall)) (= fcall-type :rerror) (do (write-len-string buffer (:ename fcall "General Error")) (when (:dot-u fcall) (buff/write-int buffer (:errno fcall)))) (= fcall-type :tflush) (buff/write-short buffer (:oldtag fcall)) (= fcall-type :tattach) (do (buff/write-int buffer (:fid fcall)) (buff/write-int buffer (:afid fcall)) (write-len-string buffer (:uname fcall)) (write-len-string buffer (:aname fcall)) (when (:dot-u fcall) (buff/write-int buffer (:uidnum fcall)))) (= fcall-type :rattach) (write-qid buffer (:qid fcall)) (= fcall-type :twalk) (do (buff/write-int buffer (:fid fcall)) (buff/write-int buffer (:newfid fcall)) (buff/write-short buffer (count (:wname fcall))) (doseq [node-name (:wname fcall)] (write-len-string buffer node-name))) (= fcall-type :rwalk) (do (buff/write-short buffer (count (:wqid fcall))) (doseq [qid (:wqid fcall)] (write-qid buffer qid))) (= fcall-type :topen) (do (buff/write-int buffer (:fid fcall)) (buff/write-byte buffer (:mode fcall))) (#{:ropen :rcreate} fcall-type) (do (write-qid buffer (:qid fcall)) (buff/write-int buffer (:iounit fcall))) (= fcall-type :tcreate) (do (buff/write-int buffer (:fid fcall)) (write-len-string buffer (:name fcall)) (buff/write-int buffer (:perm fcall)) (buff/write-byte buffer (:mode fcall)) (when (:dot-u fcall) (write-len-string (:extension fcall)))) (= fcall-type :tread) (do (buff/write-int buffer (:fid fcall)) (buff/write-long buffer (:offset fcall)) (buff/write-int buffer (:count fcall))) (= fcall-type :rread) (write-4-piece buffer (:data fcall)) (= fcall-type :twrite) (do (buff/write-int buffer (:fid fcall)) (buff/write-long buffer (:offset fcall)) (write-4-piece buffer (:data fcall))) (= fcall-type :rwrite) (buff/write-int buffer (:count fcall)) (#{:tclunk :tremove :tstat} fcall-type) (buff/write-int buffer (:fid fcall)) (#{:rstat :twstat} fcall-type) (do (when (= fcall-type :twstat) (buff/write-int buffer (:fid fcall))) (write-stats buffer (:stat fcall) true)) :else buffer) ;; Patch up the size of the message (let [length (buff/length buffer)] (buff/move-writer-index buffer 0) (buff/write-int buffer length) (buff/move-writer-index buffer length)))) (def ^{:doc "Return a transducer that encodes an fcall into a Buffer"} encode-fcall-xf (map (fn [fcall] (encode-fcall! fcall (.directBuffer PooledByteBufAllocator/DEFAULT))))) (defn decode-fcall! "Given a buffer (full of bytes) and optionally a base fcall map, decode the bytes into a full fcall map. Returns the decoded/complete fcall-map. Note: This resets the read index on the buffer on entry and exhausts it by exit." ([^Buffer base-buffer] (decode-fcall! base-buffer {})) ([^Buffer base-buffer base-fcall-map] (let [buffer (buff/ensure-little-endian base-buffer) _ (buff/reset-read-index buffer) buffer-size (buff/length buffer) size (buff/read-int buffer) _ (when (not= buffer-size size) (throw (ex-info (str "Reported message size and actual size differ: " size "; actual: " buffer-size) {:reported-size size :buffer-size buffer-size :fcall-map base-fcall-map}))) _ (when-not (<= 7 size 0xffffffff) (throw (ex-info (str "Bad fcall message size on decode: " size) {:size size :fcall-map base-fcall-map}))) ftype (buff/read-byte buffer) ftag (buff/read-short buffer) fcall-type (ensure! identity (proto/v2-codes ftype) (str "Decoded invalid type numeric: " ftype)) fcall-map (fcall {:type fcall-type :tag ftag :original-size size})] ;; TODO: Consider replacing this cond with a dispatch map (cond (#{:tversion :rversion} fcall-type) (assoc fcall-map :msize (buff/read-int buffer) :version (read-len-string buffer)) (= fcall-type :tauth) (let [afid (buff/read-int buffer) uname (read-len-string buffer) aname (read-len-string buffer)] (merge fcall-map {:afid afid :uname uname :aname aname} (when (:dot-u fcall-map) {:uidnum (buff/read-int buffer)}))) (= fcall-type :rauth) (assoc fcall-map :aqid (read-qid buffer)) (= fcall-type :rerror) (merge fcall-map {:ename (read-len-string buffer)} (when (:dot-u fcall-map) {:errno (buff/read-int buffer)})) (= fcall-type :tflush) (assoc fcall-map :oldtag (buff/read-short buffer)) (= fcall-type :tattach) (let [fid (buff/read-int buffer) afid (buff/read-int buffer) uname (read-len-string buffer) aname (read-len-string buffer)] (merge fcall-map {:fid fid :afid afid :uname uname :aname aname} (when (:dot-u fcall-map) {:uidnum (buff/read-int buffer)}))) (= fcall-type :rattach) (assoc fcall-map :qid (read-qid buffer)) (= fcall-type :twalk) (let [fid (buff/read-int buffer) newfid (buff/read-int buffer) n (buff/read-short buffer)] (assoc fcall-map :fid fid :newfid newfid :wname (mapv (fn [name-n] (read-len-string buffer)) (range n)))) (= fcall-type :rwalk) (let [n (buff/read-short buffer)] (assoc fcall-map :wqid (mapv (fn [name-n] (read-qid buffer)) (range n)))) (= fcall-type :topen) (assoc fcall-map :fid (buff/read-int buffer) :mode (buff/read-byte buffer)) (#{:ropen :rcreate} fcall-type) (assoc fcall-map :qid (read-qid buffer) :iounit (buff/read-int buffer)) (= fcall-type :tcreate) (let [fid (buff/read-int buffer) name (read-len-string buffer) perm (buff/read-int buffer) mode (buff/read-byte buffer)] (merge fcall-map {:fid fid :name <NAME> :perm perm :mode mode} (when (:dot-u fcall-map) {:extension (read-len-string buffer)}))) (= fcall-type :tread) (assoc fcall-map :fid (buff/read-int buffer) :offset (buff/read-long buffer) :count (buff/read-int buffer)) (= fcall-type :rread) (assoc fcall-map :data (read-4-piece buffer)) (= fcall-type :twrite) (let [fid (buff/read-int buffer) offset (buff/read-long buffer) cnt (buff/read-int buffer)] (assoc fcall-map :fid fid :offset offset :count cnt :data (buff/read-bytes buffer cnt))) (= fcall-type :rwrite) (assoc fcall-map :count (buff/read-int buffer)) (#{:tclunk :tremove :tstat} fcall-type) (assoc fcall-map :fid (buff/read-int buffer)) (#{:rstat :twstat} fcall-type) (merge fcall-map (when (= fcall-type :twstat) {:fid (buff/read-int buffer)}) {:stat (read-stats buffer true (:dot-u fcall-map))}) :else fcall-map)))) (def ^{:doc "A transducer that converts Buffers into fcall maps"} decode-fcall-xf (map (fn [^Buffer buffer] (decode-fcall! buffer)))) (defn directory? [qid-type] (if (map? qid-type) (directory? (:type qid-type)) (pos? (bit-and qid-type proto/QTDIR)))) (defn file? [qid-type] (if (map? qid-type) (file? (:type qid-type)) (or (= qid-type proto/QTFILE) ;; Protect against mode bit '0' (pos? (bit-and qid-type proto/QTFILE)) (pos? (bit-and qid-type proto/QTAPPEND)) (pos? (bit-and qid-type proto/QTTMP))))) (defn symlink? [qid-type] (if (map? qid-type) (symlink? (:type qid-type)) (pos? (bit-and qid-type proto/QTSYMLINK)))) (defn permission? "Return true if some stat-like map allows some specific permission for uid, otherwise false. Target-perm is expect to be an Access-type permission" [fd-stat uid target-perm] ;; Shield your eyes - we need to bash m as we conditionally check chunks of the perm bits (let [mode (:mode fd-stat) m (volatile! (bit-and mode 7))] (cond (= target-perm (bit-and target-perm @m)) true (and (= (:uid fd-stat) uid) (do (vreset! m (bit-or @m (bit-and (bit-shift-right mode 6) 7))) (= target-perm (bit-and target-perm @m)))) true (and (= (:gid fd-stat) uid) (do (vreset! m (bit-or @m (bit-and (bit-shift-right mode 3) 7))) (= target-perm (bit-and target-perm @m)))) true :else false))) (defn apply-permissions [initial-mode additional-modes] (apply bit-or initial-mode additional-modes)) (defn open->access "Convert an Open-style permission into an Access-style permission" [target-perm] (let [np (bit-and target-perm 3) access-perm (proto/perm-translation np)] (if (pos? (bit-and target-perm proto/OTRUNC)) (bit-or access-perm proto/AWRITE) access-perm))) (defn mode->stat [mode] (bit-or (bit-and mode 0777) (bit-shift-right (bit-xor (bit-and mode proto/DMDIR) proto/DMDIR) 16) (bit-shift-right (bit-and mode proto/DMDIR) 17) (bit-shift-right (bit-and mode proto/DMSYMLINK) 10) (bit-shift-right (bit-and mode proto/DMSYMLINK) 12) (bit-shift-right (bit-and mode proto/DMSETUID) 8) (bit-shift-right (bit-and mode proto/DMSETGID) 8) (bit-shift-right (bit-and mode proto/DMSTICKY) 7))) (comment (mode->stat 0664) )
true
; Copyright 2019 Cognitect. All Rights Reserved. ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS-IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns cognitect.clj9p.io (:require [cognitect.clj9p.9p :as n9p] [cognitect.clj9p.proto :as proto] [cognitect.clj9p.buffer :as buff] [clojure.core.async :as async]) (:import (cognitect.clj9p.buffer Buffer) (java.nio ByteOrder) (io.netty.buffer ;Unpooled ByteBuf ByteBufUtil) (io.netty.buffer PooledByteBufAllocator) (java.nio ByteBuffer) (java.nio.channels ByteChannel) (io.netty.channel ChannelHandlerContext) (java.util Date))) ;; 9P Protocol implementation notes ;; -------------------------------- ;; At the bottom level, 9P operates on calls sent to file descriptors (files, sockets, channels). ;; In this implementation, calls are constructed using Clojure maps. ;; Many benefits fall out of this choice (they can be serialized with JSON or ;; Transit, they can be stored on a file or database and read in, etc.). When ;; a message/call is sent to the fd, it is encoded into binary and packed on a ;; buffer. Buffers are programmed against an interface and the default ;; implementation uses a Netty ByteBuf (DirectBuffer). Buffers are also used ;; to unpack calls/messages and turn them back into maps. (defn default-buffer "This creates a Buffer suitable for use with encoding/decoding fcalls, but one should prefer using PooledByteBufAllocator from Netty (with direct Buffers only)" ([] (buff/ensure-little-endian (.directBuffer PooledByteBufAllocator/DEFAULT))) ([initial-byte-array] (if (instance? ByteBuf initial-byte-array) (buff/ensure-little-endian initial-byte-array) ;; Caller assumed Byte Arrays, but was operating in-place (buff/write-byte-array (buff/ensure-little-endian (.directBuffer PooledByteBufAllocator/DEFAULT)) initial-byte-array)))) (extend-protocol buff/Length ByteBuf (length [t] (.readableBytes t)) String (length [t] (.length t)) nil (length [t] 0)) (extend-protocol buff/Buffer ByteBuf (write-string [t s] (ByteBufUtil/writeUtf8 t ^String s) t) (write-byte-array [t ba] (.writeBytes t ^bytes ba)) (write-bytes [t bb] (.writeBytes t ^ByteBuf bb) t) (write-nio-bytes [t byte-buffer] (.writeBytes t ^ByteBuffer byte-buffer)) (write-zero [t n] (.writeZero t n) t) (write-byte [t b] (.writeByte t b) t) (write-short [t s] (.writeShort t s) t) (write-int [t i] (.writeInt t i) t) (write-long [t l] (.writeLong t l) t) (writer-index [t] (.writerIndex t)) (move-writer-index [t n] (.writerIndex t n) t) (read-string [t n] (let [ba (byte-array n)] (.readBytes t ba) (String. ba "UTF-8"))) (read-bytes [t n] (let [ba (byte-array n)] (.readBytes t ba) ba)) (read-byte [t] (.readUnsignedByte t)) (read-short [t] (.readUnsignedShort t)) (read-int [t] (.readUnsignedInt t)) (read-long [t] (.readLong t)) ;; TODO: Should the appropriate shift be done here (readable-bytes [t] (.readableBytes t)) (reset-read-index [t] (.readerIndex t 0) t) (as-byte-array [t] (.array t)) (as-byte-buffer [t] (.nioBuffer t)) ;; Note: This will share content with the underlying Buffer (ensure-little-endian [t] (.order t ByteOrder/LITTLE_ENDIAN)) (slice [t index length] (.slice t index length)) (clear [t] (.clear t) t)) (defn slice ([t offset] (buff/slice t offset (- (buff/length t) offset))) ([t offset length] (buff/slice t offset length))) (def little-endian buff/ensure-little-endian) (def length buff/length) ;; Auxiliary functions ;; ------------------- (defn path-hash [path] (if (string? path) (Math/abs ^int (hash path)) path)) (defn write-qid [^Buffer buffer qid-map] (buff/write-byte buffer (:type qid-map)) (buff/write-int buffer (:version qid-map)) (buff/write-long buffer (path-hash (:path qid-map))) buffer) (defn read-qid [^Buffer buffer] {:type (buff/read-byte buffer) :version (buff/read-int buffer) :path (buff/read-long buffer)}) ;; 9P Doesn't allow for any NUL characters at all. ;; Instead of null-terminated strings, all free-form data is prepended ;; by the length of bytes to read - as a short [2] or int [4]. ;; This design choice means you can always safely read 9P "front" to "back". ;; All strings are always UTF-8 (originally designed for Plan 9 and the 9P protocol). (defn write-2-piece [^Buffer buffer x] (buff/write-short buffer (buff/length x)) (if (string? x) (buff/write-string buffer x) (buff/write-bytes buffer x)) buffer) (def write-len-string write-2-piece) (defn write-4-piece [^Buffer buffer x] (buff/write-int buffer (buff/length x)) (if (string? x) (buff/write-string buffer x) (buff/write-bytes buffer x)) buffer) (defn read-2-piece [^Buffer buffer] (let [n (buff/read-short buffer)] (buff/read-bytes buffer n))) (defn read-len-string [^Buffer buffer] (let [n (buff/read-short buffer)] (buff/read-string buffer n))) (defn read-4-piece [^Buffer buffer] (let [n (buff/read-int buffer)] (buff/read-bytes buffer n))) (defn write-stats [^Buffer buffer stats encode-length?] (let [buffer (buff/ensure-little-endian buffer) statsz-processed (reduce (fn [{:keys [stats statsz-total]} {:keys [name uid gid muid extension] :as stat}] (let [stat-sz (apply + (if extension 61 47) ;; base size values for standard vs dot-u (if extension (count extension) 0) ;; If we're :dot-u, we'll have an extension (map count [name uid gid muid]))] {:stats (conj stats (assoc stat :statsz stat-sz)) :statsz-total (+ ^long statsz-total ^long stat-sz)})) {:stats [] :statsz-total 0} stats)] (when encode-length? (buff/write-short buffer (+ ^long (:statsz-total statsz-processed) 2))) (doseq [stat (:stats statsz-processed)] (buff/write-short buffer (:statsz stat)) (buff/write-short buffer (:type stat)) (buff/write-int buffer (:dev stat)) (write-qid buffer (:qid stat)) (buff/write-int buffer (:mode stat)) (buff/write-int buffer (:atime stat)) (buff/write-int buffer (:mtime stat)) (buff/write-long buffer (:length stat)) (write-len-string buffer (:name stat)) (write-len-string buffer (:uid stat)) (write-len-string buffer (:gid stat)) (write-len-string buffer (:muid stat)) (when (:extension stat) ;; when dot-u (write-len-string buffer (:extension stat)) (buff/write-int buffer (:uidnum stat)) (buff/write-int buffer (:gidnum stat)) (buff/write-int buffer (:muidnum stat)))) buffer)) (defn read-stats [^Buffer buffer decode-length? dot-u?] (when decode-length? (buff/read-short buffer)) (loop [stats (transient []) initial-bytes ^long (buff/readable-bytes buffer)] (if (pos? initial-bytes) (let [statsz (buff/read-short buffer) stype (buff/read-short buffer) dev (buff/read-int buffer) qid (read-qid buffer) mode (buff/read-int buffer) atime (buff/read-int buffer) mtime (buff/read-int buffer) slen (buff/read-long buffer) sname (read-len-string buffer) uid (read-len-string buffer) gid (read-len-string buffer) muid (read-len-string buffer) ;;(if (or dot-u? ;; (> statsz (- initial-bytes (buff/readable-bytes buffer))) ;; (read-len-string buffer) ;; "")) extension (if dot-u? (read-len-string buffer) "") uidnum (if dot-u? (buff/read-int buffer) 0) gidnum (if dot-u? (buff/read-int buffer) 0) muidnum (if dot-u? (buff/read-int buffer) 0)] (recur (conj! stats (merge {:statsz statsz :type stype :dev dev :qid qid :mode mode :atime atime :mtime mtime :length slen :name sname :uid uid :gid gid :muid muid} (when dot-u? {:extension extension :uidnum uidnum :gidnum gidnum :muidnum muidnum}))) ^long (buff/readable-bytes buffer))) (persistent! stats)))) (defn ensure! ([pred x] (ensure! pred x (str "Value failed predicate contract: " x))) ([pred x message] (if (pred x) x (throw (ex-info message {:type :ensure-violation :predicate pred :value x}))))) (defn now [] (.getTime ^Date (Date.))) (def mode-bits ["---" "--x" "-w-" "-wx" "r--" "r-x" "rw-" "rwx"]) (defn mode-str [mode-num] (let [mode-fn (fn [shift-num] ; Just numbers... ;(bit-and (bit-shift-right mode-num shift-num) 7) (get mode-bits (bit-and (bit-shift-right mode-num shift-num) 7))) mode-bit (cond (pos? (bit-and mode-num proto/DMDIR)) "d" (pos? (bit-and mode-num proto/DMAPPEND)) "a" :else "-")] (str mode-bit (mode-fn 6) (mode-fn 3) (mode-fn 0)))) (def default-message-size-bytes 8192) (defn numeric-fcall "Replace all fcall map values with the ensured numeric values for the protocol" [fcall-map] (merge fcall-map {:type (let [call-type (:type fcall-map)] (ensure! proto/v2-codes (if (keyword? call-type) (proto/v2 call-type) call-type) (str "Invalid type value: " call-type))) :tag (ensure! number? (:tag fcall-map) (str "Invalid tag value: " (:tag fcall-map)))})) (defn valid-fcall? [fcall-map] (every? identity (some-> fcall-map (select-keys [:type :tag]) vals))) (defn fcall "Create a valid fcall-map with defaults set. Can accept a base map, or kv-args" ([base-map] {:pre [(map? base-map)] :post [valid-fcall?]} (merge {:tag (rand-int 32000) ;; Random short generation takes ~0.05ms :fid proto/NOFID :afid proto/NOFID :uname (System/getProperty "user.name") :aname "" :stat [] :iounit default-message-size-bytes :wqid [] :msize default-message-size-bytes ;; Can be as large as 65512 :version (if (:dot-u base-map) proto/versionu proto/version) :uidnum proto/UIDUNDEF :gidnum proto/UIDUNDEF :muidnum proto/UIDUNDEF} base-map)) ([k & vkv-pairs] {:pre [(keyword? k)]} (fcall (apply hash-map k vkv-pairs)))) (defn stat "Generate a close-to-complete stat map" [base-map] (merge {:type 0 :dev 0 :statsz 0 :mode 0644 :length 0 ;; 0 Length is used for directories and devices/services :name "" :uid "user" :gid "user" :muid "user"} base-map)) ;; Encoding and decoding ;; ---------------------- ;; Messages are defined in the [RFC Message Section](http://9p.cat-v.org/documentation/rfc/#msgs) ;; fcalls/message are based on the following struct: ;; type Fcall struct { ;; Size uint32 // size of the message (4 - int) ;; Type uint8 // message type (1 - byte) ;; Fid uint32 // file identifier (4 - int) ;; Tag uint16 // message tag (2 - short) ;; Msize uint32 // maximum message size (used by Tversion, Rversion) (4 - int) ;; Version string // protocol version (used by Tversion, Rversion) (string) ;; Oldtag uint16 // tag of the message to flush (used by Tflush) (2 - short) ;; Error string // error (used by Rerror) (string) ;; Qid // file Qid (used by Rauth, Rattach, Ropen, Rcreate) (struct - 1, 4, 8 - type, version, path) ;; Iounit uint32 // maximum bytes read without breaking in multiple messages (used by Ropen, Rcreate) (4 - int) ;; Afid uint32 // authentication fid (used by Tauth, Tattach) (4 - int) ;; Uname string // user name (used by Tauth, Tattach) (string) ;; Aname string // attach name (used by Tauth, Tattach) (string) ;; Perm uint32 // file permission (mode) (used by Tcreate) (4 - int) ;; Name string // file name (used by Tcreate) (string) ;; Mode uint8 // open mode (used by Topen, Tcreate) (1 - byte) ;; Newfid uint32 // the fid that represents the file walked to (used by Twalk) (4 - int) ;; Wname []string // list of names to walk (used by Twalk) (vector of strings) ;; Wqid []Qid // list of Qids for the walked files (used by Rwalk) (vector of Qids) ;; Offset uint64 // offset in the file to read/write from/to (used by Tread, Twrite) (8 - long) ;; Count uint32 // number of bytes read/written (used by Tread, Rread, Twrite, Rwrite) (4 - int) ;; Dir // file description (used by Rstat, Twstat) ;; ;; /* 9P2000.u extensions */ ;; Errornum uint32 // error code, 9P2000.u only (used by Rerror) (4 - int) ;; Extension string // special file description, 9P2000.u only (used by Tcreate) (string) ;; Unamenum uint32 // user ID, 9P2000.u only (used by Tauth, Tattach) (4 - int) ;; } (def valid-fcall-keys #{:msize ; Tversion, Rversion :version ; Tversion, Rversion :oldtag ; Tflush :ename ; Rerror :qid ; Rattach, Ropen, Rcreate :iounit ; Ropen, Rcreate :aqid ; Rauth :afid ; Tauth, Tattach :uname ; Tauth, Tattach :aname ; Tauth, Tattach :perm ; Tcreate :name ; Tcreate :mode ; Tcreate, Topen :newfid ; Twalk :wname ; Twalk, array :wqid ; Rwalk, array :offset ; Tread, Twrite :count ; Tread, Twrite :data ; Twrite, Rread :nstat ; Twstat, Rstat :stat ; Twstat, Rstat ; dotu extensions: :errno ; Rerror ; Tcreate :extension}) (def fcall-keys {:tversion [:type :tag :msize :version] :rversion [:type :tag :msize :version] :tauth [:type :tag :afid :uname :aname] :rauth [:type :tag :aqid] :rerror [:type :tag :ename] :tflush [:type :tag :oldtag] :rflush [:type :tag] :tattach [:type :tag :afid :uname :aname] :rattach [:type :tag :qid] :twalk [:type :tag :fid :newfid :wname] :rwalk [:type :tag :wqid] :topen [:type :tag :fid :mode] :ropen [:type :tag :qid :iounit] :topenfd [:type :tag :fid :mode] :ropenfd [:type :tag :qid :iounit :unixfd] :tcreate [:type :tag :fid :name :perm :mode] :rcreate [:type :tag :qid :iounit] :tread [:type :tag :fid :offset :count] :rread [:type :tag :count :data] :twrite [:type :tag :fid :offset :count :data] :rwrite [:type :tag :count] :tclunk [:type :tag :fid] :rclunk [:type :tag] :tremove [:type :tag :fid] :rremove [:type :tag] :tstat [:type :tag :fid] :rstat [:type :tag :stat] :twstat [:type :tag :fid :stat] :rwstat [:type :tag]}) (defn show-fcall [fcall-map] (pr-str (select-keys fcall-map (get fcall-keys (:type fcall-map) [:type :tag])))) ;; 9P has two types of messages: T-Messages and R-Messages. ;; From the RFC/Intro: ;; The Plan 9 File Protocol, 9P, is used for messages between clients and servers. ;; A client transmits *requests* (T-messages) to a server, which subsequently returns *replies* (R-messages) to the client. ;; The combined acts of transmitting (receiving) a request of a particular type, and receiving (transmitting) its reply ;; is called a transaction of that type. ;; Each message consists of a sequence of bytes. Two-, four-, and eight-byte fields ;; hold unsigned integers represented in little-endian order (least significant byte first). ;; Data items of larger or variable lengths are represented by a two-byte field specifying a count, n, followed by n bytes of data. ;; Text strings are represented this way, with the text itself stored as a UTF-8 encoded sequence of Unicode characters. ;; Text strings in 9P messages are not NUL-terminated: n counts the bytes of UTF-8 data, which include no final zero byte. ;; The NUL character is illegal in all text strings in 9P, and is therefore excluded from file names, user names, and so on. ;; Messages are transported in byte form to allow for machine independence. (defn encode-fcall! "Given an fcall map and a Buffer, encode the fcall onto the buffer and return the buffer NOTE: This will reset/clear the buffer" [fcall-map ^Buffer buffer] (let [;; Return a little endian buffer buffer (buff/ensure-little-endian buffer) fcall (numeric-fcall fcall-map) ;; We'll match the type based on a keyword... fcall-type (if (keyword? (:type fcall-map)) (:type fcall-map) (proto/v2-codes (:type fcall)))] (buff/clear buffer) ;; TODO: This may have to be `write-int 0` (buff/write-zero buffer 4) ; "0000" - which will be used for total msg len when we're done ;; Imperatively pack the buffer (buff/write-byte buffer (:type fcall)) (buff/write-short buffer (:tag fcall)) ;; TODO: Consider replacing this cond with a dispatch map (cond (#{:tversion :rversion} fcall-type) (do (buff/write-int buffer (:msize fcall)) (write-len-string buffer (:version fcall))) (= fcall-type :tauth) (do (buff/write-int buffer (:afid fcall)) (write-len-string buffer (:uname fcall)) (write-len-string buffer (:aname fcall)) (when (:dot-u fcall) (buff/write-int buffer (:uidnum fcall)))) (= fcall-type :rauth) (write-qid buffer (:aqid fcall)) (= fcall-type :rerror) (do (write-len-string buffer (:ename fcall "General Error")) (when (:dot-u fcall) (buff/write-int buffer (:errno fcall)))) (= fcall-type :tflush) (buff/write-short buffer (:oldtag fcall)) (= fcall-type :tattach) (do (buff/write-int buffer (:fid fcall)) (buff/write-int buffer (:afid fcall)) (write-len-string buffer (:uname fcall)) (write-len-string buffer (:aname fcall)) (when (:dot-u fcall) (buff/write-int buffer (:uidnum fcall)))) (= fcall-type :rattach) (write-qid buffer (:qid fcall)) (= fcall-type :twalk) (do (buff/write-int buffer (:fid fcall)) (buff/write-int buffer (:newfid fcall)) (buff/write-short buffer (count (:wname fcall))) (doseq [node-name (:wname fcall)] (write-len-string buffer node-name))) (= fcall-type :rwalk) (do (buff/write-short buffer (count (:wqid fcall))) (doseq [qid (:wqid fcall)] (write-qid buffer qid))) (= fcall-type :topen) (do (buff/write-int buffer (:fid fcall)) (buff/write-byte buffer (:mode fcall))) (#{:ropen :rcreate} fcall-type) (do (write-qid buffer (:qid fcall)) (buff/write-int buffer (:iounit fcall))) (= fcall-type :tcreate) (do (buff/write-int buffer (:fid fcall)) (write-len-string buffer (:name fcall)) (buff/write-int buffer (:perm fcall)) (buff/write-byte buffer (:mode fcall)) (when (:dot-u fcall) (write-len-string (:extension fcall)))) (= fcall-type :tread) (do (buff/write-int buffer (:fid fcall)) (buff/write-long buffer (:offset fcall)) (buff/write-int buffer (:count fcall))) (= fcall-type :rread) (write-4-piece buffer (:data fcall)) (= fcall-type :twrite) (do (buff/write-int buffer (:fid fcall)) (buff/write-long buffer (:offset fcall)) (write-4-piece buffer (:data fcall))) (= fcall-type :rwrite) (buff/write-int buffer (:count fcall)) (#{:tclunk :tremove :tstat} fcall-type) (buff/write-int buffer (:fid fcall)) (#{:rstat :twstat} fcall-type) (do (when (= fcall-type :twstat) (buff/write-int buffer (:fid fcall))) (write-stats buffer (:stat fcall) true)) :else buffer) ;; Patch up the size of the message (let [length (buff/length buffer)] (buff/move-writer-index buffer 0) (buff/write-int buffer length) (buff/move-writer-index buffer length)))) (def ^{:doc "Return a transducer that encodes an fcall into a Buffer"} encode-fcall-xf (map (fn [fcall] (encode-fcall! fcall (.directBuffer PooledByteBufAllocator/DEFAULT))))) (defn decode-fcall! "Given a buffer (full of bytes) and optionally a base fcall map, decode the bytes into a full fcall map. Returns the decoded/complete fcall-map. Note: This resets the read index on the buffer on entry and exhausts it by exit." ([^Buffer base-buffer] (decode-fcall! base-buffer {})) ([^Buffer base-buffer base-fcall-map] (let [buffer (buff/ensure-little-endian base-buffer) _ (buff/reset-read-index buffer) buffer-size (buff/length buffer) size (buff/read-int buffer) _ (when (not= buffer-size size) (throw (ex-info (str "Reported message size and actual size differ: " size "; actual: " buffer-size) {:reported-size size :buffer-size buffer-size :fcall-map base-fcall-map}))) _ (when-not (<= 7 size 0xffffffff) (throw (ex-info (str "Bad fcall message size on decode: " size) {:size size :fcall-map base-fcall-map}))) ftype (buff/read-byte buffer) ftag (buff/read-short buffer) fcall-type (ensure! identity (proto/v2-codes ftype) (str "Decoded invalid type numeric: " ftype)) fcall-map (fcall {:type fcall-type :tag ftag :original-size size})] ;; TODO: Consider replacing this cond with a dispatch map (cond (#{:tversion :rversion} fcall-type) (assoc fcall-map :msize (buff/read-int buffer) :version (read-len-string buffer)) (= fcall-type :tauth) (let [afid (buff/read-int buffer) uname (read-len-string buffer) aname (read-len-string buffer)] (merge fcall-map {:afid afid :uname uname :aname aname} (when (:dot-u fcall-map) {:uidnum (buff/read-int buffer)}))) (= fcall-type :rauth) (assoc fcall-map :aqid (read-qid buffer)) (= fcall-type :rerror) (merge fcall-map {:ename (read-len-string buffer)} (when (:dot-u fcall-map) {:errno (buff/read-int buffer)})) (= fcall-type :tflush) (assoc fcall-map :oldtag (buff/read-short buffer)) (= fcall-type :tattach) (let [fid (buff/read-int buffer) afid (buff/read-int buffer) uname (read-len-string buffer) aname (read-len-string buffer)] (merge fcall-map {:fid fid :afid afid :uname uname :aname aname} (when (:dot-u fcall-map) {:uidnum (buff/read-int buffer)}))) (= fcall-type :rattach) (assoc fcall-map :qid (read-qid buffer)) (= fcall-type :twalk) (let [fid (buff/read-int buffer) newfid (buff/read-int buffer) n (buff/read-short buffer)] (assoc fcall-map :fid fid :newfid newfid :wname (mapv (fn [name-n] (read-len-string buffer)) (range n)))) (= fcall-type :rwalk) (let [n (buff/read-short buffer)] (assoc fcall-map :wqid (mapv (fn [name-n] (read-qid buffer)) (range n)))) (= fcall-type :topen) (assoc fcall-map :fid (buff/read-int buffer) :mode (buff/read-byte buffer)) (#{:ropen :rcreate} fcall-type) (assoc fcall-map :qid (read-qid buffer) :iounit (buff/read-int buffer)) (= fcall-type :tcreate) (let [fid (buff/read-int buffer) name (read-len-string buffer) perm (buff/read-int buffer) mode (buff/read-byte buffer)] (merge fcall-map {:fid fid :name PI:NAME:<NAME>END_PI :perm perm :mode mode} (when (:dot-u fcall-map) {:extension (read-len-string buffer)}))) (= fcall-type :tread) (assoc fcall-map :fid (buff/read-int buffer) :offset (buff/read-long buffer) :count (buff/read-int buffer)) (= fcall-type :rread) (assoc fcall-map :data (read-4-piece buffer)) (= fcall-type :twrite) (let [fid (buff/read-int buffer) offset (buff/read-long buffer) cnt (buff/read-int buffer)] (assoc fcall-map :fid fid :offset offset :count cnt :data (buff/read-bytes buffer cnt))) (= fcall-type :rwrite) (assoc fcall-map :count (buff/read-int buffer)) (#{:tclunk :tremove :tstat} fcall-type) (assoc fcall-map :fid (buff/read-int buffer)) (#{:rstat :twstat} fcall-type) (merge fcall-map (when (= fcall-type :twstat) {:fid (buff/read-int buffer)}) {:stat (read-stats buffer true (:dot-u fcall-map))}) :else fcall-map)))) (def ^{:doc "A transducer that converts Buffers into fcall maps"} decode-fcall-xf (map (fn [^Buffer buffer] (decode-fcall! buffer)))) (defn directory? [qid-type] (if (map? qid-type) (directory? (:type qid-type)) (pos? (bit-and qid-type proto/QTDIR)))) (defn file? [qid-type] (if (map? qid-type) (file? (:type qid-type)) (or (= qid-type proto/QTFILE) ;; Protect against mode bit '0' (pos? (bit-and qid-type proto/QTFILE)) (pos? (bit-and qid-type proto/QTAPPEND)) (pos? (bit-and qid-type proto/QTTMP))))) (defn symlink? [qid-type] (if (map? qid-type) (symlink? (:type qid-type)) (pos? (bit-and qid-type proto/QTSYMLINK)))) (defn permission? "Return true if some stat-like map allows some specific permission for uid, otherwise false. Target-perm is expect to be an Access-type permission" [fd-stat uid target-perm] ;; Shield your eyes - we need to bash m as we conditionally check chunks of the perm bits (let [mode (:mode fd-stat) m (volatile! (bit-and mode 7))] (cond (= target-perm (bit-and target-perm @m)) true (and (= (:uid fd-stat) uid) (do (vreset! m (bit-or @m (bit-and (bit-shift-right mode 6) 7))) (= target-perm (bit-and target-perm @m)))) true (and (= (:gid fd-stat) uid) (do (vreset! m (bit-or @m (bit-and (bit-shift-right mode 3) 7))) (= target-perm (bit-and target-perm @m)))) true :else false))) (defn apply-permissions [initial-mode additional-modes] (apply bit-or initial-mode additional-modes)) (defn open->access "Convert an Open-style permission into an Access-style permission" [target-perm] (let [np (bit-and target-perm 3) access-perm (proto/perm-translation np)] (if (pos? (bit-and target-perm proto/OTRUNC)) (bit-or access-perm proto/AWRITE) access-perm))) (defn mode->stat [mode] (bit-or (bit-and mode 0777) (bit-shift-right (bit-xor (bit-and mode proto/DMDIR) proto/DMDIR) 16) (bit-shift-right (bit-and mode proto/DMDIR) 17) (bit-shift-right (bit-and mode proto/DMSYMLINK) 10) (bit-shift-right (bit-and mode proto/DMSYMLINK) 12) (bit-shift-right (bit-and mode proto/DMSETUID) 8) (bit-shift-right (bit-and mode proto/DMSETGID) 8) (bit-shift-right (bit-and mode proto/DMSTICKY) 7))) (comment (mode->stat 0664) )
[ { "context": "------------------\n;; File tramp.clj\n;; Written by Chris\n;; \n;; Created 4 Oct 2012\n;; Last modified 20 Oc", "end": 110, "score": 0.9998252987861633, "start": 105, "tag": "NAME", "value": "Chris" } ]
src/ctco/expr/tramp.clj
cjfrisz/clojure-tco
64
;;---------------------------------------------------------------------- ;; File tramp.clj ;; Written by Chris ;; ;; Created 4 Oct 2012 ;; Last modified 20 Oct 2012 ;; ;; Defines the TrampMark record type for marking trampoline entry points ;; and the Tramp record type for marking those entry points with the ;; name of the trampoline function to used in the generated code. ;; ;; Tramp implements the following protocols: ;; ;; PUnparse: ;; Unparses (recursively) the expression as `(~tramp ~expr) ;; ;; TrampMark implements the following protocols: ;; ;; PLoadTrampoline: ;; Returns a Tramp record with the given trampoline ;; function name and the same expression. ;; ;; PThunkify: ;; Applies thunkify to the enclosed expression and returns ;; the result in a new TrampMark record. Uses the walk-expr ;; function provided by PWalkable. ;; ;; PWalkable: ;; Applies the given function to the enclosed expression, ;; returning the result in a new TrampMark record. ;;---------------------------------------------------------------------- (ns ctco.expr.tramp (:require [ctco.protocol :as proto])) (defrecord Tramp [tramp expr] proto/PUnparse (unparse [this] `(~tramp ~(proto/unparse expr))) proto/PWalkable (walk-expr [this f _] (Tramp. (:tramp this) (f (:expr this))))) (defrecord TrampMark [expr] proto/PLoadTrampoline (load-tramp [this tramp] (Tramp. tramp expr)) proto/PRecurify (recurify [this name arity tail?] (proto/walk-expr this #(proto/recurify % name arity tail?) nil)) proto/PThunkify (thunkify [this] (proto/walk-expr this proto/thunkify nil)) ;; Not used in practice, but useful for debugging proto/PUnparse (unparse [this] (proto/unparse (:expr this))) proto/PWalkable (walk-expr [this f _] (TrampMark. (f (:expr this)))))
118280
;;---------------------------------------------------------------------- ;; File tramp.clj ;; Written by <NAME> ;; ;; Created 4 Oct 2012 ;; Last modified 20 Oct 2012 ;; ;; Defines the TrampMark record type for marking trampoline entry points ;; and the Tramp record type for marking those entry points with the ;; name of the trampoline function to used in the generated code. ;; ;; Tramp implements the following protocols: ;; ;; PUnparse: ;; Unparses (recursively) the expression as `(~tramp ~expr) ;; ;; TrampMark implements the following protocols: ;; ;; PLoadTrampoline: ;; Returns a Tramp record with the given trampoline ;; function name and the same expression. ;; ;; PThunkify: ;; Applies thunkify to the enclosed expression and returns ;; the result in a new TrampMark record. Uses the walk-expr ;; function provided by PWalkable. ;; ;; PWalkable: ;; Applies the given function to the enclosed expression, ;; returning the result in a new TrampMark record. ;;---------------------------------------------------------------------- (ns ctco.expr.tramp (:require [ctco.protocol :as proto])) (defrecord Tramp [tramp expr] proto/PUnparse (unparse [this] `(~tramp ~(proto/unparse expr))) proto/PWalkable (walk-expr [this f _] (Tramp. (:tramp this) (f (:expr this))))) (defrecord TrampMark [expr] proto/PLoadTrampoline (load-tramp [this tramp] (Tramp. tramp expr)) proto/PRecurify (recurify [this name arity tail?] (proto/walk-expr this #(proto/recurify % name arity tail?) nil)) proto/PThunkify (thunkify [this] (proto/walk-expr this proto/thunkify nil)) ;; Not used in practice, but useful for debugging proto/PUnparse (unparse [this] (proto/unparse (:expr this))) proto/PWalkable (walk-expr [this f _] (TrampMark. (f (:expr this)))))
true
;;---------------------------------------------------------------------- ;; File tramp.clj ;; Written by PI:NAME:<NAME>END_PI ;; ;; Created 4 Oct 2012 ;; Last modified 20 Oct 2012 ;; ;; Defines the TrampMark record type for marking trampoline entry points ;; and the Tramp record type for marking those entry points with the ;; name of the trampoline function to used in the generated code. ;; ;; Tramp implements the following protocols: ;; ;; PUnparse: ;; Unparses (recursively) the expression as `(~tramp ~expr) ;; ;; TrampMark implements the following protocols: ;; ;; PLoadTrampoline: ;; Returns a Tramp record with the given trampoline ;; function name and the same expression. ;; ;; PThunkify: ;; Applies thunkify to the enclosed expression and returns ;; the result in a new TrampMark record. Uses the walk-expr ;; function provided by PWalkable. ;; ;; PWalkable: ;; Applies the given function to the enclosed expression, ;; returning the result in a new TrampMark record. ;;---------------------------------------------------------------------- (ns ctco.expr.tramp (:require [ctco.protocol :as proto])) (defrecord Tramp [tramp expr] proto/PUnparse (unparse [this] `(~tramp ~(proto/unparse expr))) proto/PWalkable (walk-expr [this f _] (Tramp. (:tramp this) (f (:expr this))))) (defrecord TrampMark [expr] proto/PLoadTrampoline (load-tramp [this tramp] (Tramp. tramp expr)) proto/PRecurify (recurify [this name arity tail?] (proto/walk-expr this #(proto/recurify % name arity tail?) nil)) proto/PThunkify (thunkify [this] (proto/walk-expr this proto/thunkify nil)) ;; Not used in practice, but useful for debugging proto/PUnparse (unparse [this] (proto/unparse (:expr this))) proto/PWalkable (walk-expr [this f _] (TrampMark. (f (:expr this)))))
[ { "context": " (parse \"length > 3 AND height < 4.5 OR name = \\\"Pete\\\"\") \n {:left {:left {:comparison [:length :> ", "end": 741, "score": 0.9990580081939697, "start": 737, "tag": "NAME", "value": "Pete" }, { "context": " :op :OR\n :right {:comparison [:name := \"Pete\"]}}\n\n (parse \"length > 3 AND (height < 4.5 OR", "end": 924, "score": 0.9992810487747192, "start": 920, "tag": "NAME", "value": "Pete" }, { "context": " (parse \"length > 3 AND (height < 4.5 OR name = \\\"Pete\\\")\") \n {:left {:comparison [:length :> 3]}\n ", "end": 988, "score": 0.9975776672363281, "start": 984, "tag": "NAME", "value": "Pete" }, { "context": " :OR\n :right {:comparison [:name := \"Pete\"]}}})))\n\n(deftest test-mongo-eval\n (testing \"han", "end": 1173, "score": 0.9993442296981812, "start": 1169, "tag": "NAME", "value": "Pete" }, { "context": "andles LIKE comparisons\"\n (does-re-match\n \"Marc\" (:name (mongo-eval (parse \"name LIKE 'Mar%'\")))\n", "end": 1670, "score": 0.9877870678901672, "start": 1666, "tag": "NAME", "value": "Marc" }, { "context": " \"Marc\" (:name (mongo-eval (parse \"name LIKE 'Mar%'\")))\n \"Markus\" (:name (mongo-eval (parse \"na", "end": 1713, "score": 0.8818846940994263, "start": 1710, "tag": "NAME", "value": "Mar" }, { "context": "me (mongo-eval (parse \"name LIKE 'Mar%'\")))\n \"Markus\" (:name (mongo-eval (parse \"name LIKE 'Mar%'\")))\n", "end": 1732, "score": 0.9997249841690063, "start": 1726, "tag": "NAME", "value": "Markus" }, { "context": "me (mongo-eval (parse \"name LIKE 'Mar%'\")))\n \"Mar\" (:name (mongo-eval (parse \"name LIKE 'Mar%'\")))\n", "end": 1791, "score": 0.9938782453536987, "start": 1788, "tag": "NAME", "value": "Mar" }, { "context": "me (mongo-eval (parse \"name LIKE 'Mar%'\")))\n \"Clinton and Marc\" (:name (mongo-eval (parse \"name LIKE '%", "end": 1854, "score": 0.9987540245056152, "start": 1847, "tag": "NAME", "value": "Clinton" }, { "context": "val (parse \"name LIKE 'Mar%'\")))\n \"Clinton and Marc\" (:name (mongo-eval (parse \"name LIKE '%Mar%'\")))", "end": 1863, "score": 0.998869776725769, "start": 1859, "tag": "NAME", "value": "Marc" }, { "context": "e (mongo-eval (parse \"name LIKE '%Mar%'\")))\n \"Mick\" (:name (mongo-eval (parse \"name LIKE 'M__k'\")))\n", "end": 1924, "score": 0.9988474249839783, "start": 1920, "tag": "NAME", "value": "Mick" }, { "context": "me (mongo-eval (parse \"name LIKE 'M__k'\")))\n \"Mark\" (:name (mongo-eval (parse \"name LIKE 'M__k'\")))\n", "end": 1984, "score": 0.9992994666099548, "start": 1980, "tag": "NAME", "value": "Mark" }, { "context": "go-eval (parse \"name ILIKE 'aye%ay%'\")))\n \"jerboa ears\" (:name (mongo-eval (parse \"name ILIKE 'JERB", "end": 2498, "score": 0.6400562524795532, "start": 2495, "tag": "NAME", "value": "boa" }, { "context": "al (parse \"name ILIKE 'aye%ay%'\")))\n \"jerboa ears\" (:name (mongo-eval (parse \"name ILIKE 'JERB%'\"))", "end": 2503, "score": 0.591772198677063, "start": 2500, "tag": "NAME", "value": "ars" }, { "context": "ength > 3 OR height = 4.5 OR width < 2 OR name = 'Pete'\"))\n {:$or [{:length {:$gt 3}} {:height 4.5} ", "end": 3391, "score": 0.9861104488372803, "start": 3387, "tag": "NAME", "value": "Pete" }, { "context": "{:$gt 3}} {:height 4.5} {:width {:$lt 2}} {:name \"Pete\"}]}\n\n (mongo-eval (parse \"length > 3 AND (hei", "end": 3471, "score": 0.9857217073440552, "start": 3467, "tag": "NAME", "value": "Pete" }, { "context": " (parse \"length > 3 AND (height < 4.5 OR name = \\\"Pete\\\" OR width < 2)\"))\n {:$and [{:length {:$gt 3}", "end": 3547, "score": 0.9896453619003296, "start": 3543, "tag": "NAME", "value": "Pete" }, { "context": ":height {:$lt 4.5}}\n {:name \"Pete\"}\n {:width {:$lt 2}}]}]}))\n\n", "end": 3675, "score": 0.9946275949478149, "start": 3671, "tag": "NAME", "value": "Pete" }, { "context": "s\"\n (does=\n (mongo-eval (parse \"name IN (\\\"Pete\\\", \\\"Sam\\\")\"))\n {:name {:$in [\"Pete\" \"Sam\"]}}", "end": 3812, "score": 0.9980412721633911, "start": 3808, "tag": "NAME", "value": "Pete" }, { "context": "es=\n (mongo-eval (parse \"name IN (\\\"Pete\\\", \\\"Sam\\\")\"))\n {:name {:$in [\"Pete\" \"Sam\"]}}))\n\n (te", "end": 3821, "score": 0.9990562796592712, "start": 3818, "tag": "NAME", "value": "Sam" }, { "context": "ame IN (\\\"Pete\\\", \\\"Sam\\\")\"))\n {:name {:$in [\"Pete\" \"Sam\"]}}))\n\n (testing \"handles simple compariso", "end": 3852, "score": 0.9979435205459595, "start": 3848, "tag": "NAME", "value": "Pete" }, { "context": "(\\\"Pete\\\", \\\"Sam\\\")\"))\n {:name {:$in [\"Pete\" \"Sam\"]}}))\n\n (testing \"handles simple comparisons wit", "end": 3858, "score": 0.999057948589325, "start": 3855, "tag": "NAME", "value": "Sam" }, { "context": "\n (does=\n (mongo-eval (parse \"NOT name = \\\"Pete\\\"\"))\n {:name {:$ne \"Pete\"}}\n\n (mongo-eval", "end": 3968, "score": 0.9938273429870605, "start": 3964, "tag": "NAME", "value": "Pete" }, { "context": "(parse \"NOT name = \\\"Pete\\\"\"))\n {:name {:$ne \"Pete\"}}\n\n (mongo-eval (parse \"NOT name != \\\"Pete\\\"", "end": 3997, "score": 0.9974230527877808, "start": 3993, "tag": "NAME", "value": "Pete" }, { "context": " \"Pete\"}}\n\n (mongo-eval (parse \"NOT name != \\\"Pete\\\"\"))\n {:name \"Pete\"}\n\n (mongo-eval (parse", "end": 4045, "score": 0.9969857335090637, "start": 4041, "tag": "NAME", "value": "Pete" }, { "context": "eval (parse \"NOT name != \\\"Pete\\\"\"))\n {:name \"Pete\"}\n\n (mongo-eval (parse \"NOT length < 3\"))\n ", "end": 4068, "score": 0.9957594275474548, "start": 4064, "tag": "NAME", "value": "Pete" }, { "context": "OT (length > 3 AND NOT (height > 4.5 AND name = \\\"Pete\\\"))\"))\n {:$or [{:length {:$not {:$gt 3}}}\n ", "end": 5366, "score": 0.9102325439453125, "start": 5362, "tag": "NAME", "value": "Pete" }, { "context": ":height {:$gt 4.5}}\n {:name \"Pete\"}]}]})))\n\n\n;; (run-tests)\n", "end": 5489, "score": 0.9373759031295776, "start": 5485, "tag": "NAME", "value": "Pete" } ]
test/qu/test/query/where.clj
marcesher/qu
325
(ns qu.test.query.where (:require [clojure.test :refer :all] [qu.test-util :refer :all] [protoflex.parse :as p] [qu.query.where :refer [parse mongo-eval]]) (:import (java.util.regex Pattern))) (deftest test-parse (testing "can parse simple comparisons" (does= (parse "length > 3") {:comparison [:length :> 3]} (parse "name IS NULL") {:comparison [:name := nil]} (parse "name IS NOT NULL") {:comparison [:name :!= nil]})) (testing "can parse complex comparisons" (does= (parse "length > 3 AND height < 4.5") {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}} (parse "length > 3 AND height < 4.5 OR name = \"Pete\"") {:left {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}} :op :OR :right {:comparison [:name := "Pete"]}} (parse "length > 3 AND (height < 4.5 OR name = \"Pete\")") {:left {:comparison [:length :> 3]} :op :AND :right {:left {:comparison [:height :< 4.5]} :op :OR :right {:comparison [:name := "Pete"]}}}))) (deftest test-mongo-eval (testing "handles equality correctly" (is (= (mongo-eval (parse "length = 3")) {:length 3}))) (testing "handles non-equality comparisons" (does= (mongo-eval (parse "length < 3")) {:length {:$lt 3}} (mongo-eval (parse "length >= 3")) {:length {:$gte 3}})) (testing "handles booleans in comparisons" (does= (mongo-eval (parse "exempt = TRUE")) {:exempt true})) (testing "handles LIKE comparisons" (does-re-match "Marc" (:name (mongo-eval (parse "name LIKE 'Mar%'"))) "Markus" (:name (mongo-eval (parse "name LIKE 'Mar%'"))) "Mar" (:name (mongo-eval (parse "name LIKE 'Mar%'"))) "Clinton and Marc" (:name (mongo-eval (parse "name LIKE '%Mar%'"))) "Mick" (:name (mongo-eval (parse "name LIKE 'M__k'"))) "Mark" (:name (mongo-eval (parse "name LIKE 'M__k'"))) ".M" (:name (mongo-eval (parse "name LIKE '._'")))) (does-not-re-match "CMark" (:name (mongo-eval (parse "name LIKE 'Mar%'"))) "Mak" (:name (mongo-eval (parse "name LIKE 'M__k'"))) "CM" (:name (mongo-eval (parse "name LIKE '._'"))))) (testing "handles ILIKE comparisons" (does-re-match "Blob fish" (:name (mongo-eval (parse "name ILIKE 'blob%'"))) "AYE AYE" (:name (mongo-eval (parse "name ILIKE 'aye%ay%'"))) "jerboa ears" (:name (mongo-eval (parse "name ILIKE 'JERB%'"))) "greater pangolin is great" (:name (mongo-eval (parse "name ILIKE '%P_ng_lin%'"))) "D. melanogaster" (:name (mongo-eval (parse "name ILIKE 'D.%Melan%'")))) (does-not-re-match "goeduck clam" (:name (mongo-eval (parse "name ILIKE 'GEODUCK clam'"))) "geoduck clam" (:name (mongo-eval (parse "name ILIKE 'G._DUCK clam'"))))) (testing "handles complex comparisons" (does= (mongo-eval (parse "length > 3 AND height = 4.5")) {:$and [ {:length {:$gt 3}} {:height 4.5}]} (mongo-eval (parse "length > 3 OR height = 4.5")) {:$or [{:length {:$gt 3}} {:height 4.5}]} (mongo-eval (parse "length > 3 OR height = 4.5 OR width < 2")) {:$or [{:length {:$gt 3}} {:height 4.5} {:width {:$lt 2}}]} (mongo-eval (parse "length > 3 OR height = 4.5 OR width < 2 OR name = 'Pete'")) {:$or [{:length {:$gt 3}} {:height 4.5} {:width {:$lt 2}} {:name "Pete"}]} (mongo-eval (parse "length > 3 AND (height < 4.5 OR name = \"Pete\" OR width < 2)")) {:$and [{:length {:$gt 3}} {:$or [{:height {:$lt 4.5}} {:name "Pete"} {:width {:$lt 2}}]}]})) (testing "handles IN comparisons" (does= (mongo-eval (parse "name IN (\"Pete\", \"Sam\")")) {:name {:$in ["Pete" "Sam"]}})) (testing "handles simple comparisons with NOT" (does= (mongo-eval (parse "NOT name = \"Pete\"")) {:name {:$ne "Pete"}} (mongo-eval (parse "NOT name != \"Pete\"")) {:name "Pete"} (mongo-eval (parse "NOT length < 3")) {:length {:$not {:$lt 3}}})) (testing "handles complex comparisons with NOT and AND" (does= (mongo-eval (parse "NOT (length > 3 AND height = 4.5)")) {:$or [{:length {:$not {:$gt 3}}} {:height {:$ne 4.5}}]} (mongo-eval (parse "NOT (length > 3 AND height = 4.5 AND width < 2)")) {:$or [{:length {:$not {:$gt 3}}} {:height {:$ne 4.5}} {:width {:$not {:$lt 2}}}]})) (testing "uses $nor on complex comparisons with NOT and OR" (does= (mongo-eval (parse "NOT (length > 3 OR height = 4.5)")) {:$nor [{:length {:$gt 3}} {:height 4.5}]} (mongo-eval (parse "NOT (length > 3 OR height = 4.5 OR width < 2)")) {:$nor [{:length {:$gt 3}} {:height 4.5} {:width {:$lt 2}}]})) (testing "NOT binds tighter than AND" (does= (mongo-eval (parse "NOT length > 3 AND height = 4.5")) {:$and [{:length {:$not {:$gt 3}}} {:height 4.5}]})) (testing "handles nested comparisons with multiple NOTs" (does= (mongo-eval (parse "NOT (length > 3 OR NOT (height > 4.5 AND name IS NOT NULL))")) {:$nor [{:length {:$gt 3}} {:$or [{:height {:$not {:$gt 4.5}}} {:name nil}]}]} (mongo-eval (parse "NOT (length > 3 AND NOT (height > 4.5 AND name = \"Pete\"))")) {:$or [{:length {:$not {:$gt 3}}} {:$and [{:height {:$gt 4.5}} {:name "Pete"}]}]}))) ;; (run-tests)
47261
(ns qu.test.query.where (:require [clojure.test :refer :all] [qu.test-util :refer :all] [protoflex.parse :as p] [qu.query.where :refer [parse mongo-eval]]) (:import (java.util.regex Pattern))) (deftest test-parse (testing "can parse simple comparisons" (does= (parse "length > 3") {:comparison [:length :> 3]} (parse "name IS NULL") {:comparison [:name := nil]} (parse "name IS NOT NULL") {:comparison [:name :!= nil]})) (testing "can parse complex comparisons" (does= (parse "length > 3 AND height < 4.5") {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}} (parse "length > 3 AND height < 4.5 OR name = \"<NAME>\"") {:left {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}} :op :OR :right {:comparison [:name := "<NAME>"]}} (parse "length > 3 AND (height < 4.5 OR name = \"<NAME>\")") {:left {:comparison [:length :> 3]} :op :AND :right {:left {:comparison [:height :< 4.5]} :op :OR :right {:comparison [:name := "<NAME>"]}}}))) (deftest test-mongo-eval (testing "handles equality correctly" (is (= (mongo-eval (parse "length = 3")) {:length 3}))) (testing "handles non-equality comparisons" (does= (mongo-eval (parse "length < 3")) {:length {:$lt 3}} (mongo-eval (parse "length >= 3")) {:length {:$gte 3}})) (testing "handles booleans in comparisons" (does= (mongo-eval (parse "exempt = TRUE")) {:exempt true})) (testing "handles LIKE comparisons" (does-re-match "<NAME>" (:name (mongo-eval (parse "name LIKE '<NAME>%'"))) "<NAME>" (:name (mongo-eval (parse "name LIKE 'Mar%'"))) "<NAME>" (:name (mongo-eval (parse "name LIKE 'Mar%'"))) "<NAME> and <NAME>" (:name (mongo-eval (parse "name LIKE '%Mar%'"))) "<NAME>" (:name (mongo-eval (parse "name LIKE 'M__k'"))) "<NAME>" (:name (mongo-eval (parse "name LIKE 'M__k'"))) ".M" (:name (mongo-eval (parse "name LIKE '._'")))) (does-not-re-match "CMark" (:name (mongo-eval (parse "name LIKE 'Mar%'"))) "Mak" (:name (mongo-eval (parse "name LIKE 'M__k'"))) "CM" (:name (mongo-eval (parse "name LIKE '._'"))))) (testing "handles ILIKE comparisons" (does-re-match "Blob fish" (:name (mongo-eval (parse "name ILIKE 'blob%'"))) "AYE AYE" (:name (mongo-eval (parse "name ILIKE 'aye%ay%'"))) "jer<NAME> e<NAME>" (:name (mongo-eval (parse "name ILIKE 'JERB%'"))) "greater pangolin is great" (:name (mongo-eval (parse "name ILIKE '%P_ng_lin%'"))) "D. melanogaster" (:name (mongo-eval (parse "name ILIKE 'D.%Melan%'")))) (does-not-re-match "goeduck clam" (:name (mongo-eval (parse "name ILIKE 'GEODUCK clam'"))) "geoduck clam" (:name (mongo-eval (parse "name ILIKE 'G._DUCK clam'"))))) (testing "handles complex comparisons" (does= (mongo-eval (parse "length > 3 AND height = 4.5")) {:$and [ {:length {:$gt 3}} {:height 4.5}]} (mongo-eval (parse "length > 3 OR height = 4.5")) {:$or [{:length {:$gt 3}} {:height 4.5}]} (mongo-eval (parse "length > 3 OR height = 4.5 OR width < 2")) {:$or [{:length {:$gt 3}} {:height 4.5} {:width {:$lt 2}}]} (mongo-eval (parse "length > 3 OR height = 4.5 OR width < 2 OR name = '<NAME>'")) {:$or [{:length {:$gt 3}} {:height 4.5} {:width {:$lt 2}} {:name "<NAME>"}]} (mongo-eval (parse "length > 3 AND (height < 4.5 OR name = \"<NAME>\" OR width < 2)")) {:$and [{:length {:$gt 3}} {:$or [{:height {:$lt 4.5}} {:name "<NAME>"} {:width {:$lt 2}}]}]})) (testing "handles IN comparisons" (does= (mongo-eval (parse "name IN (\"<NAME>\", \"<NAME>\")")) {:name {:$in ["<NAME>" "<NAME>"]}})) (testing "handles simple comparisons with NOT" (does= (mongo-eval (parse "NOT name = \"<NAME>\"")) {:name {:$ne "<NAME>"}} (mongo-eval (parse "NOT name != \"<NAME>\"")) {:name "<NAME>"} (mongo-eval (parse "NOT length < 3")) {:length {:$not {:$lt 3}}})) (testing "handles complex comparisons with NOT and AND" (does= (mongo-eval (parse "NOT (length > 3 AND height = 4.5)")) {:$or [{:length {:$not {:$gt 3}}} {:height {:$ne 4.5}}]} (mongo-eval (parse "NOT (length > 3 AND height = 4.5 AND width < 2)")) {:$or [{:length {:$not {:$gt 3}}} {:height {:$ne 4.5}} {:width {:$not {:$lt 2}}}]})) (testing "uses $nor on complex comparisons with NOT and OR" (does= (mongo-eval (parse "NOT (length > 3 OR height = 4.5)")) {:$nor [{:length {:$gt 3}} {:height 4.5}]} (mongo-eval (parse "NOT (length > 3 OR height = 4.5 OR width < 2)")) {:$nor [{:length {:$gt 3}} {:height 4.5} {:width {:$lt 2}}]})) (testing "NOT binds tighter than AND" (does= (mongo-eval (parse "NOT length > 3 AND height = 4.5")) {:$and [{:length {:$not {:$gt 3}}} {:height 4.5}]})) (testing "handles nested comparisons with multiple NOTs" (does= (mongo-eval (parse "NOT (length > 3 OR NOT (height > 4.5 AND name IS NOT NULL))")) {:$nor [{:length {:$gt 3}} {:$or [{:height {:$not {:$gt 4.5}}} {:name nil}]}]} (mongo-eval (parse "NOT (length > 3 AND NOT (height > 4.5 AND name = \"<NAME>\"))")) {:$or [{:length {:$not {:$gt 3}}} {:$and [{:height {:$gt 4.5}} {:name "<NAME>"}]}]}))) ;; (run-tests)
true
(ns qu.test.query.where (:require [clojure.test :refer :all] [qu.test-util :refer :all] [protoflex.parse :as p] [qu.query.where :refer [parse mongo-eval]]) (:import (java.util.regex Pattern))) (deftest test-parse (testing "can parse simple comparisons" (does= (parse "length > 3") {:comparison [:length :> 3]} (parse "name IS NULL") {:comparison [:name := nil]} (parse "name IS NOT NULL") {:comparison [:name :!= nil]})) (testing "can parse complex comparisons" (does= (parse "length > 3 AND height < 4.5") {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}} (parse "length > 3 AND height < 4.5 OR name = \"PI:NAME:<NAME>END_PI\"") {:left {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}} :op :OR :right {:comparison [:name := "PI:NAME:<NAME>END_PI"]}} (parse "length > 3 AND (height < 4.5 OR name = \"PI:NAME:<NAME>END_PI\")") {:left {:comparison [:length :> 3]} :op :AND :right {:left {:comparison [:height :< 4.5]} :op :OR :right {:comparison [:name := "PI:NAME:<NAME>END_PI"]}}}))) (deftest test-mongo-eval (testing "handles equality correctly" (is (= (mongo-eval (parse "length = 3")) {:length 3}))) (testing "handles non-equality comparisons" (does= (mongo-eval (parse "length < 3")) {:length {:$lt 3}} (mongo-eval (parse "length >= 3")) {:length {:$gte 3}})) (testing "handles booleans in comparisons" (does= (mongo-eval (parse "exempt = TRUE")) {:exempt true})) (testing "handles LIKE comparisons" (does-re-match "PI:NAME:<NAME>END_PI" (:name (mongo-eval (parse "name LIKE 'PI:NAME:<NAME>END_PI%'"))) "PI:NAME:<NAME>END_PI" (:name (mongo-eval (parse "name LIKE 'Mar%'"))) "PI:NAME:<NAME>END_PI" (:name (mongo-eval (parse "name LIKE 'Mar%'"))) "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI" (:name (mongo-eval (parse "name LIKE '%Mar%'"))) "PI:NAME:<NAME>END_PI" (:name (mongo-eval (parse "name LIKE 'M__k'"))) "PI:NAME:<NAME>END_PI" (:name (mongo-eval (parse "name LIKE 'M__k'"))) ".M" (:name (mongo-eval (parse "name LIKE '._'")))) (does-not-re-match "CMark" (:name (mongo-eval (parse "name LIKE 'Mar%'"))) "Mak" (:name (mongo-eval (parse "name LIKE 'M__k'"))) "CM" (:name (mongo-eval (parse "name LIKE '._'"))))) (testing "handles ILIKE comparisons" (does-re-match "Blob fish" (:name (mongo-eval (parse "name ILIKE 'blob%'"))) "AYE AYE" (:name (mongo-eval (parse "name ILIKE 'aye%ay%'"))) "jerPI:NAME:<NAME>END_PI ePI:NAME:<NAME>END_PI" (:name (mongo-eval (parse "name ILIKE 'JERB%'"))) "greater pangolin is great" (:name (mongo-eval (parse "name ILIKE '%P_ng_lin%'"))) "D. melanogaster" (:name (mongo-eval (parse "name ILIKE 'D.%Melan%'")))) (does-not-re-match "goeduck clam" (:name (mongo-eval (parse "name ILIKE 'GEODUCK clam'"))) "geoduck clam" (:name (mongo-eval (parse "name ILIKE 'G._DUCK clam'"))))) (testing "handles complex comparisons" (does= (mongo-eval (parse "length > 3 AND height = 4.5")) {:$and [ {:length {:$gt 3}} {:height 4.5}]} (mongo-eval (parse "length > 3 OR height = 4.5")) {:$or [{:length {:$gt 3}} {:height 4.5}]} (mongo-eval (parse "length > 3 OR height = 4.5 OR width < 2")) {:$or [{:length {:$gt 3}} {:height 4.5} {:width {:$lt 2}}]} (mongo-eval (parse "length > 3 OR height = 4.5 OR width < 2 OR name = 'PI:NAME:<NAME>END_PI'")) {:$or [{:length {:$gt 3}} {:height 4.5} {:width {:$lt 2}} {:name "PI:NAME:<NAME>END_PI"}]} (mongo-eval (parse "length > 3 AND (height < 4.5 OR name = \"PI:NAME:<NAME>END_PI\" OR width < 2)")) {:$and [{:length {:$gt 3}} {:$or [{:height {:$lt 4.5}} {:name "PI:NAME:<NAME>END_PI"} {:width {:$lt 2}}]}]})) (testing "handles IN comparisons" (does= (mongo-eval (parse "name IN (\"PI:NAME:<NAME>END_PI\", \"PI:NAME:<NAME>END_PI\")")) {:name {:$in ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]}})) (testing "handles simple comparisons with NOT" (does= (mongo-eval (parse "NOT name = \"PI:NAME:<NAME>END_PI\"")) {:name {:$ne "PI:NAME:<NAME>END_PI"}} (mongo-eval (parse "NOT name != \"PI:NAME:<NAME>END_PI\"")) {:name "PI:NAME:<NAME>END_PI"} (mongo-eval (parse "NOT length < 3")) {:length {:$not {:$lt 3}}})) (testing "handles complex comparisons with NOT and AND" (does= (mongo-eval (parse "NOT (length > 3 AND height = 4.5)")) {:$or [{:length {:$not {:$gt 3}}} {:height {:$ne 4.5}}]} (mongo-eval (parse "NOT (length > 3 AND height = 4.5 AND width < 2)")) {:$or [{:length {:$not {:$gt 3}}} {:height {:$ne 4.5}} {:width {:$not {:$lt 2}}}]})) (testing "uses $nor on complex comparisons with NOT and OR" (does= (mongo-eval (parse "NOT (length > 3 OR height = 4.5)")) {:$nor [{:length {:$gt 3}} {:height 4.5}]} (mongo-eval (parse "NOT (length > 3 OR height = 4.5 OR width < 2)")) {:$nor [{:length {:$gt 3}} {:height 4.5} {:width {:$lt 2}}]})) (testing "NOT binds tighter than AND" (does= (mongo-eval (parse "NOT length > 3 AND height = 4.5")) {:$and [{:length {:$not {:$gt 3}}} {:height 4.5}]})) (testing "handles nested comparisons with multiple NOTs" (does= (mongo-eval (parse "NOT (length > 3 OR NOT (height > 4.5 AND name IS NOT NULL))")) {:$nor [{:length {:$gt 3}} {:$or [{:height {:$not {:$gt 4.5}}} {:name nil}]}]} (mongo-eval (parse "NOT (length > 3 AND NOT (height > 4.5 AND name = \"PI:NAME:<NAME>END_PI\"))")) {:$or [{:length {:$not {:$gt 3}}} {:$and [{:height {:$gt 4.5}} {:name "PI:NAME:<NAME>END_PI"}]}]}))) ;; (run-tests)
[ { "context": "key \"key\"\n :secret \"secret\"}\n bucket \"bucket\"\n obj-nam", "end": 445, "score": 0.5801390409469604, "start": 439, "tag": "KEY", "value": "secret" } ]
code/test/sixsq/nuvla/server/resources/data/utils_test.clj
nuvla/server
6
(ns sixsq.nuvla.server.resources.data.utils-test (:require [clojure.string :as str] [clojure.test :refer [deftest is]] [sixsq.nuvla.server.resources.data.utils :as u]) (:import (com.amazonaws AmazonServiceException))) (deftest test-generate-url (let [os-host "s3.cloud.com" obj-store-conf {:endpoint (str "https://" os-host) :key "key" :secret "secret"} bucket "bucket" obj-name "object/name" verb :put] (is (str/starts-with? (u/generate-url obj-store-conf bucket obj-name verb) (format "https://%s/%s/%s?" os-host bucket obj-name))))) (deftest add-size-or-md5sum (with-redefs [u/get-s3-client (fn [_] nil)] (with-redefs [u/s3-object-metadata (fn [_ _ _] {:contentLength 1, :contentMD5 "aaa"})] (is (= {:bytes 1} (u/add-s3-bytes {}))) (is (= {:bytes 1} (u/add-s3-bytes nil))) (is (= {:bytes 1} (u/add-s3-bytes {:bytes 99}))) (is (= {:md5sum "aaa"} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue" :bytes 1 :md5sum "aaa"} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum))))) (with-redefs [u/s3-object-metadata (fn [_ _ _] {:contentLength 2, :contentMD5 nil})] (is (= {:bytes 2} (u/add-s3-bytes {}))) (is (= {:bytes 2} (u/add-s3-bytes nil))) (is (= {:bytes 2} (u/add-s3-bytes {:bytes 99}))) (is (= {} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue" :bytes 2} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum))))) (with-redefs [u/s3-object-metadata (fn [_ _ _] {:contentLength nil, :contentMD5 nil})] (is (= {} (u/add-s3-bytes {}))) (is (= nil (u/add-s3-bytes nil))) (is (= {:bytes 99} (u/add-s3-bytes {:bytes 99}))) (is (= {} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue"} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum))))) (with-redefs [u/s3-object-metadata (fn [_ _ _] nil)] (is (= {} (u/add-s3-bytes {}))) (is (= nil (u/add-s3-bytes nil))) (is (= {:bytes 99} (u/add-s3-bytes {:bytes 99}))) (is (= {} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue"} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum))))) (with-redefs [u/s3-object-metadata (fn [_ _ _] (let [ex (doto (AmazonServiceException. "Simulated AWS Exception for S3 permission error") (.setStatusCode 403))] (throw ex)))] (is (= {} (u/add-s3-bytes {}))) (is (= nil (u/add-s3-bytes nil))) (is (= {:bytes 99} (u/add-s3-bytes {:bytes 99}))) (is (= {} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue"} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum)))))))
68216
(ns sixsq.nuvla.server.resources.data.utils-test (:require [clojure.string :as str] [clojure.test :refer [deftest is]] [sixsq.nuvla.server.resources.data.utils :as u]) (:import (com.amazonaws AmazonServiceException))) (deftest test-generate-url (let [os-host "s3.cloud.com" obj-store-conf {:endpoint (str "https://" os-host) :key "key" :secret "<KEY>"} bucket "bucket" obj-name "object/name" verb :put] (is (str/starts-with? (u/generate-url obj-store-conf bucket obj-name verb) (format "https://%s/%s/%s?" os-host bucket obj-name))))) (deftest add-size-or-md5sum (with-redefs [u/get-s3-client (fn [_] nil)] (with-redefs [u/s3-object-metadata (fn [_ _ _] {:contentLength 1, :contentMD5 "aaa"})] (is (= {:bytes 1} (u/add-s3-bytes {}))) (is (= {:bytes 1} (u/add-s3-bytes nil))) (is (= {:bytes 1} (u/add-s3-bytes {:bytes 99}))) (is (= {:md5sum "aaa"} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue" :bytes 1 :md5sum "aaa"} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum))))) (with-redefs [u/s3-object-metadata (fn [_ _ _] {:contentLength 2, :contentMD5 nil})] (is (= {:bytes 2} (u/add-s3-bytes {}))) (is (= {:bytes 2} (u/add-s3-bytes nil))) (is (= {:bytes 2} (u/add-s3-bytes {:bytes 99}))) (is (= {} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue" :bytes 2} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum))))) (with-redefs [u/s3-object-metadata (fn [_ _ _] {:contentLength nil, :contentMD5 nil})] (is (= {} (u/add-s3-bytes {}))) (is (= nil (u/add-s3-bytes nil))) (is (= {:bytes 99} (u/add-s3-bytes {:bytes 99}))) (is (= {} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue"} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum))))) (with-redefs [u/s3-object-metadata (fn [_ _ _] nil)] (is (= {} (u/add-s3-bytes {}))) (is (= nil (u/add-s3-bytes nil))) (is (= {:bytes 99} (u/add-s3-bytes {:bytes 99}))) (is (= {} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue"} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum))))) (with-redefs [u/s3-object-metadata (fn [_ _ _] (let [ex (doto (AmazonServiceException. "Simulated AWS Exception for S3 permission error") (.setStatusCode 403))] (throw ex)))] (is (= {} (u/add-s3-bytes {}))) (is (= nil (u/add-s3-bytes nil))) (is (= {:bytes 99} (u/add-s3-bytes {:bytes 99}))) (is (= {} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue"} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum)))))))
true
(ns sixsq.nuvla.server.resources.data.utils-test (:require [clojure.string :as str] [clojure.test :refer [deftest is]] [sixsq.nuvla.server.resources.data.utils :as u]) (:import (com.amazonaws AmazonServiceException))) (deftest test-generate-url (let [os-host "s3.cloud.com" obj-store-conf {:endpoint (str "https://" os-host) :key "key" :secret "PI:KEY:<KEY>END_PI"} bucket "bucket" obj-name "object/name" verb :put] (is (str/starts-with? (u/generate-url obj-store-conf bucket obj-name verb) (format "https://%s/%s/%s?" os-host bucket obj-name))))) (deftest add-size-or-md5sum (with-redefs [u/get-s3-client (fn [_] nil)] (with-redefs [u/s3-object-metadata (fn [_ _ _] {:contentLength 1, :contentMD5 "aaa"})] (is (= {:bytes 1} (u/add-s3-bytes {}))) (is (= {:bytes 1} (u/add-s3-bytes nil))) (is (= {:bytes 1} (u/add-s3-bytes {:bytes 99}))) (is (= {:md5sum "aaa"} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue" :bytes 1 :md5sum "aaa"} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum))))) (with-redefs [u/s3-object-metadata (fn [_ _ _] {:contentLength 2, :contentMD5 nil})] (is (= {:bytes 2} (u/add-s3-bytes {}))) (is (= {:bytes 2} (u/add-s3-bytes nil))) (is (= {:bytes 2} (u/add-s3-bytes {:bytes 99}))) (is (= {} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue" :bytes 2} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum))))) (with-redefs [u/s3-object-metadata (fn [_ _ _] {:contentLength nil, :contentMD5 nil})] (is (= {} (u/add-s3-bytes {}))) (is (= nil (u/add-s3-bytes nil))) (is (= {:bytes 99} (u/add-s3-bytes {:bytes 99}))) (is (= {} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue"} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum))))) (with-redefs [u/s3-object-metadata (fn [_ _ _] nil)] (is (= {} (u/add-s3-bytes {}))) (is (= nil (u/add-s3-bytes nil))) (is (= {:bytes 99} (u/add-s3-bytes {:bytes 99}))) (is (= {} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue"} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum))))) (with-redefs [u/s3-object-metadata (fn [_ _ _] (let [ex (doto (AmazonServiceException. "Simulated AWS Exception for S3 permission error") (.setStatusCode 403))] (throw ex)))] (is (= {} (u/add-s3-bytes {}))) (is (= nil (u/add-s3-bytes nil))) (is (= {:bytes 99} (u/add-s3-bytes {:bytes 99}))) (is (= {} (u/add-s3-md5sum {}))) (is (= {:myKey "myvalue"} (-> {:myKey "myvalue"} (u/add-s3-bytes) (u/add-s3-md5sum)))))))
[ { "context": ";; Copyright (c) 2015-2017 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redi", "end": 40, "score": 0.9998806118965149, "start": 27, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright (c) 2015-2017 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redistribution and", "end": 54, "score": 0.9999327063560486, "start": 42, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
src/clojure/catacumba/impl/sse.clj
source-c/catacumba
212
;; Copyright (c) 2015-2017 Andrey Antukh <niwi@niwi.nz> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, this ;; list of conditions and the following disclaimer. ;; ;; * Redistributions in binary form must reproduce the above copyright notice, ;; this list of conditions and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns catacumba.impl.sse "Server-Sent Events handler adapter implementation." (:require [clojure.core.async :as a] [catacumba.impl.streams :as streams] [catacumba.impl.helpers :as hp] [catacumba.impl.context :as ctx] [catacumba.impl.executor :as exec] [catacumba.impl.handlers :as handlers]) (:import ratpack.handling.Handler ratpack.handling.Context ratpack.http.Response ratpack.func.Action io.netty.buffer.ByteBufAllocator org.reactivestreams.Publisher org.reactivestreams.Subscriber org.reactivestreams.Subscription)) (deftype Event [id event data] Object (toString [_] (with-out-str (when id (println "id:" id)) (when event (println "event:" event)) (when data (println "data:" data)) (println)))) (defprotocol IEventFactory (-make-event [_] "coerce to new event instance")) (extend-protocol IEventFactory String (-make-event [data] (Event. nil nil data)) Long (-make-event [d] (-make-event (str d))) Event (-make-event [event] event) clojure.lang.IPersistentMap (-make-event [data] (let [{:keys [id event data]} data] (when (and (not id) (not event) (not data)) (throw (ex-info "You must supply at least one of data, event, id" {}))) (Event. id event data)))) (defn sse "Start the sse connection with the client and dispatch it in a special hanlder." [context handler] (let [^Context ctx (:catacumba/context context) ^Response response (:catacumba/response context) xform (comp (map -make-event) (map str) (map hp/bytebuffer)) out (a/chan 1 xform) ctrl (a/chan (a/sliding-buffer 1)) dispose (fn [] (a/put! ctrl [:close nil]) (a/close! ctrl)) stream (streams/channel->publisher out dispose) headers {:content-type "text/event-stream;charset=UTF-8" :transfer-encoding "chunked" :cache-control "no-cache, no-store, max-age=0, must-revalidate" :pragma "no-cache"}] (handler (assoc context :out out :ctrl ctrl)) (ctx/set-headers! response headers) (.sendStream response (streams/bind-exec stream)))) (defmethod handlers/adapter :catacumba/sse [handler] (reify Handler (^void handle [_ ^Context ctx] (let [context (ctx/create-context ctx)] (sse context handler)))))
76527
;; Copyright (c) 2015-2017 <NAME> <<EMAIL>> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, this ;; list of conditions and the following disclaimer. ;; ;; * Redistributions in binary form must reproduce the above copyright notice, ;; this list of conditions and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns catacumba.impl.sse "Server-Sent Events handler adapter implementation." (:require [clojure.core.async :as a] [catacumba.impl.streams :as streams] [catacumba.impl.helpers :as hp] [catacumba.impl.context :as ctx] [catacumba.impl.executor :as exec] [catacumba.impl.handlers :as handlers]) (:import ratpack.handling.Handler ratpack.handling.Context ratpack.http.Response ratpack.func.Action io.netty.buffer.ByteBufAllocator org.reactivestreams.Publisher org.reactivestreams.Subscriber org.reactivestreams.Subscription)) (deftype Event [id event data] Object (toString [_] (with-out-str (when id (println "id:" id)) (when event (println "event:" event)) (when data (println "data:" data)) (println)))) (defprotocol IEventFactory (-make-event [_] "coerce to new event instance")) (extend-protocol IEventFactory String (-make-event [data] (Event. nil nil data)) Long (-make-event [d] (-make-event (str d))) Event (-make-event [event] event) clojure.lang.IPersistentMap (-make-event [data] (let [{:keys [id event data]} data] (when (and (not id) (not event) (not data)) (throw (ex-info "You must supply at least one of data, event, id" {}))) (Event. id event data)))) (defn sse "Start the sse connection with the client and dispatch it in a special hanlder." [context handler] (let [^Context ctx (:catacumba/context context) ^Response response (:catacumba/response context) xform (comp (map -make-event) (map str) (map hp/bytebuffer)) out (a/chan 1 xform) ctrl (a/chan (a/sliding-buffer 1)) dispose (fn [] (a/put! ctrl [:close nil]) (a/close! ctrl)) stream (streams/channel->publisher out dispose) headers {:content-type "text/event-stream;charset=UTF-8" :transfer-encoding "chunked" :cache-control "no-cache, no-store, max-age=0, must-revalidate" :pragma "no-cache"}] (handler (assoc context :out out :ctrl ctrl)) (ctx/set-headers! response headers) (.sendStream response (streams/bind-exec stream)))) (defmethod handlers/adapter :catacumba/sse [handler] (reify Handler (^void handle [_ ^Context ctx] (let [context (ctx/create-context ctx)] (sse context handler)))))
true
;; Copyright (c) 2015-2017 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, this ;; list of conditions and the following disclaimer. ;; ;; * Redistributions in binary form must reproduce the above copyright notice, ;; this list of conditions and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns catacumba.impl.sse "Server-Sent Events handler adapter implementation." (:require [clojure.core.async :as a] [catacumba.impl.streams :as streams] [catacumba.impl.helpers :as hp] [catacumba.impl.context :as ctx] [catacumba.impl.executor :as exec] [catacumba.impl.handlers :as handlers]) (:import ratpack.handling.Handler ratpack.handling.Context ratpack.http.Response ratpack.func.Action io.netty.buffer.ByteBufAllocator org.reactivestreams.Publisher org.reactivestreams.Subscriber org.reactivestreams.Subscription)) (deftype Event [id event data] Object (toString [_] (with-out-str (when id (println "id:" id)) (when event (println "event:" event)) (when data (println "data:" data)) (println)))) (defprotocol IEventFactory (-make-event [_] "coerce to new event instance")) (extend-protocol IEventFactory String (-make-event [data] (Event. nil nil data)) Long (-make-event [d] (-make-event (str d))) Event (-make-event [event] event) clojure.lang.IPersistentMap (-make-event [data] (let [{:keys [id event data]} data] (when (and (not id) (not event) (not data)) (throw (ex-info "You must supply at least one of data, event, id" {}))) (Event. id event data)))) (defn sse "Start the sse connection with the client and dispatch it in a special hanlder." [context handler] (let [^Context ctx (:catacumba/context context) ^Response response (:catacumba/response context) xform (comp (map -make-event) (map str) (map hp/bytebuffer)) out (a/chan 1 xform) ctrl (a/chan (a/sliding-buffer 1)) dispose (fn [] (a/put! ctrl [:close nil]) (a/close! ctrl)) stream (streams/channel->publisher out dispose) headers {:content-type "text/event-stream;charset=UTF-8" :transfer-encoding "chunked" :cache-control "no-cache, no-store, max-age=0, must-revalidate" :pragma "no-cache"}] (handler (assoc context :out out :ctrl ctrl)) (ctx/set-headers! response headers) (.sendStream response (streams/bind-exec stream)))) (defmethod handlers/adapter :catacumba/sse [handler] (reify Handler (^void handle [_ ^Context ctx] (let [context (ctx/create-context ctx)] (sse context handler)))))
[ { "context": "e \"enter login:\"}\n \"user\" {:login \"alice\", :id 1, :password \"1234\"}})\n\n(def login-entered ", "end": 365, "score": 0.9985220432281494, "start": 360, "tag": "USERNAME", "value": "alice" }, { "context": " \"user\" {:login \"alice\", :id 1, :password \"1234\"}})\n\n(def login-entered {\"login_state\" {:conn_id ", "end": 390, "score": 0.9993966817855835, "start": 386, "tag": "PASSWORD", "value": "1234" }, { "context": ":conn_id 1 :num_logins 1 :num_passwords 1 :login \"alice\"}\n \"msg-to-client\" {:conn-id 1", "end": 486, "score": 0.9966118931770325, "start": 481, "tag": "USERNAME", "value": "alice" }, { "context": "r password:\"}\n \"user\" {:login \"alice\", :id 1, :password \"1234\"}})\n\n(def login-succeede", "end": 606, "score": 0.9990811347961426, "start": 601, "tag": "USERNAME", "value": "alice" }, { "context": " \"user\" {:login \"alice\", :id 1, :password \"1234\"}})\n\n(def login-succeeded {\"msg-to-client\" {:conn", "end": 631, "score": 0.9993861317634583, "start": 627, "tag": "PASSWORD", "value": "1234" }, { "context": "uccessful\"}\n \"user\" {:login \"alice\", :id 1, :password \"1234\"}\n ", "end": 759, "score": 0.998286247253418, "start": 754, "tag": "USERNAME", "value": "alice" }, { "context": " \"user\" {:login \"alice\", :id 1, :password \"1234\"}\n \"msg-to-server\" {:conn-id", "end": 784, "score": 0.9994076490402222, "start": 780, "tag": "PASSWORD", "value": "1234" }, { "context": ":conn_id 1 :num_logins 2 :num_passwords 1 :login \"alice\"}\n \"msg-to-client\" {:co", "end": 973, "score": 0.9920742511749268, "start": 968, "tag": "USERNAME", "value": "alice" }, { "context": "gin:\"}\n \"user\" {:login \"alice\", :id 1, :password \"1234\"}})\n\n(def login-failed {", "end": 1104, "score": 0.9987646341323853, "start": 1099, "tag": "USERNAME", "value": "alice" }, { "context": " \"user\" {:login \"alice\", :id 1, :password \"1234\"}})\n\n(def login-failed {\"msg-to-client\" {:conn-id", "end": 1129, "score": 0.9993901252746582, "start": 1125, "tag": "PASSWORD", "value": "1234" }, { "context": "er password:\"}\n \"user\" {:login \"alice\", :id 1, :password \"1234\"}\n \"ms", "end": 1250, "score": 0.9983336329460144, "start": 1245, "tag": "USERNAME", "value": "alice" }, { "context": " \"user\" {:login \"alice\", :id 1, :password \"1234\"}\n \"msg-to-server\" {:type \"logi", "end": 1275, "score": 0.9994076490402222, "start": 1271, "tag": "PASSWORD", "value": "1234" }, { "context": "\n (reset! login-data/data {\"user\" {:id 1 :login \"alice\" :password \"1234\"}})\n\n (disp/dispatch {:type \"lo", "end": 1583, "score": 0.9984741806983948, "start": 1578, "tag": "USERNAME", "value": "alice" }, { "context": "ata/data {\"user\" {:id 1 :login \"alice\" :password \"1234\"}})\n\n (disp/dispatch {:type \"login\" :conn-id 1})", "end": 1600, "score": 0.9993346333503723, "start": 1596, "tag": "PASSWORD", "value": "1234" }, { "context": "\n (reset! login-data/data {\"user\" {:id 1 :login \"alice\" :password \"1234\"}})\n\n (disp/dispatch {:type \"lo", "end": 2214, "score": 0.9981876015663147, "start": 2209, "tag": "USERNAME", "value": "alice" }, { "context": "ata/data {\"user\" {:id 1 :login \"alice\" :password \"1234\"}})\n\n (disp/dispatch {:type \"login\" :conn-id 1})", "end": 2231, "score": 0.9993504881858826, "start": 2227, "tag": "PASSWORD", "value": "1234" }, { "context": "\n (reset! login-data/data {\"user\" {:id 1 :login \"alice\" :password \"1234\"}})\n\n (disp/dispatch {:type :lo", "end": 2817, "score": 0.9966127872467041, "start": 2812, "tag": "USERNAME", "value": "alice" }, { "context": "ata/data {\"user\" {:id 1 :login \"alice\" :password \"1234\"}})\n\n (disp/dispatch {:type :login :conn-id 1})\n", "end": 2834, "score": 0.9993377923965454, "start": 2830, "tag": "PASSWORD", "value": "1234" } ]
data/train/clojure/4bf9c1eaf1ffcda5a0c819f568b68ca712694941login_test.clj
harshp8l/deep-learning-lang-detection
84
(ns zombunity.login-test (:use clojure.test) (:require [zombunity.dispatch :as disp] [zombunity.data :as data] [zombunity.data.login-data :as login-data])) (def first-run {"login_state" {:conn_id 1 :num_logins 1 :num_passwords 0} "msg-to-client" {:conn-id 1 :message "enter login:"} "user" {:login "alice", :id 1, :password "1234"}}) (def login-entered {"login_state" {:conn_id 1 :num_logins 1 :num_passwords 1 :login "alice"} "msg-to-client" {:conn-id 1 :message "enter password:"} "user" {:login "alice", :id 1, :password "1234"}}) (def login-succeeded {"msg-to-client" {:conn-id 1 :message "login successful"} "user" {:login "alice", :id 1, :password "1234"} "msg-to-server" {:conn-id 1, :user-id 1, :type :user-logged-in}}) (def first-wrong-password {"login_state" {:conn_id 1 :num_logins 2 :num_passwords 1 :login "alice"} "msg-to-client" {:conn-id 1 :message "enter login:"} "user" {:login "alice", :id 1, :password "1234"}}) (def login-failed {"msg-to-client" {:conn-id 1 :message "enter password:"} "user" {:login "alice", :id 1, :password "1234"} "msg-to-server" {:type "login-max-attempts" :conn-id 1}}) (deftest test-login-success-first-try (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "1234"}}) (disp/dispatch {:type "login" :conn-id 1}) (is (= first-run @login-data/data) "Initial login prompt") (disp/dispatch {:type "alice" :conn-id 1}) (is (= login-entered @login-data/data) "Login entered") (disp/dispatch {:type "1234" :conn-id 1}) (is (= login-succeeded @login-data/data) "Password entered") (is (= nil (get "login_state" @login-data/data)))) (deftest test-login-fail-once-then-succeed (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "1234"}}) (disp/dispatch {:type "login" :conn-id 1}) (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "123" :conn-id 1}) (is (= first-wrong-password @login-data/data) "First failure") (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "1234" :conn-id 1}) (is (= login-succeeded @login-data/data) "Success after first failure")) (deftest test-login-fail (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "1234"}}) (disp/dispatch {:type :login :conn-id 1}) (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "wrong password" :conn-id 1}) (disp/dispatch {:type "bob" :conn-id 1}) (disp/dispatch {:type "1234" :conn-id 1}) (disp/dispatch {:type "" :conn-id 1}) (disp/dispatch {:type "wrong password" :conn-id 1}) (is (= login-failed @login-data/data) "Password entered"))
32882
(ns zombunity.login-test (:use clojure.test) (:require [zombunity.dispatch :as disp] [zombunity.data :as data] [zombunity.data.login-data :as login-data])) (def first-run {"login_state" {:conn_id 1 :num_logins 1 :num_passwords 0} "msg-to-client" {:conn-id 1 :message "enter login:"} "user" {:login "alice", :id 1, :password "<PASSWORD>"}}) (def login-entered {"login_state" {:conn_id 1 :num_logins 1 :num_passwords 1 :login "alice"} "msg-to-client" {:conn-id 1 :message "enter password:"} "user" {:login "alice", :id 1, :password "<PASSWORD>"}}) (def login-succeeded {"msg-to-client" {:conn-id 1 :message "login successful"} "user" {:login "alice", :id 1, :password "<PASSWORD>"} "msg-to-server" {:conn-id 1, :user-id 1, :type :user-logged-in}}) (def first-wrong-password {"login_state" {:conn_id 1 :num_logins 2 :num_passwords 1 :login "alice"} "msg-to-client" {:conn-id 1 :message "enter login:"} "user" {:login "alice", :id 1, :password "<PASSWORD>"}}) (def login-failed {"msg-to-client" {:conn-id 1 :message "enter password:"} "user" {:login "alice", :id 1, :password "<PASSWORD>"} "msg-to-server" {:type "login-max-attempts" :conn-id 1}}) (deftest test-login-success-first-try (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "<PASSWORD>"}}) (disp/dispatch {:type "login" :conn-id 1}) (is (= first-run @login-data/data) "Initial login prompt") (disp/dispatch {:type "alice" :conn-id 1}) (is (= login-entered @login-data/data) "Login entered") (disp/dispatch {:type "1234" :conn-id 1}) (is (= login-succeeded @login-data/data) "Password entered") (is (= nil (get "login_state" @login-data/data)))) (deftest test-login-fail-once-then-succeed (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "<PASSWORD>"}}) (disp/dispatch {:type "login" :conn-id 1}) (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "123" :conn-id 1}) (is (= first-wrong-password @login-data/data) "First failure") (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "1234" :conn-id 1}) (is (= login-succeeded @login-data/data) "Success after first failure")) (deftest test-login-fail (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "<PASSWORD>"}}) (disp/dispatch {:type :login :conn-id 1}) (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "wrong password" :conn-id 1}) (disp/dispatch {:type "bob" :conn-id 1}) (disp/dispatch {:type "1234" :conn-id 1}) (disp/dispatch {:type "" :conn-id 1}) (disp/dispatch {:type "wrong password" :conn-id 1}) (is (= login-failed @login-data/data) "Password entered"))
true
(ns zombunity.login-test (:use clojure.test) (:require [zombunity.dispatch :as disp] [zombunity.data :as data] [zombunity.data.login-data :as login-data])) (def first-run {"login_state" {:conn_id 1 :num_logins 1 :num_passwords 0} "msg-to-client" {:conn-id 1 :message "enter login:"} "user" {:login "alice", :id 1, :password "PI:PASSWORD:<PASSWORD>END_PI"}}) (def login-entered {"login_state" {:conn_id 1 :num_logins 1 :num_passwords 1 :login "alice"} "msg-to-client" {:conn-id 1 :message "enter password:"} "user" {:login "alice", :id 1, :password "PI:PASSWORD:<PASSWORD>END_PI"}}) (def login-succeeded {"msg-to-client" {:conn-id 1 :message "login successful"} "user" {:login "alice", :id 1, :password "PI:PASSWORD:<PASSWORD>END_PI"} "msg-to-server" {:conn-id 1, :user-id 1, :type :user-logged-in}}) (def first-wrong-password {"login_state" {:conn_id 1 :num_logins 2 :num_passwords 1 :login "alice"} "msg-to-client" {:conn-id 1 :message "enter login:"} "user" {:login "alice", :id 1, :password "PI:PASSWORD:<PASSWORD>END_PI"}}) (def login-failed {"msg-to-client" {:conn-id 1 :message "enter password:"} "user" {:login "alice", :id 1, :password "PI:PASSWORD:<PASSWORD>END_PI"} "msg-to-server" {:type "login-max-attempts" :conn-id 1}}) (deftest test-login-success-first-try (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "PI:PASSWORD:<PASSWORD>END_PI"}}) (disp/dispatch {:type "login" :conn-id 1}) (is (= first-run @login-data/data) "Initial login prompt") (disp/dispatch {:type "alice" :conn-id 1}) (is (= login-entered @login-data/data) "Login entered") (disp/dispatch {:type "1234" :conn-id 1}) (is (= login-succeeded @login-data/data) "Password entered") (is (= nil (get "login_state" @login-data/data)))) (deftest test-login-fail-once-then-succeed (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "PI:PASSWORD:<PASSWORD>END_PI"}}) (disp/dispatch {:type "login" :conn-id 1}) (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "123" :conn-id 1}) (is (= first-wrong-password @login-data/data) "First failure") (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "1234" :conn-id 1}) (is (= login-succeeded @login-data/data) "Success after first failure")) (deftest test-login-fail (disp/register-daemon (first (disp/filter-classpath-namespaces #"\.login$"))) (data/set-target :zombunity.data.login-data/login) (reset! login-data/data {"user" {:id 1 :login "alice" :password "PI:PASSWORD:<PASSWORD>END_PI"}}) (disp/dispatch {:type :login :conn-id 1}) (disp/dispatch {:type "alice" :conn-id 1}) (disp/dispatch {:type "wrong password" :conn-id 1}) (disp/dispatch {:type "bob" :conn-id 1}) (disp/dispatch {:type "1234" :conn-id 1}) (disp/dispatch {:type "" :conn-id 1}) (disp/dispatch {:type "wrong password" :conn-id 1}) (is (= login-failed @login-data/data) "Password entered"))
[ { "context": " (str\n \"Hi, I'm Josh Mathews. \"\n \"I'm a mus", "end": 305, "score": 0.9998325109481812, "start": 293, "tag": "NAME", "value": "Josh Mathews" } ]
src/homepage/home.cljs
jfacoustic/homepage-frontend
0
(ns homepage.home) (defn home [] [:section {:class "hero is-fullheight"} [:div {:class "hero-body"} [:div {:class "container introduction"} [:h1 {:class "title has-text-light"} "Introduction"] [:p {:class "has-text-light"} (str "Hi, I'm Josh Mathews. " "I'm a musician, software developer, and advocate of the Oxford Comma. " "I'm currently a consultant for IBM in Baton Rouge, Louisiana, building high-performance enterprise applications. " "This site is currently in progress. I'm rewriting it from the ground up with full-stack Clojure. ")] [:p {:class "has-text-light has-text-right side-note"} "Some friends and I took this picture! We were sponsored by the Colorado Space Grant Consortium to launch a ballon-sat. " [:a {:href "http://thecrite.com/coloradomesau/ground-control-major-tom/"} "More Info"]]]]])
98635
(ns homepage.home) (defn home [] [:section {:class "hero is-fullheight"} [:div {:class "hero-body"} [:div {:class "container introduction"} [:h1 {:class "title has-text-light"} "Introduction"] [:p {:class "has-text-light"} (str "Hi, I'm <NAME>. " "I'm a musician, software developer, and advocate of the Oxford Comma. " "I'm currently a consultant for IBM in Baton Rouge, Louisiana, building high-performance enterprise applications. " "This site is currently in progress. I'm rewriting it from the ground up with full-stack Clojure. ")] [:p {:class "has-text-light has-text-right side-note"} "Some friends and I took this picture! We were sponsored by the Colorado Space Grant Consortium to launch a ballon-sat. " [:a {:href "http://thecrite.com/coloradomesau/ground-control-major-tom/"} "More Info"]]]]])
true
(ns homepage.home) (defn home [] [:section {:class "hero is-fullheight"} [:div {:class "hero-body"} [:div {:class "container introduction"} [:h1 {:class "title has-text-light"} "Introduction"] [:p {:class "has-text-light"} (str "Hi, I'm PI:NAME:<NAME>END_PI. " "I'm a musician, software developer, and advocate of the Oxford Comma. " "I'm currently a consultant for IBM in Baton Rouge, Louisiana, building high-performance enterprise applications. " "This site is currently in progress. I'm rewriting it from the ground up with full-stack Clojure. ")] [:p {:class "has-text-light has-text-right side-note"} "Some friends and I took this picture! We were sponsored by the Colorado Space Grant Consortium to launch a ballon-sat. " [:a {:href "http://thecrite.com/coloradomesau/ground-control-major-tom/"} "More Info"]]]]])
[ { "context": ";; Copyright (c) Nicolas Buduroi. All rights reserved.\n;; The use and distribution", "end": 32, "score": 0.999888002872467, "start": 17, "tag": "NAME", "value": "Nicolas Buduroi" }, { "context": "r any other, from this software.\n\n(ns #^{:author \"Nicolas Buduroi\"\n :doc \"Clojure support for audio.\"}\n clj-", "end": 443, "score": 0.9998876452445984, "start": 428, "tag": "NAME", "value": "Nicolas Buduroi" } ]
data/test/clojure/e35b90b4597d8dd922c968ba5944184bc2f64ba0core.clj
harshp8l/deep-learning-lang-detection
84
;; Copyright (c) Nicolas Buduroi. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 which can be found in the file ;; epl-v10.html at the root of this distribution. By using this software ;; in any fashion, you are agreeing to be bound by the terms of this ;; license. ;; You must not remove this notice, or any other, from this software. (ns #^{:author "Nicolas Buduroi" :doc "Clojure support for audio."} clj-audio.core (:use clj-audio.sampled clj-audio.utils) (:import [javax.sound.sampled AudioInputStream AudioSystem Clip SourceDataLine TargetDataLine])) ;;;; Audio formats (def ^:dynamic *default-format* (make-format {:encoding :pcm-signed :sample-rate 44100 :sample-size-in-bits 16 :frame-rate 44100 :frame-size 4 :channels 2 :endianness :little-endian})) ;;;; Audio input streams (defmulti ->stream "Converts the given object to an AudioInputStream." (fn [o & _] (type o))) (defmethod ->stream String [s & _] (AudioSystem/getAudioInputStream (java.io.File. s))) (defmethod ->stream java.io.File [file & _] (AudioSystem/getAudioInputStream file)) (defmethod ->stream java.net.URL [url & _] (AudioSystem/getAudioInputStream url)) (defmethod ->stream TargetDataLine [line & _] (AudioInputStream. line)) (defmethod ->stream java.io.InputStream [stream & [length fmt]] (AudioInputStream. stream (or fmt *default-format*) (or length -1))) (defmethod ->stream clojure.lang.IFn [f n] (let [s (java.io.ByteArrayInputStream. (byte-array (map (comp byte f) (range n))))] (->stream s n))) (defn decode "Convert the given stream to a data format that can be played on most (if not all) systems. The decoded is signed PCM in little endian ordering, sample size is 16 bit if not specified by the given stream format." [audio-stream] (let [fi (->format-info audio-stream) sample-size (:sample-size-in-bits fi) sample-size (if (< sample-size 0) 16 sample-size) frame-size (* (/ sample-size 8) (:channels fi)) fmt (make-format (merge fi {:encoding :pcm-signed :sample-size-in-bits sample-size :frame-size frame-size :frame-rate (:sample-rate fi) :endianness :little-endian}))] (convert audio-stream fmt))) (defn write "Writes an audio-stream to the specified File (can be a string) or OutputStream of the specified file type. See the supported-file-types for available file types. Returns the number of bytes written." [audio-stream file-type file-or-stream] (AudioSystem/write audio-stream (file-types file-type) (file-if-string file-or-stream))) (defn finished? "Returns true if the given audio stream doesn't have any bytes available." [audio-stream] (= 0 (.available audio-stream))) (defn flush-close "Flush and close the given audio stream." [audio-stream] (.flush audio-stream) (.close audio-stream)) ;;;; Mixer (defn mixers "Returns a list of all available mixers." [] (map #(AudioSystem/getMixer %) (AudioSystem/getMixerInfo))) (defmacro with-mixer "Creates a binding to the given mixer then executes body. The mixer will be bound to *mixer* for use by other functions." [mixer & body] `(binding [*mixer* ~mixer] ~@body)) (defn supports-line? "Check if the given mixer supports the given line type." [line-type mixer] (.isLineSupported mixer (line-info line-type))) ;;;; Playback (def default-buffer-size (* 64 1024)) (def ^:dynamic *line-buffer-size* "Line buffer size in bytes, must correspond to an integral number of frames." default-buffer-size ) (def ^:dynamic *playback-buffer-size* "Playback buffer size in bytes." default-buffer-size ) (def ^:dynamic *playing* "Variable telling if play* is currently writing to a line. If set to false during playback, play* will exit." (ref false) ) (defn play* "Write the given audio stream bytes to the given source data line using a buffer of the given size. Returns the number of bytes played." [#^SourceDataLine source audio-stream buffer-size] (let [buffer (byte-array buffer-size)] (dosync (ref-set *playing* true)) (loop [cnt 0 total 0] (if (and (> cnt -1) @*playing*) (do (when (> cnt 0) (.write source buffer 0 cnt)) (recur (.read audio-stream buffer 0 (alength buffer)) (+ total cnt))) (dosync (ref-set *playing* false) total))))) (defn stop "Stop playback for the current thread." [] (dosync (ref-set *playing* false))) (defn play-with "Play the given audio stream with the specified line. Returns the number of bytes played." [audio-stream #^SourceDataLine line] (let [fmt (->format audio-stream)] (with-data-line [source line fmt] (play* source audio-stream default-buffer-size)))) (defn play "Play the given audio stream. Accepts an optional listener function that will be called when a line event is raised, taking the event type, the line and the stream position as arguments. Returns the number of bytes played." [audio-stream & [listener]] (let [line (make-line :output (->format audio-stream) *line-buffer-size*) p #(with-data-line [source line] (play* source audio-stream *playback-buffer-size*))] (if listener (with-line-listener line listener (p)) (p)))) ;;;; Clip playback (defn clip "Creates a clip from the given audio stream and open it." [audio-stream] (doto (make-line :clip (->format audio-stream)) (.open audio-stream))) (defn play-clip "Play the given clip one or n times. Optionally takes a start and end position expressed in number of frames." [clp & [n start end]] (let [start (or start 0) end (or end (dec (.getFrameLength clp)))] (doto clp (.setFramePosition start) (.setLoopPoints start end) (.loop (dec (or n 1)))))) (defn loop-clip "Play the given clip continuously in a loop. Optionally takes a start and end position expressed in number of frames." [clp & [start end]] (play-clip clp (inc Clip/LOOP_CONTINUOUSLY) start end)) ;;;; Skipping (def ^:dynamic *skip-inaccuracy-size* 1200) (defn skip "Skip the given audio stream by the specified number of bytes." [audio-stream to-skip] (loop [total 0 remainder to-skip] (if (>= (+ total *skip-inaccuracy-size*) to-skip) audio-stream (let [skipped (.skip audio-stream remainder)] (recur (+ total skipped) (- remainder skipped)))))) (defn skipper "Returns a skip-like function that takes a ratio a the length of the given audio stream." [audio-stream] (let [length (.available audio-stream)] (fn [ratio] (skip audio-stream (* ratio length)))))
25074
;; Copyright (c) <NAME>. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 which can be found in the file ;; epl-v10.html at the root of this distribution. By using this software ;; in any fashion, you are agreeing to be bound by the terms of this ;; license. ;; You must not remove this notice, or any other, from this software. (ns #^{:author "<NAME>" :doc "Clojure support for audio."} clj-audio.core (:use clj-audio.sampled clj-audio.utils) (:import [javax.sound.sampled AudioInputStream AudioSystem Clip SourceDataLine TargetDataLine])) ;;;; Audio formats (def ^:dynamic *default-format* (make-format {:encoding :pcm-signed :sample-rate 44100 :sample-size-in-bits 16 :frame-rate 44100 :frame-size 4 :channels 2 :endianness :little-endian})) ;;;; Audio input streams (defmulti ->stream "Converts the given object to an AudioInputStream." (fn [o & _] (type o))) (defmethod ->stream String [s & _] (AudioSystem/getAudioInputStream (java.io.File. s))) (defmethod ->stream java.io.File [file & _] (AudioSystem/getAudioInputStream file)) (defmethod ->stream java.net.URL [url & _] (AudioSystem/getAudioInputStream url)) (defmethod ->stream TargetDataLine [line & _] (AudioInputStream. line)) (defmethod ->stream java.io.InputStream [stream & [length fmt]] (AudioInputStream. stream (or fmt *default-format*) (or length -1))) (defmethod ->stream clojure.lang.IFn [f n] (let [s (java.io.ByteArrayInputStream. (byte-array (map (comp byte f) (range n))))] (->stream s n))) (defn decode "Convert the given stream to a data format that can be played on most (if not all) systems. The decoded is signed PCM in little endian ordering, sample size is 16 bit if not specified by the given stream format." [audio-stream] (let [fi (->format-info audio-stream) sample-size (:sample-size-in-bits fi) sample-size (if (< sample-size 0) 16 sample-size) frame-size (* (/ sample-size 8) (:channels fi)) fmt (make-format (merge fi {:encoding :pcm-signed :sample-size-in-bits sample-size :frame-size frame-size :frame-rate (:sample-rate fi) :endianness :little-endian}))] (convert audio-stream fmt))) (defn write "Writes an audio-stream to the specified File (can be a string) or OutputStream of the specified file type. See the supported-file-types for available file types. Returns the number of bytes written." [audio-stream file-type file-or-stream] (AudioSystem/write audio-stream (file-types file-type) (file-if-string file-or-stream))) (defn finished? "Returns true if the given audio stream doesn't have any bytes available." [audio-stream] (= 0 (.available audio-stream))) (defn flush-close "Flush and close the given audio stream." [audio-stream] (.flush audio-stream) (.close audio-stream)) ;;;; Mixer (defn mixers "Returns a list of all available mixers." [] (map #(AudioSystem/getMixer %) (AudioSystem/getMixerInfo))) (defmacro with-mixer "Creates a binding to the given mixer then executes body. The mixer will be bound to *mixer* for use by other functions." [mixer & body] `(binding [*mixer* ~mixer] ~@body)) (defn supports-line? "Check if the given mixer supports the given line type." [line-type mixer] (.isLineSupported mixer (line-info line-type))) ;;;; Playback (def default-buffer-size (* 64 1024)) (def ^:dynamic *line-buffer-size* "Line buffer size in bytes, must correspond to an integral number of frames." default-buffer-size ) (def ^:dynamic *playback-buffer-size* "Playback buffer size in bytes." default-buffer-size ) (def ^:dynamic *playing* "Variable telling if play* is currently writing to a line. If set to false during playback, play* will exit." (ref false) ) (defn play* "Write the given audio stream bytes to the given source data line using a buffer of the given size. Returns the number of bytes played." [#^SourceDataLine source audio-stream buffer-size] (let [buffer (byte-array buffer-size)] (dosync (ref-set *playing* true)) (loop [cnt 0 total 0] (if (and (> cnt -1) @*playing*) (do (when (> cnt 0) (.write source buffer 0 cnt)) (recur (.read audio-stream buffer 0 (alength buffer)) (+ total cnt))) (dosync (ref-set *playing* false) total))))) (defn stop "Stop playback for the current thread." [] (dosync (ref-set *playing* false))) (defn play-with "Play the given audio stream with the specified line. Returns the number of bytes played." [audio-stream #^SourceDataLine line] (let [fmt (->format audio-stream)] (with-data-line [source line fmt] (play* source audio-stream default-buffer-size)))) (defn play "Play the given audio stream. Accepts an optional listener function that will be called when a line event is raised, taking the event type, the line and the stream position as arguments. Returns the number of bytes played." [audio-stream & [listener]] (let [line (make-line :output (->format audio-stream) *line-buffer-size*) p #(with-data-line [source line] (play* source audio-stream *playback-buffer-size*))] (if listener (with-line-listener line listener (p)) (p)))) ;;;; Clip playback (defn clip "Creates a clip from the given audio stream and open it." [audio-stream] (doto (make-line :clip (->format audio-stream)) (.open audio-stream))) (defn play-clip "Play the given clip one or n times. Optionally takes a start and end position expressed in number of frames." [clp & [n start end]] (let [start (or start 0) end (or end (dec (.getFrameLength clp)))] (doto clp (.setFramePosition start) (.setLoopPoints start end) (.loop (dec (or n 1)))))) (defn loop-clip "Play the given clip continuously in a loop. Optionally takes a start and end position expressed in number of frames." [clp & [start end]] (play-clip clp (inc Clip/LOOP_CONTINUOUSLY) start end)) ;;;; Skipping (def ^:dynamic *skip-inaccuracy-size* 1200) (defn skip "Skip the given audio stream by the specified number of bytes." [audio-stream to-skip] (loop [total 0 remainder to-skip] (if (>= (+ total *skip-inaccuracy-size*) to-skip) audio-stream (let [skipped (.skip audio-stream remainder)] (recur (+ total skipped) (- remainder skipped)))))) (defn skipper "Returns a skip-like function that takes a ratio a the length of the given audio stream." [audio-stream] (let [length (.available audio-stream)] (fn [ratio] (skip audio-stream (* ratio length)))))
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 which can be found in the file ;; epl-v10.html at the root of this distribution. By using this software ;; in any fashion, you are agreeing to be bound by the terms of this ;; license. ;; You must not remove this notice, or any other, from this software. (ns #^{:author "PI:NAME:<NAME>END_PI" :doc "Clojure support for audio."} clj-audio.core (:use clj-audio.sampled clj-audio.utils) (:import [javax.sound.sampled AudioInputStream AudioSystem Clip SourceDataLine TargetDataLine])) ;;;; Audio formats (def ^:dynamic *default-format* (make-format {:encoding :pcm-signed :sample-rate 44100 :sample-size-in-bits 16 :frame-rate 44100 :frame-size 4 :channels 2 :endianness :little-endian})) ;;;; Audio input streams (defmulti ->stream "Converts the given object to an AudioInputStream." (fn [o & _] (type o))) (defmethod ->stream String [s & _] (AudioSystem/getAudioInputStream (java.io.File. s))) (defmethod ->stream java.io.File [file & _] (AudioSystem/getAudioInputStream file)) (defmethod ->stream java.net.URL [url & _] (AudioSystem/getAudioInputStream url)) (defmethod ->stream TargetDataLine [line & _] (AudioInputStream. line)) (defmethod ->stream java.io.InputStream [stream & [length fmt]] (AudioInputStream. stream (or fmt *default-format*) (or length -1))) (defmethod ->stream clojure.lang.IFn [f n] (let [s (java.io.ByteArrayInputStream. (byte-array (map (comp byte f) (range n))))] (->stream s n))) (defn decode "Convert the given stream to a data format that can be played on most (if not all) systems. The decoded is signed PCM in little endian ordering, sample size is 16 bit if not specified by the given stream format." [audio-stream] (let [fi (->format-info audio-stream) sample-size (:sample-size-in-bits fi) sample-size (if (< sample-size 0) 16 sample-size) frame-size (* (/ sample-size 8) (:channels fi)) fmt (make-format (merge fi {:encoding :pcm-signed :sample-size-in-bits sample-size :frame-size frame-size :frame-rate (:sample-rate fi) :endianness :little-endian}))] (convert audio-stream fmt))) (defn write "Writes an audio-stream to the specified File (can be a string) or OutputStream of the specified file type. See the supported-file-types for available file types. Returns the number of bytes written." [audio-stream file-type file-or-stream] (AudioSystem/write audio-stream (file-types file-type) (file-if-string file-or-stream))) (defn finished? "Returns true if the given audio stream doesn't have any bytes available." [audio-stream] (= 0 (.available audio-stream))) (defn flush-close "Flush and close the given audio stream." [audio-stream] (.flush audio-stream) (.close audio-stream)) ;;;; Mixer (defn mixers "Returns a list of all available mixers." [] (map #(AudioSystem/getMixer %) (AudioSystem/getMixerInfo))) (defmacro with-mixer "Creates a binding to the given mixer then executes body. The mixer will be bound to *mixer* for use by other functions." [mixer & body] `(binding [*mixer* ~mixer] ~@body)) (defn supports-line? "Check if the given mixer supports the given line type." [line-type mixer] (.isLineSupported mixer (line-info line-type))) ;;;; Playback (def default-buffer-size (* 64 1024)) (def ^:dynamic *line-buffer-size* "Line buffer size in bytes, must correspond to an integral number of frames." default-buffer-size ) (def ^:dynamic *playback-buffer-size* "Playback buffer size in bytes." default-buffer-size ) (def ^:dynamic *playing* "Variable telling if play* is currently writing to a line. If set to false during playback, play* will exit." (ref false) ) (defn play* "Write the given audio stream bytes to the given source data line using a buffer of the given size. Returns the number of bytes played." [#^SourceDataLine source audio-stream buffer-size] (let [buffer (byte-array buffer-size)] (dosync (ref-set *playing* true)) (loop [cnt 0 total 0] (if (and (> cnt -1) @*playing*) (do (when (> cnt 0) (.write source buffer 0 cnt)) (recur (.read audio-stream buffer 0 (alength buffer)) (+ total cnt))) (dosync (ref-set *playing* false) total))))) (defn stop "Stop playback for the current thread." [] (dosync (ref-set *playing* false))) (defn play-with "Play the given audio stream with the specified line. Returns the number of bytes played." [audio-stream #^SourceDataLine line] (let [fmt (->format audio-stream)] (with-data-line [source line fmt] (play* source audio-stream default-buffer-size)))) (defn play "Play the given audio stream. Accepts an optional listener function that will be called when a line event is raised, taking the event type, the line and the stream position as arguments. Returns the number of bytes played." [audio-stream & [listener]] (let [line (make-line :output (->format audio-stream) *line-buffer-size*) p #(with-data-line [source line] (play* source audio-stream *playback-buffer-size*))] (if listener (with-line-listener line listener (p)) (p)))) ;;;; Clip playback (defn clip "Creates a clip from the given audio stream and open it." [audio-stream] (doto (make-line :clip (->format audio-stream)) (.open audio-stream))) (defn play-clip "Play the given clip one or n times. Optionally takes a start and end position expressed in number of frames." [clp & [n start end]] (let [start (or start 0) end (or end (dec (.getFrameLength clp)))] (doto clp (.setFramePosition start) (.setLoopPoints start end) (.loop (dec (or n 1)))))) (defn loop-clip "Play the given clip continuously in a loop. Optionally takes a start and end position expressed in number of frames." [clp & [start end]] (play-clip clp (inc Clip/LOOP_CONTINUOUSLY) start end)) ;;;; Skipping (def ^:dynamic *skip-inaccuracy-size* 1200) (defn skip "Skip the given audio stream by the specified number of bytes." [audio-stream to-skip] (loop [total 0 remainder to-skip] (if (>= (+ total *skip-inaccuracy-size*) to-skip) audio-stream (let [skipped (.skip audio-stream remainder)] (recur (+ total skipped) (- remainder skipped)))))) (defn skipper "Returns a skip-like function that takes a ratio a the length of the given audio stream." [audio-stream] (let [length (.available audio-stream)] (fn [ratio] (skip audio-stream (* ratio length)))))
[ { "context": "s.crypto.SCryptUtil/check \"keijo\" (password-hash \"keijo\"))))\n\n(deftest match-properly\n (is (password-mat", "end": 175, "score": 0.8402026295661926, "start": 170, "tag": "PASSWORD", "value": "keijo" }, { "context": "\n\n(deftest match-properly\n (is (password-match? \"keijo\" (com.lambdaworks.crypto.SCryptUtil/scrypt \"keijo", "end": 235, "score": 0.9275909066200256, "start": 230, "tag": "PASSWORD", "value": "keijo" }, { "context": "keijo\" (com.lambdaworks.crypto.SCryptUtil/scrypt \"keijo\" 16384 8 1))))\n\n(deftest not-match-invalid-pwd\n ", "end": 285, "score": 0.8867829442024231, "start": 280, "tag": "PASSWORD", "value": "keijo" }, { "context": "st not-match-invalid-pwd\n (not (password-match? \"keijo2\" (com.lambdaworks.crypto.SCryptUtil/scrypt \"keijo", "end": 364, "score": 0.9475258588790894, "start": 358, "tag": "PASSWORD", "value": "keijo2" }, { "context": "jo2\" (com.lambdaworks.crypto.SCryptUtil/scrypt \"keijo\" 16384 8 1))))\n\n(deftest base64-decodes\n (is (= ", "end": 414, "score": 0.8516086339950562, "start": 411, "tag": "PASSWORD", "value": "ijo" } ]
test/ontrail/test/crypto.clj
jrosti/ontrail
1
(ns ontrail.test.crypto (:use [ontrail.crypto]) (:use [clojure.test])) (deftest hash-properly (is (com.lambdaworks.crypto.SCryptUtil/check "keijo" (password-hash "keijo")))) (deftest match-properly (is (password-match? "keijo" (com.lambdaworks.crypto.SCryptUtil/scrypt "keijo" 16384 8 1)))) (deftest not-match-invalid-pwd (not (password-match? "keijo2" (com.lambdaworks.crypto.SCryptUtil/scrypt "keijo" 16384 8 1)))) (deftest base64-decodes (is (= "esko" (byte-array-to-string (base64-decode "ZXNrbw=="))))) (deftest encrypt-and-decrypt-does-what-it-should-do (is (= "foo2" (decrypt (encrypt "foo2"))))) (deftest decrypt-does-what-it-should-do (is (= "foo2" (decrypt "hcmlYlBedinIG2d5PohVCRKkEGg="))))
21271
(ns ontrail.test.crypto (:use [ontrail.crypto]) (:use [clojure.test])) (deftest hash-properly (is (com.lambdaworks.crypto.SCryptUtil/check "keijo" (password-hash "<PASSWORD>")))) (deftest match-properly (is (password-match? "<PASSWORD>" (com.lambdaworks.crypto.SCryptUtil/scrypt "<PASSWORD>" 16384 8 1)))) (deftest not-match-invalid-pwd (not (password-match? "<PASSWORD>" (com.lambdaworks.crypto.SCryptUtil/scrypt "ke<PASSWORD>" 16384 8 1)))) (deftest base64-decodes (is (= "esko" (byte-array-to-string (base64-decode "ZXNrbw=="))))) (deftest encrypt-and-decrypt-does-what-it-should-do (is (= "foo2" (decrypt (encrypt "foo2"))))) (deftest decrypt-does-what-it-should-do (is (= "foo2" (decrypt "hcmlYlBedinIG2d5PohVCRKkEGg="))))
true
(ns ontrail.test.crypto (:use [ontrail.crypto]) (:use [clojure.test])) (deftest hash-properly (is (com.lambdaworks.crypto.SCryptUtil/check "keijo" (password-hash "PI:PASSWORD:<PASSWORD>END_PI")))) (deftest match-properly (is (password-match? "PI:PASSWORD:<PASSWORD>END_PI" (com.lambdaworks.crypto.SCryptUtil/scrypt "PI:PASSWORD:<PASSWORD>END_PI" 16384 8 1)))) (deftest not-match-invalid-pwd (not (password-match? "PI:PASSWORD:<PASSWORD>END_PI" (com.lambdaworks.crypto.SCryptUtil/scrypt "kePI:PASSWORD:<PASSWORD>END_PI" 16384 8 1)))) (deftest base64-decodes (is (= "esko" (byte-array-to-string (base64-decode "ZXNrbw=="))))) (deftest encrypt-and-decrypt-does-what-it-should-do (is (= "foo2" (decrypt (encrypt "foo2"))))) (deftest decrypt-does-what-it-should-do (is (= "foo2" (decrypt "hcmlYlBedinIG2d5PohVCRKkEGg="))))
[ { "context": "\"catorze\"\n \"quatorze\"\n (number 14)\n\n \"16\"\n \"dezesseis\"\n \"dezasseis\"\n (number 16)\n\n \"17\"\n \"dezessete", "end": 317, "score": 0.6947434544563293, "start": 310, "tag": "NAME", "value": "zesseis" }, { "context": "atorze\"\n (number 14)\n\n \"16\"\n \"dezesseis\"\n \"dezasseis\"\n (number 16)\n\n \"17\"\n \"dezessete\"\n \"dezassete", "end": 331, "score": 0.5923881530761719, "start": 325, "tag": "NAME", "value": "asseis" }, { "context": "zesseis\"\n \"dezasseis\"\n (number 16)\n\n \"17\"\n \"dezessete\"\n \"dezassete\"\n (number 17)\n\n \"18\"\n \"dezoito\"", "end": 366, "score": 0.6635127067565918, "start": 360, "tag": "NAME", "value": "zesset" }, { "context": "dezasseis\"\n (number 16)\n\n \"17\"\n \"dezessete\"\n \"dezassete\"\n (number 17)\n\n \"18\"\n \"dezoito\"\n (number 18)\n", "end": 381, "score": 0.6840993762016296, "start": 372, "tag": "NAME", "value": "dezassete" } ]
resources/languages/pt/corpus/numbers.clj
irvingflores/duckling
922
(; Context map {} "1" "um" "uma" (number 1) "2" "dois" "duas" (number 2) "3" "três" "tres" (number 3) "6" "seis" (number 6) "11" "onze" (number 11) "12" "doze" "uma dúzia" "uma duzia" (number 12) "14" "catorze" "quatorze" (number 14) "16" "dezesseis" "dezasseis" (number 16) "17" "dezessete" "dezassete" (number 17) "18" "dezoito" (number 18) "19" "dezenove" "dezanove" (number 19) "21" "vinte e um" (number 21) "23" "vinte e tres" "vinte e três" (number 23) "24" "vinte e quatro" "duas dúzias" "duas duzias" (number 24) "50" "cinquenta" "cinqüenta" "cincoenta" (number 50) "setenta" (number 70) "setenta e oito" (number 78) "oitenta" (number 80) "33" "trinta e três" "trinta e tres" (number 33) "1,1" "1,10" "01,10" (number 1.1) "0,77" ",77" (number 0.77) "100.000" "100000" "100K" "100k" (number 100000) "100" "cem" (number 100) "243" (number 243) "trezentos" (number 300) "3M" "3000K" "3000000" "3.000.000" (number 3000000) "1.200.000" "1200000" "1,2M" "1200K" ",0012G" (number 1200000) "- 1.200.000" "-1200000" "menos 1.200.000" "-1,2M" "-1200K" "-,0012G" (number -1200000) "1 ponto cinco" "um ponto cinco" "1,5" (number 1.5) )
1861
(; Context map {} "1" "um" "uma" (number 1) "2" "dois" "duas" (number 2) "3" "três" "tres" (number 3) "6" "seis" (number 6) "11" "onze" (number 11) "12" "doze" "uma dúzia" "uma duzia" (number 12) "14" "catorze" "quatorze" (number 14) "16" "de<NAME>" "dez<NAME>" (number 16) "17" "de<NAME>e" "<NAME>" (number 17) "18" "dezoito" (number 18) "19" "dezenove" "dezanove" (number 19) "21" "vinte e um" (number 21) "23" "vinte e tres" "vinte e três" (number 23) "24" "vinte e quatro" "duas dúzias" "duas duzias" (number 24) "50" "cinquenta" "cinqüenta" "cincoenta" (number 50) "setenta" (number 70) "setenta e oito" (number 78) "oitenta" (number 80) "33" "trinta e três" "trinta e tres" (number 33) "1,1" "1,10" "01,10" (number 1.1) "0,77" ",77" (number 0.77) "100.000" "100000" "100K" "100k" (number 100000) "100" "cem" (number 100) "243" (number 243) "trezentos" (number 300) "3M" "3000K" "3000000" "3.000.000" (number 3000000) "1.200.000" "1200000" "1,2M" "1200K" ",0012G" (number 1200000) "- 1.200.000" "-1200000" "menos 1.200.000" "-1,2M" "-1200K" "-,0012G" (number -1200000) "1 ponto cinco" "um ponto cinco" "1,5" (number 1.5) )
true
(; Context map {} "1" "um" "uma" (number 1) "2" "dois" "duas" (number 2) "3" "três" "tres" (number 3) "6" "seis" (number 6) "11" "onze" (number 11) "12" "doze" "uma dúzia" "uma duzia" (number 12) "14" "catorze" "quatorze" (number 14) "16" "dePI:NAME:<NAME>END_PI" "dezPI:NAME:<NAME>END_PI" (number 16) "17" "dePI:NAME:<NAME>END_PIe" "PI:NAME:<NAME>END_PI" (number 17) "18" "dezoito" (number 18) "19" "dezenove" "dezanove" (number 19) "21" "vinte e um" (number 21) "23" "vinte e tres" "vinte e três" (number 23) "24" "vinte e quatro" "duas dúzias" "duas duzias" (number 24) "50" "cinquenta" "cinqüenta" "cincoenta" (number 50) "setenta" (number 70) "setenta e oito" (number 78) "oitenta" (number 80) "33" "trinta e três" "trinta e tres" (number 33) "1,1" "1,10" "01,10" (number 1.1) "0,77" ",77" (number 0.77) "100.000" "100000" "100K" "100k" (number 100000) "100" "cem" (number 100) "243" (number 243) "trezentos" (number 300) "3M" "3000K" "3000000" "3.000.000" (number 3000000) "1.200.000" "1200000" "1,2M" "1200K" ",0012G" (number 1200000) "- 1.200.000" "-1200000" "menos 1.200.000" "-1,2M" "-1200K" "-,0012G" (number -1200000) "1 ponto cinco" "um ponto cinco" "1,5" (number 1.5) )
[ { "context": "ge/include-js \"/lsnet/js/public.js\")\n [:title \"Laura Shaffer - Independent Beauty Consultant\"]]\n [:body\n ", "end": 352, "score": 0.9997392892837524, "start": 339, "tag": "NAME", "value": "Laura Shaffer" }, { "context": "tant\"]]\n [:body\n [:div#info\n [:h1#title \"Laura Shaffer - Independent Beauty Consultant\"]\n [:h3#conta", "end": 443, "score": 0.9997437596321106, "start": 430, "tag": "NAME", "value": "Laura Shaffer" }, { "context": "onsultant\"]\n [:h3#contact-info \"940-595-1437 | laurashaffer@marykay.com\"]]\n [:div#main \n [:div#login\n [:h3 \"T", "end": 541, "score": 0.9999307990074158, "start": 517, "tag": "EMAIL", "value": "laurashaffer@marykay.com" }, { "context": "ck \"userCheck()\"]\n [:div#info\n [:h1#title \"Laura Shaffer - Independent Beauty Consultant\"]\n [:h3#conta", "end": 1513, "score": 0.999883770942688, "start": 1500, "tag": "NAME", "value": "Laura Shaffer" }, { "context": "onsultant\"]\n [:h3#contact-info \"940-595-1437 | laurashaffer@marykay.com\"]]\n [:div#main\n [:div.content\n [:div.", "end": 1611, "score": 0.999930202960968, "start": 1587, "tag": "EMAIL", "value": "laurashaffer@marykay.com" }, { "context": " [:input#user_name {:type \"text\" :value \"\" :name \"user_name\"}]]\n [:p \"Password:\"\n [:input#user_password ", "end": 10923, "score": 0.9972488880157471, "start": 10914, "tag": "USERNAME", "value": "user_name" }, { "context": "#user_password {:type \"password\" :value \"\" :name \"user_password\"}]]\n body])\n\n(def add-user-form \n [:div \n ", "end": 11021, "score": 0.7388486862182617, "start": 11008, "tag": "PASSWORD", "value": "user_password" } ]
data/train/clojure/8b6598ffe611a4e29f757f8c4d1000b07737ca08page.clj
harshp8l/deep-learning-lang-detection
84
(ns lsnet.page (:require [hiccup.core :as h] [hiccup.page :as page])) (defn layout [& body] (page/html5 [:head (page/include-css "/lsnet/css/stylesheet.css") (page/include-js "/js/jquery-1.10.2.min.js") (page/include-js "/lsnet/js/jquery.cookie.js") (page/include-js "/lsnet/js/public.js") [:title "Laura Shaffer - Independent Beauty Consultant"]] [:body [:div#info [:h1#title "Laura Shaffer - Independent Beauty Consultant"] [:h3#contact-info "940-595-1437 | laurashaffer@marykay.com"]] [:div#main [:div#login [:h3 "To see my sales, enter the 'special' password below"] [:form [:input#password {:type "text" :required "" :name "password"}] [:input#submit {:type "submit" :onclick "checkLogin()" :value "Submit"}]]] [:h2.line {:style "display:inline-block"} "Welcome to my Mary Kay clearance list!"] [:div.content body]]])) (defn menu-item [link text] [:div.cont20 [:a {:href link} [:h4 text]]]) (defn layout-admin [& body] (page/html5 [:head (page/include-js "/js/jquery-1.10.2.min.js") (page/include-js "/lsnet/js/jquery.cookie.js") (page/include-js "/lsnet/js/javascript.js") (page/include-js "/lsnet/js/md5.js") (page/include-js "/lsnet/js/user-secure.js") (page/include-css "/lsnet/css/stylesheet.css") [:title "Laura Shaffer - Independent Beauty Consultant"]] [:body [:script#user-check "userCheck()"] [:div#info [:h1#title "Laura Shaffer - Independent Beauty Consultant"] [:h3#contact-info "940-595-1437 | laurashaffer@marykay.com"]] [:div#main [:div.content [:div.pair (menu-item "/staff" "Admin Home") (menu-item "/admin-products" "List Products") (menu-item "/new-product" "New Product") (menu-item "/categories" "Categories") (menu-item "/" "Public View") (menu-item "/header-footer" "Header/Footer")]] body]])) (def front [:h4 "hello world"]) (defn form-inputs [name text content] [:div [:label {:for name} [:span text]] [:input {:type "text" :name name :size "60" :id name :value content}] [:br] [:br]]) (defn visibility-input [] [:p#visibility-input "Visible: " [:input {:type "radio" :value "0" :name "visible"}] "No " [:input {:type "radio" :checked "" :value "1" :name "visible"}] "Yes"]) (defn edit-visibility-input [visibility] [:p#visibility-input "Visible: " [:input (if (= visibility 0) {:type "radio" :value "0" :checked "" :name "visible"} {:type "radio" :value "0" :name "visible"})] "No " [:input (if (= visibility 1) {:type "radio" :value "1" :checked "" :name "visible"} {:type "radio" :value "1" :name "visible"})] "Yes"]) (defn product-form [categories] [:div [:h2 "New Product"] [:form [:fieldset (form-inputs "images" "Image Url" "") (form-inputs "product-title" "Product Title" "") (form-inputs "content" "Description" "") (form-inputs "newprice" "Discounted Price" "") (form-inputs "normprice" "Original Price" "") (form-inputs "quantity" "Inventory" "") (form-inputs "sku" "SKU" "") (form-inputs "custom" "Custom Category" "") [:span "Category" [:select#category {:name "category"} (let [categories (sort-by :position categories) cat-op-fn (fn [category] [:option (:category category)])] (map cat-op-fn categories))]] (visibility-input) [:br] [:div#log] [:br] [:input {:type "button" :value "Submit" :style "clear:both" :onclick "saveProduct()"}]]]]) (defn edit-product-form [categories product] (let [title (:title product) id (:_id product) img-src (:images product) uri (first (:uris product)) description (:content-html product) norm (:normprice product) new (:newprice product) op (if (> (count norm) 0) (read-string norm) "NaN") pp (if (> (count new) 0) (read-string new) "NaN") original-price (if (number? op) (str "$" (format "%.2f" (float op)))) product-price (if (number? pp) (str "$" (format "%.2f" (float pp)))) discount (if (and (number? op) (number? pp)) (let [old (read-string (:normprice product)) new (read-string (:newprice product))] (str "$" (format "%.2f" (float (- old new))) " (" (- 100 (int (* (/ new old) 100))) "%)"))) stock (:quantity product) sku (:sku product) visibility (read-string (:visible product)) custom (:custom product) product-category (:category product) categories (sort-by :position categories)] [:div [:h2 "Edit Product"] [:form [:fieldset (form-inputs "images" "Image Url" img-src) (form-inputs "product-title" "Product Title" title) (form-inputs "content" "Description" description) (form-inputs "newprice" "Discounted Price" new) (form-inputs "normprice" "Original Price" norm) (form-inputs "quantity" "Inventory" stock) (form-inputs "sku" "SKU" sku) (form-inputs "custom" "Custom Category" custom) [:span "Category" [:select#category {:name "category"} (let [cat-op-fn (fn [category] [:option (if (= (:category category) product-category) {:selected "selected"}) (:category category)])] (map cat-op-fn categories))]] (edit-visibility-input visibility) [:br] [:div#log] [:br] [:input {:type "button" :value "Submit" :style "clear:both" :onclick (str "updateProduct('" id "')")}]]]])) (defn list-categories [categories] [:ul.categories.compact (let [categories (sort-by :position categories) cat-item (fn [category] (let [name (:category category) uri (:uri category) id (:_id category)] [:li [:div.cont50.text-left [:a {:href (str "/edit-category/" id)} name]] [:div.cont50.text-right [:a.delete-headerfooter {:onclick "return confirm('Are you sure?')" :href (str "/delete-category/" id)} "Delete Category"]] [:hr {:style "height:1px;border:none;color:#ccc;background-coloe:#ccc"}]]))] (map cat-item categories))]) (defn position-input [m stop-value f] [:p "Position:" [:select#position {:name "position"} (let [options (range 1 (+ (count m) (f 1 1))) op-fn (fn [n] [:option (if (= n (f (read-string (str stop-value)) 1)) {:selected "selected"}) n])] (map op-fn options))]]) (defn category-template [categories] [:div [:h2 "Categories"] [:a {:href "/categories"} "New Category"] " | " [:a {:href "/sort-cats-abc"} "Sort Alphabetically"] (list-categories categories) [:h2 "Add Category"] [:a {:href "/categories"} "New Category"] [:form [:p "Category name:" [:input#category_name {:type "text" :value "" :name "category_name"}]] (position-input categories (count categories) +) (visibility-input) [:br] [:input {:type "button" :value "Add Category" :onclick "saveCategory()"}]] [:a {:href "/categories"} "Cancel"]]) (defn category-edit-template [categories category] (let [visibility (read-string (:visible category)) name (:category category) id (:_id category)] [:div [:h2 "Categories"] [:a {:href "/categories"} "New Category"] " | " [:a {:href "/sort-cats-abc"} "Sort Alphabetically"] (list-categories categories) [:h2 "Edit Category"] [:a {:href "/categories"} "New Category"] [:form [:p "Category name:" [:input#category_name {:type "text" :value name :name "category_name"}]] (position-input categories (:position category) /) (edit-visibility-input visibility) [:br] [:input {:type "button" :value "Update Category" :onclick (str "updateCategory('" id "')")}]] [:a {:href "/categories"} "Cancel"]])) (defn list-links [link-text] (for [[a b] link-text] [:li [:a {:href a} b]])) (def staff-page-home [:div [:h2 "Staff Menu"] [:p#staff-welcome] [:script "staffWelcome()"] [:ul#staff-home-menu (list-links [["/admin-products" "Manage Products"] ["/categories" "Manage Categories"] ["/header-footer" "Manage Header/Footer"] ["/new-user" "Add Staff User"] ["/new-product" "New Product"]]) [:li [:a {:onclick "logoutUser()"} "Logout"]]]]) (defn product-template-core [product] (let [title (:title product) id (:_id product) img-src (:images product) uri (first (:uris product)) description (:content-html product) norm (:normprice product) new (:newprice product) op (if (> (count norm) 0) (read-string norm) "NaN") pp (if (> (count new) 0) (read-string new) "NaN") original-price (if (number? op) (str "$" (format "%.2f" (float op)))) product-price (if (number? pp) (str "$" (format "%.2f" (float pp)))) discount (if (and (number? op) (number? pp)) (let [old (read-string (:normprice product)) new (read-string (:newprice product))] (str "$" (format "%.2f" (float (- old new))) " (" (- 100 (int (* (/ new old) 100))) "%)"))) stock (:quantity product) sku (:sku product)] [:div.product-details [:img.product-image {:title title :alt title :src img-src}] [:p.product-title title] [:p.product-description description] [:p.original-product-price [:span.price-text (if (number? op) "Retail Price: ")] [:del original-price]] [:p.product-price [:span.price-text (if (number? pp) "Price: ")] product-price] [:p.percent-off [:span.price-text (if (and (number? op) (number? pp)) "You Save: ")] discount] [:p.product-stock stock] [:p.product-sku sku]])) (defn product-template [product] (let [id (:_id product) visibility (read-string (:visible product)) mail-id (apply str (map #(str %) (take 5 id)))] [:div.cont33.product-cont.product-list-item {:onclick (str "emailForm('" mail-id "')") :id mail-id} (product-template-core product)])) (defn admin-product-template [product] (let [id (:_id product)] [:div.cont33.product-cont.product-list-item (product-template-core product) [:div#admin-options [:p.product-edit [:a.product-edit-link {:href (str "/view-product/" id)} "Edit Product"]] [:a {:onclick "return confirm('Are you sure?')" :href (str "/delete-product/" id)} "Delete Product"]]])) (defn login-input-template [& body] [:form#login-form [:p "Username:" [:input#user_name {:type "text" :value "" :name "user_name"}]] [:p "Password:" [:input#user_password {:type "password" :value "" :name "user_password"}]] body]) (def add-user-form [:div [:h2 "New Admin"] (login-input-template [:p "Confirm Password:" [:input#user_confirm_password {:type "password" :value "" :name "user_confirm_password"}]] [:p#login_error] [:input {:type "button" :value "Submit" :onclick "checkSend()"}])]) (def login-form [:div (page/include-css "/lsnet/css/login.css") (page/include-js "/lsnet/js/javascript.js") (page/include-js "/lsnet/js/md5.js") [:h2#lheader "Admin Login"] (login-input-template [:p#login_error] [:input {:type "button" :value "Login" :onclick "loginUser()"}])]) (defn header-footer-template [header-footer] (let [id (:_id header-footer) content (:content header-footer) cont-id (apply str (map #(str %) (take 5 id)))] [:div.header-footer-list-item [:a.header-footer-toggle {:onclick (str "toggleElement('" cont-id "')")} "Minimize/Maximize"] [:div {:id cont-id} [:div#admin-options [:li [:div.cont50.text-left [:a {:href (str "/edit-header-footer/" id)} "Edit"]] [:div.cont50.text-right [:a.delete-headerfooter {:onclick "return confirm('Are you sure?')" :href (str "/delete-header-footer/" id)} "Delete"]] [:hr {:style "height:1px;border:none;color:#ccc;background-coloe:#ccc"}]]] [:p.header-footer content]]])) (defn header-footer-form [header-footers] [:div (page/include-js "http://js.nicedit.com/nicEdit-latest.js") [:script "bkLib.onDomLoaded(nicEditors.allTextAreas);"] (let [headers (remove nil? (map #(if (= "Top" (:location %)) %) header-footers)) footers (remove nil? (map #(if (= "Bottom" (:location %)) %) header-footers))] [:ul.header-footers.compact [:div#headers [:h2 "Headers"] (let [headers (sort-by :position headers)] (map header-footer-template headers)) [:h2 "New Header"] [:a {:href "/header-footer#headerform"} "New Header"] [:form#headerform.headerfooterform [:div.nctext [:div.nctextlatch] [:textarea#hfcontent {:value "" :name "hfcontent"}]] (visibility-input) (position-input headers (count headers) +) [:input {:type "button" :value "Submit" :onclick "saveHeader()"}]]] [:div#footers [:h2 "Footers"] (let [footers (sort-by :position footers)] (map header-footer-template footers)) [:h2 "New Footer"] [:a {:href "/header-footer#footerform"} "New Footer"] [:form#footerform.headerfooterform [:div.nctext [:div.nctextlatch] [:textarea#hfcontent {:value "" :name "hfcontent"}]] (visibility-input) (position-input footers (count footers) +) [:input {:type "button" :value "Submit" :onclick "saveFooter()"}]]]])]) (defn edit-header-footer-form [header-footers header-footer] (let [id (:_id header-footer) visibility (read-string (:visible header-footer)) location (:location header-footer) content (:content header-footer)] [:div (page/include-js "http://js.nicedit.com/nicEdit-latest.js") [:script "bkLib.onDomLoaded(nicEditors.allTextAreas);"] (let [headers (remove nil? (map #(if (= "Top" (:location %)) %) header-footers)) footers (remove nil? (map #(if (= "Bottom" (:location %)) %) header-footers))] [:ul.header-footers.compact [:div#headers [:h2 "Headers"] (let [headers (sort-by :position headers)] (map header-footer-template headers)) [:h2 "Edit Header"] [:a {:href "/header-footer#headerform"} "New Header"] (if (= "Top" location) [:div [:form#headerform.headerfooterform [:div.nctext [:div.nctextlatch] [:textarea#hfcontent {:value "" :name "hfcontent"} content]] (edit-visibility-input visibility) (position-input headers (:position header-footer) /) [:input {:type "button" :value "Submit" :onclick (str "updateHeader('" id "')")}] [:script (str "$(document).ready(function(){$('#headerform .nicEdit-main').html('" content "');});")]]])] [:div#footers [:h2 "Footers"] (let [footers (sort-by :position footers)] (map header-footer-template footers)) [:h2 "Edit Footer"] [:a {:href "/header-footer#footerform"} "New Footer"] (if (= "Bottom" location) [:div [:form#footerform.headerfooterform [:div.nctext [:div.nctextlatch] [:textarea#hfcontent {:value "" :name "hfcontent"} content]] (edit-visibility-input visibility) (position-input footers (:position header-footer) /) [:input {:type "button" :value "Submit" :onclick (str "updateFooter('" id "')")}]]])]])])) (defn admin-products-by-category [f products categories] (let [categories (sort-by :position categories) prod-fn (fn [category] (filter #(= category (:category %)) products)) cat-fn (fn [category] (let [cat-name (:category category) cat-products (prod-fn cat-name) visibility (:visible category)] [:div.category [:h1 {:style "clear:both"} cat-name] (f cat-products)]))] (map cat-fn categories))) (defn products-by-category [f products categories] (let [products (filter #(= "1" (:visible %)) products) categories (filter (fn [category] (> (count (filter #(= (:category category) (:category %)) products)) 0)) categories)] (admin-products-by-category f products categories))) (defn front-page-headers [hfs] (let [headers (sort-by :position (filter #(= "Top" (:location %)) hfs))] [:div#headers-cont (map #(if (not (= "0" (:visible %))) [:div.header (:content %)]) headers)])) (defn front-page-footers [hfs] (let [footers (sort-by :position (filter #(= "Bottom" (:location %)) hfs))] [:div#footers-cont (map #(if (not (= "0" (:visible %))) [:div.footer (:content %)]) footers)])) (defn header-footer-page [request header-footer] (layout-admin (header-footer-form header-footer))) (defn edit-header-footer-page [request header-footer header-footers] (layout-admin (edit-header-footer-form header-footers header-footer))) (defn product-list-xform [products] (map product-template products)) (defn admin-product-list-xform [products] (map admin-product-template products)) (defn front-page [request products categories header-footers] (layout (front-page-headers header-footers) (products-by-category product-list-xform products categories) (front-page-footers header-footers))) (defn admin-home [request] (layout-admin staff-page-home)) (defn new-product-page [request categories] (layout-admin (product-form categories))) (defn edit-product-page [request product categories] (layout-admin (product-template product) (edit-product-form categories product))) (defn categories-page [request categories] (layout-admin (category-template categories))) (defn admin-products [request products categories] (layout-admin (admin-products-by-category admin-product-list-xform products categories))) (defn edit-category-page [request category categories] (layout-admin (category-edit-template categories category))) (defn new-user-page [request] (layout-admin add-user-form)) (defn login-page [request] (layout login-form))
32044
(ns lsnet.page (:require [hiccup.core :as h] [hiccup.page :as page])) (defn layout [& body] (page/html5 [:head (page/include-css "/lsnet/css/stylesheet.css") (page/include-js "/js/jquery-1.10.2.min.js") (page/include-js "/lsnet/js/jquery.cookie.js") (page/include-js "/lsnet/js/public.js") [:title "<NAME> - Independent Beauty Consultant"]] [:body [:div#info [:h1#title "<NAME> - Independent Beauty Consultant"] [:h3#contact-info "940-595-1437 | <EMAIL>"]] [:div#main [:div#login [:h3 "To see my sales, enter the 'special' password below"] [:form [:input#password {:type "text" :required "" :name "password"}] [:input#submit {:type "submit" :onclick "checkLogin()" :value "Submit"}]]] [:h2.line {:style "display:inline-block"} "Welcome to my Mary Kay clearance list!"] [:div.content body]]])) (defn menu-item [link text] [:div.cont20 [:a {:href link} [:h4 text]]]) (defn layout-admin [& body] (page/html5 [:head (page/include-js "/js/jquery-1.10.2.min.js") (page/include-js "/lsnet/js/jquery.cookie.js") (page/include-js "/lsnet/js/javascript.js") (page/include-js "/lsnet/js/md5.js") (page/include-js "/lsnet/js/user-secure.js") (page/include-css "/lsnet/css/stylesheet.css") [:title "Laura Shaffer - Independent Beauty Consultant"]] [:body [:script#user-check "userCheck()"] [:div#info [:h1#title "<NAME> - Independent Beauty Consultant"] [:h3#contact-info "940-595-1437 | <EMAIL>"]] [:div#main [:div.content [:div.pair (menu-item "/staff" "Admin Home") (menu-item "/admin-products" "List Products") (menu-item "/new-product" "New Product") (menu-item "/categories" "Categories") (menu-item "/" "Public View") (menu-item "/header-footer" "Header/Footer")]] body]])) (def front [:h4 "hello world"]) (defn form-inputs [name text content] [:div [:label {:for name} [:span text]] [:input {:type "text" :name name :size "60" :id name :value content}] [:br] [:br]]) (defn visibility-input [] [:p#visibility-input "Visible: " [:input {:type "radio" :value "0" :name "visible"}] "No " [:input {:type "radio" :checked "" :value "1" :name "visible"}] "Yes"]) (defn edit-visibility-input [visibility] [:p#visibility-input "Visible: " [:input (if (= visibility 0) {:type "radio" :value "0" :checked "" :name "visible"} {:type "radio" :value "0" :name "visible"})] "No " [:input (if (= visibility 1) {:type "radio" :value "1" :checked "" :name "visible"} {:type "radio" :value "1" :name "visible"})] "Yes"]) (defn product-form [categories] [:div [:h2 "New Product"] [:form [:fieldset (form-inputs "images" "Image Url" "") (form-inputs "product-title" "Product Title" "") (form-inputs "content" "Description" "") (form-inputs "newprice" "Discounted Price" "") (form-inputs "normprice" "Original Price" "") (form-inputs "quantity" "Inventory" "") (form-inputs "sku" "SKU" "") (form-inputs "custom" "Custom Category" "") [:span "Category" [:select#category {:name "category"} (let [categories (sort-by :position categories) cat-op-fn (fn [category] [:option (:category category)])] (map cat-op-fn categories))]] (visibility-input) [:br] [:div#log] [:br] [:input {:type "button" :value "Submit" :style "clear:both" :onclick "saveProduct()"}]]]]) (defn edit-product-form [categories product] (let [title (:title product) id (:_id product) img-src (:images product) uri (first (:uris product)) description (:content-html product) norm (:normprice product) new (:newprice product) op (if (> (count norm) 0) (read-string norm) "NaN") pp (if (> (count new) 0) (read-string new) "NaN") original-price (if (number? op) (str "$" (format "%.2f" (float op)))) product-price (if (number? pp) (str "$" (format "%.2f" (float pp)))) discount (if (and (number? op) (number? pp)) (let [old (read-string (:normprice product)) new (read-string (:newprice product))] (str "$" (format "%.2f" (float (- old new))) " (" (- 100 (int (* (/ new old) 100))) "%)"))) stock (:quantity product) sku (:sku product) visibility (read-string (:visible product)) custom (:custom product) product-category (:category product) categories (sort-by :position categories)] [:div [:h2 "Edit Product"] [:form [:fieldset (form-inputs "images" "Image Url" img-src) (form-inputs "product-title" "Product Title" title) (form-inputs "content" "Description" description) (form-inputs "newprice" "Discounted Price" new) (form-inputs "normprice" "Original Price" norm) (form-inputs "quantity" "Inventory" stock) (form-inputs "sku" "SKU" sku) (form-inputs "custom" "Custom Category" custom) [:span "Category" [:select#category {:name "category"} (let [cat-op-fn (fn [category] [:option (if (= (:category category) product-category) {:selected "selected"}) (:category category)])] (map cat-op-fn categories))]] (edit-visibility-input visibility) [:br] [:div#log] [:br] [:input {:type "button" :value "Submit" :style "clear:both" :onclick (str "updateProduct('" id "')")}]]]])) (defn list-categories [categories] [:ul.categories.compact (let [categories (sort-by :position categories) cat-item (fn [category] (let [name (:category category) uri (:uri category) id (:_id category)] [:li [:div.cont50.text-left [:a {:href (str "/edit-category/" id)} name]] [:div.cont50.text-right [:a.delete-headerfooter {:onclick "return confirm('Are you sure?')" :href (str "/delete-category/" id)} "Delete Category"]] [:hr {:style "height:1px;border:none;color:#ccc;background-coloe:#ccc"}]]))] (map cat-item categories))]) (defn position-input [m stop-value f] [:p "Position:" [:select#position {:name "position"} (let [options (range 1 (+ (count m) (f 1 1))) op-fn (fn [n] [:option (if (= n (f (read-string (str stop-value)) 1)) {:selected "selected"}) n])] (map op-fn options))]]) (defn category-template [categories] [:div [:h2 "Categories"] [:a {:href "/categories"} "New Category"] " | " [:a {:href "/sort-cats-abc"} "Sort Alphabetically"] (list-categories categories) [:h2 "Add Category"] [:a {:href "/categories"} "New Category"] [:form [:p "Category name:" [:input#category_name {:type "text" :value "" :name "category_name"}]] (position-input categories (count categories) +) (visibility-input) [:br] [:input {:type "button" :value "Add Category" :onclick "saveCategory()"}]] [:a {:href "/categories"} "Cancel"]]) (defn category-edit-template [categories category] (let [visibility (read-string (:visible category)) name (:category category) id (:_id category)] [:div [:h2 "Categories"] [:a {:href "/categories"} "New Category"] " | " [:a {:href "/sort-cats-abc"} "Sort Alphabetically"] (list-categories categories) [:h2 "Edit Category"] [:a {:href "/categories"} "New Category"] [:form [:p "Category name:" [:input#category_name {:type "text" :value name :name "category_name"}]] (position-input categories (:position category) /) (edit-visibility-input visibility) [:br] [:input {:type "button" :value "Update Category" :onclick (str "updateCategory('" id "')")}]] [:a {:href "/categories"} "Cancel"]])) (defn list-links [link-text] (for [[a b] link-text] [:li [:a {:href a} b]])) (def staff-page-home [:div [:h2 "Staff Menu"] [:p#staff-welcome] [:script "staffWelcome()"] [:ul#staff-home-menu (list-links [["/admin-products" "Manage Products"] ["/categories" "Manage Categories"] ["/header-footer" "Manage Header/Footer"] ["/new-user" "Add Staff User"] ["/new-product" "New Product"]]) [:li [:a {:onclick "logoutUser()"} "Logout"]]]]) (defn product-template-core [product] (let [title (:title product) id (:_id product) img-src (:images product) uri (first (:uris product)) description (:content-html product) norm (:normprice product) new (:newprice product) op (if (> (count norm) 0) (read-string norm) "NaN") pp (if (> (count new) 0) (read-string new) "NaN") original-price (if (number? op) (str "$" (format "%.2f" (float op)))) product-price (if (number? pp) (str "$" (format "%.2f" (float pp)))) discount (if (and (number? op) (number? pp)) (let [old (read-string (:normprice product)) new (read-string (:newprice product))] (str "$" (format "%.2f" (float (- old new))) " (" (- 100 (int (* (/ new old) 100))) "%)"))) stock (:quantity product) sku (:sku product)] [:div.product-details [:img.product-image {:title title :alt title :src img-src}] [:p.product-title title] [:p.product-description description] [:p.original-product-price [:span.price-text (if (number? op) "Retail Price: ")] [:del original-price]] [:p.product-price [:span.price-text (if (number? pp) "Price: ")] product-price] [:p.percent-off [:span.price-text (if (and (number? op) (number? pp)) "You Save: ")] discount] [:p.product-stock stock] [:p.product-sku sku]])) (defn product-template [product] (let [id (:_id product) visibility (read-string (:visible product)) mail-id (apply str (map #(str %) (take 5 id)))] [:div.cont33.product-cont.product-list-item {:onclick (str "emailForm('" mail-id "')") :id mail-id} (product-template-core product)])) (defn admin-product-template [product] (let [id (:_id product)] [:div.cont33.product-cont.product-list-item (product-template-core product) [:div#admin-options [:p.product-edit [:a.product-edit-link {:href (str "/view-product/" id)} "Edit Product"]] [:a {:onclick "return confirm('Are you sure?')" :href (str "/delete-product/" id)} "Delete Product"]]])) (defn login-input-template [& body] [:form#login-form [:p "Username:" [:input#user_name {:type "text" :value "" :name "user_name"}]] [:p "Password:" [:input#user_password {:type "password" :value "" :name "<PASSWORD>"}]] body]) (def add-user-form [:div [:h2 "New Admin"] (login-input-template [:p "Confirm Password:" [:input#user_confirm_password {:type "password" :value "" :name "user_confirm_password"}]] [:p#login_error] [:input {:type "button" :value "Submit" :onclick "checkSend()"}])]) (def login-form [:div (page/include-css "/lsnet/css/login.css") (page/include-js "/lsnet/js/javascript.js") (page/include-js "/lsnet/js/md5.js") [:h2#lheader "Admin Login"] (login-input-template [:p#login_error] [:input {:type "button" :value "Login" :onclick "loginUser()"}])]) (defn header-footer-template [header-footer] (let [id (:_id header-footer) content (:content header-footer) cont-id (apply str (map #(str %) (take 5 id)))] [:div.header-footer-list-item [:a.header-footer-toggle {:onclick (str "toggleElement('" cont-id "')")} "Minimize/Maximize"] [:div {:id cont-id} [:div#admin-options [:li [:div.cont50.text-left [:a {:href (str "/edit-header-footer/" id)} "Edit"]] [:div.cont50.text-right [:a.delete-headerfooter {:onclick "return confirm('Are you sure?')" :href (str "/delete-header-footer/" id)} "Delete"]] [:hr {:style "height:1px;border:none;color:#ccc;background-coloe:#ccc"}]]] [:p.header-footer content]]])) (defn header-footer-form [header-footers] [:div (page/include-js "http://js.nicedit.com/nicEdit-latest.js") [:script "bkLib.onDomLoaded(nicEditors.allTextAreas);"] (let [headers (remove nil? (map #(if (= "Top" (:location %)) %) header-footers)) footers (remove nil? (map #(if (= "Bottom" (:location %)) %) header-footers))] [:ul.header-footers.compact [:div#headers [:h2 "Headers"] (let [headers (sort-by :position headers)] (map header-footer-template headers)) [:h2 "New Header"] [:a {:href "/header-footer#headerform"} "New Header"] [:form#headerform.headerfooterform [:div.nctext [:div.nctextlatch] [:textarea#hfcontent {:value "" :name "hfcontent"}]] (visibility-input) (position-input headers (count headers) +) [:input {:type "button" :value "Submit" :onclick "saveHeader()"}]]] [:div#footers [:h2 "Footers"] (let [footers (sort-by :position footers)] (map header-footer-template footers)) [:h2 "New Footer"] [:a {:href "/header-footer#footerform"} "New Footer"] [:form#footerform.headerfooterform [:div.nctext [:div.nctextlatch] [:textarea#hfcontent {:value "" :name "hfcontent"}]] (visibility-input) (position-input footers (count footers) +) [:input {:type "button" :value "Submit" :onclick "saveFooter()"}]]]])]) (defn edit-header-footer-form [header-footers header-footer] (let [id (:_id header-footer) visibility (read-string (:visible header-footer)) location (:location header-footer) content (:content header-footer)] [:div (page/include-js "http://js.nicedit.com/nicEdit-latest.js") [:script "bkLib.onDomLoaded(nicEditors.allTextAreas);"] (let [headers (remove nil? (map #(if (= "Top" (:location %)) %) header-footers)) footers (remove nil? (map #(if (= "Bottom" (:location %)) %) header-footers))] [:ul.header-footers.compact [:div#headers [:h2 "Headers"] (let [headers (sort-by :position headers)] (map header-footer-template headers)) [:h2 "Edit Header"] [:a {:href "/header-footer#headerform"} "New Header"] (if (= "Top" location) [:div [:form#headerform.headerfooterform [:div.nctext [:div.nctextlatch] [:textarea#hfcontent {:value "" :name "hfcontent"} content]] (edit-visibility-input visibility) (position-input headers (:position header-footer) /) [:input {:type "button" :value "Submit" :onclick (str "updateHeader('" id "')")}] [:script (str "$(document).ready(function(){$('#headerform .nicEdit-main').html('" content "');});")]]])] [:div#footers [:h2 "Footers"] (let [footers (sort-by :position footers)] (map header-footer-template footers)) [:h2 "Edit Footer"] [:a {:href "/header-footer#footerform"} "New Footer"] (if (= "Bottom" location) [:div [:form#footerform.headerfooterform [:div.nctext [:div.nctextlatch] [:textarea#hfcontent {:value "" :name "hfcontent"} content]] (edit-visibility-input visibility) (position-input footers (:position header-footer) /) [:input {:type "button" :value "Submit" :onclick (str "updateFooter('" id "')")}]]])]])])) (defn admin-products-by-category [f products categories] (let [categories (sort-by :position categories) prod-fn (fn [category] (filter #(= category (:category %)) products)) cat-fn (fn [category] (let [cat-name (:category category) cat-products (prod-fn cat-name) visibility (:visible category)] [:div.category [:h1 {:style "clear:both"} cat-name] (f cat-products)]))] (map cat-fn categories))) (defn products-by-category [f products categories] (let [products (filter #(= "1" (:visible %)) products) categories (filter (fn [category] (> (count (filter #(= (:category category) (:category %)) products)) 0)) categories)] (admin-products-by-category f products categories))) (defn front-page-headers [hfs] (let [headers (sort-by :position (filter #(= "Top" (:location %)) hfs))] [:div#headers-cont (map #(if (not (= "0" (:visible %))) [:div.header (:content %)]) headers)])) (defn front-page-footers [hfs] (let [footers (sort-by :position (filter #(= "Bottom" (:location %)) hfs))] [:div#footers-cont (map #(if (not (= "0" (:visible %))) [:div.footer (:content %)]) footers)])) (defn header-footer-page [request header-footer] (layout-admin (header-footer-form header-footer))) (defn edit-header-footer-page [request header-footer header-footers] (layout-admin (edit-header-footer-form header-footers header-footer))) (defn product-list-xform [products] (map product-template products)) (defn admin-product-list-xform [products] (map admin-product-template products)) (defn front-page [request products categories header-footers] (layout (front-page-headers header-footers) (products-by-category product-list-xform products categories) (front-page-footers header-footers))) (defn admin-home [request] (layout-admin staff-page-home)) (defn new-product-page [request categories] (layout-admin (product-form categories))) (defn edit-product-page [request product categories] (layout-admin (product-template product) (edit-product-form categories product))) (defn categories-page [request categories] (layout-admin (category-template categories))) (defn admin-products [request products categories] (layout-admin (admin-products-by-category admin-product-list-xform products categories))) (defn edit-category-page [request category categories] (layout-admin (category-edit-template categories category))) (defn new-user-page [request] (layout-admin add-user-form)) (defn login-page [request] (layout login-form))
true
(ns lsnet.page (:require [hiccup.core :as h] [hiccup.page :as page])) (defn layout [& body] (page/html5 [:head (page/include-css "/lsnet/css/stylesheet.css") (page/include-js "/js/jquery-1.10.2.min.js") (page/include-js "/lsnet/js/jquery.cookie.js") (page/include-js "/lsnet/js/public.js") [:title "PI:NAME:<NAME>END_PI - Independent Beauty Consultant"]] [:body [:div#info [:h1#title "PI:NAME:<NAME>END_PI - Independent Beauty Consultant"] [:h3#contact-info "940-595-1437 | PI:EMAIL:<EMAIL>END_PI"]] [:div#main [:div#login [:h3 "To see my sales, enter the 'special' password below"] [:form [:input#password {:type "text" :required "" :name "password"}] [:input#submit {:type "submit" :onclick "checkLogin()" :value "Submit"}]]] [:h2.line {:style "display:inline-block"} "Welcome to my Mary Kay clearance list!"] [:div.content body]]])) (defn menu-item [link text] [:div.cont20 [:a {:href link} [:h4 text]]]) (defn layout-admin [& body] (page/html5 [:head (page/include-js "/js/jquery-1.10.2.min.js") (page/include-js "/lsnet/js/jquery.cookie.js") (page/include-js "/lsnet/js/javascript.js") (page/include-js "/lsnet/js/md5.js") (page/include-js "/lsnet/js/user-secure.js") (page/include-css "/lsnet/css/stylesheet.css") [:title "Laura Shaffer - Independent Beauty Consultant"]] [:body [:script#user-check "userCheck()"] [:div#info [:h1#title "PI:NAME:<NAME>END_PI - Independent Beauty Consultant"] [:h3#contact-info "940-595-1437 | PI:EMAIL:<EMAIL>END_PI"]] [:div#main [:div.content [:div.pair (menu-item "/staff" "Admin Home") (menu-item "/admin-products" "List Products") (menu-item "/new-product" "New Product") (menu-item "/categories" "Categories") (menu-item "/" "Public View") (menu-item "/header-footer" "Header/Footer")]] body]])) (def front [:h4 "hello world"]) (defn form-inputs [name text content] [:div [:label {:for name} [:span text]] [:input {:type "text" :name name :size "60" :id name :value content}] [:br] [:br]]) (defn visibility-input [] [:p#visibility-input "Visible: " [:input {:type "radio" :value "0" :name "visible"}] "No " [:input {:type "radio" :checked "" :value "1" :name "visible"}] "Yes"]) (defn edit-visibility-input [visibility] [:p#visibility-input "Visible: " [:input (if (= visibility 0) {:type "radio" :value "0" :checked "" :name "visible"} {:type "radio" :value "0" :name "visible"})] "No " [:input (if (= visibility 1) {:type "radio" :value "1" :checked "" :name "visible"} {:type "radio" :value "1" :name "visible"})] "Yes"]) (defn product-form [categories] [:div [:h2 "New Product"] [:form [:fieldset (form-inputs "images" "Image Url" "") (form-inputs "product-title" "Product Title" "") (form-inputs "content" "Description" "") (form-inputs "newprice" "Discounted Price" "") (form-inputs "normprice" "Original Price" "") (form-inputs "quantity" "Inventory" "") (form-inputs "sku" "SKU" "") (form-inputs "custom" "Custom Category" "") [:span "Category" [:select#category {:name "category"} (let [categories (sort-by :position categories) cat-op-fn (fn [category] [:option (:category category)])] (map cat-op-fn categories))]] (visibility-input) [:br] [:div#log] [:br] [:input {:type "button" :value "Submit" :style "clear:both" :onclick "saveProduct()"}]]]]) (defn edit-product-form [categories product] (let [title (:title product) id (:_id product) img-src (:images product) uri (first (:uris product)) description (:content-html product) norm (:normprice product) new (:newprice product) op (if (> (count norm) 0) (read-string norm) "NaN") pp (if (> (count new) 0) (read-string new) "NaN") original-price (if (number? op) (str "$" (format "%.2f" (float op)))) product-price (if (number? pp) (str "$" (format "%.2f" (float pp)))) discount (if (and (number? op) (number? pp)) (let [old (read-string (:normprice product)) new (read-string (:newprice product))] (str "$" (format "%.2f" (float (- old new))) " (" (- 100 (int (* (/ new old) 100))) "%)"))) stock (:quantity product) sku (:sku product) visibility (read-string (:visible product)) custom (:custom product) product-category (:category product) categories (sort-by :position categories)] [:div [:h2 "Edit Product"] [:form [:fieldset (form-inputs "images" "Image Url" img-src) (form-inputs "product-title" "Product Title" title) (form-inputs "content" "Description" description) (form-inputs "newprice" "Discounted Price" new) (form-inputs "normprice" "Original Price" norm) (form-inputs "quantity" "Inventory" stock) (form-inputs "sku" "SKU" sku) (form-inputs "custom" "Custom Category" custom) [:span "Category" [:select#category {:name "category"} (let [cat-op-fn (fn [category] [:option (if (= (:category category) product-category) {:selected "selected"}) (:category category)])] (map cat-op-fn categories))]] (edit-visibility-input visibility) [:br] [:div#log] [:br] [:input {:type "button" :value "Submit" :style "clear:both" :onclick (str "updateProduct('" id "')")}]]]])) (defn list-categories [categories] [:ul.categories.compact (let [categories (sort-by :position categories) cat-item (fn [category] (let [name (:category category) uri (:uri category) id (:_id category)] [:li [:div.cont50.text-left [:a {:href (str "/edit-category/" id)} name]] [:div.cont50.text-right [:a.delete-headerfooter {:onclick "return confirm('Are you sure?')" :href (str "/delete-category/" id)} "Delete Category"]] [:hr {:style "height:1px;border:none;color:#ccc;background-coloe:#ccc"}]]))] (map cat-item categories))]) (defn position-input [m stop-value f] [:p "Position:" [:select#position {:name "position"} (let [options (range 1 (+ (count m) (f 1 1))) op-fn (fn [n] [:option (if (= n (f (read-string (str stop-value)) 1)) {:selected "selected"}) n])] (map op-fn options))]]) (defn category-template [categories] [:div [:h2 "Categories"] [:a {:href "/categories"} "New Category"] " | " [:a {:href "/sort-cats-abc"} "Sort Alphabetically"] (list-categories categories) [:h2 "Add Category"] [:a {:href "/categories"} "New Category"] [:form [:p "Category name:" [:input#category_name {:type "text" :value "" :name "category_name"}]] (position-input categories (count categories) +) (visibility-input) [:br] [:input {:type "button" :value "Add Category" :onclick "saveCategory()"}]] [:a {:href "/categories"} "Cancel"]]) (defn category-edit-template [categories category] (let [visibility (read-string (:visible category)) name (:category category) id (:_id category)] [:div [:h2 "Categories"] [:a {:href "/categories"} "New Category"] " | " [:a {:href "/sort-cats-abc"} "Sort Alphabetically"] (list-categories categories) [:h2 "Edit Category"] [:a {:href "/categories"} "New Category"] [:form [:p "Category name:" [:input#category_name {:type "text" :value name :name "category_name"}]] (position-input categories (:position category) /) (edit-visibility-input visibility) [:br] [:input {:type "button" :value "Update Category" :onclick (str "updateCategory('" id "')")}]] [:a {:href "/categories"} "Cancel"]])) (defn list-links [link-text] (for [[a b] link-text] [:li [:a {:href a} b]])) (def staff-page-home [:div [:h2 "Staff Menu"] [:p#staff-welcome] [:script "staffWelcome()"] [:ul#staff-home-menu (list-links [["/admin-products" "Manage Products"] ["/categories" "Manage Categories"] ["/header-footer" "Manage Header/Footer"] ["/new-user" "Add Staff User"] ["/new-product" "New Product"]]) [:li [:a {:onclick "logoutUser()"} "Logout"]]]]) (defn product-template-core [product] (let [title (:title product) id (:_id product) img-src (:images product) uri (first (:uris product)) description (:content-html product) norm (:normprice product) new (:newprice product) op (if (> (count norm) 0) (read-string norm) "NaN") pp (if (> (count new) 0) (read-string new) "NaN") original-price (if (number? op) (str "$" (format "%.2f" (float op)))) product-price (if (number? pp) (str "$" (format "%.2f" (float pp)))) discount (if (and (number? op) (number? pp)) (let [old (read-string (:normprice product)) new (read-string (:newprice product))] (str "$" (format "%.2f" (float (- old new))) " (" (- 100 (int (* (/ new old) 100))) "%)"))) stock (:quantity product) sku (:sku product)] [:div.product-details [:img.product-image {:title title :alt title :src img-src}] [:p.product-title title] [:p.product-description description] [:p.original-product-price [:span.price-text (if (number? op) "Retail Price: ")] [:del original-price]] [:p.product-price [:span.price-text (if (number? pp) "Price: ")] product-price] [:p.percent-off [:span.price-text (if (and (number? op) (number? pp)) "You Save: ")] discount] [:p.product-stock stock] [:p.product-sku sku]])) (defn product-template [product] (let [id (:_id product) visibility (read-string (:visible product)) mail-id (apply str (map #(str %) (take 5 id)))] [:div.cont33.product-cont.product-list-item {:onclick (str "emailForm('" mail-id "')") :id mail-id} (product-template-core product)])) (defn admin-product-template [product] (let [id (:_id product)] [:div.cont33.product-cont.product-list-item (product-template-core product) [:div#admin-options [:p.product-edit [:a.product-edit-link {:href (str "/view-product/" id)} "Edit Product"]] [:a {:onclick "return confirm('Are you sure?')" :href (str "/delete-product/" id)} "Delete Product"]]])) (defn login-input-template [& body] [:form#login-form [:p "Username:" [:input#user_name {:type "text" :value "" :name "user_name"}]] [:p "Password:" [:input#user_password {:type "password" :value "" :name "PI:PASSWORD:<PASSWORD>END_PI"}]] body]) (def add-user-form [:div [:h2 "New Admin"] (login-input-template [:p "Confirm Password:" [:input#user_confirm_password {:type "password" :value "" :name "user_confirm_password"}]] [:p#login_error] [:input {:type "button" :value "Submit" :onclick "checkSend()"}])]) (def login-form [:div (page/include-css "/lsnet/css/login.css") (page/include-js "/lsnet/js/javascript.js") (page/include-js "/lsnet/js/md5.js") [:h2#lheader "Admin Login"] (login-input-template [:p#login_error] [:input {:type "button" :value "Login" :onclick "loginUser()"}])]) (defn header-footer-template [header-footer] (let [id (:_id header-footer) content (:content header-footer) cont-id (apply str (map #(str %) (take 5 id)))] [:div.header-footer-list-item [:a.header-footer-toggle {:onclick (str "toggleElement('" cont-id "')")} "Minimize/Maximize"] [:div {:id cont-id} [:div#admin-options [:li [:div.cont50.text-left [:a {:href (str "/edit-header-footer/" id)} "Edit"]] [:div.cont50.text-right [:a.delete-headerfooter {:onclick "return confirm('Are you sure?')" :href (str "/delete-header-footer/" id)} "Delete"]] [:hr {:style "height:1px;border:none;color:#ccc;background-coloe:#ccc"}]]] [:p.header-footer content]]])) (defn header-footer-form [header-footers] [:div (page/include-js "http://js.nicedit.com/nicEdit-latest.js") [:script "bkLib.onDomLoaded(nicEditors.allTextAreas);"] (let [headers (remove nil? (map #(if (= "Top" (:location %)) %) header-footers)) footers (remove nil? (map #(if (= "Bottom" (:location %)) %) header-footers))] [:ul.header-footers.compact [:div#headers [:h2 "Headers"] (let [headers (sort-by :position headers)] (map header-footer-template headers)) [:h2 "New Header"] [:a {:href "/header-footer#headerform"} "New Header"] [:form#headerform.headerfooterform [:div.nctext [:div.nctextlatch] [:textarea#hfcontent {:value "" :name "hfcontent"}]] (visibility-input) (position-input headers (count headers) +) [:input {:type "button" :value "Submit" :onclick "saveHeader()"}]]] [:div#footers [:h2 "Footers"] (let [footers (sort-by :position footers)] (map header-footer-template footers)) [:h2 "New Footer"] [:a {:href "/header-footer#footerform"} "New Footer"] [:form#footerform.headerfooterform [:div.nctext [:div.nctextlatch] [:textarea#hfcontent {:value "" :name "hfcontent"}]] (visibility-input) (position-input footers (count footers) +) [:input {:type "button" :value "Submit" :onclick "saveFooter()"}]]]])]) (defn edit-header-footer-form [header-footers header-footer] (let [id (:_id header-footer) visibility (read-string (:visible header-footer)) location (:location header-footer) content (:content header-footer)] [:div (page/include-js "http://js.nicedit.com/nicEdit-latest.js") [:script "bkLib.onDomLoaded(nicEditors.allTextAreas);"] (let [headers (remove nil? (map #(if (= "Top" (:location %)) %) header-footers)) footers (remove nil? (map #(if (= "Bottom" (:location %)) %) header-footers))] [:ul.header-footers.compact [:div#headers [:h2 "Headers"] (let [headers (sort-by :position headers)] (map header-footer-template headers)) [:h2 "Edit Header"] [:a {:href "/header-footer#headerform"} "New Header"] (if (= "Top" location) [:div [:form#headerform.headerfooterform [:div.nctext [:div.nctextlatch] [:textarea#hfcontent {:value "" :name "hfcontent"} content]] (edit-visibility-input visibility) (position-input headers (:position header-footer) /) [:input {:type "button" :value "Submit" :onclick (str "updateHeader('" id "')")}] [:script (str "$(document).ready(function(){$('#headerform .nicEdit-main').html('" content "');});")]]])] [:div#footers [:h2 "Footers"] (let [footers (sort-by :position footers)] (map header-footer-template footers)) [:h2 "Edit Footer"] [:a {:href "/header-footer#footerform"} "New Footer"] (if (= "Bottom" location) [:div [:form#footerform.headerfooterform [:div.nctext [:div.nctextlatch] [:textarea#hfcontent {:value "" :name "hfcontent"} content]] (edit-visibility-input visibility) (position-input footers (:position header-footer) /) [:input {:type "button" :value "Submit" :onclick (str "updateFooter('" id "')")}]]])]])])) (defn admin-products-by-category [f products categories] (let [categories (sort-by :position categories) prod-fn (fn [category] (filter #(= category (:category %)) products)) cat-fn (fn [category] (let [cat-name (:category category) cat-products (prod-fn cat-name) visibility (:visible category)] [:div.category [:h1 {:style "clear:both"} cat-name] (f cat-products)]))] (map cat-fn categories))) (defn products-by-category [f products categories] (let [products (filter #(= "1" (:visible %)) products) categories (filter (fn [category] (> (count (filter #(= (:category category) (:category %)) products)) 0)) categories)] (admin-products-by-category f products categories))) (defn front-page-headers [hfs] (let [headers (sort-by :position (filter #(= "Top" (:location %)) hfs))] [:div#headers-cont (map #(if (not (= "0" (:visible %))) [:div.header (:content %)]) headers)])) (defn front-page-footers [hfs] (let [footers (sort-by :position (filter #(= "Bottom" (:location %)) hfs))] [:div#footers-cont (map #(if (not (= "0" (:visible %))) [:div.footer (:content %)]) footers)])) (defn header-footer-page [request header-footer] (layout-admin (header-footer-form header-footer))) (defn edit-header-footer-page [request header-footer header-footers] (layout-admin (edit-header-footer-form header-footers header-footer))) (defn product-list-xform [products] (map product-template products)) (defn admin-product-list-xform [products] (map admin-product-template products)) (defn front-page [request products categories header-footers] (layout (front-page-headers header-footers) (products-by-category product-list-xform products categories) (front-page-footers header-footers))) (defn admin-home [request] (layout-admin staff-page-home)) (defn new-product-page [request categories] (layout-admin (product-form categories))) (defn edit-product-page [request product categories] (layout-admin (product-template product) (edit-product-form categories product))) (defn categories-page [request categories] (layout-admin (category-template categories))) (defn admin-products [request products categories] (layout-admin (admin-products-by-category admin-product-list-xform products categories))) (defn edit-category-page [request category categories] (layout-admin (category-edit-template categories category))) (defn new-user-page [request] (layout-admin add-user-form)) (defn login-page [request] (layout login-form))
[ { "context": "est-user [c]\n (let [login-code (db/->login-code \"test@example.com\")\n tokens (db/->tokens)\n user (db/-", "end": 581, "score": 0.9997749328613281, "start": 565, "tag": "EMAIL", "value": "test@example.com" } ]
test/instant_website/test_utils.clj
instantwebsite/core-api
0
(ns instant-website.test-utils (:require [crux.api :as crux] [instant-website.db :as db] [instant-website.handlers.websites :as websites] [instant-website.handlers.domains :as domains])) (defn crux-node [] (crux/start-node {})) (defn await-put! [c e] (crux/await-tx c (db/put! c e))) (defn await-delete! [c e] (crux/await-tx c (db/delete! c e))) (defn create-login-code! [c email] (let [login-code (db/->login-code email)] (await-put! c login-code) login-code)) (defn create-test-user [c] (let [login-code (db/->login-code "test@example.com") tokens (db/->tokens) user (db/->user tokens login-code)] (doseq [e [login-code tokens user]] (await-put! c e)) user)) (defn create-test-website [c u] (-> {:crux c :identity {:user-id (:crux.db/id u)} :dev-body {:name "Test" :startpage "testing"}} (websites/handle-create) :body)) (defn create-test-domain [c u] (-> {:crux c :identity {:user-id (:crux.db/id u)} :dev-body {:domain/hostname "example.com" :domain/auto-update? false}} (domains/handle-create) :body)) (comment (def c (crux/start-node {})) (create-test-domain c {:crux.db/id "u123"}))
58463
(ns instant-website.test-utils (:require [crux.api :as crux] [instant-website.db :as db] [instant-website.handlers.websites :as websites] [instant-website.handlers.domains :as domains])) (defn crux-node [] (crux/start-node {})) (defn await-put! [c e] (crux/await-tx c (db/put! c e))) (defn await-delete! [c e] (crux/await-tx c (db/delete! c e))) (defn create-login-code! [c email] (let [login-code (db/->login-code email)] (await-put! c login-code) login-code)) (defn create-test-user [c] (let [login-code (db/->login-code "<EMAIL>") tokens (db/->tokens) user (db/->user tokens login-code)] (doseq [e [login-code tokens user]] (await-put! c e)) user)) (defn create-test-website [c u] (-> {:crux c :identity {:user-id (:crux.db/id u)} :dev-body {:name "Test" :startpage "testing"}} (websites/handle-create) :body)) (defn create-test-domain [c u] (-> {:crux c :identity {:user-id (:crux.db/id u)} :dev-body {:domain/hostname "example.com" :domain/auto-update? false}} (domains/handle-create) :body)) (comment (def c (crux/start-node {})) (create-test-domain c {:crux.db/id "u123"}))
true
(ns instant-website.test-utils (:require [crux.api :as crux] [instant-website.db :as db] [instant-website.handlers.websites :as websites] [instant-website.handlers.domains :as domains])) (defn crux-node [] (crux/start-node {})) (defn await-put! [c e] (crux/await-tx c (db/put! c e))) (defn await-delete! [c e] (crux/await-tx c (db/delete! c e))) (defn create-login-code! [c email] (let [login-code (db/->login-code email)] (await-put! c login-code) login-code)) (defn create-test-user [c] (let [login-code (db/->login-code "PI:EMAIL:<EMAIL>END_PI") tokens (db/->tokens) user (db/->user tokens login-code)] (doseq [e [login-code tokens user]] (await-put! c e)) user)) (defn create-test-website [c u] (-> {:crux c :identity {:user-id (:crux.db/id u)} :dev-body {:name "Test" :startpage "testing"}} (websites/handle-create) :body)) (defn create-test-domain [c u] (-> {:crux c :identity {:user-id (:crux.db/id u)} :dev-body {:domain/hostname "example.com" :domain/auto-update? false}} (domains/handle-create) :body)) (comment (def c (crux/start-node {})) (create-test-domain c {:crux.db/id "u123"}))
[ { "context": "fault nil}\n {:key :test-setting-2\n :value \"S2\"\n ", "end": 10855, "score": 0.9704132080078125, "start": 10841, "tag": "KEY", "value": "test-setting-2" }, { "context": "encrypted!\"\n (encryption-test/with-secret-key \"ABCDEFGH12345678\"\n (toucan-name \"Sad Can\")\n (is (u/base6", "end": 17146, "score": 0.9997347593307495, "start": 17130, "tag": "KEY", "value": "ABCDEFGH12345678" }, { "context": "n-test/with-secret-key nil\n (toucan-name \"Sad Can\")\n (is (= \"Sad Can\"\n (mt/sup", "end": 17534, "score": 0.5576952695846558, "start": 17528, "tag": "NAME", "value": "ad Can" }, { "context": "-setting]\n (encryption-test/with-secret-key \"0B9cD6++AME+A7/oR7Y2xvPRHX3cHA2z7w+LbObd/9Y=\"\n (test-json-setting {:abc 123})\n (i", "end": 17957, "score": 0.9997726678848267, "start": 17912, "tag": "KEY", "value": "0B9cD6++AME+A7/oR7Y2xvPRHX3cHA2z7w+LbObd/9Y=\"" } ]
c#-metabase/test/metabase/models/setting_test.clj
hanakhry/Crime_Admin
0
(ns metabase.models.setting-test (:require [clojure.test :refer :all] [environ.core :as env] [medley.core :as m] [metabase.models.setting :as setting :refer [defsetting Setting]] [metabase.models.setting.cache :as cache] [metabase.test :as mt] [metabase.test.fixtures :as fixtures] [metabase.test.util :refer :all] [metabase.util :as u] [metabase.util.encryption-test :as encryption-test] [metabase.util.i18n :as i18n :refer [deferred-tru]] [toucan.db :as db])) (use-fixtures :once (fixtures/initialize :db)) ;; ## TEST SETTINGS DEFINITIONS (defsetting test-setting-1 (deferred-tru "Test setting - this only shows up in dev (1)")) (defsetting test-setting-2 (deferred-tru "Test setting - this only shows up in dev (2)") :default "[Default Value]") (defsetting test-setting-3 (deferred-tru "Test setting - this only shows up in dev (3)") :visibility :internal) (defsetting test-boolean-setting "Test setting - this only shows up in dev (3)" :visibility :internal :type :boolean) (defsetting test-json-setting (deferred-tru "Test setting - this only shows up in dev (4)") :type :json) (defsetting test-csv-setting "Test setting - this only shows up in dev (5)" :visibility :internal :type :csv) (defsetting test-csv-setting-with-default "Test setting - this only shows up in dev (6)" :visibility :internal :type :csv :default ["A" "B" "C"]) (defsetting test-env-setting "Test setting - this only shows up in dev (7)" :visibility :internal) (setting/defsetting toucan-name "Name for the Metabase Toucan mascot." :visibility :internal) (setting/defsetting test-setting-calculated-getter "Test setting - this only shows up in dev (8)" :type :boolean :setter :none :getter (fn [] true)) ;; ## HELPER FUNCTIONS (defn db-fetch-setting "Fetch `Setting` value from the DB to verify things work as we expect." [setting-name] (db/select-one-field :value Setting, :key (name setting-name))) (defn setting-exists-in-db? "Returns a boolean indicating whether a setting has a value stored in the application DB." [setting-name] (boolean (Setting :key (name setting-name)))) (deftest string-tag-test (testing "String vars defined by `defsetting` should have correct `:tag` metadata" (is (= 'java.lang.String (:tag (meta #'test-setting-1)))))) (deftest defsetting-getter-fn-test (testing "Test defsetting getter fn. Should return the value from env var MB_TEST_ENV_SETTING" (test-env-setting nil) (is (= "ABCDEFG" (test-env-setting)))) (testing "Test getting a default value -- if you clear the value of a Setting it should revert to returning the default value" (test-setting-2 nil) (is (= "[Default Value]" (test-setting-2))))) (deftest user-facing-value-test (testing "`user-facing-value` should return `nil` for a Setting that is using the default value" (test-setting-2 nil) (is (= nil (setting/user-facing-value :test-setting-2)))) (testing "`user-facing-value` should work correctly for calculated Settings (no underlying value)" (is (= true (test-setting-calculated-getter))) (is (= true (setting/user-facing-value :test-setting-calculated-getter))))) (deftest defsetting-setter-fn-test (test-setting-2 "FANCY NEW VALUE <3") (is (= "FANCY NEW VALUE <3" (test-setting-2))) (is (= "FANCY NEW VALUE <3" (db-fetch-setting :test-setting-2)))) (deftest set!-test (setting/set! :test-setting-2 "WHAT A NICE VALUE <3") (is (= "WHAT A NICE VALUE <3" (test-setting-2))) (is (= "WHAT A NICE VALUE <3" (db-fetch-setting :test-setting-2)))) (deftest set-many!-test (testing "should be able to set multiple settings at one time" (setting/set-many! {:test-setting-1 "I win!" :test-setting-2 "For realz"}) (is (= "I win!" (db-fetch-setting :test-setting-1))) (is (= "For realz" (db-fetch-setting :test-setting-2)))) (testing "if one change fails, the entire set of changes should be reverted" (mt/with-temporary-setting-values [test-setting-1 "123" test-setting-2 "123"] (let [orig setting/set! calls (atom 0)] ;; allow the first Setting change to succeed, then throw an Exception after that (with-redefs [setting/set! (fn [& args] (if (zero? @calls) (do (swap! calls inc) (apply orig args)) (throw (ex-info "Oops!" {}))))] (is (thrown-with-msg? Throwable #"Oops" (setting/set-many! {:test-setting-1 "ABC", :test-setting-2 "DEF"}))) (testing "changes should be reverted" (is (= "123" (test-setting-1))) (is (= "123" (test-setting-2))))))))) (deftest delete-test (testing "delete" (testing "w/o default value" (test-setting-1 "COOL") (is (= "COOL" (test-setting-1))) (is (= true (setting-exists-in-db? :test-setting-1))) (test-setting-1 nil) (is (= nil (test-setting-1))) (is (= nil (setting/get :test-setting-1))) (is (= false (setting-exists-in-db? :test-setting-1)))) (testing "w/ default value" (test-setting-2 "COOL") (is (= "COOL" (test-setting-2))) (is (= true (setting-exists-in-db? :test-setting-2))) (test-setting-2 nil) (is (= "[Default Value]" (test-setting-2)) "default value should get returned if none is set") (is (= false (setting-exists-in-db? :test-setting-2)) "setting still shouldn't exist in the DB")))) ;;; --------------------------------------------- all & user-facing-info --------------------------------------------- ;; these tests are to check that settings get returned with the correct information; these functions are what feed ;; into the API (defn- user-facing-info-with-db-and-env-var-values [setting db-value env-var-value] (do-with-temporary-setting-value setting db-value (fn [] (with-redefs [env/env {(keyword (str "mb-" (name setting))) env-var-value}] (dissoc (#'setting/user-facing-info (#'setting/resolve-setting setting)) :key :description))))) (deftest user-facing-info-test (testing "user-facing info w/ no db value, no env var value, no default value" (is (= {:value nil, :is_env_setting false, :env_name "MB_TEST_SETTING_1", :default nil} (user-facing-info-with-db-and-env-var-values :test-setting-1 nil nil)))) (testing "user-facing info w/ no db value, no env var value, default value" (is (= {:value nil, :is_env_setting false, :env_name "MB_TEST_SETTING_2", :default "[Default Value]"} (user-facing-info-with-db-and-env-var-values :test-setting-2 nil nil)))) (testing "user-facing info w/ no db value, env var value, no default value -- shouldn't leak env var value" (is (= {:value nil, :is_env_setting true, :env_name "MB_TEST_SETTING_1", :default "Using value of env var $MB_TEST_SETTING_1"} (user-facing-info-with-db-and-env-var-values :test-setting-1 nil "TOUCANS")))) (testing "user-facing info w/ no db value, env var value, default value" (is (= {:value nil, :is_env_setting true, :env_name "MB_TEST_SETTING_2", :default "Using value of env var $MB_TEST_SETTING_2"} (user-facing-info-with-db-and-env-var-values :test-setting-2 nil "TOUCANS")))) (testing "user-facing info w/ db value, no env var value, no default value" (is (= {:value "WOW", :is_env_setting false, :env_name "MB_TEST_SETTING_1", :default nil} (user-facing-info-with-db-and-env-var-values :test-setting-1 "WOW" nil)))) (testing "user-facing info w/ db value, no env var value, default value" (is (= {:value "WOW", :is_env_setting false, :env_name "MB_TEST_SETTING_2", :default "[Default Value]"} (user-facing-info-with-db-and-env-var-values :test-setting-2 "WOW" nil)))) (testing "user-facing info w/ db value, env var value, no default value -- the env var should take precedence over the db value, but should be obfuscated" (is (= {:value nil, :is_env_setting true, :env_name "MB_TEST_SETTING_1", :default "Using value of env var $MB_TEST_SETTING_1"} (user-facing-info-with-db-and-env-var-values :test-setting-1 "WOW" "ENV VAR")))) (testing "user-facing info w/ db value, env var value, default value -- env var should take precedence over default, but should be obfuscated" (is (= {:value nil, :is_env_setting true, :env_name "MB_TEST_SETTING_2", :default "Using value of env var $MB_TEST_SETTING_2"} (user-facing-info-with-db-and-env-var-values :test-setting-2 "WOW" "ENV VAR"))))) (deftest all-test (testing "setting/all" (test-setting-1 nil) (test-setting-2 "TOUCANS") (is (= {:key :test-setting-2 :value "TOUCANS" :description "Test setting - this only shows up in dev (2)" :is_env_setting false :env_name "MB_TEST_SETTING_2" :default "[Default Value]"} (some (fn [setting] (when (re-find #"^test-setting-2$" (name (:key setting))) setting)) (setting/all)))) (testing "with a custom getter" (test-setting-1 nil) (test-setting-2 "TOUCANS") (is (= {:key :test-setting-2 :value 7 :description "Test setting - this only shows up in dev (2)" :is_env_setting false :env_name "MB_TEST_SETTING_2" :default "[Default Value]"} (some (fn [setting] (when (re-find #"^test-setting-2$" (name (:key setting))) setting)) (setting/all :getter (comp count setting/get-string)))))) ;; TODO -- probably don't need both this test and the "TOUCANS" test above, we should combine them (testing "test settings" (test-setting-1 nil) (test-setting-2 "S2") (is (= [{:key :test-setting-1 :value nil :is_env_setting false :env_name "MB_TEST_SETTING_1" :description "Test setting - this only shows up in dev (1)" :default nil} {:key :test-setting-2 :value "S2" :is_env_setting false :env_name "MB_TEST_SETTING_2" :description "Test setting - this only shows up in dev (2)" :default "[Default Value]"}] (for [setting (setting/all) :when (re-find #"^test-setting-\d$" (name (:key setting)))] setting)))))) (defsetting test-i18n-setting (deferred-tru "Test setting - with i18n")) (deftest validate-description-test (testing "Validate setting description with i18n string" (mt/with-mock-i18n-bundles {"zz" {"Test setting - with i18n" "TEST SETTING - WITH I18N"}} (letfn [(description [] (some (fn [{:keys [key description]}] (when (= :test-i18n-setting key) description)) (setting/all)))] (is (= "Test setting - with i18n" (description))) (mt/with-user-locale "zz" (is (= "TEST SETTING - WITH I18N" (description)))))))) ;;; ------------------------------------------------ BOOLEAN SETTINGS ------------------------------------------------ (deftest boolean-settings-tag-test (testing "Boolean settings should have correct `:tag` metadata" (is (= 'java.lang.Boolean (:tag (meta #'test-boolean-setting)))))) (deftest boolean-setting-user-facing-info-test (is (= {:value nil, :is_env_setting false, :env_name "MB_TEST_BOOLEAN_SETTING", :default nil} (user-facing-info-with-db-and-env-var-values :test-boolean-setting nil nil)))) (deftest boolean-setting-env-vars-test (testing "values set by env vars should never be shown to the User" (let [expected {:value nil :is_env_setting true :env_name "MB_TEST_BOOLEAN_SETTING" :default "Using value of env var $MB_TEST_BOOLEAN_SETTING"}] (is (= expected (user-facing-info-with-db-and-env-var-values :test-boolean-setting nil "true"))) (testing "env var values should be case-insensitive" (is (= expected (user-facing-info-with-db-and-env-var-values :test-boolean-setting nil "TRUE")))))) (testing "if value isn't true / false" (testing "getter should throw exception" (is (thrown-with-msg? Exception #"Invalid value for string: must be either \"true\" or \"false\" \(case-insensitive\)" (test-boolean-setting "X")))) (testing "user-facing info should just return `nil` instead of failing entirely" (is (= {:value nil :is_env_setting true :env_name "MB_TEST_BOOLEAN_SETTING" :default "Using value of env var $MB_TEST_BOOLEAN_SETTING"} (user-facing-info-with-db-and-env-var-values :test-boolean-setting nil "X")))))) (deftest set-boolean-setting-test (testing "should be able to set value with a string..." (is (= "false" (test-boolean-setting "FALSE"))) (is (= false (test-boolean-setting))) (testing "... or a boolean" (is (= "false" (test-boolean-setting false))) (is (= false (test-boolean-setting)))))) ;;; ------------------------------------------------- JSON SETTINGS -------------------------------------------------- (deftest set-json-setting-test (is (= "{\"a\":100,\"b\":200}" (test-json-setting {:a 100, :b 200}))) (is (= {:a 100, :b 200} (test-json-setting)))) ;;; -------------------------------------------------- CSV Settings -------------------------------------------------- (defn- fetch-csv-setting-value [v] (with-redefs [setting/get-string (constantly v)] (test-csv-setting))) (deftest get-csv-setting-test (testing "should be able to fetch a simple CSV setting" (is (= ["A" "B" "C"] (fetch-csv-setting-value "A,B,C")))) (testing "should also work if there are quoted values that include commas in them" (is (= ["A" "B" "C1,C2" "ddd"] (fetch-csv-setting-value "A,B,\"C1,C2\",ddd"))))) (defn- set-and-fetch-csv-setting-value! [v] (test-csv-setting v) {:db-value (db/select-one-field :value setting/Setting :key "test-csv-setting") :parsed-value (test-csv-setting)}) (deftest csv-setting-test (testing "should be able to correctly set a simple CSV setting" (is (= {:db-value "A,B,C", :parsed-value ["A" "B" "C"]} (set-and-fetch-csv-setting-value! ["A" "B" "C"])))) (testing "should be a able to set a CSV setting with a value that includes commas" (is (= {:db-value "A,B,C,\"D1,D2\"", :parsed-value ["A" "B" "C" "D1,D2"]} (set-and-fetch-csv-setting-value! ["A" "B" "C" "D1,D2"])))) (testing "should be able to set a CSV setting with a value that includes spaces" (is (= {:db-value "A,B,C, D ", :parsed-value ["A" "B" "C" " D "]} (set-and-fetch-csv-setting-value! ["A" "B" "C" " D "])))) (testing "should be a able to set a CSV setting when the string is already CSV-encoded" (is (= {:db-value "A,B,C", :parsed-value ["A" "B" "C"]} (set-and-fetch-csv-setting-value! "A,B,C")))) (testing "should be able to set nil CSV setting" (is (= {:db-value nil, :parsed-value nil} (set-and-fetch-csv-setting-value! nil)))) (testing "default values for CSV settings should work" (test-csv-setting-with-default nil) (is (= ["A" "B" "C"] (test-csv-setting-with-default))))) (deftest csv-setting-user-facing-value-test (testing "`user-facing-value` should be `nil` for CSV Settings with default values" (test-csv-setting-with-default nil) (is (= nil (setting/user-facing-value :test-csv-setting-with-default))))) ;;; ----------------------------------------------- Encrypted Settings ----------------------------------------------- (defn- actual-value-in-db [setting-key] (-> (db/query {:select [:value] :from [:setting] :where [:= :key (name setting-key)]}) first :value)) (deftest encrypted-settings-test (testing "If encryption is *enabled*, make sure Settings get saved as encrypted!" (encryption-test/with-secret-key "ABCDEFGH12345678" (toucan-name "Sad Can") (is (u/base64-string? (actual-value-in-db :toucan-name))) (testing "make sure it can be decrypted as well..." (is (= "Sad Can" (toucan-name))))) (testing "But if encryption is not enabled, of course Settings shouldn't get saved as encrypted." (encryption-test/with-secret-key nil (toucan-name "Sad Can") (is (= "Sad Can" (mt/suppress-output (actual-value-in-db :toucan-name)))))))) (deftest previously-encrypted-settings-test (testing "Make sure settings that were encrypted don't cause `user-facing-info` to blow up if encyrption key changed" (mt/discard-setting-changes [test-json-setting] (encryption-test/with-secret-key "0B9cD6++AME+A7/oR7Y2xvPRHX3cHA2z7w+LbObd/9Y=" (test-json-setting {:abc 123}) (is (not= "{\"abc\":123}" (actual-value-in-db :test-json-setting)))) (testing (str "If fetching the Setting fails (e.g. because key changed) `user-facing-info` should return `nil` " "rather than failing entirely") (encryption-test/with-secret-key nil (is (= {:key :test-json-setting :value nil :is_env_setting false :env_name "MB_TEST_JSON_SETTING" :description "Test setting - this only shows up in dev (4)" :default nil} (#'setting/user-facing-info (setting/resolve-setting :test-json-setting))))))))) ;;; ----------------------------------------------- TIMESTAMP SETTINGS ----------------------------------------------- (defsetting test-timestamp-setting "Test timestamp setting" :visibility :internal :type :timestamp) (deftest timestamp-settings-test (is (= 'java.time.temporal.Temporal (:tag (meta #'test-timestamp-setting)))) (testing "make sure we can set & fetch the value and that it gets serialized/deserialized correctly" (test-timestamp-setting #t "2018-07-11T09:32:00.000Z") (is (= #t "2018-07-11T09:32:00.000Z" (test-timestamp-setting))))) ;;; ----------------------------------------------- Uncached Settings ------------------------------------------------ (defn clear-settings-last-updated-value-in-db! "Deletes the timestamp for the last updated setting from the DB." [] (db/simple-delete! Setting {:key cache/settings-last-updated-key})) (defn settings-last-updated-value-in-db "Fetches the timestamp of the last updated setting." [] (db/select-one-field :value Setting :key cache/settings-last-updated-key)) (defsetting uncached-setting "A test setting that should *not* be cached." :visibility :internal :cache? false) (deftest uncached-settings-test (encryption-test/with-secret-key nil (testing "make sure uncached setting still saves to the DB" (uncached-setting "ABCDEF") (is (= "ABCDEF" (actual-value-in-db "uncached-setting")))) (testing "make sure that fetching the Setting always fetches the latest value from the DB" (uncached-setting "ABCDEF") (db/update-where! Setting {:key "uncached-setting"} :value "123456") (is (= "123456" (uncached-setting)))) (testing "make sure that updating the setting doesn't update the last-updated timestamp in the cache $$" (clear-settings-last-updated-value-in-db!) (uncached-setting "abcdef") (is (= nil (settings-last-updated-value-in-db)))))) ;;; ----------------------------------------------- Sensitive Settings ----------------------------------------------- (defsetting test-sensitive-setting (deferred-tru "This is a sample sensitive Setting.") :sensitive? true) (deftest sensitive-settings-test (testing "`user-facing-value` should obfuscate sensitive settings" (test-sensitive-setting "ABC123") (is (= "**********23" (setting/user-facing-value "test-sensitive-setting")))) (testing "Attempting to set a sensitive setting to an obfuscated value should be ignored -- it was probably done accidentally" (test-sensitive-setting "123456") (test-sensitive-setting "**********56") (is (= "123456" (test-sensitive-setting))))) ;;; ------------------------------------------------- CACHE SYNCING -------------------------------------------------- (deftest cache-sync-test (testing "make sure that if for some reason the cache gets out of sync it will reset so we can still set new settings values (#4178)" ;; clear out any existing values of `toucan-name` (db/simple-delete! setting/Setting {:key "toucan-name"}) ;; restore the cache (cache/restore-cache-if-needed!) ;; now set a value for the `toucan-name` setting the wrong way (db/insert! setting/Setting {:key "toucan-name", :value "Reggae"}) ;; ok, now try to set the Setting the correct way (toucan-name "Banana Beak") ;; ok, make sure the setting was set (is (= "Banana Beak" (toucan-name))))) (deftest duplicated-setting-name (testing "can re-register a setting in the same ns (redefining or reloading ns)" (is (defsetting foo (deferred-tru "A testing setting") :visibility :public)) (is (defsetting foo (deferred-tru "A testing setting") :visibility :public))) (testing "if attempt to register in a different ns throws an error" (let [current-ns (ns-name *ns*)] (try (ns nested-setting-test (:require [metabase.models.setting :refer [defsetting]] [metabase.util.i18n :as i18n :refer [deferred-tru]])) (defsetting foo (deferred-tru "A testing setting") :visibility :public) (catch Exception e (is (= {:existing-setting {:description (deferred-tru "A testing setting"), :cache? true, :default nil, :name :foo, :munged-name "foo" :type :string, :sensitive? false, :tag 'java.lang.String, :namespace current-ns :visibility :public}} (ex-data e))) (is (= (str "Setting :foo already registered in " current-ns) (ex-message e)))) (finally (in-ns current-ns)))))) (defsetting test-setting-with-question-mark? "Test setting - this only shows up in dev (6)" :visibility :internal) (deftest munged-setting-name-test (testing "Only valid characters used for environment lookup" (is (nil? (test-setting-with-question-mark?))) ;; note now question mark on the environmental setting (with-redefs [env/env {:mb-test-setting-with-question-mark "resolved"}] (binding [setting/*disable-cache* false] (is (= "resolved" (test-setting-with-question-mark?)))))) (testing "Setting a setting that would munge the same throws an error" (is (= {:existing-setting {:name :test-setting-with-question-mark? :munged-name "test-setting-with-question-mark"} :new-setting {:name :test-setting-with-question-mark???? :munged-name "test-setting-with-question-mark"}} (m/map-vals #(select-keys % [:name :munged-name]) (try (defsetting test-setting-with-question-mark???? "Test setting - this only shows up in dev (6)" :visibility :internal) (catch Exception e (ex-data e))))))) (testing "Munge collision on first definition" (defsetting test-setting-normal "Test setting - this only shows up in dev (6)" :visibility :internal) (is (= {:existing-setting {:name :test-setting-normal, :munged-name "test-setting-normal"}, :new-setting {:name :test-setting-normal??, :munged-name "test-setting-normal"}} (m/map-vals #(select-keys % [:name :munged-name]) (try (defsetting test-setting-normal?? "Test setting - this only shows up in dev (6)" :visibility :internal) (catch Exception e (ex-data e))))))) (testing "Munge collision on second definition" (defsetting test-setting-normal-1?? "Test setting - this only shows up in dev (6)" :visibility :internal) (is (= {:new-setting {:munged-name "test-setting-normal-1", :name :test-setting-normal-1}, :existing-setting {:munged-name "test-setting-normal-1", :name :test-setting-normal-1??}} (m/map-vals #(select-keys % [:name :munged-name]) (try (defsetting test-setting-normal-1 "Test setting - this only shows up in dev (6)" :visibility :internal) (catch Exception e (ex-data e))))))) (testing "Removes characters not-compliant with shells" (is (= "aa1aa-b2b_cc3c" (#'setting/munge-setting-name "aa1'aa@#?-b2@b_cc'3?c?"))))) (deftest validate-default-value-for-type-test (letfn [(validate [tag default] (@#'setting/validate-default-value-for-type {:tag tag, :default default, :name :a-setting, :type :fake-type}))] (testing "No default value" (is (nil? (validate `String nil)))) (testing "No tag" (is (nil? (validate nil "abc")))) (testing "tag is not a symbol or string" (is (thrown-with-msg? AssertionError #"Setting :tag should be a symbol or string, got: \^clojure\.lang\.Keyword :string" (validate :string "Green Friend")))) (doseq [[tag valid-tag?] {"String" false "java.lang.String" true 'STRING false `str false `String true} [value valid-value?] {"Green Friend" true :green-friend false}] (testing (format "Tag = %s (valid = %b)" (pr-str tag) valid-tag?) (testing (format "Value = %s (valid = %b)" (pr-str value) valid-value?) (cond (and valid-tag? valid-value?) (is (nil? (validate tag value))) (not valid-tag?) (is (thrown-with-msg? Exception #"Cannot resolve :tag .+ to a class" (validate tag value))) (not valid-value?) (is (thrown-with-msg? Exception #"Wrong :default type: got \^clojure\.lang\.Keyword :green-friend, but expected a java\.lang\.String" (validate tag value)))))))))
20564
(ns metabase.models.setting-test (:require [clojure.test :refer :all] [environ.core :as env] [medley.core :as m] [metabase.models.setting :as setting :refer [defsetting Setting]] [metabase.models.setting.cache :as cache] [metabase.test :as mt] [metabase.test.fixtures :as fixtures] [metabase.test.util :refer :all] [metabase.util :as u] [metabase.util.encryption-test :as encryption-test] [metabase.util.i18n :as i18n :refer [deferred-tru]] [toucan.db :as db])) (use-fixtures :once (fixtures/initialize :db)) ;; ## TEST SETTINGS DEFINITIONS (defsetting test-setting-1 (deferred-tru "Test setting - this only shows up in dev (1)")) (defsetting test-setting-2 (deferred-tru "Test setting - this only shows up in dev (2)") :default "[Default Value]") (defsetting test-setting-3 (deferred-tru "Test setting - this only shows up in dev (3)") :visibility :internal) (defsetting test-boolean-setting "Test setting - this only shows up in dev (3)" :visibility :internal :type :boolean) (defsetting test-json-setting (deferred-tru "Test setting - this only shows up in dev (4)") :type :json) (defsetting test-csv-setting "Test setting - this only shows up in dev (5)" :visibility :internal :type :csv) (defsetting test-csv-setting-with-default "Test setting - this only shows up in dev (6)" :visibility :internal :type :csv :default ["A" "B" "C"]) (defsetting test-env-setting "Test setting - this only shows up in dev (7)" :visibility :internal) (setting/defsetting toucan-name "Name for the Metabase Toucan mascot." :visibility :internal) (setting/defsetting test-setting-calculated-getter "Test setting - this only shows up in dev (8)" :type :boolean :setter :none :getter (fn [] true)) ;; ## HELPER FUNCTIONS (defn db-fetch-setting "Fetch `Setting` value from the DB to verify things work as we expect." [setting-name] (db/select-one-field :value Setting, :key (name setting-name))) (defn setting-exists-in-db? "Returns a boolean indicating whether a setting has a value stored in the application DB." [setting-name] (boolean (Setting :key (name setting-name)))) (deftest string-tag-test (testing "String vars defined by `defsetting` should have correct `:tag` metadata" (is (= 'java.lang.String (:tag (meta #'test-setting-1)))))) (deftest defsetting-getter-fn-test (testing "Test defsetting getter fn. Should return the value from env var MB_TEST_ENV_SETTING" (test-env-setting nil) (is (= "ABCDEFG" (test-env-setting)))) (testing "Test getting a default value -- if you clear the value of a Setting it should revert to returning the default value" (test-setting-2 nil) (is (= "[Default Value]" (test-setting-2))))) (deftest user-facing-value-test (testing "`user-facing-value` should return `nil` for a Setting that is using the default value" (test-setting-2 nil) (is (= nil (setting/user-facing-value :test-setting-2)))) (testing "`user-facing-value` should work correctly for calculated Settings (no underlying value)" (is (= true (test-setting-calculated-getter))) (is (= true (setting/user-facing-value :test-setting-calculated-getter))))) (deftest defsetting-setter-fn-test (test-setting-2 "FANCY NEW VALUE <3") (is (= "FANCY NEW VALUE <3" (test-setting-2))) (is (= "FANCY NEW VALUE <3" (db-fetch-setting :test-setting-2)))) (deftest set!-test (setting/set! :test-setting-2 "WHAT A NICE VALUE <3") (is (= "WHAT A NICE VALUE <3" (test-setting-2))) (is (= "WHAT A NICE VALUE <3" (db-fetch-setting :test-setting-2)))) (deftest set-many!-test (testing "should be able to set multiple settings at one time" (setting/set-many! {:test-setting-1 "I win!" :test-setting-2 "For realz"}) (is (= "I win!" (db-fetch-setting :test-setting-1))) (is (= "For realz" (db-fetch-setting :test-setting-2)))) (testing "if one change fails, the entire set of changes should be reverted" (mt/with-temporary-setting-values [test-setting-1 "123" test-setting-2 "123"] (let [orig setting/set! calls (atom 0)] ;; allow the first Setting change to succeed, then throw an Exception after that (with-redefs [setting/set! (fn [& args] (if (zero? @calls) (do (swap! calls inc) (apply orig args)) (throw (ex-info "Oops!" {}))))] (is (thrown-with-msg? Throwable #"Oops" (setting/set-many! {:test-setting-1 "ABC", :test-setting-2 "DEF"}))) (testing "changes should be reverted" (is (= "123" (test-setting-1))) (is (= "123" (test-setting-2))))))))) (deftest delete-test (testing "delete" (testing "w/o default value" (test-setting-1 "COOL") (is (= "COOL" (test-setting-1))) (is (= true (setting-exists-in-db? :test-setting-1))) (test-setting-1 nil) (is (= nil (test-setting-1))) (is (= nil (setting/get :test-setting-1))) (is (= false (setting-exists-in-db? :test-setting-1)))) (testing "w/ default value" (test-setting-2 "COOL") (is (= "COOL" (test-setting-2))) (is (= true (setting-exists-in-db? :test-setting-2))) (test-setting-2 nil) (is (= "[Default Value]" (test-setting-2)) "default value should get returned if none is set") (is (= false (setting-exists-in-db? :test-setting-2)) "setting still shouldn't exist in the DB")))) ;;; --------------------------------------------- all & user-facing-info --------------------------------------------- ;; these tests are to check that settings get returned with the correct information; these functions are what feed ;; into the API (defn- user-facing-info-with-db-and-env-var-values [setting db-value env-var-value] (do-with-temporary-setting-value setting db-value (fn [] (with-redefs [env/env {(keyword (str "mb-" (name setting))) env-var-value}] (dissoc (#'setting/user-facing-info (#'setting/resolve-setting setting)) :key :description))))) (deftest user-facing-info-test (testing "user-facing info w/ no db value, no env var value, no default value" (is (= {:value nil, :is_env_setting false, :env_name "MB_TEST_SETTING_1", :default nil} (user-facing-info-with-db-and-env-var-values :test-setting-1 nil nil)))) (testing "user-facing info w/ no db value, no env var value, default value" (is (= {:value nil, :is_env_setting false, :env_name "MB_TEST_SETTING_2", :default "[Default Value]"} (user-facing-info-with-db-and-env-var-values :test-setting-2 nil nil)))) (testing "user-facing info w/ no db value, env var value, no default value -- shouldn't leak env var value" (is (= {:value nil, :is_env_setting true, :env_name "MB_TEST_SETTING_1", :default "Using value of env var $MB_TEST_SETTING_1"} (user-facing-info-with-db-and-env-var-values :test-setting-1 nil "TOUCANS")))) (testing "user-facing info w/ no db value, env var value, default value" (is (= {:value nil, :is_env_setting true, :env_name "MB_TEST_SETTING_2", :default "Using value of env var $MB_TEST_SETTING_2"} (user-facing-info-with-db-and-env-var-values :test-setting-2 nil "TOUCANS")))) (testing "user-facing info w/ db value, no env var value, no default value" (is (= {:value "WOW", :is_env_setting false, :env_name "MB_TEST_SETTING_1", :default nil} (user-facing-info-with-db-and-env-var-values :test-setting-1 "WOW" nil)))) (testing "user-facing info w/ db value, no env var value, default value" (is (= {:value "WOW", :is_env_setting false, :env_name "MB_TEST_SETTING_2", :default "[Default Value]"} (user-facing-info-with-db-and-env-var-values :test-setting-2 "WOW" nil)))) (testing "user-facing info w/ db value, env var value, no default value -- the env var should take precedence over the db value, but should be obfuscated" (is (= {:value nil, :is_env_setting true, :env_name "MB_TEST_SETTING_1", :default "Using value of env var $MB_TEST_SETTING_1"} (user-facing-info-with-db-and-env-var-values :test-setting-1 "WOW" "ENV VAR")))) (testing "user-facing info w/ db value, env var value, default value -- env var should take precedence over default, but should be obfuscated" (is (= {:value nil, :is_env_setting true, :env_name "MB_TEST_SETTING_2", :default "Using value of env var $MB_TEST_SETTING_2"} (user-facing-info-with-db-and-env-var-values :test-setting-2 "WOW" "ENV VAR"))))) (deftest all-test (testing "setting/all" (test-setting-1 nil) (test-setting-2 "TOUCANS") (is (= {:key :test-setting-2 :value "TOUCANS" :description "Test setting - this only shows up in dev (2)" :is_env_setting false :env_name "MB_TEST_SETTING_2" :default "[Default Value]"} (some (fn [setting] (when (re-find #"^test-setting-2$" (name (:key setting))) setting)) (setting/all)))) (testing "with a custom getter" (test-setting-1 nil) (test-setting-2 "TOUCANS") (is (= {:key :test-setting-2 :value 7 :description "Test setting - this only shows up in dev (2)" :is_env_setting false :env_name "MB_TEST_SETTING_2" :default "[Default Value]"} (some (fn [setting] (when (re-find #"^test-setting-2$" (name (:key setting))) setting)) (setting/all :getter (comp count setting/get-string)))))) ;; TODO -- probably don't need both this test and the "TOUCANS" test above, we should combine them (testing "test settings" (test-setting-1 nil) (test-setting-2 "S2") (is (= [{:key :test-setting-1 :value nil :is_env_setting false :env_name "MB_TEST_SETTING_1" :description "Test setting - this only shows up in dev (1)" :default nil} {:key :<KEY> :value "S2" :is_env_setting false :env_name "MB_TEST_SETTING_2" :description "Test setting - this only shows up in dev (2)" :default "[Default Value]"}] (for [setting (setting/all) :when (re-find #"^test-setting-\d$" (name (:key setting)))] setting)))))) (defsetting test-i18n-setting (deferred-tru "Test setting - with i18n")) (deftest validate-description-test (testing "Validate setting description with i18n string" (mt/with-mock-i18n-bundles {"zz" {"Test setting - with i18n" "TEST SETTING - WITH I18N"}} (letfn [(description [] (some (fn [{:keys [key description]}] (when (= :test-i18n-setting key) description)) (setting/all)))] (is (= "Test setting - with i18n" (description))) (mt/with-user-locale "zz" (is (= "TEST SETTING - WITH I18N" (description)))))))) ;;; ------------------------------------------------ BOOLEAN SETTINGS ------------------------------------------------ (deftest boolean-settings-tag-test (testing "Boolean settings should have correct `:tag` metadata" (is (= 'java.lang.Boolean (:tag (meta #'test-boolean-setting)))))) (deftest boolean-setting-user-facing-info-test (is (= {:value nil, :is_env_setting false, :env_name "MB_TEST_BOOLEAN_SETTING", :default nil} (user-facing-info-with-db-and-env-var-values :test-boolean-setting nil nil)))) (deftest boolean-setting-env-vars-test (testing "values set by env vars should never be shown to the User" (let [expected {:value nil :is_env_setting true :env_name "MB_TEST_BOOLEAN_SETTING" :default "Using value of env var $MB_TEST_BOOLEAN_SETTING"}] (is (= expected (user-facing-info-with-db-and-env-var-values :test-boolean-setting nil "true"))) (testing "env var values should be case-insensitive" (is (= expected (user-facing-info-with-db-and-env-var-values :test-boolean-setting nil "TRUE")))))) (testing "if value isn't true / false" (testing "getter should throw exception" (is (thrown-with-msg? Exception #"Invalid value for string: must be either \"true\" or \"false\" \(case-insensitive\)" (test-boolean-setting "X")))) (testing "user-facing info should just return `nil` instead of failing entirely" (is (= {:value nil :is_env_setting true :env_name "MB_TEST_BOOLEAN_SETTING" :default "Using value of env var $MB_TEST_BOOLEAN_SETTING"} (user-facing-info-with-db-and-env-var-values :test-boolean-setting nil "X")))))) (deftest set-boolean-setting-test (testing "should be able to set value with a string..." (is (= "false" (test-boolean-setting "FALSE"))) (is (= false (test-boolean-setting))) (testing "... or a boolean" (is (= "false" (test-boolean-setting false))) (is (= false (test-boolean-setting)))))) ;;; ------------------------------------------------- JSON SETTINGS -------------------------------------------------- (deftest set-json-setting-test (is (= "{\"a\":100,\"b\":200}" (test-json-setting {:a 100, :b 200}))) (is (= {:a 100, :b 200} (test-json-setting)))) ;;; -------------------------------------------------- CSV Settings -------------------------------------------------- (defn- fetch-csv-setting-value [v] (with-redefs [setting/get-string (constantly v)] (test-csv-setting))) (deftest get-csv-setting-test (testing "should be able to fetch a simple CSV setting" (is (= ["A" "B" "C"] (fetch-csv-setting-value "A,B,C")))) (testing "should also work if there are quoted values that include commas in them" (is (= ["A" "B" "C1,C2" "ddd"] (fetch-csv-setting-value "A,B,\"C1,C2\",ddd"))))) (defn- set-and-fetch-csv-setting-value! [v] (test-csv-setting v) {:db-value (db/select-one-field :value setting/Setting :key "test-csv-setting") :parsed-value (test-csv-setting)}) (deftest csv-setting-test (testing "should be able to correctly set a simple CSV setting" (is (= {:db-value "A,B,C", :parsed-value ["A" "B" "C"]} (set-and-fetch-csv-setting-value! ["A" "B" "C"])))) (testing "should be a able to set a CSV setting with a value that includes commas" (is (= {:db-value "A,B,C,\"D1,D2\"", :parsed-value ["A" "B" "C" "D1,D2"]} (set-and-fetch-csv-setting-value! ["A" "B" "C" "D1,D2"])))) (testing "should be able to set a CSV setting with a value that includes spaces" (is (= {:db-value "A,B,C, D ", :parsed-value ["A" "B" "C" " D "]} (set-and-fetch-csv-setting-value! ["A" "B" "C" " D "])))) (testing "should be a able to set a CSV setting when the string is already CSV-encoded" (is (= {:db-value "A,B,C", :parsed-value ["A" "B" "C"]} (set-and-fetch-csv-setting-value! "A,B,C")))) (testing "should be able to set nil CSV setting" (is (= {:db-value nil, :parsed-value nil} (set-and-fetch-csv-setting-value! nil)))) (testing "default values for CSV settings should work" (test-csv-setting-with-default nil) (is (= ["A" "B" "C"] (test-csv-setting-with-default))))) (deftest csv-setting-user-facing-value-test (testing "`user-facing-value` should be `nil` for CSV Settings with default values" (test-csv-setting-with-default nil) (is (= nil (setting/user-facing-value :test-csv-setting-with-default))))) ;;; ----------------------------------------------- Encrypted Settings ----------------------------------------------- (defn- actual-value-in-db [setting-key] (-> (db/query {:select [:value] :from [:setting] :where [:= :key (name setting-key)]}) first :value)) (deftest encrypted-settings-test (testing "If encryption is *enabled*, make sure Settings get saved as encrypted!" (encryption-test/with-secret-key "<KEY>" (toucan-name "Sad Can") (is (u/base64-string? (actual-value-in-db :toucan-name))) (testing "make sure it can be decrypted as well..." (is (= "Sad Can" (toucan-name))))) (testing "But if encryption is not enabled, of course Settings shouldn't get saved as encrypted." (encryption-test/with-secret-key nil (toucan-name "S<NAME>") (is (= "Sad Can" (mt/suppress-output (actual-value-in-db :toucan-name)))))))) (deftest previously-encrypted-settings-test (testing "Make sure settings that were encrypted don't cause `user-facing-info` to blow up if encyrption key changed" (mt/discard-setting-changes [test-json-setting] (encryption-test/with-secret-key "<KEY> (test-json-setting {:abc 123}) (is (not= "{\"abc\":123}" (actual-value-in-db :test-json-setting)))) (testing (str "If fetching the Setting fails (e.g. because key changed) `user-facing-info` should return `nil` " "rather than failing entirely") (encryption-test/with-secret-key nil (is (= {:key :test-json-setting :value nil :is_env_setting false :env_name "MB_TEST_JSON_SETTING" :description "Test setting - this only shows up in dev (4)" :default nil} (#'setting/user-facing-info (setting/resolve-setting :test-json-setting))))))))) ;;; ----------------------------------------------- TIMESTAMP SETTINGS ----------------------------------------------- (defsetting test-timestamp-setting "Test timestamp setting" :visibility :internal :type :timestamp) (deftest timestamp-settings-test (is (= 'java.time.temporal.Temporal (:tag (meta #'test-timestamp-setting)))) (testing "make sure we can set & fetch the value and that it gets serialized/deserialized correctly" (test-timestamp-setting #t "2018-07-11T09:32:00.000Z") (is (= #t "2018-07-11T09:32:00.000Z" (test-timestamp-setting))))) ;;; ----------------------------------------------- Uncached Settings ------------------------------------------------ (defn clear-settings-last-updated-value-in-db! "Deletes the timestamp for the last updated setting from the DB." [] (db/simple-delete! Setting {:key cache/settings-last-updated-key})) (defn settings-last-updated-value-in-db "Fetches the timestamp of the last updated setting." [] (db/select-one-field :value Setting :key cache/settings-last-updated-key)) (defsetting uncached-setting "A test setting that should *not* be cached." :visibility :internal :cache? false) (deftest uncached-settings-test (encryption-test/with-secret-key nil (testing "make sure uncached setting still saves to the DB" (uncached-setting "ABCDEF") (is (= "ABCDEF" (actual-value-in-db "uncached-setting")))) (testing "make sure that fetching the Setting always fetches the latest value from the DB" (uncached-setting "ABCDEF") (db/update-where! Setting {:key "uncached-setting"} :value "123456") (is (= "123456" (uncached-setting)))) (testing "make sure that updating the setting doesn't update the last-updated timestamp in the cache $$" (clear-settings-last-updated-value-in-db!) (uncached-setting "abcdef") (is (= nil (settings-last-updated-value-in-db)))))) ;;; ----------------------------------------------- Sensitive Settings ----------------------------------------------- (defsetting test-sensitive-setting (deferred-tru "This is a sample sensitive Setting.") :sensitive? true) (deftest sensitive-settings-test (testing "`user-facing-value` should obfuscate sensitive settings" (test-sensitive-setting "ABC123") (is (= "**********23" (setting/user-facing-value "test-sensitive-setting")))) (testing "Attempting to set a sensitive setting to an obfuscated value should be ignored -- it was probably done accidentally" (test-sensitive-setting "123456") (test-sensitive-setting "**********56") (is (= "123456" (test-sensitive-setting))))) ;;; ------------------------------------------------- CACHE SYNCING -------------------------------------------------- (deftest cache-sync-test (testing "make sure that if for some reason the cache gets out of sync it will reset so we can still set new settings values (#4178)" ;; clear out any existing values of `toucan-name` (db/simple-delete! setting/Setting {:key "toucan-name"}) ;; restore the cache (cache/restore-cache-if-needed!) ;; now set a value for the `toucan-name` setting the wrong way (db/insert! setting/Setting {:key "toucan-name", :value "Reggae"}) ;; ok, now try to set the Setting the correct way (toucan-name "Banana Beak") ;; ok, make sure the setting was set (is (= "Banana Beak" (toucan-name))))) (deftest duplicated-setting-name (testing "can re-register a setting in the same ns (redefining or reloading ns)" (is (defsetting foo (deferred-tru "A testing setting") :visibility :public)) (is (defsetting foo (deferred-tru "A testing setting") :visibility :public))) (testing "if attempt to register in a different ns throws an error" (let [current-ns (ns-name *ns*)] (try (ns nested-setting-test (:require [metabase.models.setting :refer [defsetting]] [metabase.util.i18n :as i18n :refer [deferred-tru]])) (defsetting foo (deferred-tru "A testing setting") :visibility :public) (catch Exception e (is (= {:existing-setting {:description (deferred-tru "A testing setting"), :cache? true, :default nil, :name :foo, :munged-name "foo" :type :string, :sensitive? false, :tag 'java.lang.String, :namespace current-ns :visibility :public}} (ex-data e))) (is (= (str "Setting :foo already registered in " current-ns) (ex-message e)))) (finally (in-ns current-ns)))))) (defsetting test-setting-with-question-mark? "Test setting - this only shows up in dev (6)" :visibility :internal) (deftest munged-setting-name-test (testing "Only valid characters used for environment lookup" (is (nil? (test-setting-with-question-mark?))) ;; note now question mark on the environmental setting (with-redefs [env/env {:mb-test-setting-with-question-mark "resolved"}] (binding [setting/*disable-cache* false] (is (= "resolved" (test-setting-with-question-mark?)))))) (testing "Setting a setting that would munge the same throws an error" (is (= {:existing-setting {:name :test-setting-with-question-mark? :munged-name "test-setting-with-question-mark"} :new-setting {:name :test-setting-with-question-mark???? :munged-name "test-setting-with-question-mark"}} (m/map-vals #(select-keys % [:name :munged-name]) (try (defsetting test-setting-with-question-mark???? "Test setting - this only shows up in dev (6)" :visibility :internal) (catch Exception e (ex-data e))))))) (testing "Munge collision on first definition" (defsetting test-setting-normal "Test setting - this only shows up in dev (6)" :visibility :internal) (is (= {:existing-setting {:name :test-setting-normal, :munged-name "test-setting-normal"}, :new-setting {:name :test-setting-normal??, :munged-name "test-setting-normal"}} (m/map-vals #(select-keys % [:name :munged-name]) (try (defsetting test-setting-normal?? "Test setting - this only shows up in dev (6)" :visibility :internal) (catch Exception e (ex-data e))))))) (testing "Munge collision on second definition" (defsetting test-setting-normal-1?? "Test setting - this only shows up in dev (6)" :visibility :internal) (is (= {:new-setting {:munged-name "test-setting-normal-1", :name :test-setting-normal-1}, :existing-setting {:munged-name "test-setting-normal-1", :name :test-setting-normal-1??}} (m/map-vals #(select-keys % [:name :munged-name]) (try (defsetting test-setting-normal-1 "Test setting - this only shows up in dev (6)" :visibility :internal) (catch Exception e (ex-data e))))))) (testing "Removes characters not-compliant with shells" (is (= "aa1aa-b2b_cc3c" (#'setting/munge-setting-name "aa1'aa@#?-b2@b_cc'3?c?"))))) (deftest validate-default-value-for-type-test (letfn [(validate [tag default] (@#'setting/validate-default-value-for-type {:tag tag, :default default, :name :a-setting, :type :fake-type}))] (testing "No default value" (is (nil? (validate `String nil)))) (testing "No tag" (is (nil? (validate nil "abc")))) (testing "tag is not a symbol or string" (is (thrown-with-msg? AssertionError #"Setting :tag should be a symbol or string, got: \^clojure\.lang\.Keyword :string" (validate :string "Green Friend")))) (doseq [[tag valid-tag?] {"String" false "java.lang.String" true 'STRING false `str false `String true} [value valid-value?] {"Green Friend" true :green-friend false}] (testing (format "Tag = %s (valid = %b)" (pr-str tag) valid-tag?) (testing (format "Value = %s (valid = %b)" (pr-str value) valid-value?) (cond (and valid-tag? valid-value?) (is (nil? (validate tag value))) (not valid-tag?) (is (thrown-with-msg? Exception #"Cannot resolve :tag .+ to a class" (validate tag value))) (not valid-value?) (is (thrown-with-msg? Exception #"Wrong :default type: got \^clojure\.lang\.Keyword :green-friend, but expected a java\.lang\.String" (validate tag value)))))))))
true
(ns metabase.models.setting-test (:require [clojure.test :refer :all] [environ.core :as env] [medley.core :as m] [metabase.models.setting :as setting :refer [defsetting Setting]] [metabase.models.setting.cache :as cache] [metabase.test :as mt] [metabase.test.fixtures :as fixtures] [metabase.test.util :refer :all] [metabase.util :as u] [metabase.util.encryption-test :as encryption-test] [metabase.util.i18n :as i18n :refer [deferred-tru]] [toucan.db :as db])) (use-fixtures :once (fixtures/initialize :db)) ;; ## TEST SETTINGS DEFINITIONS (defsetting test-setting-1 (deferred-tru "Test setting - this only shows up in dev (1)")) (defsetting test-setting-2 (deferred-tru "Test setting - this only shows up in dev (2)") :default "[Default Value]") (defsetting test-setting-3 (deferred-tru "Test setting - this only shows up in dev (3)") :visibility :internal) (defsetting test-boolean-setting "Test setting - this only shows up in dev (3)" :visibility :internal :type :boolean) (defsetting test-json-setting (deferred-tru "Test setting - this only shows up in dev (4)") :type :json) (defsetting test-csv-setting "Test setting - this only shows up in dev (5)" :visibility :internal :type :csv) (defsetting test-csv-setting-with-default "Test setting - this only shows up in dev (6)" :visibility :internal :type :csv :default ["A" "B" "C"]) (defsetting test-env-setting "Test setting - this only shows up in dev (7)" :visibility :internal) (setting/defsetting toucan-name "Name for the Metabase Toucan mascot." :visibility :internal) (setting/defsetting test-setting-calculated-getter "Test setting - this only shows up in dev (8)" :type :boolean :setter :none :getter (fn [] true)) ;; ## HELPER FUNCTIONS (defn db-fetch-setting "Fetch `Setting` value from the DB to verify things work as we expect." [setting-name] (db/select-one-field :value Setting, :key (name setting-name))) (defn setting-exists-in-db? "Returns a boolean indicating whether a setting has a value stored in the application DB." [setting-name] (boolean (Setting :key (name setting-name)))) (deftest string-tag-test (testing "String vars defined by `defsetting` should have correct `:tag` metadata" (is (= 'java.lang.String (:tag (meta #'test-setting-1)))))) (deftest defsetting-getter-fn-test (testing "Test defsetting getter fn. Should return the value from env var MB_TEST_ENV_SETTING" (test-env-setting nil) (is (= "ABCDEFG" (test-env-setting)))) (testing "Test getting a default value -- if you clear the value of a Setting it should revert to returning the default value" (test-setting-2 nil) (is (= "[Default Value]" (test-setting-2))))) (deftest user-facing-value-test (testing "`user-facing-value` should return `nil` for a Setting that is using the default value" (test-setting-2 nil) (is (= nil (setting/user-facing-value :test-setting-2)))) (testing "`user-facing-value` should work correctly for calculated Settings (no underlying value)" (is (= true (test-setting-calculated-getter))) (is (= true (setting/user-facing-value :test-setting-calculated-getter))))) (deftest defsetting-setter-fn-test (test-setting-2 "FANCY NEW VALUE <3") (is (= "FANCY NEW VALUE <3" (test-setting-2))) (is (= "FANCY NEW VALUE <3" (db-fetch-setting :test-setting-2)))) (deftest set!-test (setting/set! :test-setting-2 "WHAT A NICE VALUE <3") (is (= "WHAT A NICE VALUE <3" (test-setting-2))) (is (= "WHAT A NICE VALUE <3" (db-fetch-setting :test-setting-2)))) (deftest set-many!-test (testing "should be able to set multiple settings at one time" (setting/set-many! {:test-setting-1 "I win!" :test-setting-2 "For realz"}) (is (= "I win!" (db-fetch-setting :test-setting-1))) (is (= "For realz" (db-fetch-setting :test-setting-2)))) (testing "if one change fails, the entire set of changes should be reverted" (mt/with-temporary-setting-values [test-setting-1 "123" test-setting-2 "123"] (let [orig setting/set! calls (atom 0)] ;; allow the first Setting change to succeed, then throw an Exception after that (with-redefs [setting/set! (fn [& args] (if (zero? @calls) (do (swap! calls inc) (apply orig args)) (throw (ex-info "Oops!" {}))))] (is (thrown-with-msg? Throwable #"Oops" (setting/set-many! {:test-setting-1 "ABC", :test-setting-2 "DEF"}))) (testing "changes should be reverted" (is (= "123" (test-setting-1))) (is (= "123" (test-setting-2))))))))) (deftest delete-test (testing "delete" (testing "w/o default value" (test-setting-1 "COOL") (is (= "COOL" (test-setting-1))) (is (= true (setting-exists-in-db? :test-setting-1))) (test-setting-1 nil) (is (= nil (test-setting-1))) (is (= nil (setting/get :test-setting-1))) (is (= false (setting-exists-in-db? :test-setting-1)))) (testing "w/ default value" (test-setting-2 "COOL") (is (= "COOL" (test-setting-2))) (is (= true (setting-exists-in-db? :test-setting-2))) (test-setting-2 nil) (is (= "[Default Value]" (test-setting-2)) "default value should get returned if none is set") (is (= false (setting-exists-in-db? :test-setting-2)) "setting still shouldn't exist in the DB")))) ;;; --------------------------------------------- all & user-facing-info --------------------------------------------- ;; these tests are to check that settings get returned with the correct information; these functions are what feed ;; into the API (defn- user-facing-info-with-db-and-env-var-values [setting db-value env-var-value] (do-with-temporary-setting-value setting db-value (fn [] (with-redefs [env/env {(keyword (str "mb-" (name setting))) env-var-value}] (dissoc (#'setting/user-facing-info (#'setting/resolve-setting setting)) :key :description))))) (deftest user-facing-info-test (testing "user-facing info w/ no db value, no env var value, no default value" (is (= {:value nil, :is_env_setting false, :env_name "MB_TEST_SETTING_1", :default nil} (user-facing-info-with-db-and-env-var-values :test-setting-1 nil nil)))) (testing "user-facing info w/ no db value, no env var value, default value" (is (= {:value nil, :is_env_setting false, :env_name "MB_TEST_SETTING_2", :default "[Default Value]"} (user-facing-info-with-db-and-env-var-values :test-setting-2 nil nil)))) (testing "user-facing info w/ no db value, env var value, no default value -- shouldn't leak env var value" (is (= {:value nil, :is_env_setting true, :env_name "MB_TEST_SETTING_1", :default "Using value of env var $MB_TEST_SETTING_1"} (user-facing-info-with-db-and-env-var-values :test-setting-1 nil "TOUCANS")))) (testing "user-facing info w/ no db value, env var value, default value" (is (= {:value nil, :is_env_setting true, :env_name "MB_TEST_SETTING_2", :default "Using value of env var $MB_TEST_SETTING_2"} (user-facing-info-with-db-and-env-var-values :test-setting-2 nil "TOUCANS")))) (testing "user-facing info w/ db value, no env var value, no default value" (is (= {:value "WOW", :is_env_setting false, :env_name "MB_TEST_SETTING_1", :default nil} (user-facing-info-with-db-and-env-var-values :test-setting-1 "WOW" nil)))) (testing "user-facing info w/ db value, no env var value, default value" (is (= {:value "WOW", :is_env_setting false, :env_name "MB_TEST_SETTING_2", :default "[Default Value]"} (user-facing-info-with-db-and-env-var-values :test-setting-2 "WOW" nil)))) (testing "user-facing info w/ db value, env var value, no default value -- the env var should take precedence over the db value, but should be obfuscated" (is (= {:value nil, :is_env_setting true, :env_name "MB_TEST_SETTING_1", :default "Using value of env var $MB_TEST_SETTING_1"} (user-facing-info-with-db-and-env-var-values :test-setting-1 "WOW" "ENV VAR")))) (testing "user-facing info w/ db value, env var value, default value -- env var should take precedence over default, but should be obfuscated" (is (= {:value nil, :is_env_setting true, :env_name "MB_TEST_SETTING_2", :default "Using value of env var $MB_TEST_SETTING_2"} (user-facing-info-with-db-and-env-var-values :test-setting-2 "WOW" "ENV VAR"))))) (deftest all-test (testing "setting/all" (test-setting-1 nil) (test-setting-2 "TOUCANS") (is (= {:key :test-setting-2 :value "TOUCANS" :description "Test setting - this only shows up in dev (2)" :is_env_setting false :env_name "MB_TEST_SETTING_2" :default "[Default Value]"} (some (fn [setting] (when (re-find #"^test-setting-2$" (name (:key setting))) setting)) (setting/all)))) (testing "with a custom getter" (test-setting-1 nil) (test-setting-2 "TOUCANS") (is (= {:key :test-setting-2 :value 7 :description "Test setting - this only shows up in dev (2)" :is_env_setting false :env_name "MB_TEST_SETTING_2" :default "[Default Value]"} (some (fn [setting] (when (re-find #"^test-setting-2$" (name (:key setting))) setting)) (setting/all :getter (comp count setting/get-string)))))) ;; TODO -- probably don't need both this test and the "TOUCANS" test above, we should combine them (testing "test settings" (test-setting-1 nil) (test-setting-2 "S2") (is (= [{:key :test-setting-1 :value nil :is_env_setting false :env_name "MB_TEST_SETTING_1" :description "Test setting - this only shows up in dev (1)" :default nil} {:key :PI:KEY:<KEY>END_PI :value "S2" :is_env_setting false :env_name "MB_TEST_SETTING_2" :description "Test setting - this only shows up in dev (2)" :default "[Default Value]"}] (for [setting (setting/all) :when (re-find #"^test-setting-\d$" (name (:key setting)))] setting)))))) (defsetting test-i18n-setting (deferred-tru "Test setting - with i18n")) (deftest validate-description-test (testing "Validate setting description with i18n string" (mt/with-mock-i18n-bundles {"zz" {"Test setting - with i18n" "TEST SETTING - WITH I18N"}} (letfn [(description [] (some (fn [{:keys [key description]}] (when (= :test-i18n-setting key) description)) (setting/all)))] (is (= "Test setting - with i18n" (description))) (mt/with-user-locale "zz" (is (= "TEST SETTING - WITH I18N" (description)))))))) ;;; ------------------------------------------------ BOOLEAN SETTINGS ------------------------------------------------ (deftest boolean-settings-tag-test (testing "Boolean settings should have correct `:tag` metadata" (is (= 'java.lang.Boolean (:tag (meta #'test-boolean-setting)))))) (deftest boolean-setting-user-facing-info-test (is (= {:value nil, :is_env_setting false, :env_name "MB_TEST_BOOLEAN_SETTING", :default nil} (user-facing-info-with-db-and-env-var-values :test-boolean-setting nil nil)))) (deftest boolean-setting-env-vars-test (testing "values set by env vars should never be shown to the User" (let [expected {:value nil :is_env_setting true :env_name "MB_TEST_BOOLEAN_SETTING" :default "Using value of env var $MB_TEST_BOOLEAN_SETTING"}] (is (= expected (user-facing-info-with-db-and-env-var-values :test-boolean-setting nil "true"))) (testing "env var values should be case-insensitive" (is (= expected (user-facing-info-with-db-and-env-var-values :test-boolean-setting nil "TRUE")))))) (testing "if value isn't true / false" (testing "getter should throw exception" (is (thrown-with-msg? Exception #"Invalid value for string: must be either \"true\" or \"false\" \(case-insensitive\)" (test-boolean-setting "X")))) (testing "user-facing info should just return `nil` instead of failing entirely" (is (= {:value nil :is_env_setting true :env_name "MB_TEST_BOOLEAN_SETTING" :default "Using value of env var $MB_TEST_BOOLEAN_SETTING"} (user-facing-info-with-db-and-env-var-values :test-boolean-setting nil "X")))))) (deftest set-boolean-setting-test (testing "should be able to set value with a string..." (is (= "false" (test-boolean-setting "FALSE"))) (is (= false (test-boolean-setting))) (testing "... or a boolean" (is (= "false" (test-boolean-setting false))) (is (= false (test-boolean-setting)))))) ;;; ------------------------------------------------- JSON SETTINGS -------------------------------------------------- (deftest set-json-setting-test (is (= "{\"a\":100,\"b\":200}" (test-json-setting {:a 100, :b 200}))) (is (= {:a 100, :b 200} (test-json-setting)))) ;;; -------------------------------------------------- CSV Settings -------------------------------------------------- (defn- fetch-csv-setting-value [v] (with-redefs [setting/get-string (constantly v)] (test-csv-setting))) (deftest get-csv-setting-test (testing "should be able to fetch a simple CSV setting" (is (= ["A" "B" "C"] (fetch-csv-setting-value "A,B,C")))) (testing "should also work if there are quoted values that include commas in them" (is (= ["A" "B" "C1,C2" "ddd"] (fetch-csv-setting-value "A,B,\"C1,C2\",ddd"))))) (defn- set-and-fetch-csv-setting-value! [v] (test-csv-setting v) {:db-value (db/select-one-field :value setting/Setting :key "test-csv-setting") :parsed-value (test-csv-setting)}) (deftest csv-setting-test (testing "should be able to correctly set a simple CSV setting" (is (= {:db-value "A,B,C", :parsed-value ["A" "B" "C"]} (set-and-fetch-csv-setting-value! ["A" "B" "C"])))) (testing "should be a able to set a CSV setting with a value that includes commas" (is (= {:db-value "A,B,C,\"D1,D2\"", :parsed-value ["A" "B" "C" "D1,D2"]} (set-and-fetch-csv-setting-value! ["A" "B" "C" "D1,D2"])))) (testing "should be able to set a CSV setting with a value that includes spaces" (is (= {:db-value "A,B,C, D ", :parsed-value ["A" "B" "C" " D "]} (set-and-fetch-csv-setting-value! ["A" "B" "C" " D "])))) (testing "should be a able to set a CSV setting when the string is already CSV-encoded" (is (= {:db-value "A,B,C", :parsed-value ["A" "B" "C"]} (set-and-fetch-csv-setting-value! "A,B,C")))) (testing "should be able to set nil CSV setting" (is (= {:db-value nil, :parsed-value nil} (set-and-fetch-csv-setting-value! nil)))) (testing "default values for CSV settings should work" (test-csv-setting-with-default nil) (is (= ["A" "B" "C"] (test-csv-setting-with-default))))) (deftest csv-setting-user-facing-value-test (testing "`user-facing-value` should be `nil` for CSV Settings with default values" (test-csv-setting-with-default nil) (is (= nil (setting/user-facing-value :test-csv-setting-with-default))))) ;;; ----------------------------------------------- Encrypted Settings ----------------------------------------------- (defn- actual-value-in-db [setting-key] (-> (db/query {:select [:value] :from [:setting] :where [:= :key (name setting-key)]}) first :value)) (deftest encrypted-settings-test (testing "If encryption is *enabled*, make sure Settings get saved as encrypted!" (encryption-test/with-secret-key "PI:KEY:<KEY>END_PI" (toucan-name "Sad Can") (is (u/base64-string? (actual-value-in-db :toucan-name))) (testing "make sure it can be decrypted as well..." (is (= "Sad Can" (toucan-name))))) (testing "But if encryption is not enabled, of course Settings shouldn't get saved as encrypted." (encryption-test/with-secret-key nil (toucan-name "SPI:NAME:<NAME>END_PI") (is (= "Sad Can" (mt/suppress-output (actual-value-in-db :toucan-name)))))))) (deftest previously-encrypted-settings-test (testing "Make sure settings that were encrypted don't cause `user-facing-info` to blow up if encyrption key changed" (mt/discard-setting-changes [test-json-setting] (encryption-test/with-secret-key "PI:KEY:<KEY>END_PI (test-json-setting {:abc 123}) (is (not= "{\"abc\":123}" (actual-value-in-db :test-json-setting)))) (testing (str "If fetching the Setting fails (e.g. because key changed) `user-facing-info` should return `nil` " "rather than failing entirely") (encryption-test/with-secret-key nil (is (= {:key :test-json-setting :value nil :is_env_setting false :env_name "MB_TEST_JSON_SETTING" :description "Test setting - this only shows up in dev (4)" :default nil} (#'setting/user-facing-info (setting/resolve-setting :test-json-setting))))))))) ;;; ----------------------------------------------- TIMESTAMP SETTINGS ----------------------------------------------- (defsetting test-timestamp-setting "Test timestamp setting" :visibility :internal :type :timestamp) (deftest timestamp-settings-test (is (= 'java.time.temporal.Temporal (:tag (meta #'test-timestamp-setting)))) (testing "make sure we can set & fetch the value and that it gets serialized/deserialized correctly" (test-timestamp-setting #t "2018-07-11T09:32:00.000Z") (is (= #t "2018-07-11T09:32:00.000Z" (test-timestamp-setting))))) ;;; ----------------------------------------------- Uncached Settings ------------------------------------------------ (defn clear-settings-last-updated-value-in-db! "Deletes the timestamp for the last updated setting from the DB." [] (db/simple-delete! Setting {:key cache/settings-last-updated-key})) (defn settings-last-updated-value-in-db "Fetches the timestamp of the last updated setting." [] (db/select-one-field :value Setting :key cache/settings-last-updated-key)) (defsetting uncached-setting "A test setting that should *not* be cached." :visibility :internal :cache? false) (deftest uncached-settings-test (encryption-test/with-secret-key nil (testing "make sure uncached setting still saves to the DB" (uncached-setting "ABCDEF") (is (= "ABCDEF" (actual-value-in-db "uncached-setting")))) (testing "make sure that fetching the Setting always fetches the latest value from the DB" (uncached-setting "ABCDEF") (db/update-where! Setting {:key "uncached-setting"} :value "123456") (is (= "123456" (uncached-setting)))) (testing "make sure that updating the setting doesn't update the last-updated timestamp in the cache $$" (clear-settings-last-updated-value-in-db!) (uncached-setting "abcdef") (is (= nil (settings-last-updated-value-in-db)))))) ;;; ----------------------------------------------- Sensitive Settings ----------------------------------------------- (defsetting test-sensitive-setting (deferred-tru "This is a sample sensitive Setting.") :sensitive? true) (deftest sensitive-settings-test (testing "`user-facing-value` should obfuscate sensitive settings" (test-sensitive-setting "ABC123") (is (= "**********23" (setting/user-facing-value "test-sensitive-setting")))) (testing "Attempting to set a sensitive setting to an obfuscated value should be ignored -- it was probably done accidentally" (test-sensitive-setting "123456") (test-sensitive-setting "**********56") (is (= "123456" (test-sensitive-setting))))) ;;; ------------------------------------------------- CACHE SYNCING -------------------------------------------------- (deftest cache-sync-test (testing "make sure that if for some reason the cache gets out of sync it will reset so we can still set new settings values (#4178)" ;; clear out any existing values of `toucan-name` (db/simple-delete! setting/Setting {:key "toucan-name"}) ;; restore the cache (cache/restore-cache-if-needed!) ;; now set a value for the `toucan-name` setting the wrong way (db/insert! setting/Setting {:key "toucan-name", :value "Reggae"}) ;; ok, now try to set the Setting the correct way (toucan-name "Banana Beak") ;; ok, make sure the setting was set (is (= "Banana Beak" (toucan-name))))) (deftest duplicated-setting-name (testing "can re-register a setting in the same ns (redefining or reloading ns)" (is (defsetting foo (deferred-tru "A testing setting") :visibility :public)) (is (defsetting foo (deferred-tru "A testing setting") :visibility :public))) (testing "if attempt to register in a different ns throws an error" (let [current-ns (ns-name *ns*)] (try (ns nested-setting-test (:require [metabase.models.setting :refer [defsetting]] [metabase.util.i18n :as i18n :refer [deferred-tru]])) (defsetting foo (deferred-tru "A testing setting") :visibility :public) (catch Exception e (is (= {:existing-setting {:description (deferred-tru "A testing setting"), :cache? true, :default nil, :name :foo, :munged-name "foo" :type :string, :sensitive? false, :tag 'java.lang.String, :namespace current-ns :visibility :public}} (ex-data e))) (is (= (str "Setting :foo already registered in " current-ns) (ex-message e)))) (finally (in-ns current-ns)))))) (defsetting test-setting-with-question-mark? "Test setting - this only shows up in dev (6)" :visibility :internal) (deftest munged-setting-name-test (testing "Only valid characters used for environment lookup" (is (nil? (test-setting-with-question-mark?))) ;; note now question mark on the environmental setting (with-redefs [env/env {:mb-test-setting-with-question-mark "resolved"}] (binding [setting/*disable-cache* false] (is (= "resolved" (test-setting-with-question-mark?)))))) (testing "Setting a setting that would munge the same throws an error" (is (= {:existing-setting {:name :test-setting-with-question-mark? :munged-name "test-setting-with-question-mark"} :new-setting {:name :test-setting-with-question-mark???? :munged-name "test-setting-with-question-mark"}} (m/map-vals #(select-keys % [:name :munged-name]) (try (defsetting test-setting-with-question-mark???? "Test setting - this only shows up in dev (6)" :visibility :internal) (catch Exception e (ex-data e))))))) (testing "Munge collision on first definition" (defsetting test-setting-normal "Test setting - this only shows up in dev (6)" :visibility :internal) (is (= {:existing-setting {:name :test-setting-normal, :munged-name "test-setting-normal"}, :new-setting {:name :test-setting-normal??, :munged-name "test-setting-normal"}} (m/map-vals #(select-keys % [:name :munged-name]) (try (defsetting test-setting-normal?? "Test setting - this only shows up in dev (6)" :visibility :internal) (catch Exception e (ex-data e))))))) (testing "Munge collision on second definition" (defsetting test-setting-normal-1?? "Test setting - this only shows up in dev (6)" :visibility :internal) (is (= {:new-setting {:munged-name "test-setting-normal-1", :name :test-setting-normal-1}, :existing-setting {:munged-name "test-setting-normal-1", :name :test-setting-normal-1??}} (m/map-vals #(select-keys % [:name :munged-name]) (try (defsetting test-setting-normal-1 "Test setting - this only shows up in dev (6)" :visibility :internal) (catch Exception e (ex-data e))))))) (testing "Removes characters not-compliant with shells" (is (= "aa1aa-b2b_cc3c" (#'setting/munge-setting-name "aa1'aa@#?-b2@b_cc'3?c?"))))) (deftest validate-default-value-for-type-test (letfn [(validate [tag default] (@#'setting/validate-default-value-for-type {:tag tag, :default default, :name :a-setting, :type :fake-type}))] (testing "No default value" (is (nil? (validate `String nil)))) (testing "No tag" (is (nil? (validate nil "abc")))) (testing "tag is not a symbol or string" (is (thrown-with-msg? AssertionError #"Setting :tag should be a symbol or string, got: \^clojure\.lang\.Keyword :string" (validate :string "Green Friend")))) (doseq [[tag valid-tag?] {"String" false "java.lang.String" true 'STRING false `str false `String true} [value valid-value?] {"Green Friend" true :green-friend false}] (testing (format "Tag = %s (valid = %b)" (pr-str tag) valid-tag?) (testing (format "Value = %s (valid = %b)" (pr-str value) valid-value?) (cond (and valid-tag? valid-value?) (is (nil? (validate tag value))) (not valid-tag?) (is (thrown-with-msg? Exception #"Cannot resolve :tag .+ to a class" (validate tag value))) (not valid-value?) (is (thrown-with-msg? Exception #"Wrong :default type: got \^clojure\.lang\.Keyword :green-friend, but expected a java\.lang\.String" (validate tag value)))))))))
[ { "context": "ll each render frame:\n(defn render []\n (println \"tjosan\"))\n\n; Deref prevents program terminating before t", "end": 297, "score": 0.8553306460380554, "start": 291, "tag": "NAME", "value": "tjosan" } ]
LWJGL/ex01 - hello window/src/main.clj
hoppfull/Legacy-Clojure
0
(ns main) (load "graphics/window") ; A handle for closing program remotely (such as from input) (def close? (atom false)) ; Mechanism to simulate a remote close request: (future (Thread/sleep 1000) (swap! close? not)) ; Function to call each render frame: (defn render [] (println "tjosan")) ; Deref prevents program terminating before thread is finished: @(window/renderThread close? render) (System/exit 0) ; Terminate program
72367
(ns main) (load "graphics/window") ; A handle for closing program remotely (such as from input) (def close? (atom false)) ; Mechanism to simulate a remote close request: (future (Thread/sleep 1000) (swap! close? not)) ; Function to call each render frame: (defn render [] (println "<NAME>")) ; Deref prevents program terminating before thread is finished: @(window/renderThread close? render) (System/exit 0) ; Terminate program
true
(ns main) (load "graphics/window") ; A handle for closing program remotely (such as from input) (def close? (atom false)) ; Mechanism to simulate a remote close request: (future (Thread/sleep 1000) (swap! close? not)) ; Function to call each render frame: (defn render [] (println "PI:NAME:<NAME>END_PI")) ; Deref prevents program terminating before thread is finished: @(window/renderThread close? render) (System/exit 0) ; Terminate program
[ { "context": " \"clojure implementation of SHA-3\"\n :author \"Joshua Greenberg\"}\n joshua-g.sha-3\n (:require [hiphip.long :as h", "end": 76, "score": 0.999882698059082, "start": 60, "tag": "NAME", "value": "Joshua Greenberg" } ]
src/joshua_g/sha_3.clj
mikroskeem/clojure-sha-3
4
(ns ^{:doc "clojure implementation of SHA-3" :author "Joshua Greenberg"} joshua-g.sha-3 (:require [hiphip.long :as hl])) ; for mutable array sugar (set! *unchecked-math* true) (declare keccak-1600) (declare round-1600) (declare break-into-blocks-and-pad) (declare split-into-words) (declare word-to-little-endian-bytes) (def ^:private sha-3-base-params {:domain-suffix 2r10, :suffix-len 2}) (defn- to-hex-string [bytes] (apply str (map (partial format "%02x") bytes))) (defn- sha-3-with-size [size] (comp to-hex-string (partial keccak-1600 (assoc sha-3-base-params :output-size size)))) (def sha-3-224 (sha-3-with-size 224)) (def sha-3-256 (sha-3-with-size 256)) (def sha-3-384 (sha-3-with-size 384)) (def sha-3-512 (sha-3-with-size 512)) (def ^:private round-constants [0x0000000000000001 0x0000000000008082 -0x7FFFFFFFFFFF7F76 -0x7FFFFFFF7FFF8000 0x000000000000808b 0x0000000080000001 -0x7FFFFFFF7FFF7F7F -0x7FFFFFFFFFFF7FF7 0x000000000000008a 0x0000000000000088 0x0000000080008009 0x000000008000000a 0x000000008000808b -0x7FFFFFFFFFFFFF75 -0x7FFFFFFFFFFF7F77 -0x7FFFFFFFFFFF7FFD -0x7FFFFFFFFFFF7FFE -0x7FFFFFFFFFFFFF80 0x000000000000800a -0x7FFFFFFF7FFFFFF6 -0x7FFFFFFF7FFF7F7F -0x7FFFFFFFFFFF7F80 0x0000000080000001 -0x7FFFFFFF7FFF7FF8]) (def ^:private rotation-offsets (long-array [0 1 62 28 27 36 44 6 55 20 3 10 43 25 39 41 45 15 21 8 18 2 61 56 14])) (def ^:private pi-permutation (long-array [0 6 12 18 24 3 9 10 16 22 1 7 13 19 20 4 5 11 17 23 2 8 14 15 21])) (defn- calc-bit-rate [params] (- 1600 (* 2 (params :output-size)))) (defn keccak-1600 [params byte-coll] "Keccak with b = 1600, i.e. 64-bit words and 24 rounds per block" {:pre [(coll? byte-coll)]} (let [init-state (repeat 25 0) block-size-in-words (quot (calc-bit-rate params) 64) output-size-in-bytes (quot (params :output-size) 8) keccak-f (fn [state] (reduce round-1600 (long-array state) round-constants)) absorb-block (fn [state block] (->> (concat (split-into-words block) (repeat 0)) (map bit-xor state) keccak-f)) squeeze (partial take block-size-in-words)] (->> byte-coll (break-into-blocks-and-pad params) (reduce absorb-block init-state) (iterate keccak-f) (mapcat squeeze) (mapcat word-to-little-endian-bytes) (take output-size-in-bytes)))) (defmacro ^:private positive-rotate [n x] `(let [n# (long ~n) x# (long ~x)] (bit-or (bit-shift-left x# n#) (unsigned-bit-shift-right x# (- 64 n#))))) (defmacro ^:private chi-combinator [a b c] `(bit-xor (long ~a) (bit-and (long ~c) (bit-not (long ~b))))) (def ^:private i-rem-5 (hl/amake [i 25] (rem i 5))) (def ^:private inc-i-rem-5 (hl/amake [i 25] (rem (inc i) 5))) (def ^:private dec-i-rem-5 (hl/amake [i 25] (rem (+ i 4) 5))) (def ^:private chi-index-1 (hl/amake [i 25] (+ i (- (rem (+ i 1) 5) (rem i 5))))) (def ^:private chi-index-2 (hl/amake [i 25] (+ i (- (rem (+ i 2) 5) (rem i 5))))) (defn- round-1600 [state-array ^long round-constant] (let [theta (fn [sa] (let [c (let [c (long-array 5 0)] (hl/doarr [[i w] sa m i-rem-5] (hl/aset c m (bit-xor w (hl/aget c m)))) c)] (hl/doarr [[i w] sa i+ inc-i-rem-5 i- dec-i-rem-5] (hl/aset sa i (bit-xor w (hl/aget c i-) (positive-rotate 1 (hl/aget c i+)))))) sa) rho (fn [sa] (hl/doarr [[i w] sa rot rotation-offsets] (hl/aset sa i (positive-rotate rot w))) sa) pi (fn [sa] (hl/amake [i 25] (hl/aget sa (hl/aget pi-permutation i)))) chi (fn [sa] (hl/amap [w sa j chi-index-1 k chi-index-2] (chi-combinator w (hl/aget sa j) (hl/aget sa k)))) iota (fn [sa] (hl/aset sa 0 (bit-xor round-constant (hl/aget sa 0))) sa) ] (-> state-array theta rho pi chi iota))) (defn- break-into-blocks-and-pad [params input-bytes] (let [block-size-in-bytes (quot (calc-bit-rate params) 8) padding-bytes (fn [message-byte-count] (as-> (inc message-byte-count) $ (mod (- $) block-size-in-bytes) (repeat $ 0x00))) suffix-and-padding (fn [message-byte-count] (as-> (params :domain-suffix) $ (bit-or $ (bit-shift-left 1 (params :suffix-len))) (apply vector $ (padding-bytes message-byte-count)) (update $ (dec (count $)) bit-xor 0x80))) lazily-pad (fn lp [bs] (let [[block rst] (split-at block-size-in-bytes bs) n (count block)] (if (< n block-size-in-bytes) [(concat block (suffix-and-padding n))] (lazy-seq (cons block (lp rst)))))) ] (lazily-pad input-bytes))) (defn- little-endian-bytes-to-word [bs] (->> [0 (map vector (range) bs)] (apply reduce (fn [x [i b]] (bit-or x (bit-shift-left b (* i 8))))))) (defn- word-to-little-endian-bytes [w] (->> [[] w] (iterate (fn [[bs x]] [(conj bs (bit-and 0xFF x)) (unsigned-bit-shift-right x 8)])) (#(nth % 8)) first)) (defn- split-into-words [bs] (->> (partition 8 bs) (map little-endian-bytes-to-word)))
117511
(ns ^{:doc "clojure implementation of SHA-3" :author "<NAME>"} joshua-g.sha-3 (:require [hiphip.long :as hl])) ; for mutable array sugar (set! *unchecked-math* true) (declare keccak-1600) (declare round-1600) (declare break-into-blocks-and-pad) (declare split-into-words) (declare word-to-little-endian-bytes) (def ^:private sha-3-base-params {:domain-suffix 2r10, :suffix-len 2}) (defn- to-hex-string [bytes] (apply str (map (partial format "%02x") bytes))) (defn- sha-3-with-size [size] (comp to-hex-string (partial keccak-1600 (assoc sha-3-base-params :output-size size)))) (def sha-3-224 (sha-3-with-size 224)) (def sha-3-256 (sha-3-with-size 256)) (def sha-3-384 (sha-3-with-size 384)) (def sha-3-512 (sha-3-with-size 512)) (def ^:private round-constants [0x0000000000000001 0x0000000000008082 -0x7FFFFFFFFFFF7F76 -0x7FFFFFFF7FFF8000 0x000000000000808b 0x0000000080000001 -0x7FFFFFFF7FFF7F7F -0x7FFFFFFFFFFF7FF7 0x000000000000008a 0x0000000000000088 0x0000000080008009 0x000000008000000a 0x000000008000808b -0x7FFFFFFFFFFFFF75 -0x7FFFFFFFFFFF7F77 -0x7FFFFFFFFFFF7FFD -0x7FFFFFFFFFFF7FFE -0x7FFFFFFFFFFFFF80 0x000000000000800a -0x7FFFFFFF7FFFFFF6 -0x7FFFFFFF7FFF7F7F -0x7FFFFFFFFFFF7F80 0x0000000080000001 -0x7FFFFFFF7FFF7FF8]) (def ^:private rotation-offsets (long-array [0 1 62 28 27 36 44 6 55 20 3 10 43 25 39 41 45 15 21 8 18 2 61 56 14])) (def ^:private pi-permutation (long-array [0 6 12 18 24 3 9 10 16 22 1 7 13 19 20 4 5 11 17 23 2 8 14 15 21])) (defn- calc-bit-rate [params] (- 1600 (* 2 (params :output-size)))) (defn keccak-1600 [params byte-coll] "Keccak with b = 1600, i.e. 64-bit words and 24 rounds per block" {:pre [(coll? byte-coll)]} (let [init-state (repeat 25 0) block-size-in-words (quot (calc-bit-rate params) 64) output-size-in-bytes (quot (params :output-size) 8) keccak-f (fn [state] (reduce round-1600 (long-array state) round-constants)) absorb-block (fn [state block] (->> (concat (split-into-words block) (repeat 0)) (map bit-xor state) keccak-f)) squeeze (partial take block-size-in-words)] (->> byte-coll (break-into-blocks-and-pad params) (reduce absorb-block init-state) (iterate keccak-f) (mapcat squeeze) (mapcat word-to-little-endian-bytes) (take output-size-in-bytes)))) (defmacro ^:private positive-rotate [n x] `(let [n# (long ~n) x# (long ~x)] (bit-or (bit-shift-left x# n#) (unsigned-bit-shift-right x# (- 64 n#))))) (defmacro ^:private chi-combinator [a b c] `(bit-xor (long ~a) (bit-and (long ~c) (bit-not (long ~b))))) (def ^:private i-rem-5 (hl/amake [i 25] (rem i 5))) (def ^:private inc-i-rem-5 (hl/amake [i 25] (rem (inc i) 5))) (def ^:private dec-i-rem-5 (hl/amake [i 25] (rem (+ i 4) 5))) (def ^:private chi-index-1 (hl/amake [i 25] (+ i (- (rem (+ i 1) 5) (rem i 5))))) (def ^:private chi-index-2 (hl/amake [i 25] (+ i (- (rem (+ i 2) 5) (rem i 5))))) (defn- round-1600 [state-array ^long round-constant] (let [theta (fn [sa] (let [c (let [c (long-array 5 0)] (hl/doarr [[i w] sa m i-rem-5] (hl/aset c m (bit-xor w (hl/aget c m)))) c)] (hl/doarr [[i w] sa i+ inc-i-rem-5 i- dec-i-rem-5] (hl/aset sa i (bit-xor w (hl/aget c i-) (positive-rotate 1 (hl/aget c i+)))))) sa) rho (fn [sa] (hl/doarr [[i w] sa rot rotation-offsets] (hl/aset sa i (positive-rotate rot w))) sa) pi (fn [sa] (hl/amake [i 25] (hl/aget sa (hl/aget pi-permutation i)))) chi (fn [sa] (hl/amap [w sa j chi-index-1 k chi-index-2] (chi-combinator w (hl/aget sa j) (hl/aget sa k)))) iota (fn [sa] (hl/aset sa 0 (bit-xor round-constant (hl/aget sa 0))) sa) ] (-> state-array theta rho pi chi iota))) (defn- break-into-blocks-and-pad [params input-bytes] (let [block-size-in-bytes (quot (calc-bit-rate params) 8) padding-bytes (fn [message-byte-count] (as-> (inc message-byte-count) $ (mod (- $) block-size-in-bytes) (repeat $ 0x00))) suffix-and-padding (fn [message-byte-count] (as-> (params :domain-suffix) $ (bit-or $ (bit-shift-left 1 (params :suffix-len))) (apply vector $ (padding-bytes message-byte-count)) (update $ (dec (count $)) bit-xor 0x80))) lazily-pad (fn lp [bs] (let [[block rst] (split-at block-size-in-bytes bs) n (count block)] (if (< n block-size-in-bytes) [(concat block (suffix-and-padding n))] (lazy-seq (cons block (lp rst)))))) ] (lazily-pad input-bytes))) (defn- little-endian-bytes-to-word [bs] (->> [0 (map vector (range) bs)] (apply reduce (fn [x [i b]] (bit-or x (bit-shift-left b (* i 8))))))) (defn- word-to-little-endian-bytes [w] (->> [[] w] (iterate (fn [[bs x]] [(conj bs (bit-and 0xFF x)) (unsigned-bit-shift-right x 8)])) (#(nth % 8)) first)) (defn- split-into-words [bs] (->> (partition 8 bs) (map little-endian-bytes-to-word)))
true
(ns ^{:doc "clojure implementation of SHA-3" :author "PI:NAME:<NAME>END_PI"} joshua-g.sha-3 (:require [hiphip.long :as hl])) ; for mutable array sugar (set! *unchecked-math* true) (declare keccak-1600) (declare round-1600) (declare break-into-blocks-and-pad) (declare split-into-words) (declare word-to-little-endian-bytes) (def ^:private sha-3-base-params {:domain-suffix 2r10, :suffix-len 2}) (defn- to-hex-string [bytes] (apply str (map (partial format "%02x") bytes))) (defn- sha-3-with-size [size] (comp to-hex-string (partial keccak-1600 (assoc sha-3-base-params :output-size size)))) (def sha-3-224 (sha-3-with-size 224)) (def sha-3-256 (sha-3-with-size 256)) (def sha-3-384 (sha-3-with-size 384)) (def sha-3-512 (sha-3-with-size 512)) (def ^:private round-constants [0x0000000000000001 0x0000000000008082 -0x7FFFFFFFFFFF7F76 -0x7FFFFFFF7FFF8000 0x000000000000808b 0x0000000080000001 -0x7FFFFFFF7FFF7F7F -0x7FFFFFFFFFFF7FF7 0x000000000000008a 0x0000000000000088 0x0000000080008009 0x000000008000000a 0x000000008000808b -0x7FFFFFFFFFFFFF75 -0x7FFFFFFFFFFF7F77 -0x7FFFFFFFFFFF7FFD -0x7FFFFFFFFFFF7FFE -0x7FFFFFFFFFFFFF80 0x000000000000800a -0x7FFFFFFF7FFFFFF6 -0x7FFFFFFF7FFF7F7F -0x7FFFFFFFFFFF7F80 0x0000000080000001 -0x7FFFFFFF7FFF7FF8]) (def ^:private rotation-offsets (long-array [0 1 62 28 27 36 44 6 55 20 3 10 43 25 39 41 45 15 21 8 18 2 61 56 14])) (def ^:private pi-permutation (long-array [0 6 12 18 24 3 9 10 16 22 1 7 13 19 20 4 5 11 17 23 2 8 14 15 21])) (defn- calc-bit-rate [params] (- 1600 (* 2 (params :output-size)))) (defn keccak-1600 [params byte-coll] "Keccak with b = 1600, i.e. 64-bit words and 24 rounds per block" {:pre [(coll? byte-coll)]} (let [init-state (repeat 25 0) block-size-in-words (quot (calc-bit-rate params) 64) output-size-in-bytes (quot (params :output-size) 8) keccak-f (fn [state] (reduce round-1600 (long-array state) round-constants)) absorb-block (fn [state block] (->> (concat (split-into-words block) (repeat 0)) (map bit-xor state) keccak-f)) squeeze (partial take block-size-in-words)] (->> byte-coll (break-into-blocks-and-pad params) (reduce absorb-block init-state) (iterate keccak-f) (mapcat squeeze) (mapcat word-to-little-endian-bytes) (take output-size-in-bytes)))) (defmacro ^:private positive-rotate [n x] `(let [n# (long ~n) x# (long ~x)] (bit-or (bit-shift-left x# n#) (unsigned-bit-shift-right x# (- 64 n#))))) (defmacro ^:private chi-combinator [a b c] `(bit-xor (long ~a) (bit-and (long ~c) (bit-not (long ~b))))) (def ^:private i-rem-5 (hl/amake [i 25] (rem i 5))) (def ^:private inc-i-rem-5 (hl/amake [i 25] (rem (inc i) 5))) (def ^:private dec-i-rem-5 (hl/amake [i 25] (rem (+ i 4) 5))) (def ^:private chi-index-1 (hl/amake [i 25] (+ i (- (rem (+ i 1) 5) (rem i 5))))) (def ^:private chi-index-2 (hl/amake [i 25] (+ i (- (rem (+ i 2) 5) (rem i 5))))) (defn- round-1600 [state-array ^long round-constant] (let [theta (fn [sa] (let [c (let [c (long-array 5 0)] (hl/doarr [[i w] sa m i-rem-5] (hl/aset c m (bit-xor w (hl/aget c m)))) c)] (hl/doarr [[i w] sa i+ inc-i-rem-5 i- dec-i-rem-5] (hl/aset sa i (bit-xor w (hl/aget c i-) (positive-rotate 1 (hl/aget c i+)))))) sa) rho (fn [sa] (hl/doarr [[i w] sa rot rotation-offsets] (hl/aset sa i (positive-rotate rot w))) sa) pi (fn [sa] (hl/amake [i 25] (hl/aget sa (hl/aget pi-permutation i)))) chi (fn [sa] (hl/amap [w sa j chi-index-1 k chi-index-2] (chi-combinator w (hl/aget sa j) (hl/aget sa k)))) iota (fn [sa] (hl/aset sa 0 (bit-xor round-constant (hl/aget sa 0))) sa) ] (-> state-array theta rho pi chi iota))) (defn- break-into-blocks-and-pad [params input-bytes] (let [block-size-in-bytes (quot (calc-bit-rate params) 8) padding-bytes (fn [message-byte-count] (as-> (inc message-byte-count) $ (mod (- $) block-size-in-bytes) (repeat $ 0x00))) suffix-and-padding (fn [message-byte-count] (as-> (params :domain-suffix) $ (bit-or $ (bit-shift-left 1 (params :suffix-len))) (apply vector $ (padding-bytes message-byte-count)) (update $ (dec (count $)) bit-xor 0x80))) lazily-pad (fn lp [bs] (let [[block rst] (split-at block-size-in-bytes bs) n (count block)] (if (< n block-size-in-bytes) [(concat block (suffix-and-padding n))] (lazy-seq (cons block (lp rst)))))) ] (lazily-pad input-bytes))) (defn- little-endian-bytes-to-word [bs] (->> [0 (map vector (range) bs)] (apply reduce (fn [x [i b]] (bit-or x (bit-shift-left b (* i 8))))))) (defn- word-to-little-endian-bytes [w] (->> [[] w] (iterate (fn [[bs x]] [(conj bs (bit-and 0xFF x)) (unsigned-bit-shift-right x 8)])) (#(nth % 8)) first)) (defn- split-into-words [bs] (->> (partition 8 bs) (map little-endian-bytes-to-word)))
[ { "context": "(\n ; Context map\n {}\n\n \"0\"\n \"нуль\"\n (number 0)\n\n \"1\"\n \"один\"\n (number 1)\n\n ", "end": 34, "score": 0.5523261427879333, "start": 33, "tag": "NAME", "value": "н" }, { "context": "r 1)\n\n \"2\"\n \"02\"\n \"два\"\n (number 2)\n\n \"3\"\n \"три\"\n \"03\"\n (number 3)\n\n \"4\"\n \"чотири\"\n \"04\"\n ", "end": 127, "score": 0.5678195357322693, "start": 126, "tag": "NAME", "value": "т" } ]
resources/languages/uk/corpus/numbers.clj
guivn/duckling
922
( ; Context map {} "0" "нуль" (number 0) "1" "один" (number 1) "2" "02" "два" (number 2) "3" "три" "03" (number 3) "4" "чотири" "04" (number 4) "п‘ять" "5" "05" (number 5) "33" "тридцять три" "0033" (number 33) "14" "чотирнадцять" (number 14) "16" "шістнадцять" (number 16) "17" "сімнадцять" (number 17) "18" "вісімнадцять" (number 18) "п‘ятсот двадцять п‘ять" "525" (number 525) "1.1" "1.10" "01.10" "1 крапка 1" "один крапка один" (number 1.1) "0.77" ".77" (number 0.77) "100000" "100к" "100К" (number 100000) "3М" "3000К" "3000000" (number 3000000) "1200000" "1.2М" "1200К" ".0012Г" (number 1200000) "-1200000" "мінус 1200000" "-1.2М" "-1200К" "-.0012Г" (number -1200000) ;; ;; Ordinals ;; "перший" "перша" "перше" "1а" "1-а" "1ий" "1-ий" "1е" "1-е" (ordinal 1) "четвертий" "четверта" "четверте" "4ий" "4а" "4е" "4-ий" "4-а" "4-е" (ordinal 4) "п‘ятнадцятий" "15й" "15-й" (ordinal 15) "21й" "21-й" "двадцять перший" (ordinal 21) "31ий" "31-ий" "тридцять перший" (ordinal 31) "48е" "48-е" "сорок восьме" (ordinal 48) "99ий" "99-й" "дев‘яносто дев‘ятий" (ordinal 99) )
115936
( ; Context map {} "0" "<NAME>уль" (number 0) "1" "один" (number 1) "2" "02" "два" (number 2) "3" "<NAME>ри" "03" (number 3) "4" "чотири" "04" (number 4) "п‘ять" "5" "05" (number 5) "33" "тридцять три" "0033" (number 33) "14" "чотирнадцять" (number 14) "16" "шістнадцять" (number 16) "17" "сімнадцять" (number 17) "18" "вісімнадцять" (number 18) "п‘ятсот двадцять п‘ять" "525" (number 525) "1.1" "1.10" "01.10" "1 крапка 1" "один крапка один" (number 1.1) "0.77" ".77" (number 0.77) "100000" "100к" "100К" (number 100000) "3М" "3000К" "3000000" (number 3000000) "1200000" "1.2М" "1200К" ".0012Г" (number 1200000) "-1200000" "мінус 1200000" "-1.2М" "-1200К" "-.0012Г" (number -1200000) ;; ;; Ordinals ;; "перший" "перша" "перше" "1а" "1-а" "1ий" "1-ий" "1е" "1-е" (ordinal 1) "четвертий" "четверта" "четверте" "4ий" "4а" "4е" "4-ий" "4-а" "4-е" (ordinal 4) "п‘ятнадцятий" "15й" "15-й" (ordinal 15) "21й" "21-й" "двадцять перший" (ordinal 21) "31ий" "31-ий" "тридцять перший" (ordinal 31) "48е" "48-е" "сорок восьме" (ordinal 48) "99ий" "99-й" "дев‘яносто дев‘ятий" (ordinal 99) )
true
( ; Context map {} "0" "PI:NAME:<NAME>END_PIуль" (number 0) "1" "один" (number 1) "2" "02" "два" (number 2) "3" "PI:NAME:<NAME>END_PIри" "03" (number 3) "4" "чотири" "04" (number 4) "п‘ять" "5" "05" (number 5) "33" "тридцять три" "0033" (number 33) "14" "чотирнадцять" (number 14) "16" "шістнадцять" (number 16) "17" "сімнадцять" (number 17) "18" "вісімнадцять" (number 18) "п‘ятсот двадцять п‘ять" "525" (number 525) "1.1" "1.10" "01.10" "1 крапка 1" "один крапка один" (number 1.1) "0.77" ".77" (number 0.77) "100000" "100к" "100К" (number 100000) "3М" "3000К" "3000000" (number 3000000) "1200000" "1.2М" "1200К" ".0012Г" (number 1200000) "-1200000" "мінус 1200000" "-1.2М" "-1200К" "-.0012Г" (number -1200000) ;; ;; Ordinals ;; "перший" "перша" "перше" "1а" "1-а" "1ий" "1-ий" "1е" "1-е" (ordinal 1) "четвертий" "четверта" "четверте" "4ий" "4а" "4е" "4-ий" "4-а" "4-е" (ordinal 4) "п‘ятнадцятий" "15й" "15-й" (ordinal 15) "21й" "21-й" "двадцять перший" (ordinal 21) "31ий" "31-ий" "тридцять перший" (ordinal 31) "48е" "48-е" "сорок восьме" (ordinal 48) "99ий" "99-й" "дев‘яносто дев‘ятий" (ordinal 99) )
[ { "context": "ss))\n\n;; Will result into '(if true (do (println \"henlo\")))'\n(macroexpand-1 '(when true (println \"henlo\")", "end": 92, "score": 0.7151526212692261, "start": 87, "tag": "NAME", "value": "henlo" }, { "context": " \"henlo\")))'\n(macroexpand-1 '(when true (println \"henlo\")))\n", "end": 140, "score": 0.9496005773544312, "start": 135, "tag": "NAME", "value": "henlo" } ]
src/clojure_course/macros.clj
gbartoczevicz/clojure-course
1
(ns clojure-course.macros (:gen-class)) ;; Will result into '(if true (do (println "henlo")))' (macroexpand-1 '(when true (println "henlo")))
119909
(ns clojure-course.macros (:gen-class)) ;; Will result into '(if true (do (println "<NAME>")))' (macroexpand-1 '(when true (println "<NAME>")))
true
(ns clojure-course.macros (:gen-class)) ;; Will result into '(if true (do (println "PI:NAME:<NAME>END_PI")))' (macroexpand-1 '(when true (println "PI:NAME:<NAME>END_PI")))
[ { "context": " :clientSecret \"ABCDEF...\"}})\n\n\n(deftest check-metadata\n (mdtu/check-metada", "end": 2052, "score": 0.8573012948036194, "start": 2042, "tag": "KEY", "value": "ABCDEF...\"" }, { "context": "callback)\n\n (let [github-login (str \"GITHUB_USER_\" n)\n email (format \"user-%s@exa", "end": 9880, "score": 0.9658287763595581, "start": 9868, "tag": "USERNAME", "value": "GITHUB_USER_" }, { "context": "THUB_USER_\" n)\n email (format \"user-%s@example.com\" n)]\n\n (with-redefs [auth-github/g", "end": 9939, "score": 0.9977278709411621, "start": 9920, "tag": "EMAIL", "value": "user-%s@example.com" } ]
cimi/test/com/sixsq/slipstream/ssclj/resources/user_template_github_lifecycle_test.clj
slipstream/SlipStreamServer
6
(ns com.sixsq.slipstream.ssclj.resources.user-template-github-lifecycle-test (:require [clojure.data.json :as json] [clojure.test :refer [are deftest is use-fixtures]] [com.sixsq.slipstream.auth.external :as ex] [com.sixsq.slipstream.auth.github :as auth-github] [com.sixsq.slipstream.auth.utils.db :as db] [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.user :as user] [com.sixsq.slipstream.ssclj.resources.user-template :as ut] [com.sixsq.slipstream.ssclj.resources.user-template-github :as github] [com.sixsq.slipstream.ssclj.resources.user.user-identifier-utils :as uiu] [com.sixsq.slipstream.ssclj.util.metadata-test-utils :as mdtu] [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 user/resource-name))) (def configuration-base-uri (str p/service-context (u/de-camelcase configuration/resource-name))) (def user-template-base-uri (str p/service-context (u/de-camelcase ut/resource-name))) (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 configuration-user-github {:configurationTemplate {:service "session-github" ;;reusing configuration from session GitHub :instance github/registration-method :clientID "FAKE_CLIENT_ID" :clientSecret "ABCDEF..."}}) (deftest check-metadata (mdtu/check-metadata-exists (str ut/resource-url "-" github/resource-url))) (deftest lifecycle (let [href (str ut/resource-url "/" github/registration-method) template-url (str p/service-context ut/resource-url "/" github/registration-method) 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 user/form-urlencoded)) redirect-uri-example "https://example.com/webui"] ;; must create the github user template; this is not created automatically (let [user-template (->> {:group "my-group" :icon "some-icon" :order 10 :hidden false} (merge github/resource) json/write-str)] (-> session-admin (request user-template-base-uri :request-method :post :body user-template) (ltu/is-status 201)) (-> session-anon (request template-url) (ltu/body->edn) (ltu/is-status 200) (get-in [:response :body]))) ;; get user template so that user resources can be tested (let [name-attr "name" description-attr "description" properties-attr {:a "one", :b "two"} href-create {:name name-attr :description description-attr :properties properties-attr :userTemplate {:href href}} href-create-redirect {:userTemplate {:href href :redirectURI redirect-uri-example}} invalid-create (assoc-in href-create [:userTemplate :invalid] "BAD")] ;; queries by anyone should succeed but have no entries (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?))) ;; configuration must have GitHub client ID or secret, 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)) ;; create the session-github configuration to use for these tests (let [cfg-href (-> session-admin (request configuration-base-uri :request-method :post :body (json/write-str configuration-user-github)) (ltu/body->edn) (ltu/is-status 201) (ltu/location))] (is (= cfg-href (str "configuration/session-github-" github/registration-method))) (let [resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 303)) redirect-uri (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/location)) uri (-> resp ltu/location) resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create-redirect)) (ltu/body->edn) (ltu/is-status 303)) uri2 (-> resp ltu/location) resp (-> session-anon-form (request base-uri :request-method :post :body (codec/form-encode {:href href :redirectURI redirect-uri-example})) (ltu/body->edn) (ltu/is-status 303)) uri3 (-> resp ltu/location) uris [uri uri2 uri3]] ;; redirect URLs in location header should contain the client ID and resource id (doseq [u uris] (is (re-matches #".*FAKE_CLIENT_ID.*" (or u ""))) (is (re-matches callback-pattern (or u "")))) ;; anonymous, user and admin query should succeed but have no users (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?))) ;; ;; test validation callback ;; (let [get-redirect-uri #(->> % (re-matches #".*redirect_uri=(.*)$") second) get-callback-id #(->> % (re-matches #".*(callback.*)/execute$") second) validate-urls (map get-redirect-uri uris) callbacks (map get-callback-id validate-urls)] ;; all callbacks must exist (doseq [callback callbacks] (-> session-admin (request (str p/service-context callback)) (ltu/body->edn) (ltu/is-status 200))) ;; remove the authentication configuration (-> 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 ;; when a redirectURI is present, the return is 303 even on errors (doseq [[url status] (map vector validate-urls [500 303 303])] (-> session-anon (request url :request-method :get) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status status))) ;; add the configuration back again (-> session-admin (request configuration-base-uri :request-method :post :body (json/write-str configuration-user-github)) (ltu/body->edn) (ltu/is-status 201)) ;; try hitting the callback without the OAuth code parameter ;; when a redirectURI is present, the return is 303 even on errors (doseq [[callback url status] (map vector callbacks validate-urls [400 303 303])] (reset-callback! callback) (-> session-anon (request url :request-method :get) (ltu/body->edn) (ltu/message-matches #".*not contain required code.*") (ltu/is-status status))) ;; try hitting the callback with mocked codes (doseq [[callback url status create-status n] (map vector callbacks validate-urls [400 303 303] [201 303 303] (range))] (reset-callback! callback) (let [github-login (str "GITHUB_USER_" n) email (format "user-%s@example.com" n)] (with-redefs [auth-github/get-github-access-token (fn [client-id client-secret oauth-code] (case oauth-code "GOOD" "GOOD_ACCESS_CODE" "BAD" "BAD_ACCESS_CODE" nil)) auth-github/get-github-user-info (fn [access-code] (when (= access-code "GOOD_ACCESS_CODE") {:login github-login, :email email})) ex/match-existing-external-user (fn [authn-method external-login instance] "MATCHED_USER")] (-> session-anon (request (str url "?code=NONE") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*unable to retrieve GitHub access code.*") (ltu/is-status status)) (is (false? (db/user-exists? github-login))) (reset-callback! callback) (-> session-anon (request (str url "?code=BAD") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*unable to retrieve GitHub user information.*") (ltu/is-status status)) (is (nil? (uiu/find-username-by-identifier :github nil github-login))) (reset-callback! callback) (-> session-anon (request (str url "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/is-status create-status)) (let [ss-username (uiu/find-username-by-identifier :github nil github-login) user-record (->> github-login (uiu/find-username-by-identifier :github nil) (db/get-user))] (is (not (nil? ss-username))) (is (= email (:name user-record))) (is (= github/registration-method (:method user-record)))) ;; try creating the same user again, should fail (reset-callback! callback) (-> session-anon (request (str url "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*account already exists.*") (ltu/is-status status)))))) ;; 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 user/resource-name))] (ltu/verify-405-status [[base-uri :options] [base-uri :delete] [resource-uri :options] [resource-uri :put] [resource-uri :post]])))
26051
(ns com.sixsq.slipstream.ssclj.resources.user-template-github-lifecycle-test (:require [clojure.data.json :as json] [clojure.test :refer [are deftest is use-fixtures]] [com.sixsq.slipstream.auth.external :as ex] [com.sixsq.slipstream.auth.github :as auth-github] [com.sixsq.slipstream.auth.utils.db :as db] [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.user :as user] [com.sixsq.slipstream.ssclj.resources.user-template :as ut] [com.sixsq.slipstream.ssclj.resources.user-template-github :as github] [com.sixsq.slipstream.ssclj.resources.user.user-identifier-utils :as uiu] [com.sixsq.slipstream.ssclj.util.metadata-test-utils :as mdtu] [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 user/resource-name))) (def configuration-base-uri (str p/service-context (u/de-camelcase configuration/resource-name))) (def user-template-base-uri (str p/service-context (u/de-camelcase ut/resource-name))) (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 configuration-user-github {:configurationTemplate {:service "session-github" ;;reusing configuration from session GitHub :instance github/registration-method :clientID "FAKE_CLIENT_ID" :clientSecret "<KEY>}}) (deftest check-metadata (mdtu/check-metadata-exists (str ut/resource-url "-" github/resource-url))) (deftest lifecycle (let [href (str ut/resource-url "/" github/registration-method) template-url (str p/service-context ut/resource-url "/" github/registration-method) 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 user/form-urlencoded)) redirect-uri-example "https://example.com/webui"] ;; must create the github user template; this is not created automatically (let [user-template (->> {:group "my-group" :icon "some-icon" :order 10 :hidden false} (merge github/resource) json/write-str)] (-> session-admin (request user-template-base-uri :request-method :post :body user-template) (ltu/is-status 201)) (-> session-anon (request template-url) (ltu/body->edn) (ltu/is-status 200) (get-in [:response :body]))) ;; get user template so that user resources can be tested (let [name-attr "name" description-attr "description" properties-attr {:a "one", :b "two"} href-create {:name name-attr :description description-attr :properties properties-attr :userTemplate {:href href}} href-create-redirect {:userTemplate {:href href :redirectURI redirect-uri-example}} invalid-create (assoc-in href-create [:userTemplate :invalid] "BAD")] ;; queries by anyone should succeed but have no entries (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?))) ;; configuration must have GitHub client ID or secret, 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)) ;; create the session-github configuration to use for these tests (let [cfg-href (-> session-admin (request configuration-base-uri :request-method :post :body (json/write-str configuration-user-github)) (ltu/body->edn) (ltu/is-status 201) (ltu/location))] (is (= cfg-href (str "configuration/session-github-" github/registration-method))) (let [resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 303)) redirect-uri (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/location)) uri (-> resp ltu/location) resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create-redirect)) (ltu/body->edn) (ltu/is-status 303)) uri2 (-> resp ltu/location) resp (-> session-anon-form (request base-uri :request-method :post :body (codec/form-encode {:href href :redirectURI redirect-uri-example})) (ltu/body->edn) (ltu/is-status 303)) uri3 (-> resp ltu/location) uris [uri uri2 uri3]] ;; redirect URLs in location header should contain the client ID and resource id (doseq [u uris] (is (re-matches #".*FAKE_CLIENT_ID.*" (or u ""))) (is (re-matches callback-pattern (or u "")))) ;; anonymous, user and admin query should succeed but have no users (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?))) ;; ;; test validation callback ;; (let [get-redirect-uri #(->> % (re-matches #".*redirect_uri=(.*)$") second) get-callback-id #(->> % (re-matches #".*(callback.*)/execute$") second) validate-urls (map get-redirect-uri uris) callbacks (map get-callback-id validate-urls)] ;; all callbacks must exist (doseq [callback callbacks] (-> session-admin (request (str p/service-context callback)) (ltu/body->edn) (ltu/is-status 200))) ;; remove the authentication configuration (-> 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 ;; when a redirectURI is present, the return is 303 even on errors (doseq [[url status] (map vector validate-urls [500 303 303])] (-> session-anon (request url :request-method :get) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status status))) ;; add the configuration back again (-> session-admin (request configuration-base-uri :request-method :post :body (json/write-str configuration-user-github)) (ltu/body->edn) (ltu/is-status 201)) ;; try hitting the callback without the OAuth code parameter ;; when a redirectURI is present, the return is 303 even on errors (doseq [[callback url status] (map vector callbacks validate-urls [400 303 303])] (reset-callback! callback) (-> session-anon (request url :request-method :get) (ltu/body->edn) (ltu/message-matches #".*not contain required code.*") (ltu/is-status status))) ;; try hitting the callback with mocked codes (doseq [[callback url status create-status n] (map vector callbacks validate-urls [400 303 303] [201 303 303] (range))] (reset-callback! callback) (let [github-login (str "GITHUB_USER_" n) email (format "<EMAIL>" n)] (with-redefs [auth-github/get-github-access-token (fn [client-id client-secret oauth-code] (case oauth-code "GOOD" "GOOD_ACCESS_CODE" "BAD" "BAD_ACCESS_CODE" nil)) auth-github/get-github-user-info (fn [access-code] (when (= access-code "GOOD_ACCESS_CODE") {:login github-login, :email email})) ex/match-existing-external-user (fn [authn-method external-login instance] "MATCHED_USER")] (-> session-anon (request (str url "?code=NONE") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*unable to retrieve GitHub access code.*") (ltu/is-status status)) (is (false? (db/user-exists? github-login))) (reset-callback! callback) (-> session-anon (request (str url "?code=BAD") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*unable to retrieve GitHub user information.*") (ltu/is-status status)) (is (nil? (uiu/find-username-by-identifier :github nil github-login))) (reset-callback! callback) (-> session-anon (request (str url "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/is-status create-status)) (let [ss-username (uiu/find-username-by-identifier :github nil github-login) user-record (->> github-login (uiu/find-username-by-identifier :github nil) (db/get-user))] (is (not (nil? ss-username))) (is (= email (:name user-record))) (is (= github/registration-method (:method user-record)))) ;; try creating the same user again, should fail (reset-callback! callback) (-> session-anon (request (str url "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*account already exists.*") (ltu/is-status status)))))) ;; 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 user/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.user-template-github-lifecycle-test (:require [clojure.data.json :as json] [clojure.test :refer [are deftest is use-fixtures]] [com.sixsq.slipstream.auth.external :as ex] [com.sixsq.slipstream.auth.github :as auth-github] [com.sixsq.slipstream.auth.utils.db :as db] [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.user :as user] [com.sixsq.slipstream.ssclj.resources.user-template :as ut] [com.sixsq.slipstream.ssclj.resources.user-template-github :as github] [com.sixsq.slipstream.ssclj.resources.user.user-identifier-utils :as uiu] [com.sixsq.slipstream.ssclj.util.metadata-test-utils :as mdtu] [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 user/resource-name))) (def configuration-base-uri (str p/service-context (u/de-camelcase configuration/resource-name))) (def user-template-base-uri (str p/service-context (u/de-camelcase ut/resource-name))) (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 configuration-user-github {:configurationTemplate {:service "session-github" ;;reusing configuration from session GitHub :instance github/registration-method :clientID "FAKE_CLIENT_ID" :clientSecret "PI:KEY:<KEY>END_PI}}) (deftest check-metadata (mdtu/check-metadata-exists (str ut/resource-url "-" github/resource-url))) (deftest lifecycle (let [href (str ut/resource-url "/" github/registration-method) template-url (str p/service-context ut/resource-url "/" github/registration-method) 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 user/form-urlencoded)) redirect-uri-example "https://example.com/webui"] ;; must create the github user template; this is not created automatically (let [user-template (->> {:group "my-group" :icon "some-icon" :order 10 :hidden false} (merge github/resource) json/write-str)] (-> session-admin (request user-template-base-uri :request-method :post :body user-template) (ltu/is-status 201)) (-> session-anon (request template-url) (ltu/body->edn) (ltu/is-status 200) (get-in [:response :body]))) ;; get user template so that user resources can be tested (let [name-attr "name" description-attr "description" properties-attr {:a "one", :b "two"} href-create {:name name-attr :description description-attr :properties properties-attr :userTemplate {:href href}} href-create-redirect {:userTemplate {:href href :redirectURI redirect-uri-example}} invalid-create (assoc-in href-create [:userTemplate :invalid] "BAD")] ;; queries by anyone should succeed but have no entries (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?))) ;; configuration must have GitHub client ID or secret, 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)) ;; create the session-github configuration to use for these tests (let [cfg-href (-> session-admin (request configuration-base-uri :request-method :post :body (json/write-str configuration-user-github)) (ltu/body->edn) (ltu/is-status 201) (ltu/location))] (is (= cfg-href (str "configuration/session-github-" github/registration-method))) (let [resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/is-status 303)) redirect-uri (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create)) (ltu/body->edn) (ltu/location)) uri (-> resp ltu/location) resp (-> session-anon (request base-uri :request-method :post :body (json/write-str href-create-redirect)) (ltu/body->edn) (ltu/is-status 303)) uri2 (-> resp ltu/location) resp (-> session-anon-form (request base-uri :request-method :post :body (codec/form-encode {:href href :redirectURI redirect-uri-example})) (ltu/body->edn) (ltu/is-status 303)) uri3 (-> resp ltu/location) uris [uri uri2 uri3]] ;; redirect URLs in location header should contain the client ID and resource id (doseq [u uris] (is (re-matches #".*FAKE_CLIENT_ID.*" (or u ""))) (is (re-matches callback-pattern (or u "")))) ;; anonymous, user and admin query should succeed but have no users (doseq [session [session-anon session-user session-admin]] (-> session (request base-uri) (ltu/body->edn) (ltu/is-status 200) (ltu/is-count zero?))) ;; ;; test validation callback ;; (let [get-redirect-uri #(->> % (re-matches #".*redirect_uri=(.*)$") second) get-callback-id #(->> % (re-matches #".*(callback.*)/execute$") second) validate-urls (map get-redirect-uri uris) callbacks (map get-callback-id validate-urls)] ;; all callbacks must exist (doseq [callback callbacks] (-> session-admin (request (str p/service-context callback)) (ltu/body->edn) (ltu/is-status 200))) ;; remove the authentication configuration (-> 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 ;; when a redirectURI is present, the return is 303 even on errors (doseq [[url status] (map vector validate-urls [500 303 303])] (-> session-anon (request url :request-method :get) (ltu/body->edn) (ltu/message-matches #".*missing or incorrect configuration.*") (ltu/is-status status))) ;; add the configuration back again (-> session-admin (request configuration-base-uri :request-method :post :body (json/write-str configuration-user-github)) (ltu/body->edn) (ltu/is-status 201)) ;; try hitting the callback without the OAuth code parameter ;; when a redirectURI is present, the return is 303 even on errors (doseq [[callback url status] (map vector callbacks validate-urls [400 303 303])] (reset-callback! callback) (-> session-anon (request url :request-method :get) (ltu/body->edn) (ltu/message-matches #".*not contain required code.*") (ltu/is-status status))) ;; try hitting the callback with mocked codes (doseq [[callback url status create-status n] (map vector callbacks validate-urls [400 303 303] [201 303 303] (range))] (reset-callback! callback) (let [github-login (str "GITHUB_USER_" n) email (format "PI:EMAIL:<EMAIL>END_PI" n)] (with-redefs [auth-github/get-github-access-token (fn [client-id client-secret oauth-code] (case oauth-code "GOOD" "GOOD_ACCESS_CODE" "BAD" "BAD_ACCESS_CODE" nil)) auth-github/get-github-user-info (fn [access-code] (when (= access-code "GOOD_ACCESS_CODE") {:login github-login, :email email})) ex/match-existing-external-user (fn [authn-method external-login instance] "MATCHED_USER")] (-> session-anon (request (str url "?code=NONE") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*unable to retrieve GitHub access code.*") (ltu/is-status status)) (is (false? (db/user-exists? github-login))) (reset-callback! callback) (-> session-anon (request (str url "?code=BAD") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*unable to retrieve GitHub user information.*") (ltu/is-status status)) (is (nil? (uiu/find-username-by-identifier :github nil github-login))) (reset-callback! callback) (-> session-anon (request (str url "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/is-status create-status)) (let [ss-username (uiu/find-username-by-identifier :github nil github-login) user-record (->> github-login (uiu/find-username-by-identifier :github nil) (db/get-user))] (is (not (nil? ss-username))) (is (= email (:name user-record))) (is (= github/registration-method (:method user-record)))) ;; try creating the same user again, should fail (reset-callback! callback) (-> session-anon (request (str url "?code=GOOD") :request-method :get) (ltu/body->edn) (ltu/message-matches #".*account already exists.*") (ltu/is-status status)))))) ;; 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 user/resource-name))] (ltu/verify-405-status [[base-uri :options] [base-uri :delete] [resource-uri :options] [resource-uri :put] [resource-uri :post]])))
[ { "context": "ne) visible?)\n (let [user-data-key (keyword \"hidden-pane\" pane-id)\n {:keys [pane size]} (ui/use", "end": 5122, "score": 0.9825261235237122, "start": 5111, "tag": "KEY", "value": "hidden-pane" }, { "context": " (let [user-data-key (keyword \"hidden-pane\" pane-id)\n {:keys [pane size]} (ui/user-data sp", "end": 5131, "score": 0.7709875106811523, "start": 5129, "tag": "KEY", "value": "id" }, { "context": "ot visible?))\n (let [user-data-key (keyword \"hidden-pane\" pane-id)\n divider-index (max 0 (dec i", "end": 5820, "score": 0.9908304214477539, "start": 5809, "tag": "KEY", "value": "hidden-pane" }, { "context": " (let [user-data-key (keyword \"hidden-pane\" pane-id)\n divider-index (max 0 (dec index))\n ", "end": 5829, "score": 0.8766291737556458, "start": 5827, "tag": "KEY", "value": "id" }, { "context": ")))))\n\n(def ^:private open-assets-term-prefs-key \"open-assets-term\")\n\n(defn- query-and-open! [workspace project app-", "end": 95848, "score": 0.9978815913200378, "start": 95832, "tag": "KEY", "value": "open-assets-term" } ]
editor/src/clj/editor/app_view.clj
dapetcu21/defold
0
;; Copyright 2020 The Defold Foundation ;; 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.app-view (:require [clojure.java.io :as io] [clojure.edn :as edn] [clojure.string :as string] [dynamo.graph :as g] [editor.build :as build] [editor.build-errors-view :as build-errors-view] [editor.bundle :as bundle] [editor.bundle-dialog :as bundle-dialog] [editor.changes-view :as changes-view] [editor.code.data :refer [CursorRange->line-number]] [editor.console :as console] [editor.debug-view :as debug-view] [editor.defold-project :as project] [editor.dialogs :as dialogs] [editor.disk :as disk] [editor.disk-availability :as disk-availability] [editor.editor-extensions :as extensions] [editor.engine :as engine] [editor.engine.build-errors :as engine-build-errors] [editor.error-reporting :as error-reporting] [editor.fs :as fs] [editor.fxui :as fxui] [editor.game-project :as game-project] [editor.github :as github] [editor.graph-util :as gu] [editor.handler :as handler] [editor.hot-reload :as hot-reload] [editor.icons :as icons] [editor.keymap :as keymap] [editor.live-update-settings :as live-update-settings] [editor.lua :as lua] [editor.pipeline :as pipeline] [editor.pipeline.bob :as bob] [editor.placeholder-resource :as placeholder-resource] [editor.prefs :as prefs] [editor.prefs-dialog :as prefs-dialog] [editor.process :as process] [editor.progress :as progress] [editor.resource :as resource] [editor.resource-node :as resource-node] [editor.scene :as scene] [editor.scene-cache :as scene-cache] [editor.scene-visibility :as scene-visibility] [editor.search-results-view :as search-results-view] [editor.system :as system] [editor.targets :as targets] [editor.types :as types] [editor.ui :as ui] [editor.url :as url] [editor.util :as util] [editor.view :as view] [editor.workspace :as workspace] [internal.util :refer [first-where]] [service.log :as log] [util.http-server :as http-server] [util.profiler :as profiler] [util.thread-util :as thread-util] [service.smoke-log :as slog]) (:import [com.defold.editor Editor] [com.defold.editor UIUtil] [com.sun.javafx.scene NodeHelper] [java.io BufferedReader File IOException] [java.net URL] [java.util Collection List] [javafx.beans.value ChangeListener] [javafx.collections ListChangeListener ObservableList] [javafx.event Event] [javafx.geometry Orientation] [javafx.scene Parent Scene] [javafx.scene.control MenuBar SplitPane Tab TabPane TabPane$TabClosingPolicy TabPane$TabDragPolicy Tooltip] [javafx.scene.image Image ImageView] [javafx.scene.input Clipboard ClipboardContent] [javafx.scene.layout AnchorPane StackPane] [javafx.scene.shape Ellipse SVGPath] [javafx.stage Screen Stage WindowEvent])) (set! *warn-on-reflection* true) (def ^:private split-info-by-pane-kw {:left {:index 0 :pane-id "left-pane" :split-id "main-split"} :right {:index 1 :pane-id "right-pane" :split-id "workbench-split"} :bottom {:index 1 :pane-id "bottom-pane" :split-id "center-split"}}) (defn- pane-visible? [^Scene main-scene pane-kw] (let [{:keys [pane-id split-id]} (split-info-by-pane-kw pane-kw)] (some? (.lookup main-scene (str "#" split-id " #" pane-id))))) (defn- split-pane-length ^double [^SplitPane split-pane] (condp = (.getOrientation split-pane) Orientation/HORIZONTAL (.getWidth split-pane) Orientation/VERTICAL (.getHeight split-pane))) (defn- set-pane-visible! [^Scene main-scene pane-kw visible?] (let [{:keys [index pane-id split-id]} (split-info-by-pane-kw pane-kw) ^SplitPane split (.lookup main-scene (str "#" split-id)) ^Parent pane (.lookup split (str "#" pane-id))] (cond (and (nil? pane) visible?) (let [user-data-key (keyword "hidden-pane" pane-id) {:keys [pane size]} (ui/user-data split user-data-key) divider-index (max 0 (dec index)) divider-position (max 0.0 (min (if (zero? index) (/ size (split-pane-length split)) (- 1.0 (/ size (split-pane-length split)))) 1.0))] (ui/user-data! split user-data-key nil) (.add (.getItems split) index pane) (.setDividerPosition split divider-index divider-position) (.layout split)) (and (some? pane) (not visible?)) (let [user-data-key (keyword "hidden-pane" pane-id) divider-index (max 0 (dec index)) divider-position (get (.getDividerPositions split) divider-index) size (if (zero? index) (Math/floor (* divider-position (split-pane-length split))) (Math/ceil (* (- 1.0 divider-position) (split-pane-length split)))) removing-focus-owner? (some? (when-some [focus-owner (.getFocusOwner main-scene)] (ui/closest-node-where (partial identical? pane) focus-owner)))] (ui/user-data! split user-data-key {:pane pane :size size}) (.remove (.getItems split) pane) (.layout split) ;; If this action causes the focus owner to be removed from the scene, ;; move focus to the SplitPane. This ensures we have a valid UI context ;; when refreshing the menus. (when removing-focus-owner? (.requestFocus split)))) nil)) (defn- select-tool-tab! [tab-id ^Scene main-scene ^TabPane tool-tab-pane] (let [tabs (.getTabs tool-tab-pane) tab-index (first (keep-indexed (fn [i ^Tab tab] (when (= tab-id (.getId tab)) i)) tabs))] (set-pane-visible! main-scene :bottom true) (if (some? tab-index) (.select (.getSelectionModel tool-tab-pane) ^long tab-index) (throw (ex-info (str "Tab id not found: " tab-id) {:tab-id tab-id :tab-ids (mapv #(.getId ^Tab %) tabs)}))))) (def show-console! (partial select-tool-tab! "console-tab")) (def show-curve-editor! (partial select-tool-tab! "curve-editor-tab")) (def show-build-errors! (partial select-tool-tab! "build-errors-tab")) (def show-search-results! (partial select-tool-tab! "search-results-tab")) (defn show-asset-browser! [main-scene] (set-pane-visible! main-scene :left true)) (defn- show-debugger! [main-scene tool-tab-pane] ;; In addition to the controls in the console pane, ;; the right pane is used to display locals. (set-pane-visible! main-scene :right true) (show-console! main-scene tool-tab-pane)) (defn debugger-state-changed! [main-scene tool-tab-pane attention?] (ui/invalidate-menubar-item! ::debug-view/debug) (ui/user-data! main-scene ::ui/refresh-requested? true) (when attention? (show-debugger! main-scene tool-tab-pane))) (defn- fire-tab-closed-event! [^Tab tab] ;; TODO: Workaround as there's currently no API to close tabs programatically with identical semantics to close manually ;; See http://stackoverflow.com/questions/17047000/javafx-closing-a-tab-in-tabpane-dynamically (Event/fireEvent tab (Event. Tab/CLOSED_EVENT))) (defn- remove-tab! [^TabPane tab-pane ^Tab tab] (fire-tab-closed-event! tab) (.remove (.getTabs tab-pane) tab)) (defn remove-invalid-tabs! [tab-panes open-views] (let [invalid-tab? (fn [tab] (nil? (get open-views (ui/user-data tab ::view)))) closed-tabs-by-tab-pane (into [] (keep (fn [^TabPane tab-pane] (when-some [closed-tabs (not-empty (filterv invalid-tab? (.getTabs tab-pane)))] [tab-pane closed-tabs]))) tab-panes)] ;; We must remove all invalid tabs from a TabPane in one go to ensure ;; the selected tab change event does not trigger onto an invalid tab. (when (seq closed-tabs-by-tab-pane) (doseq [[^TabPane tab-pane ^Collection closed-tabs] closed-tabs-by-tab-pane] (doseq [tab closed-tabs] (fire-tab-closed-event! tab)) (.removeAll (.getTabs tab-pane) closed-tabs))))) (defn- tab-title ^String [resource is-dirty] ;; Lone underscores are treated as mnemonic letter signifiers in the overflow ;; dropdown menu, and we cannot disable mnemonic parsing for it since the ;; control is internal. We also cannot replace them with double underscores to ;; escape them, as they will show up in the Tab labels and there appears to be ;; no way to enable mnemonic parsing for them. Attempts were made to call ;; setMnemonicParsing on the parent Labelled as the Tab graphic was added to ;; the DOM, but this only worked on macOS. As a workaround, we instead replace ;; underscores with the a unicode character that looks somewhat similar. (let [resource-name (resource/resource-name resource) escaped-resource-name (string/replace resource-name "_" "\u02CD")] (if is-dirty (str "*" escaped-resource-name) escaped-resource-name))) (g/defnode AppView (property stage Stage) (property scene Scene) (property editor-tabs-split SplitPane) (property active-tab-pane TabPane) (property tool-tab-pane TabPane) (property auto-pulls g/Any) (property active-tool g/Keyword) (property manip-space g/Keyword) (property keymap-config g/Any) (input open-views g/Any :array) (input open-dirty-views g/Any :array) (input scene-view-ids g/Any :array) (input hidden-renderable-tags types/RenderableTags) (input hidden-node-outline-key-paths types/NodeOutlineKeyPaths) (input active-outline g/Any) (input active-scene g/Any) (input project-id g/NodeID) (input selected-node-ids-by-resource-node g/Any) (input selected-node-properties-by-resource-node g/Any) (input sub-selections-by-resource-node g/Any) (input debugger-execution-locations g/Any) (output open-views g/Any :cached (g/fnk [open-views] (into {} open-views))) (output open-dirty-views g/Any :cached (g/fnk [open-dirty-views] (into #{} (keep #(when (second %) (first %))) open-dirty-views))) (output active-tab Tab (g/fnk [^TabPane active-tab-pane] (some-> active-tab-pane ui/selected-tab))) (output hidden-renderable-tags types/RenderableTags (gu/passthrough hidden-renderable-tags)) (output hidden-node-outline-key-paths types/NodeOutlineKeyPaths (gu/passthrough hidden-node-outline-key-paths)) (output active-outline g/Any (gu/passthrough active-outline)) (output active-scene g/Any (gu/passthrough active-scene)) (output active-view g/NodeID (g/fnk [^Tab active-tab] (when active-tab (ui/user-data active-tab ::view)))) (output active-view-info g/Any (g/fnk [^Tab active-tab] (when active-tab {:view-id (ui/user-data active-tab ::view) :view-type (ui/user-data active-tab ::view-type)}))) (output active-resource-node g/NodeID :cached (g/fnk [active-view open-views] (:resource-node (get open-views active-view)))) (output active-resource resource/Resource :cached (g/fnk [active-view open-views] (:resource (get open-views active-view)))) (output open-resource-nodes g/Any :cached (g/fnk [open-views] (->> open-views vals (map :resource-node)))) (output selected-node-ids g/Any (g/fnk [selected-node-ids-by-resource-node active-resource-node] (get selected-node-ids-by-resource-node active-resource-node))) (output selected-node-properties g/Any (g/fnk [selected-node-properties-by-resource-node active-resource-node] (get selected-node-properties-by-resource-node active-resource-node))) (output sub-selection g/Any (g/fnk [sub-selections-by-resource-node active-resource-node] (get sub-selections-by-resource-node active-resource-node))) (output refresh-tab-panes g/Any :cached (g/fnk [^SplitPane editor-tabs-split open-views open-dirty-views] (let [tab-panes (.getItems editor-tabs-split)] (doseq [^TabPane tab-pane tab-panes ^Tab tab (.getTabs tab-pane) :let [view (ui/user-data tab ::view) resource (:resource (get open-views view)) is-dirty (contains? open-dirty-views view) title (tab-title resource is-dirty)]] (ui/text! tab title))))) (output keymap g/Any :cached (g/fnk [keymap-config] (keymap/make-keymap keymap-config {:valid-command? (set (handler/available-commands))}))) (output debugger-execution-locations g/Any (gu/passthrough debugger-execution-locations))) (defn- selection->openable-resources [selection] (when-let [resources (handler/adapt-every selection resource/Resource)] (filterv resource/openable-resource? resources))) (defn- selection->single-openable-resource [selection] (when-let [r (handler/adapt-single selection resource/Resource)] (when (resource/openable-resource? r) r))) (defn- selection->single-resource [selection] (handler/adapt-single selection resource/Resource)) (defn- context-resource-file ([app-view selection] (g/with-auto-evaluation-context evaluation-context (context-resource-file app-view selection evaluation-context))) ([app-view selection evaluation-context] (or (selection->single-openable-resource selection) (g/node-value app-view :active-resource evaluation-context)))) (defn- context-resource ([app-view selection] (g/with-auto-evaluation-context evaluation-context (context-resource app-view selection evaluation-context))) ([app-view selection evaluation-context] (or (selection->single-resource selection) (g/node-value app-view :active-resource evaluation-context)))) (defn- disconnect-sources [target-node target-label] (for [[source-node source-label] (g/sources-of target-node target-label)] (g/disconnect source-node source-label target-node target-label))) (defn- replace-connection [source-node source-label target-node target-label] (concat (disconnect-sources target-node target-label) (if (and source-node (contains? (-> source-node g/node-type* g/output-labels) source-label)) (g/connect source-node source-label target-node target-label) []))) (defn- on-selected-tab-changed! [app-view app-scene resource-node view-type] (g/transact (concat (replace-connection resource-node :node-outline app-view :active-outline) (if (= :scene view-type) (replace-connection resource-node :scene app-view :active-scene) (disconnect-sources app-view :active-scene)))) (g/invalidate-outputs! [[app-view :active-tab]]) (ui/user-data! app-scene ::ui/refresh-requested? true)) (handler/defhandler :move-tool :workbench (enabled? [app-view] true) (run [app-view] (g/transact (g/set-property app-view :active-tool :move))) (state [app-view] (= (g/node-value app-view :active-tool) :move))) (handler/defhandler :scale-tool :workbench (enabled? [app-view] true) (run [app-view] (g/transact (g/set-property app-view :active-tool :scale))) (state [app-view] (= (g/node-value app-view :active-tool) :scale))) (handler/defhandler :rotate-tool :workbench (enabled? [app-view] true) (run [app-view] (g/transact (g/set-property app-view :active-tool :rotate))) (state [app-view] (= (g/node-value app-view :active-tool) :rotate))) (handler/defhandler :show-visibility-settings :workbench (run [app-view scene-visibility] (when-let [btn (some-> ^TabPane (g/node-value app-view :active-tab-pane) (ui/selected-tab) (.. getContent (lookup "#show-visibility-settings")))] (scene-visibility/show-visibility-settings! btn scene-visibility))) (state [app-view scene-visibility] (when-let [btn (some-> ^TabPane (g/node-value app-view :active-tab-pane) (ui/selected-tab) (.. getContent (lookup "#show-visibility-settings")))] ;; TODO: We have no mechanism for updating the style nor icon on ;; on the toolbar button. For now we piggyback on the state ;; update polling to set a style when the filters are active. (if (scene-visibility/filters-appear-active? scene-visibility) (ui/add-style! btn "filters-active") (ui/remove-style! btn "filters-active")) (scene-visibility/settings-visible? btn)))) (def ^:private eye-icon-svg-path (ui/load-svg-path "scene/images/eye_icon_eye_arrow.svg")) (def ^:private perspective-icon-svg-path (ui/load-svg-path "scene/images/perspective_icon.svg")) (defn make-svg-icon-graphic ^SVGPath [^SVGPath icon-template] (doto (SVGPath.) (.setContent (.getContent icon-template)))) (defn- make-visibility-settings-graphic [] (doto (StackPane.) (ui/children! [(doto (make-svg-icon-graphic eye-icon-svg-path) (.setId "eye-icon")) (doto (Ellipse. 3.0 3.0) (.setId "active-indicator"))]))) (handler/register-menu! :toolbar [{:id :select :icon "icons/45/Icons_T_01_Select.png" :command :select-tool} {:id :move :icon "icons/45/Icons_T_02_Move.png" :command :move-tool} {:id :rotate :icon "icons/45/Icons_T_03_Rotate.png" :command :rotate-tool} {:id :scale :icon "icons/45/Icons_T_04_Scale.png" :command :scale-tool} {:id :perspective-camera :graphic-fn (partial make-svg-icon-graphic perspective-icon-svg-path) :command :toggle-perspective-camera} {:id :visibility-settings :graphic-fn make-visibility-settings-graphic :command :show-visibility-settings}]) (def ^:const prefs-window-dimensions "window-dimensions") (def ^:const prefs-split-positions "split-positions") (def ^:const prefs-hidden-panes "hidden-panes") (handler/defhandler :quit :global (enabled? [] true) (run [] (let [^Stage main-stage (ui/main-stage)] (.fireEvent main-stage (WindowEvent. main-stage WindowEvent/WINDOW_CLOSE_REQUEST))))) (defn store-window-dimensions [^Stage stage prefs] (let [dims {:x (.getX stage) :y (.getY stage) :width (.getWidth stage) :height (.getHeight stage) :maximized (.isMaximized stage) :full-screen (.isFullScreen stage)}] (prefs/set-prefs prefs prefs-window-dimensions dims))) (defn restore-window-dimensions [^Stage stage prefs] (when-let [dims (prefs/get-prefs prefs prefs-window-dimensions nil)] (let [{:keys [x y width height maximized full-screen]} dims maximized (and maximized (not system/mac?))] ; Maximized is not really a thing on macOS, and if set, cannot become false. (when (and (number? x) (number? y) (number? width) (number? height)) (when-let [_ (seq (Screen/getScreensForRectangle x y width height))] (doto stage (.setX x) (.setY y)) ;; Maximized and setWidth/setHeight in combination triggers a bug on macOS where the window becomes invisible (when (and (not maximized) (not full-screen)) (doto stage (.setWidth width) (.setHeight height))))) (when maximized (.setMaximized stage true)) (when full-screen (.setFullScreen stage true))))) (def ^:private legacy-split-ids ["main-split" "center-split" "right-split" "assets-split"]) (def ^:private split-ids ["main-split" "workbench-split" "center-split" "right-split" "assets-split"]) (defn- existing-split-panes [^Scene scene] (into {} (keep (fn [split-id] (when-some [control (.lookup scene (str "#" split-id))] [(keyword split-id) control]))) split-ids)) (defn- stored-split-positions [prefs] (if-some [split-positions (prefs/get-prefs prefs prefs-split-positions nil)] (if (vector? split-positions) ; Legacy preference format (zipmap (map keyword legacy-split-ids) split-positions) split-positions) {})) (defn store-split-positions! [^Scene scene prefs] (let [split-positions (into (stored-split-positions prefs) (map (fn [[id ^SplitPane sp]] [id (.getDividerPositions sp)])) (existing-split-panes scene))] (prefs/set-prefs prefs prefs-split-positions split-positions))) (defn restore-split-positions! [^Scene scene prefs] (let [split-positions (stored-split-positions prefs) split-panes (existing-split-panes scene)] (doseq [[id positions] split-positions] (when-some [^SplitPane split-pane (get split-panes id)] (.setDividerPositions split-pane (double-array positions)) (.layout split-pane))))) (defn stored-hidden-panes [prefs] (prefs/get-prefs prefs prefs-hidden-panes #{})) (defn store-hidden-panes! [^Scene scene prefs] (let [hidden-panes (into #{} (remove (partial pane-visible? scene)) (keys split-info-by-pane-kw))] (prefs/set-prefs prefs prefs-hidden-panes hidden-panes))) (defn restore-hidden-panes! [^Scene scene prefs] (let [hidden-panes (stored-hidden-panes prefs)] (doseq [pane-kw hidden-panes] (set-pane-visible! scene pane-kw false)))) (handler/defhandler :preferences :global (run [workspace prefs] (prefs-dialog/open-prefs prefs) (workspace/update-build-settings! workspace prefs))) (defn- collect-resources [{:keys [children] :as resource}] (if (empty? children) #{resource} (set (concat [resource] (mapcat collect-resources children))))) (defn- get-active-tabs [app-view evaluation-context] (let [tab-pane ^TabPane (g/node-value app-view :active-tab-pane evaluation-context)] (.getTabs tab-pane))) (defn- make-render-build-error [main-scene tool-tab-pane build-errors-view] (fn [error-value] (build-errors-view/update-build-errors build-errors-view error-value) (show-build-errors! main-scene tool-tab-pane))) (def ^:private remote-log-pump-thread (atom nil)) (def ^:private console-stream (atom nil)) (defn- reset-remote-log-pump-thread! [^Thread new] (when-let [old ^Thread @remote-log-pump-thread] (.interrupt old)) (reset! remote-log-pump-thread new)) (defn- start-log-pump! [log-stream sink-fn] (doto (Thread. (fn [] (try (let [this (Thread/currentThread)] (with-open [buffered-reader ^BufferedReader (io/reader log-stream :encoding "UTF-8")] (loop [] (when-not (.isInterrupted this) (when-let [line (.readLine buffered-reader)] ; line of text or nil if eof reached (sink-fn line) (recur)))))) (catch IOException _ ;; Losing the log connection is ok and even expected nil) (catch InterruptedException _ ;; Losing the log connection is ok and even expected nil)))) (.start))) (defn- local-url [target web-server] (format "http://%s:%s%s" (:local-address target) (http-server/port web-server) hot-reload/url-prefix)) (def ^:private app-task-progress {:main (ref progress/done) :build (ref progress/done) :resource-sync (ref progress/done) :save-all (ref progress/done) :fetch-libraries (ref progress/done) :download-update (ref progress/done)}) (defn- cancel-task! [task-key] (dosync (let [progress-ref (task-key app-task-progress)] (ref-set progress-ref (progress/cancel! @progress-ref))))) (def ^:private app-task-ui-priority "Task priority in descending order (from highest to lowest)" [:save-all :resource-sync :fetch-libraries :build :download-update :main]) (def ^:private render-task-progress-ui-inflight (ref false)) (defn- render-task-progress-ui! [] (let [task-progress-snapshot (ref nil)] (dosync (ref-set render-task-progress-ui-inflight false) (ref-set task-progress-snapshot (into {} (map (juxt first (comp deref second))) app-task-progress))) (let [status-bar (.. (ui/main-stage) (getScene) (getRoot) (lookup "#status-bar")) [key progress] (->> app-task-ui-priority (map (juxt identity @task-progress-snapshot)) (filter (comp (complement progress/done?) second)) first) show-progress-hbox? (boolean (and (not= key :main) progress (not (progress/done? progress))))] (ui/with-controls status-bar [progress-bar progress-hbox progress-percentage-label status-label progress-cancel-button] (ui/render-progress-message! (if key progress (@task-progress-snapshot :main)) status-label) ;; The bottom right of the status bar can show either the progress-hbox ;; or the update-link, or both. The progress-hbox will cover ;; the update-link if both are visible. (if-not show-progress-hbox? (ui/visible! progress-hbox false) (do (ui/visible! progress-hbox true) (ui/render-progress-bar! progress progress-bar) (ui/render-progress-percentage! progress progress-percentage-label) (if (progress/cancellable? progress) (doto progress-cancel-button (ui/visible! true) (ui/managed! true) (ui/on-action! (fn [_] (cancel-task! key)))) (doto progress-cancel-button (ui/visible! false) (ui/managed! false) (ui/on-action! identity))))))))) (defn- render-task-progress! [key progress] (let [schedule-render-task-progress-ui (ref false)] (dosync (ref-set (get app-task-progress key) progress) (ref-set schedule-render-task-progress-ui (not @render-task-progress-ui-inflight)) (ref-set render-task-progress-ui-inflight true)) (when @schedule-render-task-progress-ui (ui/run-later (render-task-progress-ui!))))) (defn make-render-task-progress [key] (assert (contains? app-task-progress key)) (progress/throttle-render-progress (fn [progress] (render-task-progress! key progress)))) (defn make-task-cancelled-query [keyword] (fn [] (progress/cancelled? @(keyword app-task-progress)))) (defn render-main-task-progress! [progress] (render-task-progress! :main progress)) (defn- report-build-launch-progress! [message] (render-main-task-progress! (progress/make message))) (defn clear-build-launch-progress! [] (render-main-task-progress! progress/done)) (defn- decorate-target [engine-descriptor target] (assoc target :engine-id (:id engine-descriptor))) (defn- launch-engine! [engine-descriptor project-directory prefs debug?] (try (report-build-launch-progress! "Launching engine...") (let [engine (engine/install-engine! project-directory engine-descriptor) launched-target (->> (engine/launch! engine project-directory prefs debug?) (decorate-target engine-descriptor) (targets/add-launched-target!) (targets/select-target! prefs))] (report-build-launch-progress! (format "Launched %s" (targets/target-message-label launched-target))) launched-target) (catch Exception e (targets/kill-launched-targets!) (report-build-launch-progress! "Launch failed") (throw e)))) (defn- reset-console-stream! [stream] (reset! console-stream stream) (console/clear-console!)) (defn- make-remote-log-sink [log-stream] (fn [line] (when (= @console-stream log-stream) (console/append-console-line! line)))) (defn- make-launched-log-sink [launched-target] (let [initial-output (atom "")] (fn [line] (when (< (count @initial-output) 5000) (swap! initial-output str line "\n") (when-let [target-info (engine/parse-launched-target-info @initial-output)] (targets/update-launched-target! launched-target target-info))) (when (= @console-stream (:log-stream launched-target)) (console/append-console-line! line))))) (defn- reboot-engine! [target web-server debug?] (try (report-build-launch-progress! (format "Rebooting %s..." (targets/target-message-label target))) (engine/reboot! target (local-url target web-server) debug?) (report-build-launch-progress! (format "Rebooted %s" (targets/target-message-label target))) target (catch Exception e (report-build-launch-progress! "Reboot failed") (throw e)))) (def ^:private build-in-progress? (atom false)) (defn- on-launched-hook! [project process url] (let [hook-options {:exception-policy :ignore :opts {:url url}}] (future (error-reporting/catch-all! (extensions/execute-hook! project :on-target-launched hook-options) (process/watchdog! process #(extensions/execute-hook! project :on-target-terminated hook-options)))))) (defn- launch-built-project! [project engine-descriptor project-directory prefs web-server debug?] (let [selected-target (targets/selected-target prefs) launch-new-engine! (fn [] (targets/kill-launched-targets!) (let [launched-target (launch-engine! engine-descriptor project-directory prefs debug?) log-stream (:log-stream launched-target)] (targets/when-url (:id launched-target) #(on-launched-hook! project (:process launched-target) %)) (reset-console-stream! log-stream) (reset-remote-log-pump-thread! nil) (start-log-pump! log-stream (make-launched-log-sink launched-target)) launched-target))] (try (cond (not selected-target) (launch-new-engine!) (not (targets/controllable-target? selected-target)) (do (assert (targets/launched-target? selected-target)) (launch-new-engine!)) (and (targets/controllable-target? selected-target) (targets/remote-target? selected-target)) (let [log-stream (engine/get-log-service-stream selected-target)] (reset-console-stream! log-stream) (reset-remote-log-pump-thread! (start-log-pump! log-stream (make-remote-log-sink log-stream))) (reboot-engine! selected-target web-server debug?)) :else (do (assert (and (targets/controllable-target? selected-target) (targets/launched-target? selected-target))) (if (= (:id engine-descriptor) (:engine-id selected-target)) (do ;; We're running "the same" engine and can reuse the ;; running process by rebooting (reset-console-stream! (:log-stream selected-target)) (reset-remote-log-pump-thread! nil) ;; Launched target log pump already ;; running to keep engine process ;; from halting because stdout/err is ;; not consumed. (reboot-engine! selected-target web-server debug?)) (launch-new-engine!)))) (catch Exception e (log/warn :exception e) (dialogs/make-info-dialog {:title "Launch Failed" :icon :icon/triangle-error :header {:fx/type :v-box :children [{:fx/type fxui/label :variant :header :text (format "Launching %s failed" (if (some? selected-target) (targets/target-message-label selected-target) "New Local Engine"))} {:fx/type fxui/label :text "If the engine is already running, shut down the process manually and retry"}]} :content (.getMessage e)}))))) (defn- build-project! [project evaluation-context extra-build-targets old-artifact-map render-progress!] (let [game-project (project/get-resource-node project "/game.project" evaluation-context) render-progress! (progress/throttle-render-progress render-progress!)] (try (ui/with-progress [render-progress! render-progress!] (build/build-project! project game-project evaluation-context extra-build-targets old-artifact-map render-progress!)) (catch Throwable error (error-reporting/report-exception! error) nil)))) (defn- cached-build-target-output? [node-id label evaluation-context] (and (= :build-targets label) (project/project-resource-node? node-id evaluation-context))) (defn- update-system-cache-build-targets! [evaluation-context] ;; To avoid cache churn, we only transfer the most important entries to the system cache. (let [pruned-evaluation-context (g/pruned-evaluation-context evaluation-context cached-build-target-output?)] (g/update-cache-from-evaluation-context! pruned-evaluation-context))) (defn async-build! [project prefs {:keys [debug? engine?] :or {debug? false engine? true}} old-artifact-map render-build-progress! result-fn] (let [;; After any pre-build hooks have completed successfully, we will start ;; the engine build on a separate background thread so the build servers ;; can work while we build the project. We will await the results of the ;; engine build in the final phase. engine-build-future-atom (atom nil) cancel-engine-build! (fn cancel-engine-build! [] (when-some [engine-build-future (thread-util/preset! engine-build-future-atom nil)] (future-cancel engine-build-future) nil)) start-engine-build! (fn start-engine-build! [] (assert (ui/on-ui-thread?)) (cancel-engine-build!) (when engine? (let [evaluation-context (g/make-evaluation-context) platform (engine/current-platform)] (reset! engine-build-future-atom (future (try (let [engine (engine/get-engine project evaluation-context prefs platform)] (ui/run-later ;; This potentially saves us from having to ;; re-calculate native extension file hashes the ;; next time we build the project. (g/update-cache-from-evaluation-context! evaluation-context)) engine) (catch Throwable error error)))) nil))) run-on-background-thread! (fn run-on-background-thread! [background-thread-fn ui-thread-fn] (future (try (let [return-value (background-thread-fn)] (ui/run-later (try (ui-thread-fn return-value) (catch Throwable error (reset! build-in-progress? false) (render-build-progress! progress/done) (cancel-engine-build!) (throw error))))) (catch Throwable error (reset! build-in-progress? false) (render-build-progress! progress/done) (cancel-engine-build!) (error-reporting/report-exception! error)))) nil) finish-with-result! (fn finish-with-result! [project-build-results engine build-engine-exception] (reset! build-in-progress? false) (render-build-progress! progress/done) (cancel-engine-build!) (when (some? result-fn) (result-fn project-build-results engine build-engine-exception) nil)) phase-5-await-engine-build! (fn phase-5-await-engine-build! [project-build-results] (assert (nil? (:error project-build-results))) (let [engine-build-future @engine-build-future-atom] (if (nil? engine-build-future) (finish-with-result! project-build-results nil nil) (do (render-build-progress! (progress/make-indeterminate "Fetching engine...")) (run-on-background-thread! (fn run-engine-build-on-background-thread! [] (deref engine-build-future)) (fn process-engine-build-results-on-ui-thread! [engine-or-exception] (if (instance? Throwable engine-or-exception) (finish-with-result! project-build-results nil engine-or-exception) (finish-with-result! project-build-results engine-or-exception nil)))))))) phase-4-run-post-build-hook! (fn phase-4-run-post-build-hook! [project-build-results] (render-build-progress! (progress/make-indeterminate "Executing post-build hooks...")) (let [platform (engine/current-platform) project-build-successful? (nil? (:error project-build-results))] (run-on-background-thread! (fn run-post-build-hook-on-background-thread! [] (extensions/execute-hook! project :on-build-finished {:exception-policy :ignore :opts {:success project-build-successful? :platform platform}})) (fn process-post-build-hook-results-on-ui-thread! [_] (if project-build-successful? (phase-5-await-engine-build! project-build-results) (finish-with-result! project-build-results nil nil)))))) phase-3-build-project! (fn phase-3-build-project! [] ;; We're about to create an evaluation-context. Make sure it is ;; created from the main thread, so it makes sense to update the cache ;; from it after the project build concludes. Note that we selectively ;; transfer only the cached build-targets back to the system cache. ;; We do this because the project build process involves most of the ;; cached outputs in the project graph, and the intermediate steps ;; risk evicting the previous build targets as the cache fills up. (assert (ui/on-ui-thread?)) (let [evaluation-context (g/make-evaluation-context)] (render-build-progress! (progress/make "Building project..." 1)) (run-on-background-thread! (fn run-project-build-on-background-thread! [] (let [extra-build-targets (when debug? (debug-view/build-targets project evaluation-context))] (build-project! project evaluation-context extra-build-targets old-artifact-map render-build-progress!))) (fn process-project-build-results-on-ui-thread! [project-build-results] (update-system-cache-build-targets! evaluation-context) (phase-4-run-post-build-hook! project-build-results))))) phase-2-start-engine-build! (fn phase-2-start-engine-build! [] (start-engine-build!) (phase-3-build-project!)) phase-1-run-pre-build-hook! (fn phase-1-run-pre-build-hook! [] (render-build-progress! (progress/make-indeterminate "Executing pre-build hooks...")) (let [platform (engine/current-platform)] (run-on-background-thread! (fn run-pre-build-hook-on-background-thread! [] (let [extension-error (extensions/execute-hook! project :on-build-started {:exception-policy :as-error :opts {:platform platform}})] ;; If there was an error in the pre-build hook, we won't proceed ;; with the project build. But we still want to report the build ;; failure to any post-build hooks that might need to know. (when (some? extension-error) (render-build-progress! (progress/make-indeterminate "Executing post-build hooks...")) (extensions/execute-hook! project :on-build-finished {:exception-policy :ignore :opts {:success false :platform platform}})) extension-error)) (fn process-pre-build-hook-results-on-ui-thread! [extension-error] (if (some? extension-error) (finish-with-result! {:error extension-error} nil nil) (phase-2-start-engine-build!))))))] ;; Trigger phase 1. Subsequent phases will be triggered as prior phases ;; finish without errors. Each phase will do some work on a background ;; thread, then process the results on the ui thread, and potentially ;; trigger subsequent phases which will again get off the ui thread as ;; soon as they can. (assert (not @build-in-progress?)) (reset! build-in-progress? true) (phase-1-run-pre-build-hook!))) (defn- handle-build-results! [workspace render-build-error! build-results] (let [{:keys [error artifact-map etags]} build-results] (if (some? error) (do (render-build-error! error) nil) (do (workspace/artifact-map! workspace artifact-map) (workspace/etags! workspace etags) (workspace/save-build-cache! workspace) build-results)))) (defn- build-handler [project workspace prefs web-server build-errors-view main-stage tool-tab-pane] (let [project-directory (io/file (workspace/project-path workspace)) main-scene (.getScene ^Stage main-stage) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view)] (build-errors-view/clear-build-errors build-errors-view) (async-build! project prefs {:debug? false} (workspace/artifact-map workspace) (make-render-task-progress :build) (fn [build-results engine-descriptor build-engine-exception] (when (handle-build-results! workspace render-build-error! build-results) (when engine-descriptor (show-console! main-scene tool-tab-pane) (launch-built-project! project engine-descriptor project-directory prefs web-server false)) (when build-engine-exception (log/warn :exception build-engine-exception) (g/with-auto-evaluation-context evaluation-context (engine-build-errors/handle-build-error! render-build-error! project evaluation-context build-engine-exception)))))))) (handler/defhandler :build :global (enabled? [] (not @build-in-progress?)) (run [project workspace prefs web-server build-errors-view debug-view main-stage tool-tab-pane] (debug-view/detach! debug-view) (build-handler project workspace prefs web-server build-errors-view main-stage tool-tab-pane))) (defn- debugging-supported? [project] (if (project/shared-script-state? project) true (do (dialogs/make-info-dialog {:title "Debugging Not Supported" :icon :icon/triangle-error :header "This project cannot be used with the debugger" :content {:fx/type fxui/label :style-class "dialog-content-padding" :text "It is configured to disable shared script state. If you do not specifically require different script states, consider changing the script.shared_state property in game.project."}}) false))) (defn- run-with-debugger! [workspace project prefs debug-view render-build-error! web-server] (let [project-directory (io/file (workspace/project-path workspace))] (async-build! project prefs {:debug? true} (workspace/artifact-map workspace) (make-render-task-progress :build) (fn [build-results engine-descriptor build-engine-exception] (when (handle-build-results! workspace render-build-error! build-results) (when engine-descriptor (when-let [target (launch-built-project! project engine-descriptor project-directory prefs web-server true)] (when (nil? (debug-view/current-session debug-view)) (debug-view/start-debugger! debug-view project (:address target "localhost"))))) (when build-engine-exception (log/warn :exception build-engine-exception) (g/with-auto-evaluation-context evaluation-context (engine-build-errors/handle-build-error! render-build-error! project evaluation-context build-engine-exception)))))))) (defn- attach-debugger! [workspace project prefs debug-view render-build-error!] (async-build! project prefs {:debug? true :engine? false} (workspace/artifact-map workspace) (make-render-task-progress :build) (fn [build-results _ _] (when (handle-build-results! workspace render-build-error! build-results) (let [target (targets/selected-target prefs)] (when (targets/controllable-target? target) (debug-view/attach! debug-view project target (:artifacts build-results)))))))) (handler/defhandler :start-debugger :global ;; NOTE: Shares a shortcut with :debug-view/continue. ;; Only one of them can be active at a time. This creates the impression that ;; there is a single menu item whose label changes in various states. (active? [debug-view evaluation-context] (not (debug-view/debugging? debug-view evaluation-context))) (enabled? [] (not @build-in-progress?)) (run [project workspace prefs web-server build-errors-view console-view debug-view main-stage tool-tab-pane] (when (debugging-supported? project) (let [main-scene (.getScene ^Stage main-stage) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view)] (build-errors-view/clear-build-errors build-errors-view) (if (debug-view/can-attach? prefs) (attach-debugger! workspace project prefs debug-view render-build-error!) (run-with-debugger! workspace project prefs debug-view render-build-error! web-server)))))) (handler/defhandler :rebuild :global (enabled? [] (not @build-in-progress?)) (run [project workspace prefs web-server build-errors-view debug-view main-stage tool-tab-pane] (debug-view/detach! debug-view) (workspace/clear-build-cache! workspace) (build-handler project workspace prefs web-server build-errors-view main-stage tool-tab-pane))) (handler/defhandler :build-html5 :global (run [project prefs web-server build-errors-view changes-view main-stage tool-tab-pane] (let [main-scene (.getScene ^Stage main-stage) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view) render-reload-progress! (make-render-task-progress :resource-sync) render-save-progress! (make-render-task-progress :save-all) render-build-progress! (make-render-task-progress :build) task-cancelled? (make-task-cancelled-query :build) bob-args (bob/build-html5-bob-args project prefs)] (build-errors-view/clear-build-errors build-errors-view) (disk/async-bob-build! render-reload-progress! render-save-progress! render-build-progress! task-cancelled? render-build-error! bob/build-html5-bob-commands bob-args project changes-view (fn [successful?] (when successful? (ui/open-url (format "http://localhost:%d%s/index.html" (http-server/port web-server) bob/html5-url-prefix)))))))) (defn- updated-build-resource-proj-paths [old-etags new-etags] ;; We only want to return resources that were present in the old etags since ;; we don't want to ask the engine to reload something it has not seen yet. ;; It is presumed that the engine will follow any newly-introduced references ;; and load the resources. We might ask the engine to reload these resources ;; the next time they are modified. (into #{} (keep (fn [[proj-path old-etag]] (when-some [new-etag (new-etags proj-path)] (when (not= old-etag new-etag) proj-path)))) old-etags)) (defn- updated-build-resources [evaluation-context project old-etags new-etags proj-path-or-resource] (let [resource-node (project/get-resource-node project proj-path-or-resource evaluation-context) build-targets (g/node-value resource-node :build-targets evaluation-context) updated-build-resource-proj-paths (updated-build-resource-proj-paths old-etags new-etags)] (into [] (keep (fn [{build-resource :resource :as _build-target}] (when (contains? updated-build-resource-proj-paths (resource/proj-path build-resource)) build-resource))) (rseq (pipeline/flatten-build-targets build-targets))))) (defn- can-hot-reload? [debug-view prefs evaluation-context] (when-some [target (targets/selected-target prefs)] (and (targets/controllable-target? target) (not (debug-view/suspended? debug-view evaluation-context)) (not @build-in-progress?)))) (defn- hot-reload! [project prefs build-errors-view main-stage tool-tab-pane] (let [main-scene (.getScene ^Stage main-stage) target (targets/selected-target prefs) workspace (project/workspace project) old-artifact-map (workspace/artifact-map workspace) old-etags (workspace/etags workspace) render-build-progress! (make-render-task-progress :build) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view) opts {:debug? false :engine? false}] ;; NOTE: We must build the entire project even if we only want to reload a ;; subset of resources in order to maintain a functioning build cache. ;; If we decide to support hot reload of a subset of resources, we must ;; keep track of which resource versions have been loaded by the engine, ;; or we might miss resources that were recompiled but never reloaded. (build-errors-view/clear-build-errors build-errors-view) (async-build! project prefs opts old-artifact-map render-build-progress! (fn [{:keys [error artifact-map etags]} _ _] (if (some? error) (render-build-error! error) (do (workspace/artifact-map! workspace artifact-map) (workspace/etags! workspace etags) (workspace/save-build-cache! workspace) (try (when-some [updated-build-resources (not-empty (g/with-auto-evaluation-context evaluation-context (updated-build-resources evaluation-context project old-etags etags "/game.project")))] (engine/reload-build-resources! target updated-build-resources)) (catch Exception e (dialogs/make-info-dialog {:title "Hot Reload Failed" :icon :icon/triangle-error :header (format "Failed to reload resources on '%s'" (targets/target-message-label (targets/selected-target prefs))) :content (.getMessage e)}))))))))) (handler/defhandler :hot-reload :global (enabled? [debug-view prefs evaluation-context] (can-hot-reload? debug-view prefs evaluation-context)) (run [project app-view prefs build-errors-view selection main-stage tool-tab-pane] (hot-reload! project prefs build-errors-view main-stage tool-tab-pane))) (handler/defhandler :close :global (enabled? [app-view evaluation-context] (not-empty (get-active-tabs app-view evaluation-context))) (run [app-view] (let [tab-pane (g/node-value app-view :active-tab-pane)] (when-let [tab (ui/selected-tab tab-pane)] (remove-tab! tab-pane tab))))) (handler/defhandler :close-other :global (enabled? [app-view evaluation-context] (not-empty (next (get-active-tabs app-view evaluation-context)))) (run [app-view] (let [tab-pane ^TabPane (g/node-value app-view :active-tab-pane)] (when-let [selected-tab (ui/selected-tab tab-pane)] ;; Plain doseq over .getTabs will use the iterable interface ;; and we get a ConcurrentModificationException since we ;; remove from the list while iterating. Instead put the tabs ;; in a (non-lazy) vec before iterating. (doseq [tab (vec (.getTabs tab-pane))] (when (not= tab selected-tab) (remove-tab! tab-pane tab))))))) (handler/defhandler :close-all :global (enabled? [app-view evaluation-context] (not-empty (get-active-tabs app-view evaluation-context))) (run [app-view] (let [tab-pane ^TabPane (g/node-value app-view :active-tab-pane)] (doseq [tab (vec (.getTabs tab-pane))] (remove-tab! tab-pane tab))))) (defn- editor-tab-pane "Returns the editor TabPane that is above the Node in the scene hierarchy, or nil if the Node does not reside under an editor TabPane." ^TabPane [node] (when-some [parent-tab-pane (ui/parent-tab-pane node)] (when (= "editor-tabs-split" (some-> (ui/tab-pane-parent parent-tab-pane) (.getId))) parent-tab-pane))) (declare ^:private configure-editor-tab-pane!) (defn- find-other-tab-pane ^TabPane [^SplitPane editor-tabs-split ^TabPane current-tab-pane] (first-where #(not (identical? current-tab-pane %)) (.getItems editor-tabs-split))) (defn- add-other-tab-pane! ^TabPane [^SplitPane editor-tabs-split app-view] (let [tab-panes (.getItems editor-tabs-split) app-stage ^Stage (g/node-value app-view :stage) app-scene (.getScene app-stage) new-tab-pane (TabPane.)] (assert (= 1 (count tab-panes))) (.add tab-panes new-tab-pane) (configure-editor-tab-pane! new-tab-pane app-scene app-view) new-tab-pane)) (defn- open-tab-count ^long [app-view evaluation-context] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split evaluation-context)] (loop [tab-panes (.getItems editor-tabs-split) tab-count 0] (if-some [^TabPane tab-pane (first tab-panes)] (recur (next tab-panes) (+ tab-count (.size (.getTabs tab-pane)))) tab-count)))) (defn- open-tab-pane-count ^long [app-view evaluation-context] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split evaluation-context)] (.size (.getItems editor-tabs-split)))) (handler/defhandler :move-tab :global (enabled? [app-view evaluation-context] (< 1 (open-tab-count app-view evaluation-context))) (run [app-view user-data] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split) source-tab-pane ^TabPane (g/node-value app-view :active-tab-pane) selected-tab (ui/selected-tab source-tab-pane) dest-tab-pane (or (find-other-tab-pane editor-tabs-split source-tab-pane) (add-other-tab-pane! editor-tabs-split app-view))] (.remove (.getTabs source-tab-pane) selected-tab) (.add (.getTabs dest-tab-pane) selected-tab) (.select (.getSelectionModel dest-tab-pane) selected-tab) (.requestFocus dest-tab-pane)))) (handler/defhandler :swap-tabs :global (enabled? [app-view evaluation-context] (< 1 (open-tab-pane-count app-view evaluation-context))) (run [app-view user-data] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split) active-tab-pane ^TabPane (g/node-value app-view :active-tab-pane) other-tab-pane (find-other-tab-pane editor-tabs-split active-tab-pane) active-tab-pane-selection (.getSelectionModel active-tab-pane) other-tab-pane-selection (.getSelectionModel other-tab-pane) active-tab-index (.getSelectedIndex active-tab-pane-selection) other-tab-index (.getSelectedIndex other-tab-pane-selection) active-tabs (.getTabs active-tab-pane) other-tabs (.getTabs other-tab-pane) active-tab (.get active-tabs active-tab-index) other-tab (.get other-tabs other-tab-index)] ;; Fix for DEFEDIT-1673: ;; We need to swap in a dummy tab here so that a tab is never in both ;; TabPanes at once, since the tab lists are observed internally. If we ;; do not, the tabs will lose track of their parent TabPane. (.set other-tabs other-tab-index (Tab.)) (.set active-tabs active-tab-index other-tab) (.set other-tabs other-tab-index active-tab) (.select active-tab-pane-selection other-tab) (.select other-tab-pane-selection active-tab) (.requestFocus other-tab-pane)))) (handler/defhandler :join-tab-panes :global (enabled? [app-view evaluation-context] (< 1 (open-tab-pane-count app-view evaluation-context))) (run [app-view user-data] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split) active-tab-pane ^TabPane (g/node-value app-view :active-tab-pane) selected-tab (ui/selected-tab active-tab-pane) tab-panes (.getItems editor-tabs-split) first-tab-pane ^TabPane (.get tab-panes 0) second-tab-pane ^TabPane (.get tab-panes 1) first-tabs (.getTabs first-tab-pane) second-tabs (.getTabs second-tab-pane) moved-tabs (vec second-tabs)] (.clear second-tabs) (.addAll first-tabs ^Collection moved-tabs) (.select (.getSelectionModel first-tab-pane) selected-tab) (.requestFocus first-tab-pane)))) (defn make-about-dialog [] (let [root ^Parent (ui/load-fxml "about.fxml") stage (ui/make-dialog-stage) scene (Scene. root) controls (ui/collect-controls root ["version" "channel" "editor-sha1" "engine-sha1" "time", "sponsor-push"])] (ui/text! (:version controls) (System/getProperty "defold.version" "No version")) (ui/text! (:channel controls) (or (system/defold-channel) "No channel")) (ui/text! (:editor-sha1 controls) (or (system/defold-editor-sha1) "No editor sha1")) (ui/text! (:engine-sha1 controls) (or (system/defold-engine-sha1) "No engine sha1")) (ui/text! (:time controls) (or (system/defold-build-time) "No build time")) (UIUtil/stringToTextFlowNodes (:sponsor-push controls) "[Defold Foundation Development Fund](https://www.defold.com/community-donations)") (ui/title! stage "About") (.setScene stage scene) (ui/show! stage))) (handler/defhandler :documentation :global (run [] (ui/open-url "https://www.defold.com/learn/"))) (handler/defhandler :support-forum :global (run [] (ui/open-url "https://forum.defold.com/"))) (handler/defhandler :asset-portal :global (run [] (ui/open-url "https://www.defold.com/assets"))) (handler/defhandler :report-issue :global (run [] (ui/open-url (github/new-issue-link)))) (handler/defhandler :report-suggestion :global (run [] (ui/open-url (github/new-suggestion-link)))) (handler/defhandler :search-issues :global (run [] (ui/open-url (github/search-issues-link)))) (handler/defhandler :show-logs :global (run [] (ui/open-file (.getAbsoluteFile (.toFile (Editor/getLogDirectory)))))) (handler/defhandler :donate :global (run [] (ui/open-url "https://www.defold.com/donate"))) (handler/defhandler :about :global (run [] (make-about-dialog))) (handler/defhandler :reload-stylesheet :global (run [] (ui/reload-root-styles!))) (handler/register-menu! ::menubar [{:label "File" :id ::file :children [{:label "New..." :id ::new :command :new-file} {:label "Open" :id ::open :command :open} {:label "Synchronize..." :id ::synchronize :command :synchronize} {:label "Save All" :id ::save-all :command :save-all} {:label :separator} {:label "Open Assets..." :command :open-asset} {:label "Search in Files..." :command :search-in-files} {:label :separator} {:label "Close" :command :close} {:label "Close All" :command :close-all} {:label "Close Others" :command :close-other} {:label :separator} {:label "Referencing Files..." :command :referencing-files} {:label "Dependencies..." :command :dependencies} {:label "Hot Reload" :command :hot-reload} {:label :separator} {:label "Preferences..." :command :preferences} {:label "Quit" :command :quit}]} {:label "Edit" :id ::edit :children [{:label "Undo" :icon "icons/undo.png" :command :undo} {:label "Redo" :icon "icons/redo.png" :command :redo} {:label :separator} {:label "Cut" :command :cut} {:label "Copy" :command :copy} {:label "Paste" :command :paste} {:label "Select All" :command :select-all} {:label "Delete" :icon "icons/32/Icons_M_06_trash.png" :command :delete} {:label :separator} {:label "Move Up" :command :move-up} {:label "Move Down" :command :move-down} {:label :separator :id ::edit-end}]} {:label "View" :id ::view :children [{:label "Toggle Assets Pane" :command :toggle-pane-left} {:label "Toggle Tools Pane" :command :toggle-pane-bottom} {:label "Toggle Properties Pane" :command :toggle-pane-right} {:label :separator} {:label "Show Console" :command :show-console} {:label "Show Curve Editor" :command :show-curve-editor} {:label "Show Build Errors" :command :show-build-errors} {:label "Show Search Results" :command :show-search-results} {:label :separator :id ::view-end}]} {:label "Help" :children [{:label "Profiler" :children [{:label "Measure" :command :profile} {:label "Measure and Show" :command :profile-show}]} {:label "Reload Stylesheet" :command :reload-stylesheet} {:label "Show Logs" :command :show-logs} {:label :separator} {:label "Documentation" :command :documentation} {:label "Support Forum" :command :support-forum} {:label "Find Assets" :command :asset-portal} {:label :separator} {:label "Report Issue" :command :report-issue} {:label "Report Suggestion" :command :report-suggestion} {:label "Search Issues" :command :search-issues} {:label :separator} {:label "Development Fund" :command :donate} {:label :separator} {:label "About" :command :about}]}]) (handler/register-menu! ::tab-menu [{:label "Close" :command :close} {:label "Close Others" :command :close-other} {:label "Close All" :command :close-all} {:label :separator} {:label "Move to Other Tab Pane" :command :move-tab} {:label "Swap With Other Tab Pane" :command :swap-tabs} {:label "Join Tab Panes" :command :join-tab-panes} {:label :separator} {:label "Copy Project Path" :command :copy-project-path} {:label "Copy Full Path" :command :copy-full-path} {:label "Copy Require Path" :command :copy-require-path} {:label :separator} {:label "Show in Asset Browser" :icon "icons/32/Icons_S_14_linkarrow.png" :command :show-in-asset-browser} {:label "Show in Desktop" :icon "icons/32/Icons_S_14_linkarrow.png" :command :show-in-desktop} {:label "Referencing Files..." :command :referencing-files} {:label "Dependencies..." :command :dependencies}]) (defrecord SelectionProvider [app-view] handler/SelectionProvider (selection [_] (g/node-value app-view :selected-node-ids)) (succeeding-selection [_] []) (alt-selection [_] [])) (defn ->selection-provider [app-view] (SelectionProvider. app-view)) (defn select ([app-view node-ids] (select app-view (g/node-value app-view :active-resource-node) node-ids)) ([app-view resource-node node-ids] (g/with-auto-evaluation-context evaluation-context (let [project-id (g/node-value app-view :project-id evaluation-context) open-resource-nodes (g/node-value app-view :open-resource-nodes evaluation-context)] (project/select project-id resource-node node-ids open-resource-nodes))))) (defn select! ([app-view node-ids] (select! app-view node-ids (gensym))) ([app-view node-ids op-seq] (g/transact (concat (g/operation-sequence op-seq) (g/operation-label "Select") (select app-view node-ids))))) (defn sub-select! ([app-view sub-selection] (sub-select! app-view sub-selection (gensym))) ([app-view sub-selection op-seq] (g/with-auto-evaluation-context evaluation-context (let [project-id (g/node-value app-view :project-id evaluation-context) active-resource-node (g/node-value app-view :active-resource-node evaluation-context) open-resource-nodes (g/node-value app-view :open-resource-nodes evaluation-context)] (g/transact (concat (g/operation-sequence op-seq) (g/operation-label "Select") (project/sub-select project-id active-resource-node sub-selection open-resource-nodes))))))) (defn- make-title ([] "Defold Editor 2.0") ([project-title] (str project-title " - " (make-title)))) (defn- refresh-app-title! [^Stage stage project] (let [settings (g/node-value project :settings) project-title (settings ["project" "title"]) new-title (make-title project-title)] (when (not= (.getTitle stage) new-title) (.setTitle stage new-title)))) (defn- refresh-menus-and-toolbars! [app-view ^Scene scene] (let [keymap (g/node-value app-view :keymap) command->shortcut (keymap/command->shortcut keymap)] (ui/user-data! scene :command->shortcut command->shortcut) (ui/refresh scene))) (defn- refresh-views! [app-view] (let [auto-pulls (g/node-value app-view :auto-pulls)] (doseq [[node label] auto-pulls] (profiler/profile "view" (:name @(g/node-type* node)) (g/node-value node label))))) (defn- refresh-scene-views! [app-view] (profiler/begin-frame) (doseq [view-id (g/node-value app-view :scene-view-ids)] (try (scene/refresh-scene-view! view-id) (catch Throwable error (error-reporting/report-exception! error)))) (scene-cache/prune-context! nil)) (defn- dispose-scene-views! [app-view] (doseq [view-id (g/node-value app-view :scene-view-ids)] (try (scene/dispose-scene-view! view-id) (catch Throwable error (error-reporting/report-exception! error)))) (scene-cache/drop-context! nil)) (defn- tab->resource-node [^Tab tab] (some-> tab (ui/user-data ::view) (g/node-value :view-data) second :resource-node)) (defn- tab->view-type [^Tab tab] (some-> tab (ui/user-data ::view-type) :id)) (defn- configure-editor-tab-pane! [^TabPane tab-pane ^Scene app-scene app-view] (.setTabClosingPolicy tab-pane TabPane$TabClosingPolicy/ALL_TABS) (.setTabDragPolicy tab-pane TabPane$TabDragPolicy/REORDER) (-> tab-pane (.getSelectionModel) (.selectedItemProperty) (.addListener (reify ChangeListener (changed [_this _observable _old-val new-val] (on-selected-tab-changed! app-view app-scene (tab->resource-node new-val) (tab->view-type new-val)))))) (-> tab-pane (.getTabs) (.addListener (reify ListChangeListener (onChanged [_this _change] ;; Check if we've ended up with an empty TabPane. ;; Unless we are the only one left, we should get rid of it to make room for the other TabPane. (when (empty? (.getTabs tab-pane)) (let [editor-tabs-split ^SplitPane (ui/tab-pane-parent tab-pane) tab-panes (.getItems editor-tabs-split)] (when (< 1 (count tab-panes)) (.remove tab-panes tab-pane) (.requestFocus ^TabPane (.get tab-panes 0))))))))) (ui/register-tab-pane-context-menu tab-pane ::tab-menu)) (defn- handle-focus-owner-change! [app-view app-scene new-focus-owner] (let [old-editor-tab-pane (g/node-value app-view :active-tab-pane) new-editor-tab-pane (editor-tab-pane new-focus-owner)] (when (and (some? new-editor-tab-pane) (not (identical? old-editor-tab-pane new-editor-tab-pane))) (let [selected-tab (ui/selected-tab new-editor-tab-pane) resource-node (tab->resource-node selected-tab) view-type (tab->view-type selected-tab)] (ui/add-style! old-editor-tab-pane "inactive") (ui/remove-style! new-editor-tab-pane "inactive") (g/set-property! app-view :active-tab-pane new-editor-tab-pane) (on-selected-tab-changed! app-view app-scene resource-node view-type))))) (defn open-custom-keymap [path] (try (and (not= path "") (some-> path slurp edn/read-string)) (catch IOException e (dialogs/make-info-dialog {:title "Couldn't load custom keymap config" :icon :icon/triangle-error :header {:fx/type :v-box :children [{:fx/type fxui/label :text (str "The keymap path " path " couldn't be opened.")}]} :content (.getMessage e)}) (log/error :exception e) nil))) (defn make-app-view [view-graph project ^Stage stage ^MenuBar menu-bar ^SplitPane editor-tabs-split ^TabPane tool-tab-pane prefs] (let [app-scene (.getScene stage)] (ui/disable-menu-alt-key-mnemonic! menu-bar) (.setUseSystemMenuBar menu-bar true) (.setTitle stage (make-title)) (let [editor-tab-pane (TabPane.) keymap (or (open-custom-keymap (prefs/get-prefs prefs "custom-keymap-path" "")) keymap/default-host-key-bindings) app-view (first (g/tx-nodes-added (g/transact (g/make-node view-graph AppView :stage stage :scene app-scene :editor-tabs-split editor-tabs-split :active-tab-pane editor-tab-pane :tool-tab-pane tool-tab-pane :active-tool :move :manip-space :world :keymap-config keymap))))] (.add (.getItems editor-tabs-split) editor-tab-pane) (configure-editor-tab-pane! editor-tab-pane app-scene app-view) (ui/observe (.focusOwnerProperty app-scene) (fn [_ _ new-focus-owner] (handle-focus-owner-change! app-view app-scene new-focus-owner))) (ui/register-menubar app-scene menu-bar ::menubar) (keymap/install-key-bindings! (.getScene stage) (g/node-value app-view :keymap)) (let [refresh-timer (ui/->timer "refresh-app-view" (fn [_ _] (when-not (ui/ui-disabled?) (let [refresh-requested? (ui/user-data app-scene ::ui/refresh-requested?)] (when refresh-requested? (ui/user-data! app-scene ::ui/refresh-requested? false) (refresh-menus-and-toolbars! app-view app-scene) (refresh-views! app-view)) (refresh-scene-views! app-view) (refresh-app-title! stage project)))))] (ui/timer-stop-on-closed! stage refresh-timer) (ui/timer-start! refresh-timer)) (ui/on-closed! stage (fn [_] (dispose-scene-views! app-view))) app-view))) (defn- make-tab! [app-view prefs workspace project resource resource-node resource-type view-type make-view-fn ^ObservableList tabs opts] (let [parent (AnchorPane.) tab (doto (Tab. (tab-title resource false)) (.setContent parent) (.setTooltip (Tooltip. (or (resource/proj-path resource) "unknown"))) (ui/user-data! ::view-type view-type)) view-graph (g/make-graph! :history false :volatility 2) select-fn (partial select app-view) opts (merge opts (get (:view-opts resource-type) (:id view-type)) {:app-view app-view :select-fn select-fn :prefs prefs :project project :workspace workspace :tab tab}) view (make-view-fn view-graph parent resource-node opts)] (assert (g/node-instance? view/WorkbenchView view)) (g/transact (concat (view/connect-resource-node view resource-node) (g/connect view :view-data app-view :open-views) (g/connect view :view-dirty? app-view :open-dirty-views))) (ui/user-data! tab ::view view) (.add tabs tab) (g/transact (select app-view resource-node [resource-node])) (.setGraphic tab (icons/get-image-view (or (:icon resource-type) "icons/64/Icons_29-AT-Unknown.png") 16)) (.addAll (.getStyleClass tab) ^Collection (resource/style-classes resource)) (ui/register-tab-toolbar tab "#toolbar" :toolbar) (let [close-handler (.getOnClosed tab)] (.setOnClosed tab (ui/event-handler event ;; The menu refresh can occur after the view graph is ;; deleted but before the tab controls lose input ;; focus, causing handlers to evaluate against deleted ;; graph nodes. Using run-later here prevents this. (ui/run-later (doto tab (ui/user-data! ::view-type nil) (ui/user-data! ::view nil)) (g/delete-graph! view-graph)) (when close-handler (.handle close-handler event))))) tab)) (defn- substitute-args [tmpl args] (reduce (fn [tmpl [key val]] (string/replace tmpl (format "{%s}" (name key)) (str val))) tmpl args)) (defn open-resource ([app-view prefs workspace project resource] (open-resource app-view prefs workspace project resource {})) ([app-view prefs workspace project resource opts] (let [resource-type (resource/resource-type resource) resource-node (or (project/get-resource-node project resource) (throw (ex-info (format "No resource node found for resource '%s'" (resource/proj-path resource)) {}))) text-view-type (workspace/get-view-type workspace :text) view-type (or (:selected-view-type opts) (if (nil? resource-type) (placeholder-resource/view-type workspace) (first (:view-types resource-type))) text-view-type)] (if (resource-node/defective? resource-node) (do (dialogs/make-info-dialog {:title "Unable to Open Resource" :icon :icon/triangle-error :header (format "Unable to open '%s', since it appears damaged" (resource/proj-path resource))}) false) (if-let [custom-editor (and (#{:code :text} (:id view-type)) (let [ed-pref (some-> (prefs/get-prefs prefs "code-custom-editor" "") string/trim)] (and (not (string/blank? ed-pref)) ed-pref)))] (let [cursor-range (:cursor-range opts) arg-tmpl (string/trim (if cursor-range (prefs/get-prefs prefs "code-open-file-at-line" "{file}:{line}") (prefs/get-prefs prefs "code-open-file" "{file}"))) arg-sub (cond-> {:file (resource/abs-path resource)} cursor-range (assoc :line (CursorRange->line-number cursor-range))) args (->> (string/split arg-tmpl #" ") (map #(substitute-args % arg-sub)))] (doto (ProcessBuilder. ^List (cons custom-editor args)) (.directory (workspace/project-path workspace)) (.start)) false) (if (contains? view-type :make-view-fn) (let [^SplitPane editor-tabs-split (g/node-value app-view :editor-tabs-split) tab-panes (.getItems editor-tabs-split) open-tabs (mapcat #(.getTabs ^TabPane %) tab-panes) view-type (if (g/node-value resource-node :editable?) view-type text-view-type) make-view-fn (:make-view-fn view-type) ^Tab tab (or (some #(when (and (= (tab->resource-node %) resource-node) (= view-type (ui/user-data % ::view-type))) %) open-tabs) (let [^TabPane active-tab-pane (g/node-value app-view :active-tab-pane) active-tab-pane-tabs (.getTabs active-tab-pane)] (make-tab! app-view prefs workspace project resource resource-node resource-type view-type make-view-fn active-tab-pane-tabs opts)))] (.select (.getSelectionModel (.getTabPane tab)) tab) (when-let [focus (:focus-fn view-type)] ;; Force layout pass since the focus function of some views ;; needs proper width + height (f.i. code view for ;; scrolling to selected line). (NodeHelper/layoutNodeForPrinting (.getRoot ^Scene (g/node-value app-view :scene))) (focus (ui/user-data tab ::view) opts)) ;; Do an initial rendering so it shows up as fast as possible. (ui/run-later (refresh-scene-views! app-view) (ui/run-later (slog/smoke-log "opened-resource"))) true) (let [^String path (or (resource/abs-path resource) (resource/temp-path resource)) ^File f (File. path)] (ui/open-file f (fn [msg] (ui/run-later (dialogs/make-info-dialog {:title "Could Not Open File" :icon :icon/triangle-error :header (format "Could not open '%s'" (.getName f)) :content (str "This can happen if the file type is not mapped to an application in your OS.\n\nUnderlying error from the OS:\n" msg)})))) false))))))) (handler/defhandler :open :global (active? [selection user-data] (:resources user-data (not-empty (selection->openable-resources selection)))) (enabled? [selection user-data] (some resource/exists? (:resources user-data (selection->openable-resources selection)))) (run [selection app-view prefs workspace project user-data] (doseq [resource (filter resource/exists? (:resources user-data (selection->openable-resources selection)))] (open-resource app-view prefs workspace project resource)))) (handler/defhandler :open-as :global (active? [selection] (selection->single-openable-resource selection)) (enabled? [selection user-data] (resource/exists? (selection->single-openable-resource selection))) (run [selection app-view prefs workspace project user-data] (let [resource (selection->single-openable-resource selection)] (open-resource app-view prefs workspace project resource (when-let [view-type (:selected-view-type user-data)] {:selected-view-type view-type})))) (options [workspace selection user-data] (when-not user-data (let [resource (selection->single-openable-resource selection) resource-type (resource/resource-type resource)] (map (fn [vt] {:label (or (:label vt) "External Editor") :command :open-as :user-data {:selected-view-type vt}}) (:view-types resource-type)))))) (handler/defhandler :synchronize :global (enabled? [] (disk-availability/available?)) (run [changes-view project workspace app-view] (let [render-reload-progress! (make-render-task-progress :resource-sync) render-save-progress! (make-render-task-progress :save-all)] (if (changes-view/project-is-git-repo? changes-view) ;; The project is a Git repo. ;; Check if there are locked files below the project folder before proceeding. ;; If so, we abort the sync and notify the user, since this could cause problems. (when (changes-view/ensure-no-locked-files! changes-view) (disk/async-save! render-reload-progress! render-save-progress! project changes-view (fn [successful?] (when successful? (ui/user-data! (g/node-value app-view :scene) ::ui/refresh-requested? true) (when (changes-view/regular-sync! changes-view) (disk/async-reload! render-reload-progress! workspace [] changes-view)))))) ;; The project is not a Git repo. ;; Show a dialog with info about how to set this up. (dialogs/make-info-dialog {:title "Version Control" :size :default :icon :icon/git :header "This project does not use Version Control" :content {:fx/type :text-flow :style-class "dialog-content-padding" :children [{:fx/type :text :text (str "A project under Version Control " "keeps a history of changes and " "enables you to collaborate with " "others by pushing changes to a " "server.\n\nYou can read about " "how to configure Version Control " "in the ")} {:fx/type :hyperlink :text "Defold Manual" :on-action (fn [_] (ui/open-url "https://www.defold.com/manuals/version-control/"))} {:fx/type :text :text "."}]}}))))) (handler/defhandler :save-all :global (enabled? [] (not (bob/build-in-progress?))) (run [app-view changes-view project] (let [render-reload-progress! (make-render-task-progress :resource-sync) render-save-progress! (make-render-task-progress :save-all)] (disk/async-save! render-reload-progress! render-save-progress! project changes-view (fn [successful?] (when successful? (ui/user-data! (g/node-value app-view :scene) ::ui/refresh-requested? true))))))) (handler/defhandler :show-in-desktop :global (active? [app-view selection evaluation-context] (context-resource app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource app-view selection evaluation-context)] (and (resource/abs-path r) (or (resource/exists? r) (empty? (resource/path r)))))) (run [app-view selection] (when-let [r (context-resource app-view selection)] (let [f (File. (resource/abs-path r))] (ui/open-file (fs/to-folder f)))))) (handler/defhandler :referencing-files :global (active? [app-view selection evaluation-context] (context-resource-file app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/abs-path r) (resource/exists? r)))) (run [selection app-view prefs workspace project] (when-let [r (context-resource-file app-view selection)] (doseq [resource (dialogs/make-resource-dialog workspace project {:title "Referencing Files" :selection :multiple :ok-label "Open" :filter (format "refs:%s" (resource/proj-path r))})] (open-resource app-view prefs workspace project resource))))) (handler/defhandler :dependencies :global (active? [app-view selection evaluation-context] (context-resource-file app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/abs-path r) (resource/exists? r)))) (run [selection app-view prefs workspace project] (when-let [r (context-resource-file app-view selection)] (doseq [resource (dialogs/make-resource-dialog workspace project {:title "Dependencies" :selection :multiple :ok-label "Open" :filter (format "deps:%s" (resource/proj-path r))})] (open-resource app-view prefs workspace project resource))))) (handler/defhandler :toggle-pane-left :global (run [^Stage main-stage] (let [main-scene (.getScene main-stage)] (set-pane-visible! main-scene :left (not (pane-visible? main-scene :left)))))) (handler/defhandler :toggle-pane-right :global (run [^Stage main-stage] (let [main-scene (.getScene main-stage)] (set-pane-visible! main-scene :right (not (pane-visible? main-scene :right)))))) (handler/defhandler :toggle-pane-bottom :global (run [^Stage main-stage] (let [main-scene (.getScene main-stage)] (set-pane-visible! main-scene :bottom (not (pane-visible? main-scene :bottom)))))) (handler/defhandler :show-console :global (run [^Stage main-stage tool-tab-pane] (show-console! (.getScene main-stage) tool-tab-pane))) (handler/defhandler :show-curve-editor :global (run [^Stage main-stage tool-tab-pane] (show-curve-editor! (.getScene main-stage) tool-tab-pane))) (handler/defhandler :show-build-errors :global (run [^Stage main-stage tool-tab-pane] (show-build-errors! (.getScene main-stage) tool-tab-pane))) (handler/defhandler :show-search-results :global (run [^Stage main-stage tool-tab-pane] (show-search-results! (.getScene main-stage) tool-tab-pane))) (defn- put-on-clipboard! [s] (doto (Clipboard/getSystemClipboard) (.setContent (doto (ClipboardContent.) (.putString s))))) (handler/defhandler :copy-project-path :global (active? [app-view selection evaluation-context] (context-resource-file app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/proj-path r) (resource/exists? r)))) (run [selection app-view] (when-let [r (context-resource-file app-view selection)] (put-on-clipboard! (resource/proj-path r))))) (handler/defhandler :copy-full-path :global (active? [app-view selection evaluation-context] (context-resource-file app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/abs-path r) (resource/exists? r)))) (run [selection app-view] (when-let [r (context-resource-file app-view selection)] (put-on-clipboard! (resource/abs-path r))))) (handler/defhandler :copy-require-path :global (active? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (= "lua" (resource/type-ext r)))) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/proj-path r) (resource/exists? r)))) (run [selection app-view] (when-let [r (context-resource-file app-view selection)] (put-on-clipboard! (lua/path->lua-module (resource/proj-path r)))))) (defn- gen-tooltip [workspace project app-view resource] (let [resource-type (resource/resource-type resource) view-type (or (first (:view-types resource-type)) (workspace/get-view-type workspace :text))] (when-let [make-preview-fn (:make-preview-fn view-type)] (let [tooltip (Tooltip.)] (doto tooltip (.setGraphic (doto (ImageView.) (.setScaleY -1.0))) (.setOnShowing (ui/event-handler e (let [image-view ^ImageView (.getGraphic tooltip)] (when-not (.getImage image-view) (let [resource-node (project/get-resource-node project resource) view-graph (g/make-graph! :history false :volatility 2) select-fn (partial select app-view) opts (assoc ((:id view-type) (:view-opts resource-type)) :app-view app-view :select-fn select-fn :project project :workspace workspace) preview (make-preview-fn view-graph resource-node opts 256 256)] (.setImage image-view ^Image (g/node-value preview :image)) (when-some [dispose-preview-fn (:dispose-preview-fn view-type)] (dispose-preview-fn preview)) (g/delete-graph! view-graph))))))))))) (def ^:private open-assets-term-prefs-key "open-assets-term") (defn- query-and-open! [workspace project app-view prefs term] (let [prev-filter-term (prefs/get-prefs prefs open-assets-term-prefs-key nil) filter-term-atom (atom prev-filter-term) selected-resources (dialogs/make-resource-dialog workspace project (cond-> {:title "Open Assets" :accept-fn resource/editable-resource? :selection :multiple :ok-label "Open" :filter-atom filter-term-atom :tooltip-gen (partial gen-tooltip workspace project app-view)} (some? term) (assoc :filter term))) filter-term @filter-term-atom] (when (not= prev-filter-term filter-term) (prefs/set-prefs prefs open-assets-term-prefs-key filter-term)) (doseq [resource selected-resources] (open-resource app-view prefs workspace project resource)))) (handler/defhandler :select-items :global (run [user-data] (dialogs/make-select-list-dialog (:items user-data) (:options user-data)))) (defn- get-view-text-selection [{:keys [view-id view-type]}] (when-let [text-selection-fn (:text-selection-fn view-type)] (text-selection-fn view-id))) (handler/defhandler :open-asset :global (run [workspace project app-view prefs] (let [term (get-view-text-selection (g/node-value app-view :active-view-info))] (query-and-open! workspace project app-view prefs term)))) (handler/defhandler :search-in-files :global (run [project app-view prefs search-results-view main-stage tool-tab-pane] (when-let [term (get-view-text-selection (g/node-value app-view :active-view-info))] (search-results-view/set-search-term! prefs term)) (let [main-scene (.getScene ^Stage main-stage) show-search-results-tab! (partial show-search-results! main-scene tool-tab-pane)] (search-results-view/show-search-in-files-dialog! search-results-view project prefs show-search-results-tab!)))) (defn- bundle! [main-stage tool-tab-pane changes-view build-errors-view project prefs platform bundle-options] (g/user-data! project :last-bundle-options (assoc bundle-options :platform-key platform)) (let [main-scene (.getScene ^Stage main-stage) output-directory ^File (:output-directory bundle-options) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view) render-reload-progress! (make-render-task-progress :resource-sync) render-save-progress! (make-render-task-progress :save-all) render-build-progress! (make-render-task-progress :build) task-cancelled? (make-task-cancelled-query :build) bob-args (bob/bundle-bob-args prefs platform bundle-options)] (when-not (.exists output-directory) (fs/create-directories! output-directory)) (build-errors-view/clear-build-errors build-errors-view) (disk/async-bob-build! render-reload-progress! render-save-progress! render-build-progress! task-cancelled? render-build-error! bob/bundle-bob-commands bob-args project changes-view (fn [successful?] (when successful? (if (some-> output-directory .isDirectory) (ui/open-file output-directory) (dialogs/make-info-dialog {:title "Bundle Failed" :icon :icon/triangle-error :size :large :header "Failed to bundle project, please fix build errors and try again"}))))))) (handler/defhandler :bundle :global (run [user-data workspace project prefs app-view changes-view build-errors-view main-stage tool-tab-pane] (let [owner-window (g/node-value app-view :stage) platform (:platform user-data) bundle! (partial bundle! main-stage tool-tab-pane changes-view build-errors-view project prefs platform)] (bundle-dialog/show-bundle-dialog! workspace platform prefs owner-window bundle!)))) (handler/defhandler :rebundle :global (enabled? [project] (some? (g/user-data project :last-bundle-options))) (run [workspace project prefs app-view changes-view build-errors-view main-stage tool-tab-pane] (let [last-bundle-options (g/user-data project :last-bundle-options) platform (:platform-key last-bundle-options)] (bundle! main-stage tool-tab-pane changes-view build-errors-view project prefs platform last-bundle-options)))) (def ^:private editor-extensions-allowed-commands-prefs-key "editor-extensions/allowed-commands") (defn make-extensions-ui [workspace changes-view prefs] (reify extensions/UI (reload-resources! [_] (let [success-promise (promise)] (disk/async-reload! (make-render-task-progress :resource-sync) workspace [] changes-view success-promise) (when-not @success-promise (throw (ex-info "Reload failed" {}))))) (can-execute? [_ [cmd-name :as command]] (let [allowed-commands (prefs/get-prefs prefs editor-extensions-allowed-commands-prefs-key #{})] (if (allowed-commands cmd-name) true (let [allow (ui/run-now (dialogs/make-confirmation-dialog {:title "Allow executing shell command?" :icon {:fx/type fxui/icon :type :icon/triangle-error :fill "#fa6731"} :header "Extension wants to execute a shell command" :content {:fx/type fxui/label :style-class "dialog-content-padding" :text (string/join " " command)} :buttons [{:text "Abort Command" :cancel-button true :default-button true :result false} {:text "Allow" :variant :danger :result true}]}))] (when allow (prefs/set-prefs prefs editor-extensions-allowed-commands-prefs-key (conj allowed-commands cmd-name))) allow)))) (display-output! [_ type string] (let [[console-type prefix] (case type :err [:extension-err "ERROR:EXT: "] :out [:extension-out ""])] (doseq [line (string/split-lines string)] (console/append-console-entry! console-type (str prefix line))))) (on-transact-thread [_ f] (ui/run-now (f))))) (defn- fetch-libraries [workspace project changes-view prefs] (let [library-uris (project/project-dependencies project) hosts (into #{} (map url/strip-path) library-uris)] (if-let [first-unreachable-host (first-where (complement url/reachable?) hosts)] (dialogs/make-info-dialog {:title "Fetch Failed" :icon :icon/triangle-error :size :large :header "Fetch was aborted because a host could not be reached" :content (str "Unreachable host: " first-unreachable-host "\n\nPlease verify internet connection and try again.")}) (future (error-reporting/catch-all! (ui/with-progress [render-fetch-progress! (make-render-task-progress :fetch-libraries)] (when (workspace/dependencies-reachable? library-uris) (let [lib-states (workspace/fetch-and-validate-libraries workspace library-uris render-fetch-progress!) render-install-progress! (make-render-task-progress :resource-sync)] (render-install-progress! (progress/make "Installing updated libraries...")) (ui/run-later (workspace/install-validated-libraries! workspace library-uris lib-states) (disk/async-reload! render-install-progress! workspace [] changes-view (fn [success] (when success (extensions/reload! project :library (make-extensions-ui workspace changes-view prefs)))))))))))))) (handler/defhandler :add-dependency :global (enabled? [] (disk-availability/available?)) (run [selection app-view prefs workspace project changes-view user-data] (let [game-project (project/get-resource-node project "/game.project") dependencies (game-project/get-setting game-project ["project" "dependencies"]) dependency-uri (.toURI (URL. (:dep-url user-data)))] (when (not-any? (partial = dependency-uri) dependencies) (game-project/set-setting! game-project ["project" "dependencies"] (conj (vec dependencies) dependency-uri)) (fetch-libraries workspace project changes-view prefs))))) (handler/defhandler :fetch-libraries :global (enabled? [] (disk-availability/available?)) (run [workspace project changes-view prefs] (fetch-libraries workspace project changes-view prefs))) (handler/defhandler :reload-extensions :global (enabled? [] (disk-availability/available?)) (run [project workspace changes-view prefs] (extensions/reload! project :all (make-extensions-ui workspace changes-view prefs)))) (defn- create-and-open-live-update-settings! [app-view changes-view prefs project] (let [workspace (project/workspace project) project-path (workspace/project-path workspace) settings-file (io/file project-path "liveupdate.settings") render-reload-progress! (make-render-task-progress :resource-sync)] (spit settings-file "[liveupdate]\n") (disk/async-reload! render-reload-progress! workspace [] changes-view (fn [successful?] (when successful? (when-some [created-resource (workspace/find-resource workspace "/liveupdate.settings")] (open-resource app-view prefs workspace project created-resource))))))) (handler/defhandler :live-update-settings :global (enabled? [] (disk-availability/available?)) (run [app-view changes-view prefs workspace project] (if-some [existing-resource (workspace/find-resource workspace (live-update-settings/get-live-update-settings-path project))] (open-resource app-view prefs workspace project existing-resource) (create-and-open-live-update-settings! app-view changes-view prefs project)))) (handler/defhandler :sign-ios-app :global (active? [] (util/is-mac-os?)) (run [workspace project prefs build-errors-view main-stage tool-tab-pane] (build-errors-view/clear-build-errors build-errors-view) (let [result (bundle/make-sign-dialog workspace prefs project)] (when-let [error (:error result)] (g/with-auto-evaluation-context evaluation-context (let [main-scene (.getScene ^Stage main-stage) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view)] (if (engine-build-errors/handle-build-error! render-build-error! project evaluation-context error) (dialogs/make-info-dialog {:title "Build Failed" :icon :icon/triangle-error :header "Failed to build ipa with native extensions, please fix build errors and try again"}) (do (error-reporting/report-exception! error) (when-let [message (:message result)] (dialogs/make-info-dialog {:title "Error" :icon :icon/triangle-error :header message}))))))))))
29560
;; Copyright 2020 The Defold Foundation ;; 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.app-view (:require [clojure.java.io :as io] [clojure.edn :as edn] [clojure.string :as string] [dynamo.graph :as g] [editor.build :as build] [editor.build-errors-view :as build-errors-view] [editor.bundle :as bundle] [editor.bundle-dialog :as bundle-dialog] [editor.changes-view :as changes-view] [editor.code.data :refer [CursorRange->line-number]] [editor.console :as console] [editor.debug-view :as debug-view] [editor.defold-project :as project] [editor.dialogs :as dialogs] [editor.disk :as disk] [editor.disk-availability :as disk-availability] [editor.editor-extensions :as extensions] [editor.engine :as engine] [editor.engine.build-errors :as engine-build-errors] [editor.error-reporting :as error-reporting] [editor.fs :as fs] [editor.fxui :as fxui] [editor.game-project :as game-project] [editor.github :as github] [editor.graph-util :as gu] [editor.handler :as handler] [editor.hot-reload :as hot-reload] [editor.icons :as icons] [editor.keymap :as keymap] [editor.live-update-settings :as live-update-settings] [editor.lua :as lua] [editor.pipeline :as pipeline] [editor.pipeline.bob :as bob] [editor.placeholder-resource :as placeholder-resource] [editor.prefs :as prefs] [editor.prefs-dialog :as prefs-dialog] [editor.process :as process] [editor.progress :as progress] [editor.resource :as resource] [editor.resource-node :as resource-node] [editor.scene :as scene] [editor.scene-cache :as scene-cache] [editor.scene-visibility :as scene-visibility] [editor.search-results-view :as search-results-view] [editor.system :as system] [editor.targets :as targets] [editor.types :as types] [editor.ui :as ui] [editor.url :as url] [editor.util :as util] [editor.view :as view] [editor.workspace :as workspace] [internal.util :refer [first-where]] [service.log :as log] [util.http-server :as http-server] [util.profiler :as profiler] [util.thread-util :as thread-util] [service.smoke-log :as slog]) (:import [com.defold.editor Editor] [com.defold.editor UIUtil] [com.sun.javafx.scene NodeHelper] [java.io BufferedReader File IOException] [java.net URL] [java.util Collection List] [javafx.beans.value ChangeListener] [javafx.collections ListChangeListener ObservableList] [javafx.event Event] [javafx.geometry Orientation] [javafx.scene Parent Scene] [javafx.scene.control MenuBar SplitPane Tab TabPane TabPane$TabClosingPolicy TabPane$TabDragPolicy Tooltip] [javafx.scene.image Image ImageView] [javafx.scene.input Clipboard ClipboardContent] [javafx.scene.layout AnchorPane StackPane] [javafx.scene.shape Ellipse SVGPath] [javafx.stage Screen Stage WindowEvent])) (set! *warn-on-reflection* true) (def ^:private split-info-by-pane-kw {:left {:index 0 :pane-id "left-pane" :split-id "main-split"} :right {:index 1 :pane-id "right-pane" :split-id "workbench-split"} :bottom {:index 1 :pane-id "bottom-pane" :split-id "center-split"}}) (defn- pane-visible? [^Scene main-scene pane-kw] (let [{:keys [pane-id split-id]} (split-info-by-pane-kw pane-kw)] (some? (.lookup main-scene (str "#" split-id " #" pane-id))))) (defn- split-pane-length ^double [^SplitPane split-pane] (condp = (.getOrientation split-pane) Orientation/HORIZONTAL (.getWidth split-pane) Orientation/VERTICAL (.getHeight split-pane))) (defn- set-pane-visible! [^Scene main-scene pane-kw visible?] (let [{:keys [index pane-id split-id]} (split-info-by-pane-kw pane-kw) ^SplitPane split (.lookup main-scene (str "#" split-id)) ^Parent pane (.lookup split (str "#" pane-id))] (cond (and (nil? pane) visible?) (let [user-data-key (keyword "<KEY>" pane-<KEY>) {:keys [pane size]} (ui/user-data split user-data-key) divider-index (max 0 (dec index)) divider-position (max 0.0 (min (if (zero? index) (/ size (split-pane-length split)) (- 1.0 (/ size (split-pane-length split)))) 1.0))] (ui/user-data! split user-data-key nil) (.add (.getItems split) index pane) (.setDividerPosition split divider-index divider-position) (.layout split)) (and (some? pane) (not visible?)) (let [user-data-key (keyword "<KEY>" pane-<KEY>) divider-index (max 0 (dec index)) divider-position (get (.getDividerPositions split) divider-index) size (if (zero? index) (Math/floor (* divider-position (split-pane-length split))) (Math/ceil (* (- 1.0 divider-position) (split-pane-length split)))) removing-focus-owner? (some? (when-some [focus-owner (.getFocusOwner main-scene)] (ui/closest-node-where (partial identical? pane) focus-owner)))] (ui/user-data! split user-data-key {:pane pane :size size}) (.remove (.getItems split) pane) (.layout split) ;; If this action causes the focus owner to be removed from the scene, ;; move focus to the SplitPane. This ensures we have a valid UI context ;; when refreshing the menus. (when removing-focus-owner? (.requestFocus split)))) nil)) (defn- select-tool-tab! [tab-id ^Scene main-scene ^TabPane tool-tab-pane] (let [tabs (.getTabs tool-tab-pane) tab-index (first (keep-indexed (fn [i ^Tab tab] (when (= tab-id (.getId tab)) i)) tabs))] (set-pane-visible! main-scene :bottom true) (if (some? tab-index) (.select (.getSelectionModel tool-tab-pane) ^long tab-index) (throw (ex-info (str "Tab id not found: " tab-id) {:tab-id tab-id :tab-ids (mapv #(.getId ^Tab %) tabs)}))))) (def show-console! (partial select-tool-tab! "console-tab")) (def show-curve-editor! (partial select-tool-tab! "curve-editor-tab")) (def show-build-errors! (partial select-tool-tab! "build-errors-tab")) (def show-search-results! (partial select-tool-tab! "search-results-tab")) (defn show-asset-browser! [main-scene] (set-pane-visible! main-scene :left true)) (defn- show-debugger! [main-scene tool-tab-pane] ;; In addition to the controls in the console pane, ;; the right pane is used to display locals. (set-pane-visible! main-scene :right true) (show-console! main-scene tool-tab-pane)) (defn debugger-state-changed! [main-scene tool-tab-pane attention?] (ui/invalidate-menubar-item! ::debug-view/debug) (ui/user-data! main-scene ::ui/refresh-requested? true) (when attention? (show-debugger! main-scene tool-tab-pane))) (defn- fire-tab-closed-event! [^Tab tab] ;; TODO: Workaround as there's currently no API to close tabs programatically with identical semantics to close manually ;; See http://stackoverflow.com/questions/17047000/javafx-closing-a-tab-in-tabpane-dynamically (Event/fireEvent tab (Event. Tab/CLOSED_EVENT))) (defn- remove-tab! [^TabPane tab-pane ^Tab tab] (fire-tab-closed-event! tab) (.remove (.getTabs tab-pane) tab)) (defn remove-invalid-tabs! [tab-panes open-views] (let [invalid-tab? (fn [tab] (nil? (get open-views (ui/user-data tab ::view)))) closed-tabs-by-tab-pane (into [] (keep (fn [^TabPane tab-pane] (when-some [closed-tabs (not-empty (filterv invalid-tab? (.getTabs tab-pane)))] [tab-pane closed-tabs]))) tab-panes)] ;; We must remove all invalid tabs from a TabPane in one go to ensure ;; the selected tab change event does not trigger onto an invalid tab. (when (seq closed-tabs-by-tab-pane) (doseq [[^TabPane tab-pane ^Collection closed-tabs] closed-tabs-by-tab-pane] (doseq [tab closed-tabs] (fire-tab-closed-event! tab)) (.removeAll (.getTabs tab-pane) closed-tabs))))) (defn- tab-title ^String [resource is-dirty] ;; Lone underscores are treated as mnemonic letter signifiers in the overflow ;; dropdown menu, and we cannot disable mnemonic parsing for it since the ;; control is internal. We also cannot replace them with double underscores to ;; escape them, as they will show up in the Tab labels and there appears to be ;; no way to enable mnemonic parsing for them. Attempts were made to call ;; setMnemonicParsing on the parent Labelled as the Tab graphic was added to ;; the DOM, but this only worked on macOS. As a workaround, we instead replace ;; underscores with the a unicode character that looks somewhat similar. (let [resource-name (resource/resource-name resource) escaped-resource-name (string/replace resource-name "_" "\u02CD")] (if is-dirty (str "*" escaped-resource-name) escaped-resource-name))) (g/defnode AppView (property stage Stage) (property scene Scene) (property editor-tabs-split SplitPane) (property active-tab-pane TabPane) (property tool-tab-pane TabPane) (property auto-pulls g/Any) (property active-tool g/Keyword) (property manip-space g/Keyword) (property keymap-config g/Any) (input open-views g/Any :array) (input open-dirty-views g/Any :array) (input scene-view-ids g/Any :array) (input hidden-renderable-tags types/RenderableTags) (input hidden-node-outline-key-paths types/NodeOutlineKeyPaths) (input active-outline g/Any) (input active-scene g/Any) (input project-id g/NodeID) (input selected-node-ids-by-resource-node g/Any) (input selected-node-properties-by-resource-node g/Any) (input sub-selections-by-resource-node g/Any) (input debugger-execution-locations g/Any) (output open-views g/Any :cached (g/fnk [open-views] (into {} open-views))) (output open-dirty-views g/Any :cached (g/fnk [open-dirty-views] (into #{} (keep #(when (second %) (first %))) open-dirty-views))) (output active-tab Tab (g/fnk [^TabPane active-tab-pane] (some-> active-tab-pane ui/selected-tab))) (output hidden-renderable-tags types/RenderableTags (gu/passthrough hidden-renderable-tags)) (output hidden-node-outline-key-paths types/NodeOutlineKeyPaths (gu/passthrough hidden-node-outline-key-paths)) (output active-outline g/Any (gu/passthrough active-outline)) (output active-scene g/Any (gu/passthrough active-scene)) (output active-view g/NodeID (g/fnk [^Tab active-tab] (when active-tab (ui/user-data active-tab ::view)))) (output active-view-info g/Any (g/fnk [^Tab active-tab] (when active-tab {:view-id (ui/user-data active-tab ::view) :view-type (ui/user-data active-tab ::view-type)}))) (output active-resource-node g/NodeID :cached (g/fnk [active-view open-views] (:resource-node (get open-views active-view)))) (output active-resource resource/Resource :cached (g/fnk [active-view open-views] (:resource (get open-views active-view)))) (output open-resource-nodes g/Any :cached (g/fnk [open-views] (->> open-views vals (map :resource-node)))) (output selected-node-ids g/Any (g/fnk [selected-node-ids-by-resource-node active-resource-node] (get selected-node-ids-by-resource-node active-resource-node))) (output selected-node-properties g/Any (g/fnk [selected-node-properties-by-resource-node active-resource-node] (get selected-node-properties-by-resource-node active-resource-node))) (output sub-selection g/Any (g/fnk [sub-selections-by-resource-node active-resource-node] (get sub-selections-by-resource-node active-resource-node))) (output refresh-tab-panes g/Any :cached (g/fnk [^SplitPane editor-tabs-split open-views open-dirty-views] (let [tab-panes (.getItems editor-tabs-split)] (doseq [^TabPane tab-pane tab-panes ^Tab tab (.getTabs tab-pane) :let [view (ui/user-data tab ::view) resource (:resource (get open-views view)) is-dirty (contains? open-dirty-views view) title (tab-title resource is-dirty)]] (ui/text! tab title))))) (output keymap g/Any :cached (g/fnk [keymap-config] (keymap/make-keymap keymap-config {:valid-command? (set (handler/available-commands))}))) (output debugger-execution-locations g/Any (gu/passthrough debugger-execution-locations))) (defn- selection->openable-resources [selection] (when-let [resources (handler/adapt-every selection resource/Resource)] (filterv resource/openable-resource? resources))) (defn- selection->single-openable-resource [selection] (when-let [r (handler/adapt-single selection resource/Resource)] (when (resource/openable-resource? r) r))) (defn- selection->single-resource [selection] (handler/adapt-single selection resource/Resource)) (defn- context-resource-file ([app-view selection] (g/with-auto-evaluation-context evaluation-context (context-resource-file app-view selection evaluation-context))) ([app-view selection evaluation-context] (or (selection->single-openable-resource selection) (g/node-value app-view :active-resource evaluation-context)))) (defn- context-resource ([app-view selection] (g/with-auto-evaluation-context evaluation-context (context-resource app-view selection evaluation-context))) ([app-view selection evaluation-context] (or (selection->single-resource selection) (g/node-value app-view :active-resource evaluation-context)))) (defn- disconnect-sources [target-node target-label] (for [[source-node source-label] (g/sources-of target-node target-label)] (g/disconnect source-node source-label target-node target-label))) (defn- replace-connection [source-node source-label target-node target-label] (concat (disconnect-sources target-node target-label) (if (and source-node (contains? (-> source-node g/node-type* g/output-labels) source-label)) (g/connect source-node source-label target-node target-label) []))) (defn- on-selected-tab-changed! [app-view app-scene resource-node view-type] (g/transact (concat (replace-connection resource-node :node-outline app-view :active-outline) (if (= :scene view-type) (replace-connection resource-node :scene app-view :active-scene) (disconnect-sources app-view :active-scene)))) (g/invalidate-outputs! [[app-view :active-tab]]) (ui/user-data! app-scene ::ui/refresh-requested? true)) (handler/defhandler :move-tool :workbench (enabled? [app-view] true) (run [app-view] (g/transact (g/set-property app-view :active-tool :move))) (state [app-view] (= (g/node-value app-view :active-tool) :move))) (handler/defhandler :scale-tool :workbench (enabled? [app-view] true) (run [app-view] (g/transact (g/set-property app-view :active-tool :scale))) (state [app-view] (= (g/node-value app-view :active-tool) :scale))) (handler/defhandler :rotate-tool :workbench (enabled? [app-view] true) (run [app-view] (g/transact (g/set-property app-view :active-tool :rotate))) (state [app-view] (= (g/node-value app-view :active-tool) :rotate))) (handler/defhandler :show-visibility-settings :workbench (run [app-view scene-visibility] (when-let [btn (some-> ^TabPane (g/node-value app-view :active-tab-pane) (ui/selected-tab) (.. getContent (lookup "#show-visibility-settings")))] (scene-visibility/show-visibility-settings! btn scene-visibility))) (state [app-view scene-visibility] (when-let [btn (some-> ^TabPane (g/node-value app-view :active-tab-pane) (ui/selected-tab) (.. getContent (lookup "#show-visibility-settings")))] ;; TODO: We have no mechanism for updating the style nor icon on ;; on the toolbar button. For now we piggyback on the state ;; update polling to set a style when the filters are active. (if (scene-visibility/filters-appear-active? scene-visibility) (ui/add-style! btn "filters-active") (ui/remove-style! btn "filters-active")) (scene-visibility/settings-visible? btn)))) (def ^:private eye-icon-svg-path (ui/load-svg-path "scene/images/eye_icon_eye_arrow.svg")) (def ^:private perspective-icon-svg-path (ui/load-svg-path "scene/images/perspective_icon.svg")) (defn make-svg-icon-graphic ^SVGPath [^SVGPath icon-template] (doto (SVGPath.) (.setContent (.getContent icon-template)))) (defn- make-visibility-settings-graphic [] (doto (StackPane.) (ui/children! [(doto (make-svg-icon-graphic eye-icon-svg-path) (.setId "eye-icon")) (doto (Ellipse. 3.0 3.0) (.setId "active-indicator"))]))) (handler/register-menu! :toolbar [{:id :select :icon "icons/45/Icons_T_01_Select.png" :command :select-tool} {:id :move :icon "icons/45/Icons_T_02_Move.png" :command :move-tool} {:id :rotate :icon "icons/45/Icons_T_03_Rotate.png" :command :rotate-tool} {:id :scale :icon "icons/45/Icons_T_04_Scale.png" :command :scale-tool} {:id :perspective-camera :graphic-fn (partial make-svg-icon-graphic perspective-icon-svg-path) :command :toggle-perspective-camera} {:id :visibility-settings :graphic-fn make-visibility-settings-graphic :command :show-visibility-settings}]) (def ^:const prefs-window-dimensions "window-dimensions") (def ^:const prefs-split-positions "split-positions") (def ^:const prefs-hidden-panes "hidden-panes") (handler/defhandler :quit :global (enabled? [] true) (run [] (let [^Stage main-stage (ui/main-stage)] (.fireEvent main-stage (WindowEvent. main-stage WindowEvent/WINDOW_CLOSE_REQUEST))))) (defn store-window-dimensions [^Stage stage prefs] (let [dims {:x (.getX stage) :y (.getY stage) :width (.getWidth stage) :height (.getHeight stage) :maximized (.isMaximized stage) :full-screen (.isFullScreen stage)}] (prefs/set-prefs prefs prefs-window-dimensions dims))) (defn restore-window-dimensions [^Stage stage prefs] (when-let [dims (prefs/get-prefs prefs prefs-window-dimensions nil)] (let [{:keys [x y width height maximized full-screen]} dims maximized (and maximized (not system/mac?))] ; Maximized is not really a thing on macOS, and if set, cannot become false. (when (and (number? x) (number? y) (number? width) (number? height)) (when-let [_ (seq (Screen/getScreensForRectangle x y width height))] (doto stage (.setX x) (.setY y)) ;; Maximized and setWidth/setHeight in combination triggers a bug on macOS where the window becomes invisible (when (and (not maximized) (not full-screen)) (doto stage (.setWidth width) (.setHeight height))))) (when maximized (.setMaximized stage true)) (when full-screen (.setFullScreen stage true))))) (def ^:private legacy-split-ids ["main-split" "center-split" "right-split" "assets-split"]) (def ^:private split-ids ["main-split" "workbench-split" "center-split" "right-split" "assets-split"]) (defn- existing-split-panes [^Scene scene] (into {} (keep (fn [split-id] (when-some [control (.lookup scene (str "#" split-id))] [(keyword split-id) control]))) split-ids)) (defn- stored-split-positions [prefs] (if-some [split-positions (prefs/get-prefs prefs prefs-split-positions nil)] (if (vector? split-positions) ; Legacy preference format (zipmap (map keyword legacy-split-ids) split-positions) split-positions) {})) (defn store-split-positions! [^Scene scene prefs] (let [split-positions (into (stored-split-positions prefs) (map (fn [[id ^SplitPane sp]] [id (.getDividerPositions sp)])) (existing-split-panes scene))] (prefs/set-prefs prefs prefs-split-positions split-positions))) (defn restore-split-positions! [^Scene scene prefs] (let [split-positions (stored-split-positions prefs) split-panes (existing-split-panes scene)] (doseq [[id positions] split-positions] (when-some [^SplitPane split-pane (get split-panes id)] (.setDividerPositions split-pane (double-array positions)) (.layout split-pane))))) (defn stored-hidden-panes [prefs] (prefs/get-prefs prefs prefs-hidden-panes #{})) (defn store-hidden-panes! [^Scene scene prefs] (let [hidden-panes (into #{} (remove (partial pane-visible? scene)) (keys split-info-by-pane-kw))] (prefs/set-prefs prefs prefs-hidden-panes hidden-panes))) (defn restore-hidden-panes! [^Scene scene prefs] (let [hidden-panes (stored-hidden-panes prefs)] (doseq [pane-kw hidden-panes] (set-pane-visible! scene pane-kw false)))) (handler/defhandler :preferences :global (run [workspace prefs] (prefs-dialog/open-prefs prefs) (workspace/update-build-settings! workspace prefs))) (defn- collect-resources [{:keys [children] :as resource}] (if (empty? children) #{resource} (set (concat [resource] (mapcat collect-resources children))))) (defn- get-active-tabs [app-view evaluation-context] (let [tab-pane ^TabPane (g/node-value app-view :active-tab-pane evaluation-context)] (.getTabs tab-pane))) (defn- make-render-build-error [main-scene tool-tab-pane build-errors-view] (fn [error-value] (build-errors-view/update-build-errors build-errors-view error-value) (show-build-errors! main-scene tool-tab-pane))) (def ^:private remote-log-pump-thread (atom nil)) (def ^:private console-stream (atom nil)) (defn- reset-remote-log-pump-thread! [^Thread new] (when-let [old ^Thread @remote-log-pump-thread] (.interrupt old)) (reset! remote-log-pump-thread new)) (defn- start-log-pump! [log-stream sink-fn] (doto (Thread. (fn [] (try (let [this (Thread/currentThread)] (with-open [buffered-reader ^BufferedReader (io/reader log-stream :encoding "UTF-8")] (loop [] (when-not (.isInterrupted this) (when-let [line (.readLine buffered-reader)] ; line of text or nil if eof reached (sink-fn line) (recur)))))) (catch IOException _ ;; Losing the log connection is ok and even expected nil) (catch InterruptedException _ ;; Losing the log connection is ok and even expected nil)))) (.start))) (defn- local-url [target web-server] (format "http://%s:%s%s" (:local-address target) (http-server/port web-server) hot-reload/url-prefix)) (def ^:private app-task-progress {:main (ref progress/done) :build (ref progress/done) :resource-sync (ref progress/done) :save-all (ref progress/done) :fetch-libraries (ref progress/done) :download-update (ref progress/done)}) (defn- cancel-task! [task-key] (dosync (let [progress-ref (task-key app-task-progress)] (ref-set progress-ref (progress/cancel! @progress-ref))))) (def ^:private app-task-ui-priority "Task priority in descending order (from highest to lowest)" [:save-all :resource-sync :fetch-libraries :build :download-update :main]) (def ^:private render-task-progress-ui-inflight (ref false)) (defn- render-task-progress-ui! [] (let [task-progress-snapshot (ref nil)] (dosync (ref-set render-task-progress-ui-inflight false) (ref-set task-progress-snapshot (into {} (map (juxt first (comp deref second))) app-task-progress))) (let [status-bar (.. (ui/main-stage) (getScene) (getRoot) (lookup "#status-bar")) [key progress] (->> app-task-ui-priority (map (juxt identity @task-progress-snapshot)) (filter (comp (complement progress/done?) second)) first) show-progress-hbox? (boolean (and (not= key :main) progress (not (progress/done? progress))))] (ui/with-controls status-bar [progress-bar progress-hbox progress-percentage-label status-label progress-cancel-button] (ui/render-progress-message! (if key progress (@task-progress-snapshot :main)) status-label) ;; The bottom right of the status bar can show either the progress-hbox ;; or the update-link, or both. The progress-hbox will cover ;; the update-link if both are visible. (if-not show-progress-hbox? (ui/visible! progress-hbox false) (do (ui/visible! progress-hbox true) (ui/render-progress-bar! progress progress-bar) (ui/render-progress-percentage! progress progress-percentage-label) (if (progress/cancellable? progress) (doto progress-cancel-button (ui/visible! true) (ui/managed! true) (ui/on-action! (fn [_] (cancel-task! key)))) (doto progress-cancel-button (ui/visible! false) (ui/managed! false) (ui/on-action! identity))))))))) (defn- render-task-progress! [key progress] (let [schedule-render-task-progress-ui (ref false)] (dosync (ref-set (get app-task-progress key) progress) (ref-set schedule-render-task-progress-ui (not @render-task-progress-ui-inflight)) (ref-set render-task-progress-ui-inflight true)) (when @schedule-render-task-progress-ui (ui/run-later (render-task-progress-ui!))))) (defn make-render-task-progress [key] (assert (contains? app-task-progress key)) (progress/throttle-render-progress (fn [progress] (render-task-progress! key progress)))) (defn make-task-cancelled-query [keyword] (fn [] (progress/cancelled? @(keyword app-task-progress)))) (defn render-main-task-progress! [progress] (render-task-progress! :main progress)) (defn- report-build-launch-progress! [message] (render-main-task-progress! (progress/make message))) (defn clear-build-launch-progress! [] (render-main-task-progress! progress/done)) (defn- decorate-target [engine-descriptor target] (assoc target :engine-id (:id engine-descriptor))) (defn- launch-engine! [engine-descriptor project-directory prefs debug?] (try (report-build-launch-progress! "Launching engine...") (let [engine (engine/install-engine! project-directory engine-descriptor) launched-target (->> (engine/launch! engine project-directory prefs debug?) (decorate-target engine-descriptor) (targets/add-launched-target!) (targets/select-target! prefs))] (report-build-launch-progress! (format "Launched %s" (targets/target-message-label launched-target))) launched-target) (catch Exception e (targets/kill-launched-targets!) (report-build-launch-progress! "Launch failed") (throw e)))) (defn- reset-console-stream! [stream] (reset! console-stream stream) (console/clear-console!)) (defn- make-remote-log-sink [log-stream] (fn [line] (when (= @console-stream log-stream) (console/append-console-line! line)))) (defn- make-launched-log-sink [launched-target] (let [initial-output (atom "")] (fn [line] (when (< (count @initial-output) 5000) (swap! initial-output str line "\n") (when-let [target-info (engine/parse-launched-target-info @initial-output)] (targets/update-launched-target! launched-target target-info))) (when (= @console-stream (:log-stream launched-target)) (console/append-console-line! line))))) (defn- reboot-engine! [target web-server debug?] (try (report-build-launch-progress! (format "Rebooting %s..." (targets/target-message-label target))) (engine/reboot! target (local-url target web-server) debug?) (report-build-launch-progress! (format "Rebooted %s" (targets/target-message-label target))) target (catch Exception e (report-build-launch-progress! "Reboot failed") (throw e)))) (def ^:private build-in-progress? (atom false)) (defn- on-launched-hook! [project process url] (let [hook-options {:exception-policy :ignore :opts {:url url}}] (future (error-reporting/catch-all! (extensions/execute-hook! project :on-target-launched hook-options) (process/watchdog! process #(extensions/execute-hook! project :on-target-terminated hook-options)))))) (defn- launch-built-project! [project engine-descriptor project-directory prefs web-server debug?] (let [selected-target (targets/selected-target prefs) launch-new-engine! (fn [] (targets/kill-launched-targets!) (let [launched-target (launch-engine! engine-descriptor project-directory prefs debug?) log-stream (:log-stream launched-target)] (targets/when-url (:id launched-target) #(on-launched-hook! project (:process launched-target) %)) (reset-console-stream! log-stream) (reset-remote-log-pump-thread! nil) (start-log-pump! log-stream (make-launched-log-sink launched-target)) launched-target))] (try (cond (not selected-target) (launch-new-engine!) (not (targets/controllable-target? selected-target)) (do (assert (targets/launched-target? selected-target)) (launch-new-engine!)) (and (targets/controllable-target? selected-target) (targets/remote-target? selected-target)) (let [log-stream (engine/get-log-service-stream selected-target)] (reset-console-stream! log-stream) (reset-remote-log-pump-thread! (start-log-pump! log-stream (make-remote-log-sink log-stream))) (reboot-engine! selected-target web-server debug?)) :else (do (assert (and (targets/controllable-target? selected-target) (targets/launched-target? selected-target))) (if (= (:id engine-descriptor) (:engine-id selected-target)) (do ;; We're running "the same" engine and can reuse the ;; running process by rebooting (reset-console-stream! (:log-stream selected-target)) (reset-remote-log-pump-thread! nil) ;; Launched target log pump already ;; running to keep engine process ;; from halting because stdout/err is ;; not consumed. (reboot-engine! selected-target web-server debug?)) (launch-new-engine!)))) (catch Exception e (log/warn :exception e) (dialogs/make-info-dialog {:title "Launch Failed" :icon :icon/triangle-error :header {:fx/type :v-box :children [{:fx/type fxui/label :variant :header :text (format "Launching %s failed" (if (some? selected-target) (targets/target-message-label selected-target) "New Local Engine"))} {:fx/type fxui/label :text "If the engine is already running, shut down the process manually and retry"}]} :content (.getMessage e)}))))) (defn- build-project! [project evaluation-context extra-build-targets old-artifact-map render-progress!] (let [game-project (project/get-resource-node project "/game.project" evaluation-context) render-progress! (progress/throttle-render-progress render-progress!)] (try (ui/with-progress [render-progress! render-progress!] (build/build-project! project game-project evaluation-context extra-build-targets old-artifact-map render-progress!)) (catch Throwable error (error-reporting/report-exception! error) nil)))) (defn- cached-build-target-output? [node-id label evaluation-context] (and (= :build-targets label) (project/project-resource-node? node-id evaluation-context))) (defn- update-system-cache-build-targets! [evaluation-context] ;; To avoid cache churn, we only transfer the most important entries to the system cache. (let [pruned-evaluation-context (g/pruned-evaluation-context evaluation-context cached-build-target-output?)] (g/update-cache-from-evaluation-context! pruned-evaluation-context))) (defn async-build! [project prefs {:keys [debug? engine?] :or {debug? false engine? true}} old-artifact-map render-build-progress! result-fn] (let [;; After any pre-build hooks have completed successfully, we will start ;; the engine build on a separate background thread so the build servers ;; can work while we build the project. We will await the results of the ;; engine build in the final phase. engine-build-future-atom (atom nil) cancel-engine-build! (fn cancel-engine-build! [] (when-some [engine-build-future (thread-util/preset! engine-build-future-atom nil)] (future-cancel engine-build-future) nil)) start-engine-build! (fn start-engine-build! [] (assert (ui/on-ui-thread?)) (cancel-engine-build!) (when engine? (let [evaluation-context (g/make-evaluation-context) platform (engine/current-platform)] (reset! engine-build-future-atom (future (try (let [engine (engine/get-engine project evaluation-context prefs platform)] (ui/run-later ;; This potentially saves us from having to ;; re-calculate native extension file hashes the ;; next time we build the project. (g/update-cache-from-evaluation-context! evaluation-context)) engine) (catch Throwable error error)))) nil))) run-on-background-thread! (fn run-on-background-thread! [background-thread-fn ui-thread-fn] (future (try (let [return-value (background-thread-fn)] (ui/run-later (try (ui-thread-fn return-value) (catch Throwable error (reset! build-in-progress? false) (render-build-progress! progress/done) (cancel-engine-build!) (throw error))))) (catch Throwable error (reset! build-in-progress? false) (render-build-progress! progress/done) (cancel-engine-build!) (error-reporting/report-exception! error)))) nil) finish-with-result! (fn finish-with-result! [project-build-results engine build-engine-exception] (reset! build-in-progress? false) (render-build-progress! progress/done) (cancel-engine-build!) (when (some? result-fn) (result-fn project-build-results engine build-engine-exception) nil)) phase-5-await-engine-build! (fn phase-5-await-engine-build! [project-build-results] (assert (nil? (:error project-build-results))) (let [engine-build-future @engine-build-future-atom] (if (nil? engine-build-future) (finish-with-result! project-build-results nil nil) (do (render-build-progress! (progress/make-indeterminate "Fetching engine...")) (run-on-background-thread! (fn run-engine-build-on-background-thread! [] (deref engine-build-future)) (fn process-engine-build-results-on-ui-thread! [engine-or-exception] (if (instance? Throwable engine-or-exception) (finish-with-result! project-build-results nil engine-or-exception) (finish-with-result! project-build-results engine-or-exception nil)))))))) phase-4-run-post-build-hook! (fn phase-4-run-post-build-hook! [project-build-results] (render-build-progress! (progress/make-indeterminate "Executing post-build hooks...")) (let [platform (engine/current-platform) project-build-successful? (nil? (:error project-build-results))] (run-on-background-thread! (fn run-post-build-hook-on-background-thread! [] (extensions/execute-hook! project :on-build-finished {:exception-policy :ignore :opts {:success project-build-successful? :platform platform}})) (fn process-post-build-hook-results-on-ui-thread! [_] (if project-build-successful? (phase-5-await-engine-build! project-build-results) (finish-with-result! project-build-results nil nil)))))) phase-3-build-project! (fn phase-3-build-project! [] ;; We're about to create an evaluation-context. Make sure it is ;; created from the main thread, so it makes sense to update the cache ;; from it after the project build concludes. Note that we selectively ;; transfer only the cached build-targets back to the system cache. ;; We do this because the project build process involves most of the ;; cached outputs in the project graph, and the intermediate steps ;; risk evicting the previous build targets as the cache fills up. (assert (ui/on-ui-thread?)) (let [evaluation-context (g/make-evaluation-context)] (render-build-progress! (progress/make "Building project..." 1)) (run-on-background-thread! (fn run-project-build-on-background-thread! [] (let [extra-build-targets (when debug? (debug-view/build-targets project evaluation-context))] (build-project! project evaluation-context extra-build-targets old-artifact-map render-build-progress!))) (fn process-project-build-results-on-ui-thread! [project-build-results] (update-system-cache-build-targets! evaluation-context) (phase-4-run-post-build-hook! project-build-results))))) phase-2-start-engine-build! (fn phase-2-start-engine-build! [] (start-engine-build!) (phase-3-build-project!)) phase-1-run-pre-build-hook! (fn phase-1-run-pre-build-hook! [] (render-build-progress! (progress/make-indeterminate "Executing pre-build hooks...")) (let [platform (engine/current-platform)] (run-on-background-thread! (fn run-pre-build-hook-on-background-thread! [] (let [extension-error (extensions/execute-hook! project :on-build-started {:exception-policy :as-error :opts {:platform platform}})] ;; If there was an error in the pre-build hook, we won't proceed ;; with the project build. But we still want to report the build ;; failure to any post-build hooks that might need to know. (when (some? extension-error) (render-build-progress! (progress/make-indeterminate "Executing post-build hooks...")) (extensions/execute-hook! project :on-build-finished {:exception-policy :ignore :opts {:success false :platform platform}})) extension-error)) (fn process-pre-build-hook-results-on-ui-thread! [extension-error] (if (some? extension-error) (finish-with-result! {:error extension-error} nil nil) (phase-2-start-engine-build!))))))] ;; Trigger phase 1. Subsequent phases will be triggered as prior phases ;; finish without errors. Each phase will do some work on a background ;; thread, then process the results on the ui thread, and potentially ;; trigger subsequent phases which will again get off the ui thread as ;; soon as they can. (assert (not @build-in-progress?)) (reset! build-in-progress? true) (phase-1-run-pre-build-hook!))) (defn- handle-build-results! [workspace render-build-error! build-results] (let [{:keys [error artifact-map etags]} build-results] (if (some? error) (do (render-build-error! error) nil) (do (workspace/artifact-map! workspace artifact-map) (workspace/etags! workspace etags) (workspace/save-build-cache! workspace) build-results)))) (defn- build-handler [project workspace prefs web-server build-errors-view main-stage tool-tab-pane] (let [project-directory (io/file (workspace/project-path workspace)) main-scene (.getScene ^Stage main-stage) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view)] (build-errors-view/clear-build-errors build-errors-view) (async-build! project prefs {:debug? false} (workspace/artifact-map workspace) (make-render-task-progress :build) (fn [build-results engine-descriptor build-engine-exception] (when (handle-build-results! workspace render-build-error! build-results) (when engine-descriptor (show-console! main-scene tool-tab-pane) (launch-built-project! project engine-descriptor project-directory prefs web-server false)) (when build-engine-exception (log/warn :exception build-engine-exception) (g/with-auto-evaluation-context evaluation-context (engine-build-errors/handle-build-error! render-build-error! project evaluation-context build-engine-exception)))))))) (handler/defhandler :build :global (enabled? [] (not @build-in-progress?)) (run [project workspace prefs web-server build-errors-view debug-view main-stage tool-tab-pane] (debug-view/detach! debug-view) (build-handler project workspace prefs web-server build-errors-view main-stage tool-tab-pane))) (defn- debugging-supported? [project] (if (project/shared-script-state? project) true (do (dialogs/make-info-dialog {:title "Debugging Not Supported" :icon :icon/triangle-error :header "This project cannot be used with the debugger" :content {:fx/type fxui/label :style-class "dialog-content-padding" :text "It is configured to disable shared script state. If you do not specifically require different script states, consider changing the script.shared_state property in game.project."}}) false))) (defn- run-with-debugger! [workspace project prefs debug-view render-build-error! web-server] (let [project-directory (io/file (workspace/project-path workspace))] (async-build! project prefs {:debug? true} (workspace/artifact-map workspace) (make-render-task-progress :build) (fn [build-results engine-descriptor build-engine-exception] (when (handle-build-results! workspace render-build-error! build-results) (when engine-descriptor (when-let [target (launch-built-project! project engine-descriptor project-directory prefs web-server true)] (when (nil? (debug-view/current-session debug-view)) (debug-view/start-debugger! debug-view project (:address target "localhost"))))) (when build-engine-exception (log/warn :exception build-engine-exception) (g/with-auto-evaluation-context evaluation-context (engine-build-errors/handle-build-error! render-build-error! project evaluation-context build-engine-exception)))))))) (defn- attach-debugger! [workspace project prefs debug-view render-build-error!] (async-build! project prefs {:debug? true :engine? false} (workspace/artifact-map workspace) (make-render-task-progress :build) (fn [build-results _ _] (when (handle-build-results! workspace render-build-error! build-results) (let [target (targets/selected-target prefs)] (when (targets/controllable-target? target) (debug-view/attach! debug-view project target (:artifacts build-results)))))))) (handler/defhandler :start-debugger :global ;; NOTE: Shares a shortcut with :debug-view/continue. ;; Only one of them can be active at a time. This creates the impression that ;; there is a single menu item whose label changes in various states. (active? [debug-view evaluation-context] (not (debug-view/debugging? debug-view evaluation-context))) (enabled? [] (not @build-in-progress?)) (run [project workspace prefs web-server build-errors-view console-view debug-view main-stage tool-tab-pane] (when (debugging-supported? project) (let [main-scene (.getScene ^Stage main-stage) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view)] (build-errors-view/clear-build-errors build-errors-view) (if (debug-view/can-attach? prefs) (attach-debugger! workspace project prefs debug-view render-build-error!) (run-with-debugger! workspace project prefs debug-view render-build-error! web-server)))))) (handler/defhandler :rebuild :global (enabled? [] (not @build-in-progress?)) (run [project workspace prefs web-server build-errors-view debug-view main-stage tool-tab-pane] (debug-view/detach! debug-view) (workspace/clear-build-cache! workspace) (build-handler project workspace prefs web-server build-errors-view main-stage tool-tab-pane))) (handler/defhandler :build-html5 :global (run [project prefs web-server build-errors-view changes-view main-stage tool-tab-pane] (let [main-scene (.getScene ^Stage main-stage) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view) render-reload-progress! (make-render-task-progress :resource-sync) render-save-progress! (make-render-task-progress :save-all) render-build-progress! (make-render-task-progress :build) task-cancelled? (make-task-cancelled-query :build) bob-args (bob/build-html5-bob-args project prefs)] (build-errors-view/clear-build-errors build-errors-view) (disk/async-bob-build! render-reload-progress! render-save-progress! render-build-progress! task-cancelled? render-build-error! bob/build-html5-bob-commands bob-args project changes-view (fn [successful?] (when successful? (ui/open-url (format "http://localhost:%d%s/index.html" (http-server/port web-server) bob/html5-url-prefix)))))))) (defn- updated-build-resource-proj-paths [old-etags new-etags] ;; We only want to return resources that were present in the old etags since ;; we don't want to ask the engine to reload something it has not seen yet. ;; It is presumed that the engine will follow any newly-introduced references ;; and load the resources. We might ask the engine to reload these resources ;; the next time they are modified. (into #{} (keep (fn [[proj-path old-etag]] (when-some [new-etag (new-etags proj-path)] (when (not= old-etag new-etag) proj-path)))) old-etags)) (defn- updated-build-resources [evaluation-context project old-etags new-etags proj-path-or-resource] (let [resource-node (project/get-resource-node project proj-path-or-resource evaluation-context) build-targets (g/node-value resource-node :build-targets evaluation-context) updated-build-resource-proj-paths (updated-build-resource-proj-paths old-etags new-etags)] (into [] (keep (fn [{build-resource :resource :as _build-target}] (when (contains? updated-build-resource-proj-paths (resource/proj-path build-resource)) build-resource))) (rseq (pipeline/flatten-build-targets build-targets))))) (defn- can-hot-reload? [debug-view prefs evaluation-context] (when-some [target (targets/selected-target prefs)] (and (targets/controllable-target? target) (not (debug-view/suspended? debug-view evaluation-context)) (not @build-in-progress?)))) (defn- hot-reload! [project prefs build-errors-view main-stage tool-tab-pane] (let [main-scene (.getScene ^Stage main-stage) target (targets/selected-target prefs) workspace (project/workspace project) old-artifact-map (workspace/artifact-map workspace) old-etags (workspace/etags workspace) render-build-progress! (make-render-task-progress :build) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view) opts {:debug? false :engine? false}] ;; NOTE: We must build the entire project even if we only want to reload a ;; subset of resources in order to maintain a functioning build cache. ;; If we decide to support hot reload of a subset of resources, we must ;; keep track of which resource versions have been loaded by the engine, ;; or we might miss resources that were recompiled but never reloaded. (build-errors-view/clear-build-errors build-errors-view) (async-build! project prefs opts old-artifact-map render-build-progress! (fn [{:keys [error artifact-map etags]} _ _] (if (some? error) (render-build-error! error) (do (workspace/artifact-map! workspace artifact-map) (workspace/etags! workspace etags) (workspace/save-build-cache! workspace) (try (when-some [updated-build-resources (not-empty (g/with-auto-evaluation-context evaluation-context (updated-build-resources evaluation-context project old-etags etags "/game.project")))] (engine/reload-build-resources! target updated-build-resources)) (catch Exception e (dialogs/make-info-dialog {:title "Hot Reload Failed" :icon :icon/triangle-error :header (format "Failed to reload resources on '%s'" (targets/target-message-label (targets/selected-target prefs))) :content (.getMessage e)}))))))))) (handler/defhandler :hot-reload :global (enabled? [debug-view prefs evaluation-context] (can-hot-reload? debug-view prefs evaluation-context)) (run [project app-view prefs build-errors-view selection main-stage tool-tab-pane] (hot-reload! project prefs build-errors-view main-stage tool-tab-pane))) (handler/defhandler :close :global (enabled? [app-view evaluation-context] (not-empty (get-active-tabs app-view evaluation-context))) (run [app-view] (let [tab-pane (g/node-value app-view :active-tab-pane)] (when-let [tab (ui/selected-tab tab-pane)] (remove-tab! tab-pane tab))))) (handler/defhandler :close-other :global (enabled? [app-view evaluation-context] (not-empty (next (get-active-tabs app-view evaluation-context)))) (run [app-view] (let [tab-pane ^TabPane (g/node-value app-view :active-tab-pane)] (when-let [selected-tab (ui/selected-tab tab-pane)] ;; Plain doseq over .getTabs will use the iterable interface ;; and we get a ConcurrentModificationException since we ;; remove from the list while iterating. Instead put the tabs ;; in a (non-lazy) vec before iterating. (doseq [tab (vec (.getTabs tab-pane))] (when (not= tab selected-tab) (remove-tab! tab-pane tab))))))) (handler/defhandler :close-all :global (enabled? [app-view evaluation-context] (not-empty (get-active-tabs app-view evaluation-context))) (run [app-view] (let [tab-pane ^TabPane (g/node-value app-view :active-tab-pane)] (doseq [tab (vec (.getTabs tab-pane))] (remove-tab! tab-pane tab))))) (defn- editor-tab-pane "Returns the editor TabPane that is above the Node in the scene hierarchy, or nil if the Node does not reside under an editor TabPane." ^TabPane [node] (when-some [parent-tab-pane (ui/parent-tab-pane node)] (when (= "editor-tabs-split" (some-> (ui/tab-pane-parent parent-tab-pane) (.getId))) parent-tab-pane))) (declare ^:private configure-editor-tab-pane!) (defn- find-other-tab-pane ^TabPane [^SplitPane editor-tabs-split ^TabPane current-tab-pane] (first-where #(not (identical? current-tab-pane %)) (.getItems editor-tabs-split))) (defn- add-other-tab-pane! ^TabPane [^SplitPane editor-tabs-split app-view] (let [tab-panes (.getItems editor-tabs-split) app-stage ^Stage (g/node-value app-view :stage) app-scene (.getScene app-stage) new-tab-pane (TabPane.)] (assert (= 1 (count tab-panes))) (.add tab-panes new-tab-pane) (configure-editor-tab-pane! new-tab-pane app-scene app-view) new-tab-pane)) (defn- open-tab-count ^long [app-view evaluation-context] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split evaluation-context)] (loop [tab-panes (.getItems editor-tabs-split) tab-count 0] (if-some [^TabPane tab-pane (first tab-panes)] (recur (next tab-panes) (+ tab-count (.size (.getTabs tab-pane)))) tab-count)))) (defn- open-tab-pane-count ^long [app-view evaluation-context] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split evaluation-context)] (.size (.getItems editor-tabs-split)))) (handler/defhandler :move-tab :global (enabled? [app-view evaluation-context] (< 1 (open-tab-count app-view evaluation-context))) (run [app-view user-data] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split) source-tab-pane ^TabPane (g/node-value app-view :active-tab-pane) selected-tab (ui/selected-tab source-tab-pane) dest-tab-pane (or (find-other-tab-pane editor-tabs-split source-tab-pane) (add-other-tab-pane! editor-tabs-split app-view))] (.remove (.getTabs source-tab-pane) selected-tab) (.add (.getTabs dest-tab-pane) selected-tab) (.select (.getSelectionModel dest-tab-pane) selected-tab) (.requestFocus dest-tab-pane)))) (handler/defhandler :swap-tabs :global (enabled? [app-view evaluation-context] (< 1 (open-tab-pane-count app-view evaluation-context))) (run [app-view user-data] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split) active-tab-pane ^TabPane (g/node-value app-view :active-tab-pane) other-tab-pane (find-other-tab-pane editor-tabs-split active-tab-pane) active-tab-pane-selection (.getSelectionModel active-tab-pane) other-tab-pane-selection (.getSelectionModel other-tab-pane) active-tab-index (.getSelectedIndex active-tab-pane-selection) other-tab-index (.getSelectedIndex other-tab-pane-selection) active-tabs (.getTabs active-tab-pane) other-tabs (.getTabs other-tab-pane) active-tab (.get active-tabs active-tab-index) other-tab (.get other-tabs other-tab-index)] ;; Fix for DEFEDIT-1673: ;; We need to swap in a dummy tab here so that a tab is never in both ;; TabPanes at once, since the tab lists are observed internally. If we ;; do not, the tabs will lose track of their parent TabPane. (.set other-tabs other-tab-index (Tab.)) (.set active-tabs active-tab-index other-tab) (.set other-tabs other-tab-index active-tab) (.select active-tab-pane-selection other-tab) (.select other-tab-pane-selection active-tab) (.requestFocus other-tab-pane)))) (handler/defhandler :join-tab-panes :global (enabled? [app-view evaluation-context] (< 1 (open-tab-pane-count app-view evaluation-context))) (run [app-view user-data] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split) active-tab-pane ^TabPane (g/node-value app-view :active-tab-pane) selected-tab (ui/selected-tab active-tab-pane) tab-panes (.getItems editor-tabs-split) first-tab-pane ^TabPane (.get tab-panes 0) second-tab-pane ^TabPane (.get tab-panes 1) first-tabs (.getTabs first-tab-pane) second-tabs (.getTabs second-tab-pane) moved-tabs (vec second-tabs)] (.clear second-tabs) (.addAll first-tabs ^Collection moved-tabs) (.select (.getSelectionModel first-tab-pane) selected-tab) (.requestFocus first-tab-pane)))) (defn make-about-dialog [] (let [root ^Parent (ui/load-fxml "about.fxml") stage (ui/make-dialog-stage) scene (Scene. root) controls (ui/collect-controls root ["version" "channel" "editor-sha1" "engine-sha1" "time", "sponsor-push"])] (ui/text! (:version controls) (System/getProperty "defold.version" "No version")) (ui/text! (:channel controls) (or (system/defold-channel) "No channel")) (ui/text! (:editor-sha1 controls) (or (system/defold-editor-sha1) "No editor sha1")) (ui/text! (:engine-sha1 controls) (or (system/defold-engine-sha1) "No engine sha1")) (ui/text! (:time controls) (or (system/defold-build-time) "No build time")) (UIUtil/stringToTextFlowNodes (:sponsor-push controls) "[Defold Foundation Development Fund](https://www.defold.com/community-donations)") (ui/title! stage "About") (.setScene stage scene) (ui/show! stage))) (handler/defhandler :documentation :global (run [] (ui/open-url "https://www.defold.com/learn/"))) (handler/defhandler :support-forum :global (run [] (ui/open-url "https://forum.defold.com/"))) (handler/defhandler :asset-portal :global (run [] (ui/open-url "https://www.defold.com/assets"))) (handler/defhandler :report-issue :global (run [] (ui/open-url (github/new-issue-link)))) (handler/defhandler :report-suggestion :global (run [] (ui/open-url (github/new-suggestion-link)))) (handler/defhandler :search-issues :global (run [] (ui/open-url (github/search-issues-link)))) (handler/defhandler :show-logs :global (run [] (ui/open-file (.getAbsoluteFile (.toFile (Editor/getLogDirectory)))))) (handler/defhandler :donate :global (run [] (ui/open-url "https://www.defold.com/donate"))) (handler/defhandler :about :global (run [] (make-about-dialog))) (handler/defhandler :reload-stylesheet :global (run [] (ui/reload-root-styles!))) (handler/register-menu! ::menubar [{:label "File" :id ::file :children [{:label "New..." :id ::new :command :new-file} {:label "Open" :id ::open :command :open} {:label "Synchronize..." :id ::synchronize :command :synchronize} {:label "Save All" :id ::save-all :command :save-all} {:label :separator} {:label "Open Assets..." :command :open-asset} {:label "Search in Files..." :command :search-in-files} {:label :separator} {:label "Close" :command :close} {:label "Close All" :command :close-all} {:label "Close Others" :command :close-other} {:label :separator} {:label "Referencing Files..." :command :referencing-files} {:label "Dependencies..." :command :dependencies} {:label "Hot Reload" :command :hot-reload} {:label :separator} {:label "Preferences..." :command :preferences} {:label "Quit" :command :quit}]} {:label "Edit" :id ::edit :children [{:label "Undo" :icon "icons/undo.png" :command :undo} {:label "Redo" :icon "icons/redo.png" :command :redo} {:label :separator} {:label "Cut" :command :cut} {:label "Copy" :command :copy} {:label "Paste" :command :paste} {:label "Select All" :command :select-all} {:label "Delete" :icon "icons/32/Icons_M_06_trash.png" :command :delete} {:label :separator} {:label "Move Up" :command :move-up} {:label "Move Down" :command :move-down} {:label :separator :id ::edit-end}]} {:label "View" :id ::view :children [{:label "Toggle Assets Pane" :command :toggle-pane-left} {:label "Toggle Tools Pane" :command :toggle-pane-bottom} {:label "Toggle Properties Pane" :command :toggle-pane-right} {:label :separator} {:label "Show Console" :command :show-console} {:label "Show Curve Editor" :command :show-curve-editor} {:label "Show Build Errors" :command :show-build-errors} {:label "Show Search Results" :command :show-search-results} {:label :separator :id ::view-end}]} {:label "Help" :children [{:label "Profiler" :children [{:label "Measure" :command :profile} {:label "Measure and Show" :command :profile-show}]} {:label "Reload Stylesheet" :command :reload-stylesheet} {:label "Show Logs" :command :show-logs} {:label :separator} {:label "Documentation" :command :documentation} {:label "Support Forum" :command :support-forum} {:label "Find Assets" :command :asset-portal} {:label :separator} {:label "Report Issue" :command :report-issue} {:label "Report Suggestion" :command :report-suggestion} {:label "Search Issues" :command :search-issues} {:label :separator} {:label "Development Fund" :command :donate} {:label :separator} {:label "About" :command :about}]}]) (handler/register-menu! ::tab-menu [{:label "Close" :command :close} {:label "Close Others" :command :close-other} {:label "Close All" :command :close-all} {:label :separator} {:label "Move to Other Tab Pane" :command :move-tab} {:label "Swap With Other Tab Pane" :command :swap-tabs} {:label "Join Tab Panes" :command :join-tab-panes} {:label :separator} {:label "Copy Project Path" :command :copy-project-path} {:label "Copy Full Path" :command :copy-full-path} {:label "Copy Require Path" :command :copy-require-path} {:label :separator} {:label "Show in Asset Browser" :icon "icons/32/Icons_S_14_linkarrow.png" :command :show-in-asset-browser} {:label "Show in Desktop" :icon "icons/32/Icons_S_14_linkarrow.png" :command :show-in-desktop} {:label "Referencing Files..." :command :referencing-files} {:label "Dependencies..." :command :dependencies}]) (defrecord SelectionProvider [app-view] handler/SelectionProvider (selection [_] (g/node-value app-view :selected-node-ids)) (succeeding-selection [_] []) (alt-selection [_] [])) (defn ->selection-provider [app-view] (SelectionProvider. app-view)) (defn select ([app-view node-ids] (select app-view (g/node-value app-view :active-resource-node) node-ids)) ([app-view resource-node node-ids] (g/with-auto-evaluation-context evaluation-context (let [project-id (g/node-value app-view :project-id evaluation-context) open-resource-nodes (g/node-value app-view :open-resource-nodes evaluation-context)] (project/select project-id resource-node node-ids open-resource-nodes))))) (defn select! ([app-view node-ids] (select! app-view node-ids (gensym))) ([app-view node-ids op-seq] (g/transact (concat (g/operation-sequence op-seq) (g/operation-label "Select") (select app-view node-ids))))) (defn sub-select! ([app-view sub-selection] (sub-select! app-view sub-selection (gensym))) ([app-view sub-selection op-seq] (g/with-auto-evaluation-context evaluation-context (let [project-id (g/node-value app-view :project-id evaluation-context) active-resource-node (g/node-value app-view :active-resource-node evaluation-context) open-resource-nodes (g/node-value app-view :open-resource-nodes evaluation-context)] (g/transact (concat (g/operation-sequence op-seq) (g/operation-label "Select") (project/sub-select project-id active-resource-node sub-selection open-resource-nodes))))))) (defn- make-title ([] "Defold Editor 2.0") ([project-title] (str project-title " - " (make-title)))) (defn- refresh-app-title! [^Stage stage project] (let [settings (g/node-value project :settings) project-title (settings ["project" "title"]) new-title (make-title project-title)] (when (not= (.getTitle stage) new-title) (.setTitle stage new-title)))) (defn- refresh-menus-and-toolbars! [app-view ^Scene scene] (let [keymap (g/node-value app-view :keymap) command->shortcut (keymap/command->shortcut keymap)] (ui/user-data! scene :command->shortcut command->shortcut) (ui/refresh scene))) (defn- refresh-views! [app-view] (let [auto-pulls (g/node-value app-view :auto-pulls)] (doseq [[node label] auto-pulls] (profiler/profile "view" (:name @(g/node-type* node)) (g/node-value node label))))) (defn- refresh-scene-views! [app-view] (profiler/begin-frame) (doseq [view-id (g/node-value app-view :scene-view-ids)] (try (scene/refresh-scene-view! view-id) (catch Throwable error (error-reporting/report-exception! error)))) (scene-cache/prune-context! nil)) (defn- dispose-scene-views! [app-view] (doseq [view-id (g/node-value app-view :scene-view-ids)] (try (scene/dispose-scene-view! view-id) (catch Throwable error (error-reporting/report-exception! error)))) (scene-cache/drop-context! nil)) (defn- tab->resource-node [^Tab tab] (some-> tab (ui/user-data ::view) (g/node-value :view-data) second :resource-node)) (defn- tab->view-type [^Tab tab] (some-> tab (ui/user-data ::view-type) :id)) (defn- configure-editor-tab-pane! [^TabPane tab-pane ^Scene app-scene app-view] (.setTabClosingPolicy tab-pane TabPane$TabClosingPolicy/ALL_TABS) (.setTabDragPolicy tab-pane TabPane$TabDragPolicy/REORDER) (-> tab-pane (.getSelectionModel) (.selectedItemProperty) (.addListener (reify ChangeListener (changed [_this _observable _old-val new-val] (on-selected-tab-changed! app-view app-scene (tab->resource-node new-val) (tab->view-type new-val)))))) (-> tab-pane (.getTabs) (.addListener (reify ListChangeListener (onChanged [_this _change] ;; Check if we've ended up with an empty TabPane. ;; Unless we are the only one left, we should get rid of it to make room for the other TabPane. (when (empty? (.getTabs tab-pane)) (let [editor-tabs-split ^SplitPane (ui/tab-pane-parent tab-pane) tab-panes (.getItems editor-tabs-split)] (when (< 1 (count tab-panes)) (.remove tab-panes tab-pane) (.requestFocus ^TabPane (.get tab-panes 0))))))))) (ui/register-tab-pane-context-menu tab-pane ::tab-menu)) (defn- handle-focus-owner-change! [app-view app-scene new-focus-owner] (let [old-editor-tab-pane (g/node-value app-view :active-tab-pane) new-editor-tab-pane (editor-tab-pane new-focus-owner)] (when (and (some? new-editor-tab-pane) (not (identical? old-editor-tab-pane new-editor-tab-pane))) (let [selected-tab (ui/selected-tab new-editor-tab-pane) resource-node (tab->resource-node selected-tab) view-type (tab->view-type selected-tab)] (ui/add-style! old-editor-tab-pane "inactive") (ui/remove-style! new-editor-tab-pane "inactive") (g/set-property! app-view :active-tab-pane new-editor-tab-pane) (on-selected-tab-changed! app-view app-scene resource-node view-type))))) (defn open-custom-keymap [path] (try (and (not= path "") (some-> path slurp edn/read-string)) (catch IOException e (dialogs/make-info-dialog {:title "Couldn't load custom keymap config" :icon :icon/triangle-error :header {:fx/type :v-box :children [{:fx/type fxui/label :text (str "The keymap path " path " couldn't be opened.")}]} :content (.getMessage e)}) (log/error :exception e) nil))) (defn make-app-view [view-graph project ^Stage stage ^MenuBar menu-bar ^SplitPane editor-tabs-split ^TabPane tool-tab-pane prefs] (let [app-scene (.getScene stage)] (ui/disable-menu-alt-key-mnemonic! menu-bar) (.setUseSystemMenuBar menu-bar true) (.setTitle stage (make-title)) (let [editor-tab-pane (TabPane.) keymap (or (open-custom-keymap (prefs/get-prefs prefs "custom-keymap-path" "")) keymap/default-host-key-bindings) app-view (first (g/tx-nodes-added (g/transact (g/make-node view-graph AppView :stage stage :scene app-scene :editor-tabs-split editor-tabs-split :active-tab-pane editor-tab-pane :tool-tab-pane tool-tab-pane :active-tool :move :manip-space :world :keymap-config keymap))))] (.add (.getItems editor-tabs-split) editor-tab-pane) (configure-editor-tab-pane! editor-tab-pane app-scene app-view) (ui/observe (.focusOwnerProperty app-scene) (fn [_ _ new-focus-owner] (handle-focus-owner-change! app-view app-scene new-focus-owner))) (ui/register-menubar app-scene menu-bar ::menubar) (keymap/install-key-bindings! (.getScene stage) (g/node-value app-view :keymap)) (let [refresh-timer (ui/->timer "refresh-app-view" (fn [_ _] (when-not (ui/ui-disabled?) (let [refresh-requested? (ui/user-data app-scene ::ui/refresh-requested?)] (when refresh-requested? (ui/user-data! app-scene ::ui/refresh-requested? false) (refresh-menus-and-toolbars! app-view app-scene) (refresh-views! app-view)) (refresh-scene-views! app-view) (refresh-app-title! stage project)))))] (ui/timer-stop-on-closed! stage refresh-timer) (ui/timer-start! refresh-timer)) (ui/on-closed! stage (fn [_] (dispose-scene-views! app-view))) app-view))) (defn- make-tab! [app-view prefs workspace project resource resource-node resource-type view-type make-view-fn ^ObservableList tabs opts] (let [parent (AnchorPane.) tab (doto (Tab. (tab-title resource false)) (.setContent parent) (.setTooltip (Tooltip. (or (resource/proj-path resource) "unknown"))) (ui/user-data! ::view-type view-type)) view-graph (g/make-graph! :history false :volatility 2) select-fn (partial select app-view) opts (merge opts (get (:view-opts resource-type) (:id view-type)) {:app-view app-view :select-fn select-fn :prefs prefs :project project :workspace workspace :tab tab}) view (make-view-fn view-graph parent resource-node opts)] (assert (g/node-instance? view/WorkbenchView view)) (g/transact (concat (view/connect-resource-node view resource-node) (g/connect view :view-data app-view :open-views) (g/connect view :view-dirty? app-view :open-dirty-views))) (ui/user-data! tab ::view view) (.add tabs tab) (g/transact (select app-view resource-node [resource-node])) (.setGraphic tab (icons/get-image-view (or (:icon resource-type) "icons/64/Icons_29-AT-Unknown.png") 16)) (.addAll (.getStyleClass tab) ^Collection (resource/style-classes resource)) (ui/register-tab-toolbar tab "#toolbar" :toolbar) (let [close-handler (.getOnClosed tab)] (.setOnClosed tab (ui/event-handler event ;; The menu refresh can occur after the view graph is ;; deleted but before the tab controls lose input ;; focus, causing handlers to evaluate against deleted ;; graph nodes. Using run-later here prevents this. (ui/run-later (doto tab (ui/user-data! ::view-type nil) (ui/user-data! ::view nil)) (g/delete-graph! view-graph)) (when close-handler (.handle close-handler event))))) tab)) (defn- substitute-args [tmpl args] (reduce (fn [tmpl [key val]] (string/replace tmpl (format "{%s}" (name key)) (str val))) tmpl args)) (defn open-resource ([app-view prefs workspace project resource] (open-resource app-view prefs workspace project resource {})) ([app-view prefs workspace project resource opts] (let [resource-type (resource/resource-type resource) resource-node (or (project/get-resource-node project resource) (throw (ex-info (format "No resource node found for resource '%s'" (resource/proj-path resource)) {}))) text-view-type (workspace/get-view-type workspace :text) view-type (or (:selected-view-type opts) (if (nil? resource-type) (placeholder-resource/view-type workspace) (first (:view-types resource-type))) text-view-type)] (if (resource-node/defective? resource-node) (do (dialogs/make-info-dialog {:title "Unable to Open Resource" :icon :icon/triangle-error :header (format "Unable to open '%s', since it appears damaged" (resource/proj-path resource))}) false) (if-let [custom-editor (and (#{:code :text} (:id view-type)) (let [ed-pref (some-> (prefs/get-prefs prefs "code-custom-editor" "") string/trim)] (and (not (string/blank? ed-pref)) ed-pref)))] (let [cursor-range (:cursor-range opts) arg-tmpl (string/trim (if cursor-range (prefs/get-prefs prefs "code-open-file-at-line" "{file}:{line}") (prefs/get-prefs prefs "code-open-file" "{file}"))) arg-sub (cond-> {:file (resource/abs-path resource)} cursor-range (assoc :line (CursorRange->line-number cursor-range))) args (->> (string/split arg-tmpl #" ") (map #(substitute-args % arg-sub)))] (doto (ProcessBuilder. ^List (cons custom-editor args)) (.directory (workspace/project-path workspace)) (.start)) false) (if (contains? view-type :make-view-fn) (let [^SplitPane editor-tabs-split (g/node-value app-view :editor-tabs-split) tab-panes (.getItems editor-tabs-split) open-tabs (mapcat #(.getTabs ^TabPane %) tab-panes) view-type (if (g/node-value resource-node :editable?) view-type text-view-type) make-view-fn (:make-view-fn view-type) ^Tab tab (or (some #(when (and (= (tab->resource-node %) resource-node) (= view-type (ui/user-data % ::view-type))) %) open-tabs) (let [^TabPane active-tab-pane (g/node-value app-view :active-tab-pane) active-tab-pane-tabs (.getTabs active-tab-pane)] (make-tab! app-view prefs workspace project resource resource-node resource-type view-type make-view-fn active-tab-pane-tabs opts)))] (.select (.getSelectionModel (.getTabPane tab)) tab) (when-let [focus (:focus-fn view-type)] ;; Force layout pass since the focus function of some views ;; needs proper width + height (f.i. code view for ;; scrolling to selected line). (NodeHelper/layoutNodeForPrinting (.getRoot ^Scene (g/node-value app-view :scene))) (focus (ui/user-data tab ::view) opts)) ;; Do an initial rendering so it shows up as fast as possible. (ui/run-later (refresh-scene-views! app-view) (ui/run-later (slog/smoke-log "opened-resource"))) true) (let [^String path (or (resource/abs-path resource) (resource/temp-path resource)) ^File f (File. path)] (ui/open-file f (fn [msg] (ui/run-later (dialogs/make-info-dialog {:title "Could Not Open File" :icon :icon/triangle-error :header (format "Could not open '%s'" (.getName f)) :content (str "This can happen if the file type is not mapped to an application in your OS.\n\nUnderlying error from the OS:\n" msg)})))) false))))))) (handler/defhandler :open :global (active? [selection user-data] (:resources user-data (not-empty (selection->openable-resources selection)))) (enabled? [selection user-data] (some resource/exists? (:resources user-data (selection->openable-resources selection)))) (run [selection app-view prefs workspace project user-data] (doseq [resource (filter resource/exists? (:resources user-data (selection->openable-resources selection)))] (open-resource app-view prefs workspace project resource)))) (handler/defhandler :open-as :global (active? [selection] (selection->single-openable-resource selection)) (enabled? [selection user-data] (resource/exists? (selection->single-openable-resource selection))) (run [selection app-view prefs workspace project user-data] (let [resource (selection->single-openable-resource selection)] (open-resource app-view prefs workspace project resource (when-let [view-type (:selected-view-type user-data)] {:selected-view-type view-type})))) (options [workspace selection user-data] (when-not user-data (let [resource (selection->single-openable-resource selection) resource-type (resource/resource-type resource)] (map (fn [vt] {:label (or (:label vt) "External Editor") :command :open-as :user-data {:selected-view-type vt}}) (:view-types resource-type)))))) (handler/defhandler :synchronize :global (enabled? [] (disk-availability/available?)) (run [changes-view project workspace app-view] (let [render-reload-progress! (make-render-task-progress :resource-sync) render-save-progress! (make-render-task-progress :save-all)] (if (changes-view/project-is-git-repo? changes-view) ;; The project is a Git repo. ;; Check if there are locked files below the project folder before proceeding. ;; If so, we abort the sync and notify the user, since this could cause problems. (when (changes-view/ensure-no-locked-files! changes-view) (disk/async-save! render-reload-progress! render-save-progress! project changes-view (fn [successful?] (when successful? (ui/user-data! (g/node-value app-view :scene) ::ui/refresh-requested? true) (when (changes-view/regular-sync! changes-view) (disk/async-reload! render-reload-progress! workspace [] changes-view)))))) ;; The project is not a Git repo. ;; Show a dialog with info about how to set this up. (dialogs/make-info-dialog {:title "Version Control" :size :default :icon :icon/git :header "This project does not use Version Control" :content {:fx/type :text-flow :style-class "dialog-content-padding" :children [{:fx/type :text :text (str "A project under Version Control " "keeps a history of changes and " "enables you to collaborate with " "others by pushing changes to a " "server.\n\nYou can read about " "how to configure Version Control " "in the ")} {:fx/type :hyperlink :text "Defold Manual" :on-action (fn [_] (ui/open-url "https://www.defold.com/manuals/version-control/"))} {:fx/type :text :text "."}]}}))))) (handler/defhandler :save-all :global (enabled? [] (not (bob/build-in-progress?))) (run [app-view changes-view project] (let [render-reload-progress! (make-render-task-progress :resource-sync) render-save-progress! (make-render-task-progress :save-all)] (disk/async-save! render-reload-progress! render-save-progress! project changes-view (fn [successful?] (when successful? (ui/user-data! (g/node-value app-view :scene) ::ui/refresh-requested? true))))))) (handler/defhandler :show-in-desktop :global (active? [app-view selection evaluation-context] (context-resource app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource app-view selection evaluation-context)] (and (resource/abs-path r) (or (resource/exists? r) (empty? (resource/path r)))))) (run [app-view selection] (when-let [r (context-resource app-view selection)] (let [f (File. (resource/abs-path r))] (ui/open-file (fs/to-folder f)))))) (handler/defhandler :referencing-files :global (active? [app-view selection evaluation-context] (context-resource-file app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/abs-path r) (resource/exists? r)))) (run [selection app-view prefs workspace project] (when-let [r (context-resource-file app-view selection)] (doseq [resource (dialogs/make-resource-dialog workspace project {:title "Referencing Files" :selection :multiple :ok-label "Open" :filter (format "refs:%s" (resource/proj-path r))})] (open-resource app-view prefs workspace project resource))))) (handler/defhandler :dependencies :global (active? [app-view selection evaluation-context] (context-resource-file app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/abs-path r) (resource/exists? r)))) (run [selection app-view prefs workspace project] (when-let [r (context-resource-file app-view selection)] (doseq [resource (dialogs/make-resource-dialog workspace project {:title "Dependencies" :selection :multiple :ok-label "Open" :filter (format "deps:%s" (resource/proj-path r))})] (open-resource app-view prefs workspace project resource))))) (handler/defhandler :toggle-pane-left :global (run [^Stage main-stage] (let [main-scene (.getScene main-stage)] (set-pane-visible! main-scene :left (not (pane-visible? main-scene :left)))))) (handler/defhandler :toggle-pane-right :global (run [^Stage main-stage] (let [main-scene (.getScene main-stage)] (set-pane-visible! main-scene :right (not (pane-visible? main-scene :right)))))) (handler/defhandler :toggle-pane-bottom :global (run [^Stage main-stage] (let [main-scene (.getScene main-stage)] (set-pane-visible! main-scene :bottom (not (pane-visible? main-scene :bottom)))))) (handler/defhandler :show-console :global (run [^Stage main-stage tool-tab-pane] (show-console! (.getScene main-stage) tool-tab-pane))) (handler/defhandler :show-curve-editor :global (run [^Stage main-stage tool-tab-pane] (show-curve-editor! (.getScene main-stage) tool-tab-pane))) (handler/defhandler :show-build-errors :global (run [^Stage main-stage tool-tab-pane] (show-build-errors! (.getScene main-stage) tool-tab-pane))) (handler/defhandler :show-search-results :global (run [^Stage main-stage tool-tab-pane] (show-search-results! (.getScene main-stage) tool-tab-pane))) (defn- put-on-clipboard! [s] (doto (Clipboard/getSystemClipboard) (.setContent (doto (ClipboardContent.) (.putString s))))) (handler/defhandler :copy-project-path :global (active? [app-view selection evaluation-context] (context-resource-file app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/proj-path r) (resource/exists? r)))) (run [selection app-view] (when-let [r (context-resource-file app-view selection)] (put-on-clipboard! (resource/proj-path r))))) (handler/defhandler :copy-full-path :global (active? [app-view selection evaluation-context] (context-resource-file app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/abs-path r) (resource/exists? r)))) (run [selection app-view] (when-let [r (context-resource-file app-view selection)] (put-on-clipboard! (resource/abs-path r))))) (handler/defhandler :copy-require-path :global (active? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (= "lua" (resource/type-ext r)))) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/proj-path r) (resource/exists? r)))) (run [selection app-view] (when-let [r (context-resource-file app-view selection)] (put-on-clipboard! (lua/path->lua-module (resource/proj-path r)))))) (defn- gen-tooltip [workspace project app-view resource] (let [resource-type (resource/resource-type resource) view-type (or (first (:view-types resource-type)) (workspace/get-view-type workspace :text))] (when-let [make-preview-fn (:make-preview-fn view-type)] (let [tooltip (Tooltip.)] (doto tooltip (.setGraphic (doto (ImageView.) (.setScaleY -1.0))) (.setOnShowing (ui/event-handler e (let [image-view ^ImageView (.getGraphic tooltip)] (when-not (.getImage image-view) (let [resource-node (project/get-resource-node project resource) view-graph (g/make-graph! :history false :volatility 2) select-fn (partial select app-view) opts (assoc ((:id view-type) (:view-opts resource-type)) :app-view app-view :select-fn select-fn :project project :workspace workspace) preview (make-preview-fn view-graph resource-node opts 256 256)] (.setImage image-view ^Image (g/node-value preview :image)) (when-some [dispose-preview-fn (:dispose-preview-fn view-type)] (dispose-preview-fn preview)) (g/delete-graph! view-graph))))))))))) (def ^:private open-assets-term-prefs-key "<KEY>") (defn- query-and-open! [workspace project app-view prefs term] (let [prev-filter-term (prefs/get-prefs prefs open-assets-term-prefs-key nil) filter-term-atom (atom prev-filter-term) selected-resources (dialogs/make-resource-dialog workspace project (cond-> {:title "Open Assets" :accept-fn resource/editable-resource? :selection :multiple :ok-label "Open" :filter-atom filter-term-atom :tooltip-gen (partial gen-tooltip workspace project app-view)} (some? term) (assoc :filter term))) filter-term @filter-term-atom] (when (not= prev-filter-term filter-term) (prefs/set-prefs prefs open-assets-term-prefs-key filter-term)) (doseq [resource selected-resources] (open-resource app-view prefs workspace project resource)))) (handler/defhandler :select-items :global (run [user-data] (dialogs/make-select-list-dialog (:items user-data) (:options user-data)))) (defn- get-view-text-selection [{:keys [view-id view-type]}] (when-let [text-selection-fn (:text-selection-fn view-type)] (text-selection-fn view-id))) (handler/defhandler :open-asset :global (run [workspace project app-view prefs] (let [term (get-view-text-selection (g/node-value app-view :active-view-info))] (query-and-open! workspace project app-view prefs term)))) (handler/defhandler :search-in-files :global (run [project app-view prefs search-results-view main-stage tool-tab-pane] (when-let [term (get-view-text-selection (g/node-value app-view :active-view-info))] (search-results-view/set-search-term! prefs term)) (let [main-scene (.getScene ^Stage main-stage) show-search-results-tab! (partial show-search-results! main-scene tool-tab-pane)] (search-results-view/show-search-in-files-dialog! search-results-view project prefs show-search-results-tab!)))) (defn- bundle! [main-stage tool-tab-pane changes-view build-errors-view project prefs platform bundle-options] (g/user-data! project :last-bundle-options (assoc bundle-options :platform-key platform)) (let [main-scene (.getScene ^Stage main-stage) output-directory ^File (:output-directory bundle-options) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view) render-reload-progress! (make-render-task-progress :resource-sync) render-save-progress! (make-render-task-progress :save-all) render-build-progress! (make-render-task-progress :build) task-cancelled? (make-task-cancelled-query :build) bob-args (bob/bundle-bob-args prefs platform bundle-options)] (when-not (.exists output-directory) (fs/create-directories! output-directory)) (build-errors-view/clear-build-errors build-errors-view) (disk/async-bob-build! render-reload-progress! render-save-progress! render-build-progress! task-cancelled? render-build-error! bob/bundle-bob-commands bob-args project changes-view (fn [successful?] (when successful? (if (some-> output-directory .isDirectory) (ui/open-file output-directory) (dialogs/make-info-dialog {:title "Bundle Failed" :icon :icon/triangle-error :size :large :header "Failed to bundle project, please fix build errors and try again"}))))))) (handler/defhandler :bundle :global (run [user-data workspace project prefs app-view changes-view build-errors-view main-stage tool-tab-pane] (let [owner-window (g/node-value app-view :stage) platform (:platform user-data) bundle! (partial bundle! main-stage tool-tab-pane changes-view build-errors-view project prefs platform)] (bundle-dialog/show-bundle-dialog! workspace platform prefs owner-window bundle!)))) (handler/defhandler :rebundle :global (enabled? [project] (some? (g/user-data project :last-bundle-options))) (run [workspace project prefs app-view changes-view build-errors-view main-stage tool-tab-pane] (let [last-bundle-options (g/user-data project :last-bundle-options) platform (:platform-key last-bundle-options)] (bundle! main-stage tool-tab-pane changes-view build-errors-view project prefs platform last-bundle-options)))) (def ^:private editor-extensions-allowed-commands-prefs-key "editor-extensions/allowed-commands") (defn make-extensions-ui [workspace changes-view prefs] (reify extensions/UI (reload-resources! [_] (let [success-promise (promise)] (disk/async-reload! (make-render-task-progress :resource-sync) workspace [] changes-view success-promise) (when-not @success-promise (throw (ex-info "Reload failed" {}))))) (can-execute? [_ [cmd-name :as command]] (let [allowed-commands (prefs/get-prefs prefs editor-extensions-allowed-commands-prefs-key #{})] (if (allowed-commands cmd-name) true (let [allow (ui/run-now (dialogs/make-confirmation-dialog {:title "Allow executing shell command?" :icon {:fx/type fxui/icon :type :icon/triangle-error :fill "#fa6731"} :header "Extension wants to execute a shell command" :content {:fx/type fxui/label :style-class "dialog-content-padding" :text (string/join " " command)} :buttons [{:text "Abort Command" :cancel-button true :default-button true :result false} {:text "Allow" :variant :danger :result true}]}))] (when allow (prefs/set-prefs prefs editor-extensions-allowed-commands-prefs-key (conj allowed-commands cmd-name))) allow)))) (display-output! [_ type string] (let [[console-type prefix] (case type :err [:extension-err "ERROR:EXT: "] :out [:extension-out ""])] (doseq [line (string/split-lines string)] (console/append-console-entry! console-type (str prefix line))))) (on-transact-thread [_ f] (ui/run-now (f))))) (defn- fetch-libraries [workspace project changes-view prefs] (let [library-uris (project/project-dependencies project) hosts (into #{} (map url/strip-path) library-uris)] (if-let [first-unreachable-host (first-where (complement url/reachable?) hosts)] (dialogs/make-info-dialog {:title "Fetch Failed" :icon :icon/triangle-error :size :large :header "Fetch was aborted because a host could not be reached" :content (str "Unreachable host: " first-unreachable-host "\n\nPlease verify internet connection and try again.")}) (future (error-reporting/catch-all! (ui/with-progress [render-fetch-progress! (make-render-task-progress :fetch-libraries)] (when (workspace/dependencies-reachable? library-uris) (let [lib-states (workspace/fetch-and-validate-libraries workspace library-uris render-fetch-progress!) render-install-progress! (make-render-task-progress :resource-sync)] (render-install-progress! (progress/make "Installing updated libraries...")) (ui/run-later (workspace/install-validated-libraries! workspace library-uris lib-states) (disk/async-reload! render-install-progress! workspace [] changes-view (fn [success] (when success (extensions/reload! project :library (make-extensions-ui workspace changes-view prefs)))))))))))))) (handler/defhandler :add-dependency :global (enabled? [] (disk-availability/available?)) (run [selection app-view prefs workspace project changes-view user-data] (let [game-project (project/get-resource-node project "/game.project") dependencies (game-project/get-setting game-project ["project" "dependencies"]) dependency-uri (.toURI (URL. (:dep-url user-data)))] (when (not-any? (partial = dependency-uri) dependencies) (game-project/set-setting! game-project ["project" "dependencies"] (conj (vec dependencies) dependency-uri)) (fetch-libraries workspace project changes-view prefs))))) (handler/defhandler :fetch-libraries :global (enabled? [] (disk-availability/available?)) (run [workspace project changes-view prefs] (fetch-libraries workspace project changes-view prefs))) (handler/defhandler :reload-extensions :global (enabled? [] (disk-availability/available?)) (run [project workspace changes-view prefs] (extensions/reload! project :all (make-extensions-ui workspace changes-view prefs)))) (defn- create-and-open-live-update-settings! [app-view changes-view prefs project] (let [workspace (project/workspace project) project-path (workspace/project-path workspace) settings-file (io/file project-path "liveupdate.settings") render-reload-progress! (make-render-task-progress :resource-sync)] (spit settings-file "[liveupdate]\n") (disk/async-reload! render-reload-progress! workspace [] changes-view (fn [successful?] (when successful? (when-some [created-resource (workspace/find-resource workspace "/liveupdate.settings")] (open-resource app-view prefs workspace project created-resource))))))) (handler/defhandler :live-update-settings :global (enabled? [] (disk-availability/available?)) (run [app-view changes-view prefs workspace project] (if-some [existing-resource (workspace/find-resource workspace (live-update-settings/get-live-update-settings-path project))] (open-resource app-view prefs workspace project existing-resource) (create-and-open-live-update-settings! app-view changes-view prefs project)))) (handler/defhandler :sign-ios-app :global (active? [] (util/is-mac-os?)) (run [workspace project prefs build-errors-view main-stage tool-tab-pane] (build-errors-view/clear-build-errors build-errors-view) (let [result (bundle/make-sign-dialog workspace prefs project)] (when-let [error (:error result)] (g/with-auto-evaluation-context evaluation-context (let [main-scene (.getScene ^Stage main-stage) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view)] (if (engine-build-errors/handle-build-error! render-build-error! project evaluation-context error) (dialogs/make-info-dialog {:title "Build Failed" :icon :icon/triangle-error :header "Failed to build ipa with native extensions, please fix build errors and try again"}) (do (error-reporting/report-exception! error) (when-let [message (:message result)] (dialogs/make-info-dialog {:title "Error" :icon :icon/triangle-error :header message}))))))))))
true
;; Copyright 2020 The Defold Foundation ;; 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.app-view (:require [clojure.java.io :as io] [clojure.edn :as edn] [clojure.string :as string] [dynamo.graph :as g] [editor.build :as build] [editor.build-errors-view :as build-errors-view] [editor.bundle :as bundle] [editor.bundle-dialog :as bundle-dialog] [editor.changes-view :as changes-view] [editor.code.data :refer [CursorRange->line-number]] [editor.console :as console] [editor.debug-view :as debug-view] [editor.defold-project :as project] [editor.dialogs :as dialogs] [editor.disk :as disk] [editor.disk-availability :as disk-availability] [editor.editor-extensions :as extensions] [editor.engine :as engine] [editor.engine.build-errors :as engine-build-errors] [editor.error-reporting :as error-reporting] [editor.fs :as fs] [editor.fxui :as fxui] [editor.game-project :as game-project] [editor.github :as github] [editor.graph-util :as gu] [editor.handler :as handler] [editor.hot-reload :as hot-reload] [editor.icons :as icons] [editor.keymap :as keymap] [editor.live-update-settings :as live-update-settings] [editor.lua :as lua] [editor.pipeline :as pipeline] [editor.pipeline.bob :as bob] [editor.placeholder-resource :as placeholder-resource] [editor.prefs :as prefs] [editor.prefs-dialog :as prefs-dialog] [editor.process :as process] [editor.progress :as progress] [editor.resource :as resource] [editor.resource-node :as resource-node] [editor.scene :as scene] [editor.scene-cache :as scene-cache] [editor.scene-visibility :as scene-visibility] [editor.search-results-view :as search-results-view] [editor.system :as system] [editor.targets :as targets] [editor.types :as types] [editor.ui :as ui] [editor.url :as url] [editor.util :as util] [editor.view :as view] [editor.workspace :as workspace] [internal.util :refer [first-where]] [service.log :as log] [util.http-server :as http-server] [util.profiler :as profiler] [util.thread-util :as thread-util] [service.smoke-log :as slog]) (:import [com.defold.editor Editor] [com.defold.editor UIUtil] [com.sun.javafx.scene NodeHelper] [java.io BufferedReader File IOException] [java.net URL] [java.util Collection List] [javafx.beans.value ChangeListener] [javafx.collections ListChangeListener ObservableList] [javafx.event Event] [javafx.geometry Orientation] [javafx.scene Parent Scene] [javafx.scene.control MenuBar SplitPane Tab TabPane TabPane$TabClosingPolicy TabPane$TabDragPolicy Tooltip] [javafx.scene.image Image ImageView] [javafx.scene.input Clipboard ClipboardContent] [javafx.scene.layout AnchorPane StackPane] [javafx.scene.shape Ellipse SVGPath] [javafx.stage Screen Stage WindowEvent])) (set! *warn-on-reflection* true) (def ^:private split-info-by-pane-kw {:left {:index 0 :pane-id "left-pane" :split-id "main-split"} :right {:index 1 :pane-id "right-pane" :split-id "workbench-split"} :bottom {:index 1 :pane-id "bottom-pane" :split-id "center-split"}}) (defn- pane-visible? [^Scene main-scene pane-kw] (let [{:keys [pane-id split-id]} (split-info-by-pane-kw pane-kw)] (some? (.lookup main-scene (str "#" split-id " #" pane-id))))) (defn- split-pane-length ^double [^SplitPane split-pane] (condp = (.getOrientation split-pane) Orientation/HORIZONTAL (.getWidth split-pane) Orientation/VERTICAL (.getHeight split-pane))) (defn- set-pane-visible! [^Scene main-scene pane-kw visible?] (let [{:keys [index pane-id split-id]} (split-info-by-pane-kw pane-kw) ^SplitPane split (.lookup main-scene (str "#" split-id)) ^Parent pane (.lookup split (str "#" pane-id))] (cond (and (nil? pane) visible?) (let [user-data-key (keyword "PI:KEY:<KEY>END_PI" pane-PI:KEY:<KEY>END_PI) {:keys [pane size]} (ui/user-data split user-data-key) divider-index (max 0 (dec index)) divider-position (max 0.0 (min (if (zero? index) (/ size (split-pane-length split)) (- 1.0 (/ size (split-pane-length split)))) 1.0))] (ui/user-data! split user-data-key nil) (.add (.getItems split) index pane) (.setDividerPosition split divider-index divider-position) (.layout split)) (and (some? pane) (not visible?)) (let [user-data-key (keyword "PI:KEY:<KEY>END_PI" pane-PI:KEY:<KEY>END_PI) divider-index (max 0 (dec index)) divider-position (get (.getDividerPositions split) divider-index) size (if (zero? index) (Math/floor (* divider-position (split-pane-length split))) (Math/ceil (* (- 1.0 divider-position) (split-pane-length split)))) removing-focus-owner? (some? (when-some [focus-owner (.getFocusOwner main-scene)] (ui/closest-node-where (partial identical? pane) focus-owner)))] (ui/user-data! split user-data-key {:pane pane :size size}) (.remove (.getItems split) pane) (.layout split) ;; If this action causes the focus owner to be removed from the scene, ;; move focus to the SplitPane. This ensures we have a valid UI context ;; when refreshing the menus. (when removing-focus-owner? (.requestFocus split)))) nil)) (defn- select-tool-tab! [tab-id ^Scene main-scene ^TabPane tool-tab-pane] (let [tabs (.getTabs tool-tab-pane) tab-index (first (keep-indexed (fn [i ^Tab tab] (when (= tab-id (.getId tab)) i)) tabs))] (set-pane-visible! main-scene :bottom true) (if (some? tab-index) (.select (.getSelectionModel tool-tab-pane) ^long tab-index) (throw (ex-info (str "Tab id not found: " tab-id) {:tab-id tab-id :tab-ids (mapv #(.getId ^Tab %) tabs)}))))) (def show-console! (partial select-tool-tab! "console-tab")) (def show-curve-editor! (partial select-tool-tab! "curve-editor-tab")) (def show-build-errors! (partial select-tool-tab! "build-errors-tab")) (def show-search-results! (partial select-tool-tab! "search-results-tab")) (defn show-asset-browser! [main-scene] (set-pane-visible! main-scene :left true)) (defn- show-debugger! [main-scene tool-tab-pane] ;; In addition to the controls in the console pane, ;; the right pane is used to display locals. (set-pane-visible! main-scene :right true) (show-console! main-scene tool-tab-pane)) (defn debugger-state-changed! [main-scene tool-tab-pane attention?] (ui/invalidate-menubar-item! ::debug-view/debug) (ui/user-data! main-scene ::ui/refresh-requested? true) (when attention? (show-debugger! main-scene tool-tab-pane))) (defn- fire-tab-closed-event! [^Tab tab] ;; TODO: Workaround as there's currently no API to close tabs programatically with identical semantics to close manually ;; See http://stackoverflow.com/questions/17047000/javafx-closing-a-tab-in-tabpane-dynamically (Event/fireEvent tab (Event. Tab/CLOSED_EVENT))) (defn- remove-tab! [^TabPane tab-pane ^Tab tab] (fire-tab-closed-event! tab) (.remove (.getTabs tab-pane) tab)) (defn remove-invalid-tabs! [tab-panes open-views] (let [invalid-tab? (fn [tab] (nil? (get open-views (ui/user-data tab ::view)))) closed-tabs-by-tab-pane (into [] (keep (fn [^TabPane tab-pane] (when-some [closed-tabs (not-empty (filterv invalid-tab? (.getTabs tab-pane)))] [tab-pane closed-tabs]))) tab-panes)] ;; We must remove all invalid tabs from a TabPane in one go to ensure ;; the selected tab change event does not trigger onto an invalid tab. (when (seq closed-tabs-by-tab-pane) (doseq [[^TabPane tab-pane ^Collection closed-tabs] closed-tabs-by-tab-pane] (doseq [tab closed-tabs] (fire-tab-closed-event! tab)) (.removeAll (.getTabs tab-pane) closed-tabs))))) (defn- tab-title ^String [resource is-dirty] ;; Lone underscores are treated as mnemonic letter signifiers in the overflow ;; dropdown menu, and we cannot disable mnemonic parsing for it since the ;; control is internal. We also cannot replace them with double underscores to ;; escape them, as they will show up in the Tab labels and there appears to be ;; no way to enable mnemonic parsing for them. Attempts were made to call ;; setMnemonicParsing on the parent Labelled as the Tab graphic was added to ;; the DOM, but this only worked on macOS. As a workaround, we instead replace ;; underscores with the a unicode character that looks somewhat similar. (let [resource-name (resource/resource-name resource) escaped-resource-name (string/replace resource-name "_" "\u02CD")] (if is-dirty (str "*" escaped-resource-name) escaped-resource-name))) (g/defnode AppView (property stage Stage) (property scene Scene) (property editor-tabs-split SplitPane) (property active-tab-pane TabPane) (property tool-tab-pane TabPane) (property auto-pulls g/Any) (property active-tool g/Keyword) (property manip-space g/Keyword) (property keymap-config g/Any) (input open-views g/Any :array) (input open-dirty-views g/Any :array) (input scene-view-ids g/Any :array) (input hidden-renderable-tags types/RenderableTags) (input hidden-node-outline-key-paths types/NodeOutlineKeyPaths) (input active-outline g/Any) (input active-scene g/Any) (input project-id g/NodeID) (input selected-node-ids-by-resource-node g/Any) (input selected-node-properties-by-resource-node g/Any) (input sub-selections-by-resource-node g/Any) (input debugger-execution-locations g/Any) (output open-views g/Any :cached (g/fnk [open-views] (into {} open-views))) (output open-dirty-views g/Any :cached (g/fnk [open-dirty-views] (into #{} (keep #(when (second %) (first %))) open-dirty-views))) (output active-tab Tab (g/fnk [^TabPane active-tab-pane] (some-> active-tab-pane ui/selected-tab))) (output hidden-renderable-tags types/RenderableTags (gu/passthrough hidden-renderable-tags)) (output hidden-node-outline-key-paths types/NodeOutlineKeyPaths (gu/passthrough hidden-node-outline-key-paths)) (output active-outline g/Any (gu/passthrough active-outline)) (output active-scene g/Any (gu/passthrough active-scene)) (output active-view g/NodeID (g/fnk [^Tab active-tab] (when active-tab (ui/user-data active-tab ::view)))) (output active-view-info g/Any (g/fnk [^Tab active-tab] (when active-tab {:view-id (ui/user-data active-tab ::view) :view-type (ui/user-data active-tab ::view-type)}))) (output active-resource-node g/NodeID :cached (g/fnk [active-view open-views] (:resource-node (get open-views active-view)))) (output active-resource resource/Resource :cached (g/fnk [active-view open-views] (:resource (get open-views active-view)))) (output open-resource-nodes g/Any :cached (g/fnk [open-views] (->> open-views vals (map :resource-node)))) (output selected-node-ids g/Any (g/fnk [selected-node-ids-by-resource-node active-resource-node] (get selected-node-ids-by-resource-node active-resource-node))) (output selected-node-properties g/Any (g/fnk [selected-node-properties-by-resource-node active-resource-node] (get selected-node-properties-by-resource-node active-resource-node))) (output sub-selection g/Any (g/fnk [sub-selections-by-resource-node active-resource-node] (get sub-selections-by-resource-node active-resource-node))) (output refresh-tab-panes g/Any :cached (g/fnk [^SplitPane editor-tabs-split open-views open-dirty-views] (let [tab-panes (.getItems editor-tabs-split)] (doseq [^TabPane tab-pane tab-panes ^Tab tab (.getTabs tab-pane) :let [view (ui/user-data tab ::view) resource (:resource (get open-views view)) is-dirty (contains? open-dirty-views view) title (tab-title resource is-dirty)]] (ui/text! tab title))))) (output keymap g/Any :cached (g/fnk [keymap-config] (keymap/make-keymap keymap-config {:valid-command? (set (handler/available-commands))}))) (output debugger-execution-locations g/Any (gu/passthrough debugger-execution-locations))) (defn- selection->openable-resources [selection] (when-let [resources (handler/adapt-every selection resource/Resource)] (filterv resource/openable-resource? resources))) (defn- selection->single-openable-resource [selection] (when-let [r (handler/adapt-single selection resource/Resource)] (when (resource/openable-resource? r) r))) (defn- selection->single-resource [selection] (handler/adapt-single selection resource/Resource)) (defn- context-resource-file ([app-view selection] (g/with-auto-evaluation-context evaluation-context (context-resource-file app-view selection evaluation-context))) ([app-view selection evaluation-context] (or (selection->single-openable-resource selection) (g/node-value app-view :active-resource evaluation-context)))) (defn- context-resource ([app-view selection] (g/with-auto-evaluation-context evaluation-context (context-resource app-view selection evaluation-context))) ([app-view selection evaluation-context] (or (selection->single-resource selection) (g/node-value app-view :active-resource evaluation-context)))) (defn- disconnect-sources [target-node target-label] (for [[source-node source-label] (g/sources-of target-node target-label)] (g/disconnect source-node source-label target-node target-label))) (defn- replace-connection [source-node source-label target-node target-label] (concat (disconnect-sources target-node target-label) (if (and source-node (contains? (-> source-node g/node-type* g/output-labels) source-label)) (g/connect source-node source-label target-node target-label) []))) (defn- on-selected-tab-changed! [app-view app-scene resource-node view-type] (g/transact (concat (replace-connection resource-node :node-outline app-view :active-outline) (if (= :scene view-type) (replace-connection resource-node :scene app-view :active-scene) (disconnect-sources app-view :active-scene)))) (g/invalidate-outputs! [[app-view :active-tab]]) (ui/user-data! app-scene ::ui/refresh-requested? true)) (handler/defhandler :move-tool :workbench (enabled? [app-view] true) (run [app-view] (g/transact (g/set-property app-view :active-tool :move))) (state [app-view] (= (g/node-value app-view :active-tool) :move))) (handler/defhandler :scale-tool :workbench (enabled? [app-view] true) (run [app-view] (g/transact (g/set-property app-view :active-tool :scale))) (state [app-view] (= (g/node-value app-view :active-tool) :scale))) (handler/defhandler :rotate-tool :workbench (enabled? [app-view] true) (run [app-view] (g/transact (g/set-property app-view :active-tool :rotate))) (state [app-view] (= (g/node-value app-view :active-tool) :rotate))) (handler/defhandler :show-visibility-settings :workbench (run [app-view scene-visibility] (when-let [btn (some-> ^TabPane (g/node-value app-view :active-tab-pane) (ui/selected-tab) (.. getContent (lookup "#show-visibility-settings")))] (scene-visibility/show-visibility-settings! btn scene-visibility))) (state [app-view scene-visibility] (when-let [btn (some-> ^TabPane (g/node-value app-view :active-tab-pane) (ui/selected-tab) (.. getContent (lookup "#show-visibility-settings")))] ;; TODO: We have no mechanism for updating the style nor icon on ;; on the toolbar button. For now we piggyback on the state ;; update polling to set a style when the filters are active. (if (scene-visibility/filters-appear-active? scene-visibility) (ui/add-style! btn "filters-active") (ui/remove-style! btn "filters-active")) (scene-visibility/settings-visible? btn)))) (def ^:private eye-icon-svg-path (ui/load-svg-path "scene/images/eye_icon_eye_arrow.svg")) (def ^:private perspective-icon-svg-path (ui/load-svg-path "scene/images/perspective_icon.svg")) (defn make-svg-icon-graphic ^SVGPath [^SVGPath icon-template] (doto (SVGPath.) (.setContent (.getContent icon-template)))) (defn- make-visibility-settings-graphic [] (doto (StackPane.) (ui/children! [(doto (make-svg-icon-graphic eye-icon-svg-path) (.setId "eye-icon")) (doto (Ellipse. 3.0 3.0) (.setId "active-indicator"))]))) (handler/register-menu! :toolbar [{:id :select :icon "icons/45/Icons_T_01_Select.png" :command :select-tool} {:id :move :icon "icons/45/Icons_T_02_Move.png" :command :move-tool} {:id :rotate :icon "icons/45/Icons_T_03_Rotate.png" :command :rotate-tool} {:id :scale :icon "icons/45/Icons_T_04_Scale.png" :command :scale-tool} {:id :perspective-camera :graphic-fn (partial make-svg-icon-graphic perspective-icon-svg-path) :command :toggle-perspective-camera} {:id :visibility-settings :graphic-fn make-visibility-settings-graphic :command :show-visibility-settings}]) (def ^:const prefs-window-dimensions "window-dimensions") (def ^:const prefs-split-positions "split-positions") (def ^:const prefs-hidden-panes "hidden-panes") (handler/defhandler :quit :global (enabled? [] true) (run [] (let [^Stage main-stage (ui/main-stage)] (.fireEvent main-stage (WindowEvent. main-stage WindowEvent/WINDOW_CLOSE_REQUEST))))) (defn store-window-dimensions [^Stage stage prefs] (let [dims {:x (.getX stage) :y (.getY stage) :width (.getWidth stage) :height (.getHeight stage) :maximized (.isMaximized stage) :full-screen (.isFullScreen stage)}] (prefs/set-prefs prefs prefs-window-dimensions dims))) (defn restore-window-dimensions [^Stage stage prefs] (when-let [dims (prefs/get-prefs prefs prefs-window-dimensions nil)] (let [{:keys [x y width height maximized full-screen]} dims maximized (and maximized (not system/mac?))] ; Maximized is not really a thing on macOS, and if set, cannot become false. (when (and (number? x) (number? y) (number? width) (number? height)) (when-let [_ (seq (Screen/getScreensForRectangle x y width height))] (doto stage (.setX x) (.setY y)) ;; Maximized and setWidth/setHeight in combination triggers a bug on macOS where the window becomes invisible (when (and (not maximized) (not full-screen)) (doto stage (.setWidth width) (.setHeight height))))) (when maximized (.setMaximized stage true)) (when full-screen (.setFullScreen stage true))))) (def ^:private legacy-split-ids ["main-split" "center-split" "right-split" "assets-split"]) (def ^:private split-ids ["main-split" "workbench-split" "center-split" "right-split" "assets-split"]) (defn- existing-split-panes [^Scene scene] (into {} (keep (fn [split-id] (when-some [control (.lookup scene (str "#" split-id))] [(keyword split-id) control]))) split-ids)) (defn- stored-split-positions [prefs] (if-some [split-positions (prefs/get-prefs prefs prefs-split-positions nil)] (if (vector? split-positions) ; Legacy preference format (zipmap (map keyword legacy-split-ids) split-positions) split-positions) {})) (defn store-split-positions! [^Scene scene prefs] (let [split-positions (into (stored-split-positions prefs) (map (fn [[id ^SplitPane sp]] [id (.getDividerPositions sp)])) (existing-split-panes scene))] (prefs/set-prefs prefs prefs-split-positions split-positions))) (defn restore-split-positions! [^Scene scene prefs] (let [split-positions (stored-split-positions prefs) split-panes (existing-split-panes scene)] (doseq [[id positions] split-positions] (when-some [^SplitPane split-pane (get split-panes id)] (.setDividerPositions split-pane (double-array positions)) (.layout split-pane))))) (defn stored-hidden-panes [prefs] (prefs/get-prefs prefs prefs-hidden-panes #{})) (defn store-hidden-panes! [^Scene scene prefs] (let [hidden-panes (into #{} (remove (partial pane-visible? scene)) (keys split-info-by-pane-kw))] (prefs/set-prefs prefs prefs-hidden-panes hidden-panes))) (defn restore-hidden-panes! [^Scene scene prefs] (let [hidden-panes (stored-hidden-panes prefs)] (doseq [pane-kw hidden-panes] (set-pane-visible! scene pane-kw false)))) (handler/defhandler :preferences :global (run [workspace prefs] (prefs-dialog/open-prefs prefs) (workspace/update-build-settings! workspace prefs))) (defn- collect-resources [{:keys [children] :as resource}] (if (empty? children) #{resource} (set (concat [resource] (mapcat collect-resources children))))) (defn- get-active-tabs [app-view evaluation-context] (let [tab-pane ^TabPane (g/node-value app-view :active-tab-pane evaluation-context)] (.getTabs tab-pane))) (defn- make-render-build-error [main-scene tool-tab-pane build-errors-view] (fn [error-value] (build-errors-view/update-build-errors build-errors-view error-value) (show-build-errors! main-scene tool-tab-pane))) (def ^:private remote-log-pump-thread (atom nil)) (def ^:private console-stream (atom nil)) (defn- reset-remote-log-pump-thread! [^Thread new] (when-let [old ^Thread @remote-log-pump-thread] (.interrupt old)) (reset! remote-log-pump-thread new)) (defn- start-log-pump! [log-stream sink-fn] (doto (Thread. (fn [] (try (let [this (Thread/currentThread)] (with-open [buffered-reader ^BufferedReader (io/reader log-stream :encoding "UTF-8")] (loop [] (when-not (.isInterrupted this) (when-let [line (.readLine buffered-reader)] ; line of text or nil if eof reached (sink-fn line) (recur)))))) (catch IOException _ ;; Losing the log connection is ok and even expected nil) (catch InterruptedException _ ;; Losing the log connection is ok and even expected nil)))) (.start))) (defn- local-url [target web-server] (format "http://%s:%s%s" (:local-address target) (http-server/port web-server) hot-reload/url-prefix)) (def ^:private app-task-progress {:main (ref progress/done) :build (ref progress/done) :resource-sync (ref progress/done) :save-all (ref progress/done) :fetch-libraries (ref progress/done) :download-update (ref progress/done)}) (defn- cancel-task! [task-key] (dosync (let [progress-ref (task-key app-task-progress)] (ref-set progress-ref (progress/cancel! @progress-ref))))) (def ^:private app-task-ui-priority "Task priority in descending order (from highest to lowest)" [:save-all :resource-sync :fetch-libraries :build :download-update :main]) (def ^:private render-task-progress-ui-inflight (ref false)) (defn- render-task-progress-ui! [] (let [task-progress-snapshot (ref nil)] (dosync (ref-set render-task-progress-ui-inflight false) (ref-set task-progress-snapshot (into {} (map (juxt first (comp deref second))) app-task-progress))) (let [status-bar (.. (ui/main-stage) (getScene) (getRoot) (lookup "#status-bar")) [key progress] (->> app-task-ui-priority (map (juxt identity @task-progress-snapshot)) (filter (comp (complement progress/done?) second)) first) show-progress-hbox? (boolean (and (not= key :main) progress (not (progress/done? progress))))] (ui/with-controls status-bar [progress-bar progress-hbox progress-percentage-label status-label progress-cancel-button] (ui/render-progress-message! (if key progress (@task-progress-snapshot :main)) status-label) ;; The bottom right of the status bar can show either the progress-hbox ;; or the update-link, or both. The progress-hbox will cover ;; the update-link if both are visible. (if-not show-progress-hbox? (ui/visible! progress-hbox false) (do (ui/visible! progress-hbox true) (ui/render-progress-bar! progress progress-bar) (ui/render-progress-percentage! progress progress-percentage-label) (if (progress/cancellable? progress) (doto progress-cancel-button (ui/visible! true) (ui/managed! true) (ui/on-action! (fn [_] (cancel-task! key)))) (doto progress-cancel-button (ui/visible! false) (ui/managed! false) (ui/on-action! identity))))))))) (defn- render-task-progress! [key progress] (let [schedule-render-task-progress-ui (ref false)] (dosync (ref-set (get app-task-progress key) progress) (ref-set schedule-render-task-progress-ui (not @render-task-progress-ui-inflight)) (ref-set render-task-progress-ui-inflight true)) (when @schedule-render-task-progress-ui (ui/run-later (render-task-progress-ui!))))) (defn make-render-task-progress [key] (assert (contains? app-task-progress key)) (progress/throttle-render-progress (fn [progress] (render-task-progress! key progress)))) (defn make-task-cancelled-query [keyword] (fn [] (progress/cancelled? @(keyword app-task-progress)))) (defn render-main-task-progress! [progress] (render-task-progress! :main progress)) (defn- report-build-launch-progress! [message] (render-main-task-progress! (progress/make message))) (defn clear-build-launch-progress! [] (render-main-task-progress! progress/done)) (defn- decorate-target [engine-descriptor target] (assoc target :engine-id (:id engine-descriptor))) (defn- launch-engine! [engine-descriptor project-directory prefs debug?] (try (report-build-launch-progress! "Launching engine...") (let [engine (engine/install-engine! project-directory engine-descriptor) launched-target (->> (engine/launch! engine project-directory prefs debug?) (decorate-target engine-descriptor) (targets/add-launched-target!) (targets/select-target! prefs))] (report-build-launch-progress! (format "Launched %s" (targets/target-message-label launched-target))) launched-target) (catch Exception e (targets/kill-launched-targets!) (report-build-launch-progress! "Launch failed") (throw e)))) (defn- reset-console-stream! [stream] (reset! console-stream stream) (console/clear-console!)) (defn- make-remote-log-sink [log-stream] (fn [line] (when (= @console-stream log-stream) (console/append-console-line! line)))) (defn- make-launched-log-sink [launched-target] (let [initial-output (atom "")] (fn [line] (when (< (count @initial-output) 5000) (swap! initial-output str line "\n") (when-let [target-info (engine/parse-launched-target-info @initial-output)] (targets/update-launched-target! launched-target target-info))) (when (= @console-stream (:log-stream launched-target)) (console/append-console-line! line))))) (defn- reboot-engine! [target web-server debug?] (try (report-build-launch-progress! (format "Rebooting %s..." (targets/target-message-label target))) (engine/reboot! target (local-url target web-server) debug?) (report-build-launch-progress! (format "Rebooted %s" (targets/target-message-label target))) target (catch Exception e (report-build-launch-progress! "Reboot failed") (throw e)))) (def ^:private build-in-progress? (atom false)) (defn- on-launched-hook! [project process url] (let [hook-options {:exception-policy :ignore :opts {:url url}}] (future (error-reporting/catch-all! (extensions/execute-hook! project :on-target-launched hook-options) (process/watchdog! process #(extensions/execute-hook! project :on-target-terminated hook-options)))))) (defn- launch-built-project! [project engine-descriptor project-directory prefs web-server debug?] (let [selected-target (targets/selected-target prefs) launch-new-engine! (fn [] (targets/kill-launched-targets!) (let [launched-target (launch-engine! engine-descriptor project-directory prefs debug?) log-stream (:log-stream launched-target)] (targets/when-url (:id launched-target) #(on-launched-hook! project (:process launched-target) %)) (reset-console-stream! log-stream) (reset-remote-log-pump-thread! nil) (start-log-pump! log-stream (make-launched-log-sink launched-target)) launched-target))] (try (cond (not selected-target) (launch-new-engine!) (not (targets/controllable-target? selected-target)) (do (assert (targets/launched-target? selected-target)) (launch-new-engine!)) (and (targets/controllable-target? selected-target) (targets/remote-target? selected-target)) (let [log-stream (engine/get-log-service-stream selected-target)] (reset-console-stream! log-stream) (reset-remote-log-pump-thread! (start-log-pump! log-stream (make-remote-log-sink log-stream))) (reboot-engine! selected-target web-server debug?)) :else (do (assert (and (targets/controllable-target? selected-target) (targets/launched-target? selected-target))) (if (= (:id engine-descriptor) (:engine-id selected-target)) (do ;; We're running "the same" engine and can reuse the ;; running process by rebooting (reset-console-stream! (:log-stream selected-target)) (reset-remote-log-pump-thread! nil) ;; Launched target log pump already ;; running to keep engine process ;; from halting because stdout/err is ;; not consumed. (reboot-engine! selected-target web-server debug?)) (launch-new-engine!)))) (catch Exception e (log/warn :exception e) (dialogs/make-info-dialog {:title "Launch Failed" :icon :icon/triangle-error :header {:fx/type :v-box :children [{:fx/type fxui/label :variant :header :text (format "Launching %s failed" (if (some? selected-target) (targets/target-message-label selected-target) "New Local Engine"))} {:fx/type fxui/label :text "If the engine is already running, shut down the process manually and retry"}]} :content (.getMessage e)}))))) (defn- build-project! [project evaluation-context extra-build-targets old-artifact-map render-progress!] (let [game-project (project/get-resource-node project "/game.project" evaluation-context) render-progress! (progress/throttle-render-progress render-progress!)] (try (ui/with-progress [render-progress! render-progress!] (build/build-project! project game-project evaluation-context extra-build-targets old-artifact-map render-progress!)) (catch Throwable error (error-reporting/report-exception! error) nil)))) (defn- cached-build-target-output? [node-id label evaluation-context] (and (= :build-targets label) (project/project-resource-node? node-id evaluation-context))) (defn- update-system-cache-build-targets! [evaluation-context] ;; To avoid cache churn, we only transfer the most important entries to the system cache. (let [pruned-evaluation-context (g/pruned-evaluation-context evaluation-context cached-build-target-output?)] (g/update-cache-from-evaluation-context! pruned-evaluation-context))) (defn async-build! [project prefs {:keys [debug? engine?] :or {debug? false engine? true}} old-artifact-map render-build-progress! result-fn] (let [;; After any pre-build hooks have completed successfully, we will start ;; the engine build on a separate background thread so the build servers ;; can work while we build the project. We will await the results of the ;; engine build in the final phase. engine-build-future-atom (atom nil) cancel-engine-build! (fn cancel-engine-build! [] (when-some [engine-build-future (thread-util/preset! engine-build-future-atom nil)] (future-cancel engine-build-future) nil)) start-engine-build! (fn start-engine-build! [] (assert (ui/on-ui-thread?)) (cancel-engine-build!) (when engine? (let [evaluation-context (g/make-evaluation-context) platform (engine/current-platform)] (reset! engine-build-future-atom (future (try (let [engine (engine/get-engine project evaluation-context prefs platform)] (ui/run-later ;; This potentially saves us from having to ;; re-calculate native extension file hashes the ;; next time we build the project. (g/update-cache-from-evaluation-context! evaluation-context)) engine) (catch Throwable error error)))) nil))) run-on-background-thread! (fn run-on-background-thread! [background-thread-fn ui-thread-fn] (future (try (let [return-value (background-thread-fn)] (ui/run-later (try (ui-thread-fn return-value) (catch Throwable error (reset! build-in-progress? false) (render-build-progress! progress/done) (cancel-engine-build!) (throw error))))) (catch Throwable error (reset! build-in-progress? false) (render-build-progress! progress/done) (cancel-engine-build!) (error-reporting/report-exception! error)))) nil) finish-with-result! (fn finish-with-result! [project-build-results engine build-engine-exception] (reset! build-in-progress? false) (render-build-progress! progress/done) (cancel-engine-build!) (when (some? result-fn) (result-fn project-build-results engine build-engine-exception) nil)) phase-5-await-engine-build! (fn phase-5-await-engine-build! [project-build-results] (assert (nil? (:error project-build-results))) (let [engine-build-future @engine-build-future-atom] (if (nil? engine-build-future) (finish-with-result! project-build-results nil nil) (do (render-build-progress! (progress/make-indeterminate "Fetching engine...")) (run-on-background-thread! (fn run-engine-build-on-background-thread! [] (deref engine-build-future)) (fn process-engine-build-results-on-ui-thread! [engine-or-exception] (if (instance? Throwable engine-or-exception) (finish-with-result! project-build-results nil engine-or-exception) (finish-with-result! project-build-results engine-or-exception nil)))))))) phase-4-run-post-build-hook! (fn phase-4-run-post-build-hook! [project-build-results] (render-build-progress! (progress/make-indeterminate "Executing post-build hooks...")) (let [platform (engine/current-platform) project-build-successful? (nil? (:error project-build-results))] (run-on-background-thread! (fn run-post-build-hook-on-background-thread! [] (extensions/execute-hook! project :on-build-finished {:exception-policy :ignore :opts {:success project-build-successful? :platform platform}})) (fn process-post-build-hook-results-on-ui-thread! [_] (if project-build-successful? (phase-5-await-engine-build! project-build-results) (finish-with-result! project-build-results nil nil)))))) phase-3-build-project! (fn phase-3-build-project! [] ;; We're about to create an evaluation-context. Make sure it is ;; created from the main thread, so it makes sense to update the cache ;; from it after the project build concludes. Note that we selectively ;; transfer only the cached build-targets back to the system cache. ;; We do this because the project build process involves most of the ;; cached outputs in the project graph, and the intermediate steps ;; risk evicting the previous build targets as the cache fills up. (assert (ui/on-ui-thread?)) (let [evaluation-context (g/make-evaluation-context)] (render-build-progress! (progress/make "Building project..." 1)) (run-on-background-thread! (fn run-project-build-on-background-thread! [] (let [extra-build-targets (when debug? (debug-view/build-targets project evaluation-context))] (build-project! project evaluation-context extra-build-targets old-artifact-map render-build-progress!))) (fn process-project-build-results-on-ui-thread! [project-build-results] (update-system-cache-build-targets! evaluation-context) (phase-4-run-post-build-hook! project-build-results))))) phase-2-start-engine-build! (fn phase-2-start-engine-build! [] (start-engine-build!) (phase-3-build-project!)) phase-1-run-pre-build-hook! (fn phase-1-run-pre-build-hook! [] (render-build-progress! (progress/make-indeterminate "Executing pre-build hooks...")) (let [platform (engine/current-platform)] (run-on-background-thread! (fn run-pre-build-hook-on-background-thread! [] (let [extension-error (extensions/execute-hook! project :on-build-started {:exception-policy :as-error :opts {:platform platform}})] ;; If there was an error in the pre-build hook, we won't proceed ;; with the project build. But we still want to report the build ;; failure to any post-build hooks that might need to know. (when (some? extension-error) (render-build-progress! (progress/make-indeterminate "Executing post-build hooks...")) (extensions/execute-hook! project :on-build-finished {:exception-policy :ignore :opts {:success false :platform platform}})) extension-error)) (fn process-pre-build-hook-results-on-ui-thread! [extension-error] (if (some? extension-error) (finish-with-result! {:error extension-error} nil nil) (phase-2-start-engine-build!))))))] ;; Trigger phase 1. Subsequent phases will be triggered as prior phases ;; finish without errors. Each phase will do some work on a background ;; thread, then process the results on the ui thread, and potentially ;; trigger subsequent phases which will again get off the ui thread as ;; soon as they can. (assert (not @build-in-progress?)) (reset! build-in-progress? true) (phase-1-run-pre-build-hook!))) (defn- handle-build-results! [workspace render-build-error! build-results] (let [{:keys [error artifact-map etags]} build-results] (if (some? error) (do (render-build-error! error) nil) (do (workspace/artifact-map! workspace artifact-map) (workspace/etags! workspace etags) (workspace/save-build-cache! workspace) build-results)))) (defn- build-handler [project workspace prefs web-server build-errors-view main-stage tool-tab-pane] (let [project-directory (io/file (workspace/project-path workspace)) main-scene (.getScene ^Stage main-stage) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view)] (build-errors-view/clear-build-errors build-errors-view) (async-build! project prefs {:debug? false} (workspace/artifact-map workspace) (make-render-task-progress :build) (fn [build-results engine-descriptor build-engine-exception] (when (handle-build-results! workspace render-build-error! build-results) (when engine-descriptor (show-console! main-scene tool-tab-pane) (launch-built-project! project engine-descriptor project-directory prefs web-server false)) (when build-engine-exception (log/warn :exception build-engine-exception) (g/with-auto-evaluation-context evaluation-context (engine-build-errors/handle-build-error! render-build-error! project evaluation-context build-engine-exception)))))))) (handler/defhandler :build :global (enabled? [] (not @build-in-progress?)) (run [project workspace prefs web-server build-errors-view debug-view main-stage tool-tab-pane] (debug-view/detach! debug-view) (build-handler project workspace prefs web-server build-errors-view main-stage tool-tab-pane))) (defn- debugging-supported? [project] (if (project/shared-script-state? project) true (do (dialogs/make-info-dialog {:title "Debugging Not Supported" :icon :icon/triangle-error :header "This project cannot be used with the debugger" :content {:fx/type fxui/label :style-class "dialog-content-padding" :text "It is configured to disable shared script state. If you do not specifically require different script states, consider changing the script.shared_state property in game.project."}}) false))) (defn- run-with-debugger! [workspace project prefs debug-view render-build-error! web-server] (let [project-directory (io/file (workspace/project-path workspace))] (async-build! project prefs {:debug? true} (workspace/artifact-map workspace) (make-render-task-progress :build) (fn [build-results engine-descriptor build-engine-exception] (when (handle-build-results! workspace render-build-error! build-results) (when engine-descriptor (when-let [target (launch-built-project! project engine-descriptor project-directory prefs web-server true)] (when (nil? (debug-view/current-session debug-view)) (debug-view/start-debugger! debug-view project (:address target "localhost"))))) (when build-engine-exception (log/warn :exception build-engine-exception) (g/with-auto-evaluation-context evaluation-context (engine-build-errors/handle-build-error! render-build-error! project evaluation-context build-engine-exception)))))))) (defn- attach-debugger! [workspace project prefs debug-view render-build-error!] (async-build! project prefs {:debug? true :engine? false} (workspace/artifact-map workspace) (make-render-task-progress :build) (fn [build-results _ _] (when (handle-build-results! workspace render-build-error! build-results) (let [target (targets/selected-target prefs)] (when (targets/controllable-target? target) (debug-view/attach! debug-view project target (:artifacts build-results)))))))) (handler/defhandler :start-debugger :global ;; NOTE: Shares a shortcut with :debug-view/continue. ;; Only one of them can be active at a time. This creates the impression that ;; there is a single menu item whose label changes in various states. (active? [debug-view evaluation-context] (not (debug-view/debugging? debug-view evaluation-context))) (enabled? [] (not @build-in-progress?)) (run [project workspace prefs web-server build-errors-view console-view debug-view main-stage tool-tab-pane] (when (debugging-supported? project) (let [main-scene (.getScene ^Stage main-stage) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view)] (build-errors-view/clear-build-errors build-errors-view) (if (debug-view/can-attach? prefs) (attach-debugger! workspace project prefs debug-view render-build-error!) (run-with-debugger! workspace project prefs debug-view render-build-error! web-server)))))) (handler/defhandler :rebuild :global (enabled? [] (not @build-in-progress?)) (run [project workspace prefs web-server build-errors-view debug-view main-stage tool-tab-pane] (debug-view/detach! debug-view) (workspace/clear-build-cache! workspace) (build-handler project workspace prefs web-server build-errors-view main-stage tool-tab-pane))) (handler/defhandler :build-html5 :global (run [project prefs web-server build-errors-view changes-view main-stage tool-tab-pane] (let [main-scene (.getScene ^Stage main-stage) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view) render-reload-progress! (make-render-task-progress :resource-sync) render-save-progress! (make-render-task-progress :save-all) render-build-progress! (make-render-task-progress :build) task-cancelled? (make-task-cancelled-query :build) bob-args (bob/build-html5-bob-args project prefs)] (build-errors-view/clear-build-errors build-errors-view) (disk/async-bob-build! render-reload-progress! render-save-progress! render-build-progress! task-cancelled? render-build-error! bob/build-html5-bob-commands bob-args project changes-view (fn [successful?] (when successful? (ui/open-url (format "http://localhost:%d%s/index.html" (http-server/port web-server) bob/html5-url-prefix)))))))) (defn- updated-build-resource-proj-paths [old-etags new-etags] ;; We only want to return resources that were present in the old etags since ;; we don't want to ask the engine to reload something it has not seen yet. ;; It is presumed that the engine will follow any newly-introduced references ;; and load the resources. We might ask the engine to reload these resources ;; the next time they are modified. (into #{} (keep (fn [[proj-path old-etag]] (when-some [new-etag (new-etags proj-path)] (when (not= old-etag new-etag) proj-path)))) old-etags)) (defn- updated-build-resources [evaluation-context project old-etags new-etags proj-path-or-resource] (let [resource-node (project/get-resource-node project proj-path-or-resource evaluation-context) build-targets (g/node-value resource-node :build-targets evaluation-context) updated-build-resource-proj-paths (updated-build-resource-proj-paths old-etags new-etags)] (into [] (keep (fn [{build-resource :resource :as _build-target}] (when (contains? updated-build-resource-proj-paths (resource/proj-path build-resource)) build-resource))) (rseq (pipeline/flatten-build-targets build-targets))))) (defn- can-hot-reload? [debug-view prefs evaluation-context] (when-some [target (targets/selected-target prefs)] (and (targets/controllable-target? target) (not (debug-view/suspended? debug-view evaluation-context)) (not @build-in-progress?)))) (defn- hot-reload! [project prefs build-errors-view main-stage tool-tab-pane] (let [main-scene (.getScene ^Stage main-stage) target (targets/selected-target prefs) workspace (project/workspace project) old-artifact-map (workspace/artifact-map workspace) old-etags (workspace/etags workspace) render-build-progress! (make-render-task-progress :build) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view) opts {:debug? false :engine? false}] ;; NOTE: We must build the entire project even if we only want to reload a ;; subset of resources in order to maintain a functioning build cache. ;; If we decide to support hot reload of a subset of resources, we must ;; keep track of which resource versions have been loaded by the engine, ;; or we might miss resources that were recompiled but never reloaded. (build-errors-view/clear-build-errors build-errors-view) (async-build! project prefs opts old-artifact-map render-build-progress! (fn [{:keys [error artifact-map etags]} _ _] (if (some? error) (render-build-error! error) (do (workspace/artifact-map! workspace artifact-map) (workspace/etags! workspace etags) (workspace/save-build-cache! workspace) (try (when-some [updated-build-resources (not-empty (g/with-auto-evaluation-context evaluation-context (updated-build-resources evaluation-context project old-etags etags "/game.project")))] (engine/reload-build-resources! target updated-build-resources)) (catch Exception e (dialogs/make-info-dialog {:title "Hot Reload Failed" :icon :icon/triangle-error :header (format "Failed to reload resources on '%s'" (targets/target-message-label (targets/selected-target prefs))) :content (.getMessage e)}))))))))) (handler/defhandler :hot-reload :global (enabled? [debug-view prefs evaluation-context] (can-hot-reload? debug-view prefs evaluation-context)) (run [project app-view prefs build-errors-view selection main-stage tool-tab-pane] (hot-reload! project prefs build-errors-view main-stage tool-tab-pane))) (handler/defhandler :close :global (enabled? [app-view evaluation-context] (not-empty (get-active-tabs app-view evaluation-context))) (run [app-view] (let [tab-pane (g/node-value app-view :active-tab-pane)] (when-let [tab (ui/selected-tab tab-pane)] (remove-tab! tab-pane tab))))) (handler/defhandler :close-other :global (enabled? [app-view evaluation-context] (not-empty (next (get-active-tabs app-view evaluation-context)))) (run [app-view] (let [tab-pane ^TabPane (g/node-value app-view :active-tab-pane)] (when-let [selected-tab (ui/selected-tab tab-pane)] ;; Plain doseq over .getTabs will use the iterable interface ;; and we get a ConcurrentModificationException since we ;; remove from the list while iterating. Instead put the tabs ;; in a (non-lazy) vec before iterating. (doseq [tab (vec (.getTabs tab-pane))] (when (not= tab selected-tab) (remove-tab! tab-pane tab))))))) (handler/defhandler :close-all :global (enabled? [app-view evaluation-context] (not-empty (get-active-tabs app-view evaluation-context))) (run [app-view] (let [tab-pane ^TabPane (g/node-value app-view :active-tab-pane)] (doseq [tab (vec (.getTabs tab-pane))] (remove-tab! tab-pane tab))))) (defn- editor-tab-pane "Returns the editor TabPane that is above the Node in the scene hierarchy, or nil if the Node does not reside under an editor TabPane." ^TabPane [node] (when-some [parent-tab-pane (ui/parent-tab-pane node)] (when (= "editor-tabs-split" (some-> (ui/tab-pane-parent parent-tab-pane) (.getId))) parent-tab-pane))) (declare ^:private configure-editor-tab-pane!) (defn- find-other-tab-pane ^TabPane [^SplitPane editor-tabs-split ^TabPane current-tab-pane] (first-where #(not (identical? current-tab-pane %)) (.getItems editor-tabs-split))) (defn- add-other-tab-pane! ^TabPane [^SplitPane editor-tabs-split app-view] (let [tab-panes (.getItems editor-tabs-split) app-stage ^Stage (g/node-value app-view :stage) app-scene (.getScene app-stage) new-tab-pane (TabPane.)] (assert (= 1 (count tab-panes))) (.add tab-panes new-tab-pane) (configure-editor-tab-pane! new-tab-pane app-scene app-view) new-tab-pane)) (defn- open-tab-count ^long [app-view evaluation-context] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split evaluation-context)] (loop [tab-panes (.getItems editor-tabs-split) tab-count 0] (if-some [^TabPane tab-pane (first tab-panes)] (recur (next tab-panes) (+ tab-count (.size (.getTabs tab-pane)))) tab-count)))) (defn- open-tab-pane-count ^long [app-view evaluation-context] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split evaluation-context)] (.size (.getItems editor-tabs-split)))) (handler/defhandler :move-tab :global (enabled? [app-view evaluation-context] (< 1 (open-tab-count app-view evaluation-context))) (run [app-view user-data] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split) source-tab-pane ^TabPane (g/node-value app-view :active-tab-pane) selected-tab (ui/selected-tab source-tab-pane) dest-tab-pane (or (find-other-tab-pane editor-tabs-split source-tab-pane) (add-other-tab-pane! editor-tabs-split app-view))] (.remove (.getTabs source-tab-pane) selected-tab) (.add (.getTabs dest-tab-pane) selected-tab) (.select (.getSelectionModel dest-tab-pane) selected-tab) (.requestFocus dest-tab-pane)))) (handler/defhandler :swap-tabs :global (enabled? [app-view evaluation-context] (< 1 (open-tab-pane-count app-view evaluation-context))) (run [app-view user-data] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split) active-tab-pane ^TabPane (g/node-value app-view :active-tab-pane) other-tab-pane (find-other-tab-pane editor-tabs-split active-tab-pane) active-tab-pane-selection (.getSelectionModel active-tab-pane) other-tab-pane-selection (.getSelectionModel other-tab-pane) active-tab-index (.getSelectedIndex active-tab-pane-selection) other-tab-index (.getSelectedIndex other-tab-pane-selection) active-tabs (.getTabs active-tab-pane) other-tabs (.getTabs other-tab-pane) active-tab (.get active-tabs active-tab-index) other-tab (.get other-tabs other-tab-index)] ;; Fix for DEFEDIT-1673: ;; We need to swap in a dummy tab here so that a tab is never in both ;; TabPanes at once, since the tab lists are observed internally. If we ;; do not, the tabs will lose track of their parent TabPane. (.set other-tabs other-tab-index (Tab.)) (.set active-tabs active-tab-index other-tab) (.set other-tabs other-tab-index active-tab) (.select active-tab-pane-selection other-tab) (.select other-tab-pane-selection active-tab) (.requestFocus other-tab-pane)))) (handler/defhandler :join-tab-panes :global (enabled? [app-view evaluation-context] (< 1 (open-tab-pane-count app-view evaluation-context))) (run [app-view user-data] (let [editor-tabs-split ^SplitPane (g/node-value app-view :editor-tabs-split) active-tab-pane ^TabPane (g/node-value app-view :active-tab-pane) selected-tab (ui/selected-tab active-tab-pane) tab-panes (.getItems editor-tabs-split) first-tab-pane ^TabPane (.get tab-panes 0) second-tab-pane ^TabPane (.get tab-panes 1) first-tabs (.getTabs first-tab-pane) second-tabs (.getTabs second-tab-pane) moved-tabs (vec second-tabs)] (.clear second-tabs) (.addAll first-tabs ^Collection moved-tabs) (.select (.getSelectionModel first-tab-pane) selected-tab) (.requestFocus first-tab-pane)))) (defn make-about-dialog [] (let [root ^Parent (ui/load-fxml "about.fxml") stage (ui/make-dialog-stage) scene (Scene. root) controls (ui/collect-controls root ["version" "channel" "editor-sha1" "engine-sha1" "time", "sponsor-push"])] (ui/text! (:version controls) (System/getProperty "defold.version" "No version")) (ui/text! (:channel controls) (or (system/defold-channel) "No channel")) (ui/text! (:editor-sha1 controls) (or (system/defold-editor-sha1) "No editor sha1")) (ui/text! (:engine-sha1 controls) (or (system/defold-engine-sha1) "No engine sha1")) (ui/text! (:time controls) (or (system/defold-build-time) "No build time")) (UIUtil/stringToTextFlowNodes (:sponsor-push controls) "[Defold Foundation Development Fund](https://www.defold.com/community-donations)") (ui/title! stage "About") (.setScene stage scene) (ui/show! stage))) (handler/defhandler :documentation :global (run [] (ui/open-url "https://www.defold.com/learn/"))) (handler/defhandler :support-forum :global (run [] (ui/open-url "https://forum.defold.com/"))) (handler/defhandler :asset-portal :global (run [] (ui/open-url "https://www.defold.com/assets"))) (handler/defhandler :report-issue :global (run [] (ui/open-url (github/new-issue-link)))) (handler/defhandler :report-suggestion :global (run [] (ui/open-url (github/new-suggestion-link)))) (handler/defhandler :search-issues :global (run [] (ui/open-url (github/search-issues-link)))) (handler/defhandler :show-logs :global (run [] (ui/open-file (.getAbsoluteFile (.toFile (Editor/getLogDirectory)))))) (handler/defhandler :donate :global (run [] (ui/open-url "https://www.defold.com/donate"))) (handler/defhandler :about :global (run [] (make-about-dialog))) (handler/defhandler :reload-stylesheet :global (run [] (ui/reload-root-styles!))) (handler/register-menu! ::menubar [{:label "File" :id ::file :children [{:label "New..." :id ::new :command :new-file} {:label "Open" :id ::open :command :open} {:label "Synchronize..." :id ::synchronize :command :synchronize} {:label "Save All" :id ::save-all :command :save-all} {:label :separator} {:label "Open Assets..." :command :open-asset} {:label "Search in Files..." :command :search-in-files} {:label :separator} {:label "Close" :command :close} {:label "Close All" :command :close-all} {:label "Close Others" :command :close-other} {:label :separator} {:label "Referencing Files..." :command :referencing-files} {:label "Dependencies..." :command :dependencies} {:label "Hot Reload" :command :hot-reload} {:label :separator} {:label "Preferences..." :command :preferences} {:label "Quit" :command :quit}]} {:label "Edit" :id ::edit :children [{:label "Undo" :icon "icons/undo.png" :command :undo} {:label "Redo" :icon "icons/redo.png" :command :redo} {:label :separator} {:label "Cut" :command :cut} {:label "Copy" :command :copy} {:label "Paste" :command :paste} {:label "Select All" :command :select-all} {:label "Delete" :icon "icons/32/Icons_M_06_trash.png" :command :delete} {:label :separator} {:label "Move Up" :command :move-up} {:label "Move Down" :command :move-down} {:label :separator :id ::edit-end}]} {:label "View" :id ::view :children [{:label "Toggle Assets Pane" :command :toggle-pane-left} {:label "Toggle Tools Pane" :command :toggle-pane-bottom} {:label "Toggle Properties Pane" :command :toggle-pane-right} {:label :separator} {:label "Show Console" :command :show-console} {:label "Show Curve Editor" :command :show-curve-editor} {:label "Show Build Errors" :command :show-build-errors} {:label "Show Search Results" :command :show-search-results} {:label :separator :id ::view-end}]} {:label "Help" :children [{:label "Profiler" :children [{:label "Measure" :command :profile} {:label "Measure and Show" :command :profile-show}]} {:label "Reload Stylesheet" :command :reload-stylesheet} {:label "Show Logs" :command :show-logs} {:label :separator} {:label "Documentation" :command :documentation} {:label "Support Forum" :command :support-forum} {:label "Find Assets" :command :asset-portal} {:label :separator} {:label "Report Issue" :command :report-issue} {:label "Report Suggestion" :command :report-suggestion} {:label "Search Issues" :command :search-issues} {:label :separator} {:label "Development Fund" :command :donate} {:label :separator} {:label "About" :command :about}]}]) (handler/register-menu! ::tab-menu [{:label "Close" :command :close} {:label "Close Others" :command :close-other} {:label "Close All" :command :close-all} {:label :separator} {:label "Move to Other Tab Pane" :command :move-tab} {:label "Swap With Other Tab Pane" :command :swap-tabs} {:label "Join Tab Panes" :command :join-tab-panes} {:label :separator} {:label "Copy Project Path" :command :copy-project-path} {:label "Copy Full Path" :command :copy-full-path} {:label "Copy Require Path" :command :copy-require-path} {:label :separator} {:label "Show in Asset Browser" :icon "icons/32/Icons_S_14_linkarrow.png" :command :show-in-asset-browser} {:label "Show in Desktop" :icon "icons/32/Icons_S_14_linkarrow.png" :command :show-in-desktop} {:label "Referencing Files..." :command :referencing-files} {:label "Dependencies..." :command :dependencies}]) (defrecord SelectionProvider [app-view] handler/SelectionProvider (selection [_] (g/node-value app-view :selected-node-ids)) (succeeding-selection [_] []) (alt-selection [_] [])) (defn ->selection-provider [app-view] (SelectionProvider. app-view)) (defn select ([app-view node-ids] (select app-view (g/node-value app-view :active-resource-node) node-ids)) ([app-view resource-node node-ids] (g/with-auto-evaluation-context evaluation-context (let [project-id (g/node-value app-view :project-id evaluation-context) open-resource-nodes (g/node-value app-view :open-resource-nodes evaluation-context)] (project/select project-id resource-node node-ids open-resource-nodes))))) (defn select! ([app-view node-ids] (select! app-view node-ids (gensym))) ([app-view node-ids op-seq] (g/transact (concat (g/operation-sequence op-seq) (g/operation-label "Select") (select app-view node-ids))))) (defn sub-select! ([app-view sub-selection] (sub-select! app-view sub-selection (gensym))) ([app-view sub-selection op-seq] (g/with-auto-evaluation-context evaluation-context (let [project-id (g/node-value app-view :project-id evaluation-context) active-resource-node (g/node-value app-view :active-resource-node evaluation-context) open-resource-nodes (g/node-value app-view :open-resource-nodes evaluation-context)] (g/transact (concat (g/operation-sequence op-seq) (g/operation-label "Select") (project/sub-select project-id active-resource-node sub-selection open-resource-nodes))))))) (defn- make-title ([] "Defold Editor 2.0") ([project-title] (str project-title " - " (make-title)))) (defn- refresh-app-title! [^Stage stage project] (let [settings (g/node-value project :settings) project-title (settings ["project" "title"]) new-title (make-title project-title)] (when (not= (.getTitle stage) new-title) (.setTitle stage new-title)))) (defn- refresh-menus-and-toolbars! [app-view ^Scene scene] (let [keymap (g/node-value app-view :keymap) command->shortcut (keymap/command->shortcut keymap)] (ui/user-data! scene :command->shortcut command->shortcut) (ui/refresh scene))) (defn- refresh-views! [app-view] (let [auto-pulls (g/node-value app-view :auto-pulls)] (doseq [[node label] auto-pulls] (profiler/profile "view" (:name @(g/node-type* node)) (g/node-value node label))))) (defn- refresh-scene-views! [app-view] (profiler/begin-frame) (doseq [view-id (g/node-value app-view :scene-view-ids)] (try (scene/refresh-scene-view! view-id) (catch Throwable error (error-reporting/report-exception! error)))) (scene-cache/prune-context! nil)) (defn- dispose-scene-views! [app-view] (doseq [view-id (g/node-value app-view :scene-view-ids)] (try (scene/dispose-scene-view! view-id) (catch Throwable error (error-reporting/report-exception! error)))) (scene-cache/drop-context! nil)) (defn- tab->resource-node [^Tab tab] (some-> tab (ui/user-data ::view) (g/node-value :view-data) second :resource-node)) (defn- tab->view-type [^Tab tab] (some-> tab (ui/user-data ::view-type) :id)) (defn- configure-editor-tab-pane! [^TabPane tab-pane ^Scene app-scene app-view] (.setTabClosingPolicy tab-pane TabPane$TabClosingPolicy/ALL_TABS) (.setTabDragPolicy tab-pane TabPane$TabDragPolicy/REORDER) (-> tab-pane (.getSelectionModel) (.selectedItemProperty) (.addListener (reify ChangeListener (changed [_this _observable _old-val new-val] (on-selected-tab-changed! app-view app-scene (tab->resource-node new-val) (tab->view-type new-val)))))) (-> tab-pane (.getTabs) (.addListener (reify ListChangeListener (onChanged [_this _change] ;; Check if we've ended up with an empty TabPane. ;; Unless we are the only one left, we should get rid of it to make room for the other TabPane. (when (empty? (.getTabs tab-pane)) (let [editor-tabs-split ^SplitPane (ui/tab-pane-parent tab-pane) tab-panes (.getItems editor-tabs-split)] (when (< 1 (count tab-panes)) (.remove tab-panes tab-pane) (.requestFocus ^TabPane (.get tab-panes 0))))))))) (ui/register-tab-pane-context-menu tab-pane ::tab-menu)) (defn- handle-focus-owner-change! [app-view app-scene new-focus-owner] (let [old-editor-tab-pane (g/node-value app-view :active-tab-pane) new-editor-tab-pane (editor-tab-pane new-focus-owner)] (when (and (some? new-editor-tab-pane) (not (identical? old-editor-tab-pane new-editor-tab-pane))) (let [selected-tab (ui/selected-tab new-editor-tab-pane) resource-node (tab->resource-node selected-tab) view-type (tab->view-type selected-tab)] (ui/add-style! old-editor-tab-pane "inactive") (ui/remove-style! new-editor-tab-pane "inactive") (g/set-property! app-view :active-tab-pane new-editor-tab-pane) (on-selected-tab-changed! app-view app-scene resource-node view-type))))) (defn open-custom-keymap [path] (try (and (not= path "") (some-> path slurp edn/read-string)) (catch IOException e (dialogs/make-info-dialog {:title "Couldn't load custom keymap config" :icon :icon/triangle-error :header {:fx/type :v-box :children [{:fx/type fxui/label :text (str "The keymap path " path " couldn't be opened.")}]} :content (.getMessage e)}) (log/error :exception e) nil))) (defn make-app-view [view-graph project ^Stage stage ^MenuBar menu-bar ^SplitPane editor-tabs-split ^TabPane tool-tab-pane prefs] (let [app-scene (.getScene stage)] (ui/disable-menu-alt-key-mnemonic! menu-bar) (.setUseSystemMenuBar menu-bar true) (.setTitle stage (make-title)) (let [editor-tab-pane (TabPane.) keymap (or (open-custom-keymap (prefs/get-prefs prefs "custom-keymap-path" "")) keymap/default-host-key-bindings) app-view (first (g/tx-nodes-added (g/transact (g/make-node view-graph AppView :stage stage :scene app-scene :editor-tabs-split editor-tabs-split :active-tab-pane editor-tab-pane :tool-tab-pane tool-tab-pane :active-tool :move :manip-space :world :keymap-config keymap))))] (.add (.getItems editor-tabs-split) editor-tab-pane) (configure-editor-tab-pane! editor-tab-pane app-scene app-view) (ui/observe (.focusOwnerProperty app-scene) (fn [_ _ new-focus-owner] (handle-focus-owner-change! app-view app-scene new-focus-owner))) (ui/register-menubar app-scene menu-bar ::menubar) (keymap/install-key-bindings! (.getScene stage) (g/node-value app-view :keymap)) (let [refresh-timer (ui/->timer "refresh-app-view" (fn [_ _] (when-not (ui/ui-disabled?) (let [refresh-requested? (ui/user-data app-scene ::ui/refresh-requested?)] (when refresh-requested? (ui/user-data! app-scene ::ui/refresh-requested? false) (refresh-menus-and-toolbars! app-view app-scene) (refresh-views! app-view)) (refresh-scene-views! app-view) (refresh-app-title! stage project)))))] (ui/timer-stop-on-closed! stage refresh-timer) (ui/timer-start! refresh-timer)) (ui/on-closed! stage (fn [_] (dispose-scene-views! app-view))) app-view))) (defn- make-tab! [app-view prefs workspace project resource resource-node resource-type view-type make-view-fn ^ObservableList tabs opts] (let [parent (AnchorPane.) tab (doto (Tab. (tab-title resource false)) (.setContent parent) (.setTooltip (Tooltip. (or (resource/proj-path resource) "unknown"))) (ui/user-data! ::view-type view-type)) view-graph (g/make-graph! :history false :volatility 2) select-fn (partial select app-view) opts (merge opts (get (:view-opts resource-type) (:id view-type)) {:app-view app-view :select-fn select-fn :prefs prefs :project project :workspace workspace :tab tab}) view (make-view-fn view-graph parent resource-node opts)] (assert (g/node-instance? view/WorkbenchView view)) (g/transact (concat (view/connect-resource-node view resource-node) (g/connect view :view-data app-view :open-views) (g/connect view :view-dirty? app-view :open-dirty-views))) (ui/user-data! tab ::view view) (.add tabs tab) (g/transact (select app-view resource-node [resource-node])) (.setGraphic tab (icons/get-image-view (or (:icon resource-type) "icons/64/Icons_29-AT-Unknown.png") 16)) (.addAll (.getStyleClass tab) ^Collection (resource/style-classes resource)) (ui/register-tab-toolbar tab "#toolbar" :toolbar) (let [close-handler (.getOnClosed tab)] (.setOnClosed tab (ui/event-handler event ;; The menu refresh can occur after the view graph is ;; deleted but before the tab controls lose input ;; focus, causing handlers to evaluate against deleted ;; graph nodes. Using run-later here prevents this. (ui/run-later (doto tab (ui/user-data! ::view-type nil) (ui/user-data! ::view nil)) (g/delete-graph! view-graph)) (when close-handler (.handle close-handler event))))) tab)) (defn- substitute-args [tmpl args] (reduce (fn [tmpl [key val]] (string/replace tmpl (format "{%s}" (name key)) (str val))) tmpl args)) (defn open-resource ([app-view prefs workspace project resource] (open-resource app-view prefs workspace project resource {})) ([app-view prefs workspace project resource opts] (let [resource-type (resource/resource-type resource) resource-node (or (project/get-resource-node project resource) (throw (ex-info (format "No resource node found for resource '%s'" (resource/proj-path resource)) {}))) text-view-type (workspace/get-view-type workspace :text) view-type (or (:selected-view-type opts) (if (nil? resource-type) (placeholder-resource/view-type workspace) (first (:view-types resource-type))) text-view-type)] (if (resource-node/defective? resource-node) (do (dialogs/make-info-dialog {:title "Unable to Open Resource" :icon :icon/triangle-error :header (format "Unable to open '%s', since it appears damaged" (resource/proj-path resource))}) false) (if-let [custom-editor (and (#{:code :text} (:id view-type)) (let [ed-pref (some-> (prefs/get-prefs prefs "code-custom-editor" "") string/trim)] (and (not (string/blank? ed-pref)) ed-pref)))] (let [cursor-range (:cursor-range opts) arg-tmpl (string/trim (if cursor-range (prefs/get-prefs prefs "code-open-file-at-line" "{file}:{line}") (prefs/get-prefs prefs "code-open-file" "{file}"))) arg-sub (cond-> {:file (resource/abs-path resource)} cursor-range (assoc :line (CursorRange->line-number cursor-range))) args (->> (string/split arg-tmpl #" ") (map #(substitute-args % arg-sub)))] (doto (ProcessBuilder. ^List (cons custom-editor args)) (.directory (workspace/project-path workspace)) (.start)) false) (if (contains? view-type :make-view-fn) (let [^SplitPane editor-tabs-split (g/node-value app-view :editor-tabs-split) tab-panes (.getItems editor-tabs-split) open-tabs (mapcat #(.getTabs ^TabPane %) tab-panes) view-type (if (g/node-value resource-node :editable?) view-type text-view-type) make-view-fn (:make-view-fn view-type) ^Tab tab (or (some #(when (and (= (tab->resource-node %) resource-node) (= view-type (ui/user-data % ::view-type))) %) open-tabs) (let [^TabPane active-tab-pane (g/node-value app-view :active-tab-pane) active-tab-pane-tabs (.getTabs active-tab-pane)] (make-tab! app-view prefs workspace project resource resource-node resource-type view-type make-view-fn active-tab-pane-tabs opts)))] (.select (.getSelectionModel (.getTabPane tab)) tab) (when-let [focus (:focus-fn view-type)] ;; Force layout pass since the focus function of some views ;; needs proper width + height (f.i. code view for ;; scrolling to selected line). (NodeHelper/layoutNodeForPrinting (.getRoot ^Scene (g/node-value app-view :scene))) (focus (ui/user-data tab ::view) opts)) ;; Do an initial rendering so it shows up as fast as possible. (ui/run-later (refresh-scene-views! app-view) (ui/run-later (slog/smoke-log "opened-resource"))) true) (let [^String path (or (resource/abs-path resource) (resource/temp-path resource)) ^File f (File. path)] (ui/open-file f (fn [msg] (ui/run-later (dialogs/make-info-dialog {:title "Could Not Open File" :icon :icon/triangle-error :header (format "Could not open '%s'" (.getName f)) :content (str "This can happen if the file type is not mapped to an application in your OS.\n\nUnderlying error from the OS:\n" msg)})))) false))))))) (handler/defhandler :open :global (active? [selection user-data] (:resources user-data (not-empty (selection->openable-resources selection)))) (enabled? [selection user-data] (some resource/exists? (:resources user-data (selection->openable-resources selection)))) (run [selection app-view prefs workspace project user-data] (doseq [resource (filter resource/exists? (:resources user-data (selection->openable-resources selection)))] (open-resource app-view prefs workspace project resource)))) (handler/defhandler :open-as :global (active? [selection] (selection->single-openable-resource selection)) (enabled? [selection user-data] (resource/exists? (selection->single-openable-resource selection))) (run [selection app-view prefs workspace project user-data] (let [resource (selection->single-openable-resource selection)] (open-resource app-view prefs workspace project resource (when-let [view-type (:selected-view-type user-data)] {:selected-view-type view-type})))) (options [workspace selection user-data] (when-not user-data (let [resource (selection->single-openable-resource selection) resource-type (resource/resource-type resource)] (map (fn [vt] {:label (or (:label vt) "External Editor") :command :open-as :user-data {:selected-view-type vt}}) (:view-types resource-type)))))) (handler/defhandler :synchronize :global (enabled? [] (disk-availability/available?)) (run [changes-view project workspace app-view] (let [render-reload-progress! (make-render-task-progress :resource-sync) render-save-progress! (make-render-task-progress :save-all)] (if (changes-view/project-is-git-repo? changes-view) ;; The project is a Git repo. ;; Check if there are locked files below the project folder before proceeding. ;; If so, we abort the sync and notify the user, since this could cause problems. (when (changes-view/ensure-no-locked-files! changes-view) (disk/async-save! render-reload-progress! render-save-progress! project changes-view (fn [successful?] (when successful? (ui/user-data! (g/node-value app-view :scene) ::ui/refresh-requested? true) (when (changes-view/regular-sync! changes-view) (disk/async-reload! render-reload-progress! workspace [] changes-view)))))) ;; The project is not a Git repo. ;; Show a dialog with info about how to set this up. (dialogs/make-info-dialog {:title "Version Control" :size :default :icon :icon/git :header "This project does not use Version Control" :content {:fx/type :text-flow :style-class "dialog-content-padding" :children [{:fx/type :text :text (str "A project under Version Control " "keeps a history of changes and " "enables you to collaborate with " "others by pushing changes to a " "server.\n\nYou can read about " "how to configure Version Control " "in the ")} {:fx/type :hyperlink :text "Defold Manual" :on-action (fn [_] (ui/open-url "https://www.defold.com/manuals/version-control/"))} {:fx/type :text :text "."}]}}))))) (handler/defhandler :save-all :global (enabled? [] (not (bob/build-in-progress?))) (run [app-view changes-view project] (let [render-reload-progress! (make-render-task-progress :resource-sync) render-save-progress! (make-render-task-progress :save-all)] (disk/async-save! render-reload-progress! render-save-progress! project changes-view (fn [successful?] (when successful? (ui/user-data! (g/node-value app-view :scene) ::ui/refresh-requested? true))))))) (handler/defhandler :show-in-desktop :global (active? [app-view selection evaluation-context] (context-resource app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource app-view selection evaluation-context)] (and (resource/abs-path r) (or (resource/exists? r) (empty? (resource/path r)))))) (run [app-view selection] (when-let [r (context-resource app-view selection)] (let [f (File. (resource/abs-path r))] (ui/open-file (fs/to-folder f)))))) (handler/defhandler :referencing-files :global (active? [app-view selection evaluation-context] (context-resource-file app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/abs-path r) (resource/exists? r)))) (run [selection app-view prefs workspace project] (when-let [r (context-resource-file app-view selection)] (doseq [resource (dialogs/make-resource-dialog workspace project {:title "Referencing Files" :selection :multiple :ok-label "Open" :filter (format "refs:%s" (resource/proj-path r))})] (open-resource app-view prefs workspace project resource))))) (handler/defhandler :dependencies :global (active? [app-view selection evaluation-context] (context-resource-file app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/abs-path r) (resource/exists? r)))) (run [selection app-view prefs workspace project] (when-let [r (context-resource-file app-view selection)] (doseq [resource (dialogs/make-resource-dialog workspace project {:title "Dependencies" :selection :multiple :ok-label "Open" :filter (format "deps:%s" (resource/proj-path r))})] (open-resource app-view prefs workspace project resource))))) (handler/defhandler :toggle-pane-left :global (run [^Stage main-stage] (let [main-scene (.getScene main-stage)] (set-pane-visible! main-scene :left (not (pane-visible? main-scene :left)))))) (handler/defhandler :toggle-pane-right :global (run [^Stage main-stage] (let [main-scene (.getScene main-stage)] (set-pane-visible! main-scene :right (not (pane-visible? main-scene :right)))))) (handler/defhandler :toggle-pane-bottom :global (run [^Stage main-stage] (let [main-scene (.getScene main-stage)] (set-pane-visible! main-scene :bottom (not (pane-visible? main-scene :bottom)))))) (handler/defhandler :show-console :global (run [^Stage main-stage tool-tab-pane] (show-console! (.getScene main-stage) tool-tab-pane))) (handler/defhandler :show-curve-editor :global (run [^Stage main-stage tool-tab-pane] (show-curve-editor! (.getScene main-stage) tool-tab-pane))) (handler/defhandler :show-build-errors :global (run [^Stage main-stage tool-tab-pane] (show-build-errors! (.getScene main-stage) tool-tab-pane))) (handler/defhandler :show-search-results :global (run [^Stage main-stage tool-tab-pane] (show-search-results! (.getScene main-stage) tool-tab-pane))) (defn- put-on-clipboard! [s] (doto (Clipboard/getSystemClipboard) (.setContent (doto (ClipboardContent.) (.putString s))))) (handler/defhandler :copy-project-path :global (active? [app-view selection evaluation-context] (context-resource-file app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/proj-path r) (resource/exists? r)))) (run [selection app-view] (when-let [r (context-resource-file app-view selection)] (put-on-clipboard! (resource/proj-path r))))) (handler/defhandler :copy-full-path :global (active? [app-view selection evaluation-context] (context-resource-file app-view selection evaluation-context)) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/abs-path r) (resource/exists? r)))) (run [selection app-view] (when-let [r (context-resource-file app-view selection)] (put-on-clipboard! (resource/abs-path r))))) (handler/defhandler :copy-require-path :global (active? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (= "lua" (resource/type-ext r)))) (enabled? [app-view selection evaluation-context] (when-let [r (context-resource-file app-view selection evaluation-context)] (and (resource/proj-path r) (resource/exists? r)))) (run [selection app-view] (when-let [r (context-resource-file app-view selection)] (put-on-clipboard! (lua/path->lua-module (resource/proj-path r)))))) (defn- gen-tooltip [workspace project app-view resource] (let [resource-type (resource/resource-type resource) view-type (or (first (:view-types resource-type)) (workspace/get-view-type workspace :text))] (when-let [make-preview-fn (:make-preview-fn view-type)] (let [tooltip (Tooltip.)] (doto tooltip (.setGraphic (doto (ImageView.) (.setScaleY -1.0))) (.setOnShowing (ui/event-handler e (let [image-view ^ImageView (.getGraphic tooltip)] (when-not (.getImage image-view) (let [resource-node (project/get-resource-node project resource) view-graph (g/make-graph! :history false :volatility 2) select-fn (partial select app-view) opts (assoc ((:id view-type) (:view-opts resource-type)) :app-view app-view :select-fn select-fn :project project :workspace workspace) preview (make-preview-fn view-graph resource-node opts 256 256)] (.setImage image-view ^Image (g/node-value preview :image)) (when-some [dispose-preview-fn (:dispose-preview-fn view-type)] (dispose-preview-fn preview)) (g/delete-graph! view-graph))))))))))) (def ^:private open-assets-term-prefs-key "PI:KEY:<KEY>END_PI") (defn- query-and-open! [workspace project app-view prefs term] (let [prev-filter-term (prefs/get-prefs prefs open-assets-term-prefs-key nil) filter-term-atom (atom prev-filter-term) selected-resources (dialogs/make-resource-dialog workspace project (cond-> {:title "Open Assets" :accept-fn resource/editable-resource? :selection :multiple :ok-label "Open" :filter-atom filter-term-atom :tooltip-gen (partial gen-tooltip workspace project app-view)} (some? term) (assoc :filter term))) filter-term @filter-term-atom] (when (not= prev-filter-term filter-term) (prefs/set-prefs prefs open-assets-term-prefs-key filter-term)) (doseq [resource selected-resources] (open-resource app-view prefs workspace project resource)))) (handler/defhandler :select-items :global (run [user-data] (dialogs/make-select-list-dialog (:items user-data) (:options user-data)))) (defn- get-view-text-selection [{:keys [view-id view-type]}] (when-let [text-selection-fn (:text-selection-fn view-type)] (text-selection-fn view-id))) (handler/defhandler :open-asset :global (run [workspace project app-view prefs] (let [term (get-view-text-selection (g/node-value app-view :active-view-info))] (query-and-open! workspace project app-view prefs term)))) (handler/defhandler :search-in-files :global (run [project app-view prefs search-results-view main-stage tool-tab-pane] (when-let [term (get-view-text-selection (g/node-value app-view :active-view-info))] (search-results-view/set-search-term! prefs term)) (let [main-scene (.getScene ^Stage main-stage) show-search-results-tab! (partial show-search-results! main-scene tool-tab-pane)] (search-results-view/show-search-in-files-dialog! search-results-view project prefs show-search-results-tab!)))) (defn- bundle! [main-stage tool-tab-pane changes-view build-errors-view project prefs platform bundle-options] (g/user-data! project :last-bundle-options (assoc bundle-options :platform-key platform)) (let [main-scene (.getScene ^Stage main-stage) output-directory ^File (:output-directory bundle-options) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view) render-reload-progress! (make-render-task-progress :resource-sync) render-save-progress! (make-render-task-progress :save-all) render-build-progress! (make-render-task-progress :build) task-cancelled? (make-task-cancelled-query :build) bob-args (bob/bundle-bob-args prefs platform bundle-options)] (when-not (.exists output-directory) (fs/create-directories! output-directory)) (build-errors-view/clear-build-errors build-errors-view) (disk/async-bob-build! render-reload-progress! render-save-progress! render-build-progress! task-cancelled? render-build-error! bob/bundle-bob-commands bob-args project changes-view (fn [successful?] (when successful? (if (some-> output-directory .isDirectory) (ui/open-file output-directory) (dialogs/make-info-dialog {:title "Bundle Failed" :icon :icon/triangle-error :size :large :header "Failed to bundle project, please fix build errors and try again"}))))))) (handler/defhandler :bundle :global (run [user-data workspace project prefs app-view changes-view build-errors-view main-stage tool-tab-pane] (let [owner-window (g/node-value app-view :stage) platform (:platform user-data) bundle! (partial bundle! main-stage tool-tab-pane changes-view build-errors-view project prefs platform)] (bundle-dialog/show-bundle-dialog! workspace platform prefs owner-window bundle!)))) (handler/defhandler :rebundle :global (enabled? [project] (some? (g/user-data project :last-bundle-options))) (run [workspace project prefs app-view changes-view build-errors-view main-stage tool-tab-pane] (let [last-bundle-options (g/user-data project :last-bundle-options) platform (:platform-key last-bundle-options)] (bundle! main-stage tool-tab-pane changes-view build-errors-view project prefs platform last-bundle-options)))) (def ^:private editor-extensions-allowed-commands-prefs-key "editor-extensions/allowed-commands") (defn make-extensions-ui [workspace changes-view prefs] (reify extensions/UI (reload-resources! [_] (let [success-promise (promise)] (disk/async-reload! (make-render-task-progress :resource-sync) workspace [] changes-view success-promise) (when-not @success-promise (throw (ex-info "Reload failed" {}))))) (can-execute? [_ [cmd-name :as command]] (let [allowed-commands (prefs/get-prefs prefs editor-extensions-allowed-commands-prefs-key #{})] (if (allowed-commands cmd-name) true (let [allow (ui/run-now (dialogs/make-confirmation-dialog {:title "Allow executing shell command?" :icon {:fx/type fxui/icon :type :icon/triangle-error :fill "#fa6731"} :header "Extension wants to execute a shell command" :content {:fx/type fxui/label :style-class "dialog-content-padding" :text (string/join " " command)} :buttons [{:text "Abort Command" :cancel-button true :default-button true :result false} {:text "Allow" :variant :danger :result true}]}))] (when allow (prefs/set-prefs prefs editor-extensions-allowed-commands-prefs-key (conj allowed-commands cmd-name))) allow)))) (display-output! [_ type string] (let [[console-type prefix] (case type :err [:extension-err "ERROR:EXT: "] :out [:extension-out ""])] (doseq [line (string/split-lines string)] (console/append-console-entry! console-type (str prefix line))))) (on-transact-thread [_ f] (ui/run-now (f))))) (defn- fetch-libraries [workspace project changes-view prefs] (let [library-uris (project/project-dependencies project) hosts (into #{} (map url/strip-path) library-uris)] (if-let [first-unreachable-host (first-where (complement url/reachable?) hosts)] (dialogs/make-info-dialog {:title "Fetch Failed" :icon :icon/triangle-error :size :large :header "Fetch was aborted because a host could not be reached" :content (str "Unreachable host: " first-unreachable-host "\n\nPlease verify internet connection and try again.")}) (future (error-reporting/catch-all! (ui/with-progress [render-fetch-progress! (make-render-task-progress :fetch-libraries)] (when (workspace/dependencies-reachable? library-uris) (let [lib-states (workspace/fetch-and-validate-libraries workspace library-uris render-fetch-progress!) render-install-progress! (make-render-task-progress :resource-sync)] (render-install-progress! (progress/make "Installing updated libraries...")) (ui/run-later (workspace/install-validated-libraries! workspace library-uris lib-states) (disk/async-reload! render-install-progress! workspace [] changes-view (fn [success] (when success (extensions/reload! project :library (make-extensions-ui workspace changes-view prefs)))))))))))))) (handler/defhandler :add-dependency :global (enabled? [] (disk-availability/available?)) (run [selection app-view prefs workspace project changes-view user-data] (let [game-project (project/get-resource-node project "/game.project") dependencies (game-project/get-setting game-project ["project" "dependencies"]) dependency-uri (.toURI (URL. (:dep-url user-data)))] (when (not-any? (partial = dependency-uri) dependencies) (game-project/set-setting! game-project ["project" "dependencies"] (conj (vec dependencies) dependency-uri)) (fetch-libraries workspace project changes-view prefs))))) (handler/defhandler :fetch-libraries :global (enabled? [] (disk-availability/available?)) (run [workspace project changes-view prefs] (fetch-libraries workspace project changes-view prefs))) (handler/defhandler :reload-extensions :global (enabled? [] (disk-availability/available?)) (run [project workspace changes-view prefs] (extensions/reload! project :all (make-extensions-ui workspace changes-view prefs)))) (defn- create-and-open-live-update-settings! [app-view changes-view prefs project] (let [workspace (project/workspace project) project-path (workspace/project-path workspace) settings-file (io/file project-path "liveupdate.settings") render-reload-progress! (make-render-task-progress :resource-sync)] (spit settings-file "[liveupdate]\n") (disk/async-reload! render-reload-progress! workspace [] changes-view (fn [successful?] (when successful? (when-some [created-resource (workspace/find-resource workspace "/liveupdate.settings")] (open-resource app-view prefs workspace project created-resource))))))) (handler/defhandler :live-update-settings :global (enabled? [] (disk-availability/available?)) (run [app-view changes-view prefs workspace project] (if-some [existing-resource (workspace/find-resource workspace (live-update-settings/get-live-update-settings-path project))] (open-resource app-view prefs workspace project existing-resource) (create-and-open-live-update-settings! app-view changes-view prefs project)))) (handler/defhandler :sign-ios-app :global (active? [] (util/is-mac-os?)) (run [workspace project prefs build-errors-view main-stage tool-tab-pane] (build-errors-view/clear-build-errors build-errors-view) (let [result (bundle/make-sign-dialog workspace prefs project)] (when-let [error (:error result)] (g/with-auto-evaluation-context evaluation-context (let [main-scene (.getScene ^Stage main-stage) render-build-error! (make-render-build-error main-scene tool-tab-pane build-errors-view)] (if (engine-build-errors/handle-build-error! render-build-error! project evaluation-context error) (dialogs/make-info-dialog {:title "Build Failed" :icon :icon/triangle-error :header "Failed to build ipa with native extensions, please fix build errors and try again"}) (do (error-reporting/report-exception! error) (when-let [message (:message result)] (dialogs/make-info-dialog {:title "Error" :icon :icon/triangle-error :header message}))))))))))
[ { "context": "aradigms of AI Programming\n;;;; Copyright (c) 1991 Peter Norvig\n\n;;;; File prolog.lisp: prolog from (11.3), with ", "end": 79, "score": 0.9997673034667969, "start": 67, "tag": "NAME", "value": "Peter Norvig" }, { "context": "- (:member :?x (1 2 3))))\n\n(comment\n\n (<- (:likes Kim Robin))\n (<- (:likes Sandy Lee))\n (<- (:likes S", "end": 5831, "score": 0.9995524883270264, "start": 5828, "tag": "NAME", "value": "Kim" }, { "context": "member :?x (1 2 3))))\n\n(comment\n\n (<- (:likes Kim Robin))\n (<- (:likes Sandy Lee))\n (<- (:likes Sandy K", "end": 5837, "score": 0.9555596709251404, "start": 5832, "tag": "NAME", "value": "Robin" }, { "context": "\n(comment\n\n (<- (:likes Kim Robin))\n (<- (:likes Sandy Lee))\n (<- (:likes Sandy Kim))\n (<- (:likes Robin c", "end": 5863, "score": 0.9913966059684753, "start": 5854, "tag": "NAME", "value": "Sandy Lee" }, { "context": "im Robin))\n (<- (:likes Sandy Lee))\n (<- (:likes Sandy Kim))\n (<- (:likes Robin cats))\n (<- (:likes Sa", "end": 5885, "score": 0.9988397359848022, "start": 5880, "tag": "NAME", "value": "Sandy" }, { "context": "in))\n (<- (:likes Sandy Lee))\n (<- (:likes Sandy Kim))\n (<- (:likes Robin cats))\n (<- (:likes Sandy ", "end": 5889, "score": 0.9578039646148682, "start": 5886, "tag": "NAME", "value": "Kim" }, { "context": "andy Lee))\n (<- (:likes Sandy Kim))\n (<- (:likes Robin cats))\n (<- (:likes Sandy :?x) (:likes :?x cats)", "end": 5911, "score": 0.9992749094963074, "start": 5906, "tag": "NAME", "value": "Robin" }, { "context": "ndy Kim))\n (<- (:likes Robin cats))\n (<- (:likes Sandy :?x) (:likes :?x cats))\n (<- (:likes Kim :?x) (:", "end": 5938, "score": 0.9986878633499146, "start": 5933, "tag": "NAME", "value": "Sandy" }, { "context": ":likes Sandy :?x) (:likes :?x cats))\n (<- (:likes Kim :?x) (:likes :?x Lee) (:likes :?x Kim))\n (<- (:l", "end": 5980, "score": 0.9971144199371338, "start": 5977, "tag": "NAME", "value": "Kim" }, { "context": "ikes :?x cats))\n (<- (:likes Kim :?x) (:likes :?x Lee) (:likes :?x Kim))\n (<- (:likes :?x :?x))\n\n (?-", "end": 6001, "score": 0.9976407289505005, "start": 5998, "tag": "NAME", "value": "Lee" }, { "context": " (<- (:likes Kim :?x) (:likes :?x Lee) (:likes :?x Kim))\n (<- (:likes :?x :?x))\n\n (?- (:likes Sandy :?", "end": 6018, "score": 0.9943616986274719, "start": 6015, "tag": "NAME", "value": "Kim" }, { "context": "s :?x Kim))\n (<- (:likes :?x :?x))\n\n (?- (:likes Sandy :?who))\n (?- (:likes :?who Sandy))\n (?- (:likes", "end": 6065, "score": 0.9970675706863403, "start": 6060, "tag": "NAME", "value": "Sandy" }, { "context": ")\n\n (?- (:likes Sandy :?who))\n (?- (:likes :?who Sandy))\n (?- (:likes :?x :?y) (:likes :?y :?x)))\n\n(com", "end": 6099, "score": 0.9944012761116028, "start": 6094, "tag": "NAME", "value": "Sandy" } ]
clojure/src/prolog.cljc
jfacorro/paip-lisp
0
;;;; Code from Paradigms of AI Programming ;;;; Copyright (c) 1991 Peter Norvig ;;;; File prolog.lisp: prolog from (11.3), with interactive backtracking. (ns prolog ; does not require "prolog1" (:require [unify :as u] [patmatch :as p] [clojure.walk :as walk] [clojure.string :as str])) ;;;; does not include destructive unification (11.6); see prologc.lisp (declare prove-all show-prolog-vars) (def db-clauses "clauses are stored on the predicate's plist" (atom {:show-prolog-vars #'show-prolog-vars})) (def db-predicates "a list of all predicates stored in the database." (atom #{})) ;; clauses are represented as (head . body) cons cells (defn clause-head [clause] (first clause)) (defn clause-body [clause] (next clause)) ;; clauses are stored on the predicate's plist (defn get-clauses [pred] (@db-clauses pred)) (defn predicate [relation] (first relation)) (defn args "The arguments of a relation" [x] (next x)) (defn unique-find-anywhere-if "return a list of leaves of tree satisfying predicate, with duplicates removed." ([predicate tree] (unique-find-anywhere-if predicate tree #{})) ([predicate tree found-so-far] (cond (seq? tree) (unique-find-anywhere-if predicate (first tree) (unique-find-anywhere-if predicate (next tree) found-so-far)) (predicate tree) (conj found-so-far tree) :else found-so-far))) (defn non-anon-variable? [x] (and (p/variable? x) (not (= x :?)))) (defn variables-in "Return a list of all the variables in EXP." [exp] (unique-find-anywhere-if non-anon-variable? exp)) (defn replace-?-vars [exp] "Replace any ? within exp with a var of the form ?123." (cond (= exp :?) (keyword (gensym "?")) (and (seq? exp) (seq exp)) (cons (replace-?-vars (first exp)) (replace-?-vars (next exp))) :else exp)) (defmacro <- "add a clause to the data base." [& clause] (p/dbg :<- clause) `(add-clause '~(replace-?-vars clause))) (defn add-clause "add a clause to the data base, indexed by head's predicate." [clause] ;; the predicate must be a non-variable keyword. (p/dbg :add-clause clause) (let [pred (predicate (clause-head clause))] (assert (and (keyword? pred) (not (p/variable? pred)))) (swap! db-predicates conj pred) (swap! db-clauses update-in [pred] (fnil conj []) clause) pred)) (defn clear-predicate "remove the clauses for a single predicate." [predicate] (swap! db-clauses dissoc predicate)) (defn clear-db "remove all clauses (for all predicates) from the data base." [] (map clear-predicate @db-predicates)) (defn rename-variables "replace all variables in x with new ones." [x] (walk/prewalk-replace (reduce #(assoc %1 %2 (keyword (gensym (name %2)))) {} (variables-in x)) x)) #_(defn find-anywhere-if "does predicate apply to any non seq in the tree?" [predicate tree] (if (and (seq? tree) #_(not (empty? tree))) (or (find-anywhere-if predicate (first tree)) (find-anywhere-if predicate (next tree))) (predicate tree))) (defn continue? [] "Ask user if we should continue looking for solutions." (case (str/trimr (read-line)) ";" true "." nil "\n" (continue?) (do (println " Type ; to see more or . to stop") (continue?)))) (defn prove "Return a list of possible solutions to goal." [goal bindings other-goals] (p/dbg :prove :goal goal :bindings bindings :other-goals other-goals) (let [pred (predicate goal) clauses (or (get-clauses pred) [])] (p/dbg :prove :clauses clauses :predicate pred) (if (vector? clauses) (some (fn [clause] (p/dbg :prove :some-fn :clause clause) (let [new-clause (rename-variables clause) unification (u/unify goal (clause-head new-clause) bindings)] (p/dbg :prove :some-fn :new-clause new-clause :bindings bindings) (p/dbg :prove :some-fn :unify goal (clause-head new-clause) bindings :result unification ) (prove-all (concat (clause-body new-clause) other-goals) unification))) clauses) ;; The predicate's "clauses" can be an atom: ;; a primitive function to call (clauses (next goal) bindings other-goals)))) (defn prove-all "Find a solution to the conjunction of goals." [goals bindings] (p/dbg :prove-all :goal goals :bindings bindings) (cond (nil? bindings) nil (nil? goals) bindings :else (prove (first goals) bindings (next goals)))) (defn show-prolog-vars "Print each variable with its binding. Then ask the user if more solutions are desired." [vars bindings other-goals] (p/dbg :show-prolog-vars :vars vars :bindings bindings :other-goals other-goals) (if-not vars (print "\nYes") (doseq [x vars] (print "\n" x " = " (u/subst-bindings bindings x)))) (flush) (if (continue?) nil (prove-all other-goals bindings))) (defn top-level-prove [goals] (prove-all `(~@goals (:show-prolog-vars ~@(variables-in goals))) {}) (println "\nNo.")) (defmacro ?- [& goals] `(top-level-prove '~(replace-?-vars goals))) ;;------------------------------------------------------------------------------ ;; Examples ;;------------------------------------------------------------------------------ (comment (<- (:member :?item (:?item & :?rest))) (<- (:member :?item (:?x & :?rest)) (:member :?item :?rest)) (?- (:member 4 (1 2 3))) (?- (:member 2 (1 2 3))) (?- (:member 2 (1 2 3 2 1))) (?- (:member 2 :?list)) (?- (:member :?x (1 2 3)))) (comment (<- (:likes Kim Robin)) (<- (:likes Sandy Lee)) (<- (:likes Sandy Kim)) (<- (:likes Robin cats)) (<- (:likes Sandy :?x) (:likes :?x cats)) (<- (:likes Kim :?x) (:likes :?x Lee) (:likes :?x Kim)) (<- (:likes :?x :?x)) (?- (:likes Sandy :?who)) (?- (:likes :?who Sandy)) (?- (:likes :?x :?y) (:likes :?y :?x))) (comment (<- (:length () 0)) (<- (:length (:?x & :?y) (1 + :?n)) (:length :?y :?n)) (?- (:length (a b c d) :?n)) (?- (:length :?list (1 + (1 + 0)))) (?- (:length :?list :?n)) ) (comment (<- (:member :?item (:?item & :?rest))) (<- (:member :?item (:?x & :?rest)) (:member :?item :?rest)) (<- (:nextto :?x :?y :?list) (:iright :?y :?x :?list)) (<- (:nextto :?x :?y :?list) (:iright :?x :?y :?list)) (<- (:iright :?left :?right (:?left :?right & :?rest))) (<- (:iright :?left :?right (:?x & :?rest)) (:iright :?left :?right :?rest)) (<- (:= :?x :?x)) (<- (:zebra :?h :?w :?z) ;; Each house is of the form: ;; (house nationality pet cigarette drink house-color) (:= :?h ((house norwegian :? :? :? :?) ;1,10 :? (house :? :? :? milk :?) :? :?)) ; 9 (:member (house englishman :? :? :? red) :?h) ; 2 (:member (house spaniard dog :? :? :?) :?h) ; 3 (:member (house :? :? :? coffee green) :?h) ; 4 (:member (house ukrainian :? :? tea :?) :?h) ; 5 (:iright (house :? :? :? :? ivory) ; 6 (house :? :? :? :? green) :?h) (:member (house :? snails winston :? :?) :?h) ; 7 (:member (house :? :? kools :? yellow) :?h) ; 8 (:nextto (house :? :? chesterfield :? :?) ;11 (house :? fox :? :? :?) :?h) (:nextto (house :? :? kools :? :?) ;12 (house :? horse :? :? :?) :?h) (:member (house :? :? luckystrike orange-juice :?) :?h);13 (:member (house japanese :? parliaments :? :?) :?h) ;14 (:nextto (house norwegian :? :? :? :?) ;15 (house :? :? :? :? blue) :?h) ;; Now for the questions: (:member (house :?w :? :? water :?) :?h) ;Q1 (:member (house :?z zebra :? :? :?) :?h)) ;Q2 (?- (:zebra :?houses :?water-drinker :?zebra-owner)) )
17463
;;;; Code from Paradigms of AI Programming ;;;; Copyright (c) 1991 <NAME> ;;;; File prolog.lisp: prolog from (11.3), with interactive backtracking. (ns prolog ; does not require "prolog1" (:require [unify :as u] [patmatch :as p] [clojure.walk :as walk] [clojure.string :as str])) ;;;; does not include destructive unification (11.6); see prologc.lisp (declare prove-all show-prolog-vars) (def db-clauses "clauses are stored on the predicate's plist" (atom {:show-prolog-vars #'show-prolog-vars})) (def db-predicates "a list of all predicates stored in the database." (atom #{})) ;; clauses are represented as (head . body) cons cells (defn clause-head [clause] (first clause)) (defn clause-body [clause] (next clause)) ;; clauses are stored on the predicate's plist (defn get-clauses [pred] (@db-clauses pred)) (defn predicate [relation] (first relation)) (defn args "The arguments of a relation" [x] (next x)) (defn unique-find-anywhere-if "return a list of leaves of tree satisfying predicate, with duplicates removed." ([predicate tree] (unique-find-anywhere-if predicate tree #{})) ([predicate tree found-so-far] (cond (seq? tree) (unique-find-anywhere-if predicate (first tree) (unique-find-anywhere-if predicate (next tree) found-so-far)) (predicate tree) (conj found-so-far tree) :else found-so-far))) (defn non-anon-variable? [x] (and (p/variable? x) (not (= x :?)))) (defn variables-in "Return a list of all the variables in EXP." [exp] (unique-find-anywhere-if non-anon-variable? exp)) (defn replace-?-vars [exp] "Replace any ? within exp with a var of the form ?123." (cond (= exp :?) (keyword (gensym "?")) (and (seq? exp) (seq exp)) (cons (replace-?-vars (first exp)) (replace-?-vars (next exp))) :else exp)) (defmacro <- "add a clause to the data base." [& clause] (p/dbg :<- clause) `(add-clause '~(replace-?-vars clause))) (defn add-clause "add a clause to the data base, indexed by head's predicate." [clause] ;; the predicate must be a non-variable keyword. (p/dbg :add-clause clause) (let [pred (predicate (clause-head clause))] (assert (and (keyword? pred) (not (p/variable? pred)))) (swap! db-predicates conj pred) (swap! db-clauses update-in [pred] (fnil conj []) clause) pred)) (defn clear-predicate "remove the clauses for a single predicate." [predicate] (swap! db-clauses dissoc predicate)) (defn clear-db "remove all clauses (for all predicates) from the data base." [] (map clear-predicate @db-predicates)) (defn rename-variables "replace all variables in x with new ones." [x] (walk/prewalk-replace (reduce #(assoc %1 %2 (keyword (gensym (name %2)))) {} (variables-in x)) x)) #_(defn find-anywhere-if "does predicate apply to any non seq in the tree?" [predicate tree] (if (and (seq? tree) #_(not (empty? tree))) (or (find-anywhere-if predicate (first tree)) (find-anywhere-if predicate (next tree))) (predicate tree))) (defn continue? [] "Ask user if we should continue looking for solutions." (case (str/trimr (read-line)) ";" true "." nil "\n" (continue?) (do (println " Type ; to see more or . to stop") (continue?)))) (defn prove "Return a list of possible solutions to goal." [goal bindings other-goals] (p/dbg :prove :goal goal :bindings bindings :other-goals other-goals) (let [pred (predicate goal) clauses (or (get-clauses pred) [])] (p/dbg :prove :clauses clauses :predicate pred) (if (vector? clauses) (some (fn [clause] (p/dbg :prove :some-fn :clause clause) (let [new-clause (rename-variables clause) unification (u/unify goal (clause-head new-clause) bindings)] (p/dbg :prove :some-fn :new-clause new-clause :bindings bindings) (p/dbg :prove :some-fn :unify goal (clause-head new-clause) bindings :result unification ) (prove-all (concat (clause-body new-clause) other-goals) unification))) clauses) ;; The predicate's "clauses" can be an atom: ;; a primitive function to call (clauses (next goal) bindings other-goals)))) (defn prove-all "Find a solution to the conjunction of goals." [goals bindings] (p/dbg :prove-all :goal goals :bindings bindings) (cond (nil? bindings) nil (nil? goals) bindings :else (prove (first goals) bindings (next goals)))) (defn show-prolog-vars "Print each variable with its binding. Then ask the user if more solutions are desired." [vars bindings other-goals] (p/dbg :show-prolog-vars :vars vars :bindings bindings :other-goals other-goals) (if-not vars (print "\nYes") (doseq [x vars] (print "\n" x " = " (u/subst-bindings bindings x)))) (flush) (if (continue?) nil (prove-all other-goals bindings))) (defn top-level-prove [goals] (prove-all `(~@goals (:show-prolog-vars ~@(variables-in goals))) {}) (println "\nNo.")) (defmacro ?- [& goals] `(top-level-prove '~(replace-?-vars goals))) ;;------------------------------------------------------------------------------ ;; Examples ;;------------------------------------------------------------------------------ (comment (<- (:member :?item (:?item & :?rest))) (<- (:member :?item (:?x & :?rest)) (:member :?item :?rest)) (?- (:member 4 (1 2 3))) (?- (:member 2 (1 2 3))) (?- (:member 2 (1 2 3 2 1))) (?- (:member 2 :?list)) (?- (:member :?x (1 2 3)))) (comment (<- (:likes <NAME> <NAME>)) (<- (:likes <NAME>)) (<- (:likes <NAME> <NAME>)) (<- (:likes <NAME> cats)) (<- (:likes <NAME> :?x) (:likes :?x cats)) (<- (:likes <NAME> :?x) (:likes :?x <NAME>) (:likes :?x <NAME>)) (<- (:likes :?x :?x)) (?- (:likes <NAME> :?who)) (?- (:likes :?who <NAME>)) (?- (:likes :?x :?y) (:likes :?y :?x))) (comment (<- (:length () 0)) (<- (:length (:?x & :?y) (1 + :?n)) (:length :?y :?n)) (?- (:length (a b c d) :?n)) (?- (:length :?list (1 + (1 + 0)))) (?- (:length :?list :?n)) ) (comment (<- (:member :?item (:?item & :?rest))) (<- (:member :?item (:?x & :?rest)) (:member :?item :?rest)) (<- (:nextto :?x :?y :?list) (:iright :?y :?x :?list)) (<- (:nextto :?x :?y :?list) (:iright :?x :?y :?list)) (<- (:iright :?left :?right (:?left :?right & :?rest))) (<- (:iright :?left :?right (:?x & :?rest)) (:iright :?left :?right :?rest)) (<- (:= :?x :?x)) (<- (:zebra :?h :?w :?z) ;; Each house is of the form: ;; (house nationality pet cigarette drink house-color) (:= :?h ((house norwegian :? :? :? :?) ;1,10 :? (house :? :? :? milk :?) :? :?)) ; 9 (:member (house englishman :? :? :? red) :?h) ; 2 (:member (house spaniard dog :? :? :?) :?h) ; 3 (:member (house :? :? :? coffee green) :?h) ; 4 (:member (house ukrainian :? :? tea :?) :?h) ; 5 (:iright (house :? :? :? :? ivory) ; 6 (house :? :? :? :? green) :?h) (:member (house :? snails winston :? :?) :?h) ; 7 (:member (house :? :? kools :? yellow) :?h) ; 8 (:nextto (house :? :? chesterfield :? :?) ;11 (house :? fox :? :? :?) :?h) (:nextto (house :? :? kools :? :?) ;12 (house :? horse :? :? :?) :?h) (:member (house :? :? luckystrike orange-juice :?) :?h);13 (:member (house japanese :? parliaments :? :?) :?h) ;14 (:nextto (house norwegian :? :? :? :?) ;15 (house :? :? :? :? blue) :?h) ;; Now for the questions: (:member (house :?w :? :? water :?) :?h) ;Q1 (:member (house :?z zebra :? :? :?) :?h)) ;Q2 (?- (:zebra :?houses :?water-drinker :?zebra-owner)) )
true
;;;; Code from Paradigms of AI Programming ;;;; Copyright (c) 1991 PI:NAME:<NAME>END_PI ;;;; File prolog.lisp: prolog from (11.3), with interactive backtracking. (ns prolog ; does not require "prolog1" (:require [unify :as u] [patmatch :as p] [clojure.walk :as walk] [clojure.string :as str])) ;;;; does not include destructive unification (11.6); see prologc.lisp (declare prove-all show-prolog-vars) (def db-clauses "clauses are stored on the predicate's plist" (atom {:show-prolog-vars #'show-prolog-vars})) (def db-predicates "a list of all predicates stored in the database." (atom #{})) ;; clauses are represented as (head . body) cons cells (defn clause-head [clause] (first clause)) (defn clause-body [clause] (next clause)) ;; clauses are stored on the predicate's plist (defn get-clauses [pred] (@db-clauses pred)) (defn predicate [relation] (first relation)) (defn args "The arguments of a relation" [x] (next x)) (defn unique-find-anywhere-if "return a list of leaves of tree satisfying predicate, with duplicates removed." ([predicate tree] (unique-find-anywhere-if predicate tree #{})) ([predicate tree found-so-far] (cond (seq? tree) (unique-find-anywhere-if predicate (first tree) (unique-find-anywhere-if predicate (next tree) found-so-far)) (predicate tree) (conj found-so-far tree) :else found-so-far))) (defn non-anon-variable? [x] (and (p/variable? x) (not (= x :?)))) (defn variables-in "Return a list of all the variables in EXP." [exp] (unique-find-anywhere-if non-anon-variable? exp)) (defn replace-?-vars [exp] "Replace any ? within exp with a var of the form ?123." (cond (= exp :?) (keyword (gensym "?")) (and (seq? exp) (seq exp)) (cons (replace-?-vars (first exp)) (replace-?-vars (next exp))) :else exp)) (defmacro <- "add a clause to the data base." [& clause] (p/dbg :<- clause) `(add-clause '~(replace-?-vars clause))) (defn add-clause "add a clause to the data base, indexed by head's predicate." [clause] ;; the predicate must be a non-variable keyword. (p/dbg :add-clause clause) (let [pred (predicate (clause-head clause))] (assert (and (keyword? pred) (not (p/variable? pred)))) (swap! db-predicates conj pred) (swap! db-clauses update-in [pred] (fnil conj []) clause) pred)) (defn clear-predicate "remove the clauses for a single predicate." [predicate] (swap! db-clauses dissoc predicate)) (defn clear-db "remove all clauses (for all predicates) from the data base." [] (map clear-predicate @db-predicates)) (defn rename-variables "replace all variables in x with new ones." [x] (walk/prewalk-replace (reduce #(assoc %1 %2 (keyword (gensym (name %2)))) {} (variables-in x)) x)) #_(defn find-anywhere-if "does predicate apply to any non seq in the tree?" [predicate tree] (if (and (seq? tree) #_(not (empty? tree))) (or (find-anywhere-if predicate (first tree)) (find-anywhere-if predicate (next tree))) (predicate tree))) (defn continue? [] "Ask user if we should continue looking for solutions." (case (str/trimr (read-line)) ";" true "." nil "\n" (continue?) (do (println " Type ; to see more or . to stop") (continue?)))) (defn prove "Return a list of possible solutions to goal." [goal bindings other-goals] (p/dbg :prove :goal goal :bindings bindings :other-goals other-goals) (let [pred (predicate goal) clauses (or (get-clauses pred) [])] (p/dbg :prove :clauses clauses :predicate pred) (if (vector? clauses) (some (fn [clause] (p/dbg :prove :some-fn :clause clause) (let [new-clause (rename-variables clause) unification (u/unify goal (clause-head new-clause) bindings)] (p/dbg :prove :some-fn :new-clause new-clause :bindings bindings) (p/dbg :prove :some-fn :unify goal (clause-head new-clause) bindings :result unification ) (prove-all (concat (clause-body new-clause) other-goals) unification))) clauses) ;; The predicate's "clauses" can be an atom: ;; a primitive function to call (clauses (next goal) bindings other-goals)))) (defn prove-all "Find a solution to the conjunction of goals." [goals bindings] (p/dbg :prove-all :goal goals :bindings bindings) (cond (nil? bindings) nil (nil? goals) bindings :else (prove (first goals) bindings (next goals)))) (defn show-prolog-vars "Print each variable with its binding. Then ask the user if more solutions are desired." [vars bindings other-goals] (p/dbg :show-prolog-vars :vars vars :bindings bindings :other-goals other-goals) (if-not vars (print "\nYes") (doseq [x vars] (print "\n" x " = " (u/subst-bindings bindings x)))) (flush) (if (continue?) nil (prove-all other-goals bindings))) (defn top-level-prove [goals] (prove-all `(~@goals (:show-prolog-vars ~@(variables-in goals))) {}) (println "\nNo.")) (defmacro ?- [& goals] `(top-level-prove '~(replace-?-vars goals))) ;;------------------------------------------------------------------------------ ;; Examples ;;------------------------------------------------------------------------------ (comment (<- (:member :?item (:?item & :?rest))) (<- (:member :?item (:?x & :?rest)) (:member :?item :?rest)) (?- (:member 4 (1 2 3))) (?- (:member 2 (1 2 3))) (?- (:member 2 (1 2 3 2 1))) (?- (:member 2 :?list)) (?- (:member :?x (1 2 3)))) (comment (<- (:likes PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI)) (<- (:likes PI:NAME:<NAME>END_PI)) (<- (:likes PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI)) (<- (:likes PI:NAME:<NAME>END_PI cats)) (<- (:likes PI:NAME:<NAME>END_PI :?x) (:likes :?x cats)) (<- (:likes PI:NAME:<NAME>END_PI :?x) (:likes :?x PI:NAME:<NAME>END_PI) (:likes :?x PI:NAME:<NAME>END_PI)) (<- (:likes :?x :?x)) (?- (:likes PI:NAME:<NAME>END_PI :?who)) (?- (:likes :?who PI:NAME:<NAME>END_PI)) (?- (:likes :?x :?y) (:likes :?y :?x))) (comment (<- (:length () 0)) (<- (:length (:?x & :?y) (1 + :?n)) (:length :?y :?n)) (?- (:length (a b c d) :?n)) (?- (:length :?list (1 + (1 + 0)))) (?- (:length :?list :?n)) ) (comment (<- (:member :?item (:?item & :?rest))) (<- (:member :?item (:?x & :?rest)) (:member :?item :?rest)) (<- (:nextto :?x :?y :?list) (:iright :?y :?x :?list)) (<- (:nextto :?x :?y :?list) (:iright :?x :?y :?list)) (<- (:iright :?left :?right (:?left :?right & :?rest))) (<- (:iright :?left :?right (:?x & :?rest)) (:iright :?left :?right :?rest)) (<- (:= :?x :?x)) (<- (:zebra :?h :?w :?z) ;; Each house is of the form: ;; (house nationality pet cigarette drink house-color) (:= :?h ((house norwegian :? :? :? :?) ;1,10 :? (house :? :? :? milk :?) :? :?)) ; 9 (:member (house englishman :? :? :? red) :?h) ; 2 (:member (house spaniard dog :? :? :?) :?h) ; 3 (:member (house :? :? :? coffee green) :?h) ; 4 (:member (house ukrainian :? :? tea :?) :?h) ; 5 (:iright (house :? :? :? :? ivory) ; 6 (house :? :? :? :? green) :?h) (:member (house :? snails winston :? :?) :?h) ; 7 (:member (house :? :? kools :? yellow) :?h) ; 8 (:nextto (house :? :? chesterfield :? :?) ;11 (house :? fox :? :? :?) :?h) (:nextto (house :? :? kools :? :?) ;12 (house :? horse :? :? :?) :?h) (:member (house :? :? luckystrike orange-juice :?) :?h);13 (:member (house japanese :? parliaments :? :?) :?h) ;14 (:nextto (house norwegian :? :? :? :?) ;15 (house :? :? :? :? blue) :?h) ;; Now for the questions: (:member (house :?w :? :? water :?) :?h) ;Q1 (:member (house :?z zebra :? :? :?) :?h)) ;Q2 (?- (:zebra :?houses :?water-drinker :?zebra-owner)) )
[ { "context": "ojure/tools.reader]]\n [com.github.kyleburton/clj-xpath \"1.4.11\" :exclusions [org.clojure/tools", "end": 912, "score": 0.9878349900245667, "start": 902, "tag": "USERNAME", "value": "kyleburton" }, { "context": "er.com\"\n :mailer-from \"no-reply@clj-money.com\"\n :application-name \"c", "end": 9910, "score": 0.999913215637207, "start": 9888, "tag": "EMAIL", "value": "no-reply@clj-money.com" }, { "context": "ient-secret\"\n :secret \"9c3931112e73122ab46bf6fc0c40e72490b72b444b857dec35abc07056d3e867d952", "end": 10275, "score": 0.9989888668060303, "start": 10257, "tag": "KEY", "value": "9c3931112e73122ab4" }, { "context": " :secret \"9c3931112e73122ab46bf6fc0c40e72490b72b444b857dec35abc07056d3e867d952664eae62ba", "end": 10285, "score": 0.5689513683319092, "start": 10283, "tag": "KEY", "value": "40" }, { "context": " :secret \"9c3931112e73122ab46bf6fc0c40e72490b72b444b857dec35abc07056d3e867d952664eae62ba1db8d9", "end": 10291, "score": 0.6035343408584595, "start": 10286, "tag": "KEY", "value": "72490" }, { "context": " :secret \"9c3931112e73122ab46bf6fc0c40e72490b72b444b857dec35abc07056d3e867d952664eae62ba1db8d9408", "end": 10294, "score": 0.6140968799591064, "start": 10292, "tag": "KEY", "value": "72" }, { "context": " :secret \"9c3931112e73122ab46bf6fc0c40e72490b72b444b857dec35abc07056d3e867d952664eae62ba1db8d94089834ee2fd9fc989d6af8c7bd21fcfb6371bde27d3\"\n :site-protocol \"http", "end": 10385, "score": 0.6390174627304077, "start": 10295, "tag": "KEY", "value": "444b857dec35abc07056d3e867d952664eae62ba1db8d94089834ee2fd9fc989d6af8c7bd21fcfb6371bde27d3" } ]
project.clj
dgknght/clj-money
5
(defproject clj-money "1.0.0-SNAPSHOT" :description "Accounting application written in Clojure for the web" :url "http://money.herokuapp.com" :license {:name "Eclipse Public License v1.0" :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [[org.clojure/clojure "1.10.1" :exclusions [org.clojure/tools.reader]] [org.clojure/tools.logging "1.1.0" :exclusions [org.clojure/tools.reader]] [org.clojure/core.async "1.3.610" :exclusions [org.clojure/tools.reader]] [org.clojure/tools.cli "1.0.206" :exclusions [org.clojure/tools.reader]] [org.clojure/tools.reader "1.3.4"] [org.clojure/data.xml "0.2.0-alpha6"] [clj-http "3.9.0" :exclusions [org.clojure/tools.reader]] [cheshire "5.8.0" :exclusions [org.clojure/tools.reader]] [com.github.kyleburton/clj-xpath "1.4.11" :exclusions [org.clojure/tools.reader]] [ch.qos.logback/logback-classic "1.2.3" :exclusions [org.clojure/tools.reader]] [org.clojure/java.jdbc "0.7.11" :exclusions [org.clojure/tools.reader]] [org.postgresql/postgresql "42.2.2" :exclusions [org.clojure/tools.reader]] [clj-postgresql "0.7.0" :exclusions [org.slf4j/slf4j-api org.postgresql/postgresql org.clojure/tools.reader]] [honeysql "0.9.10" :exclusions [org.clojure/spec.alpha org.clojure/clojure org.clojure/core.specs.alpha org.clojure/tools.reader]] [clj-time "0.14.3" :exclusions [org.clojure/tools.reader]] [compojure "1.6.1" :exclusions [org.clojure/tools.reader]] [ring/ring-core "1.8.0" :exclusions [ring/ring-codec]] [ring/ring-jetty-adapter "1.6.3" :exclusions [org.clojure/tools.reader]] [ring/ring-codec "1.1.1" :exclusions [org.clojure/tools.reader]] [ring/ring-json "0.4.0" :exclusions [org.clojure/tools.reader]] [ring/ring-anti-forgery "1.2.0" :exclusions [org.clojure/tools.reader]] [hiccup "1.0.5" :exclusions [org.clojure/tools.reader]] [cljs-http "0.1.45" :exclusions [org.clojure/tools.reader]] [selmer "1.11.7" :exclusions [joda-time com.google.javascript/closure-compiler org.clojure/tools.reader]] [reagent "0.8.0" :exclusions [com.google.code.findbugs/jsr305 org.clojure/tools.reader]] [reagent-forms "0.5.41"] [reagent-utils "0.3.1"] [org.clojure/clojurescript "1.10.238" :exclusions [org.clojure/tools.reader]] [com.google.guava/guava "22.0" :exclusions [com.google.code.findbugs/jsr305 org.clojure/tools.reader]] [clojure-guava "0.0.8" :exclusions [org.clojure/clojure com.google.guava/guava org.clojure/tools.reader]] [secretary "1.2.3" :exclusions [com.google.javascript/closure-compiler org.clojure/tools.reader]] [venantius/accountant "0.2.4" :exclusions [com.google.javascript/closure-compiler org.clojure/tools.reader]] [closure-clj "0.1.2" :exclusions [com.google.javascript/closure-compiler org.clojure/tools.reader]] [environ "1.2.0" :exclusions [org.clojure/tools.reader]] [ragtime "0.7.2" :exclusions [org.clojure/tools.reader]] [clj-factory "0.2.1" :exclusions [org.clojure/tools.reader]] [digest "1.4.8" :exclusions [org.clojure/tools.reader]] [faker "0.3.2" :exclusions [org.clojure/tools.reader]] [com.draines/postal "2.0.2" :exclusions [org.clojure/tools.reader]] [com.andrewmcveigh/cljs-time "0.5.2"] [buddy/buddy-sign "3.1.0" :exclusions [com.fasterxml.jackson.dataformat/jackson-dataformat-smile com.fasterxml.jackson.dataformat/jackson-dataformat-cbor cheshire commons-codec com.fasterxml.jackson.core/jackson-core]] [buddy/buddy-hashers "1.4.0" :exclusions [com.fasterxml.jackson.dataformat/jackson-dataformat-smile com.fasterxml.jackson.dataformat/jackson-dataformat-cbor cheshire commons-codec com.fasterxml.jackson.core/jackson-core]] [org.mindrot/jbcrypt "0.3m"] [co.deps/ring-etag-middleware "0.2.1"] [camel-snake-kebab "0.4.1"] [com.github.dgknght/app-lib "0.1.22"] [lambdaisland/uri "1.4.54"] [stowaway "0.1.8" :exclusions [org.clojure/spec.alpha org.clojure/clojure org.clojure/core.specs.alpha org.clojure/tools.logging]]] :min-lein-version "2.0.0" :plugins [[lein-environ "1.1.0" :exclusions [org.clojure/tools.reader]] [lein-cljsbuild "1.1.6" :exclusions [org.clojure/tools.reader]] [lein-cljfmt "0.7.0"] [lein-figwheel "0.5.16"]] :hooks [] :uberjar-name "clj-money-standalone.jar" :aot [clj-money.web.server] :clean-targets ^{:protect false} [:target-path [:cljsbuild :builds :app :compiler :output-dir] [:cljsbuild :builds :app :compiler :output-to]] :source-paths ["src/clj" "src/cljc"] :resource-paths ["resources" "target/cljsbuild"] :cljsbuild {:builds [{:id :production :source-paths ["src/cljs" "src/cljc"] :compiler {:output-to "target/cljsbuild/public/js/prod/app.js" :output-dir "target/cljsbuild/public/js/prod" :source-map "target/cljsbuild/public/js/prod/app.js.map" :optimizations :advanced :pretty-print false}} {:id :development :figwheel true :source-paths ["src/cljs" "src/cljc"] :compiler {:main "clj-money.core" :asset-path "/js/app" :output-to "resources/public/js/app/main.js" :output-dir "resources/public/js/app" :source-map true :optimizations :none :pretty-print true}}]} :aliases {"migrate" ["run" "-m" "clj-money.db/migrate"] "rollback" ["run" "-m" "clj-money.db/rollback"] "remigrate" ["run" "-m" "clj-money.db/remigrate"] "partition" ["run" "-m" "clj-money.db/create-partitions"] "check-trans" ["run" "-m" "clj-money.db/check-transaction-balances"] "chunk-file" ["run" "-m" "clj-money.import.gnucash/chunk-file"] "seed" ["run" "-m" "clj-money.seed/seed"] "generate-transactions" ["run" "-m" "clj-money.seed/generate-transactions"] "sass" ["run" "-m" "clj-money.tasks/compile-sass"] "recalc" ["run" "-m" "clj-money.tasks/recalc"] "migrate-account" ["run" "-m" "clj-money.tasks/migrate-account"] "export-user-tags" ["run" "-m" "clj-money.tasks/export-user-tags"] "import-user-tags" ["run" "-m" "clj-money.tasks/import-user-tags"] "update-commodity-price-ranges" ["run" "-m" "clj-money.tasks/update-commodity-price-ranges"]} :jvm-opts ["-Duser.timezone=UTC"] :profiles {:production {:env {:production true}} :dev [:project/dev :profiles/dev] :test [:project/test :profiles/test] :profiles/dev {} :profiles/test {} :project/dev {:env {:db "postgresql://app_user:please01@localhost/money_development" :partition-period "year" :show-error-messages? "true" :site-protocol "http" :site-host "lvh.me:5000"}} :project/test {:dependencies [[ring/ring-mock "0.4.0"] [peridot "0.5.2"]] :env {:db "postgresql://app_user:please01@localhost/money_test" :partition-period "year" :mailer-host "testmailer.com" :mailer-from "no-reply@clj-money.com" :application-name "clj-money" :show-error-messages? "true" :detailed-import-logging? "false" :google-client-id "google-id" :google-client-secret "google-client-secret" :secret "9c3931112e73122ab46bf6fc0c40e72490b72b444b857dec35abc07056d3e867d952664eae62ba1db8d94089834ee2fd9fc989d6af8c7bd21fcfb6371bde27d3" :site-protocol "https" :site-host "www.mymoney.com"}} :uberjar {:prep-tasks ["compile" ["cljsbuild" "once"] "sass"]}})
74577
(defproject clj-money "1.0.0-SNAPSHOT" :description "Accounting application written in Clojure for the web" :url "http://money.herokuapp.com" :license {:name "Eclipse Public License v1.0" :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [[org.clojure/clojure "1.10.1" :exclusions [org.clojure/tools.reader]] [org.clojure/tools.logging "1.1.0" :exclusions [org.clojure/tools.reader]] [org.clojure/core.async "1.3.610" :exclusions [org.clojure/tools.reader]] [org.clojure/tools.cli "1.0.206" :exclusions [org.clojure/tools.reader]] [org.clojure/tools.reader "1.3.4"] [org.clojure/data.xml "0.2.0-alpha6"] [clj-http "3.9.0" :exclusions [org.clojure/tools.reader]] [cheshire "5.8.0" :exclusions [org.clojure/tools.reader]] [com.github.kyleburton/clj-xpath "1.4.11" :exclusions [org.clojure/tools.reader]] [ch.qos.logback/logback-classic "1.2.3" :exclusions [org.clojure/tools.reader]] [org.clojure/java.jdbc "0.7.11" :exclusions [org.clojure/tools.reader]] [org.postgresql/postgresql "42.2.2" :exclusions [org.clojure/tools.reader]] [clj-postgresql "0.7.0" :exclusions [org.slf4j/slf4j-api org.postgresql/postgresql org.clojure/tools.reader]] [honeysql "0.9.10" :exclusions [org.clojure/spec.alpha org.clojure/clojure org.clojure/core.specs.alpha org.clojure/tools.reader]] [clj-time "0.14.3" :exclusions [org.clojure/tools.reader]] [compojure "1.6.1" :exclusions [org.clojure/tools.reader]] [ring/ring-core "1.8.0" :exclusions [ring/ring-codec]] [ring/ring-jetty-adapter "1.6.3" :exclusions [org.clojure/tools.reader]] [ring/ring-codec "1.1.1" :exclusions [org.clojure/tools.reader]] [ring/ring-json "0.4.0" :exclusions [org.clojure/tools.reader]] [ring/ring-anti-forgery "1.2.0" :exclusions [org.clojure/tools.reader]] [hiccup "1.0.5" :exclusions [org.clojure/tools.reader]] [cljs-http "0.1.45" :exclusions [org.clojure/tools.reader]] [selmer "1.11.7" :exclusions [joda-time com.google.javascript/closure-compiler org.clojure/tools.reader]] [reagent "0.8.0" :exclusions [com.google.code.findbugs/jsr305 org.clojure/tools.reader]] [reagent-forms "0.5.41"] [reagent-utils "0.3.1"] [org.clojure/clojurescript "1.10.238" :exclusions [org.clojure/tools.reader]] [com.google.guava/guava "22.0" :exclusions [com.google.code.findbugs/jsr305 org.clojure/tools.reader]] [clojure-guava "0.0.8" :exclusions [org.clojure/clojure com.google.guava/guava org.clojure/tools.reader]] [secretary "1.2.3" :exclusions [com.google.javascript/closure-compiler org.clojure/tools.reader]] [venantius/accountant "0.2.4" :exclusions [com.google.javascript/closure-compiler org.clojure/tools.reader]] [closure-clj "0.1.2" :exclusions [com.google.javascript/closure-compiler org.clojure/tools.reader]] [environ "1.2.0" :exclusions [org.clojure/tools.reader]] [ragtime "0.7.2" :exclusions [org.clojure/tools.reader]] [clj-factory "0.2.1" :exclusions [org.clojure/tools.reader]] [digest "1.4.8" :exclusions [org.clojure/tools.reader]] [faker "0.3.2" :exclusions [org.clojure/tools.reader]] [com.draines/postal "2.0.2" :exclusions [org.clojure/tools.reader]] [com.andrewmcveigh/cljs-time "0.5.2"] [buddy/buddy-sign "3.1.0" :exclusions [com.fasterxml.jackson.dataformat/jackson-dataformat-smile com.fasterxml.jackson.dataformat/jackson-dataformat-cbor cheshire commons-codec com.fasterxml.jackson.core/jackson-core]] [buddy/buddy-hashers "1.4.0" :exclusions [com.fasterxml.jackson.dataformat/jackson-dataformat-smile com.fasterxml.jackson.dataformat/jackson-dataformat-cbor cheshire commons-codec com.fasterxml.jackson.core/jackson-core]] [org.mindrot/jbcrypt "0.3m"] [co.deps/ring-etag-middleware "0.2.1"] [camel-snake-kebab "0.4.1"] [com.github.dgknght/app-lib "0.1.22"] [lambdaisland/uri "1.4.54"] [stowaway "0.1.8" :exclusions [org.clojure/spec.alpha org.clojure/clojure org.clojure/core.specs.alpha org.clojure/tools.logging]]] :min-lein-version "2.0.0" :plugins [[lein-environ "1.1.0" :exclusions [org.clojure/tools.reader]] [lein-cljsbuild "1.1.6" :exclusions [org.clojure/tools.reader]] [lein-cljfmt "0.7.0"] [lein-figwheel "0.5.16"]] :hooks [] :uberjar-name "clj-money-standalone.jar" :aot [clj-money.web.server] :clean-targets ^{:protect false} [:target-path [:cljsbuild :builds :app :compiler :output-dir] [:cljsbuild :builds :app :compiler :output-to]] :source-paths ["src/clj" "src/cljc"] :resource-paths ["resources" "target/cljsbuild"] :cljsbuild {:builds [{:id :production :source-paths ["src/cljs" "src/cljc"] :compiler {:output-to "target/cljsbuild/public/js/prod/app.js" :output-dir "target/cljsbuild/public/js/prod" :source-map "target/cljsbuild/public/js/prod/app.js.map" :optimizations :advanced :pretty-print false}} {:id :development :figwheel true :source-paths ["src/cljs" "src/cljc"] :compiler {:main "clj-money.core" :asset-path "/js/app" :output-to "resources/public/js/app/main.js" :output-dir "resources/public/js/app" :source-map true :optimizations :none :pretty-print true}}]} :aliases {"migrate" ["run" "-m" "clj-money.db/migrate"] "rollback" ["run" "-m" "clj-money.db/rollback"] "remigrate" ["run" "-m" "clj-money.db/remigrate"] "partition" ["run" "-m" "clj-money.db/create-partitions"] "check-trans" ["run" "-m" "clj-money.db/check-transaction-balances"] "chunk-file" ["run" "-m" "clj-money.import.gnucash/chunk-file"] "seed" ["run" "-m" "clj-money.seed/seed"] "generate-transactions" ["run" "-m" "clj-money.seed/generate-transactions"] "sass" ["run" "-m" "clj-money.tasks/compile-sass"] "recalc" ["run" "-m" "clj-money.tasks/recalc"] "migrate-account" ["run" "-m" "clj-money.tasks/migrate-account"] "export-user-tags" ["run" "-m" "clj-money.tasks/export-user-tags"] "import-user-tags" ["run" "-m" "clj-money.tasks/import-user-tags"] "update-commodity-price-ranges" ["run" "-m" "clj-money.tasks/update-commodity-price-ranges"]} :jvm-opts ["-Duser.timezone=UTC"] :profiles {:production {:env {:production true}} :dev [:project/dev :profiles/dev] :test [:project/test :profiles/test] :profiles/dev {} :profiles/test {} :project/dev {:env {:db "postgresql://app_user:please01@localhost/money_development" :partition-period "year" :show-error-messages? "true" :site-protocol "http" :site-host "lvh.me:5000"}} :project/test {:dependencies [[ring/ring-mock "0.4.0"] [peridot "0.5.2"]] :env {:db "postgresql://app_user:please01@localhost/money_test" :partition-period "year" :mailer-host "testmailer.com" :mailer-from "<EMAIL>" :application-name "clj-money" :show-error-messages? "true" :detailed-import-logging? "false" :google-client-id "google-id" :google-client-secret "google-client-secret" :secret "<KEY>6bf6fc0c<KEY>e<KEY>b<KEY>b<KEY>" :site-protocol "https" :site-host "www.mymoney.com"}} :uberjar {:prep-tasks ["compile" ["cljsbuild" "once"] "sass"]}})
true
(defproject clj-money "1.0.0-SNAPSHOT" :description "Accounting application written in Clojure for the web" :url "http://money.herokuapp.com" :license {:name "Eclipse Public License v1.0" :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [[org.clojure/clojure "1.10.1" :exclusions [org.clojure/tools.reader]] [org.clojure/tools.logging "1.1.0" :exclusions [org.clojure/tools.reader]] [org.clojure/core.async "1.3.610" :exclusions [org.clojure/tools.reader]] [org.clojure/tools.cli "1.0.206" :exclusions [org.clojure/tools.reader]] [org.clojure/tools.reader "1.3.4"] [org.clojure/data.xml "0.2.0-alpha6"] [clj-http "3.9.0" :exclusions [org.clojure/tools.reader]] [cheshire "5.8.0" :exclusions [org.clojure/tools.reader]] [com.github.kyleburton/clj-xpath "1.4.11" :exclusions [org.clojure/tools.reader]] [ch.qos.logback/logback-classic "1.2.3" :exclusions [org.clojure/tools.reader]] [org.clojure/java.jdbc "0.7.11" :exclusions [org.clojure/tools.reader]] [org.postgresql/postgresql "42.2.2" :exclusions [org.clojure/tools.reader]] [clj-postgresql "0.7.0" :exclusions [org.slf4j/slf4j-api org.postgresql/postgresql org.clojure/tools.reader]] [honeysql "0.9.10" :exclusions [org.clojure/spec.alpha org.clojure/clojure org.clojure/core.specs.alpha org.clojure/tools.reader]] [clj-time "0.14.3" :exclusions [org.clojure/tools.reader]] [compojure "1.6.1" :exclusions [org.clojure/tools.reader]] [ring/ring-core "1.8.0" :exclusions [ring/ring-codec]] [ring/ring-jetty-adapter "1.6.3" :exclusions [org.clojure/tools.reader]] [ring/ring-codec "1.1.1" :exclusions [org.clojure/tools.reader]] [ring/ring-json "0.4.0" :exclusions [org.clojure/tools.reader]] [ring/ring-anti-forgery "1.2.0" :exclusions [org.clojure/tools.reader]] [hiccup "1.0.5" :exclusions [org.clojure/tools.reader]] [cljs-http "0.1.45" :exclusions [org.clojure/tools.reader]] [selmer "1.11.7" :exclusions [joda-time com.google.javascript/closure-compiler org.clojure/tools.reader]] [reagent "0.8.0" :exclusions [com.google.code.findbugs/jsr305 org.clojure/tools.reader]] [reagent-forms "0.5.41"] [reagent-utils "0.3.1"] [org.clojure/clojurescript "1.10.238" :exclusions [org.clojure/tools.reader]] [com.google.guava/guava "22.0" :exclusions [com.google.code.findbugs/jsr305 org.clojure/tools.reader]] [clojure-guava "0.0.8" :exclusions [org.clojure/clojure com.google.guava/guava org.clojure/tools.reader]] [secretary "1.2.3" :exclusions [com.google.javascript/closure-compiler org.clojure/tools.reader]] [venantius/accountant "0.2.4" :exclusions [com.google.javascript/closure-compiler org.clojure/tools.reader]] [closure-clj "0.1.2" :exclusions [com.google.javascript/closure-compiler org.clojure/tools.reader]] [environ "1.2.0" :exclusions [org.clojure/tools.reader]] [ragtime "0.7.2" :exclusions [org.clojure/tools.reader]] [clj-factory "0.2.1" :exclusions [org.clojure/tools.reader]] [digest "1.4.8" :exclusions [org.clojure/tools.reader]] [faker "0.3.2" :exclusions [org.clojure/tools.reader]] [com.draines/postal "2.0.2" :exclusions [org.clojure/tools.reader]] [com.andrewmcveigh/cljs-time "0.5.2"] [buddy/buddy-sign "3.1.0" :exclusions [com.fasterxml.jackson.dataformat/jackson-dataformat-smile com.fasterxml.jackson.dataformat/jackson-dataformat-cbor cheshire commons-codec com.fasterxml.jackson.core/jackson-core]] [buddy/buddy-hashers "1.4.0" :exclusions [com.fasterxml.jackson.dataformat/jackson-dataformat-smile com.fasterxml.jackson.dataformat/jackson-dataformat-cbor cheshire commons-codec com.fasterxml.jackson.core/jackson-core]] [org.mindrot/jbcrypt "0.3m"] [co.deps/ring-etag-middleware "0.2.1"] [camel-snake-kebab "0.4.1"] [com.github.dgknght/app-lib "0.1.22"] [lambdaisland/uri "1.4.54"] [stowaway "0.1.8" :exclusions [org.clojure/spec.alpha org.clojure/clojure org.clojure/core.specs.alpha org.clojure/tools.logging]]] :min-lein-version "2.0.0" :plugins [[lein-environ "1.1.0" :exclusions [org.clojure/tools.reader]] [lein-cljsbuild "1.1.6" :exclusions [org.clojure/tools.reader]] [lein-cljfmt "0.7.0"] [lein-figwheel "0.5.16"]] :hooks [] :uberjar-name "clj-money-standalone.jar" :aot [clj-money.web.server] :clean-targets ^{:protect false} [:target-path [:cljsbuild :builds :app :compiler :output-dir] [:cljsbuild :builds :app :compiler :output-to]] :source-paths ["src/clj" "src/cljc"] :resource-paths ["resources" "target/cljsbuild"] :cljsbuild {:builds [{:id :production :source-paths ["src/cljs" "src/cljc"] :compiler {:output-to "target/cljsbuild/public/js/prod/app.js" :output-dir "target/cljsbuild/public/js/prod" :source-map "target/cljsbuild/public/js/prod/app.js.map" :optimizations :advanced :pretty-print false}} {:id :development :figwheel true :source-paths ["src/cljs" "src/cljc"] :compiler {:main "clj-money.core" :asset-path "/js/app" :output-to "resources/public/js/app/main.js" :output-dir "resources/public/js/app" :source-map true :optimizations :none :pretty-print true}}]} :aliases {"migrate" ["run" "-m" "clj-money.db/migrate"] "rollback" ["run" "-m" "clj-money.db/rollback"] "remigrate" ["run" "-m" "clj-money.db/remigrate"] "partition" ["run" "-m" "clj-money.db/create-partitions"] "check-trans" ["run" "-m" "clj-money.db/check-transaction-balances"] "chunk-file" ["run" "-m" "clj-money.import.gnucash/chunk-file"] "seed" ["run" "-m" "clj-money.seed/seed"] "generate-transactions" ["run" "-m" "clj-money.seed/generate-transactions"] "sass" ["run" "-m" "clj-money.tasks/compile-sass"] "recalc" ["run" "-m" "clj-money.tasks/recalc"] "migrate-account" ["run" "-m" "clj-money.tasks/migrate-account"] "export-user-tags" ["run" "-m" "clj-money.tasks/export-user-tags"] "import-user-tags" ["run" "-m" "clj-money.tasks/import-user-tags"] "update-commodity-price-ranges" ["run" "-m" "clj-money.tasks/update-commodity-price-ranges"]} :jvm-opts ["-Duser.timezone=UTC"] :profiles {:production {:env {:production true}} :dev [:project/dev :profiles/dev] :test [:project/test :profiles/test] :profiles/dev {} :profiles/test {} :project/dev {:env {:db "postgresql://app_user:please01@localhost/money_development" :partition-period "year" :show-error-messages? "true" :site-protocol "http" :site-host "lvh.me:5000"}} :project/test {:dependencies [[ring/ring-mock "0.4.0"] [peridot "0.5.2"]] :env {:db "postgresql://app_user:please01@localhost/money_test" :partition-period "year" :mailer-host "testmailer.com" :mailer-from "PI:EMAIL:<EMAIL>END_PI" :application-name "clj-money" :show-error-messages? "true" :detailed-import-logging? "false" :google-client-id "google-id" :google-client-secret "google-client-secret" :secret "PI:KEY:<KEY>END_PI6bf6fc0cPI:KEY:<KEY>END_PIePI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PI" :site-protocol "https" :site-host "www.mymoney.com"}} :uberjar {:prep-tasks ["compile" ["cljsbuild" "once"] "sass"]}})
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998123645782471, "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.9998253583908081, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/src/clj/editor/messages.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.messages (:import [java.util ResourceBundle]) (:require [clojure.java.io :as io])) (set! *warn-on-reflection* true) (defn bundle-map [^ResourceBundle bundle] (let [ks (enumeration-seq (.getKeys bundle))] (zipmap ks (map #(.getString bundle %) ks)))) (defn load-bundle-in-namespace [ns-sym bundle] (create-ns ns-sym) (doseq [[k v] (bundle-map bundle)] (intern ns-sym (with-meta (symbol k) {:bundle bundle}) v))) (defn resource-bundle [path] (ResourceBundle/getBundle path)) (load-bundle-in-namespace 'editor.messages (resource-bundle "messages"))
32473
;; 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.messages (:import [java.util ResourceBundle]) (:require [clojure.java.io :as io])) (set! *warn-on-reflection* true) (defn bundle-map [^ResourceBundle bundle] (let [ks (enumeration-seq (.getKeys bundle))] (zipmap ks (map #(.getString bundle %) ks)))) (defn load-bundle-in-namespace [ns-sym bundle] (create-ns ns-sym) (doseq [[k v] (bundle-map bundle)] (intern ns-sym (with-meta (symbol k) {:bundle bundle}) v))) (defn resource-bundle [path] (ResourceBundle/getBundle path)) (load-bundle-in-namespace 'editor.messages (resource-bundle "messages"))
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.messages (:import [java.util ResourceBundle]) (:require [clojure.java.io :as io])) (set! *warn-on-reflection* true) (defn bundle-map [^ResourceBundle bundle] (let [ks (enumeration-seq (.getKeys bundle))] (zipmap ks (map #(.getString bundle %) ks)))) (defn load-bundle-in-namespace [ns-sym bundle] (create-ns ns-sym) (doseq [[k v] (bundle-map bundle)] (intern ns-sym (with-meta (symbol k) {:bundle bundle}) v))) (defn resource-bundle [path] (ResourceBundle/getBundle path)) (load-bundle-in-namespace 'editor.messages (resource-bundle "messages"))
[ { "context": "ange 1 (inc t))))\n\n\n\n\n(def init-results '({:name \"Vixen\" :points 0}\n {:name \"Blitzen\" ", "end": 1144, "score": 0.9993696212768555, "start": 1139, "tag": "NAME", "value": "Vixen" }, { "context": "me \"Vixen\" :points 0}\n {:name \"Blitzen\" :points 0}\n {:name \"Rudolph\" ", "end": 1192, "score": 0.9995704293251038, "start": 1185, "tag": "NAME", "value": "Blitzen" }, { "context": " \"Blitzen\" :points 0}\n {:name \"Rudolph\" :points 0}\n {:name \"Cupid\" :p", "end": 1240, "score": 0.9993838667869568, "start": 1233, "tag": "NAME", "value": "Rudolph" }, { "context": " \"Rudolph\" :points 0}\n {:name \"Cupid\" :points 0}\n {:name \"Donner\" :", "end": 1286, "score": 0.9996925592422485, "start": 1281, "tag": "NAME", "value": "Cupid" }, { "context": "me \"Cupid\" :points 0}\n {:name \"Donner\" :points 0}\n {:name \"Dasher\" :", "end": 1333, "score": 0.9995160698890686, "start": 1327, "tag": "NAME", "value": "Donner" }, { "context": "e \"Donner\" :points 0}\n {:name \"Dasher\" :points 0}\n {:name \"Comet\" :p", "end": 1380, "score": 0.9996218681335449, "start": 1374, "tag": "NAME", "value": "Dasher" }, { "context": "e \"Dasher\" :points 0}\n {:name \"Comet\" :points 0}\n {:name \"Prancer\" ", "end": 1426, "score": 0.9996002912521362, "start": 1421, "tag": "NAME", "value": "Comet" }, { "context": "me \"Comet\" :points 0}\n {:name \"Prancer\" :points 0}\n {:name \"Dancer\" :", "end": 1474, "score": 0.9996890425682068, "start": 1467, "tag": "NAME", "value": "Prancer" }, { "context": " \"Prancer\" :points 0}\n {:name \"Dancer\" :points 0}))\n \n(def data '({:name \"Vi", "end": 1521, "score": 0.9996570348739624, "start": 1515, "tag": "NAME", "value": "Dancer" }, { "context": "er\" :points 0}))\n \n(def data '({:name \"Vixen\" :speed 8 :fly-time 8 :rest-time 53}\n ", "end": 1574, "score": 0.9995796084403992, "start": 1569, "tag": "NAME", "value": "Vixen" }, { "context": " 8 :fly-time 8 :rest-time 53}\n {:name \"Blitzen\" :speed 13 :fly-time 4 :rest-time 49}\n ", "end": 1639, "score": 0.9996537566184998, "start": 1632, "tag": "NAME", "value": "Blitzen" }, { "context": "13 :fly-time 4 :rest-time 49}\n {:name \"Rudolph\" :speed 20 :fly-time 7 :rest-time 132}\n ", "end": 1705, "score": 0.9996082782745361, "start": 1698, "tag": "NAME", "value": "Rudolph" }, { "context": "0 :fly-time 7 :rest-time 132}\n {:name \"Cupid\" :speed 12 :fly-time 4 :rest-time 43}\n ", "end": 1770, "score": 0.9996472597122192, "start": 1765, "tag": "NAME", "value": "Cupid" }, { "context": "12 :fly-time 4 :rest-time 43}\n {:name \"Donner\" :speed 9 :fly-time 5 :rest-time 38}\n ", "end": 1835, "score": 0.9990628957748413, "start": 1829, "tag": "NAME", "value": "Donner" }, { "context": " 9 :fly-time 5 :rest-time 38}\n {:name \"Dasher\" :speed 10 :fly-time 4 :rest-time 37}\n ", "end": 1899, "score": 0.9991974234580994, "start": 1893, "tag": "NAME", "value": "Dasher" }, { "context": "10 :fly-time 4 :rest-time 37}\n {:name \"Comet\" :speed 3 :fly-time 37 :rest-time 76}\n ", "end": 1963, "score": 0.9989767074584961, "start": 1958, "tag": "NAME", "value": "Comet" }, { "context": "3 :fly-time 37 :rest-time 76}\n {:name \"Prancer\" :speed 9 :fly-time 12 :rest-time 97}\n ", "end": 2029, "score": 0.9995187520980835, "start": 2022, "tag": "NAME", "value": "Prancer" }, { "context": "9 :fly-time 12 :rest-time 97}\n {:name \"Dancer\" :speed 37 :fly-time 1 :rest-time 36}))\n\n", "end": 2094, "score": 0.9992673993110657, "start": 2088, "tag": "NAME", "value": "Dancer" } ]
day14.clj
tharibo/adventofcode
0
(defn full-flight-periods [total-duration fly-time rest-time] (int (/ total-duration (+ fly-time rest-time)))) (defn final-seconds-of-flight [total-duration fly-time rest-time] (mod total-duration (+ fly-time rest-time))) (defn compute-distance [total-duration speed fly-time rest-time] (+ (* speed fly-time (full-flight-periods total-duration fly-time rest-time)) (* speed (min fly-time (final-seconds-of-flight total-duration fly-time rest-time))))) (defn compute-all [coll t] (reduce #(cons {:name (:name %2) :distance (compute-distance t (:speed %2) (:fly-time %2) (:rest-time %2))} %1) [] coll)) (defn leader [coll] (:name (last (sort-by :distance coll)))) (defn compute-all2 [coll t] (reduce #(let [current-results (compute-all coll %2) current-leader (leader current-results)] (map (fn [result](if (= (:name result) current-leader) {:name (:name result) :points (inc (:points result))} result)) %1)) init-results (range 1 (inc t)))) (def init-results '({:name "Vixen" :points 0} {:name "Blitzen" :points 0} {:name "Rudolph" :points 0} {:name "Cupid" :points 0} {:name "Donner" :points 0} {:name "Dasher" :points 0} {:name "Comet" :points 0} {:name "Prancer" :points 0} {:name "Dancer" :points 0})) (def data '({:name "Vixen" :speed 8 :fly-time 8 :rest-time 53} {:name "Blitzen" :speed 13 :fly-time 4 :rest-time 49} {:name "Rudolph" :speed 20 :fly-time 7 :rest-time 132} {:name "Cupid" :speed 12 :fly-time 4 :rest-time 43} {:name "Donner" :speed 9 :fly-time 5 :rest-time 38} {:name "Dasher" :speed 10 :fly-time 4 :rest-time 37} {:name "Comet" :speed 3 :fly-time 37 :rest-time 76} {:name "Prancer" :speed 9 :fly-time 12 :rest-time 97} {:name "Dancer" :speed 37 :fly-time 1 :rest-time 36}))
10324
(defn full-flight-periods [total-duration fly-time rest-time] (int (/ total-duration (+ fly-time rest-time)))) (defn final-seconds-of-flight [total-duration fly-time rest-time] (mod total-duration (+ fly-time rest-time))) (defn compute-distance [total-duration speed fly-time rest-time] (+ (* speed fly-time (full-flight-periods total-duration fly-time rest-time)) (* speed (min fly-time (final-seconds-of-flight total-duration fly-time rest-time))))) (defn compute-all [coll t] (reduce #(cons {:name (:name %2) :distance (compute-distance t (:speed %2) (:fly-time %2) (:rest-time %2))} %1) [] coll)) (defn leader [coll] (:name (last (sort-by :distance coll)))) (defn compute-all2 [coll t] (reduce #(let [current-results (compute-all coll %2) current-leader (leader current-results)] (map (fn [result](if (= (:name result) current-leader) {:name (:name result) :points (inc (:points result))} result)) %1)) init-results (range 1 (inc t)))) (def init-results '({:name "<NAME>" :points 0} {:name "<NAME>" :points 0} {:name "<NAME>" :points 0} {:name "<NAME>" :points 0} {:name "<NAME>" :points 0} {:name "<NAME>" :points 0} {:name "<NAME>" :points 0} {:name "<NAME>" :points 0} {:name "<NAME>" :points 0})) (def data '({:name "<NAME>" :speed 8 :fly-time 8 :rest-time 53} {:name "<NAME>" :speed 13 :fly-time 4 :rest-time 49} {:name "<NAME>" :speed 20 :fly-time 7 :rest-time 132} {:name "<NAME>" :speed 12 :fly-time 4 :rest-time 43} {:name "<NAME>" :speed 9 :fly-time 5 :rest-time 38} {:name "<NAME>" :speed 10 :fly-time 4 :rest-time 37} {:name "<NAME>" :speed 3 :fly-time 37 :rest-time 76} {:name "<NAME>" :speed 9 :fly-time 12 :rest-time 97} {:name "<NAME>" :speed 37 :fly-time 1 :rest-time 36}))
true
(defn full-flight-periods [total-duration fly-time rest-time] (int (/ total-duration (+ fly-time rest-time)))) (defn final-seconds-of-flight [total-duration fly-time rest-time] (mod total-duration (+ fly-time rest-time))) (defn compute-distance [total-duration speed fly-time rest-time] (+ (* speed fly-time (full-flight-periods total-duration fly-time rest-time)) (* speed (min fly-time (final-seconds-of-flight total-duration fly-time rest-time))))) (defn compute-all [coll t] (reduce #(cons {:name (:name %2) :distance (compute-distance t (:speed %2) (:fly-time %2) (:rest-time %2))} %1) [] coll)) (defn leader [coll] (:name (last (sort-by :distance coll)))) (defn compute-all2 [coll t] (reduce #(let [current-results (compute-all coll %2) current-leader (leader current-results)] (map (fn [result](if (= (:name result) current-leader) {:name (:name result) :points (inc (:points result))} result)) %1)) init-results (range 1 (inc t)))) (def init-results '({:name "PI:NAME:<NAME>END_PI" :points 0} {:name "PI:NAME:<NAME>END_PI" :points 0} {:name "PI:NAME:<NAME>END_PI" :points 0} {:name "PI:NAME:<NAME>END_PI" :points 0} {:name "PI:NAME:<NAME>END_PI" :points 0} {:name "PI:NAME:<NAME>END_PI" :points 0} {:name "PI:NAME:<NAME>END_PI" :points 0} {:name "PI:NAME:<NAME>END_PI" :points 0} {:name "PI:NAME:<NAME>END_PI" :points 0})) (def data '({:name "PI:NAME:<NAME>END_PI" :speed 8 :fly-time 8 :rest-time 53} {:name "PI:NAME:<NAME>END_PI" :speed 13 :fly-time 4 :rest-time 49} {:name "PI:NAME:<NAME>END_PI" :speed 20 :fly-time 7 :rest-time 132} {:name "PI:NAME:<NAME>END_PI" :speed 12 :fly-time 4 :rest-time 43} {:name "PI:NAME:<NAME>END_PI" :speed 9 :fly-time 5 :rest-time 38} {:name "PI:NAME:<NAME>END_PI" :speed 10 :fly-time 4 :rest-time 37} {:name "PI:NAME:<NAME>END_PI" :speed 3 :fly-time 37 :rest-time 76} {:name "PI:NAME:<NAME>END_PI" :speed 9 :fly-time 12 :rest-time 97} {:name "PI:NAME:<NAME>END_PI" :speed 37 :fly-time 1 :rest-time 36}))
[ { "context": "\n (with-out-str (built-like :Account {:password \"foo\"}))\n => #\":password should contain a digit\")\n\n(s", "end": 718, "score": 0.9805973172187805, "start": 715, "tag": "PASSWORD", "value": "foo" } ]
test/structural_typing/use/condensed_type_descriptions/f_explain_with.clj
marick/structural-typing
265
(ns structural-typing.use.condensed-type-descriptions.f-explain-with (:require [structural-typing.assist.oopsie :as oopsie]) (:use midje.sweet structural-typing.type structural-typing.global-type structural-typing.clojure.core structural-typing.assist.testutil) (:refer-clojure :except [any?])) (start-over!) (def good-password? (->> (partial re-find #"\d") (explain-with (fn [oopsie] (format "%s should contain a digit" (oopsie/friendly-path oopsie)))))) (type! :Account {:password good-password?}) (fact (with-out-str (built-like :Account {:password "foo"})) => #":password should contain a digit") (start-over!)
811
(ns structural-typing.use.condensed-type-descriptions.f-explain-with (:require [structural-typing.assist.oopsie :as oopsie]) (:use midje.sweet structural-typing.type structural-typing.global-type structural-typing.clojure.core structural-typing.assist.testutil) (:refer-clojure :except [any?])) (start-over!) (def good-password? (->> (partial re-find #"\d") (explain-with (fn [oopsie] (format "%s should contain a digit" (oopsie/friendly-path oopsie)))))) (type! :Account {:password good-password?}) (fact (with-out-str (built-like :Account {:password "<PASSWORD>"})) => #":password should contain a digit") (start-over!)
true
(ns structural-typing.use.condensed-type-descriptions.f-explain-with (:require [structural-typing.assist.oopsie :as oopsie]) (:use midje.sweet structural-typing.type structural-typing.global-type structural-typing.clojure.core structural-typing.assist.testutil) (:refer-clojure :except [any?])) (start-over!) (def good-password? (->> (partial re-find #"\d") (explain-with (fn [oopsie] (format "%s should contain a digit" (oopsie/friendly-path oopsie)))))) (type! :Account {:password good-password?}) (fact (with-out-str (built-like :Account {:password "PI:PASSWORD:<PASSWORD>END_PI"})) => #":password should contain a digit") (start-over!)
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998068809509277, "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.9998214840888977, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/src/clj/editor/resource_watch.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.resource-watch (:require [clojure.java.io :as io] [clojure.string :as str] [editor.settings-core :as settings-core] [editor.library :as library] [editor.resource :as resource] [editor.system :as system] [dynamo.graph :as g]) (:import [java.io File] [java.net URI])) (set! *warn-on-reflection* true) (defn- resource-root-dir [resource] (when-let [path-splits (seq (rest (str/split (resource/proj-path resource) #"/")))] ; skip initial "" (if (= (count path-splits) 1) (when (= (resource/source-type resource) :folder) (first path-splits)) (first path-splits)))) (defn parse-include-dirs [include-string] (filter (comp not str/blank?) (str/split include-string #"[,\s]"))) (defn- extract-game-project-include-dirs [game-project-resource] (with-open [reader (io/reader game-project-resource)] (let [settings (settings-core/parse-settings reader)] (parse-include-dirs (str (settings-core/get-setting settings ["library" "include_dirs"])))))) (defn- load-library-zip [workspace file] (let [base-path (library/library-base-path file) zip-resources (resource/load-zip-resources workspace file base-path) game-project-resource (first (filter (fn [resource] (= "game.project" (resource/resource-name resource))) (:tree zip-resources)))] (when game-project-resource (let [include-dirs (set (extract-game-project-include-dirs game-project-resource))] (update zip-resources :tree (fn [tree] (filter #(include-dirs (resource-root-dir %)) tree))))))) (defn- make-library-snapshot [workspace lib-state] (let [file ^File (:file lib-state) tag (:tag lib-state) uri-string (.toString ^URI (:uri lib-state)) zip-file-version (if-not (str/blank? tag) tag (str (.lastModified file))) {resources :tree crc :crc} (load-library-zip workspace file) flat-resources (resource/resource-list-seq resources)] {:resources resources :status-map (into {} (map (fn [resource] (let [path (resource/proj-path resource) version (str zip-file-version ":" (crc path))] [path {:version version :source :library :library uri-string}])) flat-resources))})) (defn- update-library-snapshot-cache [library-snapshot-cache workspace lib-states] (reduce (fn [ret {:keys [^File file] :as lib-state}] (if file (let [lib-file-path (.getPath file) cached-snapshot (get library-snapshot-cache lib-file-path) mtime (.lastModified file) snapshot (if (and cached-snapshot (= mtime (-> cached-snapshot meta :mtime))) cached-snapshot (with-meta (make-library-snapshot workspace lib-state) {:mtime mtime}))] (assoc ret lib-file-path snapshot)) ret)) {} lib-states)) (defn- make-library-snapshots [library-snapshot-cache lib-states] (into [] (comp (map :file) (filter some?) (map #(.getPath ^File %)) (map library-snapshot-cache)) lib-states)) (defn- make-builtins-snapshot [workspace] (let [unpack-path (system/defold-unpack-path) builtins-zip-file (io/file unpack-path "builtins" "builtins.zip") resources (:tree (resource/load-zip-resources workspace builtins-zip-file)) flat-resources (resource/resource-list-seq resources)] {:resources resources :status-map (into {} (map (juxt resource/proj-path (constantly {:version :constant :source :builtins})) flat-resources))})) (def reserved-proj-paths #{"/builtins" "/build" "/.internal" "/.git"}) (def ^:private ignored-proj-paths-atom (atom nil)) (defn- ignored-proj-paths [^File root] (assert (and (some? root) (.isDirectory root))) (swap! ignored-proj-paths-atom (fn [ignored-proj-paths] (if (some? ignored-proj-paths) ignored-proj-paths (let [defignore-file (io/file root ".defignore")] (if (.isFile defignore-file) (set (str/split-lines (slurp defignore-file))) #{})))))) (defn ignored-proj-path? [^File root path] (contains? (ignored-proj-paths root) path)) (defn reserved-proj-path? [^File root path] (or (reserved-proj-paths path) (ignored-proj-path? root path))) (defn- file-resource-filter [^File root ^File f] (not (or (= (.charAt (.getName f) 0) \.) (reserved-proj-path? root (resource/file->proj-path root f))))) (defn- make-file-tree ([workspace ^File file] (make-file-tree workspace (io/file (g/node-value workspace :root)) file)) ([workspace ^File root ^File file] (let [children (into [] (comp (filter (partial file-resource-filter root)) (map #(make-file-tree workspace root %))) (.listFiles file))] (resource/make-file-resource workspace (.getPath root) file children)))) (defn- file-resource-status [r] (assert (resource/file-resource? r)) {:version (str (.lastModified ^File (io/file r))) :source :directory}) (defn file-resource-status-map-entry [r] [(resource/proj-path r) (file-resource-status r)]) (defn file-resource-status-map-entry? [[proj-path {:keys [version source]}]] (and (string? proj-path) (str/starts-with? proj-path "/") (= :directory source) (try (Long/parseUnsignedLong version) true (catch NumberFormatException _ false)))) (defn- make-directory-snapshot [workspace ^File root] (assert (and root (.isDirectory root))) (let [resources (resource/children (make-file-tree workspace root)) flat-resources (resource/resource-list-seq resources)] {:resources resources :status-map (into {} (map file-resource-status-map-entry) flat-resources)})) (defn- resource-paths [snapshot] (set (keys (:status-map snapshot)))) (defn empty-snapshot [] {:resources nil :status-map nil :errors nil}) (defn- combine-snapshots [snapshots] (reduce (fn [result snapshot] (if-let [collisions (seq (clojure.set/intersection (resource-paths result) (resource-paths snapshot)))] (update result :errors conj {:collisions (select-keys (:status-map snapshot) collisions)}) (-> result (update :resources concat (:resources snapshot)) (update :status-map merge (:status-map snapshot))))) (empty-snapshot) snapshots)) (defn- make-debugger-snapshot [workspace] (let [base-path (if (system/defold-dev?) ;; Use local debugger support files so we can see ;; changes to them instantly without re-packing/restarting. (.getAbsolutePath (io/file "bundle-resources")) (system/defold-unpack-path)) root (io/file base-path "_defold/debugger") mount-root (io/file base-path) resources (resource/children (make-file-tree workspace mount-root root)) flat-resources (resource/resource-list-seq resources)] {:resources resources :status-map (into {} (map file-resource-status-map-entry) flat-resources)})) (defn update-snapshot-status [snapshot file-resource-status-map-entries] (assert (every? file-resource-status-map-entry? file-resource-status-map-entries)) (update snapshot :status-map into file-resource-status-map-entries)) (defn make-snapshot-info [workspace project-directory library-uris snapshot-cache] (let [lib-states (library/current-library-state project-directory library-uris) new-library-snapshot-cache (update-library-snapshot-cache snapshot-cache workspace lib-states)] {:snapshot (combine-snapshots (list* (make-builtins-snapshot workspace) (make-directory-snapshot workspace project-directory) (make-debugger-snapshot workspace) (make-library-snapshots new-library-snapshot-cache lib-states))) :snapshot-cache new-library-snapshot-cache})) (defn make-resource-map [snapshot] (into {} (map (juxt resource/proj-path identity) (resource/resource-list-seq (:resources snapshot))))) (defn- resource-status [snapshot path] (get-in snapshot [:status-map path])) (defn diff [old-snapshot new-snapshot] (let [old-map (make-resource-map old-snapshot) new-map (make-resource-map new-snapshot) old-paths (set (keys old-map)) new-paths (set (keys new-map)) common-paths (clojure.set/intersection new-paths old-paths) added-paths (clojure.set/difference new-paths old-paths) removed-paths (clojure.set/difference old-paths new-paths) changed-paths (filter #(not= (resource-status old-snapshot %) (resource-status new-snapshot %)) common-paths) added (map new-map added-paths) removed (map old-map removed-paths) changed (map new-map changed-paths)] (assert (empty? (clojure.set/intersection (set added) (set removed)))) (assert (empty? (clojure.set/intersection (set added) (set changed)))) (assert (empty? (clojure.set/intersection (set removed) (set changed)))) {:added added :removed removed :changed changed})) (defn empty-diff? [diff] (not (or (seq (:added diff)) (seq (:removed diff)) (seq (:changed diff)))))
63233
;; 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.resource-watch (:require [clojure.java.io :as io] [clojure.string :as str] [editor.settings-core :as settings-core] [editor.library :as library] [editor.resource :as resource] [editor.system :as system] [dynamo.graph :as g]) (:import [java.io File] [java.net URI])) (set! *warn-on-reflection* true) (defn- resource-root-dir [resource] (when-let [path-splits (seq (rest (str/split (resource/proj-path resource) #"/")))] ; skip initial "" (if (= (count path-splits) 1) (when (= (resource/source-type resource) :folder) (first path-splits)) (first path-splits)))) (defn parse-include-dirs [include-string] (filter (comp not str/blank?) (str/split include-string #"[,\s]"))) (defn- extract-game-project-include-dirs [game-project-resource] (with-open [reader (io/reader game-project-resource)] (let [settings (settings-core/parse-settings reader)] (parse-include-dirs (str (settings-core/get-setting settings ["library" "include_dirs"])))))) (defn- load-library-zip [workspace file] (let [base-path (library/library-base-path file) zip-resources (resource/load-zip-resources workspace file base-path) game-project-resource (first (filter (fn [resource] (= "game.project" (resource/resource-name resource))) (:tree zip-resources)))] (when game-project-resource (let [include-dirs (set (extract-game-project-include-dirs game-project-resource))] (update zip-resources :tree (fn [tree] (filter #(include-dirs (resource-root-dir %)) tree))))))) (defn- make-library-snapshot [workspace lib-state] (let [file ^File (:file lib-state) tag (:tag lib-state) uri-string (.toString ^URI (:uri lib-state)) zip-file-version (if-not (str/blank? tag) tag (str (.lastModified file))) {resources :tree crc :crc} (load-library-zip workspace file) flat-resources (resource/resource-list-seq resources)] {:resources resources :status-map (into {} (map (fn [resource] (let [path (resource/proj-path resource) version (str zip-file-version ":" (crc path))] [path {:version version :source :library :library uri-string}])) flat-resources))})) (defn- update-library-snapshot-cache [library-snapshot-cache workspace lib-states] (reduce (fn [ret {:keys [^File file] :as lib-state}] (if file (let [lib-file-path (.getPath file) cached-snapshot (get library-snapshot-cache lib-file-path) mtime (.lastModified file) snapshot (if (and cached-snapshot (= mtime (-> cached-snapshot meta :mtime))) cached-snapshot (with-meta (make-library-snapshot workspace lib-state) {:mtime mtime}))] (assoc ret lib-file-path snapshot)) ret)) {} lib-states)) (defn- make-library-snapshots [library-snapshot-cache lib-states] (into [] (comp (map :file) (filter some?) (map #(.getPath ^File %)) (map library-snapshot-cache)) lib-states)) (defn- make-builtins-snapshot [workspace] (let [unpack-path (system/defold-unpack-path) builtins-zip-file (io/file unpack-path "builtins" "builtins.zip") resources (:tree (resource/load-zip-resources workspace builtins-zip-file)) flat-resources (resource/resource-list-seq resources)] {:resources resources :status-map (into {} (map (juxt resource/proj-path (constantly {:version :constant :source :builtins})) flat-resources))})) (def reserved-proj-paths #{"/builtins" "/build" "/.internal" "/.git"}) (def ^:private ignored-proj-paths-atom (atom nil)) (defn- ignored-proj-paths [^File root] (assert (and (some? root) (.isDirectory root))) (swap! ignored-proj-paths-atom (fn [ignored-proj-paths] (if (some? ignored-proj-paths) ignored-proj-paths (let [defignore-file (io/file root ".defignore")] (if (.isFile defignore-file) (set (str/split-lines (slurp defignore-file))) #{})))))) (defn ignored-proj-path? [^File root path] (contains? (ignored-proj-paths root) path)) (defn reserved-proj-path? [^File root path] (or (reserved-proj-paths path) (ignored-proj-path? root path))) (defn- file-resource-filter [^File root ^File f] (not (or (= (.charAt (.getName f) 0) \.) (reserved-proj-path? root (resource/file->proj-path root f))))) (defn- make-file-tree ([workspace ^File file] (make-file-tree workspace (io/file (g/node-value workspace :root)) file)) ([workspace ^File root ^File file] (let [children (into [] (comp (filter (partial file-resource-filter root)) (map #(make-file-tree workspace root %))) (.listFiles file))] (resource/make-file-resource workspace (.getPath root) file children)))) (defn- file-resource-status [r] (assert (resource/file-resource? r)) {:version (str (.lastModified ^File (io/file r))) :source :directory}) (defn file-resource-status-map-entry [r] [(resource/proj-path r) (file-resource-status r)]) (defn file-resource-status-map-entry? [[proj-path {:keys [version source]}]] (and (string? proj-path) (str/starts-with? proj-path "/") (= :directory source) (try (Long/parseUnsignedLong version) true (catch NumberFormatException _ false)))) (defn- make-directory-snapshot [workspace ^File root] (assert (and root (.isDirectory root))) (let [resources (resource/children (make-file-tree workspace root)) flat-resources (resource/resource-list-seq resources)] {:resources resources :status-map (into {} (map file-resource-status-map-entry) flat-resources)})) (defn- resource-paths [snapshot] (set (keys (:status-map snapshot)))) (defn empty-snapshot [] {:resources nil :status-map nil :errors nil}) (defn- combine-snapshots [snapshots] (reduce (fn [result snapshot] (if-let [collisions (seq (clojure.set/intersection (resource-paths result) (resource-paths snapshot)))] (update result :errors conj {:collisions (select-keys (:status-map snapshot) collisions)}) (-> result (update :resources concat (:resources snapshot)) (update :status-map merge (:status-map snapshot))))) (empty-snapshot) snapshots)) (defn- make-debugger-snapshot [workspace] (let [base-path (if (system/defold-dev?) ;; Use local debugger support files so we can see ;; changes to them instantly without re-packing/restarting. (.getAbsolutePath (io/file "bundle-resources")) (system/defold-unpack-path)) root (io/file base-path "_defold/debugger") mount-root (io/file base-path) resources (resource/children (make-file-tree workspace mount-root root)) flat-resources (resource/resource-list-seq resources)] {:resources resources :status-map (into {} (map file-resource-status-map-entry) flat-resources)})) (defn update-snapshot-status [snapshot file-resource-status-map-entries] (assert (every? file-resource-status-map-entry? file-resource-status-map-entries)) (update snapshot :status-map into file-resource-status-map-entries)) (defn make-snapshot-info [workspace project-directory library-uris snapshot-cache] (let [lib-states (library/current-library-state project-directory library-uris) new-library-snapshot-cache (update-library-snapshot-cache snapshot-cache workspace lib-states)] {:snapshot (combine-snapshots (list* (make-builtins-snapshot workspace) (make-directory-snapshot workspace project-directory) (make-debugger-snapshot workspace) (make-library-snapshots new-library-snapshot-cache lib-states))) :snapshot-cache new-library-snapshot-cache})) (defn make-resource-map [snapshot] (into {} (map (juxt resource/proj-path identity) (resource/resource-list-seq (:resources snapshot))))) (defn- resource-status [snapshot path] (get-in snapshot [:status-map path])) (defn diff [old-snapshot new-snapshot] (let [old-map (make-resource-map old-snapshot) new-map (make-resource-map new-snapshot) old-paths (set (keys old-map)) new-paths (set (keys new-map)) common-paths (clojure.set/intersection new-paths old-paths) added-paths (clojure.set/difference new-paths old-paths) removed-paths (clojure.set/difference old-paths new-paths) changed-paths (filter #(not= (resource-status old-snapshot %) (resource-status new-snapshot %)) common-paths) added (map new-map added-paths) removed (map old-map removed-paths) changed (map new-map changed-paths)] (assert (empty? (clojure.set/intersection (set added) (set removed)))) (assert (empty? (clojure.set/intersection (set added) (set changed)))) (assert (empty? (clojure.set/intersection (set removed) (set changed)))) {:added added :removed removed :changed changed})) (defn empty-diff? [diff] (not (or (seq (:added diff)) (seq (:removed diff)) (seq (:changed diff)))))
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.resource-watch (:require [clojure.java.io :as io] [clojure.string :as str] [editor.settings-core :as settings-core] [editor.library :as library] [editor.resource :as resource] [editor.system :as system] [dynamo.graph :as g]) (:import [java.io File] [java.net URI])) (set! *warn-on-reflection* true) (defn- resource-root-dir [resource] (when-let [path-splits (seq (rest (str/split (resource/proj-path resource) #"/")))] ; skip initial "" (if (= (count path-splits) 1) (when (= (resource/source-type resource) :folder) (first path-splits)) (first path-splits)))) (defn parse-include-dirs [include-string] (filter (comp not str/blank?) (str/split include-string #"[,\s]"))) (defn- extract-game-project-include-dirs [game-project-resource] (with-open [reader (io/reader game-project-resource)] (let [settings (settings-core/parse-settings reader)] (parse-include-dirs (str (settings-core/get-setting settings ["library" "include_dirs"])))))) (defn- load-library-zip [workspace file] (let [base-path (library/library-base-path file) zip-resources (resource/load-zip-resources workspace file base-path) game-project-resource (first (filter (fn [resource] (= "game.project" (resource/resource-name resource))) (:tree zip-resources)))] (when game-project-resource (let [include-dirs (set (extract-game-project-include-dirs game-project-resource))] (update zip-resources :tree (fn [tree] (filter #(include-dirs (resource-root-dir %)) tree))))))) (defn- make-library-snapshot [workspace lib-state] (let [file ^File (:file lib-state) tag (:tag lib-state) uri-string (.toString ^URI (:uri lib-state)) zip-file-version (if-not (str/blank? tag) tag (str (.lastModified file))) {resources :tree crc :crc} (load-library-zip workspace file) flat-resources (resource/resource-list-seq resources)] {:resources resources :status-map (into {} (map (fn [resource] (let [path (resource/proj-path resource) version (str zip-file-version ":" (crc path))] [path {:version version :source :library :library uri-string}])) flat-resources))})) (defn- update-library-snapshot-cache [library-snapshot-cache workspace lib-states] (reduce (fn [ret {:keys [^File file] :as lib-state}] (if file (let [lib-file-path (.getPath file) cached-snapshot (get library-snapshot-cache lib-file-path) mtime (.lastModified file) snapshot (if (and cached-snapshot (= mtime (-> cached-snapshot meta :mtime))) cached-snapshot (with-meta (make-library-snapshot workspace lib-state) {:mtime mtime}))] (assoc ret lib-file-path snapshot)) ret)) {} lib-states)) (defn- make-library-snapshots [library-snapshot-cache lib-states] (into [] (comp (map :file) (filter some?) (map #(.getPath ^File %)) (map library-snapshot-cache)) lib-states)) (defn- make-builtins-snapshot [workspace] (let [unpack-path (system/defold-unpack-path) builtins-zip-file (io/file unpack-path "builtins" "builtins.zip") resources (:tree (resource/load-zip-resources workspace builtins-zip-file)) flat-resources (resource/resource-list-seq resources)] {:resources resources :status-map (into {} (map (juxt resource/proj-path (constantly {:version :constant :source :builtins})) flat-resources))})) (def reserved-proj-paths #{"/builtins" "/build" "/.internal" "/.git"}) (def ^:private ignored-proj-paths-atom (atom nil)) (defn- ignored-proj-paths [^File root] (assert (and (some? root) (.isDirectory root))) (swap! ignored-proj-paths-atom (fn [ignored-proj-paths] (if (some? ignored-proj-paths) ignored-proj-paths (let [defignore-file (io/file root ".defignore")] (if (.isFile defignore-file) (set (str/split-lines (slurp defignore-file))) #{})))))) (defn ignored-proj-path? [^File root path] (contains? (ignored-proj-paths root) path)) (defn reserved-proj-path? [^File root path] (or (reserved-proj-paths path) (ignored-proj-path? root path))) (defn- file-resource-filter [^File root ^File f] (not (or (= (.charAt (.getName f) 0) \.) (reserved-proj-path? root (resource/file->proj-path root f))))) (defn- make-file-tree ([workspace ^File file] (make-file-tree workspace (io/file (g/node-value workspace :root)) file)) ([workspace ^File root ^File file] (let [children (into [] (comp (filter (partial file-resource-filter root)) (map #(make-file-tree workspace root %))) (.listFiles file))] (resource/make-file-resource workspace (.getPath root) file children)))) (defn- file-resource-status [r] (assert (resource/file-resource? r)) {:version (str (.lastModified ^File (io/file r))) :source :directory}) (defn file-resource-status-map-entry [r] [(resource/proj-path r) (file-resource-status r)]) (defn file-resource-status-map-entry? [[proj-path {:keys [version source]}]] (and (string? proj-path) (str/starts-with? proj-path "/") (= :directory source) (try (Long/parseUnsignedLong version) true (catch NumberFormatException _ false)))) (defn- make-directory-snapshot [workspace ^File root] (assert (and root (.isDirectory root))) (let [resources (resource/children (make-file-tree workspace root)) flat-resources (resource/resource-list-seq resources)] {:resources resources :status-map (into {} (map file-resource-status-map-entry) flat-resources)})) (defn- resource-paths [snapshot] (set (keys (:status-map snapshot)))) (defn empty-snapshot [] {:resources nil :status-map nil :errors nil}) (defn- combine-snapshots [snapshots] (reduce (fn [result snapshot] (if-let [collisions (seq (clojure.set/intersection (resource-paths result) (resource-paths snapshot)))] (update result :errors conj {:collisions (select-keys (:status-map snapshot) collisions)}) (-> result (update :resources concat (:resources snapshot)) (update :status-map merge (:status-map snapshot))))) (empty-snapshot) snapshots)) (defn- make-debugger-snapshot [workspace] (let [base-path (if (system/defold-dev?) ;; Use local debugger support files so we can see ;; changes to them instantly without re-packing/restarting. (.getAbsolutePath (io/file "bundle-resources")) (system/defold-unpack-path)) root (io/file base-path "_defold/debugger") mount-root (io/file base-path) resources (resource/children (make-file-tree workspace mount-root root)) flat-resources (resource/resource-list-seq resources)] {:resources resources :status-map (into {} (map file-resource-status-map-entry) flat-resources)})) (defn update-snapshot-status [snapshot file-resource-status-map-entries] (assert (every? file-resource-status-map-entry? file-resource-status-map-entries)) (update snapshot :status-map into file-resource-status-map-entries)) (defn make-snapshot-info [workspace project-directory library-uris snapshot-cache] (let [lib-states (library/current-library-state project-directory library-uris) new-library-snapshot-cache (update-library-snapshot-cache snapshot-cache workspace lib-states)] {:snapshot (combine-snapshots (list* (make-builtins-snapshot workspace) (make-directory-snapshot workspace project-directory) (make-debugger-snapshot workspace) (make-library-snapshots new-library-snapshot-cache lib-states))) :snapshot-cache new-library-snapshot-cache})) (defn make-resource-map [snapshot] (into {} (map (juxt resource/proj-path identity) (resource/resource-list-seq (:resources snapshot))))) (defn- resource-status [snapshot path] (get-in snapshot [:status-map path])) (defn diff [old-snapshot new-snapshot] (let [old-map (make-resource-map old-snapshot) new-map (make-resource-map new-snapshot) old-paths (set (keys old-map)) new-paths (set (keys new-map)) common-paths (clojure.set/intersection new-paths old-paths) added-paths (clojure.set/difference new-paths old-paths) removed-paths (clojure.set/difference old-paths new-paths) changed-paths (filter #(not= (resource-status old-snapshot %) (resource-status new-snapshot %)) common-paths) added (map new-map added-paths) removed (map old-map removed-paths) changed (map new-map changed-paths)] (assert (empty? (clojure.set/intersection (set added) (set removed)))) (assert (empty? (clojure.set/intersection (set added) (set changed)))) (assert (empty? (clojure.set/intersection (set removed) (set changed)))) {:added added :removed removed :changed changed})) (defn empty-diff? [diff] (not (or (seq (:added diff)) (seq (:removed diff)) (seq (:changed diff)))))
[ { "context": "(def libhoney-version \"1.0.6\")\n\n(defproject conormcd/clj-honeycomb (str libhoney-version\n ", "end": 50, "score": 0.6387937068939209, "start": 44, "tag": "USERNAME", "value": "conorm" }, { "context": "uilt on libhoney-java.\"\n :url \"http://github.com/conormcd/clj-honeycomb\"\n :license {:name \"Apache License,", "end": 351, "score": 0.9987234473228455, "start": 343, "tag": "USERNAME", "value": "conormcd" }, { "context": "Version 2.0\"\n :url \"https://github.com/conormcd/clj-honeycomb/blob/master/LICENSE\"}\n :repositori", "end": 460, "score": 0.9988760948181152, "start": 452, "tag": "USERNAME", "value": "conormcd" }, { "context": "username\n :password :env/clojars_password\n :sign-releases fals", "end": 682, "score": 0.9860442876815796, "start": 662, "tag": "PASSWORD", "value": "env/clojars_password" }, { "context": "sername\n :password :env/clojars_password\n :sign-releases fal", "end": 924, "score": 0.8866519927978516, "start": 904, "tag": "PASSWORD", "value": "env/clojars_password" } ]
project.clj
conormcd/clj-honeycomb
17
(def libhoney-version "1.0.6") (defproject conormcd/clj-honeycomb (str libhoney-version (or (some->> "CIRCLE_BUILD_NUM" System/getenv (str ".")) "-dev")) :description "A Clojure interface to Honeycomb.io, built on libhoney-java." :url "http://github.com/conormcd/clj-honeycomb" :license {:name "Apache License, Version 2.0" :url "https://github.com/conormcd/clj-honeycomb/blob/master/LICENSE"} :repositories [["releases" {:url "https://clojars.org/repo" :username :env/clojars_username :password :env/clojars_password :sign-releases false}] ["snapshots" {:url "https://clojars.org/repo" :username :env/clojars_username :password :env/clojars_password :sign-releases false}]] :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/data.codec "0.1.1"] [org.clojure/data.json "0.2.6"] [clojure-future-spec "1.9.0"] [io.honeycomb.libhoney/libhoney-java ~libhoney-version]] :java-source-paths ["src-java"] :pedantic? :abort :global-vars {*warn-on-reflection* true} :plugins [[lein-cljfmt "0.6.3"] [lein-cloverage "1.0.13" :exclusions [org.clojure/clojure]] [lein-codox "0.10.5"] [lein-kibit "0.1.6"] [lein-nvd "0.6.0" :exclusions [org.apache.maven.wagon/wagon-http org.codehaus.plexus/plexus-utils org.slf4j/slf4j-api org.slf4j/jcl-over-slf4j]]] :nvd {:data-directory "/tmp/nvd/data"} :profiles {:dev {:dependencies [[cloverage "1.0.13" :exclusions [org.clojure/clojure]] [org.clojure/data.json "0.2.6"] [org.clojure/test.check "0.10.0-alpha3"] [ch.qos.logback/logback-classic "1.2.3"] [ring/ring-mock "0.3.2"] [se.haleby/stub-http "0.2.7"]] :codox {:exclude-vars nil :namespaces :all}}})
113815
(def libhoney-version "1.0.6") (defproject conormcd/clj-honeycomb (str libhoney-version (or (some->> "CIRCLE_BUILD_NUM" System/getenv (str ".")) "-dev")) :description "A Clojure interface to Honeycomb.io, built on libhoney-java." :url "http://github.com/conormcd/clj-honeycomb" :license {:name "Apache License, Version 2.0" :url "https://github.com/conormcd/clj-honeycomb/blob/master/LICENSE"} :repositories [["releases" {:url "https://clojars.org/repo" :username :env/clojars_username :password :<PASSWORD> :sign-releases false}] ["snapshots" {:url "https://clojars.org/repo" :username :env/clojars_username :password :<PASSWORD> :sign-releases false}]] :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/data.codec "0.1.1"] [org.clojure/data.json "0.2.6"] [clojure-future-spec "1.9.0"] [io.honeycomb.libhoney/libhoney-java ~libhoney-version]] :java-source-paths ["src-java"] :pedantic? :abort :global-vars {*warn-on-reflection* true} :plugins [[lein-cljfmt "0.6.3"] [lein-cloverage "1.0.13" :exclusions [org.clojure/clojure]] [lein-codox "0.10.5"] [lein-kibit "0.1.6"] [lein-nvd "0.6.0" :exclusions [org.apache.maven.wagon/wagon-http org.codehaus.plexus/plexus-utils org.slf4j/slf4j-api org.slf4j/jcl-over-slf4j]]] :nvd {:data-directory "/tmp/nvd/data"} :profiles {:dev {:dependencies [[cloverage "1.0.13" :exclusions [org.clojure/clojure]] [org.clojure/data.json "0.2.6"] [org.clojure/test.check "0.10.0-alpha3"] [ch.qos.logback/logback-classic "1.2.3"] [ring/ring-mock "0.3.2"] [se.haleby/stub-http "0.2.7"]] :codox {:exclude-vars nil :namespaces :all}}})
true
(def libhoney-version "1.0.6") (defproject conormcd/clj-honeycomb (str libhoney-version (or (some->> "CIRCLE_BUILD_NUM" System/getenv (str ".")) "-dev")) :description "A Clojure interface to Honeycomb.io, built on libhoney-java." :url "http://github.com/conormcd/clj-honeycomb" :license {:name "Apache License, Version 2.0" :url "https://github.com/conormcd/clj-honeycomb/blob/master/LICENSE"} :repositories [["releases" {:url "https://clojars.org/repo" :username :env/clojars_username :password :PI:PASSWORD:<PASSWORD>END_PI :sign-releases false}] ["snapshots" {:url "https://clojars.org/repo" :username :env/clojars_username :password :PI:PASSWORD:<PASSWORD>END_PI :sign-releases false}]] :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/data.codec "0.1.1"] [org.clojure/data.json "0.2.6"] [clojure-future-spec "1.9.0"] [io.honeycomb.libhoney/libhoney-java ~libhoney-version]] :java-source-paths ["src-java"] :pedantic? :abort :global-vars {*warn-on-reflection* true} :plugins [[lein-cljfmt "0.6.3"] [lein-cloverage "1.0.13" :exclusions [org.clojure/clojure]] [lein-codox "0.10.5"] [lein-kibit "0.1.6"] [lein-nvd "0.6.0" :exclusions [org.apache.maven.wagon/wagon-http org.codehaus.plexus/plexus-utils org.slf4j/slf4j-api org.slf4j/jcl-over-slf4j]]] :nvd {:data-directory "/tmp/nvd/data"} :profiles {:dev {:dependencies [[cloverage "1.0.13" :exclusions [org.clojure/clojure]] [org.clojure/data.json "0.2.6"] [org.clojure/test.check "0.10.0-alpha3"] [ch.qos.logback/logback-classic "1.2.3"] [ring/ring-mock "0.3.2"] [se.haleby/stub-http "0.2.7"]] :codox {:exclude-vars nil :namespaces :all}}})
[ { "context": " :format-key :dif10})\n granule (d/ingest-concept-with-metadata", "end": 2122, "score": 0.9486689567565918, "start": 2120, "tag": "KEY", "value": "10" }, { "context": " :format-key :echo10})]\n (index/wait-until-indexed)\n\n (testing \"", "end": 2594, "score": 0.9682326316833496, "start": 2592, "tag": "KEY", "value": "10" }, { "context": " :format-key :dif10})\n g1 (d/ingest-concept-with-metadata-file", "end": 27601, "score": 0.9838869571685791, "start": 27599, "tag": "KEY", "value": "10" }, { "context": " :format-key :echo10})]\n [coll1 g1]))\n\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 28038, "score": 0.9016397595405579, "start": 28032, "tag": "KEY", "value": "echo10" } ]
system-int-test/test/cmr/system_int_test/search/granule_orbit_search_test.clj
eereiter/Common-Metadata-Repository
0
(ns cmr.system-int-test.search.granule-orbit-search-test "Tests for spatial search with orbital back tracking." (:require [clojure.string :as s] [clojure.test :refer :all] [cmr.common.util :as u] [cmr.spatial.codec :as codec] [cmr.spatial.derived :as derived] [cmr.spatial.kml :as kml] [cmr.spatial.line-string :as l] [cmr.spatial.mbr :as m] [cmr.spatial.point :as point] [cmr.spatial.polygon :as poly] [cmr.spatial.ring-relations :as rr] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.core :as d] [cmr.system-int-test.data2.granule :as dg] [cmr.system-int-test.search.granule-spatial-search-test :as st] [cmr.system-int-test.utils.dev-system-util :as dev-sys-util] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search] [cmr.umm.umm-spatial :as umm-s])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"})) (defn- make-gran ([coll ur asc-crossing start-lat start-dir end-lat end-dir] (make-gran coll ur asc-crossing start-lat start-dir end-lat end-dir {})) ([coll ur asc-crossing start-lat start-dir end-lat end-dir other-attribs] (let [orbit (dg/orbit asc-crossing start-lat start-dir end-lat end-dir)] (d/ingest "PROV1" (dg/granule coll (merge {:granule-ur ur :spatial-coverage (apply dg/spatial orbit nil)} other-attribs)))))) (deftest orbit-bug-CMR-4722 (let [coll (d/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-collection.xml" {:provider-id "PROV1" :concept-type :collection :native-id "OMSO2-collection" :format-key :dif10}) granule (d/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-granule.xml" {:provider-id "PROV1" :concept-type :granule :concept-id "C4-PROV1" :native-id "OMSO2-granule" :format-key :echo10})] (index/wait-until-indexed) (testing "Orbit search crossing the equator for OMSO2 granules." (u/are3 [items wnes] (let [found (search/find-refs :granule {:bounding-box (codec/url-encode (apply m/mbr wnes)) :provider "PROV1" :page-size 50}) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Rectangle that should find the granule" [granule] [150 70 170 60] "Rectangle not crossing the equator that should not find the granule" [] [-128.32 53.602 -46.758 1.241] "CMR-4722: Search crossing the equator should not erroneously find the granule" [] [-128.32 53.602 -46.758 -1.241])))) (deftest orbit-bug-CMR-5007 (let [coll (d/ingest-concept-with-metadata-file "CMR-5007/dif10_Collection_C1239966837-GES_DISC.xml" {:provider-id "PROV1" :concept-type :collection :native-id "GES_DISC-collection" :format-key :dif10}) granule (d/ingest-concept-with-metadata-file "CMR-5007/echo10_Granlue_G1278223734-GES_DISC.xml" {:provider-id "PROV1" :concept-type :granule :concept-id "C4-PROV1" :native-id "GES_DISC-granule" :format-key :echo10})] (index/wait-until-indexed) (testing "Polygon search for granules near poles." (u/are3 [items coords params] (let [found (search/find-refs :granule (merge {:polygon (apply st/search-poly coords) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "CMR-5007: Search north pole with altitude > 86.52 won't throw 500 error." [granule] [-30,87 90,87 150,87 -150,87 -90,87 -30,87] nil "CMR-5007: Search south pole with altitude < -86.52 won't throw 500 error." [granule] [-30,-87 -90,-87 -150,-87 150,-87 90,-87 -30,-87] nil)) (testing "line searches" (u/are3 [items coords params] (let [found (search/find-refs :granule {:line (codec/url-encode (l/ords->line-string :geodetic coords)) :provider "PROV1" :page-size 50}) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Line search with altitude < -86.52 won't throw 500 error." [granule] [-180,-86.6,0,0] nil "Line search with altitude > 86.52 won't throw 500 error." [granule] [0,0 180, 86.6] nil)))) ;; This tests searching for bounding boxes or polygons that cross the start circular ;; latitude of the collection with fractional orbit granules. This was added to test ;; the fix for this issue as described in CMR-1168 and uses the collection/granules from ;; that issue. (deftest fractional-orbit-non-zero-start-clat (let [orbit-parameters {:swath-width 2 :period 96.7 :inclination-angle 94.0 :number-of-orbits 0.25 :start-circular-latitude 50.0} coll1 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit orbit-parameters})})) g1 (make-gran coll1 "gran1" 70.80471 50.0 :asc 50.0 :desc) g2 (make-gran coll1 "gran2" 70.80471 50.0 :desc -50.0 :desc) g3 (make-gran coll1 "gran3" 70.80471 -50.0 :desc -50.0 :asc) g4 (make-gran coll1 "gran4" 70.80471 -50.0 :asc 50 :asc)] (index/wait-until-indexed) (testing "Bounding box" (u/are2 [items wnes params] (let [found (search/find-refs :granule (merge {:bounding-box (codec/url-encode (apply m/mbr wnes)) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Rectangle crossing the start circular latitude of the collection" [g1] [54.844 52.133 97.734 25.165] nil "Rectangle crossing the start circular latitdue of the colletion on the other side of the earth" [g1 g2] [-125.156 52.133 -82.266 25.165] nil "Rectangle crossing the start circular latitude * -1" [g3 g4] [54.844 -25.165 97.734 -52.133] nil "Rectangle touching the north pole" [g1] [-90 90 90 85] nil "Rectangle touching the south pole" [g3] [0 -85 180 -90] nil "Rectangle crossing the antimeridian and the collection start circular latitude" [g1 g2] [125.156 52.133 -82.266 25.165] nil "The whole earth" [g1 g2 g3 g4] [-180 90 180 -90] nil)) (testing "Polygon" (u/are2 [items coords params] (let [found (search/find-refs :granule (merge {:polygon (apply st/search-poly coords) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Rectangle crossing the start circular latitude of the collection" [g1] [54.844,25.165 97.734,25.165 97.734,52.133 54.844,52.133 54.844,25.165] nil "Rectangle crossing the start circular latitdue of the colletion on the other side of the earth" [g1 g2] [-125.156,52.133 -125.156,25.165 -82.266,25.165 -82.266,52.133 -125.156,52.133] nil "Rectangle crossing the start circular latitude * -1" [g3 g4] [97.734,-52.133 97.734,-25.165 54.844,-25.165 54.844,-52.133 97.734,-52.133] nil "Triangle touching the north pole" [g1] [0,90 -45,85 45,85 0,90] nil "Pentagon touching the south pole" [g3 g4] [97.734,-52.133 97.734,-25.165 54.844,-25.165 54.844,-52.133 97.734,-90 97.734,-52.133] nil "Rectangle crossing the antimeridian and the collection start circular latitude" [g1 g2] [125.156,52.133 125.156,25.165 -82.266,25.165 -82.266,52.133 125.156,52.133] nil "Pentagon over the north pole" [g1] [0,80 72,80 144,80 -144,80 -72,80 0,80] nil "Pentagon over the south pole" [g3] [0,-80 -72,-80 -144,-80 144,-80 72,-80 0,-80] nil)))) (deftest orbit-search (let [;; orbit parameters op1 {:swath-width 1450 :period 98.88 :inclination-angle 98.15 :number-of-orbits 0.5 :start-circular-latitude -90} op2 {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude -50} ;; orbit parameters with missing value to test defaulting to 0 op3-bad {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude nil} coll1 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op1})})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params2" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op2})})) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params3" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op3-bad})})) g1 (make-gran coll1 "gran1" -158.1 81.8 :desc -81.8 :desc) g2 (make-gran coll1 "gran2" 177.16 -81.8 :asc 81.8 :asc) g3 (make-gran coll1 "gran3" 127.73 81.8 :desc -81.8 :desc) g4 (make-gran coll1 "gran4" 103 -81.8 :asc 81.8 :asc) g5 (make-gran coll2 "gran5" 79.88192 50 :asc 50 :desc) g6 (make-gran coll2 "gran6" 55.67938 -50 :asc 50 :asc) g7 (make-gran coll2 "gran7" 31.48193 50 :desc -50 :desc) g8 (make-gran coll2 "gran8" 7.28116 -50 :asc 50 :asc) g9 (make-gran coll3 "gran9" 127.73 81.8 :desc -81.8 :desc)] (index/wait-until-indexed) (testing "bounding rectangle searches" (u/are2 [items wnes params] (let [found (search/find-refs :granule (merge {:bounding-box (codec/url-encode (apply m/mbr wnes)) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Orbits crossing a rectangle over the equator and anti-meridian" [g2 g7] [145 45 -145 -45] nil "Orbits crossing a rectangle over the equator and meridian" [g1 g3 g8] [-45 45 45 -45] nil "Orbits crossing a rectangle in the western hemisphere near the north pole" [g5] [-90 89 -45 85] nil "Orbits crossing a rectangle in the southern hemisphere crossing the anti-meridian" [g2 g3 g4 g7] [145 -45 -145 -85] nil "Specifying parent collection" [g2] [145 45 -145 -45] {:concept-id (:concept-id coll1)})) (testing "point searches" (are [items lon_lat params] (let [found (search/find-refs :granule {:point (codec/url-encode (apply point/point lon_lat)) :provider "PROV1" :page-size 50}) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) [g3] [-45,45] nil [g1] [0,-20] nil [g2] [-180,0] nil)) (testing "line searches" (are [items coords params] (let [found (search/find-refs :granule {:line (codec/url-encode (l/ords->line-string :geodetic coords)) :provider "PROV1" :page-size 50}) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) ;; Line crossing prime meridian and equator [g1 g8] [-45,-45 45,45] nil)) ;; Line crossing the antimeridian - This case gets different results from catalog-rest ;; (returns g2 & g7) and will fail if uncommented. Need to determine if it ;; is supposed to return both granules or not. ; [g2] [179,-45 -170, 30] nil (testing "polygon searches" (u/are2 [items coords params] (let [found (search/find-refs :granule (merge {:polygon (apply st/search-poly coords) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Triangle crossing prime meridian" [g1 g8] [-45,-45 45,-45 45,0, -45,-45] nil "Pentagon over the north pole" [g1 g2 g3 g4 g5 g9] [0,80 72,80 144,80 -144,80 -72,80 0,80] nil "Concave polygon crossing antimeridian and equator" [g2 g4 g7 g9] [170,-70 -170,-80 -175,20 -179,-10 175,25 170,-70] nil)))) (deftest multi-orbit-search (let [;; orbit parameters op1 {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 14 :start-circular-latitude 50} op2 {:swath-width 400 :period 98.88 :inclination-angle 98.3 :number-of-orbits 1 :start-circular-latitude 0} coll1 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op1})})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params2" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op2})})) g1 (make-gran coll1 "gran1" 104.0852 50 :asc 50 :asc) g2 (make-gran coll2 "gran2" 31.946 70.113955 :asc -71.344289 :desc)] (index/wait-until-indexed) (testing "bounding rectangle searches" (u/are2 [items wnes params] (let [found (search/find-refs :granule (merge {:bounding-box (codec/url-encode (apply m/mbr wnes)) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Search large box that finds the granule" [g1] [-134.648 69.163 76.84 65.742] {:concept-id (:concept-id coll1)} "Search near equator that doesn't intersect granule" [] [0 1 1 0] {:concept-id (:concept-id coll1)} "Search near equator that intersects granule" [g1] [1 11 15 1] {:concept-id (:concept-id coll1)} "Search near north pole - FIXME" [] [1 89.5 1.5 89] {:concept-id (:concept-id coll1)} "Search for granules with exactly one orbit does not match areas seen on the second pass" [] [175.55 38.273 -164.883 17.912] {:concept-id (:concept-id coll2)})))) ;; The following test is deliberately commented out because it is marked as @broken ;; in ECHO. It is included here for completeness. ;; ;; The following comment is repeated verbatim from the ECHO cucumber test: ;; ;; Orbit searching is known to have some issues. The following query successfully finds a granule ;; when it appears from the drawing of the granule in Reverb that it shouldn't. I manually verified that ;; the query does match the query output in echo-catalog when searching the legacy provider schemas. ;; At some point it would be a good idea for someone in the ECHO organization to have a better understanding ;; of the backtrack algorithm and be able to definitively state when an orbit granule doesn intersect a ;; particular bounding box. ;; ; "Broken test" ; [] [0 1 6 0] nil (deftest ascending-crossing-precision-test (let [coll (d/ingest-concept-with-metadata-file "iso-samples/CMR-5269-IsoMendsCollection.xml" {:provider-id "PROV1" :concept-type :collection :format-key :iso19115}) gran (d/ingest-concept-with-metadata-file "iso-samples/CMR-5269-IsoSmapGranule.xml" {:provider-id "PROV1" :concept-type :granule :format-key :iso-smap}) _ (index/wait-until-indexed) json-response (search/find-concepts-json :granule {:concept-id (:concept-id gran)}) granule-json (-> json-response :results :entries first) expected-points-in-polygons [(point/point 25.235719457640535 -21.19078458692315) (point/point 23.13297924763377 -39.771484792279814) (point/point 22.646805419273353 -43.610681332179986) (point/point 22.199982651743795 -43.5950693405511) (point/point 22.711995770988835 -39.7567775481513) (point/point 24.8885475222218 -21.178659983890096) (point/point 25.235719457640535 -21.19078458692315)] expected-ascending-crossing -140.637396 expected-equator-crossings [-140.637396] actual-ascending-crossing (-> granule-json :orbit :ascending-crossing) actual-equator-crossings (->> granule-json :orbit-calculated-spatial-domains (keep :equator-crossing-longitude)) actual-points-in-polygons (->> granule-json :shapes (mapcat :rings) (mapcat :points))] (is (= expected-points-in-polygons actual-points-in-polygons)) (is (= expected-ascending-crossing actual-ascending-crossing)) (is (= expected-equator-crossings actual-equator-crossings)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Visualizations ;; ;; Ingests for visualizations (defn- ingest-orbit-coll-and-granule-swath [] (let [coll (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit {:inclination-angle 98.2 :period 100.0 :swath-width 2 :start-circular-latitude 0 :number-of-orbits 0.25}})}))] [coll (make-gran coll "gran1" 88.0 0 :asc 88 :asc)])) (defn- ingest-orbit-coll-and-granule [] (let [coll (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude 50}})}))] ; -50 ; 0 [coll (make-gran coll "gran1" 70.80471 ; ascending crossing -50 :asc ; start lat, start dir 50 :asc ; end lat end dir {:beginning-date-time "2003-09-27T17:03:27.000000Z" :ending-date-time "2003-09-27T17:30:23.000000Z" :orbit-calculated-spatial-domains [{:orbit-number 3838 :equator-crossing-longitude 70.80471 :equator-crossing-date-time "2003-09-27T15:40:15Z"} {:orbit-number 3839 :equator-crossing-longitude 46.602737 :equator-crossing-date-time "2003-09-27T17:16:56Z"}]})])) (defn- ingest-orbit-coll-and-granules-north-pole [] (let [coll (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude ;50 -50}})}))] ; 0 [coll (make-gran coll "gran1" 31.48193 50 :desc -50 :desc)])) (defn- ingest-orbit-coll-and-granules-prime-meridian [] (let [coll (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude -50}})}))] [coll (make-gran coll "gran1" 7.28116 -50 :asc 50 :asc)])) (defn- ingest-CMR-4722-data [] (let [coll1 (d/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-collection.xml" {:provider-id "PROV1" :concept-type :collection :native-id "orbit3" :format-key :dif10}) g1 (d/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-granule.xml" {:provider-id "PROV1" :concept-type :granule :concept-id "C1-PROV1" :native-id "granule1" :format-key :echo10})] [coll1 g1])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Visualization code (defn- mbr-finds-granule? [mbr] (let [resp (search/find-refs :granule {:bounding-box (codec/url-encode mbr) :page-size 0 :provider "PROV1"})] (> (:hits resp) 0))) (defn- polygon-finds-granule? [coords] (let [resp (search/find-refs :granule {:provider "PROV1" :polygon (apply st/search-poly coords) :page-size 0})] (> (:hits resp) 0))) (defn- create-mbrs "Split an area on the earth into a bunch of bounding rectangles and return them as a list" ([] (create-mbrs -180.0 180.0 -90.0 90.0 3.0)) ([min-lon max-lon min-lat max-lat step] (for [[west east] (partition 2 1 (range min-lon (inc max-lon) step)) [south north] (partition 2 1 (range min-lat (inc max-lat) step))] (m/mbr west north east south)))) (defn- mbr->polygon-coords "Get the coordinates from the corners of an mbr" [mbr] (let [corners (-> (m/corner-points mbr) distinct reverse) points (conj (vec corners) (first corners))] (point/points->ords points))) (defn- create-polygons "Split an area on the earth into a bunch of box shaped polygons and return them as a list" ([] (create-polygons -180.0 180.0 -90.0 90.0 30.0)) ([min-lon max-lon min-lat max-lat step] (let [mbrs (create-mbrs min-lon max-lon min-lat max-lat step)] (map mbr->polygon-coords mbrs)))) (comment ;; 1. Perform setup ;; evaluate this block ;; First modify the metadata in ingest-orbit-coll-and-granule if you want. (do (dev-sys-util/reset) (taoensso.timbre/set-level! :warn) ; turn down log level (ingest/create-provider {:provider-guid "provguid1" :provider-id "PROV1"}) ; (ingest-orbit-coll-and-granules-north-pole) ; (ingest-orbit-coll-and-granules-prime-meridian) ; (ingest-orbit-coll-and-granule) ; (ingest-orbit-coll-and-granule-swath) (ingest-CMR-4722-data)) ;; Figure out how many mbrs we're going to search with to get an idea of how long things will take (count (create-mbrs 45.0 90.0 -55.0 55.0 3)) (count (create-mbrs)) ;; 2. Evaluate this block to find all the mbrs. ;; It will print out "Elapsed time: XXXX msecs" when it's done (def matching-mbrs "Creates mbrs all over the globe as search areas. Returns any mbrs which find granules in the local system. Takes awhile to run, so performed as a future." (future (time (doall (filter mbr-finds-granule? (create-mbrs -180.0 180.0 -90.0 90.0 3)))))) ;; Or evaluate this block to use polygons instead of mbrs (def matching-polys (future (time (doall (keep (fn [coords] (when (polygon-finds-granule? coords) (umm-s/set-coordinate-system :geodetic (apply st/polygon coords)))) (create-polygons -46.0 46.0 -89.0 89.0 3)))))) (mbr-finds-granule? (m/mbr 40 30 45 24)) ;; How many were found? This will block on the future (count @matching-mbrs) (count @matching-polys) ;; 3. Evaluate a block like this to save the mbrs to kml and open in google earth. ;; Google Earth will open when you evaluate it. (as long as you've installed it) ;; You can give different tests unique names. Otherwise it will overwrite the file. (kml/display-shapes @matching-mbrs "start_circ_pos_50.kml") (kml/display-shapes @matching-polys "start_circ_pos_50_poly.kml") ;; visualize the kml representation (do (spit "granule_kml.kml" (:out (clojure.java.shell/sh "curl" "--silent" "http://localhost:3003/granules.kml"))) (clojure.java.shell/sh "open" "granule_kml.kml")))
12271
(ns cmr.system-int-test.search.granule-orbit-search-test "Tests for spatial search with orbital back tracking." (:require [clojure.string :as s] [clojure.test :refer :all] [cmr.common.util :as u] [cmr.spatial.codec :as codec] [cmr.spatial.derived :as derived] [cmr.spatial.kml :as kml] [cmr.spatial.line-string :as l] [cmr.spatial.mbr :as m] [cmr.spatial.point :as point] [cmr.spatial.polygon :as poly] [cmr.spatial.ring-relations :as rr] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.core :as d] [cmr.system-int-test.data2.granule :as dg] [cmr.system-int-test.search.granule-spatial-search-test :as st] [cmr.system-int-test.utils.dev-system-util :as dev-sys-util] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search] [cmr.umm.umm-spatial :as umm-s])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"})) (defn- make-gran ([coll ur asc-crossing start-lat start-dir end-lat end-dir] (make-gran coll ur asc-crossing start-lat start-dir end-lat end-dir {})) ([coll ur asc-crossing start-lat start-dir end-lat end-dir other-attribs] (let [orbit (dg/orbit asc-crossing start-lat start-dir end-lat end-dir)] (d/ingest "PROV1" (dg/granule coll (merge {:granule-ur ur :spatial-coverage (apply dg/spatial orbit nil)} other-attribs)))))) (deftest orbit-bug-CMR-4722 (let [coll (d/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-collection.xml" {:provider-id "PROV1" :concept-type :collection :native-id "OMSO2-collection" :format-key :dif<KEY>}) granule (d/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-granule.xml" {:provider-id "PROV1" :concept-type :granule :concept-id "C4-PROV1" :native-id "OMSO2-granule" :format-key :echo<KEY>})] (index/wait-until-indexed) (testing "Orbit search crossing the equator for OMSO2 granules." (u/are3 [items wnes] (let [found (search/find-refs :granule {:bounding-box (codec/url-encode (apply m/mbr wnes)) :provider "PROV1" :page-size 50}) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Rectangle that should find the granule" [granule] [150 70 170 60] "Rectangle not crossing the equator that should not find the granule" [] [-128.32 53.602 -46.758 1.241] "CMR-4722: Search crossing the equator should not erroneously find the granule" [] [-128.32 53.602 -46.758 -1.241])))) (deftest orbit-bug-CMR-5007 (let [coll (d/ingest-concept-with-metadata-file "CMR-5007/dif10_Collection_C1239966837-GES_DISC.xml" {:provider-id "PROV1" :concept-type :collection :native-id "GES_DISC-collection" :format-key :dif10}) granule (d/ingest-concept-with-metadata-file "CMR-5007/echo10_Granlue_G1278223734-GES_DISC.xml" {:provider-id "PROV1" :concept-type :granule :concept-id "C4-PROV1" :native-id "GES_DISC-granule" :format-key :echo10})] (index/wait-until-indexed) (testing "Polygon search for granules near poles." (u/are3 [items coords params] (let [found (search/find-refs :granule (merge {:polygon (apply st/search-poly coords) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "CMR-5007: Search north pole with altitude > 86.52 won't throw 500 error." [granule] [-30,87 90,87 150,87 -150,87 -90,87 -30,87] nil "CMR-5007: Search south pole with altitude < -86.52 won't throw 500 error." [granule] [-30,-87 -90,-87 -150,-87 150,-87 90,-87 -30,-87] nil)) (testing "line searches" (u/are3 [items coords params] (let [found (search/find-refs :granule {:line (codec/url-encode (l/ords->line-string :geodetic coords)) :provider "PROV1" :page-size 50}) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Line search with altitude < -86.52 won't throw 500 error." [granule] [-180,-86.6,0,0] nil "Line search with altitude > 86.52 won't throw 500 error." [granule] [0,0 180, 86.6] nil)))) ;; This tests searching for bounding boxes or polygons that cross the start circular ;; latitude of the collection with fractional orbit granules. This was added to test ;; the fix for this issue as described in CMR-1168 and uses the collection/granules from ;; that issue. (deftest fractional-orbit-non-zero-start-clat (let [orbit-parameters {:swath-width 2 :period 96.7 :inclination-angle 94.0 :number-of-orbits 0.25 :start-circular-latitude 50.0} coll1 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit orbit-parameters})})) g1 (make-gran coll1 "gran1" 70.80471 50.0 :asc 50.0 :desc) g2 (make-gran coll1 "gran2" 70.80471 50.0 :desc -50.0 :desc) g3 (make-gran coll1 "gran3" 70.80471 -50.0 :desc -50.0 :asc) g4 (make-gran coll1 "gran4" 70.80471 -50.0 :asc 50 :asc)] (index/wait-until-indexed) (testing "Bounding box" (u/are2 [items wnes params] (let [found (search/find-refs :granule (merge {:bounding-box (codec/url-encode (apply m/mbr wnes)) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Rectangle crossing the start circular latitude of the collection" [g1] [54.844 52.133 97.734 25.165] nil "Rectangle crossing the start circular latitdue of the colletion on the other side of the earth" [g1 g2] [-125.156 52.133 -82.266 25.165] nil "Rectangle crossing the start circular latitude * -1" [g3 g4] [54.844 -25.165 97.734 -52.133] nil "Rectangle touching the north pole" [g1] [-90 90 90 85] nil "Rectangle touching the south pole" [g3] [0 -85 180 -90] nil "Rectangle crossing the antimeridian and the collection start circular latitude" [g1 g2] [125.156 52.133 -82.266 25.165] nil "The whole earth" [g1 g2 g3 g4] [-180 90 180 -90] nil)) (testing "Polygon" (u/are2 [items coords params] (let [found (search/find-refs :granule (merge {:polygon (apply st/search-poly coords) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Rectangle crossing the start circular latitude of the collection" [g1] [54.844,25.165 97.734,25.165 97.734,52.133 54.844,52.133 54.844,25.165] nil "Rectangle crossing the start circular latitdue of the colletion on the other side of the earth" [g1 g2] [-125.156,52.133 -125.156,25.165 -82.266,25.165 -82.266,52.133 -125.156,52.133] nil "Rectangle crossing the start circular latitude * -1" [g3 g4] [97.734,-52.133 97.734,-25.165 54.844,-25.165 54.844,-52.133 97.734,-52.133] nil "Triangle touching the north pole" [g1] [0,90 -45,85 45,85 0,90] nil "Pentagon touching the south pole" [g3 g4] [97.734,-52.133 97.734,-25.165 54.844,-25.165 54.844,-52.133 97.734,-90 97.734,-52.133] nil "Rectangle crossing the antimeridian and the collection start circular latitude" [g1 g2] [125.156,52.133 125.156,25.165 -82.266,25.165 -82.266,52.133 125.156,52.133] nil "Pentagon over the north pole" [g1] [0,80 72,80 144,80 -144,80 -72,80 0,80] nil "Pentagon over the south pole" [g3] [0,-80 -72,-80 -144,-80 144,-80 72,-80 0,-80] nil)))) (deftest orbit-search (let [;; orbit parameters op1 {:swath-width 1450 :period 98.88 :inclination-angle 98.15 :number-of-orbits 0.5 :start-circular-latitude -90} op2 {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude -50} ;; orbit parameters with missing value to test defaulting to 0 op3-bad {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude nil} coll1 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op1})})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params2" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op2})})) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params3" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op3-bad})})) g1 (make-gran coll1 "gran1" -158.1 81.8 :desc -81.8 :desc) g2 (make-gran coll1 "gran2" 177.16 -81.8 :asc 81.8 :asc) g3 (make-gran coll1 "gran3" 127.73 81.8 :desc -81.8 :desc) g4 (make-gran coll1 "gran4" 103 -81.8 :asc 81.8 :asc) g5 (make-gran coll2 "gran5" 79.88192 50 :asc 50 :desc) g6 (make-gran coll2 "gran6" 55.67938 -50 :asc 50 :asc) g7 (make-gran coll2 "gran7" 31.48193 50 :desc -50 :desc) g8 (make-gran coll2 "gran8" 7.28116 -50 :asc 50 :asc) g9 (make-gran coll3 "gran9" 127.73 81.8 :desc -81.8 :desc)] (index/wait-until-indexed) (testing "bounding rectangle searches" (u/are2 [items wnes params] (let [found (search/find-refs :granule (merge {:bounding-box (codec/url-encode (apply m/mbr wnes)) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Orbits crossing a rectangle over the equator and anti-meridian" [g2 g7] [145 45 -145 -45] nil "Orbits crossing a rectangle over the equator and meridian" [g1 g3 g8] [-45 45 45 -45] nil "Orbits crossing a rectangle in the western hemisphere near the north pole" [g5] [-90 89 -45 85] nil "Orbits crossing a rectangle in the southern hemisphere crossing the anti-meridian" [g2 g3 g4 g7] [145 -45 -145 -85] nil "Specifying parent collection" [g2] [145 45 -145 -45] {:concept-id (:concept-id coll1)})) (testing "point searches" (are [items lon_lat params] (let [found (search/find-refs :granule {:point (codec/url-encode (apply point/point lon_lat)) :provider "PROV1" :page-size 50}) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) [g3] [-45,45] nil [g1] [0,-20] nil [g2] [-180,0] nil)) (testing "line searches" (are [items coords params] (let [found (search/find-refs :granule {:line (codec/url-encode (l/ords->line-string :geodetic coords)) :provider "PROV1" :page-size 50}) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) ;; Line crossing prime meridian and equator [g1 g8] [-45,-45 45,45] nil)) ;; Line crossing the antimeridian - This case gets different results from catalog-rest ;; (returns g2 & g7) and will fail if uncommented. Need to determine if it ;; is supposed to return both granules or not. ; [g2] [179,-45 -170, 30] nil (testing "polygon searches" (u/are2 [items coords params] (let [found (search/find-refs :granule (merge {:polygon (apply st/search-poly coords) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Triangle crossing prime meridian" [g1 g8] [-45,-45 45,-45 45,0, -45,-45] nil "Pentagon over the north pole" [g1 g2 g3 g4 g5 g9] [0,80 72,80 144,80 -144,80 -72,80 0,80] nil "Concave polygon crossing antimeridian and equator" [g2 g4 g7 g9] [170,-70 -170,-80 -175,20 -179,-10 175,25 170,-70] nil)))) (deftest multi-orbit-search (let [;; orbit parameters op1 {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 14 :start-circular-latitude 50} op2 {:swath-width 400 :period 98.88 :inclination-angle 98.3 :number-of-orbits 1 :start-circular-latitude 0} coll1 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op1})})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params2" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op2})})) g1 (make-gran coll1 "gran1" 104.0852 50 :asc 50 :asc) g2 (make-gran coll2 "gran2" 31.946 70.113955 :asc -71.344289 :desc)] (index/wait-until-indexed) (testing "bounding rectangle searches" (u/are2 [items wnes params] (let [found (search/find-refs :granule (merge {:bounding-box (codec/url-encode (apply m/mbr wnes)) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Search large box that finds the granule" [g1] [-134.648 69.163 76.84 65.742] {:concept-id (:concept-id coll1)} "Search near equator that doesn't intersect granule" [] [0 1 1 0] {:concept-id (:concept-id coll1)} "Search near equator that intersects granule" [g1] [1 11 15 1] {:concept-id (:concept-id coll1)} "Search near north pole - FIXME" [] [1 89.5 1.5 89] {:concept-id (:concept-id coll1)} "Search for granules with exactly one orbit does not match areas seen on the second pass" [] [175.55 38.273 -164.883 17.912] {:concept-id (:concept-id coll2)})))) ;; The following test is deliberately commented out because it is marked as @broken ;; in ECHO. It is included here for completeness. ;; ;; The following comment is repeated verbatim from the ECHO cucumber test: ;; ;; Orbit searching is known to have some issues. The following query successfully finds a granule ;; when it appears from the drawing of the granule in Reverb that it shouldn't. I manually verified that ;; the query does match the query output in echo-catalog when searching the legacy provider schemas. ;; At some point it would be a good idea for someone in the ECHO organization to have a better understanding ;; of the backtrack algorithm and be able to definitively state when an orbit granule doesn intersect a ;; particular bounding box. ;; ; "Broken test" ; [] [0 1 6 0] nil (deftest ascending-crossing-precision-test (let [coll (d/ingest-concept-with-metadata-file "iso-samples/CMR-5269-IsoMendsCollection.xml" {:provider-id "PROV1" :concept-type :collection :format-key :iso19115}) gran (d/ingest-concept-with-metadata-file "iso-samples/CMR-5269-IsoSmapGranule.xml" {:provider-id "PROV1" :concept-type :granule :format-key :iso-smap}) _ (index/wait-until-indexed) json-response (search/find-concepts-json :granule {:concept-id (:concept-id gran)}) granule-json (-> json-response :results :entries first) expected-points-in-polygons [(point/point 25.235719457640535 -21.19078458692315) (point/point 23.13297924763377 -39.771484792279814) (point/point 22.646805419273353 -43.610681332179986) (point/point 22.199982651743795 -43.5950693405511) (point/point 22.711995770988835 -39.7567775481513) (point/point 24.8885475222218 -21.178659983890096) (point/point 25.235719457640535 -21.19078458692315)] expected-ascending-crossing -140.637396 expected-equator-crossings [-140.637396] actual-ascending-crossing (-> granule-json :orbit :ascending-crossing) actual-equator-crossings (->> granule-json :orbit-calculated-spatial-domains (keep :equator-crossing-longitude)) actual-points-in-polygons (->> granule-json :shapes (mapcat :rings) (mapcat :points))] (is (= expected-points-in-polygons actual-points-in-polygons)) (is (= expected-ascending-crossing actual-ascending-crossing)) (is (= expected-equator-crossings actual-equator-crossings)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Visualizations ;; ;; Ingests for visualizations (defn- ingest-orbit-coll-and-granule-swath [] (let [coll (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit {:inclination-angle 98.2 :period 100.0 :swath-width 2 :start-circular-latitude 0 :number-of-orbits 0.25}})}))] [coll (make-gran coll "gran1" 88.0 0 :asc 88 :asc)])) (defn- ingest-orbit-coll-and-granule [] (let [coll (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude 50}})}))] ; -50 ; 0 [coll (make-gran coll "gran1" 70.80471 ; ascending crossing -50 :asc ; start lat, start dir 50 :asc ; end lat end dir {:beginning-date-time "2003-09-27T17:03:27.000000Z" :ending-date-time "2003-09-27T17:30:23.000000Z" :orbit-calculated-spatial-domains [{:orbit-number 3838 :equator-crossing-longitude 70.80471 :equator-crossing-date-time "2003-09-27T15:40:15Z"} {:orbit-number 3839 :equator-crossing-longitude 46.602737 :equator-crossing-date-time "2003-09-27T17:16:56Z"}]})])) (defn- ingest-orbit-coll-and-granules-north-pole [] (let [coll (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude ;50 -50}})}))] ; 0 [coll (make-gran coll "gran1" 31.48193 50 :desc -50 :desc)])) (defn- ingest-orbit-coll-and-granules-prime-meridian [] (let [coll (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude -50}})}))] [coll (make-gran coll "gran1" 7.28116 -50 :asc 50 :asc)])) (defn- ingest-CMR-4722-data [] (let [coll1 (d/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-collection.xml" {:provider-id "PROV1" :concept-type :collection :native-id "orbit3" :format-key :dif<KEY>}) g1 (d/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-granule.xml" {:provider-id "PROV1" :concept-type :granule :concept-id "C1-PROV1" :native-id "granule1" :format-key :<KEY>})] [coll1 g1])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Visualization code (defn- mbr-finds-granule? [mbr] (let [resp (search/find-refs :granule {:bounding-box (codec/url-encode mbr) :page-size 0 :provider "PROV1"})] (> (:hits resp) 0))) (defn- polygon-finds-granule? [coords] (let [resp (search/find-refs :granule {:provider "PROV1" :polygon (apply st/search-poly coords) :page-size 0})] (> (:hits resp) 0))) (defn- create-mbrs "Split an area on the earth into a bunch of bounding rectangles and return them as a list" ([] (create-mbrs -180.0 180.0 -90.0 90.0 3.0)) ([min-lon max-lon min-lat max-lat step] (for [[west east] (partition 2 1 (range min-lon (inc max-lon) step)) [south north] (partition 2 1 (range min-lat (inc max-lat) step))] (m/mbr west north east south)))) (defn- mbr->polygon-coords "Get the coordinates from the corners of an mbr" [mbr] (let [corners (-> (m/corner-points mbr) distinct reverse) points (conj (vec corners) (first corners))] (point/points->ords points))) (defn- create-polygons "Split an area on the earth into a bunch of box shaped polygons and return them as a list" ([] (create-polygons -180.0 180.0 -90.0 90.0 30.0)) ([min-lon max-lon min-lat max-lat step] (let [mbrs (create-mbrs min-lon max-lon min-lat max-lat step)] (map mbr->polygon-coords mbrs)))) (comment ;; 1. Perform setup ;; evaluate this block ;; First modify the metadata in ingest-orbit-coll-and-granule if you want. (do (dev-sys-util/reset) (taoensso.timbre/set-level! :warn) ; turn down log level (ingest/create-provider {:provider-guid "provguid1" :provider-id "PROV1"}) ; (ingest-orbit-coll-and-granules-north-pole) ; (ingest-orbit-coll-and-granules-prime-meridian) ; (ingest-orbit-coll-and-granule) ; (ingest-orbit-coll-and-granule-swath) (ingest-CMR-4722-data)) ;; Figure out how many mbrs we're going to search with to get an idea of how long things will take (count (create-mbrs 45.0 90.0 -55.0 55.0 3)) (count (create-mbrs)) ;; 2. Evaluate this block to find all the mbrs. ;; It will print out "Elapsed time: XXXX msecs" when it's done (def matching-mbrs "Creates mbrs all over the globe as search areas. Returns any mbrs which find granules in the local system. Takes awhile to run, so performed as a future." (future (time (doall (filter mbr-finds-granule? (create-mbrs -180.0 180.0 -90.0 90.0 3)))))) ;; Or evaluate this block to use polygons instead of mbrs (def matching-polys (future (time (doall (keep (fn [coords] (when (polygon-finds-granule? coords) (umm-s/set-coordinate-system :geodetic (apply st/polygon coords)))) (create-polygons -46.0 46.0 -89.0 89.0 3)))))) (mbr-finds-granule? (m/mbr 40 30 45 24)) ;; How many were found? This will block on the future (count @matching-mbrs) (count @matching-polys) ;; 3. Evaluate a block like this to save the mbrs to kml and open in google earth. ;; Google Earth will open when you evaluate it. (as long as you've installed it) ;; You can give different tests unique names. Otherwise it will overwrite the file. (kml/display-shapes @matching-mbrs "start_circ_pos_50.kml") (kml/display-shapes @matching-polys "start_circ_pos_50_poly.kml") ;; visualize the kml representation (do (spit "granule_kml.kml" (:out (clojure.java.shell/sh "curl" "--silent" "http://localhost:3003/granules.kml"))) (clojure.java.shell/sh "open" "granule_kml.kml")))
true
(ns cmr.system-int-test.search.granule-orbit-search-test "Tests for spatial search with orbital back tracking." (:require [clojure.string :as s] [clojure.test :refer :all] [cmr.common.util :as u] [cmr.spatial.codec :as codec] [cmr.spatial.derived :as derived] [cmr.spatial.kml :as kml] [cmr.spatial.line-string :as l] [cmr.spatial.mbr :as m] [cmr.spatial.point :as point] [cmr.spatial.polygon :as poly] [cmr.spatial.ring-relations :as rr] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.core :as d] [cmr.system-int-test.data2.granule :as dg] [cmr.system-int-test.search.granule-spatial-search-test :as st] [cmr.system-int-test.utils.dev-system-util :as dev-sys-util] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search] [cmr.umm.umm-spatial :as umm-s])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"})) (defn- make-gran ([coll ur asc-crossing start-lat start-dir end-lat end-dir] (make-gran coll ur asc-crossing start-lat start-dir end-lat end-dir {})) ([coll ur asc-crossing start-lat start-dir end-lat end-dir other-attribs] (let [orbit (dg/orbit asc-crossing start-lat start-dir end-lat end-dir)] (d/ingest "PROV1" (dg/granule coll (merge {:granule-ur ur :spatial-coverage (apply dg/spatial orbit nil)} other-attribs)))))) (deftest orbit-bug-CMR-4722 (let [coll (d/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-collection.xml" {:provider-id "PROV1" :concept-type :collection :native-id "OMSO2-collection" :format-key :difPI:KEY:<KEY>END_PI}) granule (d/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-granule.xml" {:provider-id "PROV1" :concept-type :granule :concept-id "C4-PROV1" :native-id "OMSO2-granule" :format-key :echoPI:KEY:<KEY>END_PI})] (index/wait-until-indexed) (testing "Orbit search crossing the equator for OMSO2 granules." (u/are3 [items wnes] (let [found (search/find-refs :granule {:bounding-box (codec/url-encode (apply m/mbr wnes)) :provider "PROV1" :page-size 50}) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Rectangle that should find the granule" [granule] [150 70 170 60] "Rectangle not crossing the equator that should not find the granule" [] [-128.32 53.602 -46.758 1.241] "CMR-4722: Search crossing the equator should not erroneously find the granule" [] [-128.32 53.602 -46.758 -1.241])))) (deftest orbit-bug-CMR-5007 (let [coll (d/ingest-concept-with-metadata-file "CMR-5007/dif10_Collection_C1239966837-GES_DISC.xml" {:provider-id "PROV1" :concept-type :collection :native-id "GES_DISC-collection" :format-key :dif10}) granule (d/ingest-concept-with-metadata-file "CMR-5007/echo10_Granlue_G1278223734-GES_DISC.xml" {:provider-id "PROV1" :concept-type :granule :concept-id "C4-PROV1" :native-id "GES_DISC-granule" :format-key :echo10})] (index/wait-until-indexed) (testing "Polygon search for granules near poles." (u/are3 [items coords params] (let [found (search/find-refs :granule (merge {:polygon (apply st/search-poly coords) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "CMR-5007: Search north pole with altitude > 86.52 won't throw 500 error." [granule] [-30,87 90,87 150,87 -150,87 -90,87 -30,87] nil "CMR-5007: Search south pole with altitude < -86.52 won't throw 500 error." [granule] [-30,-87 -90,-87 -150,-87 150,-87 90,-87 -30,-87] nil)) (testing "line searches" (u/are3 [items coords params] (let [found (search/find-refs :granule {:line (codec/url-encode (l/ords->line-string :geodetic coords)) :provider "PROV1" :page-size 50}) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Line search with altitude < -86.52 won't throw 500 error." [granule] [-180,-86.6,0,0] nil "Line search with altitude > 86.52 won't throw 500 error." [granule] [0,0 180, 86.6] nil)))) ;; This tests searching for bounding boxes or polygons that cross the start circular ;; latitude of the collection with fractional orbit granules. This was added to test ;; the fix for this issue as described in CMR-1168 and uses the collection/granules from ;; that issue. (deftest fractional-orbit-non-zero-start-clat (let [orbit-parameters {:swath-width 2 :period 96.7 :inclination-angle 94.0 :number-of-orbits 0.25 :start-circular-latitude 50.0} coll1 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit orbit-parameters})})) g1 (make-gran coll1 "gran1" 70.80471 50.0 :asc 50.0 :desc) g2 (make-gran coll1 "gran2" 70.80471 50.0 :desc -50.0 :desc) g3 (make-gran coll1 "gran3" 70.80471 -50.0 :desc -50.0 :asc) g4 (make-gran coll1 "gran4" 70.80471 -50.0 :asc 50 :asc)] (index/wait-until-indexed) (testing "Bounding box" (u/are2 [items wnes params] (let [found (search/find-refs :granule (merge {:bounding-box (codec/url-encode (apply m/mbr wnes)) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Rectangle crossing the start circular latitude of the collection" [g1] [54.844 52.133 97.734 25.165] nil "Rectangle crossing the start circular latitdue of the colletion on the other side of the earth" [g1 g2] [-125.156 52.133 -82.266 25.165] nil "Rectangle crossing the start circular latitude * -1" [g3 g4] [54.844 -25.165 97.734 -52.133] nil "Rectangle touching the north pole" [g1] [-90 90 90 85] nil "Rectangle touching the south pole" [g3] [0 -85 180 -90] nil "Rectangle crossing the antimeridian and the collection start circular latitude" [g1 g2] [125.156 52.133 -82.266 25.165] nil "The whole earth" [g1 g2 g3 g4] [-180 90 180 -90] nil)) (testing "Polygon" (u/are2 [items coords params] (let [found (search/find-refs :granule (merge {:polygon (apply st/search-poly coords) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Rectangle crossing the start circular latitude of the collection" [g1] [54.844,25.165 97.734,25.165 97.734,52.133 54.844,52.133 54.844,25.165] nil "Rectangle crossing the start circular latitdue of the colletion on the other side of the earth" [g1 g2] [-125.156,52.133 -125.156,25.165 -82.266,25.165 -82.266,52.133 -125.156,52.133] nil "Rectangle crossing the start circular latitude * -1" [g3 g4] [97.734,-52.133 97.734,-25.165 54.844,-25.165 54.844,-52.133 97.734,-52.133] nil "Triangle touching the north pole" [g1] [0,90 -45,85 45,85 0,90] nil "Pentagon touching the south pole" [g3 g4] [97.734,-52.133 97.734,-25.165 54.844,-25.165 54.844,-52.133 97.734,-90 97.734,-52.133] nil "Rectangle crossing the antimeridian and the collection start circular latitude" [g1 g2] [125.156,52.133 125.156,25.165 -82.266,25.165 -82.266,52.133 125.156,52.133] nil "Pentagon over the north pole" [g1] [0,80 72,80 144,80 -144,80 -72,80 0,80] nil "Pentagon over the south pole" [g3] [0,-80 -72,-80 -144,-80 144,-80 72,-80 0,-80] nil)))) (deftest orbit-search (let [;; orbit parameters op1 {:swath-width 1450 :period 98.88 :inclination-angle 98.15 :number-of-orbits 0.5 :start-circular-latitude -90} op2 {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude -50} ;; orbit parameters with missing value to test defaulting to 0 op3-bad {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude nil} coll1 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op1})})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params2" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op2})})) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params3" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op3-bad})})) g1 (make-gran coll1 "gran1" -158.1 81.8 :desc -81.8 :desc) g2 (make-gran coll1 "gran2" 177.16 -81.8 :asc 81.8 :asc) g3 (make-gran coll1 "gran3" 127.73 81.8 :desc -81.8 :desc) g4 (make-gran coll1 "gran4" 103 -81.8 :asc 81.8 :asc) g5 (make-gran coll2 "gran5" 79.88192 50 :asc 50 :desc) g6 (make-gran coll2 "gran6" 55.67938 -50 :asc 50 :asc) g7 (make-gran coll2 "gran7" 31.48193 50 :desc -50 :desc) g8 (make-gran coll2 "gran8" 7.28116 -50 :asc 50 :asc) g9 (make-gran coll3 "gran9" 127.73 81.8 :desc -81.8 :desc)] (index/wait-until-indexed) (testing "bounding rectangle searches" (u/are2 [items wnes params] (let [found (search/find-refs :granule (merge {:bounding-box (codec/url-encode (apply m/mbr wnes)) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Orbits crossing a rectangle over the equator and anti-meridian" [g2 g7] [145 45 -145 -45] nil "Orbits crossing a rectangle over the equator and meridian" [g1 g3 g8] [-45 45 45 -45] nil "Orbits crossing a rectangle in the western hemisphere near the north pole" [g5] [-90 89 -45 85] nil "Orbits crossing a rectangle in the southern hemisphere crossing the anti-meridian" [g2 g3 g4 g7] [145 -45 -145 -85] nil "Specifying parent collection" [g2] [145 45 -145 -45] {:concept-id (:concept-id coll1)})) (testing "point searches" (are [items lon_lat params] (let [found (search/find-refs :granule {:point (codec/url-encode (apply point/point lon_lat)) :provider "PROV1" :page-size 50}) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) [g3] [-45,45] nil [g1] [0,-20] nil [g2] [-180,0] nil)) (testing "line searches" (are [items coords params] (let [found (search/find-refs :granule {:line (codec/url-encode (l/ords->line-string :geodetic coords)) :provider "PROV1" :page-size 50}) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) ;; Line crossing prime meridian and equator [g1 g8] [-45,-45 45,45] nil)) ;; Line crossing the antimeridian - This case gets different results from catalog-rest ;; (returns g2 & g7) and will fail if uncommented. Need to determine if it ;; is supposed to return both granules or not. ; [g2] [179,-45 -170, 30] nil (testing "polygon searches" (u/are2 [items coords params] (let [found (search/find-refs :granule (merge {:polygon (apply st/search-poly coords) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Triangle crossing prime meridian" [g1 g8] [-45,-45 45,-45 45,0, -45,-45] nil "Pentagon over the north pole" [g1 g2 g3 g4 g5 g9] [0,80 72,80 144,80 -144,80 -72,80 0,80] nil "Concave polygon crossing antimeridian and equator" [g2 g4 g7 g9] [170,-70 -170,-80 -175,20 -179,-10 175,25 170,-70] nil)))) (deftest multi-orbit-search (let [;; orbit parameters op1 {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 14 :start-circular-latitude 50} op2 {:swath-width 400 :period 98.88 :inclination-angle 98.3 :number-of-orbits 1 :start-circular-latitude 0} coll1 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op1})})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params2" :spatial-coverage (dc/spatial {:gsr :orbit :orbit op2})})) g1 (make-gran coll1 "gran1" 104.0852 50 :asc 50 :asc) g2 (make-gran coll2 "gran2" 31.946 70.113955 :asc -71.344289 :desc)] (index/wait-until-indexed) (testing "bounding rectangle searches" (u/are2 [items wnes params] (let [found (search/find-refs :granule (merge {:bounding-box (codec/url-encode (apply m/mbr wnes)) :provider "PROV1" :page-size 50} params)) matches? (d/refs-match? items found)] (when-not matches? (println "Expected:" (->> items (map :granule-ur) sort pr-str)) (println "Actual:" (->> found :refs (map :name) sort pr-str))) matches?) "Search large box that finds the granule" [g1] [-134.648 69.163 76.84 65.742] {:concept-id (:concept-id coll1)} "Search near equator that doesn't intersect granule" [] [0 1 1 0] {:concept-id (:concept-id coll1)} "Search near equator that intersects granule" [g1] [1 11 15 1] {:concept-id (:concept-id coll1)} "Search near north pole - FIXME" [] [1 89.5 1.5 89] {:concept-id (:concept-id coll1)} "Search for granules with exactly one orbit does not match areas seen on the second pass" [] [175.55 38.273 -164.883 17.912] {:concept-id (:concept-id coll2)})))) ;; The following test is deliberately commented out because it is marked as @broken ;; in ECHO. It is included here for completeness. ;; ;; The following comment is repeated verbatim from the ECHO cucumber test: ;; ;; Orbit searching is known to have some issues. The following query successfully finds a granule ;; when it appears from the drawing of the granule in Reverb that it shouldn't. I manually verified that ;; the query does match the query output in echo-catalog when searching the legacy provider schemas. ;; At some point it would be a good idea for someone in the ECHO organization to have a better understanding ;; of the backtrack algorithm and be able to definitively state when an orbit granule doesn intersect a ;; particular bounding box. ;; ; "Broken test" ; [] [0 1 6 0] nil (deftest ascending-crossing-precision-test (let [coll (d/ingest-concept-with-metadata-file "iso-samples/CMR-5269-IsoMendsCollection.xml" {:provider-id "PROV1" :concept-type :collection :format-key :iso19115}) gran (d/ingest-concept-with-metadata-file "iso-samples/CMR-5269-IsoSmapGranule.xml" {:provider-id "PROV1" :concept-type :granule :format-key :iso-smap}) _ (index/wait-until-indexed) json-response (search/find-concepts-json :granule {:concept-id (:concept-id gran)}) granule-json (-> json-response :results :entries first) expected-points-in-polygons [(point/point 25.235719457640535 -21.19078458692315) (point/point 23.13297924763377 -39.771484792279814) (point/point 22.646805419273353 -43.610681332179986) (point/point 22.199982651743795 -43.5950693405511) (point/point 22.711995770988835 -39.7567775481513) (point/point 24.8885475222218 -21.178659983890096) (point/point 25.235719457640535 -21.19078458692315)] expected-ascending-crossing -140.637396 expected-equator-crossings [-140.637396] actual-ascending-crossing (-> granule-json :orbit :ascending-crossing) actual-equator-crossings (->> granule-json :orbit-calculated-spatial-domains (keep :equator-crossing-longitude)) actual-points-in-polygons (->> granule-json :shapes (mapcat :rings) (mapcat :points))] (is (= expected-points-in-polygons actual-points-in-polygons)) (is (= expected-ascending-crossing actual-ascending-crossing)) (is (= expected-equator-crossings actual-equator-crossings)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Visualizations ;; ;; Ingests for visualizations (defn- ingest-orbit-coll-and-granule-swath [] (let [coll (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit {:inclination-angle 98.2 :period 100.0 :swath-width 2 :start-circular-latitude 0 :number-of-orbits 0.25}})}))] [coll (make-gran coll "gran1" 88.0 0 :asc 88 :asc)])) (defn- ingest-orbit-coll-and-granule [] (let [coll (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude 50}})}))] ; -50 ; 0 [coll (make-gran coll "gran1" 70.80471 ; ascending crossing -50 :asc ; start lat, start dir 50 :asc ; end lat end dir {:beginning-date-time "2003-09-27T17:03:27.000000Z" :ending-date-time "2003-09-27T17:30:23.000000Z" :orbit-calculated-spatial-domains [{:orbit-number 3838 :equator-crossing-longitude 70.80471 :equator-crossing-date-time "2003-09-27T15:40:15Z"} {:orbit-number 3839 :equator-crossing-longitude 46.602737 :equator-crossing-date-time "2003-09-27T17:16:56Z"}]})])) (defn- ingest-orbit-coll-and-granules-north-pole [] (let [coll (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude ;50 -50}})}))] ; 0 [coll (make-gran coll "gran1" 31.48193 50 :desc -50 :desc)])) (defn- ingest-orbit-coll-and-granules-prime-meridian [] (let [coll (d/ingest "PROV1" (dc/collection {:entry-title "orbit-params1" :spatial-coverage (dc/spatial {:gsr :orbit :orbit {:swath-width 2 :period 96.7 :inclination-angle 94 :number-of-orbits 0.25 :start-circular-latitude -50}})}))] [coll (make-gran coll "gran1" 7.28116 -50 :asc 50 :asc)])) (defn- ingest-CMR-4722-data [] (let [coll1 (d/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-collection.xml" {:provider-id "PROV1" :concept-type :collection :native-id "orbit3" :format-key :difPI:KEY:<KEY>END_PI}) g1 (d/ingest-concept-with-metadata-file "CMR-4722/OMSO2.003-granule.xml" {:provider-id "PROV1" :concept-type :granule :concept-id "C1-PROV1" :native-id "granule1" :format-key :PI:KEY:<KEY>END_PI})] [coll1 g1])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Visualization code (defn- mbr-finds-granule? [mbr] (let [resp (search/find-refs :granule {:bounding-box (codec/url-encode mbr) :page-size 0 :provider "PROV1"})] (> (:hits resp) 0))) (defn- polygon-finds-granule? [coords] (let [resp (search/find-refs :granule {:provider "PROV1" :polygon (apply st/search-poly coords) :page-size 0})] (> (:hits resp) 0))) (defn- create-mbrs "Split an area on the earth into a bunch of bounding rectangles and return them as a list" ([] (create-mbrs -180.0 180.0 -90.0 90.0 3.0)) ([min-lon max-lon min-lat max-lat step] (for [[west east] (partition 2 1 (range min-lon (inc max-lon) step)) [south north] (partition 2 1 (range min-lat (inc max-lat) step))] (m/mbr west north east south)))) (defn- mbr->polygon-coords "Get the coordinates from the corners of an mbr" [mbr] (let [corners (-> (m/corner-points mbr) distinct reverse) points (conj (vec corners) (first corners))] (point/points->ords points))) (defn- create-polygons "Split an area on the earth into a bunch of box shaped polygons and return them as a list" ([] (create-polygons -180.0 180.0 -90.0 90.0 30.0)) ([min-lon max-lon min-lat max-lat step] (let [mbrs (create-mbrs min-lon max-lon min-lat max-lat step)] (map mbr->polygon-coords mbrs)))) (comment ;; 1. Perform setup ;; evaluate this block ;; First modify the metadata in ingest-orbit-coll-and-granule if you want. (do (dev-sys-util/reset) (taoensso.timbre/set-level! :warn) ; turn down log level (ingest/create-provider {:provider-guid "provguid1" :provider-id "PROV1"}) ; (ingest-orbit-coll-and-granules-north-pole) ; (ingest-orbit-coll-and-granules-prime-meridian) ; (ingest-orbit-coll-and-granule) ; (ingest-orbit-coll-and-granule-swath) (ingest-CMR-4722-data)) ;; Figure out how many mbrs we're going to search with to get an idea of how long things will take (count (create-mbrs 45.0 90.0 -55.0 55.0 3)) (count (create-mbrs)) ;; 2. Evaluate this block to find all the mbrs. ;; It will print out "Elapsed time: XXXX msecs" when it's done (def matching-mbrs "Creates mbrs all over the globe as search areas. Returns any mbrs which find granules in the local system. Takes awhile to run, so performed as a future." (future (time (doall (filter mbr-finds-granule? (create-mbrs -180.0 180.0 -90.0 90.0 3)))))) ;; Or evaluate this block to use polygons instead of mbrs (def matching-polys (future (time (doall (keep (fn [coords] (when (polygon-finds-granule? coords) (umm-s/set-coordinate-system :geodetic (apply st/polygon coords)))) (create-polygons -46.0 46.0 -89.0 89.0 3)))))) (mbr-finds-granule? (m/mbr 40 30 45 24)) ;; How many were found? This will block on the future (count @matching-mbrs) (count @matching-polys) ;; 3. Evaluate a block like this to save the mbrs to kml and open in google earth. ;; Google Earth will open when you evaluate it. (as long as you've installed it) ;; You can give different tests unique names. Otherwise it will overwrite the file. (kml/display-shapes @matching-mbrs "start_circ_pos_50.kml") (kml/display-shapes @matching-polys "start_circ_pos_50_poly.kml") ;; visualize the kml representation (do (spit "granule_kml.kml" (:out (clojure.java.shell/sh "curl" "--silent" "http://localhost:3003/granules.kml"))) (clojure.java.shell/sh "open" "granule_kml.kml")))
[ { "context": "\n :email \"non-interractiva@s3.amazonws.com\"\n :role :", "end": 2772, "score": 0.9999069571495056, "start": 2740, "tag": "EMAIL", "value": "non-interractiva@s3.amazonws.com" } ]
src/lambda/filters.clj
raiffeisenbankinternational/edd-core
4
(ns lambda.filters (:require [lambda.util :as util] [clojure.tools.logging :as log] [clojure.string :as str] [sdk.aws.s3 :as s3] [lambda.jwt :as jwt] [lambda.uuid :as uuid])) (def from-queue {:cond (fn [{:keys [body]}] (if (and (contains? body :Records) (= (:eventSource (first (:Records body))) "aws:sqs")) true false)) :fn (fn [{:keys [body] :as ctx}] (assoc ctx :body (util/to-edn (-> body (:Records) (first) (:body)))))}) (defn parse-key [key] (try (let [parts (str/split key #"/") realm (first parts) parts (rest parts) realm (if (= realm "upload") "prod" realm) parts (if (re-matches #"[\d]{4}-[\d]{2}-[\d]{2}" (first parts)) (rest parts) parts) interaction-id (first parts) parts (rest parts) request-id (-> parts (first) (str/split #"\.") (first))] {:request-id (uuid/parse request-id) :interaction-id (uuid/parse interaction-id) :realm realm}) (catch Exception e (log/error "Unable to parse key. Shouls be in format /{{ realm }}/{{ uuid }}/{{ uuid }}.*") (throw (ex-info "Unable to parse key" {:key key}))))) (def from-bucket {:cond (fn [{:keys [body]}] (if (and (contains? body :Records) (= (:eventSource (first (:Records body))) "aws:s3")) true)) :fn (fn [{:keys [body] :as ctx}] (-> ctx (assoc-in [:user :id] (name (:service-name ctx))) (assoc-in [:user :role] :non-interactive) (assoc :body (let [record (first (:Records body)) key (get-in record [:s3 :object :key]) bucket (get-in record [:s3 :bucket :name])] (if-not (str/ends-with? key "/") (let [{:keys [request-id interaction-id realm]} (parse-key key)] {:request-id request-id :interaction-id interaction-id :user (name (:service-name ctx)) :meta {:realm (keyword realm) :user {:id request-id :email "non-interractiva@s3.amazonws.com" :role :non-interactive}} :commands [{:cmd-id :object-uploaded :id request-id :body (s3/get-object record) :key key}]}) {:skip true})))))}) (defn has-role? [user role] (some #(= role %) (get user :roles []))) (defn get-realm [body {:keys [roles]} role] (let [realm-prefix "realm-" realm (->> roles (map name) (filter #(str/starts-with? % realm-prefix)) (first))] (when-not realm (throw (ex-info (str "Realm: " realm) {:error "Missing realm in request token"}))) (keyword (subs realm (count realm-prefix))))) (defn non-interactive [user] (first (filter #(= % :non-interactive) (:roles user)))) (defn check-user-role [{:keys [body req] :as ctx}] (let [{:keys [user body]} (jwt/parse-token ctx (or (get-in req [:headers :x-authorization]) (get-in req [:headers :X-Authorization]))) role (or (get-in body [:user :selected-role]) (non-interactive user) (first (remove #(or (= % :anonymous) (str/starts-with? (name %) "realm-")) (:roles user))))] (cond (:error body) (assoc ctx :body body) (= role :non-interactive) (assoc ctx :meta (:meta body)) (has-role? user role) (assoc ctx :user {:id (:id user) :email (:email user) :role role :roles (:roles user [])} :meta {:realm (get-realm body user role) :user {:id (:id user) :email (:email user) :role role}}) :else (assoc ctx :user {:id "anonymous" :email "anonymous" :role :anonymous})))) (def from-api {:init jwt/fetch-jwks-keys :cond (fn [{:keys [body]}] (contains? body :path)) :fn (fn [{:keys [req body] :as ctx}] (cond (= (:path req) "/health") (assoc ctx :health-check true) (= (:httpMethod req) "OPTIONS") (assoc ctx :health-check true) :else (-> ctx (assoc :body (util/to-edn (:body body))) (check-user-role))))}) (defn to-api [{:keys [resp] :as ctx}] (log/debug "to-api" resp) (assoc ctx :resp {:statusCode 200 :isBase64Encoded false :headers {"Access-Control-Allow-Headers" "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" "Access-Control-Allow-Methods" "OPTIONS,POST,PUT,GET" "Access-Control-Expose-Headers" "*" "Content-Type" "application/json" "Access-Control-Allow-Origin" "*"} :body (util/to-json resp)}))
50154
(ns lambda.filters (:require [lambda.util :as util] [clojure.tools.logging :as log] [clojure.string :as str] [sdk.aws.s3 :as s3] [lambda.jwt :as jwt] [lambda.uuid :as uuid])) (def from-queue {:cond (fn [{:keys [body]}] (if (and (contains? body :Records) (= (:eventSource (first (:Records body))) "aws:sqs")) true false)) :fn (fn [{:keys [body] :as ctx}] (assoc ctx :body (util/to-edn (-> body (:Records) (first) (:body)))))}) (defn parse-key [key] (try (let [parts (str/split key #"/") realm (first parts) parts (rest parts) realm (if (= realm "upload") "prod" realm) parts (if (re-matches #"[\d]{4}-[\d]{2}-[\d]{2}" (first parts)) (rest parts) parts) interaction-id (first parts) parts (rest parts) request-id (-> parts (first) (str/split #"\.") (first))] {:request-id (uuid/parse request-id) :interaction-id (uuid/parse interaction-id) :realm realm}) (catch Exception e (log/error "Unable to parse key. Shouls be in format /{{ realm }}/{{ uuid }}/{{ uuid }}.*") (throw (ex-info "Unable to parse key" {:key key}))))) (def from-bucket {:cond (fn [{:keys [body]}] (if (and (contains? body :Records) (= (:eventSource (first (:Records body))) "aws:s3")) true)) :fn (fn [{:keys [body] :as ctx}] (-> ctx (assoc-in [:user :id] (name (:service-name ctx))) (assoc-in [:user :role] :non-interactive) (assoc :body (let [record (first (:Records body)) key (get-in record [:s3 :object :key]) bucket (get-in record [:s3 :bucket :name])] (if-not (str/ends-with? key "/") (let [{:keys [request-id interaction-id realm]} (parse-key key)] {:request-id request-id :interaction-id interaction-id :user (name (:service-name ctx)) :meta {:realm (keyword realm) :user {:id request-id :email "<EMAIL>" :role :non-interactive}} :commands [{:cmd-id :object-uploaded :id request-id :body (s3/get-object record) :key key}]}) {:skip true})))))}) (defn has-role? [user role] (some #(= role %) (get user :roles []))) (defn get-realm [body {:keys [roles]} role] (let [realm-prefix "realm-" realm (->> roles (map name) (filter #(str/starts-with? % realm-prefix)) (first))] (when-not realm (throw (ex-info (str "Realm: " realm) {:error "Missing realm in request token"}))) (keyword (subs realm (count realm-prefix))))) (defn non-interactive [user] (first (filter #(= % :non-interactive) (:roles user)))) (defn check-user-role [{:keys [body req] :as ctx}] (let [{:keys [user body]} (jwt/parse-token ctx (or (get-in req [:headers :x-authorization]) (get-in req [:headers :X-Authorization]))) role (or (get-in body [:user :selected-role]) (non-interactive user) (first (remove #(or (= % :anonymous) (str/starts-with? (name %) "realm-")) (:roles user))))] (cond (:error body) (assoc ctx :body body) (= role :non-interactive) (assoc ctx :meta (:meta body)) (has-role? user role) (assoc ctx :user {:id (:id user) :email (:email user) :role role :roles (:roles user [])} :meta {:realm (get-realm body user role) :user {:id (:id user) :email (:email user) :role role}}) :else (assoc ctx :user {:id "anonymous" :email "anonymous" :role :anonymous})))) (def from-api {:init jwt/fetch-jwks-keys :cond (fn [{:keys [body]}] (contains? body :path)) :fn (fn [{:keys [req body] :as ctx}] (cond (= (:path req) "/health") (assoc ctx :health-check true) (= (:httpMethod req) "OPTIONS") (assoc ctx :health-check true) :else (-> ctx (assoc :body (util/to-edn (:body body))) (check-user-role))))}) (defn to-api [{:keys [resp] :as ctx}] (log/debug "to-api" resp) (assoc ctx :resp {:statusCode 200 :isBase64Encoded false :headers {"Access-Control-Allow-Headers" "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" "Access-Control-Allow-Methods" "OPTIONS,POST,PUT,GET" "Access-Control-Expose-Headers" "*" "Content-Type" "application/json" "Access-Control-Allow-Origin" "*"} :body (util/to-json resp)}))
true
(ns lambda.filters (:require [lambda.util :as util] [clojure.tools.logging :as log] [clojure.string :as str] [sdk.aws.s3 :as s3] [lambda.jwt :as jwt] [lambda.uuid :as uuid])) (def from-queue {:cond (fn [{:keys [body]}] (if (and (contains? body :Records) (= (:eventSource (first (:Records body))) "aws:sqs")) true false)) :fn (fn [{:keys [body] :as ctx}] (assoc ctx :body (util/to-edn (-> body (:Records) (first) (:body)))))}) (defn parse-key [key] (try (let [parts (str/split key #"/") realm (first parts) parts (rest parts) realm (if (= realm "upload") "prod" realm) parts (if (re-matches #"[\d]{4}-[\d]{2}-[\d]{2}" (first parts)) (rest parts) parts) interaction-id (first parts) parts (rest parts) request-id (-> parts (first) (str/split #"\.") (first))] {:request-id (uuid/parse request-id) :interaction-id (uuid/parse interaction-id) :realm realm}) (catch Exception e (log/error "Unable to parse key. Shouls be in format /{{ realm }}/{{ uuid }}/{{ uuid }}.*") (throw (ex-info "Unable to parse key" {:key key}))))) (def from-bucket {:cond (fn [{:keys [body]}] (if (and (contains? body :Records) (= (:eventSource (first (:Records body))) "aws:s3")) true)) :fn (fn [{:keys [body] :as ctx}] (-> ctx (assoc-in [:user :id] (name (:service-name ctx))) (assoc-in [:user :role] :non-interactive) (assoc :body (let [record (first (:Records body)) key (get-in record [:s3 :object :key]) bucket (get-in record [:s3 :bucket :name])] (if-not (str/ends-with? key "/") (let [{:keys [request-id interaction-id realm]} (parse-key key)] {:request-id request-id :interaction-id interaction-id :user (name (:service-name ctx)) :meta {:realm (keyword realm) :user {:id request-id :email "PI:EMAIL:<EMAIL>END_PI" :role :non-interactive}} :commands [{:cmd-id :object-uploaded :id request-id :body (s3/get-object record) :key key}]}) {:skip true})))))}) (defn has-role? [user role] (some #(= role %) (get user :roles []))) (defn get-realm [body {:keys [roles]} role] (let [realm-prefix "realm-" realm (->> roles (map name) (filter #(str/starts-with? % realm-prefix)) (first))] (when-not realm (throw (ex-info (str "Realm: " realm) {:error "Missing realm in request token"}))) (keyword (subs realm (count realm-prefix))))) (defn non-interactive [user] (first (filter #(= % :non-interactive) (:roles user)))) (defn check-user-role [{:keys [body req] :as ctx}] (let [{:keys [user body]} (jwt/parse-token ctx (or (get-in req [:headers :x-authorization]) (get-in req [:headers :X-Authorization]))) role (or (get-in body [:user :selected-role]) (non-interactive user) (first (remove #(or (= % :anonymous) (str/starts-with? (name %) "realm-")) (:roles user))))] (cond (:error body) (assoc ctx :body body) (= role :non-interactive) (assoc ctx :meta (:meta body)) (has-role? user role) (assoc ctx :user {:id (:id user) :email (:email user) :role role :roles (:roles user [])} :meta {:realm (get-realm body user role) :user {:id (:id user) :email (:email user) :role role}}) :else (assoc ctx :user {:id "anonymous" :email "anonymous" :role :anonymous})))) (def from-api {:init jwt/fetch-jwks-keys :cond (fn [{:keys [body]}] (contains? body :path)) :fn (fn [{:keys [req body] :as ctx}] (cond (= (:path req) "/health") (assoc ctx :health-check true) (= (:httpMethod req) "OPTIONS") (assoc ctx :health-check true) :else (-> ctx (assoc :body (util/to-edn (:body body))) (check-user-role))))}) (defn to-api [{:keys [resp] :as ctx}] (log/debug "to-api" resp) (assoc ctx :resp {:statusCode 200 :isBase64Encoded false :headers {"Access-Control-Allow-Headers" "Id, VersionId, X-Authorization,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token" "Access-Control-Allow-Methods" "OPTIONS,POST,PUT,GET" "Access-Control-Expose-Headers" "*" "Content-Type" "application/json" "Access-Control-Allow-Origin" "*"} :body (util/to-json resp)}))
[ { "context": "rofile email\"}\n {:send \"link\"\n :email \"zk@welcomecapital.co\"\n :connection \"email\"}))\n\n (gol\n (def a", "end": 6563, "score": 0.9999119639396667, "start": 6543, "tag": "EMAIL", "value": "zk@welcomecapital.co" }, { "context": "rofile email\"}\n {:send \"link\"\n :email \"zk@welcomecapital.co\"\n :connection \"email\"}))\n\n (.passwordlessS", "end": 7815, "score": 0.9999040961265564, "start": 7795, "tag": "EMAIL", "value": "zk@welcomecapital.co" }, { "context": ")\n (clj->js\n {:send \"link\"\n :email \"zk@welcomecapital.co\"\n :connection \"email\"})\n (fn [err res]\n ", "end": 8080, "score": 0.9999086260795593, "start": 8060, "tag": "EMAIL", "value": "zk@welcomecapital.co" } ]
src/cljs-browser/rx/browser/auth0.cljs
zk/rx-lib
0
(ns rx.browser.auth0 (:require [rx.kitchen-sink :as ks] [rx.browser :as browser] [rx.browser.local-storage :as ls] [auth0-spa-js] [auth0] [rx.anom :as anom :refer-macros [gol <? <defn]] [clojure.core.async :as async :refer [go <! put! chan close!]])) (defn <create-client [opts] (ks/<promise (js/createAuth0Client (clj->js opts)))) (defn <login-with-redirect [client opts] (ks/<promise (.loginWithRedirect client (clj->js opts)))) (defn <login-with-popup [client] (ks/<promise (.loginWithPopup client))) (defn webauth [opts] (js/auth0.WebAuth. (clj->js opts))) (defn ensure-webauth-client [opts] (if (map? opts) (webauth opts) opts)) (defn <passwordless-start [opts-or-client opts] (let [ch (chan) client (ensure-webauth-client opts-or-client)] (.passwordlessStart client (clj->js opts) (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) res))) (close! ch))) ch)) (defn <parse-hash [webauth-opts-or-client & [opts]] (let [ch (chan) client (ensure-webauth-client webauth-opts-or-client)] (.parseHash client (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) {:access-token (.-accessToken res) :expires-in (.-expiresIn res) :id-token (.-idToken res)}))) (close! ch))) ch)) (defn <user-info [webauth-opts-or-client access-token] (let [ch (chan) client (ensure-webauth-client webauth-opts-or-client)] (try (.userInfo (.-client client) access-token (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) (js->clj res :keywordize-keys true)))) (close! ch))) (catch js/Error e (put! ch (anom/from-err e)) (close! ch))) ch)) (defn <check-session [webauth-opts-or-client opts] (let [ch (chan)] (.checkSession (ensure-webauth-client webauth-opts-or-client) (clj->js opts) (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) (js->clj res :keywordize-keys true)))) (close! ch))) ch)) (defn <logout [webauth-opts-or-client opts] (let [ch (chan)] (.logout (ensure-webauth-client webauth-opts-or-client) (clj->js opts) (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) (js->clj res :keywordize-keys true)))) (close! ch))) ch)) (defn <logout-and-clear-local [& args] (ls/set-transit "wc-access-token" nil) (ls/set-transit "wc-user-info" nil) (apply <logout args)) ;; CLJS Api (defn get-current-user [] (ls/get-transit "wc-user-info")) (<defn <handle-login-hash [webauth-opts-or-client] (let [client (ensure-webauth-client webauth-opts-or-client) auth (<? (<parse-hash client {})) user-info (<? (<user-info client (:access-token auth)))] (ls/set-transit "wc-access-token" (:access-token auth)) (ls/set-transit "wc-user-info" user-info) user-info)) (<defn <init-auth [webauth-opts-or-client] (try (if-let [access-token (ls/get-transit "wc-access-token")] (let [user-info (<! (<user-info webauth-opts-or-client access-token))] (if (anom/? user-info) (let [user-info (<! (<handle-login-hash webauth-opts-or-client))] (if (anom/? user-info) (do (println "Auth failed, clearing local auth state" (pr-str user-info)) (ls/set-transit "wc-access-token" nil) (ls/set-transit "wc-user-info" nil) nil) (do (println "Auth succeeded via hash info") (ls/set-transit "wc-user-info" user-info) #_(set! js/window.location.hash "") user-info))) (do (println "Auth succeeded via stored token") (ls/set-transit "wc-user-info" user-info) user-info))) (let [user-info (<! (<handle-login-hash webauth-opts-or-client))] (if (anom/? user-info) (do (println "Auth failed, clearing local auth state" (pr-str user-info)) (ls/set-transit "wc-access-token" nil) (ls/set-transit "wc-user-info" nil) nil) (do (println "Auth succeeded via hash info") (ls/set-transit "wc-user-info" user-info) #_(set! js/window.location.hash "") user-info)))) (catch js/Error e (println "Auth failed with exception" e) (ls/set-transit "wc-access-token" nil) (ls/set-transit "wc-user-info" nil) (throw e)))) (comment (<logout-and-clear-local {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI"} {:clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :returnTo "http://localhost:5000"}) (<init-auth {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :scope "openid profile email"}) (ls/set-transit "wc-user-info" nil) (ls/set-transit "wc-access-token" nil) (ls/get-transit "wc-user-info") (ls/get-transit "wc-access-token") (gol (ks/pp (<! (<handle-login-hash {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :scope "openid profile email"})))) (ls/get-transit "wc-access-token") (ks/<pp (<passwordless-start {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :scope "openid profile email"} {:send "link" :email "zk@welcomecapital.co" :connection "email"})) (gol (def auth (ks/spy (<! (<parse-hash {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI"} {}))))) (prn (.-accessToken auth)) (gol (ls/set-transit "wc-user-info" (<! (<user-info {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI"} (ls/get-transit "wc-access-token"))))) (ls/get-transit "wc-user-info") (gol (ks/pp (<! (<check-session {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :redirectUri "http://localhost:5000"} {} (.-accessToken auth))))) (gol (ks/pp (<! (<parse-hash {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI"} {})))) (ks/<pp (<passwordless-start {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :scope "openid profile email"} {:send "link" :email "zk@welcomecapital.co" :connection "email"})) (.passwordlessStart (webauth {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token"}) (clj->js {:send "link" :email "zk@welcomecapital.co" :connection "email"}) (fn [err res] )) (.userInfo (webauth {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token"}) (fn [& a] (prn a))) (gol (let [client (<! (<create-client {:domain "welcap.us.auth0.com" :client_id "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :redirect_uri "http://localhost:5000/auth0-cb"}))] (time (<! (<login-with-redirect client))))) (gol (let [client (<! (<create-client {:domain "welcap.us.auth0.com" :client_id "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :redirect_uri "http://localhost:5000"}))] (time (<! (<login-with-popup client))))) )
56137
(ns rx.browser.auth0 (:require [rx.kitchen-sink :as ks] [rx.browser :as browser] [rx.browser.local-storage :as ls] [auth0-spa-js] [auth0] [rx.anom :as anom :refer-macros [gol <? <defn]] [clojure.core.async :as async :refer [go <! put! chan close!]])) (defn <create-client [opts] (ks/<promise (js/createAuth0Client (clj->js opts)))) (defn <login-with-redirect [client opts] (ks/<promise (.loginWithRedirect client (clj->js opts)))) (defn <login-with-popup [client] (ks/<promise (.loginWithPopup client))) (defn webauth [opts] (js/auth0.WebAuth. (clj->js opts))) (defn ensure-webauth-client [opts] (if (map? opts) (webauth opts) opts)) (defn <passwordless-start [opts-or-client opts] (let [ch (chan) client (ensure-webauth-client opts-or-client)] (.passwordlessStart client (clj->js opts) (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) res))) (close! ch))) ch)) (defn <parse-hash [webauth-opts-or-client & [opts]] (let [ch (chan) client (ensure-webauth-client webauth-opts-or-client)] (.parseHash client (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) {:access-token (.-accessToken res) :expires-in (.-expiresIn res) :id-token (.-idToken res)}))) (close! ch))) ch)) (defn <user-info [webauth-opts-or-client access-token] (let [ch (chan) client (ensure-webauth-client webauth-opts-or-client)] (try (.userInfo (.-client client) access-token (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) (js->clj res :keywordize-keys true)))) (close! ch))) (catch js/Error e (put! ch (anom/from-err e)) (close! ch))) ch)) (defn <check-session [webauth-opts-or-client opts] (let [ch (chan)] (.checkSession (ensure-webauth-client webauth-opts-or-client) (clj->js opts) (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) (js->clj res :keywordize-keys true)))) (close! ch))) ch)) (defn <logout [webauth-opts-or-client opts] (let [ch (chan)] (.logout (ensure-webauth-client webauth-opts-or-client) (clj->js opts) (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) (js->clj res :keywordize-keys true)))) (close! ch))) ch)) (defn <logout-and-clear-local [& args] (ls/set-transit "wc-access-token" nil) (ls/set-transit "wc-user-info" nil) (apply <logout args)) ;; CLJS Api (defn get-current-user [] (ls/get-transit "wc-user-info")) (<defn <handle-login-hash [webauth-opts-or-client] (let [client (ensure-webauth-client webauth-opts-or-client) auth (<? (<parse-hash client {})) user-info (<? (<user-info client (:access-token auth)))] (ls/set-transit "wc-access-token" (:access-token auth)) (ls/set-transit "wc-user-info" user-info) user-info)) (<defn <init-auth [webauth-opts-or-client] (try (if-let [access-token (ls/get-transit "wc-access-token")] (let [user-info (<! (<user-info webauth-opts-or-client access-token))] (if (anom/? user-info) (let [user-info (<! (<handle-login-hash webauth-opts-or-client))] (if (anom/? user-info) (do (println "Auth failed, clearing local auth state" (pr-str user-info)) (ls/set-transit "wc-access-token" nil) (ls/set-transit "wc-user-info" nil) nil) (do (println "Auth succeeded via hash info") (ls/set-transit "wc-user-info" user-info) #_(set! js/window.location.hash "") user-info))) (do (println "Auth succeeded via stored token") (ls/set-transit "wc-user-info" user-info) user-info))) (let [user-info (<! (<handle-login-hash webauth-opts-or-client))] (if (anom/? user-info) (do (println "Auth failed, clearing local auth state" (pr-str user-info)) (ls/set-transit "wc-access-token" nil) (ls/set-transit "wc-user-info" nil) nil) (do (println "Auth succeeded via hash info") (ls/set-transit "wc-user-info" user-info) #_(set! js/window.location.hash "") user-info)))) (catch js/Error e (println "Auth failed with exception" e) (ls/set-transit "wc-access-token" nil) (ls/set-transit "wc-user-info" nil) (throw e)))) (comment (<logout-and-clear-local {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI"} {:clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :returnTo "http://localhost:5000"}) (<init-auth {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :scope "openid profile email"}) (ls/set-transit "wc-user-info" nil) (ls/set-transit "wc-access-token" nil) (ls/get-transit "wc-user-info") (ls/get-transit "wc-access-token") (gol (ks/pp (<! (<handle-login-hash {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :scope "openid profile email"})))) (ls/get-transit "wc-access-token") (ks/<pp (<passwordless-start {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :scope "openid profile email"} {:send "link" :email "<EMAIL>" :connection "email"})) (gol (def auth (ks/spy (<! (<parse-hash {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI"} {}))))) (prn (.-accessToken auth)) (gol (ls/set-transit "wc-user-info" (<! (<user-info {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI"} (ls/get-transit "wc-access-token"))))) (ls/get-transit "wc-user-info") (gol (ks/pp (<! (<check-session {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :redirectUri "http://localhost:5000"} {} (.-accessToken auth))))) (gol (ks/pp (<! (<parse-hash {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI"} {})))) (ks/<pp (<passwordless-start {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :scope "openid profile email"} {:send "link" :email "<EMAIL>" :connection "email"})) (.passwordlessStart (webauth {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token"}) (clj->js {:send "link" :email "<EMAIL>" :connection "email"}) (fn [err res] )) (.userInfo (webauth {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token"}) (fn [& a] (prn a))) (gol (let [client (<! (<create-client {:domain "welcap.us.auth0.com" :client_id "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :redirect_uri "http://localhost:5000/auth0-cb"}))] (time (<! (<login-with-redirect client))))) (gol (let [client (<! (<create-client {:domain "welcap.us.auth0.com" :client_id "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :redirect_uri "http://localhost:5000"}))] (time (<! (<login-with-popup client))))) )
true
(ns rx.browser.auth0 (:require [rx.kitchen-sink :as ks] [rx.browser :as browser] [rx.browser.local-storage :as ls] [auth0-spa-js] [auth0] [rx.anom :as anom :refer-macros [gol <? <defn]] [clojure.core.async :as async :refer [go <! put! chan close!]])) (defn <create-client [opts] (ks/<promise (js/createAuth0Client (clj->js opts)))) (defn <login-with-redirect [client opts] (ks/<promise (.loginWithRedirect client (clj->js opts)))) (defn <login-with-popup [client] (ks/<promise (.loginWithPopup client))) (defn webauth [opts] (js/auth0.WebAuth. (clj->js opts))) (defn ensure-webauth-client [opts] (if (map? opts) (webauth opts) opts)) (defn <passwordless-start [opts-or-client opts] (let [ch (chan) client (ensure-webauth-client opts-or-client)] (.passwordlessStart client (clj->js opts) (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) res))) (close! ch))) ch)) (defn <parse-hash [webauth-opts-or-client & [opts]] (let [ch (chan) client (ensure-webauth-client webauth-opts-or-client)] (.parseHash client (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) {:access-token (.-accessToken res) :expires-in (.-expiresIn res) :id-token (.-idToken res)}))) (close! ch))) ch)) (defn <user-info [webauth-opts-or-client access-token] (let [ch (chan) client (ensure-webauth-client webauth-opts-or-client)] (try (.userInfo (.-client client) access-token (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) (js->clj res :keywordize-keys true)))) (close! ch))) (catch js/Error e (put! ch (anom/from-err e)) (close! ch))) ch)) (defn <check-session [webauth-opts-or-client opts] (let [ch (chan)] (.checkSession (ensure-webauth-client webauth-opts-or-client) (clj->js opts) (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) (js->clj res :keywordize-keys true)))) (close! ch))) ch)) (defn <logout [webauth-opts-or-client opts] (let [ch (chan)] (.logout (ensure-webauth-client webauth-opts-or-client) (clj->js opts) (fn [err res] (when (or err res) (put! ch (if err (anom/anom {:desc (.-errorDescription err) :err (js->clj err)}) (js->clj res :keywordize-keys true)))) (close! ch))) ch)) (defn <logout-and-clear-local [& args] (ls/set-transit "wc-access-token" nil) (ls/set-transit "wc-user-info" nil) (apply <logout args)) ;; CLJS Api (defn get-current-user [] (ls/get-transit "wc-user-info")) (<defn <handle-login-hash [webauth-opts-or-client] (let [client (ensure-webauth-client webauth-opts-or-client) auth (<? (<parse-hash client {})) user-info (<? (<user-info client (:access-token auth)))] (ls/set-transit "wc-access-token" (:access-token auth)) (ls/set-transit "wc-user-info" user-info) user-info)) (<defn <init-auth [webauth-opts-or-client] (try (if-let [access-token (ls/get-transit "wc-access-token")] (let [user-info (<! (<user-info webauth-opts-or-client access-token))] (if (anom/? user-info) (let [user-info (<! (<handle-login-hash webauth-opts-or-client))] (if (anom/? user-info) (do (println "Auth failed, clearing local auth state" (pr-str user-info)) (ls/set-transit "wc-access-token" nil) (ls/set-transit "wc-user-info" nil) nil) (do (println "Auth succeeded via hash info") (ls/set-transit "wc-user-info" user-info) #_(set! js/window.location.hash "") user-info))) (do (println "Auth succeeded via stored token") (ls/set-transit "wc-user-info" user-info) user-info))) (let [user-info (<! (<handle-login-hash webauth-opts-or-client))] (if (anom/? user-info) (do (println "Auth failed, clearing local auth state" (pr-str user-info)) (ls/set-transit "wc-access-token" nil) (ls/set-transit "wc-user-info" nil) nil) (do (println "Auth succeeded via hash info") (ls/set-transit "wc-user-info" user-info) #_(set! js/window.location.hash "") user-info)))) (catch js/Error e (println "Auth failed with exception" e) (ls/set-transit "wc-access-token" nil) (ls/set-transit "wc-user-info" nil) (throw e)))) (comment (<logout-and-clear-local {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI"} {:clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :returnTo "http://localhost:5000"}) (<init-auth {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :scope "openid profile email"}) (ls/set-transit "wc-user-info" nil) (ls/set-transit "wc-access-token" nil) (ls/get-transit "wc-user-info") (ls/get-transit "wc-access-token") (gol (ks/pp (<! (<handle-login-hash {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :scope "openid profile email"})))) (ls/get-transit "wc-access-token") (ks/<pp (<passwordless-start {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :scope "openid profile email"} {:send "link" :email "PI:EMAIL:<EMAIL>END_PI" :connection "email"})) (gol (def auth (ks/spy (<! (<parse-hash {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI"} {}))))) (prn (.-accessToken auth)) (gol (ls/set-transit "wc-user-info" (<! (<user-info {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI"} (ls/get-transit "wc-access-token"))))) (ls/get-transit "wc-user-info") (gol (ks/pp (<! (<check-session {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :redirectUri "http://localhost:5000"} {} (.-accessToken auth))))) (gol (ks/pp (<! (<parse-hash {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI"} {})))) (ks/<pp (<passwordless-start {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token" :scope "openid profile email"} {:send "link" :email "PI:EMAIL:<EMAIL>END_PI" :connection "email"})) (.passwordlessStart (webauth {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token"}) (clj->js {:send "link" :email "PI:EMAIL:<EMAIL>END_PI" :connection "email"}) (fn [err res] )) (.userInfo (webauth {:domain "welcap.us.auth0.com" :clientID "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :responseType "token id_token"}) (fn [& a] (prn a))) (gol (let [client (<! (<create-client {:domain "welcap.us.auth0.com" :client_id "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :redirect_uri "http://localhost:5000/auth0-cb"}))] (time (<! (<login-with-redirect client))))) (gol (let [client (<! (<create-client {:domain "welcap.us.auth0.com" :client_id "I3yfRzzSB8GsjkAMhnScttxhSVhaziuI" :redirect_uri "http://localhost:5000"}))] (time (<! (<login-with-popup client))))) )
[ { "context": " [re-frame \"0.10.2\"]\n [com.andrewmcveigh/cljs-time \"0.5.2\"]\n [org.clojure/", "end": 335, "score": 0.953022301197052, "start": 322, "tag": "USERNAME", "value": "andrewmcveigh" }, { "context": " :credentials {:secret \"93e34684-f889-4021-851a-4dd278138612\"}}}}\n :externs [\"lib/keycloak/", "end": 3667, "score": 0.9995419979095459, "start": 3631, "tag": "KEY", "value": "93e34684-f889-4021-851a-4dd278138612" } ]
sample/frontend/project.clj
borkdude/keycloak-clojure
122
(defproject myapp/frontend "0.1.0-SNAPSHOT" :dependencies [[org.clojure/clojure "1.9.0"] [org.clojure/clojurescript "1.9.946"] [mount "0.1.11"] [com.taoensso/timbre "4.10.0"] [reagent "0.7.0"] [re-frame "0.10.2"] [com.andrewmcveigh/cljs-time "0.5.2"] [org.clojure/core.async "0.3.465"] [re-com "2.1.0"] [secretary "1.2.3"] [garden "1.3.3"] [ns-tracker "0.3.1"] [figwheel-sidecar "0.5.14"] [com.cemerick/piggieback "0.2.2"] [day8.re-frame/http-fx "0.1.4"] ] :plugins [[lein-cljsbuild "1.1.5"] [lein-garden "0.2.8"]] :min-lein-version "2.5.3" :source-paths ["src/clj"] :clean-targets ^{:protect false} ["resources/public/js/compiled" "target" "test/js" "resources/public/css"] :garden {:builds [{:id "screen" :source-paths ["src/clj"] :stylesheet myapp.front.css/screen :compiler {:output-to "resources/public/css/screen.css" :pretty-print? true}}]} :repl-options {:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :aliases {"dev" ["do" "clean" ["pdo" ["figwheel" "dev"] ["garden" "auto"]]] "build" ["do" "clean" ["cljsbuild" "once" "min"] ["garden" "once"]]} :profiles {:dev {:dependencies [[binaryage/devtools "0.9.7"] [day8.re-frame/trace "0.1.13"] [figwheel-sidecar "0.5.14"] [proto-repl "0.3.1"] [com.cemerick/piggieback "0.2.2" :exclude [org.clojure/clojurescript]] [org.clojure/tools.nrepl "0.2.13"] [re-frisk "0.5.2"]] :repl-options {:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :plugins [[lein-figwheel "0.5.14"] [lein-doo "0.1.8"] [lein-pdo "0.1.1"]]}} :figwheel {:css-dirs ["resources/public/css"] :server-port 3449 :nrepl-port 7002 :nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :cljsbuild {:builds [{:id "dev" :source-paths ["src/cljs"] :figwheel {:on-jsload "myapp.front.core/mount-root"} :compiler {:main myapp.front.core :output-to "resources/public/js/compiled/app.js" :output-dir "resources/public/js/compiled/out" :asset-path "js/compiled/out" :source-map-timestamp true :preloads [devtools.preload day8.re-frame.trace.preload re-frisk.preload] :closure-defines {"re_frame.trace.trace_enabled_QMARK_" true} :external-config {:devtools/config {:features-to-install :all} :myapp {:keycloak {:url "https://keycloak.mydomain.com/auth" :realm "myrealm" :clientId "myapp" :credentials {:secret "93e34684-f889-4021-851a-4dd278138612"}}}} :externs ["lib/keycloak/keycloak-externs.js"] :foreign-libs [{:file "lib/keycloak/keycloak.js" :provides ["keycloak-js"]}]}} {:id "min" :source-paths ["src/cljs"] :jar true :compiler {:main myapp.front.core :output-to "resources/public/js/compiled/app.js" :optimizations :advanced :closure-defines {goog.DEBUG false} :externs ["lib/keycloak/keycloak-externs.js"] :foreign-libs [{:file "lib/keycloak/keycloak.min.js" :provides ["keycloak-js"]}] :pretty-print false}} {:id "test" :source-paths ["src/cljs" "test/cljs"] :compiler {:main myapp.front.runner :output-to "resources/public/js/compiled/test.js" :output-dir "resources/public/js/compiled/test/out" :foreign-libs [{:file "lib/keycloak/keycloak.js" :provides ["keycloak-js"]}] :optimizations :none}}]} :jvm-opts ["--add-modules" "java.xml.bind"])
41210
(defproject myapp/frontend "0.1.0-SNAPSHOT" :dependencies [[org.clojure/clojure "1.9.0"] [org.clojure/clojurescript "1.9.946"] [mount "0.1.11"] [com.taoensso/timbre "4.10.0"] [reagent "0.7.0"] [re-frame "0.10.2"] [com.andrewmcveigh/cljs-time "0.5.2"] [org.clojure/core.async "0.3.465"] [re-com "2.1.0"] [secretary "1.2.3"] [garden "1.3.3"] [ns-tracker "0.3.1"] [figwheel-sidecar "0.5.14"] [com.cemerick/piggieback "0.2.2"] [day8.re-frame/http-fx "0.1.4"] ] :plugins [[lein-cljsbuild "1.1.5"] [lein-garden "0.2.8"]] :min-lein-version "2.5.3" :source-paths ["src/clj"] :clean-targets ^{:protect false} ["resources/public/js/compiled" "target" "test/js" "resources/public/css"] :garden {:builds [{:id "screen" :source-paths ["src/clj"] :stylesheet myapp.front.css/screen :compiler {:output-to "resources/public/css/screen.css" :pretty-print? true}}]} :repl-options {:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :aliases {"dev" ["do" "clean" ["pdo" ["figwheel" "dev"] ["garden" "auto"]]] "build" ["do" "clean" ["cljsbuild" "once" "min"] ["garden" "once"]]} :profiles {:dev {:dependencies [[binaryage/devtools "0.9.7"] [day8.re-frame/trace "0.1.13"] [figwheel-sidecar "0.5.14"] [proto-repl "0.3.1"] [com.cemerick/piggieback "0.2.2" :exclude [org.clojure/clojurescript]] [org.clojure/tools.nrepl "0.2.13"] [re-frisk "0.5.2"]] :repl-options {:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :plugins [[lein-figwheel "0.5.14"] [lein-doo "0.1.8"] [lein-pdo "0.1.1"]]}} :figwheel {:css-dirs ["resources/public/css"] :server-port 3449 :nrepl-port 7002 :nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :cljsbuild {:builds [{:id "dev" :source-paths ["src/cljs"] :figwheel {:on-jsload "myapp.front.core/mount-root"} :compiler {:main myapp.front.core :output-to "resources/public/js/compiled/app.js" :output-dir "resources/public/js/compiled/out" :asset-path "js/compiled/out" :source-map-timestamp true :preloads [devtools.preload day8.re-frame.trace.preload re-frisk.preload] :closure-defines {"re_frame.trace.trace_enabled_QMARK_" true} :external-config {:devtools/config {:features-to-install :all} :myapp {:keycloak {:url "https://keycloak.mydomain.com/auth" :realm "myrealm" :clientId "myapp" :credentials {:secret "<KEY>"}}}} :externs ["lib/keycloak/keycloak-externs.js"] :foreign-libs [{:file "lib/keycloak/keycloak.js" :provides ["keycloak-js"]}]}} {:id "min" :source-paths ["src/cljs"] :jar true :compiler {:main myapp.front.core :output-to "resources/public/js/compiled/app.js" :optimizations :advanced :closure-defines {goog.DEBUG false} :externs ["lib/keycloak/keycloak-externs.js"] :foreign-libs [{:file "lib/keycloak/keycloak.min.js" :provides ["keycloak-js"]}] :pretty-print false}} {:id "test" :source-paths ["src/cljs" "test/cljs"] :compiler {:main myapp.front.runner :output-to "resources/public/js/compiled/test.js" :output-dir "resources/public/js/compiled/test/out" :foreign-libs [{:file "lib/keycloak/keycloak.js" :provides ["keycloak-js"]}] :optimizations :none}}]} :jvm-opts ["--add-modules" "java.xml.bind"])
true
(defproject myapp/frontend "0.1.0-SNAPSHOT" :dependencies [[org.clojure/clojure "1.9.0"] [org.clojure/clojurescript "1.9.946"] [mount "0.1.11"] [com.taoensso/timbre "4.10.0"] [reagent "0.7.0"] [re-frame "0.10.2"] [com.andrewmcveigh/cljs-time "0.5.2"] [org.clojure/core.async "0.3.465"] [re-com "2.1.0"] [secretary "1.2.3"] [garden "1.3.3"] [ns-tracker "0.3.1"] [figwheel-sidecar "0.5.14"] [com.cemerick/piggieback "0.2.2"] [day8.re-frame/http-fx "0.1.4"] ] :plugins [[lein-cljsbuild "1.1.5"] [lein-garden "0.2.8"]] :min-lein-version "2.5.3" :source-paths ["src/clj"] :clean-targets ^{:protect false} ["resources/public/js/compiled" "target" "test/js" "resources/public/css"] :garden {:builds [{:id "screen" :source-paths ["src/clj"] :stylesheet myapp.front.css/screen :compiler {:output-to "resources/public/css/screen.css" :pretty-print? true}}]} :repl-options {:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :aliases {"dev" ["do" "clean" ["pdo" ["figwheel" "dev"] ["garden" "auto"]]] "build" ["do" "clean" ["cljsbuild" "once" "min"] ["garden" "once"]]} :profiles {:dev {:dependencies [[binaryage/devtools "0.9.7"] [day8.re-frame/trace "0.1.13"] [figwheel-sidecar "0.5.14"] [proto-repl "0.3.1"] [com.cemerick/piggieback "0.2.2" :exclude [org.clojure/clojurescript]] [org.clojure/tools.nrepl "0.2.13"] [re-frisk "0.5.2"]] :repl-options {:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :plugins [[lein-figwheel "0.5.14"] [lein-doo "0.1.8"] [lein-pdo "0.1.1"]]}} :figwheel {:css-dirs ["resources/public/css"] :server-port 3449 :nrepl-port 7002 :nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :cljsbuild {:builds [{:id "dev" :source-paths ["src/cljs"] :figwheel {:on-jsload "myapp.front.core/mount-root"} :compiler {:main myapp.front.core :output-to "resources/public/js/compiled/app.js" :output-dir "resources/public/js/compiled/out" :asset-path "js/compiled/out" :source-map-timestamp true :preloads [devtools.preload day8.re-frame.trace.preload re-frisk.preload] :closure-defines {"re_frame.trace.trace_enabled_QMARK_" true} :external-config {:devtools/config {:features-to-install :all} :myapp {:keycloak {:url "https://keycloak.mydomain.com/auth" :realm "myrealm" :clientId "myapp" :credentials {:secret "PI:KEY:<KEY>END_PI"}}}} :externs ["lib/keycloak/keycloak-externs.js"] :foreign-libs [{:file "lib/keycloak/keycloak.js" :provides ["keycloak-js"]}]}} {:id "min" :source-paths ["src/cljs"] :jar true :compiler {:main myapp.front.core :output-to "resources/public/js/compiled/app.js" :optimizations :advanced :closure-defines {goog.DEBUG false} :externs ["lib/keycloak/keycloak-externs.js"] :foreign-libs [{:file "lib/keycloak/keycloak.min.js" :provides ["keycloak-js"]}] :pretty-print false}} {:id "test" :source-paths ["src/cljs" "test/cljs"] :compiler {:main myapp.front.runner :output-to "resources/public/js/compiled/test.js" :output-dir "resources/public/js/compiled/test/out" :foreign-libs [{:file "lib/keycloak/keycloak.js" :provides ["keycloak-js"]}] :optimizations :none}}]} :jvm-opts ["--add-modules" "java.xml.bind"])
[ { "context": ";;\n;;\n;; Copyright 2013-2015 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic", "end": 33, "score": 0.950448215007782, "start": 30, "tag": "NAME", "value": "Net" } ]
pigpen-pig/src/test/clojure/pigpen/pig/runtime_test.clj
ombagus/Netflix
327
;; ;; ;; Copyright 2013-2015 Netflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.pig.runtime-test (:require [clojure.test :refer :all] [pigpen.runtime :as rt] [pigpen.pig.runtime :refer :all] [pigpen.extensions.test :refer [test-diff pigsym-zero pigsym-inc]] [taoensso.nippy :refer [freeze thaw]] [clojure.core.async :as a] [pigpen.extensions.core-async :as ae]) (:import [org.apache.pig.data DataByteArray Tuple TupleFactory DataBag BagFactory] [java.util Map])) ;; TODO test-tuple ;; TODO test-bag ; ***************** (deftest test-cast-bytes (testing "nil" (is (= nil (cast-bytes nil nil)))) (let [b (byte-array (mapv byte [97 98 99]))] (testing "bytearray" (is (= b (cast-bytes "bytearray" b)))) (testing "chararray" (is (= "abc" (cast-bytes "chararray" b)))))) ; ***************** (deftest test-hybrid->clojure (testing "DataByteArray" (is (= (rt/hybrid->clojure (DataByteArray. (freeze {:a [1 2 3]}))) {:a [1 2 3]}))) (testing "Tuple" (is (= (rt/hybrid->clojure (tuple (DataByteArray. (freeze "foo")) (DataByteArray. (freeze "bar")))) ["foo" "bar"]))) (testing "DataBag" (is (= (rt/hybrid->clojure (bag (tuple (DataByteArray. (freeze "foo"))))) ["foo"])))) ; ***************** ;; TODO test-native->clojure ; ***************** (deftest test-bag->chan (let [c (a/chan 5) b (bag (tuple 1) (tuple "a"))] (#'pigpen.pig.runtime/bag->chan c b) (is (= (a/<!! c) 1)) (is (= (a/<!! c) "a")))) (deftest test-lazy-bag-args (let [b (bag (tuple 1) (tuple "a")) args [b 2 "b"] [args* input-bags] (#'pigpen.pig.runtime/lazy-bag-args args) [a0 a1 a2] args* [i0 i1 i2] input-bags] (is (ae/channel? a0)) (is (= a1 2)) (is (= a2 "b")) (is (ae/channel? i0)) (is (nil? i1)) (is (nil? i2)))) (deftest test-create-accumulate-state (let [b (bag (tuple 1) (tuple "a")) t (tuple b 2 "b") [input-bags result] (#'pigpen.pig.runtime/create-accumulate-state (fn [[x y z]] [(a/<!! x) y z]) t) [i0 i1 i2] input-bags] (is (ae/channel? i0)) (is (nil? i1)) (is (nil? i2)) (is (ae/channel? result)))) (deftest test-accumulate (require '[clojure.core.async :as a]) (testing "1 bag" (let [t (tuple (apply bag (map tuple (range 100))) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [(range 100) 2 "b"])) (is (nil? state)))) (testing "2 bags" (let [t (tuple (apply bag (map tuple (range 100))) 2 "b") t' (tuple (apply bag (map tuple (range 100 200))) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) state t') result (udf-get-value state) state (udf-cleanup state)] (is (= result [(range 200) 2 "b"])) (is (nil? state)))) (testing "2 bag args" (let [t (tuple (bag (tuple 1) (tuple 2) (tuple 3)) (bag (tuple 4) (tuple 5) (tuple 6))) t' (tuple (bag (tuple 7) (tuple 8) (tuple 9)) (bag (tuple 10) (tuple 11) (tuple 12))) state (udf-accumulate (fn [_ [x y]] [(a/<!! x) (a/<!! y)]) nil t) state (udf-accumulate (fn [_ [x y]] [(a/<!! x) (a/<!! y)]) state t') result (udf-get-value state) state (udf-cleanup state)] (is (= result [[1 2 3 7 8 9] [4 5 6 10 11 12]])) (is (nil? state)))) (testing "empty bag" (let [t (tuple (bag) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [[] 2 "b"])) (is (nil? state)))) (testing "single value bag" (let [t (tuple (bag (tuple 1)) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [[1] 2 "b"])) (is (nil? state)))) (testing "all values" (let [t (tuple 1 2 "b") state (udf-accumulate (fn [_ [x y z]] [x y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [1 2 "b"])) (is (nil? state)))) (testing "nil in bag" (let [t (tuple (bag (tuple 1) (tuple nil) (tuple 3)) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [[1 nil 3] 2 "b"])) (is (nil? state)))) (testing "nil value" (let [t (tuple (bag) nil "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [[] nil "b"])) (is (nil? state)))) (testing "nil result" (let [t (tuple (apply bag (map tuple (range 100))) 2 "b") state (udf-accumulate (fn [_ [x y z]] nil) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result nil)) (is (nil? state)))) (testing "throw in agg" (let [t (tuple (bag (tuple "1") (tuple "a") (tuple "3")) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(mapv #(java.lang.Long/valueOf %) (a/<!! x)) y z]) nil t)] (is (thrown? RuntimeException (udf-get-value state))) (is (nil? (udf-cleanup state))))) (testing "throw in udf" (let [t (tuple (bag) 2 "b") state (udf-accumulate (fn [_ [x y z]] (throw (Exception.))) nil t)] (is (thrown? Exception (udf-get-value state))) (is (nil? (udf-cleanup state)))))) ; ***************** ;; TODO test serialization equivalency ;; TODO test serialization round-trip
70143
;; ;; ;; Copyright 2013-2015 <NAME>flix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.pig.runtime-test (:require [clojure.test :refer :all] [pigpen.runtime :as rt] [pigpen.pig.runtime :refer :all] [pigpen.extensions.test :refer [test-diff pigsym-zero pigsym-inc]] [taoensso.nippy :refer [freeze thaw]] [clojure.core.async :as a] [pigpen.extensions.core-async :as ae]) (:import [org.apache.pig.data DataByteArray Tuple TupleFactory DataBag BagFactory] [java.util Map])) ;; TODO test-tuple ;; TODO test-bag ; ***************** (deftest test-cast-bytes (testing "nil" (is (= nil (cast-bytes nil nil)))) (let [b (byte-array (mapv byte [97 98 99]))] (testing "bytearray" (is (= b (cast-bytes "bytearray" b)))) (testing "chararray" (is (= "abc" (cast-bytes "chararray" b)))))) ; ***************** (deftest test-hybrid->clojure (testing "DataByteArray" (is (= (rt/hybrid->clojure (DataByteArray. (freeze {:a [1 2 3]}))) {:a [1 2 3]}))) (testing "Tuple" (is (= (rt/hybrid->clojure (tuple (DataByteArray. (freeze "foo")) (DataByteArray. (freeze "bar")))) ["foo" "bar"]))) (testing "DataBag" (is (= (rt/hybrid->clojure (bag (tuple (DataByteArray. (freeze "foo"))))) ["foo"])))) ; ***************** ;; TODO test-native->clojure ; ***************** (deftest test-bag->chan (let [c (a/chan 5) b (bag (tuple 1) (tuple "a"))] (#'pigpen.pig.runtime/bag->chan c b) (is (= (a/<!! c) 1)) (is (= (a/<!! c) "a")))) (deftest test-lazy-bag-args (let [b (bag (tuple 1) (tuple "a")) args [b 2 "b"] [args* input-bags] (#'pigpen.pig.runtime/lazy-bag-args args) [a0 a1 a2] args* [i0 i1 i2] input-bags] (is (ae/channel? a0)) (is (= a1 2)) (is (= a2 "b")) (is (ae/channel? i0)) (is (nil? i1)) (is (nil? i2)))) (deftest test-create-accumulate-state (let [b (bag (tuple 1) (tuple "a")) t (tuple b 2 "b") [input-bags result] (#'pigpen.pig.runtime/create-accumulate-state (fn [[x y z]] [(a/<!! x) y z]) t) [i0 i1 i2] input-bags] (is (ae/channel? i0)) (is (nil? i1)) (is (nil? i2)) (is (ae/channel? result)))) (deftest test-accumulate (require '[clojure.core.async :as a]) (testing "1 bag" (let [t (tuple (apply bag (map tuple (range 100))) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [(range 100) 2 "b"])) (is (nil? state)))) (testing "2 bags" (let [t (tuple (apply bag (map tuple (range 100))) 2 "b") t' (tuple (apply bag (map tuple (range 100 200))) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) state t') result (udf-get-value state) state (udf-cleanup state)] (is (= result [(range 200) 2 "b"])) (is (nil? state)))) (testing "2 bag args" (let [t (tuple (bag (tuple 1) (tuple 2) (tuple 3)) (bag (tuple 4) (tuple 5) (tuple 6))) t' (tuple (bag (tuple 7) (tuple 8) (tuple 9)) (bag (tuple 10) (tuple 11) (tuple 12))) state (udf-accumulate (fn [_ [x y]] [(a/<!! x) (a/<!! y)]) nil t) state (udf-accumulate (fn [_ [x y]] [(a/<!! x) (a/<!! y)]) state t') result (udf-get-value state) state (udf-cleanup state)] (is (= result [[1 2 3 7 8 9] [4 5 6 10 11 12]])) (is (nil? state)))) (testing "empty bag" (let [t (tuple (bag) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [[] 2 "b"])) (is (nil? state)))) (testing "single value bag" (let [t (tuple (bag (tuple 1)) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [[1] 2 "b"])) (is (nil? state)))) (testing "all values" (let [t (tuple 1 2 "b") state (udf-accumulate (fn [_ [x y z]] [x y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [1 2 "b"])) (is (nil? state)))) (testing "nil in bag" (let [t (tuple (bag (tuple 1) (tuple nil) (tuple 3)) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [[1 nil 3] 2 "b"])) (is (nil? state)))) (testing "nil value" (let [t (tuple (bag) nil "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [[] nil "b"])) (is (nil? state)))) (testing "nil result" (let [t (tuple (apply bag (map tuple (range 100))) 2 "b") state (udf-accumulate (fn [_ [x y z]] nil) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result nil)) (is (nil? state)))) (testing "throw in agg" (let [t (tuple (bag (tuple "1") (tuple "a") (tuple "3")) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(mapv #(java.lang.Long/valueOf %) (a/<!! x)) y z]) nil t)] (is (thrown? RuntimeException (udf-get-value state))) (is (nil? (udf-cleanup state))))) (testing "throw in udf" (let [t (tuple (bag) 2 "b") state (udf-accumulate (fn [_ [x y z]] (throw (Exception.))) nil t)] (is (thrown? Exception (udf-get-value state))) (is (nil? (udf-cleanup state)))))) ; ***************** ;; TODO test serialization equivalency ;; TODO test serialization round-trip
true
;; ;; ;; Copyright 2013-2015 PI:NAME:<NAME>END_PIflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.pig.runtime-test (:require [clojure.test :refer :all] [pigpen.runtime :as rt] [pigpen.pig.runtime :refer :all] [pigpen.extensions.test :refer [test-diff pigsym-zero pigsym-inc]] [taoensso.nippy :refer [freeze thaw]] [clojure.core.async :as a] [pigpen.extensions.core-async :as ae]) (:import [org.apache.pig.data DataByteArray Tuple TupleFactory DataBag BagFactory] [java.util Map])) ;; TODO test-tuple ;; TODO test-bag ; ***************** (deftest test-cast-bytes (testing "nil" (is (= nil (cast-bytes nil nil)))) (let [b (byte-array (mapv byte [97 98 99]))] (testing "bytearray" (is (= b (cast-bytes "bytearray" b)))) (testing "chararray" (is (= "abc" (cast-bytes "chararray" b)))))) ; ***************** (deftest test-hybrid->clojure (testing "DataByteArray" (is (= (rt/hybrid->clojure (DataByteArray. (freeze {:a [1 2 3]}))) {:a [1 2 3]}))) (testing "Tuple" (is (= (rt/hybrid->clojure (tuple (DataByteArray. (freeze "foo")) (DataByteArray. (freeze "bar")))) ["foo" "bar"]))) (testing "DataBag" (is (= (rt/hybrid->clojure (bag (tuple (DataByteArray. (freeze "foo"))))) ["foo"])))) ; ***************** ;; TODO test-native->clojure ; ***************** (deftest test-bag->chan (let [c (a/chan 5) b (bag (tuple 1) (tuple "a"))] (#'pigpen.pig.runtime/bag->chan c b) (is (= (a/<!! c) 1)) (is (= (a/<!! c) "a")))) (deftest test-lazy-bag-args (let [b (bag (tuple 1) (tuple "a")) args [b 2 "b"] [args* input-bags] (#'pigpen.pig.runtime/lazy-bag-args args) [a0 a1 a2] args* [i0 i1 i2] input-bags] (is (ae/channel? a0)) (is (= a1 2)) (is (= a2 "b")) (is (ae/channel? i0)) (is (nil? i1)) (is (nil? i2)))) (deftest test-create-accumulate-state (let [b (bag (tuple 1) (tuple "a")) t (tuple b 2 "b") [input-bags result] (#'pigpen.pig.runtime/create-accumulate-state (fn [[x y z]] [(a/<!! x) y z]) t) [i0 i1 i2] input-bags] (is (ae/channel? i0)) (is (nil? i1)) (is (nil? i2)) (is (ae/channel? result)))) (deftest test-accumulate (require '[clojure.core.async :as a]) (testing "1 bag" (let [t (tuple (apply bag (map tuple (range 100))) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [(range 100) 2 "b"])) (is (nil? state)))) (testing "2 bags" (let [t (tuple (apply bag (map tuple (range 100))) 2 "b") t' (tuple (apply bag (map tuple (range 100 200))) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) state t') result (udf-get-value state) state (udf-cleanup state)] (is (= result [(range 200) 2 "b"])) (is (nil? state)))) (testing "2 bag args" (let [t (tuple (bag (tuple 1) (tuple 2) (tuple 3)) (bag (tuple 4) (tuple 5) (tuple 6))) t' (tuple (bag (tuple 7) (tuple 8) (tuple 9)) (bag (tuple 10) (tuple 11) (tuple 12))) state (udf-accumulate (fn [_ [x y]] [(a/<!! x) (a/<!! y)]) nil t) state (udf-accumulate (fn [_ [x y]] [(a/<!! x) (a/<!! y)]) state t') result (udf-get-value state) state (udf-cleanup state)] (is (= result [[1 2 3 7 8 9] [4 5 6 10 11 12]])) (is (nil? state)))) (testing "empty bag" (let [t (tuple (bag) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [[] 2 "b"])) (is (nil? state)))) (testing "single value bag" (let [t (tuple (bag (tuple 1)) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [[1] 2 "b"])) (is (nil? state)))) (testing "all values" (let [t (tuple 1 2 "b") state (udf-accumulate (fn [_ [x y z]] [x y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [1 2 "b"])) (is (nil? state)))) (testing "nil in bag" (let [t (tuple (bag (tuple 1) (tuple nil) (tuple 3)) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [[1 nil 3] 2 "b"])) (is (nil? state)))) (testing "nil value" (let [t (tuple (bag) nil "b") state (udf-accumulate (fn [_ [x y z]] [(a/<!! x) y z]) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result [[] nil "b"])) (is (nil? state)))) (testing "nil result" (let [t (tuple (apply bag (map tuple (range 100))) 2 "b") state (udf-accumulate (fn [_ [x y z]] nil) nil t) result (udf-get-value state) state (udf-cleanup state)] (is (= result nil)) (is (nil? state)))) (testing "throw in agg" (let [t (tuple (bag (tuple "1") (tuple "a") (tuple "3")) 2 "b") state (udf-accumulate (fn [_ [x y z]] [(mapv #(java.lang.Long/valueOf %) (a/<!! x)) y z]) nil t)] (is (thrown? RuntimeException (udf-get-value state))) (is (nil? (udf-cleanup state))))) (testing "throw in udf" (let [t (tuple (bag) 2 "b") state (udf-accumulate (fn [_ [x y z]] (throw (Exception.))) nil t)] (is (thrown? Exception (udf-get-value state))) (is (nil? (udf-cleanup state)))))) ; ***************** ;; TODO test serialization equivalency ;; TODO test serialization round-trip
[ { "context": " support - print a usage message.\"\n :author \"Simon Brooke\"}\n adl-support.print-usage\n (:require [clojure.", "end": 106, "score": 0.9998811483383179, "start": 94, "tag": "NAME", "value": "Simon Brooke" }, { "context": "nse for more details.\n;;;;\n;;;; Copyright (C) 2018 Simon Brooke\n;;;;\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 766, "score": 0.9998728036880493, "start": 754, "tag": "NAME", "value": "Simon Brooke" } ]
src/adl_support/print_usage.clj
simon-brooke/adl-support
0
(ns ^{:doc "Application Description Language support - print a usage message." :author "Simon Brooke"} adl-support.print-usage (:require [clojure.string :refer [join]])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; ;;;; adl-support.print-usage: functions used by ADL-generated code. ;;;; ;;;; This program is free software; you can redistribute it and/or ;;;; modify it under the terms of the MIT-style licence provided; see LICENSE. ;;;; ;;;; 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 ;;;; License for more details. ;;;; ;;;; Copyright (C) 2018 Simon Brooke ;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn print-usage "Print a UN*X style usage message. `project-name` should be the base name of the executable jar file you generate, `parsed-options` should be options as parsed by [clojure.tools.cli](https://github.com/clojure/tools.cli). If `extra-args` is supplied, it should be a map of name, documentation pairs for each additional argument which may be supplied." ([project-name parsed-options] (print-usage project-name parsed-options {})) ([project-name parsed-options extra-args] (println (join "\n" (flatten (list (join " " (concat (list "Usage: java -jar " (str project-name "-" (or (System/getProperty (str project-name ".version")) "[VERSION]") "-standalone.jar") "-options") (map name (keys extra-args)))) "where options include:" (:summary parsed-options) (doall (map #(str " " (name %) "\t\t" (extra-args %)) (keys extra-args)))))))))
75767
(ns ^{:doc "Application Description Language support - print a usage message." :author "<NAME>"} adl-support.print-usage (:require [clojure.string :refer [join]])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; ;;;; adl-support.print-usage: functions used by ADL-generated code. ;;;; ;;;; This program is free software; you can redistribute it and/or ;;;; modify it under the terms of the MIT-style licence provided; see LICENSE. ;;;; ;;;; 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 ;;;; License for more details. ;;;; ;;;; Copyright (C) 2018 <NAME> ;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn print-usage "Print a UN*X style usage message. `project-name` should be the base name of the executable jar file you generate, `parsed-options` should be options as parsed by [clojure.tools.cli](https://github.com/clojure/tools.cli). If `extra-args` is supplied, it should be a map of name, documentation pairs for each additional argument which may be supplied." ([project-name parsed-options] (print-usage project-name parsed-options {})) ([project-name parsed-options extra-args] (println (join "\n" (flatten (list (join " " (concat (list "Usage: java -jar " (str project-name "-" (or (System/getProperty (str project-name ".version")) "[VERSION]") "-standalone.jar") "-options") (map name (keys extra-args)))) "where options include:" (:summary parsed-options) (doall (map #(str " " (name %) "\t\t" (extra-args %)) (keys extra-args)))))))))
true
(ns ^{:doc "Application Description Language support - print a usage message." :author "PI:NAME:<NAME>END_PI"} adl-support.print-usage (:require [clojure.string :refer [join]])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; ;;;; adl-support.print-usage: functions used by ADL-generated code. ;;;; ;;;; This program is free software; you can redistribute it and/or ;;;; modify it under the terms of the MIT-style licence provided; see LICENSE. ;;;; ;;;; 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 ;;;; License for more details. ;;;; ;;;; Copyright (C) 2018 PI:NAME:<NAME>END_PI ;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn print-usage "Print a UN*X style usage message. `project-name` should be the base name of the executable jar file you generate, `parsed-options` should be options as parsed by [clojure.tools.cli](https://github.com/clojure/tools.cli). If `extra-args` is supplied, it should be a map of name, documentation pairs for each additional argument which may be supplied." ([project-name parsed-options] (print-usage project-name parsed-options {})) ([project-name parsed-options extra-args] (println (join "\n" (flatten (list (join " " (concat (list "Usage: java -jar " (str project-name "-" (or (System/getProperty (str project-name ".version")) "[VERSION]") "-standalone.jar") "-options") (map name (keys extra-args)))) "where options include:" (:summary parsed-options) (doall (map #(str " " (name %) "\t\t" (extra-args %)) (keys extra-args)))))))))
[ { "context": "\"Utilities for benchmarking scripts.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-04-06\"\n :version \"2017-05-29\"}", "end": 278, "score": 0.8946546912193298, "start": 242, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/scripts/clojure/palisades/lakes/elements/scripts/defs.clj
palisades-lakes/les-elemens
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.scripts.defs {:doc "Utilities for benchmarking scripts." :author "palisades dot lakes at gmail dot com" :since "2017-04-06" :version "2017-05-29"} (:require [clojure.string :as s] [clojure.java.io :as io] [palisades.lakes.elements.api :as mc])) ;;---------------------------------------------------------------- (defn ^java.io.File ns-file [prefix for-ns fname] (let [f (apply io/file prefix (concat (drop 2 (s/split (str for-ns) #"\.")) [fname]))] (io/make-parents f) f)) (defn ^java.io.File log-file [for-ns fname] (ns-file "logs" for-ns fname)) (defn ^java.io.File data-file [for-ns fname] (ns-file "data" for-ns fname)) ;;---------------------------------------------------------------- ;; coercions ;;---------------------------------------------------------------- (defn array-list ^java.util.ArrayList [x] (java.util.ArrayList. ^java.util.List (vec x))) (defn lazy-list [x] (map identity (vec x))) ;;---------------------------------------------------------------- ;; criterium output ;;---------------------------------------------------------------- (defn simplify [record] (let [record (dissoc record :runtime-details :os-details :samples :results :overhead :final-gc-time :sample-count :execution-count :tail-quantile :warmup-time :outlier-variance :outliers :options :sample-mean :sample-variance :warmup-executions :variance)] (assoc (dissoc record :mean) :msec (first (:mean record)) ;;:variance (first (:variance record)) :lower-q (first (:lower-q record)) :upper-q (first (:upper-q record))))) ;;----------------------------------------------------------------
36985
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.scripts.defs {:doc "Utilities for benchmarking scripts." :author "<EMAIL>" :since "2017-04-06" :version "2017-05-29"} (:require [clojure.string :as s] [clojure.java.io :as io] [palisades.lakes.elements.api :as mc])) ;;---------------------------------------------------------------- (defn ^java.io.File ns-file [prefix for-ns fname] (let [f (apply io/file prefix (concat (drop 2 (s/split (str for-ns) #"\.")) [fname]))] (io/make-parents f) f)) (defn ^java.io.File log-file [for-ns fname] (ns-file "logs" for-ns fname)) (defn ^java.io.File data-file [for-ns fname] (ns-file "data" for-ns fname)) ;;---------------------------------------------------------------- ;; coercions ;;---------------------------------------------------------------- (defn array-list ^java.util.ArrayList [x] (java.util.ArrayList. ^java.util.List (vec x))) (defn lazy-list [x] (map identity (vec x))) ;;---------------------------------------------------------------- ;; criterium output ;;---------------------------------------------------------------- (defn simplify [record] (let [record (dissoc record :runtime-details :os-details :samples :results :overhead :final-gc-time :sample-count :execution-count :tail-quantile :warmup-time :outlier-variance :outliers :options :sample-mean :sample-variance :warmup-executions :variance)] (assoc (dissoc record :mean) :msec (first (:mean record)) ;;:variance (first (:variance record)) :lower-q (first (:lower-q record)) :upper-q (first (:upper-q record))))) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.scripts.defs {:doc "Utilities for benchmarking scripts." :author "PI:EMAIL:<EMAIL>END_PI" :since "2017-04-06" :version "2017-05-29"} (:require [clojure.string :as s] [clojure.java.io :as io] [palisades.lakes.elements.api :as mc])) ;;---------------------------------------------------------------- (defn ^java.io.File ns-file [prefix for-ns fname] (let [f (apply io/file prefix (concat (drop 2 (s/split (str for-ns) #"\.")) [fname]))] (io/make-parents f) f)) (defn ^java.io.File log-file [for-ns fname] (ns-file "logs" for-ns fname)) (defn ^java.io.File data-file [for-ns fname] (ns-file "data" for-ns fname)) ;;---------------------------------------------------------------- ;; coercions ;;---------------------------------------------------------------- (defn array-list ^java.util.ArrayList [x] (java.util.ArrayList. ^java.util.List (vec x))) (defn lazy-list [x] (map identity (vec x))) ;;---------------------------------------------------------------- ;; criterium output ;;---------------------------------------------------------------- (defn simplify [record] (let [record (dissoc record :runtime-details :os-details :samples :results :overhead :final-gc-time :sample-count :execution-count :tail-quantile :warmup-time :outlier-variance :outliers :options :sample-mean :sample-variance :warmup-executions :variance)] (assoc (dissoc record :mean) :msec (first (:mean record)) ;;:variance (first (:variance record)) :lower-q (first (:lower-q record)) :upper-q (first (:upper-q record))))) ;;----------------------------------------------------------------
[ { "context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,", "end": 48, "score": 0.9998858571052551, "start": 36, "tag": "NAME", "value": "Ronen Narkis" }, { "context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,\n Version 2.", "end": 61, "score": 0.8438491821289062, "start": 50, "tag": "EMAIL", "value": "narkisr.com" } ]
src/aws/networking.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 aws.networking "AWS networking functions" (:import com.amazonaws.services.ec2.model.AssociateAddressRequest) (:require [hypervisors.networking :as net] [taoensso.timbre :as timbre] [amazonica.aws.ec2 :as ec2] [slingshot.slingshot :refer [throw+]] [re-core.model :refer (hypervisor)] [supernal.sshj :refer (execute)] [clojure.core.strint :refer (<<)] [clojure.string :refer (join)] [aws.common :refer (with-ctx instance-desc)] [re-core.persistency.systems :as s])) (timbre/refer-timbre) (defn instance-ip [{:keys [aws] :as spec} endpoint instance-id] (let [public-ip (instance-desc endpoint instance-id :public-ip-address) private-ip (instance-desc endpoint instance-id :private-ip-address)] (if public-ip public-ip (when (and (aws :network-interfaces) private-ip) private-ip)))) (defn update-ip [{:keys [aws] :as spec} endpoint instance-id] "updates public dns in the machine persisted data" (when (s/system-exists? (spec :system-id)) (s/partial-system (spec :system-id) {:machine {:ip (instance-ip spec endpoint instance-id)}}))) (defn set-hostname [{:keys [machine] :as spec} endpoint instance-id user] "Uses a generic method of setting hostname in Linux (see http://www.debianadmin.com/manpages/sysctlmanpage.txt) Note that in ec2 both Centos and Ubuntu use sudo!" (let [{:keys [hostname domain os]} machine fqdn (<< "~{hostname}.~{domain}") remote {:host (instance-ip spec endpoint instance-id) :user user} flavor (hypervisor :aws :ostemplates os :flavor) ] (net/set-hostname hostname fqdn remote flavor) (with-ctx ec2/create-tags {:resources [instance-id] :tags [{:key "Name" :value hostname}]}) )) (defn describe-eip [endpoint instance-id] (with-ctx ec2/describe-addresses :filters [{:name "instance-id" :values [instance-id]}])) (defn describe-address [endpoint ip] (get-in (with-ctx ec2/describe-addresses {:public-ips [ip]}) [:addresses 0])) (defn attach-vpc-ip [endpoint instance-id {:keys [machine aws] :as spec}] (let [{:keys [ip]} machine {:keys [allocation-id]} (describe-address endpoint ip)] (with-ctx ec2/associate-address {:instance-id instance-id :allocation-id allocation-id}))) (defn assoc-pub-ip [endpoint instance-id {:keys [machine aws] :as spec}] (let [{:keys [ip]} machine {:keys [network-interfaces]} aws] (if-not network-interfaces (with-ctx ec2/associate-address {:instance-id instance-id :public-ip ip}) (attach-vpc-ip endpoint instance-id spec))))
66315
(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 aws.networking "AWS networking functions" (:import com.amazonaws.services.ec2.model.AssociateAddressRequest) (:require [hypervisors.networking :as net] [taoensso.timbre :as timbre] [amazonica.aws.ec2 :as ec2] [slingshot.slingshot :refer [throw+]] [re-core.model :refer (hypervisor)] [supernal.sshj :refer (execute)] [clojure.core.strint :refer (<<)] [clojure.string :refer (join)] [aws.common :refer (with-ctx instance-desc)] [re-core.persistency.systems :as s])) (timbre/refer-timbre) (defn instance-ip [{:keys [aws] :as spec} endpoint instance-id] (let [public-ip (instance-desc endpoint instance-id :public-ip-address) private-ip (instance-desc endpoint instance-id :private-ip-address)] (if public-ip public-ip (when (and (aws :network-interfaces) private-ip) private-ip)))) (defn update-ip [{:keys [aws] :as spec} endpoint instance-id] "updates public dns in the machine persisted data" (when (s/system-exists? (spec :system-id)) (s/partial-system (spec :system-id) {:machine {:ip (instance-ip spec endpoint instance-id)}}))) (defn set-hostname [{:keys [machine] :as spec} endpoint instance-id user] "Uses a generic method of setting hostname in Linux (see http://www.debianadmin.com/manpages/sysctlmanpage.txt) Note that in ec2 both Centos and Ubuntu use sudo!" (let [{:keys [hostname domain os]} machine fqdn (<< "~{hostname}.~{domain}") remote {:host (instance-ip spec endpoint instance-id) :user user} flavor (hypervisor :aws :ostemplates os :flavor) ] (net/set-hostname hostname fqdn remote flavor) (with-ctx ec2/create-tags {:resources [instance-id] :tags [{:key "Name" :value hostname}]}) )) (defn describe-eip [endpoint instance-id] (with-ctx ec2/describe-addresses :filters [{:name "instance-id" :values [instance-id]}])) (defn describe-address [endpoint ip] (get-in (with-ctx ec2/describe-addresses {:public-ips [ip]}) [:addresses 0])) (defn attach-vpc-ip [endpoint instance-id {:keys [machine aws] :as spec}] (let [{:keys [ip]} machine {:keys [allocation-id]} (describe-address endpoint ip)] (with-ctx ec2/associate-address {:instance-id instance-id :allocation-id allocation-id}))) (defn assoc-pub-ip [endpoint instance-id {:keys [machine aws] :as spec}] (let [{:keys [ip]} machine {:keys [network-interfaces]} aws] (if-not network-interfaces (with-ctx ec2/associate-address {:instance-id instance-id :public-ip ip}) (attach-vpc-ip endpoint instance-id spec))))
true
(comment re-core, Copyright 2012 PI:NAME:<NAME>END_PI, PI:EMAIL:<EMAIL>END_PI Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.) (ns aws.networking "AWS networking functions" (:import com.amazonaws.services.ec2.model.AssociateAddressRequest) (:require [hypervisors.networking :as net] [taoensso.timbre :as timbre] [amazonica.aws.ec2 :as ec2] [slingshot.slingshot :refer [throw+]] [re-core.model :refer (hypervisor)] [supernal.sshj :refer (execute)] [clojure.core.strint :refer (<<)] [clojure.string :refer (join)] [aws.common :refer (with-ctx instance-desc)] [re-core.persistency.systems :as s])) (timbre/refer-timbre) (defn instance-ip [{:keys [aws] :as spec} endpoint instance-id] (let [public-ip (instance-desc endpoint instance-id :public-ip-address) private-ip (instance-desc endpoint instance-id :private-ip-address)] (if public-ip public-ip (when (and (aws :network-interfaces) private-ip) private-ip)))) (defn update-ip [{:keys [aws] :as spec} endpoint instance-id] "updates public dns in the machine persisted data" (when (s/system-exists? (spec :system-id)) (s/partial-system (spec :system-id) {:machine {:ip (instance-ip spec endpoint instance-id)}}))) (defn set-hostname [{:keys [machine] :as spec} endpoint instance-id user] "Uses a generic method of setting hostname in Linux (see http://www.debianadmin.com/manpages/sysctlmanpage.txt) Note that in ec2 both Centos and Ubuntu use sudo!" (let [{:keys [hostname domain os]} machine fqdn (<< "~{hostname}.~{domain}") remote {:host (instance-ip spec endpoint instance-id) :user user} flavor (hypervisor :aws :ostemplates os :flavor) ] (net/set-hostname hostname fqdn remote flavor) (with-ctx ec2/create-tags {:resources [instance-id] :tags [{:key "Name" :value hostname}]}) )) (defn describe-eip [endpoint instance-id] (with-ctx ec2/describe-addresses :filters [{:name "instance-id" :values [instance-id]}])) (defn describe-address [endpoint ip] (get-in (with-ctx ec2/describe-addresses {:public-ips [ip]}) [:addresses 0])) (defn attach-vpc-ip [endpoint instance-id {:keys [machine aws] :as spec}] (let [{:keys [ip]} machine {:keys [allocation-id]} (describe-address endpoint ip)] (with-ctx ec2/associate-address {:instance-id instance-id :allocation-id allocation-id}))) (defn assoc-pub-ip [endpoint instance-id {:keys [machine aws] :as spec}] (let [{:keys [ip]} machine {:keys [network-interfaces]} aws] (if-not network-interfaces (with-ctx ec2/associate-address {:instance-id instance-id :public-ip ip}) (attach-vpc-ip endpoint instance-id spec))))
[ { "context": " \n\n; The MIT License (MIT)\n;\n; Copyright (c) 2015 Jason Waag\n;\n; Permission is hereby granted, free of charge,", "end": 1527, "score": 0.9998025894165039, "start": 1517, "tag": "NAME", "value": "Jason Waag" } ]
src/accounting/render.cljs
jaw977/accounting-cljs-om
2
(ns accounting.render (:require [clojure.string :as str] [om.dom :as dom :include-macros true] [accounting.util :refer [log log-clj fixpt->str]])) (def right-align #js {:style #js {:textAlign "right"}}) (def top-align #js {:style #js {:verticalAlign "text-top"}}) (defn display-unit [unit] (if unit (str (subs (str unit) 1) " ") "$")) (defn display-amount ([amount] (display-amount amount nil nil)) ([amount unit] (display-amount amount unit nil)) ([amount unit neg] (str (display-unit unit) (str/replace (fixpt->str (if neg (- amount) amount)) #"\B(?=(\d{3})+(?!\d))" ",")))) (defn table-headings [headings] (dom/thead nil (apply dom/tr nil (for [heading headings] (dom/th nil heading))))) (defn menu [desc titles current-screen send! event-type] (apply dom/p nil desc (interpose " \u00A0 " (for [title titles :let [screen (keyword (str/lower-case title))]] (if (= screen current-screen) (dom/span #js {:style #js {:fontWeight "bold"}} title) (dom/a #js {:onClick (send! event-type screen) :href "#"} title)))))) (defn camelcase-symbol->str [sym] (if (symbol? sym) (str/replace (str sym) #"([a-z])([A-Z])" "$1 $2") (str sym))) (defn format-date [date] (if date (let [date (str date)] (str (subs date 0 4) "/" (subs date 4 6) "/" (subs date 6))))) ; The MIT License (MIT) ; ; Copyright (c) 2015 Jason Waag ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ; THE SOFTWARE.
40933
(ns accounting.render (:require [clojure.string :as str] [om.dom :as dom :include-macros true] [accounting.util :refer [log log-clj fixpt->str]])) (def right-align #js {:style #js {:textAlign "right"}}) (def top-align #js {:style #js {:verticalAlign "text-top"}}) (defn display-unit [unit] (if unit (str (subs (str unit) 1) " ") "$")) (defn display-amount ([amount] (display-amount amount nil nil)) ([amount unit] (display-amount amount unit nil)) ([amount unit neg] (str (display-unit unit) (str/replace (fixpt->str (if neg (- amount) amount)) #"\B(?=(\d{3})+(?!\d))" ",")))) (defn table-headings [headings] (dom/thead nil (apply dom/tr nil (for [heading headings] (dom/th nil heading))))) (defn menu [desc titles current-screen send! event-type] (apply dom/p nil desc (interpose " \u00A0 " (for [title titles :let [screen (keyword (str/lower-case title))]] (if (= screen current-screen) (dom/span #js {:style #js {:fontWeight "bold"}} title) (dom/a #js {:onClick (send! event-type screen) :href "#"} title)))))) (defn camelcase-symbol->str [sym] (if (symbol? sym) (str/replace (str sym) #"([a-z])([A-Z])" "$1 $2") (str sym))) (defn format-date [date] (if date (let [date (str date)] (str (subs date 0 4) "/" (subs date 4 6) "/" (subs date 6))))) ; The MIT License (MIT) ; ; Copyright (c) 2015 <NAME> ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ; THE SOFTWARE.
true
(ns accounting.render (:require [clojure.string :as str] [om.dom :as dom :include-macros true] [accounting.util :refer [log log-clj fixpt->str]])) (def right-align #js {:style #js {:textAlign "right"}}) (def top-align #js {:style #js {:verticalAlign "text-top"}}) (defn display-unit [unit] (if unit (str (subs (str unit) 1) " ") "$")) (defn display-amount ([amount] (display-amount amount nil nil)) ([amount unit] (display-amount amount unit nil)) ([amount unit neg] (str (display-unit unit) (str/replace (fixpt->str (if neg (- amount) amount)) #"\B(?=(\d{3})+(?!\d))" ",")))) (defn table-headings [headings] (dom/thead nil (apply dom/tr nil (for [heading headings] (dom/th nil heading))))) (defn menu [desc titles current-screen send! event-type] (apply dom/p nil desc (interpose " \u00A0 " (for [title titles :let [screen (keyword (str/lower-case title))]] (if (= screen current-screen) (dom/span #js {:style #js {:fontWeight "bold"}} title) (dom/a #js {:onClick (send! event-type screen) :href "#"} title)))))) (defn camelcase-symbol->str [sym] (if (symbol? sym) (str/replace (str sym) #"([a-z])([A-Z])" "$1 $2") (str sym))) (defn format-date [date] (if date (let [date (str date)] (str (subs date 0 4) "/" (subs date 4 6) "/" (subs date 6))))) ; The MIT License (MIT) ; ; Copyright (c) 2015 PI:NAME:<NAME>END_PI ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ; THE SOFTWARE.
[ { "context": "s.gcal.ent/event--regular\n {:iCalUID \"goog-event-id@google.com\",\n :description \"Ivan Fedorov is invitin", "end": 13073, "score": 0.9991801381111145, "start": 13049, "tag": "EMAIL", "value": "goog-event-id@google.com" }, { "context": "oog-event-id@google.com\",\n :description \"Ivan Fedorov is inviting you to a scheduled Zoom meeting.\",\n ", "end": 13112, "score": 0.9997555613517761, "start": 13100, "tag": "NAME", "value": "Ivan Fedorov" }, { "context": " \"default\",\n :creator {:email \"hello@example.io\", :self true},\n :extendedProperties {:shared {:", "end": 13242, "score": 0.9998810887336731, "start": 13226, "tag": "EMAIL", "value": "hello@example.io" }, { "context": " :conferenceSolution {:key {:type \"hangoutsMeet\"},\n :", "end": 13710, "score": 0.7694306969642639, "start": 13698, "tag": "KEY", "value": "hangoutsMeet" }, { "context": "021-01-11T09:20:30.000Z\",\n :summary \"LaMarr and Ivan zoom\",\n :attendees [{:email \"", "end": 14380, "score": 0.9823164939880371, "start": 14374, "tag": "NAME", "value": "LaMarr" }, { "context": "09:20:30.000Z\",\n :summary \"LaMarr and Ivan zoom\",\n :attendees [{:email \"example@g", "end": 14389, "score": 0.7686554193496704, "start": 14385, "tag": "NAME", "value": "Ivan" }, { "context": " and Ivan zoom\",\n :attendees [{:email \"example@gmail.com\", :responseStatus \"needsAction\"}\n ", "end": 14447, "score": 0.9999265670776367, "start": 14430, "tag": "EMAIL", "value": "example@gmail.com" }, { "context": "s \"needsAction\"}\n {:email \"hello@example.io\", :organizer true, :self true, :responseStatus \"a", "end": 14530, "score": 0.9999257326126099, "start": 14514, "tag": "EMAIL", "value": "hello@example.io" }, { "context": "ion \"https://us04web.zoom.us/j/smth?pwd=smth\",\n :hangoutLink \"https://meet.google.com", "end": 14928, "score": 0.8580048084259033, "start": 14924, "tag": "PASSWORD", "value": "smth" }, { "context": "e.com/not-an-id\",\n :organizer {:email \"hello@example.io\", :self true}})\n\n\n", "end": 15039, "score": 0.9999257922172546, "start": 15023, "tag": "EMAIL", "value": "hello@example.io" } ]
src/gcal_clj/specs_event.clj
spacegangster/gcal-clj
6
(ns gcal-clj.specs-event "Google's doc https://developers.google.com/calendar/v3/reference/events#resource" (:require [clojure.spec.alpha :as s] [common.specs] [common.specs.http] [gcal-clj.specs-macros :as sm])) (s/def :s.prop-type.goog/time-coord (s/keys :req-un [(or :s.prop.goog/dateTime :s.prop.goog/date)] :opt-un [:s.prop.goog/timeZone])) (s/def :s.prop.goog/dateTime string?) (s/def :s.prop.goog/date string?) (s/def :s.prop.goog/timeZone string?) (s/def :s.prop/rfc-3339-timestamp string?) (s/def :s.http/etag string?) (s/def :s.prop.gcal/id string?) (s/def :s.prop-type/uri string?) (s/def :s.prop-type/not-empty-string string?) (s/def :s.prop.gcal/summary string?) ; can be empty or non-present (s/def :s.prop.gcal/created :s.prop/rfc-3339-timestamp) (s/def :s.prop.gcal/updated :s.prop/rfc-3339-timestamp) (s/def :s.prop-type.gcal/prop-map (s/map-of (s/or :s string? :k keyword?) string?)) (s/valid? :s.prop-type.gcal/prop-map {:ff "33", "fa" "fa"}) (sm/mapdef1 :s.gcal.ent/reminder {:s.prop.gcal.reminder/method string?, :s.prop.gcal.reminder/minutes nat-int?}) (s/def :s.prop.gcal/responseStatus #{"needsAction" ; - The attendee has not responded to the invitation. "declined" ; - The attendee has declined the invitation. "tentative" ; - The attendee has tentatively accepted the invitation. "accepted"}) ; - The attendee has accepted the invitation. (s/def :s.prop.gcal/transparency ; Whether the event blocks time on the calendar. Optional. Possible values are: #{"opaque" ; - Default value. The event does block time on the calendar. This is equivalent to setting Show me as to Busy in the Calendar UI. "transparent"}) ; - The event does not block time on the calendar. This is equivalent to setting Show me as to Available in the Calendar UI. (s/def :s.prop.gcal/visibility ; Visibility of the event. Optional. Possible values are: #{"default" ; Uses the default visibility for events on the calendar. This is the default value. "public" ; The event is public and event details are visible to all readers of the calendar. "private" ; The event is private and only event attendees may view event details. "confidential"}) ; The event is private. This value is provided for compatibility reasons. (s/def :s.prop.gcal/eventType ; Specific type of the event. Read-only. Possible values are: #{"default" ; A regular event or not further specified. "outOfOffice"}) ; An out-of-office event. (s/def :s.prop.gcal/status #{"confirmed" ; The event is confirmed. This is the default status. "tentative" ; The event is tentatively confirmed. "cancelled"}) ; The event is cancelled (deleted). ; The list method returns cancelled events only on incremental sync ; (when syncToken or updatedMin are specified) or if the showDeleted flag ; is set to true. The get method always returns them. (s/def :s.prop.gcal.evt-cancelled/status #{"cancelled"}) ;;;;; Person ;;;;; (sm/def-map-props {:s.prop.gcal.person/id string? ; google plus id :s.prop.gcal/displayName string? :s.prop.gcal.person/organizer boolean? :s.prop.gcal/self boolean? ; is organiser? :s.prop.gcal/resource boolean? :s.prop.gcal/optional boolean? :s.prop.gcal/comment string? :s.prop.gcal/additionalGuests pos-int?}) (s/def :s.gcal.ent/person ; used for creator, organizer, and attendee fields (s/keys :opt-un [:s.prop.gcal/id :s.prop/email :s.prop.gcal/displayName :s.prop.gcal/self])) (s/def :s.gcal.ent/attendee (s/merge :s.gcal.ent/person (s/keys :opt-un [:s.prop.gcal.person/organizer :s.prop.gcal/resource :s.prop.gcal/optional :s.prop.gcal/responseStatus :s.prop.gcal/comment :s.prop.gcal/additionalGuests]))) (sm/mapdef-opt :s.gcal.prop/ext-props {:s.prop.gcal/private :s.prop-type.gcal/prop-map :s.prop.gcal/shared :s.prop-type.gcal/prop-map}) (sm/mapdef1 :s.gcal.prop/create-request-conf-sol-key {:s.prop.gcal/type string?}) (sm/mapdef1 :s.prop.gcal/create-request-status {:s.prop.gcal/statusCode string?}) (sm/mapdef1 :s.gcal.ent/create-request {:s.prop.gcal/requestId string? :s.prop.gcal/conferenceSolutionKey :s.gcal.prop/create-request-conf-sol-key :s.prop.gcal.create-request/status :s.prop.gcal/create-request-status}) (sm/def-map-props {:s.prop.gcal.evt.entry-point/uri :s.prop-type/uri :s.prop.gcal.evt.entry-point/label :s.prop-type/not-empty-string :s.prop.gcal.evt.entry-point/pin string?, :s.prop.gcal.evt.entry-point/accessCode string?, :s.prop.gcal.evt.entry-point/meetingCode string?, :s.prop.gcal.evt.entry-point/passcode string?, :s.prop.gcal.evt.entry-point/password string?}) (s/def :s.prop.gcal.evt.entry-point/entryPointType #{"video" ; joining a conference over HTTP. A conference can have zero or one video entry point. "phone" ; joining a conference by dialing a phone number. A conference can have zero or more phone entry points. "sip" ; joining a conference over SIP. A conference can have zero or one sip entry point. "more"}) ; further conference joining instructions, for example additional phone numbers. A conference can have zero or one more entry point. A conference with only a more entry point is not a valid conference. (s/def :s.gcal.prop/entry-point (s/keys :req-un [:s.prop.gcal.evt.entry-point/entryPointType] :opt-un [:s.prop.gcal.evt.entry-point/uri :s.prop.gcal.evt.entry-point/label :s.prop.gcal.evt.entry-point/pin :s.prop.gcal.evt.entry-point/accessCode :s.prop.gcal.evt.entry-point/meetingCode :s.prop.gcal.evt.entry-point/passcode :s.prop.gcal.evt.entry-point/password])) (sm/mapdef1 :s.prop.gcal.evt/conference-solution {:s.prop.gcal/key :s.prop.gcal/conferenceSolutionKey :s.prop.gcal/name string? :s.prop.gcal/iconUri string?}) (sm/def-map-props {:s.prop.gcal.conf-data/createRequest :s.gcal.ent/create-request :s.prop.gcal.conf-data/entryPoints (s/coll-of :s.gcal.prop/entry-point) :s.prop.gcal.conf-data/conferenceSolution :s.prop.gcal.evt/conference-solution :s.prop.gcal.conf-data/conferenceId string? :s.prop.gcal.conf-data/signature string? :s.prop.gcal.conf-data/notes string?}) (s/def :s.gcal.ent/conf-data (s/keys :req-un [(or :s.prop.gcal.conf-data/createRequest :s.prop.gcal.conf-data/entryPoints)] :opt-un [:s.prop.gcal.conf-data/conferenceSolution :s.prop.gcal.conf-data/conferenceId :s.prop.gcal.conf-data/signature :s.prop.gcal.conf-data/notes])) ; A gadget that extends this event. ; Gadgets are deprecated; this structure is instead only used for returning birthday calendar metadata. (sm/mapdef2 :s.prop.gcal.evt/gadget {} {:s.prop.gcal/type string? :s.prop.gcal/title string? :s.prop.gcal/link string? :s.prop.gcal/iconLink string? :s.prop.gcal/width nat-int? :s.prop.gcal/height nat-int? :s.prop.gcal/display string? :s.prop.gcal/preferences (s/map-of string? string?)}) (sm/mapdef2 :s.prop.gcal.evt/reminders {:s.prop.gcal/useDefault boolean?} {:s.prop.gcal/overrides (s/coll-of :s.gcal.ent/reminder)}) (sm/mapdef1 :s.prop.gcal.evt/source ; Source from which the event was created. For example, a web page, an email message ; or any document identifiable by an URL with HTTP or HTTPS scheme. ; Can only be seen or modified by the creator of the event. {:s.prop.gcal/url string? :s.prop.gcal/title string?}) (sm/mapdef1 :s.ent.gcal/attachment {:s.prop.gcal/fileUrl string? :s.prop.gcal/title string? :s.prop.gcal/mimeType string? :s.prop.gcal/iconLink string? :s.prop.gcal/fileId string?}) (sm/def-map-props {:s.gcal.prop.event/kind #{"calendar#event"} :s.prop.gcal/htmlLink string? :s.prop.gcal/description string? :s.prop.gcal/location string? :s.prop.gcal/colorId string? :s.prop.gcal/creator :s.gcal.ent/person :s.prop.gcal/organizer :s.gcal.ent/person :s.prop.gcal/start :s.prop-type.goog/time-coord :s.prop.gcal/end :s.prop-type.goog/time-coord :s.prop.gcal/endTimeUnspecified boolean? :s.prop.gcal/recurrence :s.prop/recurrence :s.prop.gcal/recurringEventId :s.prop/id_goog :s.prop.gcal/originalStartTime :s.prop-type.goog/time-coord :s.prop.gcal/iCalUID string? :s.prop.gcal/sequence nat-int? :s.prop.gcal/attendees (s/coll-of :s.gcal.ent/attendee) :s.prop.gcal/attendeesOmitted boolean? :s.prop.gcal/extendedProperties :s.gcal.prop/ext-props :s.prop.gcal/hangoutLink :s.prop-type/url ; read-only :s.prop.gcal/conferenceData :s.gcal.ent/conf-data :s.prop.gcal/gadget :s.prop.gcal.evt/gadget :s.prop.gcal/anyoneCanAddSelf boolean? :s.prop.gcal/guestsCanInviteOthers boolean? :s.prop.gcal/guestsCanModify boolean? :s.prop.gcal/guestsCanSeeOtherGuests boolean? :s.prop.gcal/privateCopy boolean? ; r-o :s.prop.gcal/locked boolean? ; r-o :s.prop.gcal/reminders :s.prop.gcal.evt/reminders :s.prop.gcal/source :s.prop.gcal.evt/source ; only for the creator :s.prop.gcal/attachments (s/coll-of :s.ent.gcal/attachment)}) (s/def ::evt-opt-keys (s/keys :opt-un [:s.prop.gcal/updated :s.prop.gcal/summary ; yep, can be untitled :s.prop.gcal/description :s.prop.gcal/location :s.prop.gcal/colorId :s.prop.gcal/creator :s.prop.gcal/organizer :s.prop.gcal/start :s.prop.gcal/end :s.prop.gcal/endTimeUnspecified :s.prop.gcal/transparency :s.prop.gcal/visibility :s.prop.gcal/iCalUID :s.prop.gcal/sequence :s.prop.gcal/attendees :s.prop.gcal/attendeesOmitted :s.prop.gcal/extendedProperties :s.prop.gcal/hangoutLink :s.prop.gcal/conferenceData :s.prop.gcal/gadget :s.prop.gcal/anyoneCanAddSelf :s.prop.gcal/guestsCanInviteOthers :s.prop.gcal/guestsCanModify :s.prop.gcal/guestsCanSeeOtherGuests :s.prop.gcal/privateCopy :s.prop.gcal/locked :s.prop.gcal/reminders :s.prop.gcal/source :s.prop.gcal/attachments :s.prop.gcal/eventType])) (s/def :s.gcal.ent/event--regular (s/merge ::evt-opt-keys (s/keys :req-un [:s.prop.gcal/id :s.gcal.prop.event/kind :s.prop.gcal/status :s.http/etag :s.prop.gcal/htmlLink :s.prop.gcal/created]))) (s/def :s.gcal.ent/event--regular-cancelled (s/keys :req-un [:s.prop.gcal/id :s.prop.gcal.evt-cancelled/status])) (s/def :s.gcal.ent/event--rec-base (s/merge ::evt-opt-keys (s/keys :req-un [:s.prop.gcal/id :s.gcal.prop.event/kind :s.prop.gcal/status :s.http/etag :s.prop/recurrence :s.prop.gcal/htmlLink :s.prop.gcal/created]))) (s/def :s.gcal.ent/event--rec-exception (s/merge ::evt-opt-keys (s/keys :req-un [:s.prop.gcal/id :s.gcal.prop.event/kind :s.prop.gcal/status :s.http/etag :s.prop.gcal/recurringEventId :s.prop.gcal/originalStartTime]))) (s/def :s.gcal.ent/event--rec-exception-cancelled ; Cancelled exceptions of an uncancelled recurring event indicate that ; this instance should no longer be presented to the user. Clients should ; store these events for the lifetime of the parent recurring event. ; Cancelled exceptions are only guaranteed to have values for the id, ; recurringEventId and originalStartTime fields populated. The other fields might be empty. (s/keys :req-un [:s.prop.gcal/id :s.prop.gcal.evt-cancelled/status :s.prop.gcal/recurringEventId :s.prop.gcal/originalStartTime])) (s/def :s.gcal.ent/event (s/or ::regular :s.gcal.ent/event--regular ::regular-cancelled :s.gcal.ent/event--regular-cancelled ::rec-base :s.gcal.ent/event--rec-base ::rec-exception :s.gcal.ent/event--rec-exception ::rec-exception-cancelled :s.gcal.ent/event--rec-exception-cancelled)) (s/assert :s.gcal.ent/event--regular {:iCalUID "goog-event-id@google.com", :description "Ivan Fedorov is inviting you to a scheduled Zoom meeting.", :eventType "default", :creator {:email "hello@example.io", :self true}, :extendedProperties {:shared {:zmMeetingNum "75615174335"}}, :updated "2021-01-16T16:56:04.847Z", :conferenceData {:entryPoints [{:entryPointType "video", :uri "https://meet.google.com/not-an-id", :label "meet.google.com/not-an-id"}], :conferenceSolution {:key {:type "hangoutsMeet"}, :name "Google Meet", :iconUri "https://fonts.gstatic.com/s/i/productlogos/meet_2020q4/v6/web-512dp/logo_meet_2020q4_color_2x_web_512dp.png"}, :conferenceId "not-an-id", :signature "AL9oL6XRix+Rb5sHtGh5M/DQk3e1"}, :htmlLink "https://www.google.com/calendar/event?eid=not-an-id", :start {:dateTime "2021-01-12T09:00:00+03:00", :timeZone "Europe/Moscow"}, :etag "\"3221632329694000\"", :created "2021-01-11T09:20:30.000Z", :summary "LaMarr and Ivan zoom", :attendees [{:email "example@gmail.com", :responseStatus "needsAction"} {:email "hello@example.io", :organizer true, :self true, :responseStatus "accepted"}], :status "confirmed", :id "not-an-id", :kind "calendar#event", :sequence 1, :reminders {:useDefault true}, :end {:dateTime "2021-01-12T09:40:00+03:00", :timeZone "Europe/Moscow"}, :location "https://us04web.zoom.us/j/smth?pwd=smth", :hangoutLink "https://meet.google.com/not-an-id", :organizer {:email "hello@example.io", :self true}})
109516
(ns gcal-clj.specs-event "Google's doc https://developers.google.com/calendar/v3/reference/events#resource" (:require [clojure.spec.alpha :as s] [common.specs] [common.specs.http] [gcal-clj.specs-macros :as sm])) (s/def :s.prop-type.goog/time-coord (s/keys :req-un [(or :s.prop.goog/dateTime :s.prop.goog/date)] :opt-un [:s.prop.goog/timeZone])) (s/def :s.prop.goog/dateTime string?) (s/def :s.prop.goog/date string?) (s/def :s.prop.goog/timeZone string?) (s/def :s.prop/rfc-3339-timestamp string?) (s/def :s.http/etag string?) (s/def :s.prop.gcal/id string?) (s/def :s.prop-type/uri string?) (s/def :s.prop-type/not-empty-string string?) (s/def :s.prop.gcal/summary string?) ; can be empty or non-present (s/def :s.prop.gcal/created :s.prop/rfc-3339-timestamp) (s/def :s.prop.gcal/updated :s.prop/rfc-3339-timestamp) (s/def :s.prop-type.gcal/prop-map (s/map-of (s/or :s string? :k keyword?) string?)) (s/valid? :s.prop-type.gcal/prop-map {:ff "33", "fa" "fa"}) (sm/mapdef1 :s.gcal.ent/reminder {:s.prop.gcal.reminder/method string?, :s.prop.gcal.reminder/minutes nat-int?}) (s/def :s.prop.gcal/responseStatus #{"needsAction" ; - The attendee has not responded to the invitation. "declined" ; - The attendee has declined the invitation. "tentative" ; - The attendee has tentatively accepted the invitation. "accepted"}) ; - The attendee has accepted the invitation. (s/def :s.prop.gcal/transparency ; Whether the event blocks time on the calendar. Optional. Possible values are: #{"opaque" ; - Default value. The event does block time on the calendar. This is equivalent to setting Show me as to Busy in the Calendar UI. "transparent"}) ; - The event does not block time on the calendar. This is equivalent to setting Show me as to Available in the Calendar UI. (s/def :s.prop.gcal/visibility ; Visibility of the event. Optional. Possible values are: #{"default" ; Uses the default visibility for events on the calendar. This is the default value. "public" ; The event is public and event details are visible to all readers of the calendar. "private" ; The event is private and only event attendees may view event details. "confidential"}) ; The event is private. This value is provided for compatibility reasons. (s/def :s.prop.gcal/eventType ; Specific type of the event. Read-only. Possible values are: #{"default" ; A regular event or not further specified. "outOfOffice"}) ; An out-of-office event. (s/def :s.prop.gcal/status #{"confirmed" ; The event is confirmed. This is the default status. "tentative" ; The event is tentatively confirmed. "cancelled"}) ; The event is cancelled (deleted). ; The list method returns cancelled events only on incremental sync ; (when syncToken or updatedMin are specified) or if the showDeleted flag ; is set to true. The get method always returns them. (s/def :s.prop.gcal.evt-cancelled/status #{"cancelled"}) ;;;;; Person ;;;;; (sm/def-map-props {:s.prop.gcal.person/id string? ; google plus id :s.prop.gcal/displayName string? :s.prop.gcal.person/organizer boolean? :s.prop.gcal/self boolean? ; is organiser? :s.prop.gcal/resource boolean? :s.prop.gcal/optional boolean? :s.prop.gcal/comment string? :s.prop.gcal/additionalGuests pos-int?}) (s/def :s.gcal.ent/person ; used for creator, organizer, and attendee fields (s/keys :opt-un [:s.prop.gcal/id :s.prop/email :s.prop.gcal/displayName :s.prop.gcal/self])) (s/def :s.gcal.ent/attendee (s/merge :s.gcal.ent/person (s/keys :opt-un [:s.prop.gcal.person/organizer :s.prop.gcal/resource :s.prop.gcal/optional :s.prop.gcal/responseStatus :s.prop.gcal/comment :s.prop.gcal/additionalGuests]))) (sm/mapdef-opt :s.gcal.prop/ext-props {:s.prop.gcal/private :s.prop-type.gcal/prop-map :s.prop.gcal/shared :s.prop-type.gcal/prop-map}) (sm/mapdef1 :s.gcal.prop/create-request-conf-sol-key {:s.prop.gcal/type string?}) (sm/mapdef1 :s.prop.gcal/create-request-status {:s.prop.gcal/statusCode string?}) (sm/mapdef1 :s.gcal.ent/create-request {:s.prop.gcal/requestId string? :s.prop.gcal/conferenceSolutionKey :s.gcal.prop/create-request-conf-sol-key :s.prop.gcal.create-request/status :s.prop.gcal/create-request-status}) (sm/def-map-props {:s.prop.gcal.evt.entry-point/uri :s.prop-type/uri :s.prop.gcal.evt.entry-point/label :s.prop-type/not-empty-string :s.prop.gcal.evt.entry-point/pin string?, :s.prop.gcal.evt.entry-point/accessCode string?, :s.prop.gcal.evt.entry-point/meetingCode string?, :s.prop.gcal.evt.entry-point/passcode string?, :s.prop.gcal.evt.entry-point/password string?}) (s/def :s.prop.gcal.evt.entry-point/entryPointType #{"video" ; joining a conference over HTTP. A conference can have zero or one video entry point. "phone" ; joining a conference by dialing a phone number. A conference can have zero or more phone entry points. "sip" ; joining a conference over SIP. A conference can have zero or one sip entry point. "more"}) ; further conference joining instructions, for example additional phone numbers. A conference can have zero or one more entry point. A conference with only a more entry point is not a valid conference. (s/def :s.gcal.prop/entry-point (s/keys :req-un [:s.prop.gcal.evt.entry-point/entryPointType] :opt-un [:s.prop.gcal.evt.entry-point/uri :s.prop.gcal.evt.entry-point/label :s.prop.gcal.evt.entry-point/pin :s.prop.gcal.evt.entry-point/accessCode :s.prop.gcal.evt.entry-point/meetingCode :s.prop.gcal.evt.entry-point/passcode :s.prop.gcal.evt.entry-point/password])) (sm/mapdef1 :s.prop.gcal.evt/conference-solution {:s.prop.gcal/key :s.prop.gcal/conferenceSolutionKey :s.prop.gcal/name string? :s.prop.gcal/iconUri string?}) (sm/def-map-props {:s.prop.gcal.conf-data/createRequest :s.gcal.ent/create-request :s.prop.gcal.conf-data/entryPoints (s/coll-of :s.gcal.prop/entry-point) :s.prop.gcal.conf-data/conferenceSolution :s.prop.gcal.evt/conference-solution :s.prop.gcal.conf-data/conferenceId string? :s.prop.gcal.conf-data/signature string? :s.prop.gcal.conf-data/notes string?}) (s/def :s.gcal.ent/conf-data (s/keys :req-un [(or :s.prop.gcal.conf-data/createRequest :s.prop.gcal.conf-data/entryPoints)] :opt-un [:s.prop.gcal.conf-data/conferenceSolution :s.prop.gcal.conf-data/conferenceId :s.prop.gcal.conf-data/signature :s.prop.gcal.conf-data/notes])) ; A gadget that extends this event. ; Gadgets are deprecated; this structure is instead only used for returning birthday calendar metadata. (sm/mapdef2 :s.prop.gcal.evt/gadget {} {:s.prop.gcal/type string? :s.prop.gcal/title string? :s.prop.gcal/link string? :s.prop.gcal/iconLink string? :s.prop.gcal/width nat-int? :s.prop.gcal/height nat-int? :s.prop.gcal/display string? :s.prop.gcal/preferences (s/map-of string? string?)}) (sm/mapdef2 :s.prop.gcal.evt/reminders {:s.prop.gcal/useDefault boolean?} {:s.prop.gcal/overrides (s/coll-of :s.gcal.ent/reminder)}) (sm/mapdef1 :s.prop.gcal.evt/source ; Source from which the event was created. For example, a web page, an email message ; or any document identifiable by an URL with HTTP or HTTPS scheme. ; Can only be seen or modified by the creator of the event. {:s.prop.gcal/url string? :s.prop.gcal/title string?}) (sm/mapdef1 :s.ent.gcal/attachment {:s.prop.gcal/fileUrl string? :s.prop.gcal/title string? :s.prop.gcal/mimeType string? :s.prop.gcal/iconLink string? :s.prop.gcal/fileId string?}) (sm/def-map-props {:s.gcal.prop.event/kind #{"calendar#event"} :s.prop.gcal/htmlLink string? :s.prop.gcal/description string? :s.prop.gcal/location string? :s.prop.gcal/colorId string? :s.prop.gcal/creator :s.gcal.ent/person :s.prop.gcal/organizer :s.gcal.ent/person :s.prop.gcal/start :s.prop-type.goog/time-coord :s.prop.gcal/end :s.prop-type.goog/time-coord :s.prop.gcal/endTimeUnspecified boolean? :s.prop.gcal/recurrence :s.prop/recurrence :s.prop.gcal/recurringEventId :s.prop/id_goog :s.prop.gcal/originalStartTime :s.prop-type.goog/time-coord :s.prop.gcal/iCalUID string? :s.prop.gcal/sequence nat-int? :s.prop.gcal/attendees (s/coll-of :s.gcal.ent/attendee) :s.prop.gcal/attendeesOmitted boolean? :s.prop.gcal/extendedProperties :s.gcal.prop/ext-props :s.prop.gcal/hangoutLink :s.prop-type/url ; read-only :s.prop.gcal/conferenceData :s.gcal.ent/conf-data :s.prop.gcal/gadget :s.prop.gcal.evt/gadget :s.prop.gcal/anyoneCanAddSelf boolean? :s.prop.gcal/guestsCanInviteOthers boolean? :s.prop.gcal/guestsCanModify boolean? :s.prop.gcal/guestsCanSeeOtherGuests boolean? :s.prop.gcal/privateCopy boolean? ; r-o :s.prop.gcal/locked boolean? ; r-o :s.prop.gcal/reminders :s.prop.gcal.evt/reminders :s.prop.gcal/source :s.prop.gcal.evt/source ; only for the creator :s.prop.gcal/attachments (s/coll-of :s.ent.gcal/attachment)}) (s/def ::evt-opt-keys (s/keys :opt-un [:s.prop.gcal/updated :s.prop.gcal/summary ; yep, can be untitled :s.prop.gcal/description :s.prop.gcal/location :s.prop.gcal/colorId :s.prop.gcal/creator :s.prop.gcal/organizer :s.prop.gcal/start :s.prop.gcal/end :s.prop.gcal/endTimeUnspecified :s.prop.gcal/transparency :s.prop.gcal/visibility :s.prop.gcal/iCalUID :s.prop.gcal/sequence :s.prop.gcal/attendees :s.prop.gcal/attendeesOmitted :s.prop.gcal/extendedProperties :s.prop.gcal/hangoutLink :s.prop.gcal/conferenceData :s.prop.gcal/gadget :s.prop.gcal/anyoneCanAddSelf :s.prop.gcal/guestsCanInviteOthers :s.prop.gcal/guestsCanModify :s.prop.gcal/guestsCanSeeOtherGuests :s.prop.gcal/privateCopy :s.prop.gcal/locked :s.prop.gcal/reminders :s.prop.gcal/source :s.prop.gcal/attachments :s.prop.gcal/eventType])) (s/def :s.gcal.ent/event--regular (s/merge ::evt-opt-keys (s/keys :req-un [:s.prop.gcal/id :s.gcal.prop.event/kind :s.prop.gcal/status :s.http/etag :s.prop.gcal/htmlLink :s.prop.gcal/created]))) (s/def :s.gcal.ent/event--regular-cancelled (s/keys :req-un [:s.prop.gcal/id :s.prop.gcal.evt-cancelled/status])) (s/def :s.gcal.ent/event--rec-base (s/merge ::evt-opt-keys (s/keys :req-un [:s.prop.gcal/id :s.gcal.prop.event/kind :s.prop.gcal/status :s.http/etag :s.prop/recurrence :s.prop.gcal/htmlLink :s.prop.gcal/created]))) (s/def :s.gcal.ent/event--rec-exception (s/merge ::evt-opt-keys (s/keys :req-un [:s.prop.gcal/id :s.gcal.prop.event/kind :s.prop.gcal/status :s.http/etag :s.prop.gcal/recurringEventId :s.prop.gcal/originalStartTime]))) (s/def :s.gcal.ent/event--rec-exception-cancelled ; Cancelled exceptions of an uncancelled recurring event indicate that ; this instance should no longer be presented to the user. Clients should ; store these events for the lifetime of the parent recurring event. ; Cancelled exceptions are only guaranteed to have values for the id, ; recurringEventId and originalStartTime fields populated. The other fields might be empty. (s/keys :req-un [:s.prop.gcal/id :s.prop.gcal.evt-cancelled/status :s.prop.gcal/recurringEventId :s.prop.gcal/originalStartTime])) (s/def :s.gcal.ent/event (s/or ::regular :s.gcal.ent/event--regular ::regular-cancelled :s.gcal.ent/event--regular-cancelled ::rec-base :s.gcal.ent/event--rec-base ::rec-exception :s.gcal.ent/event--rec-exception ::rec-exception-cancelled :s.gcal.ent/event--rec-exception-cancelled)) (s/assert :s.gcal.ent/event--regular {:iCalUID "<EMAIL>", :description "<NAME> is inviting you to a scheduled Zoom meeting.", :eventType "default", :creator {:email "<EMAIL>", :self true}, :extendedProperties {:shared {:zmMeetingNum "75615174335"}}, :updated "2021-01-16T16:56:04.847Z", :conferenceData {:entryPoints [{:entryPointType "video", :uri "https://meet.google.com/not-an-id", :label "meet.google.com/not-an-id"}], :conferenceSolution {:key {:type "<KEY>"}, :name "Google Meet", :iconUri "https://fonts.gstatic.com/s/i/productlogos/meet_2020q4/v6/web-512dp/logo_meet_2020q4_color_2x_web_512dp.png"}, :conferenceId "not-an-id", :signature "AL9oL6XRix+Rb5sHtGh5M/DQk3e1"}, :htmlLink "https://www.google.com/calendar/event?eid=not-an-id", :start {:dateTime "2021-01-12T09:00:00+03:00", :timeZone "Europe/Moscow"}, :etag "\"3221632329694000\"", :created "2021-01-11T09:20:30.000Z", :summary "<NAME> and <NAME> zoom", :attendees [{:email "<EMAIL>", :responseStatus "needsAction"} {:email "<EMAIL>", :organizer true, :self true, :responseStatus "accepted"}], :status "confirmed", :id "not-an-id", :kind "calendar#event", :sequence 1, :reminders {:useDefault true}, :end {:dateTime "2021-01-12T09:40:00+03:00", :timeZone "Europe/Moscow"}, :location "https://us04web.zoom.us/j/smth?pwd=<PASSWORD>", :hangoutLink "https://meet.google.com/not-an-id", :organizer {:email "<EMAIL>", :self true}})
true
(ns gcal-clj.specs-event "Google's doc https://developers.google.com/calendar/v3/reference/events#resource" (:require [clojure.spec.alpha :as s] [common.specs] [common.specs.http] [gcal-clj.specs-macros :as sm])) (s/def :s.prop-type.goog/time-coord (s/keys :req-un [(or :s.prop.goog/dateTime :s.prop.goog/date)] :opt-un [:s.prop.goog/timeZone])) (s/def :s.prop.goog/dateTime string?) (s/def :s.prop.goog/date string?) (s/def :s.prop.goog/timeZone string?) (s/def :s.prop/rfc-3339-timestamp string?) (s/def :s.http/etag string?) (s/def :s.prop.gcal/id string?) (s/def :s.prop-type/uri string?) (s/def :s.prop-type/not-empty-string string?) (s/def :s.prop.gcal/summary string?) ; can be empty or non-present (s/def :s.prop.gcal/created :s.prop/rfc-3339-timestamp) (s/def :s.prop.gcal/updated :s.prop/rfc-3339-timestamp) (s/def :s.prop-type.gcal/prop-map (s/map-of (s/or :s string? :k keyword?) string?)) (s/valid? :s.prop-type.gcal/prop-map {:ff "33", "fa" "fa"}) (sm/mapdef1 :s.gcal.ent/reminder {:s.prop.gcal.reminder/method string?, :s.prop.gcal.reminder/minutes nat-int?}) (s/def :s.prop.gcal/responseStatus #{"needsAction" ; - The attendee has not responded to the invitation. "declined" ; - The attendee has declined the invitation. "tentative" ; - The attendee has tentatively accepted the invitation. "accepted"}) ; - The attendee has accepted the invitation. (s/def :s.prop.gcal/transparency ; Whether the event blocks time on the calendar. Optional. Possible values are: #{"opaque" ; - Default value. The event does block time on the calendar. This is equivalent to setting Show me as to Busy in the Calendar UI. "transparent"}) ; - The event does not block time on the calendar. This is equivalent to setting Show me as to Available in the Calendar UI. (s/def :s.prop.gcal/visibility ; Visibility of the event. Optional. Possible values are: #{"default" ; Uses the default visibility for events on the calendar. This is the default value. "public" ; The event is public and event details are visible to all readers of the calendar. "private" ; The event is private and only event attendees may view event details. "confidential"}) ; The event is private. This value is provided for compatibility reasons. (s/def :s.prop.gcal/eventType ; Specific type of the event. Read-only. Possible values are: #{"default" ; A regular event or not further specified. "outOfOffice"}) ; An out-of-office event. (s/def :s.prop.gcal/status #{"confirmed" ; The event is confirmed. This is the default status. "tentative" ; The event is tentatively confirmed. "cancelled"}) ; The event is cancelled (deleted). ; The list method returns cancelled events only on incremental sync ; (when syncToken or updatedMin are specified) or if the showDeleted flag ; is set to true. The get method always returns them. (s/def :s.prop.gcal.evt-cancelled/status #{"cancelled"}) ;;;;; Person ;;;;; (sm/def-map-props {:s.prop.gcal.person/id string? ; google plus id :s.prop.gcal/displayName string? :s.prop.gcal.person/organizer boolean? :s.prop.gcal/self boolean? ; is organiser? :s.prop.gcal/resource boolean? :s.prop.gcal/optional boolean? :s.prop.gcal/comment string? :s.prop.gcal/additionalGuests pos-int?}) (s/def :s.gcal.ent/person ; used for creator, organizer, and attendee fields (s/keys :opt-un [:s.prop.gcal/id :s.prop/email :s.prop.gcal/displayName :s.prop.gcal/self])) (s/def :s.gcal.ent/attendee (s/merge :s.gcal.ent/person (s/keys :opt-un [:s.prop.gcal.person/organizer :s.prop.gcal/resource :s.prop.gcal/optional :s.prop.gcal/responseStatus :s.prop.gcal/comment :s.prop.gcal/additionalGuests]))) (sm/mapdef-opt :s.gcal.prop/ext-props {:s.prop.gcal/private :s.prop-type.gcal/prop-map :s.prop.gcal/shared :s.prop-type.gcal/prop-map}) (sm/mapdef1 :s.gcal.prop/create-request-conf-sol-key {:s.prop.gcal/type string?}) (sm/mapdef1 :s.prop.gcal/create-request-status {:s.prop.gcal/statusCode string?}) (sm/mapdef1 :s.gcal.ent/create-request {:s.prop.gcal/requestId string? :s.prop.gcal/conferenceSolutionKey :s.gcal.prop/create-request-conf-sol-key :s.prop.gcal.create-request/status :s.prop.gcal/create-request-status}) (sm/def-map-props {:s.prop.gcal.evt.entry-point/uri :s.prop-type/uri :s.prop.gcal.evt.entry-point/label :s.prop-type/not-empty-string :s.prop.gcal.evt.entry-point/pin string?, :s.prop.gcal.evt.entry-point/accessCode string?, :s.prop.gcal.evt.entry-point/meetingCode string?, :s.prop.gcal.evt.entry-point/passcode string?, :s.prop.gcal.evt.entry-point/password string?}) (s/def :s.prop.gcal.evt.entry-point/entryPointType #{"video" ; joining a conference over HTTP. A conference can have zero or one video entry point. "phone" ; joining a conference by dialing a phone number. A conference can have zero or more phone entry points. "sip" ; joining a conference over SIP. A conference can have zero or one sip entry point. "more"}) ; further conference joining instructions, for example additional phone numbers. A conference can have zero or one more entry point. A conference with only a more entry point is not a valid conference. (s/def :s.gcal.prop/entry-point (s/keys :req-un [:s.prop.gcal.evt.entry-point/entryPointType] :opt-un [:s.prop.gcal.evt.entry-point/uri :s.prop.gcal.evt.entry-point/label :s.prop.gcal.evt.entry-point/pin :s.prop.gcal.evt.entry-point/accessCode :s.prop.gcal.evt.entry-point/meetingCode :s.prop.gcal.evt.entry-point/passcode :s.prop.gcal.evt.entry-point/password])) (sm/mapdef1 :s.prop.gcal.evt/conference-solution {:s.prop.gcal/key :s.prop.gcal/conferenceSolutionKey :s.prop.gcal/name string? :s.prop.gcal/iconUri string?}) (sm/def-map-props {:s.prop.gcal.conf-data/createRequest :s.gcal.ent/create-request :s.prop.gcal.conf-data/entryPoints (s/coll-of :s.gcal.prop/entry-point) :s.prop.gcal.conf-data/conferenceSolution :s.prop.gcal.evt/conference-solution :s.prop.gcal.conf-data/conferenceId string? :s.prop.gcal.conf-data/signature string? :s.prop.gcal.conf-data/notes string?}) (s/def :s.gcal.ent/conf-data (s/keys :req-un [(or :s.prop.gcal.conf-data/createRequest :s.prop.gcal.conf-data/entryPoints)] :opt-un [:s.prop.gcal.conf-data/conferenceSolution :s.prop.gcal.conf-data/conferenceId :s.prop.gcal.conf-data/signature :s.prop.gcal.conf-data/notes])) ; A gadget that extends this event. ; Gadgets are deprecated; this structure is instead only used for returning birthday calendar metadata. (sm/mapdef2 :s.prop.gcal.evt/gadget {} {:s.prop.gcal/type string? :s.prop.gcal/title string? :s.prop.gcal/link string? :s.prop.gcal/iconLink string? :s.prop.gcal/width nat-int? :s.prop.gcal/height nat-int? :s.prop.gcal/display string? :s.prop.gcal/preferences (s/map-of string? string?)}) (sm/mapdef2 :s.prop.gcal.evt/reminders {:s.prop.gcal/useDefault boolean?} {:s.prop.gcal/overrides (s/coll-of :s.gcal.ent/reminder)}) (sm/mapdef1 :s.prop.gcal.evt/source ; Source from which the event was created. For example, a web page, an email message ; or any document identifiable by an URL with HTTP or HTTPS scheme. ; Can only be seen or modified by the creator of the event. {:s.prop.gcal/url string? :s.prop.gcal/title string?}) (sm/mapdef1 :s.ent.gcal/attachment {:s.prop.gcal/fileUrl string? :s.prop.gcal/title string? :s.prop.gcal/mimeType string? :s.prop.gcal/iconLink string? :s.prop.gcal/fileId string?}) (sm/def-map-props {:s.gcal.prop.event/kind #{"calendar#event"} :s.prop.gcal/htmlLink string? :s.prop.gcal/description string? :s.prop.gcal/location string? :s.prop.gcal/colorId string? :s.prop.gcal/creator :s.gcal.ent/person :s.prop.gcal/organizer :s.gcal.ent/person :s.prop.gcal/start :s.prop-type.goog/time-coord :s.prop.gcal/end :s.prop-type.goog/time-coord :s.prop.gcal/endTimeUnspecified boolean? :s.prop.gcal/recurrence :s.prop/recurrence :s.prop.gcal/recurringEventId :s.prop/id_goog :s.prop.gcal/originalStartTime :s.prop-type.goog/time-coord :s.prop.gcal/iCalUID string? :s.prop.gcal/sequence nat-int? :s.prop.gcal/attendees (s/coll-of :s.gcal.ent/attendee) :s.prop.gcal/attendeesOmitted boolean? :s.prop.gcal/extendedProperties :s.gcal.prop/ext-props :s.prop.gcal/hangoutLink :s.prop-type/url ; read-only :s.prop.gcal/conferenceData :s.gcal.ent/conf-data :s.prop.gcal/gadget :s.prop.gcal.evt/gadget :s.prop.gcal/anyoneCanAddSelf boolean? :s.prop.gcal/guestsCanInviteOthers boolean? :s.prop.gcal/guestsCanModify boolean? :s.prop.gcal/guestsCanSeeOtherGuests boolean? :s.prop.gcal/privateCopy boolean? ; r-o :s.prop.gcal/locked boolean? ; r-o :s.prop.gcal/reminders :s.prop.gcal.evt/reminders :s.prop.gcal/source :s.prop.gcal.evt/source ; only for the creator :s.prop.gcal/attachments (s/coll-of :s.ent.gcal/attachment)}) (s/def ::evt-opt-keys (s/keys :opt-un [:s.prop.gcal/updated :s.prop.gcal/summary ; yep, can be untitled :s.prop.gcal/description :s.prop.gcal/location :s.prop.gcal/colorId :s.prop.gcal/creator :s.prop.gcal/organizer :s.prop.gcal/start :s.prop.gcal/end :s.prop.gcal/endTimeUnspecified :s.prop.gcal/transparency :s.prop.gcal/visibility :s.prop.gcal/iCalUID :s.prop.gcal/sequence :s.prop.gcal/attendees :s.prop.gcal/attendeesOmitted :s.prop.gcal/extendedProperties :s.prop.gcal/hangoutLink :s.prop.gcal/conferenceData :s.prop.gcal/gadget :s.prop.gcal/anyoneCanAddSelf :s.prop.gcal/guestsCanInviteOthers :s.prop.gcal/guestsCanModify :s.prop.gcal/guestsCanSeeOtherGuests :s.prop.gcal/privateCopy :s.prop.gcal/locked :s.prop.gcal/reminders :s.prop.gcal/source :s.prop.gcal/attachments :s.prop.gcal/eventType])) (s/def :s.gcal.ent/event--regular (s/merge ::evt-opt-keys (s/keys :req-un [:s.prop.gcal/id :s.gcal.prop.event/kind :s.prop.gcal/status :s.http/etag :s.prop.gcal/htmlLink :s.prop.gcal/created]))) (s/def :s.gcal.ent/event--regular-cancelled (s/keys :req-un [:s.prop.gcal/id :s.prop.gcal.evt-cancelled/status])) (s/def :s.gcal.ent/event--rec-base (s/merge ::evt-opt-keys (s/keys :req-un [:s.prop.gcal/id :s.gcal.prop.event/kind :s.prop.gcal/status :s.http/etag :s.prop/recurrence :s.prop.gcal/htmlLink :s.prop.gcal/created]))) (s/def :s.gcal.ent/event--rec-exception (s/merge ::evt-opt-keys (s/keys :req-un [:s.prop.gcal/id :s.gcal.prop.event/kind :s.prop.gcal/status :s.http/etag :s.prop.gcal/recurringEventId :s.prop.gcal/originalStartTime]))) (s/def :s.gcal.ent/event--rec-exception-cancelled ; Cancelled exceptions of an uncancelled recurring event indicate that ; this instance should no longer be presented to the user. Clients should ; store these events for the lifetime of the parent recurring event. ; Cancelled exceptions are only guaranteed to have values for the id, ; recurringEventId and originalStartTime fields populated. The other fields might be empty. (s/keys :req-un [:s.prop.gcal/id :s.prop.gcal.evt-cancelled/status :s.prop.gcal/recurringEventId :s.prop.gcal/originalStartTime])) (s/def :s.gcal.ent/event (s/or ::regular :s.gcal.ent/event--regular ::regular-cancelled :s.gcal.ent/event--regular-cancelled ::rec-base :s.gcal.ent/event--rec-base ::rec-exception :s.gcal.ent/event--rec-exception ::rec-exception-cancelled :s.gcal.ent/event--rec-exception-cancelled)) (s/assert :s.gcal.ent/event--regular {:iCalUID "PI:EMAIL:<EMAIL>END_PI", :description "PI:NAME:<NAME>END_PI is inviting you to a scheduled Zoom meeting.", :eventType "default", :creator {:email "PI:EMAIL:<EMAIL>END_PI", :self true}, :extendedProperties {:shared {:zmMeetingNum "75615174335"}}, :updated "2021-01-16T16:56:04.847Z", :conferenceData {:entryPoints [{:entryPointType "video", :uri "https://meet.google.com/not-an-id", :label "meet.google.com/not-an-id"}], :conferenceSolution {:key {:type "PI:KEY:<KEY>END_PI"}, :name "Google Meet", :iconUri "https://fonts.gstatic.com/s/i/productlogos/meet_2020q4/v6/web-512dp/logo_meet_2020q4_color_2x_web_512dp.png"}, :conferenceId "not-an-id", :signature "AL9oL6XRix+Rb5sHtGh5M/DQk3e1"}, :htmlLink "https://www.google.com/calendar/event?eid=not-an-id", :start {:dateTime "2021-01-12T09:00:00+03:00", :timeZone "Europe/Moscow"}, :etag "\"3221632329694000\"", :created "2021-01-11T09:20:30.000Z", :summary "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI zoom", :attendees [{:email "PI:EMAIL:<EMAIL>END_PI", :responseStatus "needsAction"} {:email "PI:EMAIL:<EMAIL>END_PI", :organizer true, :self true, :responseStatus "accepted"}], :status "confirmed", :id "not-an-id", :kind "calendar#event", :sequence 1, :reminders {:useDefault true}, :end {:dateTime "2021-01-12T09:40:00+03:00", :timeZone "Europe/Moscow"}, :location "https://us04web.zoom.us/j/smth?pwd=PI:PASSWORD:<PASSWORD>END_PI", :hangoutLink "https://meet.google.com/not-an-id", :organizer {:email "PI:EMAIL:<EMAIL>END_PI", :self true}})