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": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-12-19\" }\n \n taiga.scripts.debu", "end": 105, "score": 0.9998777508735657, "start": 87, "tag": "NAME", "value": "John Alan McDonald" } ]
src/scripts/clojure/taiga/scripts/debug/moves.clj
wahpenayo/taiga
4
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "John Alan McDonald" :date "2016-12-19" } taiga.scripts.debug.moves (:require [clojure.pprint :as pp] [taiga.split.object.categorical.move :as move])) ;;------------------------------------------------------------------------------ (let [left #{:a :b :c} right #{:d} moves (move/moves (sort left))] (loop [moves moves left left right right] (println (sort left) (sort right)) (when-not (empty? moves) (let [move (first moves) item (move/item move) right? (move/right? move)] (println move) (if right? (recur (rest moves) (disj left item) (conj right item)) (recur (rest moves) (conj left item) (disj right item))))))) ;;------------------------------------------------------------------------------
121791
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>" :date "2016-12-19" } taiga.scripts.debug.moves (:require [clojure.pprint :as pp] [taiga.split.object.categorical.move :as move])) ;;------------------------------------------------------------------------------ (let [left #{:a :b :c} right #{:d} moves (move/moves (sort left))] (loop [moves moves left left right right] (println (sort left) (sort right)) (when-not (empty? moves) (let [move (first moves) item (move/item move) right? (move/right? move)] (println move) (if right? (recur (rest moves) (disj left item) (conj right item)) (recur (rest moves) (conj left item) (disj right item))))))) ;;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-12-19" } taiga.scripts.debug.moves (:require [clojure.pprint :as pp] [taiga.split.object.categorical.move :as move])) ;;------------------------------------------------------------------------------ (let [left #{:a :b :c} right #{:d} moves (move/moves (sort left))] (loop [moves moves left left right right] (println (sort left) (sort right)) (when-not (empty? moves) (let [move (first moves) item (move/item move) right? (move/right? move)] (println move) (if right? (recur (rest moves) (disj left item) (conj right item)) (recur (rest moves) (conj left item) (disj right item))))))) ;;------------------------------------------------------------------------------
[ { "context": "> any?] => :strohm/subscription-key]\n (let [key (random-uuid)\n watch-fn (fn [_key _ref old new]\n ", "end": 1488, "score": 0.9323384165763855, "start": 1477, "tag": "KEY", "value": "random-uuid" } ]
Strohm/src/strohm_native/flow.cljs
svdo/strohm
0
(ns strohm-native.flow (:require [com.fulcrologic.guardrails.core :refer [=> >defn]] [strohm-native.impl.flow :as impl] [strohm-native.log :as log] [strohm-native.spec] [strohm-native.tx :refer [send-props!]] [strohm-native.utils :as utils]) (:require-macros [strohm-native.flow])) (defonce ^:export store (atom nil)) (defn ^:export create-store! [& args] (reset! store (apply impl/create-store args))) (>defn ^:export get-state [] [=> :strohm/state] (:state @store)) (>defn ^:export dispatch! [action] [:strohm/action => :strohm/action] (log/debug "dispatch!" action) (swap! store (:dispatch @store) action) action) (def ^:export dispatch impl/dispatch) (>defn ^:export dispatch-from-native [serialized-action] [string? => :strohm/action] (log/debug "dispatch-from-native" serialized-action) (try (let [action (utils/js->clj' (js/JSON.parse serialized-action))] (dispatch! action)) (catch ExceptionInfo ex-info (tap> {:ex-info ex-info}) (throw (js/Error. (ex-message ex-info)))) (catch js/Error js-error (tap> {:js-error js-error}) (throw js-error)) (catch :default e (tap> e) (throw e)))) (defn- subscribe-and-send-current-value [key watch-fn] (add-watch store key watch-fn) (watch-fn key nil nil @store)) (>defn ^:export subscribe! [callback] [[any? any? => any?] => :strohm/subscription-key] (let [key (random-uuid) watch-fn (fn [_key _ref old new] (log/debug "Triggered cljs subscription" key) (callback (:state old) (:state new)))] (subscribe-and-send-current-value key watch-fn) key)) (defn- trigger-subscription-update-to-native [props-spec key _ref old new] (log/debug "Triggered native subscription" key) (let [old-props (impl/state->props (:state old) props-spec) new-props (impl/state->props (:state new) props-spec)] (send-props! key old-props new-props))) (>defn ^:export subscribe-from-native [subscription-id serialized-props-spec] [string? string? => string?] (try (let [props-spec (utils/js->clj' (js/JSON.parse serialized-props-spec)) watch-fn (partial trigger-subscription-update-to-native props-spec)] (log/debug "subscribe-from-native" subscription-id props-spec) (subscribe-and-send-current-value (uuid subscription-id) watch-fn) subscription-id) (catch ExceptionInfo ex-info (tap> {:ex-info ex-info}) (throw (js/Error. (ex-message ex-info)))) (catch js/Error js-error (tap> {:js-error js-error}) (throw js-error)) (catch :default e (tap> e) (throw e)))) (>defn ^:export unsubscribe! [key] [:strohm/subscription-key => nil?] (remove-watch store key) nil) (>defn ^:export unsubscribe-from-native [subscription-id] [string? => boolean?] (log/debug "unsubscribe-from-native" subscription-id) (let [key (uuid subscription-id)] (some? (unsubscribe! key)))) (>defn ^:export combine-reducers [reducers] [map? => :strohm/reducer] (impl/combine-reducers reducers)) (def ^:export clj->js' utils/clj->js') (def ^:export js->clj' utils/js->clj')
20724
(ns strohm-native.flow (:require [com.fulcrologic.guardrails.core :refer [=> >defn]] [strohm-native.impl.flow :as impl] [strohm-native.log :as log] [strohm-native.spec] [strohm-native.tx :refer [send-props!]] [strohm-native.utils :as utils]) (:require-macros [strohm-native.flow])) (defonce ^:export store (atom nil)) (defn ^:export create-store! [& args] (reset! store (apply impl/create-store args))) (>defn ^:export get-state [] [=> :strohm/state] (:state @store)) (>defn ^:export dispatch! [action] [:strohm/action => :strohm/action] (log/debug "dispatch!" action) (swap! store (:dispatch @store) action) action) (def ^:export dispatch impl/dispatch) (>defn ^:export dispatch-from-native [serialized-action] [string? => :strohm/action] (log/debug "dispatch-from-native" serialized-action) (try (let [action (utils/js->clj' (js/JSON.parse serialized-action))] (dispatch! action)) (catch ExceptionInfo ex-info (tap> {:ex-info ex-info}) (throw (js/Error. (ex-message ex-info)))) (catch js/Error js-error (tap> {:js-error js-error}) (throw js-error)) (catch :default e (tap> e) (throw e)))) (defn- subscribe-and-send-current-value [key watch-fn] (add-watch store key watch-fn) (watch-fn key nil nil @store)) (>defn ^:export subscribe! [callback] [[any? any? => any?] => :strohm/subscription-key] (let [key (<KEY>) watch-fn (fn [_key _ref old new] (log/debug "Triggered cljs subscription" key) (callback (:state old) (:state new)))] (subscribe-and-send-current-value key watch-fn) key)) (defn- trigger-subscription-update-to-native [props-spec key _ref old new] (log/debug "Triggered native subscription" key) (let [old-props (impl/state->props (:state old) props-spec) new-props (impl/state->props (:state new) props-spec)] (send-props! key old-props new-props))) (>defn ^:export subscribe-from-native [subscription-id serialized-props-spec] [string? string? => string?] (try (let [props-spec (utils/js->clj' (js/JSON.parse serialized-props-spec)) watch-fn (partial trigger-subscription-update-to-native props-spec)] (log/debug "subscribe-from-native" subscription-id props-spec) (subscribe-and-send-current-value (uuid subscription-id) watch-fn) subscription-id) (catch ExceptionInfo ex-info (tap> {:ex-info ex-info}) (throw (js/Error. (ex-message ex-info)))) (catch js/Error js-error (tap> {:js-error js-error}) (throw js-error)) (catch :default e (tap> e) (throw e)))) (>defn ^:export unsubscribe! [key] [:strohm/subscription-key => nil?] (remove-watch store key) nil) (>defn ^:export unsubscribe-from-native [subscription-id] [string? => boolean?] (log/debug "unsubscribe-from-native" subscription-id) (let [key (uuid subscription-id)] (some? (unsubscribe! key)))) (>defn ^:export combine-reducers [reducers] [map? => :strohm/reducer] (impl/combine-reducers reducers)) (def ^:export clj->js' utils/clj->js') (def ^:export js->clj' utils/js->clj')
true
(ns strohm-native.flow (:require [com.fulcrologic.guardrails.core :refer [=> >defn]] [strohm-native.impl.flow :as impl] [strohm-native.log :as log] [strohm-native.spec] [strohm-native.tx :refer [send-props!]] [strohm-native.utils :as utils]) (:require-macros [strohm-native.flow])) (defonce ^:export store (atom nil)) (defn ^:export create-store! [& args] (reset! store (apply impl/create-store args))) (>defn ^:export get-state [] [=> :strohm/state] (:state @store)) (>defn ^:export dispatch! [action] [:strohm/action => :strohm/action] (log/debug "dispatch!" action) (swap! store (:dispatch @store) action) action) (def ^:export dispatch impl/dispatch) (>defn ^:export dispatch-from-native [serialized-action] [string? => :strohm/action] (log/debug "dispatch-from-native" serialized-action) (try (let [action (utils/js->clj' (js/JSON.parse serialized-action))] (dispatch! action)) (catch ExceptionInfo ex-info (tap> {:ex-info ex-info}) (throw (js/Error. (ex-message ex-info)))) (catch js/Error js-error (tap> {:js-error js-error}) (throw js-error)) (catch :default e (tap> e) (throw e)))) (defn- subscribe-and-send-current-value [key watch-fn] (add-watch store key watch-fn) (watch-fn key nil nil @store)) (>defn ^:export subscribe! [callback] [[any? any? => any?] => :strohm/subscription-key] (let [key (PI:KEY:<KEY>END_PI) watch-fn (fn [_key _ref old new] (log/debug "Triggered cljs subscription" key) (callback (:state old) (:state new)))] (subscribe-and-send-current-value key watch-fn) key)) (defn- trigger-subscription-update-to-native [props-spec key _ref old new] (log/debug "Triggered native subscription" key) (let [old-props (impl/state->props (:state old) props-spec) new-props (impl/state->props (:state new) props-spec)] (send-props! key old-props new-props))) (>defn ^:export subscribe-from-native [subscription-id serialized-props-spec] [string? string? => string?] (try (let [props-spec (utils/js->clj' (js/JSON.parse serialized-props-spec)) watch-fn (partial trigger-subscription-update-to-native props-spec)] (log/debug "subscribe-from-native" subscription-id props-spec) (subscribe-and-send-current-value (uuid subscription-id) watch-fn) subscription-id) (catch ExceptionInfo ex-info (tap> {:ex-info ex-info}) (throw (js/Error. (ex-message ex-info)))) (catch js/Error js-error (tap> {:js-error js-error}) (throw js-error)) (catch :default e (tap> e) (throw e)))) (>defn ^:export unsubscribe! [key] [:strohm/subscription-key => nil?] (remove-watch store key) nil) (>defn ^:export unsubscribe-from-native [subscription-id] [string? => boolean?] (log/debug "unsubscribe-from-native" subscription-id) (let [key (uuid subscription-id)] (some? (unsubscribe! key)))) (>defn ^:export combine-reducers [reducers] [map? => :strohm/reducer] (impl/combine-reducers reducers)) (def ^:export clj->js' utils/clj->js') (def ^:export js->clj' utils/js->clj')
[ { "context": "; SPDX-FileCopyrightText: 2021 Orcro Ltd. team@orcro.co.uk \n; \n; SPDX-License-Identifier: Apache-2.0\n\n(ns we", "end": 58, "score": 0.9999291896820068, "start": 42, "tag": "EMAIL", "value": "team@orcro.co.uk" } ]
test/urltester/core_test.clj
Orcro/urltester
1
; SPDX-FileCopyrightText: 2021 Orcro Ltd. team@orcro.co.uk ; ; SPDX-License-Identifier: Apache-2.0 (ns webtester.core-test (:require [clojure.test :refer :all] [webtester.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
78245
; SPDX-FileCopyrightText: 2021 Orcro Ltd. <EMAIL> ; ; SPDX-License-Identifier: Apache-2.0 (ns webtester.core-test (:require [clojure.test :refer :all] [webtester.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
true
; SPDX-FileCopyrightText: 2021 Orcro Ltd. PI:EMAIL:<EMAIL>END_PI ; ; SPDX-License-Identifier: Apache-2.0 (ns webtester.core-test (:require [clojure.test :refer :all] [webtester.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
[ { "context": "; Copyright 2015 Zalando SE\n;\n; Licensed under the Apache License, Version", "end": 24, "score": 0.7190762162208557, "start": 17, "tag": "NAME", "value": "Zalando" }, { "context": " :db-user \"postgres\"\n :db-password \"postgres\"\n :db-init-sql \"SET search_path TO zk_data, ", "end": 1003, "score": 0.9994588494300842, "start": 995, "tag": "PASSWORD", "value": "postgres" } ]
src/org/zalando/stups/kio/sql.clj
maxim-tschumak/kio
0
; Copyright 2015 Zalando SE ; ; 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 org.zalando.stups.kio.sql (:require [yesql.core :refer [defqueries]] [org.zalando.stups.friboo.system.db :refer [def-db-component generate-hystrix-commands]])) (def-db-component DB :auto-migration? true) (def default-db-configuration {:db-classname "org.postgresql.Driver" :db-subprotocol "postgresql" :db-subname "//localhost:5432/kio" :db-user "postgres" :db-password "postgres" :db-init-sql "SET search_path TO zk_data, public"}) (defqueries "db/applications.sql") (generate-hystrix-commands) (def column-prefix-pattern #"[a-z]+_(.+)") (defn remove-prefix [m] (->> m name (re-find column-prefix-pattern) second keyword)) (defn strip-prefixes "Removes the database field prefix." [results] (map (fn [result] (into {} (map (fn [[k v]] [(remove-prefix k) v]) result))) results))
33383
; Copyright 2015 <NAME> SE ; ; 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 org.zalando.stups.kio.sql (:require [yesql.core :refer [defqueries]] [org.zalando.stups.friboo.system.db :refer [def-db-component generate-hystrix-commands]])) (def-db-component DB :auto-migration? true) (def default-db-configuration {:db-classname "org.postgresql.Driver" :db-subprotocol "postgresql" :db-subname "//localhost:5432/kio" :db-user "postgres" :db-password "<PASSWORD>" :db-init-sql "SET search_path TO zk_data, public"}) (defqueries "db/applications.sql") (generate-hystrix-commands) (def column-prefix-pattern #"[a-z]+_(.+)") (defn remove-prefix [m] (->> m name (re-find column-prefix-pattern) second keyword)) (defn strip-prefixes "Removes the database field prefix." [results] (map (fn [result] (into {} (map (fn [[k v]] [(remove-prefix k) v]) result))) results))
true
; Copyright 2015 PI:NAME:<NAME>END_PI SE ; ; 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 org.zalando.stups.kio.sql (:require [yesql.core :refer [defqueries]] [org.zalando.stups.friboo.system.db :refer [def-db-component generate-hystrix-commands]])) (def-db-component DB :auto-migration? true) (def default-db-configuration {:db-classname "org.postgresql.Driver" :db-subprotocol "postgresql" :db-subname "//localhost:5432/kio" :db-user "postgres" :db-password "PI:PASSWORD:<PASSWORD>END_PI" :db-init-sql "SET search_path TO zk_data, public"}) (defqueries "db/applications.sql") (generate-hystrix-commands) (def column-prefix-pattern #"[a-z]+_(.+)") (defn remove-prefix [m] (->> m name (re-find column-prefix-pattern) second keyword)) (defn strip-prefixes "Removes the database field prefix." [results] (map (fn [result] (into {} (map (fn [[k v]] [(remove-prefix k) v]) result))) results))
[ { "context": "es.clj -- Unit tests of Incanter functions \n\n;; by David Edgar Liebke http://incanter.org\n;; March 12, 2009\n\n;; Copyrig", "end": 82, "score": 0.9998895525932312, "start": 64, "tag": "NAME", "value": "David Edgar Liebke" }, { "context": "//incanter.org\n;; March 12, 2009\n\n;; Copyright (c) David Edgar Liebke, 2009. All rights reserved. The use\n;; and distr", "end": 157, "score": 0.9998838305473328, "start": 139, "tag": "NAME", "value": "David Edgar Liebke" } ]
data/clojure/e3e953e4b71bf7dd74337d7840f7b559_io_tests.clj
maxim5/code-inspector
5
;;; test-cases.clj -- Unit tests of Incanter functions ;; by David Edgar Liebke http://incanter.org ;; March 12, 2009 ;; Copyright (c) David Edgar Liebke, 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. ;; CHANGE LOG ;; March 12, 2009: First version ;; to run these tests: ;; (use 'tests test-cases) ;; need to load this file to define data variables ;; (use 'clojure.contrib.test-is) ;; then run tests ;; (run-tests 'incanter.tests.test-cases) (ns incanter.io-tests (:use clojure.test (incanter core io))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; UNIT TESTS FOR incanter.io.clj ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;(def incanter-home (System/getProperty "incanter.home")) (def incanter-home "../../") ;; read in a dataset from a space delimited file (def test-data (read-dataset (str incanter-home "data/cars.dat") :delim \space :header true)) ; default delimiter: \, ;; read in a dataset from a comma delimited file (def test-csv-data (read-dataset (str incanter-home "data/cars.csv") :header true)) ;; read in a dataset from a tab delimited file (def test-tdd-data (read-dataset (str incanter-home "data/cars.tdd") :header true :delim \tab)) ;; read in the iris dataset from a space delimited file (def iris-data (read-dataset (str incanter-home "data/iris.dat") :delim \space :header true)) ;; read in the social science survey dataset from a space delimited file (def ols-data (to-matrix (read-dataset (str incanter-home "data/olsexamp.dat") :delim \space :header true))) ;; convert the space-delimited dataset into a matrix (def test-mat (to-matrix test-data)) ;; convert the csv dataset into a matrix (def test-csv-mat (to-matrix test-csv-data)) ;; convert the tab-delimited dataset into a matrix (def test-tdd-mat (to-matrix test-tdd-data)) ;; convert the iris-data into a matrix, encoding strings into multiple dummy variables (def iris-mat (to-matrix iris-data)) (def iris-mat-dummies (to-matrix iris-data :dummies true)) (deftest io-validation ;; validate matrices read from files (is (= (reduce plus test-mat) (matrix [770 2149] 2))) (is (= (reduce plus test-csv-mat) (matrix [770 2149] 2))) (is (= (reduce plus test-tdd-mat) (matrix [770 2149] 2))) ;; confirm that iris species factor was converted to two dummy variables (is (= (first iris-mat) (matrix [5.10 3.50 1.40 0.20 0] 5))) (is (= (first iris-mat-dummies) (matrix [5.10 3.50 1.40 0.20 0 0] 6)))) ;; end of io-validation tests (deftest read-dataset-validation (doseq [[name cars-dataset] [["dat" test-data] ["csv" test-csv-data] ["tdd" test-tdd-data]]] (is (= [:speed :dist] (:column-names cars-dataset)) (str "Reading column names for " name " failed")) (is (= 50 (count (:rows cars-dataset)))) (str "Reading rows for " name " failed"))) ;; end of read-dataset-validation tests
11086
;;; test-cases.clj -- Unit tests of Incanter functions ;; by <NAME> http://incanter.org ;; March 12, 2009 ;; Copyright (c) <NAME>, 2009. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. ;; CHANGE LOG ;; March 12, 2009: First version ;; to run these tests: ;; (use 'tests test-cases) ;; need to load this file to define data variables ;; (use 'clojure.contrib.test-is) ;; then run tests ;; (run-tests 'incanter.tests.test-cases) (ns incanter.io-tests (:use clojure.test (incanter core io))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; UNIT TESTS FOR incanter.io.clj ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;(def incanter-home (System/getProperty "incanter.home")) (def incanter-home "../../") ;; read in a dataset from a space delimited file (def test-data (read-dataset (str incanter-home "data/cars.dat") :delim \space :header true)) ; default delimiter: \, ;; read in a dataset from a comma delimited file (def test-csv-data (read-dataset (str incanter-home "data/cars.csv") :header true)) ;; read in a dataset from a tab delimited file (def test-tdd-data (read-dataset (str incanter-home "data/cars.tdd") :header true :delim \tab)) ;; read in the iris dataset from a space delimited file (def iris-data (read-dataset (str incanter-home "data/iris.dat") :delim \space :header true)) ;; read in the social science survey dataset from a space delimited file (def ols-data (to-matrix (read-dataset (str incanter-home "data/olsexamp.dat") :delim \space :header true))) ;; convert the space-delimited dataset into a matrix (def test-mat (to-matrix test-data)) ;; convert the csv dataset into a matrix (def test-csv-mat (to-matrix test-csv-data)) ;; convert the tab-delimited dataset into a matrix (def test-tdd-mat (to-matrix test-tdd-data)) ;; convert the iris-data into a matrix, encoding strings into multiple dummy variables (def iris-mat (to-matrix iris-data)) (def iris-mat-dummies (to-matrix iris-data :dummies true)) (deftest io-validation ;; validate matrices read from files (is (= (reduce plus test-mat) (matrix [770 2149] 2))) (is (= (reduce plus test-csv-mat) (matrix [770 2149] 2))) (is (= (reduce plus test-tdd-mat) (matrix [770 2149] 2))) ;; confirm that iris species factor was converted to two dummy variables (is (= (first iris-mat) (matrix [5.10 3.50 1.40 0.20 0] 5))) (is (= (first iris-mat-dummies) (matrix [5.10 3.50 1.40 0.20 0 0] 6)))) ;; end of io-validation tests (deftest read-dataset-validation (doseq [[name cars-dataset] [["dat" test-data] ["csv" test-csv-data] ["tdd" test-tdd-data]]] (is (= [:speed :dist] (:column-names cars-dataset)) (str "Reading column names for " name " failed")) (is (= 50 (count (:rows cars-dataset)))) (str "Reading rows for " name " failed"))) ;; end of read-dataset-validation tests
true
;;; test-cases.clj -- Unit tests of Incanter functions ;; by PI:NAME:<NAME>END_PI http://incanter.org ;; March 12, 2009 ;; Copyright (c) PI:NAME:<NAME>END_PI, 2009. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. ;; CHANGE LOG ;; March 12, 2009: First version ;; to run these tests: ;; (use 'tests test-cases) ;; need to load this file to define data variables ;; (use 'clojure.contrib.test-is) ;; then run tests ;; (run-tests 'incanter.tests.test-cases) (ns incanter.io-tests (:use clojure.test (incanter core io))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; UNIT TESTS FOR incanter.io.clj ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;(def incanter-home (System/getProperty "incanter.home")) (def incanter-home "../../") ;; read in a dataset from a space delimited file (def test-data (read-dataset (str incanter-home "data/cars.dat") :delim \space :header true)) ; default delimiter: \, ;; read in a dataset from a comma delimited file (def test-csv-data (read-dataset (str incanter-home "data/cars.csv") :header true)) ;; read in a dataset from a tab delimited file (def test-tdd-data (read-dataset (str incanter-home "data/cars.tdd") :header true :delim \tab)) ;; read in the iris dataset from a space delimited file (def iris-data (read-dataset (str incanter-home "data/iris.dat") :delim \space :header true)) ;; read in the social science survey dataset from a space delimited file (def ols-data (to-matrix (read-dataset (str incanter-home "data/olsexamp.dat") :delim \space :header true))) ;; convert the space-delimited dataset into a matrix (def test-mat (to-matrix test-data)) ;; convert the csv dataset into a matrix (def test-csv-mat (to-matrix test-csv-data)) ;; convert the tab-delimited dataset into a matrix (def test-tdd-mat (to-matrix test-tdd-data)) ;; convert the iris-data into a matrix, encoding strings into multiple dummy variables (def iris-mat (to-matrix iris-data)) (def iris-mat-dummies (to-matrix iris-data :dummies true)) (deftest io-validation ;; validate matrices read from files (is (= (reduce plus test-mat) (matrix [770 2149] 2))) (is (= (reduce plus test-csv-mat) (matrix [770 2149] 2))) (is (= (reduce plus test-tdd-mat) (matrix [770 2149] 2))) ;; confirm that iris species factor was converted to two dummy variables (is (= (first iris-mat) (matrix [5.10 3.50 1.40 0.20 0] 5))) (is (= (first iris-mat-dummies) (matrix [5.10 3.50 1.40 0.20 0 0] 6)))) ;; end of io-validation tests (deftest read-dataset-validation (doseq [[name cars-dataset] [["dat" test-data] ["csv" test-csv-data] ["tdd" test-tdd-data]]] (is (= [:speed :dist] (:column-names cars-dataset)) (str "Reading column names for " name " failed")) (is (= 50 (count (:rows cars-dataset)))) (str "Reading rows for " name " failed"))) ;; end of read-dataset-validation tests
[ { "context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.bixby.cons.con1\n", "end": 597, "score": 0.9998562932014465, "start": 584, "tag": "NAME", "value": "Kenneth Leung" } ]
src/main/clojure/czlab/bixby/cons/con1.clj
llnek/skaro
0
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, Kenneth Leung. All rights reserved. (ns czlab.bixby.cons.con1 (:require [czlab.cljant.antlib :as a] [io.aviso.ansi :as ansi] [clojure.string :as cs] [clojure.java.io :as io] [czlab.basal.io :as i] [czlab.basal.util :as u] [czlab.bixby.core :as b] [czlab.bixby.exec :as e] [czlab.twisty.core :as tc] [czlab.twisty.codec :as co] [czlab.bixby.cons.con2 :as c2] [czlab.basal.core :as c :refer [n#]]) (:import [java.util ResourceBundle Properties Calendar Map Date] [java.io DataOutputStream File] [java.net Socket InetAddress InetSocketAddress])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) (def ^:dynamic *config-object* nil) (def ^:dynamic *pkey-object* nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-xxx "Print out help messages." [pfx end] (try (dotimes [n end] (c/prn!! "%s" (u/rstr (b/get-rc-base) (str pfx (+ 1 n))))) (finally (c/prn!! "")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-create "Help for action: create." [] (on-help-xxx "usage.new.d" 5)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-create "Create a new pod." {:arglists '([args])} [args] (if (empty? args) (u/throw-BadData "CmdError!") (apply c2/create-pod (c/_1 args) (drop 1 args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-podify "Help for action: podify." [] (on-help-xxx "usage.podify.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-podify "Package app into a standalone app." {:arglists '([args])} [args] (if (empty? args) (u/throw-BadData "CmdError!") (let [a (io/file (b/get-proc-dir)) dir (i/mkdirs (io/file (c/_1 args)))] (a/run* (a/zip {:includes "**/*" :basedir a :destFile (io/file dir (str (.getName a) ".zip"))}))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-start "Help for action: start." [] (on-help-xxx "usage.start.d" 4)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-stop "Help for action: stop." [] (on-help-xxx "usage.stop.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- run-pod-bg "Run the application in the background." [podDir] (let [progW (io/file podDir "bin/bixby.bat") prog (io/file podDir "bin/bixby") tk (if (u/is-windows?) (a/exec {:dir podDir :executable "cmd.exe"} [[:argvalues ["/C" "start" "/B" "/MIN" (u/fpath progW) "run"]]]))] (if false (a/exec {:dir podDir :executable (u/fpath prog)} [[:argvalues ["run" "bg"]]])) ;run the target (if tk (a/run* tk) (u/throw-BadData "CmdError!")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-start "Start the application." {:arglists '([args])} [args] (let [s2 (c/_1 args) cwd (b/get-proc-dir)] ;; background job is handled differently on windows (if (and (u/is-windows?) (c/in? #{"-bg" "--background"} s2)) (run-pod-bg cwd) (do (-> b/banner ansi/bold-magenta c/prn!!) (e/start-via-cons cwd))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-stop [args] (c/try! (c/wo* [soc (Socket.)] (.connect soc (InetSocketAddress. (InetAddress/getLocalHost) (-> "bixby.kill.port" u/get-sys-prop (c/s->int 4444))) 5000) (let [os (.getOutputStream soc)] (-> (DataOutputStream. os) (.writeInt 117)) (.flush os))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-debug "Help for action: debug." [] (on-help-xxx "usage.debug.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-debug "Debug the application." {:arglists '([args])} [args] (on-start args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-demos "Help for action :demo." [] (on-help-xxx "usage.demo.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-demos "Generate demo samples." {:arglists '([args])} [args] (if (empty? args) (u/throw-BadData "CmdError!") (c2/publish-samples (c/_1 args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gen-pwd "Generate a passord." {:arglists '([args])} [args] (let [c (c/_1 args) n (c/s->long (str c) 16)] (if-not (and (>= n 8) (<= n 48)) (u/throw-BadData "CmdError!") (-> n co/strong-pwd<> co/pw-text i/x->str)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gen-guid "Generate a UUID." {:arglists '([])} [] (u/uuid<>)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-encrypt "Encrypt some data." [args] (let [[s k] (cond (c/one? args) [(c/_1 args) *pkey-object*] (c/two? args) [(c/_2 args)(c/_1 args)] :else (u/throw-BadData "CmdError!"))] (try (-> (co/pwd<> s k) co/pw-encoded i/x->str) (catch Throwable e (c/prn!! "Failed to encrypt: %s." (u/emsg e)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-decrypt "Decrypt some data." [args] (let [[s k] (cond (c/one? args) [(c/_1 args) *pkey-object*] (c/two? args) [(c/_2 args)(c/_1 args)] :else (u/throw-BadData "CmdError!"))] (try (-> (co/pwd<> s k) co/pw-text i/x->str) (catch Throwable e (c/prn!! "Failed to decrypt: %s." (u/emsg e)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-hash "Generate a hash/digest on the data." [args] (if-not (empty? args) (tc/gen-digest (c/_1 args)) (u/throw-BadData "CmdError!"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-mac "Generate a MAC on the data." [args] (if (empty? args) (u/throw-BadData "CmdError!") (tc/gen-mac *pkey-object* (c/_1 args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-generate "Help for action: generate." [] (on-help-xxx "usage.gen.d" 9)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-generate "Various generate functions." {:arglists '([args])} [args] (let [c (c/_1 args) args (drop 1 args)] (cond (c/in? #{"-p" "--password"} c) (gen-pwd args) (c/in? #{"-h" "--hash"} c) (on-hash args) (c/in? #{"-m" "--mac"} c) (on-mac args) (c/in? #{"-u" "--uuid"} c) (gen-guid) (c/in? #{"-e" "--encrypt"} c) (on-encrypt args) (c/in? #{"-d" "--decrypt"} c) (on-decrypt args) :else (u/throw-BadData "CmdError!")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn prn-generate "Print from the function." {:arglists '([args])} [args] (c/prn!! "%s" (on-generate args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-version "Help for action: version." [] (on-help-xxx "usage.version.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-version "Print out the version." {:arglists '([args])} [args] (let [rcb (b/get-rc-base)] (->> (u/get-sys-prop "bixby.version") (u/rstr rcb "usage.version.o1") (c/prn!! "%s" )) (->> (u/get-sys-prop "java.version") (u/rstr rcb "usage.version.o2") (c/prn!! "%s")) (c/prn!! ""))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- scan-jars "Scan a directory for jar files and list the file paths." [out dir] (let [sep (u/get-sys-prop "line.separator")] (c/sbf+ out (c/sreduce<> #(c/sbf+ %1 (str "<classpathentry " "kind=\"lib\"" " path=\"" (u/fpath %2) "\"/>" sep)) (i/list-files dir ".jar"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- gen-eclipse-proj "Generate a eclipse project file." [pdir] (let [ec (io/file pdir "eclipse.projfiles") poddir (io/file pdir) pod (i/fname poddir) sb (c/sbf<>)] (i/mkdirs ec) (i/clean-dir ec) (i/spit-utf8 (io/file ec ".project") (-> (i/res->str (str "czlab/bixby/eclipse/java/project.txt")) (cs/replace "${APP.NAME}" pod) (cs/replace "${JAVA.TEST}" (u/fpath (io/file poddir "src/test/java"))) (cs/replace "${JAVA.SRC}" (u/fpath (io/file poddir "src/main/java"))) (cs/replace "${CLJ.TEST}" (u/fpath (io/file poddir "src/test/clojure"))) (cs/replace "${CLJ.SRC}" (u/fpath (io/file poddir "src/main/clojure"))))) (i/mkdirs (io/file poddir b/dn-build "classes")) (doall (map (partial scan-jars sb) [(io/file (b/get-proc-dir) b/dn-dist) (io/file (b/get-proc-dir) b/dn-lib) (io/file poddir b/dn-target)])) (i/spit-utf8 (io/file ec ".classpath") (-> (i/res->str (str "czlab/bixby/eclipse/java/classpath.txt")) (cs/replace "${CLASS.PATH.ENTRIES}" (str sb)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-ide "Help for action: ide." [] (on-help-xxx "usage.ide.d" 4)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-ide "Generate project files for IDEs." {:arglists '([args])} [args] (if-not (and (not-empty args) (c/in? #{"-e" "--eclipse"} (c/_1 args))) (u/throw-BadData "CmdError!") (gen-eclipse-proj (b/get-proc-dir)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-service-specs "Help for action: service." [] (on-help-xxx "usage.svc.d" 8)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-service-specs "Print out specs for built-in plugins." {:arglists '([args])} [args] (let [clj (u/cljrt<>)] (-> (c/preduce<map> #(assoc! %1 (c/_1 %2) (u/var* clj (str "czlab.bixby.plugs." (c/kw->str (c/_2 %2))))) {:OnceTimer :loops/OnceTimerSpec :FilePicker :files/FilePickerSpec :TCP :socket/TCPSpec :JMS :jms/JMSSpec :POP3 :mails/POP3Spec :IMAP :mails/IMAPSpec :HTTP :http/HTTPSpec :RepeatingTimer :loops/RepeatingTimerSpec}) i/fmt->edn c/prn!!))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-help-help "Help for action: help." {:arglists '([])} [] (u/throw-BadData "CmdError!")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def bixby-tasks nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-help "Print out help message for an action." {:arglists '([args])} [args] (c/if-fn [h (c/_2 (bixby-tasks (keyword (c/_1 args))))] (h) (u/throw-BadData "CmdError!"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (alter-var-root #'bixby-tasks (fn [_] {:new [on-create on-help-create] :ide [on-ide on-help-ide] :podify [on-podify on-help-podify] :debug [on-debug on-help-debug] :help [on-help on-help-help] :run [on-start on-help-start] :stop [on-stop on-help-stop] :demos [on-demos on-help-demos] :crypto [prn-generate on-help-generate] :version [on-version on-help-version] :service [on-service-specs on-help-service-specs]})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
57644
;; 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. ;; ;; Copyright © 2013-2022, <NAME>. All rights reserved. (ns czlab.bixby.cons.con1 (:require [czlab.cljant.antlib :as a] [io.aviso.ansi :as ansi] [clojure.string :as cs] [clojure.java.io :as io] [czlab.basal.io :as i] [czlab.basal.util :as u] [czlab.bixby.core :as b] [czlab.bixby.exec :as e] [czlab.twisty.core :as tc] [czlab.twisty.codec :as co] [czlab.bixby.cons.con2 :as c2] [czlab.basal.core :as c :refer [n#]]) (:import [java.util ResourceBundle Properties Calendar Map Date] [java.io DataOutputStream File] [java.net Socket InetAddress InetSocketAddress])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) (def ^:dynamic *config-object* nil) (def ^:dynamic *pkey-object* nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-xxx "Print out help messages." [pfx end] (try (dotimes [n end] (c/prn!! "%s" (u/rstr (b/get-rc-base) (str pfx (+ 1 n))))) (finally (c/prn!! "")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-create "Help for action: create." [] (on-help-xxx "usage.new.d" 5)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-create "Create a new pod." {:arglists '([args])} [args] (if (empty? args) (u/throw-BadData "CmdError!") (apply c2/create-pod (c/_1 args) (drop 1 args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-podify "Help for action: podify." [] (on-help-xxx "usage.podify.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-podify "Package app into a standalone app." {:arglists '([args])} [args] (if (empty? args) (u/throw-BadData "CmdError!") (let [a (io/file (b/get-proc-dir)) dir (i/mkdirs (io/file (c/_1 args)))] (a/run* (a/zip {:includes "**/*" :basedir a :destFile (io/file dir (str (.getName a) ".zip"))}))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-start "Help for action: start." [] (on-help-xxx "usage.start.d" 4)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-stop "Help for action: stop." [] (on-help-xxx "usage.stop.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- run-pod-bg "Run the application in the background." [podDir] (let [progW (io/file podDir "bin/bixby.bat") prog (io/file podDir "bin/bixby") tk (if (u/is-windows?) (a/exec {:dir podDir :executable "cmd.exe"} [[:argvalues ["/C" "start" "/B" "/MIN" (u/fpath progW) "run"]]]))] (if false (a/exec {:dir podDir :executable (u/fpath prog)} [[:argvalues ["run" "bg"]]])) ;run the target (if tk (a/run* tk) (u/throw-BadData "CmdError!")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-start "Start the application." {:arglists '([args])} [args] (let [s2 (c/_1 args) cwd (b/get-proc-dir)] ;; background job is handled differently on windows (if (and (u/is-windows?) (c/in? #{"-bg" "--background"} s2)) (run-pod-bg cwd) (do (-> b/banner ansi/bold-magenta c/prn!!) (e/start-via-cons cwd))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-stop [args] (c/try! (c/wo* [soc (Socket.)] (.connect soc (InetSocketAddress. (InetAddress/getLocalHost) (-> "bixby.kill.port" u/get-sys-prop (c/s->int 4444))) 5000) (let [os (.getOutputStream soc)] (-> (DataOutputStream. os) (.writeInt 117)) (.flush os))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-debug "Help for action: debug." [] (on-help-xxx "usage.debug.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-debug "Debug the application." {:arglists '([args])} [args] (on-start args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-demos "Help for action :demo." [] (on-help-xxx "usage.demo.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-demos "Generate demo samples." {:arglists '([args])} [args] (if (empty? args) (u/throw-BadData "CmdError!") (c2/publish-samples (c/_1 args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gen-pwd "Generate a passord." {:arglists '([args])} [args] (let [c (c/_1 args) n (c/s->long (str c) 16)] (if-not (and (>= n 8) (<= n 48)) (u/throw-BadData "CmdError!") (-> n co/strong-pwd<> co/pw-text i/x->str)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gen-guid "Generate a UUID." {:arglists '([])} [] (u/uuid<>)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-encrypt "Encrypt some data." [args] (let [[s k] (cond (c/one? args) [(c/_1 args) *pkey-object*] (c/two? args) [(c/_2 args)(c/_1 args)] :else (u/throw-BadData "CmdError!"))] (try (-> (co/pwd<> s k) co/pw-encoded i/x->str) (catch Throwable e (c/prn!! "Failed to encrypt: %s." (u/emsg e)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-decrypt "Decrypt some data." [args] (let [[s k] (cond (c/one? args) [(c/_1 args) *pkey-object*] (c/two? args) [(c/_2 args)(c/_1 args)] :else (u/throw-BadData "CmdError!"))] (try (-> (co/pwd<> s k) co/pw-text i/x->str) (catch Throwable e (c/prn!! "Failed to decrypt: %s." (u/emsg e)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-hash "Generate a hash/digest on the data." [args] (if-not (empty? args) (tc/gen-digest (c/_1 args)) (u/throw-BadData "CmdError!"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-mac "Generate a MAC on the data." [args] (if (empty? args) (u/throw-BadData "CmdError!") (tc/gen-mac *pkey-object* (c/_1 args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-generate "Help for action: generate." [] (on-help-xxx "usage.gen.d" 9)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-generate "Various generate functions." {:arglists '([args])} [args] (let [c (c/_1 args) args (drop 1 args)] (cond (c/in? #{"-p" "--password"} c) (gen-pwd args) (c/in? #{"-h" "--hash"} c) (on-hash args) (c/in? #{"-m" "--mac"} c) (on-mac args) (c/in? #{"-u" "--uuid"} c) (gen-guid) (c/in? #{"-e" "--encrypt"} c) (on-encrypt args) (c/in? #{"-d" "--decrypt"} c) (on-decrypt args) :else (u/throw-BadData "CmdError!")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn prn-generate "Print from the function." {:arglists '([args])} [args] (c/prn!! "%s" (on-generate args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-version "Help for action: version." [] (on-help-xxx "usage.version.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-version "Print out the version." {:arglists '([args])} [args] (let [rcb (b/get-rc-base)] (->> (u/get-sys-prop "bixby.version") (u/rstr rcb "usage.version.o1") (c/prn!! "%s" )) (->> (u/get-sys-prop "java.version") (u/rstr rcb "usage.version.o2") (c/prn!! "%s")) (c/prn!! ""))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- scan-jars "Scan a directory for jar files and list the file paths." [out dir] (let [sep (u/get-sys-prop "line.separator")] (c/sbf+ out (c/sreduce<> #(c/sbf+ %1 (str "<classpathentry " "kind=\"lib\"" " path=\"" (u/fpath %2) "\"/>" sep)) (i/list-files dir ".jar"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- gen-eclipse-proj "Generate a eclipse project file." [pdir] (let [ec (io/file pdir "eclipse.projfiles") poddir (io/file pdir) pod (i/fname poddir) sb (c/sbf<>)] (i/mkdirs ec) (i/clean-dir ec) (i/spit-utf8 (io/file ec ".project") (-> (i/res->str (str "czlab/bixby/eclipse/java/project.txt")) (cs/replace "${APP.NAME}" pod) (cs/replace "${JAVA.TEST}" (u/fpath (io/file poddir "src/test/java"))) (cs/replace "${JAVA.SRC}" (u/fpath (io/file poddir "src/main/java"))) (cs/replace "${CLJ.TEST}" (u/fpath (io/file poddir "src/test/clojure"))) (cs/replace "${CLJ.SRC}" (u/fpath (io/file poddir "src/main/clojure"))))) (i/mkdirs (io/file poddir b/dn-build "classes")) (doall (map (partial scan-jars sb) [(io/file (b/get-proc-dir) b/dn-dist) (io/file (b/get-proc-dir) b/dn-lib) (io/file poddir b/dn-target)])) (i/spit-utf8 (io/file ec ".classpath") (-> (i/res->str (str "czlab/bixby/eclipse/java/classpath.txt")) (cs/replace "${CLASS.PATH.ENTRIES}" (str sb)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-ide "Help for action: ide." [] (on-help-xxx "usage.ide.d" 4)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-ide "Generate project files for IDEs." {:arglists '([args])} [args] (if-not (and (not-empty args) (c/in? #{"-e" "--eclipse"} (c/_1 args))) (u/throw-BadData "CmdError!") (gen-eclipse-proj (b/get-proc-dir)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-service-specs "Help for action: service." [] (on-help-xxx "usage.svc.d" 8)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-service-specs "Print out specs for built-in plugins." {:arglists '([args])} [args] (let [clj (u/cljrt<>)] (-> (c/preduce<map> #(assoc! %1 (c/_1 %2) (u/var* clj (str "czlab.bixby.plugs." (c/kw->str (c/_2 %2))))) {:OnceTimer :loops/OnceTimerSpec :FilePicker :files/FilePickerSpec :TCP :socket/TCPSpec :JMS :jms/JMSSpec :POP3 :mails/POP3Spec :IMAP :mails/IMAPSpec :HTTP :http/HTTPSpec :RepeatingTimer :loops/RepeatingTimerSpec}) i/fmt->edn c/prn!!))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-help-help "Help for action: help." {:arglists '([])} [] (u/throw-BadData "CmdError!")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def bixby-tasks nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-help "Print out help message for an action." {:arglists '([args])} [args] (c/if-fn [h (c/_2 (bixby-tasks (keyword (c/_1 args))))] (h) (u/throw-BadData "CmdError!"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (alter-var-root #'bixby-tasks (fn [_] {:new [on-create on-help-create] :ide [on-ide on-help-ide] :podify [on-podify on-help-podify] :debug [on-debug on-help-debug] :help [on-help on-help-help] :run [on-start on-help-start] :stop [on-stop on-help-stop] :demos [on-demos on-help-demos] :crypto [prn-generate on-help-generate] :version [on-version on-help-version] :service [on-service-specs on-help-service-specs]})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
true
;; 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. ;; ;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved. (ns czlab.bixby.cons.con1 (:require [czlab.cljant.antlib :as a] [io.aviso.ansi :as ansi] [clojure.string :as cs] [clojure.java.io :as io] [czlab.basal.io :as i] [czlab.basal.util :as u] [czlab.bixby.core :as b] [czlab.bixby.exec :as e] [czlab.twisty.core :as tc] [czlab.twisty.codec :as co] [czlab.bixby.cons.con2 :as c2] [czlab.basal.core :as c :refer [n#]]) (:import [java.util ResourceBundle Properties Calendar Map Date] [java.io DataOutputStream File] [java.net Socket InetAddress InetSocketAddress])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) (def ^:dynamic *config-object* nil) (def ^:dynamic *pkey-object* nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-xxx "Print out help messages." [pfx end] (try (dotimes [n end] (c/prn!! "%s" (u/rstr (b/get-rc-base) (str pfx (+ 1 n))))) (finally (c/prn!! "")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-create "Help for action: create." [] (on-help-xxx "usage.new.d" 5)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-create "Create a new pod." {:arglists '([args])} [args] (if (empty? args) (u/throw-BadData "CmdError!") (apply c2/create-pod (c/_1 args) (drop 1 args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-podify "Help for action: podify." [] (on-help-xxx "usage.podify.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-podify "Package app into a standalone app." {:arglists '([args])} [args] (if (empty? args) (u/throw-BadData "CmdError!") (let [a (io/file (b/get-proc-dir)) dir (i/mkdirs (io/file (c/_1 args)))] (a/run* (a/zip {:includes "**/*" :basedir a :destFile (io/file dir (str (.getName a) ".zip"))}))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-start "Help for action: start." [] (on-help-xxx "usage.start.d" 4)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-stop "Help for action: stop." [] (on-help-xxx "usage.stop.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- run-pod-bg "Run the application in the background." [podDir] (let [progW (io/file podDir "bin/bixby.bat") prog (io/file podDir "bin/bixby") tk (if (u/is-windows?) (a/exec {:dir podDir :executable "cmd.exe"} [[:argvalues ["/C" "start" "/B" "/MIN" (u/fpath progW) "run"]]]))] (if false (a/exec {:dir podDir :executable (u/fpath prog)} [[:argvalues ["run" "bg"]]])) ;run the target (if tk (a/run* tk) (u/throw-BadData "CmdError!")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-start "Start the application." {:arglists '([args])} [args] (let [s2 (c/_1 args) cwd (b/get-proc-dir)] ;; background job is handled differently on windows (if (and (u/is-windows?) (c/in? #{"-bg" "--background"} s2)) (run-pod-bg cwd) (do (-> b/banner ansi/bold-magenta c/prn!!) (e/start-via-cons cwd))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-stop [args] (c/try! (c/wo* [soc (Socket.)] (.connect soc (InetSocketAddress. (InetAddress/getLocalHost) (-> "bixby.kill.port" u/get-sys-prop (c/s->int 4444))) 5000) (let [os (.getOutputStream soc)] (-> (DataOutputStream. os) (.writeInt 117)) (.flush os))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-debug "Help for action: debug." [] (on-help-xxx "usage.debug.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-debug "Debug the application." {:arglists '([args])} [args] (on-start args)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-demos "Help for action :demo." [] (on-help-xxx "usage.demo.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-demos "Generate demo samples." {:arglists '([args])} [args] (if (empty? args) (u/throw-BadData "CmdError!") (c2/publish-samples (c/_1 args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gen-pwd "Generate a passord." {:arglists '([args])} [args] (let [c (c/_1 args) n (c/s->long (str c) 16)] (if-not (and (>= n 8) (<= n 48)) (u/throw-BadData "CmdError!") (-> n co/strong-pwd<> co/pw-text i/x->str)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gen-guid "Generate a UUID." {:arglists '([])} [] (u/uuid<>)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-encrypt "Encrypt some data." [args] (let [[s k] (cond (c/one? args) [(c/_1 args) *pkey-object*] (c/two? args) [(c/_2 args)(c/_1 args)] :else (u/throw-BadData "CmdError!"))] (try (-> (co/pwd<> s k) co/pw-encoded i/x->str) (catch Throwable e (c/prn!! "Failed to encrypt: %s." (u/emsg e)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-decrypt "Decrypt some data." [args] (let [[s k] (cond (c/one? args) [(c/_1 args) *pkey-object*] (c/two? args) [(c/_2 args)(c/_1 args)] :else (u/throw-BadData "CmdError!"))] (try (-> (co/pwd<> s k) co/pw-text i/x->str) (catch Throwable e (c/prn!! "Failed to decrypt: %s." (u/emsg e)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-hash "Generate a hash/digest on the data." [args] (if-not (empty? args) (tc/gen-digest (c/_1 args)) (u/throw-BadData "CmdError!"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-mac "Generate a MAC on the data." [args] (if (empty? args) (u/throw-BadData "CmdError!") (tc/gen-mac *pkey-object* (c/_1 args)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-generate "Help for action: generate." [] (on-help-xxx "usage.gen.d" 9)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-generate "Various generate functions." {:arglists '([args])} [args] (let [c (c/_1 args) args (drop 1 args)] (cond (c/in? #{"-p" "--password"} c) (gen-pwd args) (c/in? #{"-h" "--hash"} c) (on-hash args) (c/in? #{"-m" "--mac"} c) (on-mac args) (c/in? #{"-u" "--uuid"} c) (gen-guid) (c/in? #{"-e" "--encrypt"} c) (on-encrypt args) (c/in? #{"-d" "--decrypt"} c) (on-decrypt args) :else (u/throw-BadData "CmdError!")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn prn-generate "Print from the function." {:arglists '([args])} [args] (c/prn!! "%s" (on-generate args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-version "Help for action: version." [] (on-help-xxx "usage.version.d" 2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-version "Print out the version." {:arglists '([args])} [args] (let [rcb (b/get-rc-base)] (->> (u/get-sys-prop "bixby.version") (u/rstr rcb "usage.version.o1") (c/prn!! "%s" )) (->> (u/get-sys-prop "java.version") (u/rstr rcb "usage.version.o2") (c/prn!! "%s")) (c/prn!! ""))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- scan-jars "Scan a directory for jar files and list the file paths." [out dir] (let [sep (u/get-sys-prop "line.separator")] (c/sbf+ out (c/sreduce<> #(c/sbf+ %1 (str "<classpathentry " "kind=\"lib\"" " path=\"" (u/fpath %2) "\"/>" sep)) (i/list-files dir ".jar"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- gen-eclipse-proj "Generate a eclipse project file." [pdir] (let [ec (io/file pdir "eclipse.projfiles") poddir (io/file pdir) pod (i/fname poddir) sb (c/sbf<>)] (i/mkdirs ec) (i/clean-dir ec) (i/spit-utf8 (io/file ec ".project") (-> (i/res->str (str "czlab/bixby/eclipse/java/project.txt")) (cs/replace "${APP.NAME}" pod) (cs/replace "${JAVA.TEST}" (u/fpath (io/file poddir "src/test/java"))) (cs/replace "${JAVA.SRC}" (u/fpath (io/file poddir "src/main/java"))) (cs/replace "${CLJ.TEST}" (u/fpath (io/file poddir "src/test/clojure"))) (cs/replace "${CLJ.SRC}" (u/fpath (io/file poddir "src/main/clojure"))))) (i/mkdirs (io/file poddir b/dn-build "classes")) (doall (map (partial scan-jars sb) [(io/file (b/get-proc-dir) b/dn-dist) (io/file (b/get-proc-dir) b/dn-lib) (io/file poddir b/dn-target)])) (i/spit-utf8 (io/file ec ".classpath") (-> (i/res->str (str "czlab/bixby/eclipse/java/classpath.txt")) (cs/replace "${CLASS.PATH.ENTRIES}" (str sb)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-ide "Help for action: ide." [] (on-help-xxx "usage.ide.d" 4)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-ide "Generate project files for IDEs." {:arglists '([args])} [args] (if-not (and (not-empty args) (c/in? #{"-e" "--eclipse"} (c/_1 args))) (u/throw-BadData "CmdError!") (gen-eclipse-proj (b/get-proc-dir)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- on-help-service-specs "Help for action: service." [] (on-help-xxx "usage.svc.d" 8)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-service-specs "Print out specs for built-in plugins." {:arglists '([args])} [args] (let [clj (u/cljrt<>)] (-> (c/preduce<map> #(assoc! %1 (c/_1 %2) (u/var* clj (str "czlab.bixby.plugs." (c/kw->str (c/_2 %2))))) {:OnceTimer :loops/OnceTimerSpec :FilePicker :files/FilePickerSpec :TCP :socket/TCPSpec :JMS :jms/JMSSpec :POP3 :mails/POP3Spec :IMAP :mails/IMAPSpec :HTTP :http/HTTPSpec :RepeatingTimer :loops/RepeatingTimerSpec}) i/fmt->edn c/prn!!))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-help-help "Help for action: help." {:arglists '([])} [] (u/throw-BadData "CmdError!")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def bixby-tasks nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn on-help "Print out help message for an action." {:arglists '([args])} [args] (c/if-fn [h (c/_2 (bixby-tasks (keyword (c/_1 args))))] (h) (u/throw-BadData "CmdError!"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (alter-var-root #'bixby-tasks (fn [_] {:new [on-create on-help-create] :ide [on-ide on-help-ide] :podify [on-podify on-help-podify] :debug [on-debug on-help-debug] :help [on-help on-help-help] :run [on-start on-help-start] :stop [on-stop on-help-stop] :demos [on-demos on-help-demos] :crypto [prn-generate on-help-generate] :version [on-version on-help-version] :service [on-service-specs on-help-service-specs]})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": " \"\" (Process.Run \"ganache-cli\" [\"-d\" \"-f\" \"http://192.168.1.4:8545\" \">\" \"_\"])))\n\n(def test\n (Chain\n \"one spl", "end": 210, "score": 0.9000473618507385, "start": 199, "tag": "IP_ADDRESS", "value": "192.168.1.4" }, { "context": "0)\n ; setup our node to default\n (Eth \"http://127.0.0.1:8545\")\n (Eth.Unlock \"0x90F8bf6A479f320ead074411", "end": 369, "score": 0.99077308177948, "start": 360, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "eeeeeeEEeE\" >> .args ; from token (ETH)\n \"0x6b175474e89094c44da98b954eedeac495271d0f\" >> .args ; to ", "end": 1459, "score": 0.5448917150497437, "start": 1457, "tag": "KEY", "value": "54" }, { "context": "eeeEEeE\" >> .args ; from token (ETH)\n \"0x6b175474e89094c44da98b954eedeac495271d0f\" >> .args ; to to", "end": 1461, "score": 0.544979453086853, "start": 1460, "tag": "KEY", "value": "4" }, { "context": "EEeE\" >> .args ; from token (ETH)\n \"0x6b175474e89094c44da98b954eedeac495271d0f\" >> .args ; to token (DAI)\n 1 (BigInt) (BigInt.", "end": 1493, "score": 0.6688340306282043, "start": 1463, "tag": "KEY", "value": "9094c44da98b954eedeac495271d0f" }, { "context": "hain\n \"one split test\"\n :Looped\n (Eth \"ws://192.168.1.4:8546\")\n (Eth.Contract :Contract \"0x6b175474e890", "end": 1979, "score": 0.999176561832428, "start": 1968, "tag": "IP_ADDRESS", "value": "192.168.1.4" } ]
tests/test.clj
fragcolor-xyz/chainblocks-web3
0
(import "../target/debug/web3.dll") (import "../target/debug/libweb3.dylib") (def Root (Node)) (def ganache (Chain "run-ganache" :Looped "" (Process.Run "ganache-cli" ["-d" "-f" "http://192.168.1.4:8545" ">" "_"]))) (def test (Chain "one split test" :Looped ; wait ganache (Pause 2.0) ; setup our node to default (Eth "http://127.0.0.1:8545") (Eth.Unlock "0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1") ; Load our contract (Eth.Contract :Name "one-split" :Contract "0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E" :Abi (slurp "onesplit.json")) ; Make a constant call "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" >> .args ; from token (ETH) "0x6b175474e89094c44da98b954eedeac495271d0f" >> .args ; to token (DAI) 1 (BigInt) (BigInt.Shift 18) >> .args ; amount 100 >> .args ; parts 0 >> .args ; disable flags .args (Eth.Read :Contract .one-split :Method "getExpectedReturn") (Log) >= .res ; Print results .res (Take 0) (ExpectBytes) >= .expected (BigInt.ToFloat -18) (Log "price") .res (Take 1) (ExpectSeq) >= .distribution (ForEach #((ExpectBytes) (BigInt.ToFloat) (Log "dexes"))) (Clear .args) 1 (BigInt) (BigInt.Shift 18) (Set "options" "value") (Eth.GasPrice) (Set "options" "gas-price") "500000" (BigInt) (Set "options" "gas") "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" >> .args ; from token (ETH) "0x6b175474e89094c44da98b954eedeac495271d0f" >> .args ; to token (DAI) 1 (BigInt) (BigInt.Shift 18) >> .args ; amount .expected >> .args ; min return .distribution >> .args ; distribution 0 >> .args ; flags .args (Eth.Write :Contract .one-split :Method "swap" :From "0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1" :Options .options :Confirmations 0) (Log) ; the end )) (def ws-test (Chain "one split test" :Looped (Eth "ws://192.168.1.4:8546") (Eth.Contract :Contract "0x6b175474e89094c44da98b954eedeac495271d0f" :Abi (slurp "dai.json")) (Eth.WaitEvent :Event "Transfer") (Log "Log") (Take "transaction_hash") (ExpectBytes) (Eth.Transaction) (Log "Tx"))) (defchain test-Block (Eth "https://cloudflare-eth.com") 1000000 (Eth.Block :Full true) (Log)) ;; (schedule Root ganache) ;; (schedule Root test) ;; (schedule Root ws-test) (schedule Root test-Block) (run Root 0.1) (def test nil) (def Root nil)
63284
(import "../target/debug/web3.dll") (import "../target/debug/libweb3.dylib") (def Root (Node)) (def ganache (Chain "run-ganache" :Looped "" (Process.Run "ganache-cli" ["-d" "-f" "http://192.168.1.4:8545" ">" "_"]))) (def test (Chain "one split test" :Looped ; wait ganache (Pause 2.0) ; setup our node to default (Eth "http://127.0.0.1:8545") (Eth.Unlock "0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1") ; Load our contract (Eth.Contract :Name "one-split" :Contract "0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E" :Abi (slurp "onesplit.json")) ; Make a constant call "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" >> .args ; from token (ETH) "0x6b175474e89094c44da98b954eedeac495271d0f" >> .args ; to token (DAI) 1 (BigInt) (BigInt.Shift 18) >> .args ; amount 100 >> .args ; parts 0 >> .args ; disable flags .args (Eth.Read :Contract .one-split :Method "getExpectedReturn") (Log) >= .res ; Print results .res (Take 0) (ExpectBytes) >= .expected (BigInt.ToFloat -18) (Log "price") .res (Take 1) (ExpectSeq) >= .distribution (ForEach #((ExpectBytes) (BigInt.ToFloat) (Log "dexes"))) (Clear .args) 1 (BigInt) (BigInt.Shift 18) (Set "options" "value") (Eth.GasPrice) (Set "options" "gas-price") "500000" (BigInt) (Set "options" "gas") "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" >> .args ; from token (ETH) "0x6b17<KEY>7<KEY>e8<KEY>" >> .args ; to token (DAI) 1 (BigInt) (BigInt.Shift 18) >> .args ; amount .expected >> .args ; min return .distribution >> .args ; distribution 0 >> .args ; flags .args (Eth.Write :Contract .one-split :Method "swap" :From "0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1" :Options .options :Confirmations 0) (Log) ; the end )) (def ws-test (Chain "one split test" :Looped (Eth "ws://192.168.1.4:8546") (Eth.Contract :Contract "0x6b175474e89094c44da98b954eedeac495271d0f" :Abi (slurp "dai.json")) (Eth.WaitEvent :Event "Transfer") (Log "Log") (Take "transaction_hash") (ExpectBytes) (Eth.Transaction) (Log "Tx"))) (defchain test-Block (Eth "https://cloudflare-eth.com") 1000000 (Eth.Block :Full true) (Log)) ;; (schedule Root ganache) ;; (schedule Root test) ;; (schedule Root ws-test) (schedule Root test-Block) (run Root 0.1) (def test nil) (def Root nil)
true
(import "../target/debug/web3.dll") (import "../target/debug/libweb3.dylib") (def Root (Node)) (def ganache (Chain "run-ganache" :Looped "" (Process.Run "ganache-cli" ["-d" "-f" "http://192.168.1.4:8545" ">" "_"]))) (def test (Chain "one split test" :Looped ; wait ganache (Pause 2.0) ; setup our node to default (Eth "http://127.0.0.1:8545") (Eth.Unlock "0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1") ; Load our contract (Eth.Contract :Name "one-split" :Contract "0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E" :Abi (slurp "onesplit.json")) ; Make a constant call "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" >> .args ; from token (ETH) "0x6b175474e89094c44da98b954eedeac495271d0f" >> .args ; to token (DAI) 1 (BigInt) (BigInt.Shift 18) >> .args ; amount 100 >> .args ; parts 0 >> .args ; disable flags .args (Eth.Read :Contract .one-split :Method "getExpectedReturn") (Log) >= .res ; Print results .res (Take 0) (ExpectBytes) >= .expected (BigInt.ToFloat -18) (Log "price") .res (Take 1) (ExpectSeq) >= .distribution (ForEach #((ExpectBytes) (BigInt.ToFloat) (Log "dexes"))) (Clear .args) 1 (BigInt) (BigInt.Shift 18) (Set "options" "value") (Eth.GasPrice) (Set "options" "gas-price") "500000" (BigInt) (Set "options" "gas") "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" >> .args ; from token (ETH) "0x6b17PI:KEY:<KEY>END_PI7PI:KEY:<KEY>END_PIe8PI:KEY:<KEY>END_PI" >> .args ; to token (DAI) 1 (BigInt) (BigInt.Shift 18) >> .args ; amount .expected >> .args ; min return .distribution >> .args ; distribution 0 >> .args ; flags .args (Eth.Write :Contract .one-split :Method "swap" :From "0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1" :Options .options :Confirmations 0) (Log) ; the end )) (def ws-test (Chain "one split test" :Looped (Eth "ws://192.168.1.4:8546") (Eth.Contract :Contract "0x6b175474e89094c44da98b954eedeac495271d0f" :Abi (slurp "dai.json")) (Eth.WaitEvent :Event "Transfer") (Log "Log") (Take "transaction_hash") (ExpectBytes) (Eth.Transaction) (Log "Tx"))) (defchain test-Block (Eth "https://cloudflare-eth.com") 1000000 (Eth.Block :Full true) (Log)) ;; (schedule Root ganache) ;; (schedule Root test) ;; (schedule Root ws-test) (schedule Root test-Block) (run Root 0.1) (def test nil) (def Root nil)
[ { "context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;\n;; Copyright (c) 2008, J. Bester\n;; All rights reserved.\n;;\n;; Redistribution and ", "end": 247, "score": 0.9998881816864014, "start": 238, "tag": "NAME", "value": "J. Bester" }, { "context": "cal formula to prefix expressions\"\n :author \"J. Bester\"}\n org.mobileink.migae.infix\n (:refer-clojure :", "end": 1842, "score": 0.9998810887336731, "start": 1833, "tag": "NAME", "value": "J. Bester" } ]
datastore/src/org/mobileink/migae/infix.clj
mobileink/migae
0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; File : infix.clj ;; Function : Infix Math library ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Copyright (c) 2008, J. Bester ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; * Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY ;; EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY ;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; from ;; https://github.com/liebke/incanter/tree/master/modules/incanter-core/src/incanter (ns ^{:doc "Library for converting infix mathematical formula to prefix expressions" :author "J. Bester"} org.mobileink.migae.infix (:refer-clojure :exclude [filter])) ;; operator precedence for formula macro (def +precedence-table+ (atom {})) ;; symbol translation for symbols in formula (only supports binary operators) (def +translation-table+ (atom {})) (def +highest-precedence+ (atom 0)) (defn defop "Define operators for formula macro" ([op prec & [trans]] (swap! +precedence-table+ assoc op prec) (when-not (nil? trans) (swap! +translation-table+ assoc op trans)) (reset! +highest-precedence+ (reduce max (map val @+precedence-table+))))) ;; == operators == (defop '|| 10 "CompositeFilterOperator.or") (defop '&& 20 "CompositeFilterOperator.and") (defop '= 30 "FilterOperator.EQUAL") (defop '!= 30 "FilterOperator.NOT_EQUAL") (defop '< 40 "FilterOperator.LESS_THAN") (defop '> 40 "FilterOperator.GREATER_THAN") (defop '<= 40 "FilterOperator.LESS_THAN_OR_EQUAL") (defop '>= 40 "FilterOperator.GREATER_THAN_OR_EQUAL") (defop '<= 40 "FilterOperator.LESS_THAN_OR_EQUAL") (defop 'in 40 "FilterOperator.IN") ;; (defop '- 60 '-) ;; (defop '+ 60 '+) ;; (defop '/ 80 '/) ;; (defop '* 80 '*) (defn- operator? "Check if is valid operator" ([sym] (not (nil? (get @+precedence-table+ sym))))) (defn- find-lowest-precedence "find the operator with lowest precedence; search from left to right" ([col] ;; loop through terms in the coluence (loop [idx 0 col col lowest-idx nil lowest-prec @+highest-precedence+] ;; nothing left to process (if (empty? col) ;; return lowest found lowest-idx ;; otherwise check if current term is lower (let [prec (get @+precedence-table+ (first col))] ;; is of lower or equal precedence (if (and prec (<= prec lowest-prec)) (recur (inc idx) (rest col) idx prec) ;; is of high precedence therefore skip for now (recur (inc idx) (rest col) lowest-idx lowest-prec))))))) (defn- translate-op "Translation of symbol => symbol for binary op allows for user defined operators" ([op] (get @+translation-table+ op op))) (defn infix-to-prefix "Convert from infix notation to prefix notation" ([col] (cond ;; handle term only (not (seq? col)) col ;; handle sequence containing one term (i.e. handle parens) (= (count col) 1) (infix-to-prefix (first col)) ;; handle all other cases true (let [lowest (find-lowest-precedence col)] (if (nil? lowest) ;; nothing to split col ;; (a b c) bind a to hd, c to tl, and b to op (let [[hd [op & tl]] (split-at lowest col)] ;; (println "hd: " hd) ;; (println "op: " op) ;; (println (format "tl: %s\n" tl)) ;; recurse (vector ;; list (infix-to-prefix hd) (translate-op op) (infix-to-prefix tl)))))))) (defmacro $= "Formula macro translates from infix to gae query syntax" ([& equation] ; (do (println "form: " equation) (vec (infix-to-prefix equation)))) (defmacro filter "Formula macro translates from infix to gae query syntax" ([& equation] (vec (infix-to-prefix equation))))
62979
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; File : infix.clj ;; Function : Infix Math library ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Copyright (c) 2008, <NAME> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; * Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY ;; EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY ;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; from ;; https://github.com/liebke/incanter/tree/master/modules/incanter-core/src/incanter (ns ^{:doc "Library for converting infix mathematical formula to prefix expressions" :author "<NAME>"} org.mobileink.migae.infix (:refer-clojure :exclude [filter])) ;; operator precedence for formula macro (def +precedence-table+ (atom {})) ;; symbol translation for symbols in formula (only supports binary operators) (def +translation-table+ (atom {})) (def +highest-precedence+ (atom 0)) (defn defop "Define operators for formula macro" ([op prec & [trans]] (swap! +precedence-table+ assoc op prec) (when-not (nil? trans) (swap! +translation-table+ assoc op trans)) (reset! +highest-precedence+ (reduce max (map val @+precedence-table+))))) ;; == operators == (defop '|| 10 "CompositeFilterOperator.or") (defop '&& 20 "CompositeFilterOperator.and") (defop '= 30 "FilterOperator.EQUAL") (defop '!= 30 "FilterOperator.NOT_EQUAL") (defop '< 40 "FilterOperator.LESS_THAN") (defop '> 40 "FilterOperator.GREATER_THAN") (defop '<= 40 "FilterOperator.LESS_THAN_OR_EQUAL") (defop '>= 40 "FilterOperator.GREATER_THAN_OR_EQUAL") (defop '<= 40 "FilterOperator.LESS_THAN_OR_EQUAL") (defop 'in 40 "FilterOperator.IN") ;; (defop '- 60 '-) ;; (defop '+ 60 '+) ;; (defop '/ 80 '/) ;; (defop '* 80 '*) (defn- operator? "Check if is valid operator" ([sym] (not (nil? (get @+precedence-table+ sym))))) (defn- find-lowest-precedence "find the operator with lowest precedence; search from left to right" ([col] ;; loop through terms in the coluence (loop [idx 0 col col lowest-idx nil lowest-prec @+highest-precedence+] ;; nothing left to process (if (empty? col) ;; return lowest found lowest-idx ;; otherwise check if current term is lower (let [prec (get @+precedence-table+ (first col))] ;; is of lower or equal precedence (if (and prec (<= prec lowest-prec)) (recur (inc idx) (rest col) idx prec) ;; is of high precedence therefore skip for now (recur (inc idx) (rest col) lowest-idx lowest-prec))))))) (defn- translate-op "Translation of symbol => symbol for binary op allows for user defined operators" ([op] (get @+translation-table+ op op))) (defn infix-to-prefix "Convert from infix notation to prefix notation" ([col] (cond ;; handle term only (not (seq? col)) col ;; handle sequence containing one term (i.e. handle parens) (= (count col) 1) (infix-to-prefix (first col)) ;; handle all other cases true (let [lowest (find-lowest-precedence col)] (if (nil? lowest) ;; nothing to split col ;; (a b c) bind a to hd, c to tl, and b to op (let [[hd [op & tl]] (split-at lowest col)] ;; (println "hd: " hd) ;; (println "op: " op) ;; (println (format "tl: %s\n" tl)) ;; recurse (vector ;; list (infix-to-prefix hd) (translate-op op) (infix-to-prefix tl)))))))) (defmacro $= "Formula macro translates from infix to gae query syntax" ([& equation] ; (do (println "form: " equation) (vec (infix-to-prefix equation)))) (defmacro filter "Formula macro translates from infix to gae query syntax" ([& equation] (vec (infix-to-prefix equation))))
true
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; File : infix.clj ;; Function : Infix Math library ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Copyright (c) 2008, PI:NAME:<NAME>END_PI ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; * Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY ;; EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY ;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; from ;; https://github.com/liebke/incanter/tree/master/modules/incanter-core/src/incanter (ns ^{:doc "Library for converting infix mathematical formula to prefix expressions" :author "PI:NAME:<NAME>END_PI"} org.mobileink.migae.infix (:refer-clojure :exclude [filter])) ;; operator precedence for formula macro (def +precedence-table+ (atom {})) ;; symbol translation for symbols in formula (only supports binary operators) (def +translation-table+ (atom {})) (def +highest-precedence+ (atom 0)) (defn defop "Define operators for formula macro" ([op prec & [trans]] (swap! +precedence-table+ assoc op prec) (when-not (nil? trans) (swap! +translation-table+ assoc op trans)) (reset! +highest-precedence+ (reduce max (map val @+precedence-table+))))) ;; == operators == (defop '|| 10 "CompositeFilterOperator.or") (defop '&& 20 "CompositeFilterOperator.and") (defop '= 30 "FilterOperator.EQUAL") (defop '!= 30 "FilterOperator.NOT_EQUAL") (defop '< 40 "FilterOperator.LESS_THAN") (defop '> 40 "FilterOperator.GREATER_THAN") (defop '<= 40 "FilterOperator.LESS_THAN_OR_EQUAL") (defop '>= 40 "FilterOperator.GREATER_THAN_OR_EQUAL") (defop '<= 40 "FilterOperator.LESS_THAN_OR_EQUAL") (defop 'in 40 "FilterOperator.IN") ;; (defop '- 60 '-) ;; (defop '+ 60 '+) ;; (defop '/ 80 '/) ;; (defop '* 80 '*) (defn- operator? "Check if is valid operator" ([sym] (not (nil? (get @+precedence-table+ sym))))) (defn- find-lowest-precedence "find the operator with lowest precedence; search from left to right" ([col] ;; loop through terms in the coluence (loop [idx 0 col col lowest-idx nil lowest-prec @+highest-precedence+] ;; nothing left to process (if (empty? col) ;; return lowest found lowest-idx ;; otherwise check if current term is lower (let [prec (get @+precedence-table+ (first col))] ;; is of lower or equal precedence (if (and prec (<= prec lowest-prec)) (recur (inc idx) (rest col) idx prec) ;; is of high precedence therefore skip for now (recur (inc idx) (rest col) lowest-idx lowest-prec))))))) (defn- translate-op "Translation of symbol => symbol for binary op allows for user defined operators" ([op] (get @+translation-table+ op op))) (defn infix-to-prefix "Convert from infix notation to prefix notation" ([col] (cond ;; handle term only (not (seq? col)) col ;; handle sequence containing one term (i.e. handle parens) (= (count col) 1) (infix-to-prefix (first col)) ;; handle all other cases true (let [lowest (find-lowest-precedence col)] (if (nil? lowest) ;; nothing to split col ;; (a b c) bind a to hd, c to tl, and b to op (let [[hd [op & tl]] (split-at lowest col)] ;; (println "hd: " hd) ;; (println "op: " op) ;; (println (format "tl: %s\n" tl)) ;; recurse (vector ;; list (infix-to-prefix hd) (translate-op op) (infix-to-prefix tl)))))))) (defmacro $= "Formula macro translates from infix to gae query syntax" ([& equation] ; (do (println "form: " equation) (vec (infix-to-prefix equation)))) (defmacro filter "Formula macro translates from infix to gae query syntax" ([& equation] (vec (infix-to-prefix equation))))
[ { "context": "ftest test-encrypted-kv-store\n (let [passwords [\"test1\" \"test2\" \"test3\"]\n processed-passwords (ma", "end": 3011, "score": 0.9937761425971985, "start": 3006, "tag": "PASSWORD", "value": "test1" }, { "context": "st-encrypted-kv-store\n (let [passwords [\"test1\" \"test2\" \"test3\"]\n processed-passwords (mapv #(vec", "end": 3019, "score": 0.9917972087860107, "start": 3014, "tag": "PASSWORD", "value": "test2" }, { "context": "pted-kv-store\n (let [passwords [\"test1\" \"test2\" \"test3\"]\n processed-passwords (mapv #(vector :cac", "end": 3027, "score": 0.9916475415229797, "start": 3022, "tag": "PASSWORD", "value": "test3" } ]
waiter/test/waiter/kv_test.clj
twosigmajab/waiter
1
;; ;; Copyright (c) Two Sigma Open Source, LLC ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns waiter.kv-test (:require [clj-time.core :as t] [clojure.java.io :as io] [clojure.test :refer :all] [waiter.curator :as curator] [waiter.kv :as kv]) (:import (java.util Arrays) (org.apache.curator.framework CuratorFrameworkFactory CuratorFramework) (org.apache.curator.retry RetryNTimes))) (deftest test-local-kv-store (let [test-store (kv/new-local-kv-store {}) bytes (byte-array 10)] (Arrays/fill bytes (byte 1)) (is (nil? (kv/fetch test-store :a))) (kv/store test-store :a bytes) (is (Arrays/equals bytes ^bytes (kv/fetch test-store :a))) (kv/store test-store :a 3) (is (= 3 (kv/fetch test-store :a))) (is (nil? (kv/fetch test-store :b))) (is (= {:store {:count 1, :data {:a 3}}, :variant "in-memory"} (kv/state test-store))) (kv/delete test-store :a) (is (nil? (kv/fetch test-store :a))) (is (nil? (kv/fetch test-store :b))) (kv/delete test-store :does-not-exist) (is (= {:store {:count 0, :data {}}, :variant "in-memory"} (kv/state test-store))))) (defn work-dir "Returns the canonical path for the ./kv-store directory" [] (-> "./kv-store" (io/file) (.getCanonicalPath))) (deftest test-file-based-kv-store (let [target-file (str (work-dir) "/foo.bin")] (let [test-store (kv/new-file-based-kv-store {:target-file target-file}) bytes (byte-array 10)] (Arrays/fill bytes (byte 1)) (is (nil? (kv/fetch test-store :a))) (kv/store test-store :a bytes) (is (Arrays/equals bytes ^bytes (kv/fetch test-store :a))) (kv/store test-store :a 3) (is (= 3 (kv/fetch test-store :a))) (is (nil? (kv/fetch test-store :b))) (is (= {:store {:count 1, :data {:a 3}}, :variant "file-based"} (kv/state test-store)))) ;; testing data was persisted in the file (let [test-store (kv/new-file-based-kv-store {:target-file target-file})] (is (= {:store {:count 1, :data {:a 3}}, :variant "file-based"} (kv/state test-store))) (kv/delete test-store :a) (is (nil? (kv/fetch test-store :a))) (is (nil? (kv/fetch test-store :b))) (kv/delete test-store :does-not-exist) (is (= {:store {:count 0, :data {}}, :variant "file-based"} (kv/state test-store)))))) (deftest test-encrypted-kv-store (let [passwords ["test1" "test2" "test3"] processed-passwords (mapv #(vector :cached %) passwords) local-kv-store (kv/new-local-kv-store {}) encrypted-kv-store (kv/new-encrypted-kv-store processed-passwords local-kv-store)] (is (nil? (kv/fetch local-kv-store :a))) (is (nil? (kv/fetch encrypted-kv-store :a))) (is (nil? (kv/fetch local-kv-store :b))) (is (nil? (kv/fetch encrypted-kv-store :b))) ; store propagates to underlying store (kv/store encrypted-kv-store :b 2) (is (not (nil? (kv/fetch local-kv-store :b)))) (is (= 2 (kv/fetch encrypted-kv-store :b))) ; store does not corrupt underlying store (kv/store encrypted-kv-store :a 5) (is (not (nil? (kv/fetch local-kv-store :a)))) (is (= 5 (kv/fetch encrypted-kv-store :a))) (is (not (nil? (kv/fetch local-kv-store :b)))) (is (= 2 (kv/fetch encrypted-kv-store :b))) ; store updates underlying store (kv/store encrypted-kv-store :b 11) (is (not (nil? (kv/fetch local-kv-store :b)))) (is (= 11 (kv/fetch encrypted-kv-store :b))) (is (= "encrypted" (get (kv/state encrypted-kv-store) :variant))) (is (= 2 (get-in (kv/state encrypted-kv-store) [:inner-state :store :count]))) (is (= #{:a :b} (set (keys (get-in (kv/state encrypted-kv-store) [:inner-state :store :data]))))) ; delete :a and :b (kv/delete encrypted-kv-store :a) (is (nil? (kv/fetch local-kv-store :a))) (is (nil? (kv/fetch encrypted-kv-store :a))) (kv/delete encrypted-kv-store :b) (is (nil? (kv/fetch local-kv-store :b))) (is (nil? (kv/fetch encrypted-kv-store :b))) (is (= "encrypted" (get (kv/state encrypted-kv-store) :variant))) (is (= {:count 0, :data {}} (get-in (kv/state encrypted-kv-store) [:inner-state :store]))) (kv/delete encrypted-kv-store :does-not-exist))) (deftest test-cached-kv-store (let [cache-config {:threshold 1000 :ttl (-> 60 t/seconds t/in-millis)} local-kv-store (kv/new-local-kv-store {}) cached-kv-store (kv/new-cached-kv-store cache-config local-kv-store)] (is (nil? (kv/fetch local-kv-store :a))) (is (nil? (kv/fetch cached-kv-store :a))) (kv/store local-kv-store :a 1) ; cache looks up underlying store during miss (is (kv/fetch local-kv-store :a)) (is (= 1 (kv/fetch local-kv-store :a))) (is (nil? (kv/fetch cached-kv-store :a))) ; store to cache propagates to underlying store (kv/store cached-kv-store :b 2) (is (= 2 (kv/fetch cached-kv-store :b))) (is (= 2 (kv/fetch local-kv-store :b))) (kv/store cached-kv-store :b 11) (is (= 11 (kv/fetch cached-kv-store :b))) (is (= 11 (kv/fetch local-kv-store :b))) ; cache works with refresh call (kv/store cached-kv-store :b 13) (is (= 13 (kv/fetch cached-kv-store :b))) (kv/store local-kv-store :b 17) (is (= 13 (kv/fetch cached-kv-store :b))) (is (= 17 (kv/fetch local-kv-store :b))) (is (= 17 (kv/fetch cached-kv-store :b :refresh true))) (is (= "cache" (get (kv/state cached-kv-store) :variant))) (is (= {:count 2, :data {:a 1, :b 17}} (get-in (kv/state cached-kv-store) [:inner-state :store]))) ; delete removes entry from cache (kv/delete cached-kv-store :b) (is (nil? (kv/fetch local-kv-store :b))) (is (nil? (kv/fetch cached-kv-store :b))) (is (nil? (kv/fetch cached-kv-store :b :refresh true))) (is (= "cache" (get (kv/state cached-kv-store) :variant))) (is (= {:count 1, :data {:a 1}} (get-in (kv/state cached-kv-store) [:inner-state :store]))))) (deftest test-validate-zk-key (kv/validate-zk-key "test-key") (is (thrown-with-msg? Exception #"Key may not contain '/'" (kv/validate-zk-key "evil-key/evil-key"))) (is (thrown-with-msg? Exception #"Key may not begin with '.'" (kv/validate-zk-key "..")))) (deftest test-key->zk-key (is (= "/base/6f1e/blah" (kv/key->zk-path "/base" "blah"))) (is (= "/base2/42d3/blahblah" (kv/key->zk-path "/base2" "blahblah")))) (deftest test-zk-kv-store (let [zk (curator/start-in-process-zookeeper) zk-server (:zk-server zk) curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100)) services-base-path "/test-zk-kv-store/base-path"] (is (kv/new-zk-kv-store {:curator curator :base-path "/waiter-tokens" :sync-timeout-ms 1})) (try (.start curator) (testing "in-memory-zk" (let [get-value-from-curator (fn [key] (.forPath (.checkExists curator) (kv/key->zk-path services-base-path key))) test-store (kv/new-zk-kv-store {:curator curator :base-path services-base-path :sync-timeout-ms 1}) bytes (byte-array 10)] (Arrays/fill bytes (byte 1)) (is (nil? (kv/fetch test-store "a"))) (is (nil? (get-value-from-curator "a"))) (kv/store test-store "a" bytes) (is (Arrays/equals bytes ^bytes (kv/fetch test-store "a"))) (is (not (nil? (get-value-from-curator "a")))) (kv/store test-store "a" 3) (is (= 3 (kv/fetch test-store "a"))) (is (not (nil? (get-value-from-curator "a")))) (is (nil? (kv/fetch test-store "b"))) (is (nil? (get-value-from-curator "b"))) (kv/delete test-store "a") (is (nil? (kv/fetch test-store "a"))) (is (nil? (get-value-from-curator "a"))) (is (nil? (kv/fetch test-store "b"))) (is (nil? (get-value-from-curator "b"))) (kv/delete test-store "does-not-exist") (is (nil? (get-value-from-curator "does-not-exist"))) (is (= {:base-path services-base-path, :variant "zookeeper"} (kv/state test-store))))) (finally (.close curator) (.stop zk-server))))) (deftest test-new-kv-store (let [base-path "/waiter" kv-config {:kind :zk :zk {:factory-fn 'waiter.kv/new-zk-kv-store :sync-timeout-ms 2000} :relative-path "tokens"} zk (curator/start-in-process-zookeeper) zk-server (:zk-server zk) curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100)) kv-store (kv/new-kv-store kv-config curator base-path nil)] (try (.start curator) (kv/store kv-store "foo" "bar") (is (= "bar" (kv/retrieve kv-store "foo" true))) (finally (.close curator) (.stop zk-server))))) (deftest test-new-zk-kv-store (testing "Creating a new ZooKeeper key/value store" (testing "should throw on non-integer sync-timeout-ms" (is (thrown? AssertionError (kv/new-zk-kv-store {:curator (reify CuratorFramework) :base-path "" :sync-timeout-ms 1.1})))))) (deftest test-zk-keys (testing "List ZK keys" (let [base-path "/waiter" kv-config {:kind :zk :zk {:factory-fn 'waiter.kv/new-zk-kv-store :sync-timeout-ms 2000} :relative-path "tokens"} zk (curator/start-in-process-zookeeper) zk-server (:zk-server zk) curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100)) kv-store (kv/new-kv-store kv-config curator base-path nil)] (try (.start curator) (kv/store kv-store "foo" "bar") (kv/store kv-store "foo2" "bar2") (kv/store kv-store "foo3" "bar3") (is (= #{"foo" "foo2" "foo3"} (set (kv/zk-keys curator (str base-path "/" (:relative-path kv-config)))))) (finally (.close curator) (.stop zk-server))))))
7114
;; ;; Copyright (c) Two Sigma Open Source, LLC ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns waiter.kv-test (:require [clj-time.core :as t] [clojure.java.io :as io] [clojure.test :refer :all] [waiter.curator :as curator] [waiter.kv :as kv]) (:import (java.util Arrays) (org.apache.curator.framework CuratorFrameworkFactory CuratorFramework) (org.apache.curator.retry RetryNTimes))) (deftest test-local-kv-store (let [test-store (kv/new-local-kv-store {}) bytes (byte-array 10)] (Arrays/fill bytes (byte 1)) (is (nil? (kv/fetch test-store :a))) (kv/store test-store :a bytes) (is (Arrays/equals bytes ^bytes (kv/fetch test-store :a))) (kv/store test-store :a 3) (is (= 3 (kv/fetch test-store :a))) (is (nil? (kv/fetch test-store :b))) (is (= {:store {:count 1, :data {:a 3}}, :variant "in-memory"} (kv/state test-store))) (kv/delete test-store :a) (is (nil? (kv/fetch test-store :a))) (is (nil? (kv/fetch test-store :b))) (kv/delete test-store :does-not-exist) (is (= {:store {:count 0, :data {}}, :variant "in-memory"} (kv/state test-store))))) (defn work-dir "Returns the canonical path for the ./kv-store directory" [] (-> "./kv-store" (io/file) (.getCanonicalPath))) (deftest test-file-based-kv-store (let [target-file (str (work-dir) "/foo.bin")] (let [test-store (kv/new-file-based-kv-store {:target-file target-file}) bytes (byte-array 10)] (Arrays/fill bytes (byte 1)) (is (nil? (kv/fetch test-store :a))) (kv/store test-store :a bytes) (is (Arrays/equals bytes ^bytes (kv/fetch test-store :a))) (kv/store test-store :a 3) (is (= 3 (kv/fetch test-store :a))) (is (nil? (kv/fetch test-store :b))) (is (= {:store {:count 1, :data {:a 3}}, :variant "file-based"} (kv/state test-store)))) ;; testing data was persisted in the file (let [test-store (kv/new-file-based-kv-store {:target-file target-file})] (is (= {:store {:count 1, :data {:a 3}}, :variant "file-based"} (kv/state test-store))) (kv/delete test-store :a) (is (nil? (kv/fetch test-store :a))) (is (nil? (kv/fetch test-store :b))) (kv/delete test-store :does-not-exist) (is (= {:store {:count 0, :data {}}, :variant "file-based"} (kv/state test-store)))))) (deftest test-encrypted-kv-store (let [passwords ["<PASSWORD>" "<PASSWORD>" "<PASSWORD>"] processed-passwords (mapv #(vector :cached %) passwords) local-kv-store (kv/new-local-kv-store {}) encrypted-kv-store (kv/new-encrypted-kv-store processed-passwords local-kv-store)] (is (nil? (kv/fetch local-kv-store :a))) (is (nil? (kv/fetch encrypted-kv-store :a))) (is (nil? (kv/fetch local-kv-store :b))) (is (nil? (kv/fetch encrypted-kv-store :b))) ; store propagates to underlying store (kv/store encrypted-kv-store :b 2) (is (not (nil? (kv/fetch local-kv-store :b)))) (is (= 2 (kv/fetch encrypted-kv-store :b))) ; store does not corrupt underlying store (kv/store encrypted-kv-store :a 5) (is (not (nil? (kv/fetch local-kv-store :a)))) (is (= 5 (kv/fetch encrypted-kv-store :a))) (is (not (nil? (kv/fetch local-kv-store :b)))) (is (= 2 (kv/fetch encrypted-kv-store :b))) ; store updates underlying store (kv/store encrypted-kv-store :b 11) (is (not (nil? (kv/fetch local-kv-store :b)))) (is (= 11 (kv/fetch encrypted-kv-store :b))) (is (= "encrypted" (get (kv/state encrypted-kv-store) :variant))) (is (= 2 (get-in (kv/state encrypted-kv-store) [:inner-state :store :count]))) (is (= #{:a :b} (set (keys (get-in (kv/state encrypted-kv-store) [:inner-state :store :data]))))) ; delete :a and :b (kv/delete encrypted-kv-store :a) (is (nil? (kv/fetch local-kv-store :a))) (is (nil? (kv/fetch encrypted-kv-store :a))) (kv/delete encrypted-kv-store :b) (is (nil? (kv/fetch local-kv-store :b))) (is (nil? (kv/fetch encrypted-kv-store :b))) (is (= "encrypted" (get (kv/state encrypted-kv-store) :variant))) (is (= {:count 0, :data {}} (get-in (kv/state encrypted-kv-store) [:inner-state :store]))) (kv/delete encrypted-kv-store :does-not-exist))) (deftest test-cached-kv-store (let [cache-config {:threshold 1000 :ttl (-> 60 t/seconds t/in-millis)} local-kv-store (kv/new-local-kv-store {}) cached-kv-store (kv/new-cached-kv-store cache-config local-kv-store)] (is (nil? (kv/fetch local-kv-store :a))) (is (nil? (kv/fetch cached-kv-store :a))) (kv/store local-kv-store :a 1) ; cache looks up underlying store during miss (is (kv/fetch local-kv-store :a)) (is (= 1 (kv/fetch local-kv-store :a))) (is (nil? (kv/fetch cached-kv-store :a))) ; store to cache propagates to underlying store (kv/store cached-kv-store :b 2) (is (= 2 (kv/fetch cached-kv-store :b))) (is (= 2 (kv/fetch local-kv-store :b))) (kv/store cached-kv-store :b 11) (is (= 11 (kv/fetch cached-kv-store :b))) (is (= 11 (kv/fetch local-kv-store :b))) ; cache works with refresh call (kv/store cached-kv-store :b 13) (is (= 13 (kv/fetch cached-kv-store :b))) (kv/store local-kv-store :b 17) (is (= 13 (kv/fetch cached-kv-store :b))) (is (= 17 (kv/fetch local-kv-store :b))) (is (= 17 (kv/fetch cached-kv-store :b :refresh true))) (is (= "cache" (get (kv/state cached-kv-store) :variant))) (is (= {:count 2, :data {:a 1, :b 17}} (get-in (kv/state cached-kv-store) [:inner-state :store]))) ; delete removes entry from cache (kv/delete cached-kv-store :b) (is (nil? (kv/fetch local-kv-store :b))) (is (nil? (kv/fetch cached-kv-store :b))) (is (nil? (kv/fetch cached-kv-store :b :refresh true))) (is (= "cache" (get (kv/state cached-kv-store) :variant))) (is (= {:count 1, :data {:a 1}} (get-in (kv/state cached-kv-store) [:inner-state :store]))))) (deftest test-validate-zk-key (kv/validate-zk-key "test-key") (is (thrown-with-msg? Exception #"Key may not contain '/'" (kv/validate-zk-key "evil-key/evil-key"))) (is (thrown-with-msg? Exception #"Key may not begin with '.'" (kv/validate-zk-key "..")))) (deftest test-key->zk-key (is (= "/base/6f1e/blah" (kv/key->zk-path "/base" "blah"))) (is (= "/base2/42d3/blahblah" (kv/key->zk-path "/base2" "blahblah")))) (deftest test-zk-kv-store (let [zk (curator/start-in-process-zookeeper) zk-server (:zk-server zk) curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100)) services-base-path "/test-zk-kv-store/base-path"] (is (kv/new-zk-kv-store {:curator curator :base-path "/waiter-tokens" :sync-timeout-ms 1})) (try (.start curator) (testing "in-memory-zk" (let [get-value-from-curator (fn [key] (.forPath (.checkExists curator) (kv/key->zk-path services-base-path key))) test-store (kv/new-zk-kv-store {:curator curator :base-path services-base-path :sync-timeout-ms 1}) bytes (byte-array 10)] (Arrays/fill bytes (byte 1)) (is (nil? (kv/fetch test-store "a"))) (is (nil? (get-value-from-curator "a"))) (kv/store test-store "a" bytes) (is (Arrays/equals bytes ^bytes (kv/fetch test-store "a"))) (is (not (nil? (get-value-from-curator "a")))) (kv/store test-store "a" 3) (is (= 3 (kv/fetch test-store "a"))) (is (not (nil? (get-value-from-curator "a")))) (is (nil? (kv/fetch test-store "b"))) (is (nil? (get-value-from-curator "b"))) (kv/delete test-store "a") (is (nil? (kv/fetch test-store "a"))) (is (nil? (get-value-from-curator "a"))) (is (nil? (kv/fetch test-store "b"))) (is (nil? (get-value-from-curator "b"))) (kv/delete test-store "does-not-exist") (is (nil? (get-value-from-curator "does-not-exist"))) (is (= {:base-path services-base-path, :variant "zookeeper"} (kv/state test-store))))) (finally (.close curator) (.stop zk-server))))) (deftest test-new-kv-store (let [base-path "/waiter" kv-config {:kind :zk :zk {:factory-fn 'waiter.kv/new-zk-kv-store :sync-timeout-ms 2000} :relative-path "tokens"} zk (curator/start-in-process-zookeeper) zk-server (:zk-server zk) curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100)) kv-store (kv/new-kv-store kv-config curator base-path nil)] (try (.start curator) (kv/store kv-store "foo" "bar") (is (= "bar" (kv/retrieve kv-store "foo" true))) (finally (.close curator) (.stop zk-server))))) (deftest test-new-zk-kv-store (testing "Creating a new ZooKeeper key/value store" (testing "should throw on non-integer sync-timeout-ms" (is (thrown? AssertionError (kv/new-zk-kv-store {:curator (reify CuratorFramework) :base-path "" :sync-timeout-ms 1.1})))))) (deftest test-zk-keys (testing "List ZK keys" (let [base-path "/waiter" kv-config {:kind :zk :zk {:factory-fn 'waiter.kv/new-zk-kv-store :sync-timeout-ms 2000} :relative-path "tokens"} zk (curator/start-in-process-zookeeper) zk-server (:zk-server zk) curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100)) kv-store (kv/new-kv-store kv-config curator base-path nil)] (try (.start curator) (kv/store kv-store "foo" "bar") (kv/store kv-store "foo2" "bar2") (kv/store kv-store "foo3" "bar3") (is (= #{"foo" "foo2" "foo3"} (set (kv/zk-keys curator (str base-path "/" (:relative-path kv-config)))))) (finally (.close curator) (.stop zk-server))))))
true
;; ;; Copyright (c) Two Sigma Open Source, LLC ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns waiter.kv-test (:require [clj-time.core :as t] [clojure.java.io :as io] [clojure.test :refer :all] [waiter.curator :as curator] [waiter.kv :as kv]) (:import (java.util Arrays) (org.apache.curator.framework CuratorFrameworkFactory CuratorFramework) (org.apache.curator.retry RetryNTimes))) (deftest test-local-kv-store (let [test-store (kv/new-local-kv-store {}) bytes (byte-array 10)] (Arrays/fill bytes (byte 1)) (is (nil? (kv/fetch test-store :a))) (kv/store test-store :a bytes) (is (Arrays/equals bytes ^bytes (kv/fetch test-store :a))) (kv/store test-store :a 3) (is (= 3 (kv/fetch test-store :a))) (is (nil? (kv/fetch test-store :b))) (is (= {:store {:count 1, :data {:a 3}}, :variant "in-memory"} (kv/state test-store))) (kv/delete test-store :a) (is (nil? (kv/fetch test-store :a))) (is (nil? (kv/fetch test-store :b))) (kv/delete test-store :does-not-exist) (is (= {:store {:count 0, :data {}}, :variant "in-memory"} (kv/state test-store))))) (defn work-dir "Returns the canonical path for the ./kv-store directory" [] (-> "./kv-store" (io/file) (.getCanonicalPath))) (deftest test-file-based-kv-store (let [target-file (str (work-dir) "/foo.bin")] (let [test-store (kv/new-file-based-kv-store {:target-file target-file}) bytes (byte-array 10)] (Arrays/fill bytes (byte 1)) (is (nil? (kv/fetch test-store :a))) (kv/store test-store :a bytes) (is (Arrays/equals bytes ^bytes (kv/fetch test-store :a))) (kv/store test-store :a 3) (is (= 3 (kv/fetch test-store :a))) (is (nil? (kv/fetch test-store :b))) (is (= {:store {:count 1, :data {:a 3}}, :variant "file-based"} (kv/state test-store)))) ;; testing data was persisted in the file (let [test-store (kv/new-file-based-kv-store {:target-file target-file})] (is (= {:store {:count 1, :data {:a 3}}, :variant "file-based"} (kv/state test-store))) (kv/delete test-store :a) (is (nil? (kv/fetch test-store :a))) (is (nil? (kv/fetch test-store :b))) (kv/delete test-store :does-not-exist) (is (= {:store {:count 0, :data {}}, :variant "file-based"} (kv/state test-store)))))) (deftest test-encrypted-kv-store (let [passwords ["PI:PASSWORD:<PASSWORD>END_PI" "PI:PASSWORD:<PASSWORD>END_PI" "PI:PASSWORD:<PASSWORD>END_PI"] processed-passwords (mapv #(vector :cached %) passwords) local-kv-store (kv/new-local-kv-store {}) encrypted-kv-store (kv/new-encrypted-kv-store processed-passwords local-kv-store)] (is (nil? (kv/fetch local-kv-store :a))) (is (nil? (kv/fetch encrypted-kv-store :a))) (is (nil? (kv/fetch local-kv-store :b))) (is (nil? (kv/fetch encrypted-kv-store :b))) ; store propagates to underlying store (kv/store encrypted-kv-store :b 2) (is (not (nil? (kv/fetch local-kv-store :b)))) (is (= 2 (kv/fetch encrypted-kv-store :b))) ; store does not corrupt underlying store (kv/store encrypted-kv-store :a 5) (is (not (nil? (kv/fetch local-kv-store :a)))) (is (= 5 (kv/fetch encrypted-kv-store :a))) (is (not (nil? (kv/fetch local-kv-store :b)))) (is (= 2 (kv/fetch encrypted-kv-store :b))) ; store updates underlying store (kv/store encrypted-kv-store :b 11) (is (not (nil? (kv/fetch local-kv-store :b)))) (is (= 11 (kv/fetch encrypted-kv-store :b))) (is (= "encrypted" (get (kv/state encrypted-kv-store) :variant))) (is (= 2 (get-in (kv/state encrypted-kv-store) [:inner-state :store :count]))) (is (= #{:a :b} (set (keys (get-in (kv/state encrypted-kv-store) [:inner-state :store :data]))))) ; delete :a and :b (kv/delete encrypted-kv-store :a) (is (nil? (kv/fetch local-kv-store :a))) (is (nil? (kv/fetch encrypted-kv-store :a))) (kv/delete encrypted-kv-store :b) (is (nil? (kv/fetch local-kv-store :b))) (is (nil? (kv/fetch encrypted-kv-store :b))) (is (= "encrypted" (get (kv/state encrypted-kv-store) :variant))) (is (= {:count 0, :data {}} (get-in (kv/state encrypted-kv-store) [:inner-state :store]))) (kv/delete encrypted-kv-store :does-not-exist))) (deftest test-cached-kv-store (let [cache-config {:threshold 1000 :ttl (-> 60 t/seconds t/in-millis)} local-kv-store (kv/new-local-kv-store {}) cached-kv-store (kv/new-cached-kv-store cache-config local-kv-store)] (is (nil? (kv/fetch local-kv-store :a))) (is (nil? (kv/fetch cached-kv-store :a))) (kv/store local-kv-store :a 1) ; cache looks up underlying store during miss (is (kv/fetch local-kv-store :a)) (is (= 1 (kv/fetch local-kv-store :a))) (is (nil? (kv/fetch cached-kv-store :a))) ; store to cache propagates to underlying store (kv/store cached-kv-store :b 2) (is (= 2 (kv/fetch cached-kv-store :b))) (is (= 2 (kv/fetch local-kv-store :b))) (kv/store cached-kv-store :b 11) (is (= 11 (kv/fetch cached-kv-store :b))) (is (= 11 (kv/fetch local-kv-store :b))) ; cache works with refresh call (kv/store cached-kv-store :b 13) (is (= 13 (kv/fetch cached-kv-store :b))) (kv/store local-kv-store :b 17) (is (= 13 (kv/fetch cached-kv-store :b))) (is (= 17 (kv/fetch local-kv-store :b))) (is (= 17 (kv/fetch cached-kv-store :b :refresh true))) (is (= "cache" (get (kv/state cached-kv-store) :variant))) (is (= {:count 2, :data {:a 1, :b 17}} (get-in (kv/state cached-kv-store) [:inner-state :store]))) ; delete removes entry from cache (kv/delete cached-kv-store :b) (is (nil? (kv/fetch local-kv-store :b))) (is (nil? (kv/fetch cached-kv-store :b))) (is (nil? (kv/fetch cached-kv-store :b :refresh true))) (is (= "cache" (get (kv/state cached-kv-store) :variant))) (is (= {:count 1, :data {:a 1}} (get-in (kv/state cached-kv-store) [:inner-state :store]))))) (deftest test-validate-zk-key (kv/validate-zk-key "test-key") (is (thrown-with-msg? Exception #"Key may not contain '/'" (kv/validate-zk-key "evil-key/evil-key"))) (is (thrown-with-msg? Exception #"Key may not begin with '.'" (kv/validate-zk-key "..")))) (deftest test-key->zk-key (is (= "/base/6f1e/blah" (kv/key->zk-path "/base" "blah"))) (is (= "/base2/42d3/blahblah" (kv/key->zk-path "/base2" "blahblah")))) (deftest test-zk-kv-store (let [zk (curator/start-in-process-zookeeper) zk-server (:zk-server zk) curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100)) services-base-path "/test-zk-kv-store/base-path"] (is (kv/new-zk-kv-store {:curator curator :base-path "/waiter-tokens" :sync-timeout-ms 1})) (try (.start curator) (testing "in-memory-zk" (let [get-value-from-curator (fn [key] (.forPath (.checkExists curator) (kv/key->zk-path services-base-path key))) test-store (kv/new-zk-kv-store {:curator curator :base-path services-base-path :sync-timeout-ms 1}) bytes (byte-array 10)] (Arrays/fill bytes (byte 1)) (is (nil? (kv/fetch test-store "a"))) (is (nil? (get-value-from-curator "a"))) (kv/store test-store "a" bytes) (is (Arrays/equals bytes ^bytes (kv/fetch test-store "a"))) (is (not (nil? (get-value-from-curator "a")))) (kv/store test-store "a" 3) (is (= 3 (kv/fetch test-store "a"))) (is (not (nil? (get-value-from-curator "a")))) (is (nil? (kv/fetch test-store "b"))) (is (nil? (get-value-from-curator "b"))) (kv/delete test-store "a") (is (nil? (kv/fetch test-store "a"))) (is (nil? (get-value-from-curator "a"))) (is (nil? (kv/fetch test-store "b"))) (is (nil? (get-value-from-curator "b"))) (kv/delete test-store "does-not-exist") (is (nil? (get-value-from-curator "does-not-exist"))) (is (= {:base-path services-base-path, :variant "zookeeper"} (kv/state test-store))))) (finally (.close curator) (.stop zk-server))))) (deftest test-new-kv-store (let [base-path "/waiter" kv-config {:kind :zk :zk {:factory-fn 'waiter.kv/new-zk-kv-store :sync-timeout-ms 2000} :relative-path "tokens"} zk (curator/start-in-process-zookeeper) zk-server (:zk-server zk) curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100)) kv-store (kv/new-kv-store kv-config curator base-path nil)] (try (.start curator) (kv/store kv-store "foo" "bar") (is (= "bar" (kv/retrieve kv-store "foo" true))) (finally (.close curator) (.stop zk-server))))) (deftest test-new-zk-kv-store (testing "Creating a new ZooKeeper key/value store" (testing "should throw on non-integer sync-timeout-ms" (is (thrown? AssertionError (kv/new-zk-kv-store {:curator (reify CuratorFramework) :base-path "" :sync-timeout-ms 1.1})))))) (deftest test-zk-keys (testing "List ZK keys" (let [base-path "/waiter" kv-config {:kind :zk :zk {:factory-fn 'waiter.kv/new-zk-kv-store :sync-timeout-ms 2000} :relative-path "tokens"} zk (curator/start-in-process-zookeeper) zk-server (:zk-server zk) curator (CuratorFrameworkFactory/newClient (:zk-connection-string zk) (RetryNTimes. 10 100)) kv-store (kv/new-kv-store kv-config curator base-path nil)] (try (.start curator) (kv/store kv-store "foo" "bar") (kv/store kv-store "foo2" "bar2") (kv/store kv-store "foo3" "bar3") (is (= #{"foo" "foo2" "foo3"} (set (kv/zk-keys curator (str base-path "/" (:relative-path kv-config)))))) (finally (.close curator) (.stop zk-server))))))
[ { "context": "(ns simple-re-fancoil.event)\n\n;; -- Domino 2 - Event Handlers ---------------------------", "end": 39, "score": 0.5517191886901855, "start": 36, "tag": "NAME", "value": "Dom" } ]
examples/simple/src/simple_re_fancoil/event.cljs
itarck/re-fancoil
0
(ns simple-re-fancoil.event) ;; -- Domino 2 - Event Handlers ----------------------------------------------- (def event-db-chains {:initialize ;; usage: (dispatch [:initialize]) [(fn [_db _] ;; the two parameters are not important here, so use _ {:time (js/Date.) ;; What it returns becomes the new application state :time-color "#f88"})] :time-color-change ;; dispatched when the user enters a new colour into the UI text field [(fn [db [_ new-color-value]] ;; -db event handlers given 2 parameters: current application state and event (a vector) (assoc db :time-color new-color-value))] :timer ;; every second an event of this kind will be dispatched [(fn [db [_ new-time]] ;; note how the 2nd parameter is destructured to obtain the data value (assoc db :time new-time))]})
37166
(ns simple-re-fancoil.event) ;; -- <NAME>ino 2 - Event Handlers ----------------------------------------------- (def event-db-chains {:initialize ;; usage: (dispatch [:initialize]) [(fn [_db _] ;; the two parameters are not important here, so use _ {:time (js/Date.) ;; What it returns becomes the new application state :time-color "#f88"})] :time-color-change ;; dispatched when the user enters a new colour into the UI text field [(fn [db [_ new-color-value]] ;; -db event handlers given 2 parameters: current application state and event (a vector) (assoc db :time-color new-color-value))] :timer ;; every second an event of this kind will be dispatched [(fn [db [_ new-time]] ;; note how the 2nd parameter is destructured to obtain the data value (assoc db :time new-time))]})
true
(ns simple-re-fancoil.event) ;; -- PI:NAME:<NAME>END_PIino 2 - Event Handlers ----------------------------------------------- (def event-db-chains {:initialize ;; usage: (dispatch [:initialize]) [(fn [_db _] ;; the two parameters are not important here, so use _ {:time (js/Date.) ;; What it returns becomes the new application state :time-color "#f88"})] :time-color-change ;; dispatched when the user enters a new colour into the UI text field [(fn [db [_ new-color-value]] ;; -db event handlers given 2 parameters: current application state and event (a vector) (assoc db :time-color new-color-value))] :timer ;; every second an event of this kind will be dispatched [(fn [db [_ new-time]] ;; note how the 2nd parameter is destructured to obtain the data value (assoc db :time new-time))]})
[ { "context": "t (double (rationalize (double x))).\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-04-14\"\n :version \"2017-05-24\"}", "end": 291, "score": 0.9868735671043396, "start": 255, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/scripts/clojure/palisades/lakes/elements/scripts/numbers/ratio.clj
palisades-lakes/les-elemens
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.scripts.numbers.ratio {:doc "Test (double (rationalize (double x)))." :author "palisades dot lakes at gmail dot com" :since "2017-04-14" :version "2017-05-24"} #_(:require [palisades.lakes.elements.api :as mc]) (:import [clojure.lang Ratio])) ;;---------------------------------------------------------------- #_(doseq [d [(/ 1.0 Math/E) (Math/nextUp (/ 1.0 Math/E)) (Math/nextDown (/ 1.0 Math/E))]] (println d) (println (double (rationalize (double d)))) (println (double (BigFraction. (double d))))) ;;---------------------------------------------------------------- #_(defn double<-ratio ^double [^Ratio r] (double r)) #_(defn double<-ratio ^double [^Ratio r] (double (.decimalValue r))) (defn double<-ratio ^double [^Ratio r] (.doubleValue (.decimalValue r))) ;;---------------------------------------------------------------- (println "round trip (double (rationalize (double d)))") (loop [i (int 0) d (double (/ 1.0 Math/E))] (let [r (rationalize d) dr (double<-ratio r)] (if (and (< i (int 3)) (== d dr)) (recur (inc i) (Math/nextUp d)) (do (println i (== d dr)) (println d (Double/toHexString d)) (println r) (println dr (Double/toHexString dr)) (println))))) ;;----------------------------------------------------------------
62677
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.scripts.numbers.ratio {:doc "Test (double (rationalize (double x)))." :author "<EMAIL>" :since "2017-04-14" :version "2017-05-24"} #_(:require [palisades.lakes.elements.api :as mc]) (:import [clojure.lang Ratio])) ;;---------------------------------------------------------------- #_(doseq [d [(/ 1.0 Math/E) (Math/nextUp (/ 1.0 Math/E)) (Math/nextDown (/ 1.0 Math/E))]] (println d) (println (double (rationalize (double d)))) (println (double (BigFraction. (double d))))) ;;---------------------------------------------------------------- #_(defn double<-ratio ^double [^Ratio r] (double r)) #_(defn double<-ratio ^double [^Ratio r] (double (.decimalValue r))) (defn double<-ratio ^double [^Ratio r] (.doubleValue (.decimalValue r))) ;;---------------------------------------------------------------- (println "round trip (double (rationalize (double d)))") (loop [i (int 0) d (double (/ 1.0 Math/E))] (let [r (rationalize d) dr (double<-ratio r)] (if (and (< i (int 3)) (== d dr)) (recur (inc i) (Math/nextUp d)) (do (println i (== d dr)) (println d (Double/toHexString d)) (println r) (println dr (Double/toHexString dr)) (println))))) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.scripts.numbers.ratio {:doc "Test (double (rationalize (double x)))." :author "PI:EMAIL:<EMAIL>END_PI" :since "2017-04-14" :version "2017-05-24"} #_(:require [palisades.lakes.elements.api :as mc]) (:import [clojure.lang Ratio])) ;;---------------------------------------------------------------- #_(doseq [d [(/ 1.0 Math/E) (Math/nextUp (/ 1.0 Math/E)) (Math/nextDown (/ 1.0 Math/E))]] (println d) (println (double (rationalize (double d)))) (println (double (BigFraction. (double d))))) ;;---------------------------------------------------------------- #_(defn double<-ratio ^double [^Ratio r] (double r)) #_(defn double<-ratio ^double [^Ratio r] (double (.decimalValue r))) (defn double<-ratio ^double [^Ratio r] (.doubleValue (.decimalValue r))) ;;---------------------------------------------------------------- (println "round trip (double (rationalize (double d)))") (loop [i (int 0) d (double (/ 1.0 Math/E))] (let [r (rationalize d) dr (double<-ratio r)] (if (and (< i (int 3)) (== d dr)) (recur (inc i) (Math/nextUp d)) (do (println i (== d dr)) (println d (Double/toHexString d)) (println r) (println dr (Double/toHexString dr)) (println))))) ;;----------------------------------------------------------------
[ { "context": "(\n ; Context map\n {}\n\n \"0\"\n \"noll\"\n (number 0)\n\n \"1\"\n \"en\"\n \"ett\"\n (number 1)\n", "end": 37, "score": 0.9996630549430847, "start": 33, "tag": "NAME", "value": "noll" }, { "context": "t map\n {}\n\n \"0\"\n \"noll\"\n (number 0)\n\n \"1\"\n \"en\"\n \"ett\"\n (number 1)\n\n \"2\"\n \"två\"\n \"ett par\"\n", "end": 64, "score": 0.7165205478668213, "start": 62, "tag": "NAME", "value": "en" }, { "context": " {}\n\n \"0\"\n \"noll\"\n (number 0)\n\n \"1\"\n \"en\"\n \"ett\"\n (number 1)\n\n \"2\"\n \"två\"\n \"ett par\"\n (numbe", "end": 72, "score": 0.996482253074646, "start": 69, "tag": "NAME", "value": "ett" }, { "context": "r 0)\n\n \"1\"\n \"en\"\n \"ett\"\n (number 1)\n\n \"2\"\n \"två\"\n \"ett par\"\n (number 2)\n\n \"7\"\n \"sju\"\n (numbe", "end": 100, "score": 0.998432457447052, "start": 97, "tag": "NAME", "value": "två" }, { "context": "\"1\"\n \"en\"\n \"ett\"\n (number 1)\n\n \"2\"\n \"två\"\n \"ett par\"\n (number 2)\n\n \"7\"\n \"sju\"\n (number 7)\n\n ", "end": 108, "score": 0.9381993412971497, "start": 105, "tag": "NAME", "value": "ett" }, { "context": "\n \"2\"\n \"två\"\n \"ett par\"\n (number 2)\n\n \"7\"\n \"sju\"\n (number 7)\n\n \"14\"\n \"fjorton\"\n (number 14)\n\n", "end": 140, "score": 0.9994825124740601, "start": 137, "tag": "NAME", "value": "sju" }, { "context": "(number 2)\n\n \"7\"\n \"sju\"\n (number 7)\n\n \"14\"\n \"fjorton\"\n (number 14)\n\n \"16\"\n \"sexton\"\n (number 16)\n\n", "end": 173, "score": 0.9998199343681335, "start": 166, "tag": "NAME", "value": "fjorton" }, { "context": "r 7)\n\n \"14\"\n \"fjorton\"\n (number 14)\n\n \"16\"\n \"sexton\"\n (number 16)\n\n \"17\"\n \"sjutton\"\n (number 17)\n", "end": 206, "score": 0.9998253583908081, "start": 200, "tag": "NAME", "value": "sexton" }, { "context": "r 14)\n\n \"16\"\n \"sexton\"\n (number 16)\n\n \"17\"\n \"sjutton\"\n (number 17)\n\n \"18\"\n \"arton\"\n (number 18)\n\n ", "end": 240, "score": 0.9998155236244202, "start": 233, "tag": "NAME", "value": "sjutton" }, { "context": " 16)\n\n \"17\"\n \"sjutton\"\n (number 17)\n\n \"18\"\n \"arton\"\n (number 18)\n\n \"20\"\n \"tjugo\"\n (number 20)\n\n ", "end": 272, "score": 0.9998048543930054, "start": 267, "tag": "NAME", "value": "arton" }, { "context": "er 17)\n\n \"18\"\n \"arton\"\n (number 18)\n\n \"20\"\n \"tjugo\"\n (number 20)\n\n \"1,1\"\n \"1,10\"\n \"01,10\"\n (num", "end": 304, "score": 0.999782383441925, "start": 299, "tag": "NAME", "value": "tjugo" } ]
resources/languages/sv/corpus/numbers.clj
guivn/duckling
922
( ; Context map {} "0" "noll" (number 0) "1" "en" "ett" (number 1) "2" "två" "ett par" (number 2) "7" "sju" (number 7) "14" "fjorton" (number 14) "16" "sexton" (number 16) "17" "sjutton" (number 17) "18" "arton" (number 18) "20" "tjugo" (number 20) "1,1" "1,10" "01,10" (number 1.1) "0,77" ",77" (number 0.77) "100.000" "100000" "100K" "100k" (number 100000) "3M" "3000K" "3000000" "3.000.000" (number 3000000) "1.200.000" "1200000" "1,2M" "1200K" ",0012G" (number 1200000) "- 1.200.000" "-1200000" "minus 1.200.000" "negativ 1200000" "-1,2M" "-1200K" "-,0012G" (number -1200000) "5 tusen" "fem tusen" (number 5000) )
115720
( ; Context map {} "0" "<NAME>" (number 0) "1" "<NAME>" "<NAME>" (number 1) "2" "<NAME>" "<NAME> par" (number 2) "7" "<NAME>" (number 7) "14" "<NAME>" (number 14) "16" "<NAME>" (number 16) "17" "<NAME>" (number 17) "18" "<NAME>" (number 18) "20" "<NAME>" (number 20) "1,1" "1,10" "01,10" (number 1.1) "0,77" ",77" (number 0.77) "100.000" "100000" "100K" "100k" (number 100000) "3M" "3000K" "3000000" "3.000.000" (number 3000000) "1.200.000" "1200000" "1,2M" "1200K" ",0012G" (number 1200000) "- 1.200.000" "-1200000" "minus 1.200.000" "negativ 1200000" "-1,2M" "-1200K" "-,0012G" (number -1200000) "5 tusen" "fem tusen" (number 5000) )
true
( ; Context map {} "0" "PI:NAME:<NAME>END_PI" (number 0) "1" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" (number 1) "2" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI par" (number 2) "7" "PI:NAME:<NAME>END_PI" (number 7) "14" "PI:NAME:<NAME>END_PI" (number 14) "16" "PI:NAME:<NAME>END_PI" (number 16) "17" "PI:NAME:<NAME>END_PI" (number 17) "18" "PI:NAME:<NAME>END_PI" (number 18) "20" "PI:NAME:<NAME>END_PI" (number 20) "1,1" "1,10" "01,10" (number 1.1) "0,77" ",77" (number 0.77) "100.000" "100000" "100K" "100k" (number 100000) "3M" "3000K" "3000000" "3.000.000" (number 3000000) "1.200.000" "1200000" "1,2M" "1200K" ",0012G" (number 1200000) "- 1.200.000" "-1200000" "minus 1.200.000" "negativ 1200000" "-1,2M" "-1200K" "-,0012G" (number -1200000) "5 tusen" "fem tusen" (number 5000) )
[ { "context": "e/literal\n;; :term/value \"Robert\"\n;; :term/datatype {:type", "end": 2247, "score": 0.9996514320373535, "start": 2241, "tag": "NAME", "value": "Robert" } ]
src/test/rdf/quad_test.cljs
kubelt/kubelt
0
(ns rdf.quad-test "Test the implementation of RDF/cljs quads." (:require [cljs.test :as t :refer [deftest is use-fixtures]]) (:require ["rdf-data-factory" :refer [Quad]]) (:require [com.kubelt.lib.rdf.quad :as rdf.quad])) ;; TODO rename to reflect namespace where RDF store quads are ;; implemented. ;; Utilities ;; ----------------------------------------------------------------------------- ;; (defn quad->subject ;; "Retrieve the subject value from a Quad instance." ;; [^Quad quad] ;; (.-value (.-subject quad))) ;; (defn quad->predicate ;; "Retrieve the predicate value from a Quad instance." ;; [^Quad quad] ;; (.-value (.-predicate quad))) ;; (defn quad->object ;; "Retrieve the object value from a Quad instance." ;; [^Quad quad] ;; (.-value (.-object quad))) ;; (defn quad->graph ;; "Retrieve the graph value from a Quad instance." ;; [^Quad quad] ;; (.-value (.-graph quad))) ;; Fixtures ;; ----------------------------------------------------------------------------- ;; A fixture can run :once (before and after *all* tests are executed), ;; or :each (before and after each individual test). #_(use-fixtures :once {:before (fn [] (println "start all")) :after (fn [] (println "done all"))}) #_(use-fixtures :each {:before (fn [] (println "start test")) :after (fn [] (println "done test"))}) ;; Data ;; ----------------------------------------------------------------------------- ;; TODO should we have a type registry, i.e. a map from keyword to XML ;; Schema datatype IRI? e.g. ;; :schema/string => "http://www.w3.org/2001/XMLSchema#string ;; (def xml-schema ;; #:schema {:string "http://www.w3.org/2001/XMLSchema#string"}) ;; (def pikachu-map ;; #::rdf.quad {:subject :pok/pikachu ;; :predicate :pok/hasName ;; :object "Pikachu"}) ;; ;; TODO test usage of fully expanded quads like this: ;; (def pikachu-full-map ;; #::rdf.quad {:subject {:term/type :type/named ;; :term/value "pok:pikachu"} ;; :predicate {:term/type :type/named ;; :term/value "pok:hasName"} ;; :object {:term/type :type/literal ;; :term/value "Robert" ;; :term/datatype {:type/type :type/named ;; :type/value :schema/string}}}) ;; (def pikachu-vec ;; [:pok/pikachu :pok/hasName "Pikachu"]) ;; Tests ;; ----------------------------------------------------------------------------- ;; TODO test quad creation when keywords are not namespaced ;; TODO test quad creation when supplying values as strings ;; TODO test quad creation when using full IRIs (should be compacted if ;; a matching prefix is registered) ;; ;; Quad ;; ;; (deftest map->quad-test ;; "Define a quad as a Clojure map without specifying the graph ;; component. The resulting Quad instance should be a part of the quad ;; store's default graph." ;; (let [q (rdf.quad/map->quad pikachu-map)] ;; (is (= (type q) Quad)) ;; (is (= (quad->subject q) "pok:pikachu")) ;; (is (= (quad->predicate q) "pok:hasName")) ;; (is (= (quad->object q) "Pikachu")) ;; (is (= (quad->graph q) "")))) ;; (deftest map+graph->quad-test ;; "Define a quad as a Clojure map, specifying the graph component. The ;; resulting quad should have the correct graph component." ;; (let [m (assoc pikachu-map ::rdf.quad/graph :pebble-cave) ;; q (rdf.quad/map->quad m)] ;; (is (= (type q) Quad)) ;; (is (= (quad->subject q) "pok:pikachu")) ;; (is (= (quad->predicate q) "pok:hasName")) ;; (is (= (quad->object q) "Pikachu")) ;; (is (= (quad->graph q) "pebble-cave")))) ;; (deftest vec->quad-test ;; "Define a quad as a Clojure vector without specifying the graph ;; component. The resulting Quad instance should be a part of the quad ;; store's default graph." ;; (let [q (rdf.quad/vec->quad pikachu-vec)] ;; (is (= (type q) Quad)) ;; (is (= (quad->subject q) "pok:pikachu")) ;; (is (= (quad->predicate q) "pok:hasName")) ;; (is (= (quad->object q) "Pikachu")) ;; (is (= (quad->graph q) "")))) ;; (deftest vec+graph->quad-test ;; "Define a quad as a Clojure vector, specifying the graph ;; component. The resulting Quad instance should have the correct graph ;; component." ;; (let [v (conj pikachu-vec :pebble-cave) ;; q (rdf.quad/vec->quad v)] ;; (is (= (type q) Quad)) ;; (is (= (quad->subject q) "pok:pikachu")) ;; (is (= (quad->predicate q) "pok:hasName")) ;; (is (= (quad->object q) "Pikachu")) ;; (is (= (quad->graph q) "pebble-cave"))))
108320
(ns rdf.quad-test "Test the implementation of RDF/cljs quads." (:require [cljs.test :as t :refer [deftest is use-fixtures]]) (:require ["rdf-data-factory" :refer [Quad]]) (:require [com.kubelt.lib.rdf.quad :as rdf.quad])) ;; TODO rename to reflect namespace where RDF store quads are ;; implemented. ;; Utilities ;; ----------------------------------------------------------------------------- ;; (defn quad->subject ;; "Retrieve the subject value from a Quad instance." ;; [^Quad quad] ;; (.-value (.-subject quad))) ;; (defn quad->predicate ;; "Retrieve the predicate value from a Quad instance." ;; [^Quad quad] ;; (.-value (.-predicate quad))) ;; (defn quad->object ;; "Retrieve the object value from a Quad instance." ;; [^Quad quad] ;; (.-value (.-object quad))) ;; (defn quad->graph ;; "Retrieve the graph value from a Quad instance." ;; [^Quad quad] ;; (.-value (.-graph quad))) ;; Fixtures ;; ----------------------------------------------------------------------------- ;; A fixture can run :once (before and after *all* tests are executed), ;; or :each (before and after each individual test). #_(use-fixtures :once {:before (fn [] (println "start all")) :after (fn [] (println "done all"))}) #_(use-fixtures :each {:before (fn [] (println "start test")) :after (fn [] (println "done test"))}) ;; Data ;; ----------------------------------------------------------------------------- ;; TODO should we have a type registry, i.e. a map from keyword to XML ;; Schema datatype IRI? e.g. ;; :schema/string => "http://www.w3.org/2001/XMLSchema#string ;; (def xml-schema ;; #:schema {:string "http://www.w3.org/2001/XMLSchema#string"}) ;; (def pikachu-map ;; #::rdf.quad {:subject :pok/pikachu ;; :predicate :pok/hasName ;; :object "Pikachu"}) ;; ;; TODO test usage of fully expanded quads like this: ;; (def pikachu-full-map ;; #::rdf.quad {:subject {:term/type :type/named ;; :term/value "pok:pikachu"} ;; :predicate {:term/type :type/named ;; :term/value "pok:hasName"} ;; :object {:term/type :type/literal ;; :term/value "<NAME>" ;; :term/datatype {:type/type :type/named ;; :type/value :schema/string}}}) ;; (def pikachu-vec ;; [:pok/pikachu :pok/hasName "Pikachu"]) ;; Tests ;; ----------------------------------------------------------------------------- ;; TODO test quad creation when keywords are not namespaced ;; TODO test quad creation when supplying values as strings ;; TODO test quad creation when using full IRIs (should be compacted if ;; a matching prefix is registered) ;; ;; Quad ;; ;; (deftest map->quad-test ;; "Define a quad as a Clojure map without specifying the graph ;; component. The resulting Quad instance should be a part of the quad ;; store's default graph." ;; (let [q (rdf.quad/map->quad pikachu-map)] ;; (is (= (type q) Quad)) ;; (is (= (quad->subject q) "pok:pikachu")) ;; (is (= (quad->predicate q) "pok:hasName")) ;; (is (= (quad->object q) "Pikachu")) ;; (is (= (quad->graph q) "")))) ;; (deftest map+graph->quad-test ;; "Define a quad as a Clojure map, specifying the graph component. The ;; resulting quad should have the correct graph component." ;; (let [m (assoc pikachu-map ::rdf.quad/graph :pebble-cave) ;; q (rdf.quad/map->quad m)] ;; (is (= (type q) Quad)) ;; (is (= (quad->subject q) "pok:pikachu")) ;; (is (= (quad->predicate q) "pok:hasName")) ;; (is (= (quad->object q) "Pikachu")) ;; (is (= (quad->graph q) "pebble-cave")))) ;; (deftest vec->quad-test ;; "Define a quad as a Clojure vector without specifying the graph ;; component. The resulting Quad instance should be a part of the quad ;; store's default graph." ;; (let [q (rdf.quad/vec->quad pikachu-vec)] ;; (is (= (type q) Quad)) ;; (is (= (quad->subject q) "pok:pikachu")) ;; (is (= (quad->predicate q) "pok:hasName")) ;; (is (= (quad->object q) "Pikachu")) ;; (is (= (quad->graph q) "")))) ;; (deftest vec+graph->quad-test ;; "Define a quad as a Clojure vector, specifying the graph ;; component. The resulting Quad instance should have the correct graph ;; component." ;; (let [v (conj pikachu-vec :pebble-cave) ;; q (rdf.quad/vec->quad v)] ;; (is (= (type q) Quad)) ;; (is (= (quad->subject q) "pok:pikachu")) ;; (is (= (quad->predicate q) "pok:hasName")) ;; (is (= (quad->object q) "Pikachu")) ;; (is (= (quad->graph q) "pebble-cave"))))
true
(ns rdf.quad-test "Test the implementation of RDF/cljs quads." (:require [cljs.test :as t :refer [deftest is use-fixtures]]) (:require ["rdf-data-factory" :refer [Quad]]) (:require [com.kubelt.lib.rdf.quad :as rdf.quad])) ;; TODO rename to reflect namespace where RDF store quads are ;; implemented. ;; Utilities ;; ----------------------------------------------------------------------------- ;; (defn quad->subject ;; "Retrieve the subject value from a Quad instance." ;; [^Quad quad] ;; (.-value (.-subject quad))) ;; (defn quad->predicate ;; "Retrieve the predicate value from a Quad instance." ;; [^Quad quad] ;; (.-value (.-predicate quad))) ;; (defn quad->object ;; "Retrieve the object value from a Quad instance." ;; [^Quad quad] ;; (.-value (.-object quad))) ;; (defn quad->graph ;; "Retrieve the graph value from a Quad instance." ;; [^Quad quad] ;; (.-value (.-graph quad))) ;; Fixtures ;; ----------------------------------------------------------------------------- ;; A fixture can run :once (before and after *all* tests are executed), ;; or :each (before and after each individual test). #_(use-fixtures :once {:before (fn [] (println "start all")) :after (fn [] (println "done all"))}) #_(use-fixtures :each {:before (fn [] (println "start test")) :after (fn [] (println "done test"))}) ;; Data ;; ----------------------------------------------------------------------------- ;; TODO should we have a type registry, i.e. a map from keyword to XML ;; Schema datatype IRI? e.g. ;; :schema/string => "http://www.w3.org/2001/XMLSchema#string ;; (def xml-schema ;; #:schema {:string "http://www.w3.org/2001/XMLSchema#string"}) ;; (def pikachu-map ;; #::rdf.quad {:subject :pok/pikachu ;; :predicate :pok/hasName ;; :object "Pikachu"}) ;; ;; TODO test usage of fully expanded quads like this: ;; (def pikachu-full-map ;; #::rdf.quad {:subject {:term/type :type/named ;; :term/value "pok:pikachu"} ;; :predicate {:term/type :type/named ;; :term/value "pok:hasName"} ;; :object {:term/type :type/literal ;; :term/value "PI:NAME:<NAME>END_PI" ;; :term/datatype {:type/type :type/named ;; :type/value :schema/string}}}) ;; (def pikachu-vec ;; [:pok/pikachu :pok/hasName "Pikachu"]) ;; Tests ;; ----------------------------------------------------------------------------- ;; TODO test quad creation when keywords are not namespaced ;; TODO test quad creation when supplying values as strings ;; TODO test quad creation when using full IRIs (should be compacted if ;; a matching prefix is registered) ;; ;; Quad ;; ;; (deftest map->quad-test ;; "Define a quad as a Clojure map without specifying the graph ;; component. The resulting Quad instance should be a part of the quad ;; store's default graph." ;; (let [q (rdf.quad/map->quad pikachu-map)] ;; (is (= (type q) Quad)) ;; (is (= (quad->subject q) "pok:pikachu")) ;; (is (= (quad->predicate q) "pok:hasName")) ;; (is (= (quad->object q) "Pikachu")) ;; (is (= (quad->graph q) "")))) ;; (deftest map+graph->quad-test ;; "Define a quad as a Clojure map, specifying the graph component. The ;; resulting quad should have the correct graph component." ;; (let [m (assoc pikachu-map ::rdf.quad/graph :pebble-cave) ;; q (rdf.quad/map->quad m)] ;; (is (= (type q) Quad)) ;; (is (= (quad->subject q) "pok:pikachu")) ;; (is (= (quad->predicate q) "pok:hasName")) ;; (is (= (quad->object q) "Pikachu")) ;; (is (= (quad->graph q) "pebble-cave")))) ;; (deftest vec->quad-test ;; "Define a quad as a Clojure vector without specifying the graph ;; component. The resulting Quad instance should be a part of the quad ;; store's default graph." ;; (let [q (rdf.quad/vec->quad pikachu-vec)] ;; (is (= (type q) Quad)) ;; (is (= (quad->subject q) "pok:pikachu")) ;; (is (= (quad->predicate q) "pok:hasName")) ;; (is (= (quad->object q) "Pikachu")) ;; (is (= (quad->graph q) "")))) ;; (deftest vec+graph->quad-test ;; "Define a quad as a Clojure vector, specifying the graph ;; component. The resulting Quad instance should have the correct graph ;; component." ;; (let [v (conj pikachu-vec :pebble-cave) ;; q (rdf.quad/vec->quad v)] ;; (is (= (type q) Quad)) ;; (is (= (quad->subject q) "pok:pikachu")) ;; (is (= (quad->predicate q) "pok:hasName")) ;; (is (= (quad->object q) "Pikachu")) ;; (is (= (quad->graph q) "pebble-cave"))))
[ { "context": "defn mapify\n \"Return a seq of maps like {:name \\\"Edward Cullen\\\" :glitter-index 10}\"\n [rows]\n (map (fn [unmapp", "end": 441, "score": 0.9998137354850769, "start": 428, "tag": "NAME", "value": "Edward Cullen" } ]
fwpd/src/fwpd/core.clj
kraii/randomic-clojure
0
(ns fwpd.core (:require [clojure.string :as str])) (def filename "suspects.csv") (def vamp-keys [:name :glitter-index]) (defn str->int [str] (Integer. str)) (def conversions {:name identity :glitter-index str->int}) (defn convert [vamp-key value] ((get conversions vamp-key) value)) (defn parse [string] (map #(str/split % #",") (str/split string #"\n"))) (defn mapify "Return a seq of maps like {:name \"Edward Cullen\" :glitter-index 10}" [rows] (map (fn [unmapped-row] (reduce (fn [row-map [vamp-key value]] (assoc row-map vamp-key (convert vamp-key value))) {} (map vector vamp-keys unmapped-row))) rows)) (defn glitter-filter [minimum-glitter records] (filter #(>= (:glitter-index %) minimum-glitter) records)) (def suspects (mapify (parse (slurp filename)))) ;#2. (defn append [suspects name glitter-index] (conj suspects {:name name :glitter-index glitter-index})) ;#3 (defn validate ([suspect] (validate suspect {:name string? :glitter-index integer?})) ([suspect validations] (every? #((% validations) (% suspect)) [:name :glitter-index]))) ;#4 (defn to-csv [suspects] (letfn [(conv [suspect] [(:name suspect) (:glitter-index suspect)])] (str/join "\n" (map (partial str/join ",") (map conv suspects)))))
38828
(ns fwpd.core (:require [clojure.string :as str])) (def filename "suspects.csv") (def vamp-keys [:name :glitter-index]) (defn str->int [str] (Integer. str)) (def conversions {:name identity :glitter-index str->int}) (defn convert [vamp-key value] ((get conversions vamp-key) value)) (defn parse [string] (map #(str/split % #",") (str/split string #"\n"))) (defn mapify "Return a seq of maps like {:name \"<NAME>\" :glitter-index 10}" [rows] (map (fn [unmapped-row] (reduce (fn [row-map [vamp-key value]] (assoc row-map vamp-key (convert vamp-key value))) {} (map vector vamp-keys unmapped-row))) rows)) (defn glitter-filter [minimum-glitter records] (filter #(>= (:glitter-index %) minimum-glitter) records)) (def suspects (mapify (parse (slurp filename)))) ;#2. (defn append [suspects name glitter-index] (conj suspects {:name name :glitter-index glitter-index})) ;#3 (defn validate ([suspect] (validate suspect {:name string? :glitter-index integer?})) ([suspect validations] (every? #((% validations) (% suspect)) [:name :glitter-index]))) ;#4 (defn to-csv [suspects] (letfn [(conv [suspect] [(:name suspect) (:glitter-index suspect)])] (str/join "\n" (map (partial str/join ",") (map conv suspects)))))
true
(ns fwpd.core (:require [clojure.string :as str])) (def filename "suspects.csv") (def vamp-keys [:name :glitter-index]) (defn str->int [str] (Integer. str)) (def conversions {:name identity :glitter-index str->int}) (defn convert [vamp-key value] ((get conversions vamp-key) value)) (defn parse [string] (map #(str/split % #",") (str/split string #"\n"))) (defn mapify "Return a seq of maps like {:name \"PI:NAME:<NAME>END_PI\" :glitter-index 10}" [rows] (map (fn [unmapped-row] (reduce (fn [row-map [vamp-key value]] (assoc row-map vamp-key (convert vamp-key value))) {} (map vector vamp-keys unmapped-row))) rows)) (defn glitter-filter [minimum-glitter records] (filter #(>= (:glitter-index %) minimum-glitter) records)) (def suspects (mapify (parse (slurp filename)))) ;#2. (defn append [suspects name glitter-index] (conj suspects {:name name :glitter-index glitter-index})) ;#3 (defn validate ([suspect] (validate suspect {:name string? :glitter-index integer?})) ([suspect validations] (every? #((% validations) (% suspect)) [:name :glitter-index]))) ;#4 (defn to-csv [suspects] (letfn [(conv [suspect] [(:name suspect) (:glitter-index suspect)])] (str/join "\n" (map (partial str/join ",") (map conv suspects)))))
[ { "context": "hemas.\"\n\n :url\n \"https://github.com/rutledgepaulv/schema-conformer\"\n\n :license\n {:name \"MIT Licen", "end": 213, "score": 0.606751561164856, "start": 212, "tag": "USERNAME", "value": "v" }, { "context": "ddition\n [:developers\n [:developer\n [:name \"Paul Rutledge\"]\n [:url \"https://github.com/rutledgepaulv\"]\n ", "end": 485, "score": 0.9998902082443237, "start": 472, "tag": "NAME", "value": "Paul Rutledge" }, { "context": "me \"Paul Rutledge\"]\n [:url \"https://github.com/rutledgepaulv\"]\n [:email \"rutledgepaulv@gmail.com\"]\n [:ti", "end": 531, "score": 0.8424409031867981, "start": 518, "tag": "USERNAME", "value": "rutledgepaulv" }, { "context": " \"https://github.com/rutledgepaulv\"]\n [:email \"rutledgepaulv@gmail.com\"]\n [:timezone \"-5\"]]]\n\n :deploy-repositories\n", "end": 570, "score": 0.9999287128448486, "start": 547, "tag": "EMAIL", "value": "rutledgepaulv@gmail.com" } ]
project.clj
RutledgePaulV/schema-conformer
0
(defproject org.clojars.rutledgepaulv/schema-conformer "0.1.4-SNAPSHOT" :description "A library for configurable conforming of data according to prismatic schemas." :url "https://github.com/rutledgepaulv/schema-conformer" :license {:name "MIT License" :url "http://opensource.org/licenses/MIT" :year 2020 :key "mit"} :scm {:name "git" :url "https://github.com/rutledgepaulv/schema-conformer"} :pom-addition [:developers [:developer [:name "Paul Rutledge"] [:url "https://github.com/rutledgepaulv"] [:email "rutledgepaulv@gmail.com"] [:timezone "-5"]]] :deploy-repositories [["releases" :clojars] ["snapshots" :clojars]] :dependencies [[org.clojure/clojure "1.10.1"] [prismatic/schema "1.1.12"]] :plugins [[lein-cloverage "1.1.2"]] :repl-options {:init-ns schema-conformer.core} :profiles {:test {:dependencies [[clj-time "0.15.2" :scope "test"]]}})
77790
(defproject org.clojars.rutledgepaulv/schema-conformer "0.1.4-SNAPSHOT" :description "A library for configurable conforming of data according to prismatic schemas." :url "https://github.com/rutledgepaulv/schema-conformer" :license {:name "MIT License" :url "http://opensource.org/licenses/MIT" :year 2020 :key "mit"} :scm {:name "git" :url "https://github.com/rutledgepaulv/schema-conformer"} :pom-addition [:developers [:developer [:name "<NAME>"] [:url "https://github.com/rutledgepaulv"] [:email "<EMAIL>"] [:timezone "-5"]]] :deploy-repositories [["releases" :clojars] ["snapshots" :clojars]] :dependencies [[org.clojure/clojure "1.10.1"] [prismatic/schema "1.1.12"]] :plugins [[lein-cloverage "1.1.2"]] :repl-options {:init-ns schema-conformer.core} :profiles {:test {:dependencies [[clj-time "0.15.2" :scope "test"]]}})
true
(defproject org.clojars.rutledgepaulv/schema-conformer "0.1.4-SNAPSHOT" :description "A library for configurable conforming of data according to prismatic schemas." :url "https://github.com/rutledgepaulv/schema-conformer" :license {:name "MIT License" :url "http://opensource.org/licenses/MIT" :year 2020 :key "mit"} :scm {:name "git" :url "https://github.com/rutledgepaulv/schema-conformer"} :pom-addition [:developers [:developer [:name "PI:NAME:<NAME>END_PI"] [:url "https://github.com/rutledgepaulv"] [:email "PI:EMAIL:<EMAIL>END_PI"] [:timezone "-5"]]] :deploy-repositories [["releases" :clojars] ["snapshots" :clojars]] :dependencies [[org.clojure/clojure "1.10.1"] [prismatic/schema "1.1.12"]] :plugins [[lein-cloverage "1.1.2"]] :repl-options {:init-ns schema-conformer.core} :profiles {:test {:dependencies [[clj-time "0.15.2" :scope "test"]]}})
[ { "context": " :key-password (env :keystore-password \"changeit\")\n :truststore (env :trus", "end": 2255, "score": 0.9987053871154785, "start": 2247, "tag": "PASSWORD", "value": "changeit" }, { "context": " :trust-password (env :truststore-password \"changeit\")}]\n\n (reset! int-server (ring/run-jetty h", "end": 2406, "score": 0.9990242123603821, "start": 2398, "tag": "PASSWORD", "value": "changeit" } ]
bai-bff/src/bai_bff/services/endpoints.clj
gavinmbell/benchmark-ai-1
6
;; Copyright 2019 Amazon.com, Inc. or its affiliates. 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. ;; A copy of the License is located at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; or in the "license" file accompanying this file. This file 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 bai-bff.services.endpoints (:require [bai-bff.services :refer [RunService]] [bai-bff.http-api :as http-api] [bai-bff.utils.utils :refer [assert-configured!]] [clojure.pprint :refer :all] [environ.core :refer [env]] [ring.adapter.jetty :as ring] [taoensso.timbre :as log]) (:import (org.eclipse.jetty.server Server) (org.eclipse.jetty.util.thread QueuedThreadPool))) (def endpoints-required-keys #{:endpoints-port}) ;;TODO - come and take a look a this... apparently this ain't a thing anymore??? (defn jetty-configurator-provider [] (fn [^Server server] (let [^QueuedThreadPool threadPool (QueuedThreadPool. (Integer/valueOf (env :thread-pool-size)))] (.setMaxQueued threadPool (Integer/valueOf (env :max-queue-size))) (.setSendServerVersion server false) (.setThreadPool server threadPool)))) (defrecord EndpointsServer [int-server] RunService (start! [this] (locking this (log/info (str "starting endpoints server component... port["(env :endpoints-port)"]")) (pprint (type (env :endpoints-port))) (assert-configured! endpoints-required-keys) (let [handler (http-api/create-application-routes) base-options {:port (Integer/valueOf (env :endpoints-port "8085")) :join? false} ;; :configurator (jetty-configurator-provider) ;;TODO - see above ssl-options {:ssl? true :ssl-port "443" :keystore (env :keystore "keystore.jks") :key-password (env :keystore-password "changeit") :truststore (env :truststore "truststore.jks") :trust-password (env :truststore-password "changeit")}] (reset! int-server (ring/run-jetty handler (merge base-options #_ssl-options)))))) (stop! [this] (locking this (when @int-server (.stop @int-server)))) Object (toString [_] "<EndpointsServer>")) (defmethod print-method EndpointsServer [v ^java.io.Writer w] (.write w "<EndpointsServer>")) (defn create-endpoints-service [] (->EndpointsServer (atom nil)))
98297
;; Copyright 2019 Amazon.com, Inc. or its affiliates. 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. ;; A copy of the License is located at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; or in the "license" file accompanying this file. This file 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 bai-bff.services.endpoints (:require [bai-bff.services :refer [RunService]] [bai-bff.http-api :as http-api] [bai-bff.utils.utils :refer [assert-configured!]] [clojure.pprint :refer :all] [environ.core :refer [env]] [ring.adapter.jetty :as ring] [taoensso.timbre :as log]) (:import (org.eclipse.jetty.server Server) (org.eclipse.jetty.util.thread QueuedThreadPool))) (def endpoints-required-keys #{:endpoints-port}) ;;TODO - come and take a look a this... apparently this ain't a thing anymore??? (defn jetty-configurator-provider [] (fn [^Server server] (let [^QueuedThreadPool threadPool (QueuedThreadPool. (Integer/valueOf (env :thread-pool-size)))] (.setMaxQueued threadPool (Integer/valueOf (env :max-queue-size))) (.setSendServerVersion server false) (.setThreadPool server threadPool)))) (defrecord EndpointsServer [int-server] RunService (start! [this] (locking this (log/info (str "starting endpoints server component... port["(env :endpoints-port)"]")) (pprint (type (env :endpoints-port))) (assert-configured! endpoints-required-keys) (let [handler (http-api/create-application-routes) base-options {:port (Integer/valueOf (env :endpoints-port "8085")) :join? false} ;; :configurator (jetty-configurator-provider) ;;TODO - see above ssl-options {:ssl? true :ssl-port "443" :keystore (env :keystore "keystore.jks") :key-password (env :keystore-password "<PASSWORD>") :truststore (env :truststore "truststore.jks") :trust-password (env :truststore-password "<PASSWORD>")}] (reset! int-server (ring/run-jetty handler (merge base-options #_ssl-options)))))) (stop! [this] (locking this (when @int-server (.stop @int-server)))) Object (toString [_] "<EndpointsServer>")) (defmethod print-method EndpointsServer [v ^java.io.Writer w] (.write w "<EndpointsServer>")) (defn create-endpoints-service [] (->EndpointsServer (atom nil)))
true
;; Copyright 2019 Amazon.com, Inc. or its affiliates. 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. ;; A copy of the License is located at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; or in the "license" file accompanying this file. This file 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 bai-bff.services.endpoints (:require [bai-bff.services :refer [RunService]] [bai-bff.http-api :as http-api] [bai-bff.utils.utils :refer [assert-configured!]] [clojure.pprint :refer :all] [environ.core :refer [env]] [ring.adapter.jetty :as ring] [taoensso.timbre :as log]) (:import (org.eclipse.jetty.server Server) (org.eclipse.jetty.util.thread QueuedThreadPool))) (def endpoints-required-keys #{:endpoints-port}) ;;TODO - come and take a look a this... apparently this ain't a thing anymore??? (defn jetty-configurator-provider [] (fn [^Server server] (let [^QueuedThreadPool threadPool (QueuedThreadPool. (Integer/valueOf (env :thread-pool-size)))] (.setMaxQueued threadPool (Integer/valueOf (env :max-queue-size))) (.setSendServerVersion server false) (.setThreadPool server threadPool)))) (defrecord EndpointsServer [int-server] RunService (start! [this] (locking this (log/info (str "starting endpoints server component... port["(env :endpoints-port)"]")) (pprint (type (env :endpoints-port))) (assert-configured! endpoints-required-keys) (let [handler (http-api/create-application-routes) base-options {:port (Integer/valueOf (env :endpoints-port "8085")) :join? false} ;; :configurator (jetty-configurator-provider) ;;TODO - see above ssl-options {:ssl? true :ssl-port "443" :keystore (env :keystore "keystore.jks") :key-password (env :keystore-password "PI:PASSWORD:<PASSWORD>END_PI") :truststore (env :truststore "truststore.jks") :trust-password (env :truststore-password "PI:PASSWORD:<PASSWORD>END_PI")}] (reset! int-server (ring/run-jetty handler (merge base-options #_ssl-options)))))) (stop! [this] (locking this (when @int-server (.stop @int-server)))) Object (toString [_] "<EndpointsServer>")) (defmethod print-method EndpointsServer [v ^java.io.Writer w] (.write w "<EndpointsServer>")) (defn create-endpoints-service [] (->EndpointsServer (atom nil)))
[ { "context": "a\" 10 \"2017-02-18\" \"2017-02-28\")\n(addStudent \"1\" \"Saurabh\" 26 \"male\" 1000 \"B5\")\n(addStudent \"1\" \"Mayank\" 24", "end": 1621, "score": 0.9997202754020691, "start": 1614, "tag": "NAME", "value": "Saurabh" }, { "context": "\" \"Saurabh\" 26 \"male\" 1000 \"B5\")\n(addStudent \"1\" \"Mayank\" 24 \"male\" 1000 \"A4\")\n(addTransaction \"1\" \"Mayank", "end": 1667, "score": 0.9995465278625488, "start": 1661, "tag": "NAME", "value": "Mayank" }, { "context": "Mayank\" 24 \"male\" 1000 \"A4\")\n(addTransaction \"1\" \"Mayank\" \"Soap\" 2 20 \"2017-02-18\")\n(addTransaction \"1\" \"S", "end": 1717, "score": 0.9969662427902222, "start": 1711, "tag": "NAME", "value": "Mayank" } ]
src/projectv/core.clj
geekskool/ashram-courses-clojure
0
(ns projectv.core (:gen-class)) (require '[clojure.java.io :as io]) (require '[clojure.data.json :as json]) (def course (atom {})) (def file-path "data.json") (defn addCourse [id coursename duration start end] (let [thiscourse {"name" coursename, "duration" duration, "start" start, "end" end, "students" {}}] (swap! course assoc-in [id] thiscourse))) (defn addStudent [id studentname age gender deposit roomNo] (let [student {"age" age, "gender" gender, "deposit" deposit, "roomNo" roomNo, "transactions" []}] (swap! course assoc-in [id "students" studentname] student))) (defn addTransaction [id studentName desc quantity rate date] (let [transaction {"desc" desc, "quantity" quantity, "rate" rate, "total" (* quantity rate), "date" date} length (count (get-in @course [id "students" studentName "transactions"]))] (swap! course assoc-in [id "students" studentName "transactions" length] transaction))) (defn updateDeposit [id studentName amount] (swap! course update-in [id "students" studentName "deposit"] + amount)) (defn save [] (spit file-path (json/write-str @course))) (defn main [] (if (.exists (io/as-file file-path)) (reset! course (json/read-str (slurp file-path))))) (addCourse "1" "Vipasana" 10 "2017-02-18" "2017-02-28") (addStudent "1" "Saurabh" 26 "male" 1000 "B5") (addStudent "1" "Mayank" 24 "male" 1000 "A4") (addTransaction "1" "Mayank" "Soap" 2 20 "2017-02-18") (addTransaction "1" "Saurabh" "Water Bottle" 5 15 "2017-02-19") (updateDeposit "1" "Mayank" 1000) ;(def course (atom {:name "Course 1", ; :duration 10 ; :start "2017-02-18" ; :end "2017-02-28" ; :students {}}))
41967
(ns projectv.core (:gen-class)) (require '[clojure.java.io :as io]) (require '[clojure.data.json :as json]) (def course (atom {})) (def file-path "data.json") (defn addCourse [id coursename duration start end] (let [thiscourse {"name" coursename, "duration" duration, "start" start, "end" end, "students" {}}] (swap! course assoc-in [id] thiscourse))) (defn addStudent [id studentname age gender deposit roomNo] (let [student {"age" age, "gender" gender, "deposit" deposit, "roomNo" roomNo, "transactions" []}] (swap! course assoc-in [id "students" studentname] student))) (defn addTransaction [id studentName desc quantity rate date] (let [transaction {"desc" desc, "quantity" quantity, "rate" rate, "total" (* quantity rate), "date" date} length (count (get-in @course [id "students" studentName "transactions"]))] (swap! course assoc-in [id "students" studentName "transactions" length] transaction))) (defn updateDeposit [id studentName amount] (swap! course update-in [id "students" studentName "deposit"] + amount)) (defn save [] (spit file-path (json/write-str @course))) (defn main [] (if (.exists (io/as-file file-path)) (reset! course (json/read-str (slurp file-path))))) (addCourse "1" "Vipasana" 10 "2017-02-18" "2017-02-28") (addStudent "1" "<NAME>" 26 "male" 1000 "B5") (addStudent "1" "<NAME>" 24 "male" 1000 "A4") (addTransaction "1" "<NAME>" "Soap" 2 20 "2017-02-18") (addTransaction "1" "Saurabh" "Water Bottle" 5 15 "2017-02-19") (updateDeposit "1" "Mayank" 1000) ;(def course (atom {:name "Course 1", ; :duration 10 ; :start "2017-02-18" ; :end "2017-02-28" ; :students {}}))
true
(ns projectv.core (:gen-class)) (require '[clojure.java.io :as io]) (require '[clojure.data.json :as json]) (def course (atom {})) (def file-path "data.json") (defn addCourse [id coursename duration start end] (let [thiscourse {"name" coursename, "duration" duration, "start" start, "end" end, "students" {}}] (swap! course assoc-in [id] thiscourse))) (defn addStudent [id studentname age gender deposit roomNo] (let [student {"age" age, "gender" gender, "deposit" deposit, "roomNo" roomNo, "transactions" []}] (swap! course assoc-in [id "students" studentname] student))) (defn addTransaction [id studentName desc quantity rate date] (let [transaction {"desc" desc, "quantity" quantity, "rate" rate, "total" (* quantity rate), "date" date} length (count (get-in @course [id "students" studentName "transactions"]))] (swap! course assoc-in [id "students" studentName "transactions" length] transaction))) (defn updateDeposit [id studentName amount] (swap! course update-in [id "students" studentName "deposit"] + amount)) (defn save [] (spit file-path (json/write-str @course))) (defn main [] (if (.exists (io/as-file file-path)) (reset! course (json/read-str (slurp file-path))))) (addCourse "1" "Vipasana" 10 "2017-02-18" "2017-02-28") (addStudent "1" "PI:NAME:<NAME>END_PI" 26 "male" 1000 "B5") (addStudent "1" "PI:NAME:<NAME>END_PI" 24 "male" 1000 "A4") (addTransaction "1" "PI:NAME:<NAME>END_PI" "Soap" 2 20 "2017-02-18") (addTransaction "1" "Saurabh" "Water Bottle" 5 15 "2017-02-19") (updateDeposit "1" "Mayank" 1000) ;(def course (atom {:name "Course 1", ; :duration 10 ; :start "2017-02-18" ; :end "2017-02-28" ; :students {}}))
[ { "context": " {:offset \"-04:00\" :zone \"America/St_Kitts\"}\n {:offset \"-04:00\" :zone \"Am", "end": 13212, "score": 0.9995940923690796, "start": 13207, "tag": "NAME", "value": "Kitts" }, { "context": " {:offset \"+13:00\" :zone \"Antarctica/South_Pole\"}\n {:offset \"+03:00\" :zone \"An", "end": 14847, "score": 0.9921277165412903, "start": 14843, "tag": "NAME", "value": "Pole" } ]
src/datasim_ui/timezone.cljs
yetanalytics/datasim-ui
2
(ns datasim-ui.timezone) (def timezones [{:offset "Z" :zone "Africa/Abidjan"} {:offset "Z" :zone "Africa/Accra"} {:offset "+03:00" :zone "Africa/Addis_Ababa"} {:offset "+01:00" :zone "Africa/Algiers"} {:offset "+03:00" :zone "Africa/Asmara"} {:offset "+03:00" :zone "Africa/Asmera"} {:offset "Z" :zone "Africa/Bamako"} {:offset "+01:00" :zone "Africa/Bangui"} {:offset "Z" :zone "Africa/Banjul"} {:offset "Z" :zone "Africa/Bissau"} {:offset "+02:00" :zone "Africa/Blantyre"} {:offset "+01:00" :zone "Africa/Brazzaville"} {:offset "+02:00" :zone "Africa/Bujumbura"} {:offset "+02:00" :zone "Africa/Cairo"} {:offset "Z" :zone "Africa/Casablanca"} {:offset "+01:00" :zone "Africa/Ceuta"} {:offset "Z" :zone "Africa/Conakry"} {:offset "Z" :zone "Africa/Dakar"} {:offset "+03:00" :zone "Africa/Dar_es_Salaam"} {:offset "+03:00" :zone "Africa/Djibouti"} {:offset "+01:00" :zone "Africa/Douala"} {:offset "Z" :zone "Africa/El_Aaiun"} {:offset "Z" :zone "Africa/Freetown"} {:offset "+02:00" :zone "Africa/Gaborone"} {:offset "+02:00" :zone "Africa/Harare"} {:offset "+02:00" :zone "Africa/Johannesburg"} {:offset "+03:00" :zone "Africa/Juba"} {:offset "+03:00" :zone "Africa/Kampala"} {:offset "+03:00" :zone "Africa/Khartoum"} {:offset "+02:00" :zone "Africa/Kigali"} {:offset "+01:00" :zone "Africa/Kinshasa"} {:offset "+01:00" :zone "Africa/Lagos"} {:offset "+01:00" :zone "Africa/Libreville"} {:offset "Z" :zone "Africa/Lome"} {:offset "+01:00" :zone "Africa/Luanda"} {:offset "+02:00" :zone "Africa/Lubumbashi"} {:offset "+02:00" :zone "Africa/Lusaka"} {:offset "+01:00" :zone "Africa/Malabo"} {:offset "+02:00" :zone "Africa/Maputo"} {:offset "+02:00" :zone "Africa/Maseru"} {:offset "+02:00" :zone "Africa/Mbabane"} {:offset "+03:00" :zone "Africa/Mogadishu"} {:offset "Z" :zone "Africa/Monrovia"} {:offset "+03:00" :zone "Africa/Nairobi"} {:offset "+01:00" :zone "Africa/Ndjamena"} {:offset "+01:00" :zone "Africa/Niamey"} {:offset "Z" :zone "Africa/Nouakchott"} {:offset "Z" :zone "Africa/Ouagadougou"} {:offset "+01:00" :zone "Africa/Porto-Novo"} {:offset "Z" :zone "Africa/Sao_Tome"} {:offset "Z" :zone "Africa/Timbuktu"} {:offset "+02:00" :zone "Africa/Tripoli"} {:offset "+01:00" :zone "Africa/Tunis"} {:offset "+02:00" :zone "Africa/Windhoek"} {:offset "-10:00" :zone "America/Adak"} {:offset "-09:00" :zone "America/Anchorage"} {:offset "-04:00" :zone "America/Anguilla"} {:offset "-04:00" :zone "America/Antigua"} {:offset "-03:00" :zone "America/Araguaina"} {:offset "-03:00" :zone "America/Argentina/Buenos_Aires"} {:offset "-03:00" :zone "America/Argentina/Catamarca"} {:offset "-03:00" :zone "America/Argentina/ComodRivadavia"} {:offset "-03:00" :zone "America/Argentina/Cordoba"} {:offset "-03:00" :zone "America/Argentina/Jujuy"} {:offset "-03:00" :zone "America/Argentina/La_Rioja"} {:offset "-03:00" :zone "America/Argentina/Mendoza"} {:offset "-03:00" :zone "America/Argentina/Rio_Gallegos"} {:offset "-03:00" :zone "America/Argentina/Salta"} {:offset "-03:00" :zone "America/Argentina/San_Juan"} {:offset "-03:00" :zone "America/Argentina/San_Luis"} {:offset "-03:00" :zone "America/Argentina/Tucuman"} {:offset "-03:00" :zone "America/Argentina/Ushuaia"} {:offset "-04:00" :zone "America/Aruba"} {:offset "-03:00" :zone "America/Asuncion"} {:offset "-05:00" :zone "America/Atikokan"} {:offset "-10:00" :zone "America/Atka"} {:offset "-03:00" :zone "America/Bahia"} {:offset "-06:00" :zone "America/Bahia_Banderas"} {:offset "-04:00" :zone "America/Barbados"} {:offset "-03:00" :zone "America/Belem"} {:offset "-06:00" :zone "America/Belize"} {:offset "-04:00" :zone "America/Blanc-Sablon"} {:offset "-04:00" :zone "America/Boa_Vista"} {:offset "-05:00" :zone "America/Bogota"} {:offset "-07:00" :zone "America/Boise"} {:offset "-03:00" :zone "America/Buenos_Aires"} {:offset "-07:00" :zone "America/Cambridge_Bay"} {:offset "-03:00" :zone "America/Campo_Grande"} {:offset "-05:00" :zone "America/Cancun"} {:offset "-04:00" :zone "America/Caracas"} {:offset "-03:00" :zone "America/Catamarca"} {:offset "-03:00" :zone "America/Cayenne"} {:offset "-05:00" :zone "America/Cayman"} {:offset "-06:00" :zone "America/Chicago"} {:offset "-07:00" :zone "America/Chihuahua"} {:offset "-05:00" :zone "America/Coral_Harbour"} {:offset "-03:00" :zone "America/Cordoba"} {:offset "-06:00" :zone "America/Costa_Rica"} {:offset "-07:00" :zone "America/Creston"} {:offset "-03:00" :zone "America/Cuiaba"} {:offset "-04:00" :zone "America/Curacao"} {:offset "Z" :zone "America/Danmarkshavn"} {:offset "-08:00" :zone "America/Dawson"} {:offset "-07:00" :zone "America/Dawson_Creek"} {:offset "-07:00" :zone "America/Denver"} {:offset "-05:00" :zone "America/Detroit"} {:offset "-04:00" :zone "America/Dominica"} {:offset "-07:00" :zone "America/Edmonton"} {:offset "-05:00" :zone "America/Eirunepe"} {:offset "-06:00" :zone "America/El_Salvador"} {:offset "-08:00" :zone "America/Ensenada"} {:offset "-07:00" :zone "America/Fort_Nelson"} {:offset "-05:00" :zone "America/Fort_Wayne"} {:offset "-03:00" :zone "America/Fortaleza"} {:offset "-04:00" :zone "America/Glace_Bay"} {:offset "-03:00" :zone "America/Godthab"} {:offset "-04:00" :zone "America/Goose_Bay"} {:offset "-04:00" :zone "America/Grand_Turk"} {:offset "-04:00" :zone "America/Grenada"} {:offset "-04:00" :zone "America/Guadeloupe"} {:offset "-06:00" :zone "America/Guatemala"} {:offset "-05:00" :zone "America/Guayaquil"} {:offset "-04:00" :zone "America/Guyana"} {:offset "-04:00" :zone "America/Halifax"} {:offset "-05:00" :zone "America/Havana"} {:offset "-07:00" :zone "America/Hermosillo"} {:offset "-05:00" :zone "America/Indiana/Indianapolis"} {:offset "-06:00" :zone "America/Indiana/Knox"} {:offset "-05:00" :zone "America/Indiana/Marengo"} {:offset "-05:00" :zone "America/Indiana/Petersburg"} {:offset "-06:00" :zone "America/Indiana/Tell_City"} {:offset "-05:00" :zone "America/Indiana/Vevay"} {:offset "-05:00" :zone "America/Indiana/Vincennes"} {:offset "-05:00" :zone "America/Indiana/Winamac"} {:offset "-05:00" :zone "America/Indianapolis"} {:offset "-07:00" :zone "America/Inuvik"} {:offset "-05:00" :zone "America/Iqaluit"} {:offset "-05:00" :zone "America/Jamaica"} {:offset "-03:00" :zone "America/Jujuy"} {:offset "-09:00" :zone "America/Juneau"} {:offset "-05:00" :zone "America/Kentucky/Louisville"} {:offset "-05:00" :zone "America/Kentucky/Monticello"} {:offset "-06:00" :zone "America/Knox_IN"} {:offset "-04:00" :zone "America/Kralendijk"} {:offset "-04:00" :zone "America/La_Paz"} {:offset "-05:00" :zone "America/Lima"} {:offset "-08:00" :zone "America/Los_Angeles"} {:offset "-05:00" :zone "America/Louisville"} {:offset "-04:00" :zone "America/Lower_Princes"} {:offset "-03:00" :zone "America/Maceio"} {:offset "-06:00" :zone "America/Managua"} {:offset "-04:00" :zone "America/Manaus"} {:offset "-04:00" :zone "America/Marigot"} {:offset "-04:00" :zone "America/Martinique"} {:offset "-06:00" :zone "America/Matamoros"} {:offset "-07:00" :zone "America/Mazatlan"} {:offset "-03:00" :zone "America/Mendoza"} {:offset "-06:00" :zone "America/Menominee"} {:offset "-06:00" :zone "America/Merida"} {:offset "-09:00" :zone "America/Metlakatla"} {:offset "-06:00" :zone "America/Mexico_City"} {:offset "-03:00" :zone "America/Miquelon"} {:offset "-04:00" :zone "America/Moncton"} {:offset "-06:00" :zone "America/Monterrey"} {:offset "-03:00" :zone "America/Montevideo"} {:offset "-05:00" :zone "America/Montreal"} {:offset "-04:00" :zone "America/Montserrat"} {:offset "-05:00" :zone "America/Nassau"} {:offset "-05:00" :zone "America/New_York"} {:offset "-05:00" :zone "America/Nipigon"} {:offset "-09:00" :zone "America/Nome"} {:offset "-02:00" :zone "America/Noronha"} {:offset "-06:00" :zone "America/North_Dakota/Beulah"} {:offset "-06:00" :zone "America/North_Dakota/Center"} {:offset "-06:00" :zone "America/North_Dakota/New_Salem"} {:offset "-07:00" :zone "America/Ojinaga"} {:offset "-05:00" :zone "America/Panama"} {:offset "-05:00" :zone "America/Pangnirtung"} {:offset "-03:00" :zone "America/Paramaribo"} {:offset "-07:00" :zone "America/Phoenix"} {:offset "-05:00" :zone "America/Port-au-Prince"} {:offset "-04:00" :zone "America/Port_of_Spain"} {:offset "-05:00" :zone "America/Porto_Acre"} {:offset "-04:00" :zone "America/Porto_Velho"} {:offset "-04:00" :zone "America/Puerto_Rico"} {:offset "-03:00" :zone "America/Punta_Arenas"} {:offset "-06:00" :zone "America/Rainy_River"} {:offset "-06:00" :zone "America/Rankin_Inlet"} {:offset "-03:00" :zone "America/Recife"} {:offset "-06:00" :zone "America/Regina"} {:offset "-06:00" :zone "America/Resolute"} {:offset "-05:00" :zone "America/Rio_Branco"} {:offset "-03:00" :zone "America/Rosario"} {:offset "-08:00" :zone "America/Santa_Isabel"} {:offset "-03:00" :zone "America/Santarem"} {:offset "-03:00" :zone "America/Santiago"} {:offset "-04:00" :zone "America/Santo_Domingo"} {:offset "-02:00" :zone "America/Sao_Paulo"} {:offset "-01:00" :zone "America/Scoresbysund"} {:offset "-07:00" :zone "America/Shiprock"} {:offset "-09:00" :zone "America/Sitka"} {:offset "-04:00" :zone "America/St_Barthelemy"} {:offset "-03:30" :zone "America/St_Johns"} {:offset "-04:00" :zone "America/St_Kitts"} {:offset "-04:00" :zone "America/St_Lucia"} {:offset "-04:00" :zone "America/St_Thomas"} {:offset "-04:00" :zone "America/St_Vincent"} {:offset "-06:00" :zone "America/Swift_Current"} {:offset "-06:00" :zone "America/Tegucigalpa"} {:offset "-04:00" :zone "America/Thule"} {:offset "-05:00" :zone "America/Thunder_Bay"} {:offset "-08:00" :zone "America/Tijuana"} {:offset "-05:00" :zone "America/Toronto"} {:offset "-04:00" :zone "America/Tortola"} {:offset "-08:00" :zone "America/Vancouver"} {:offset "-04:00" :zone "America/Virgin"} {:offset "-08:00" :zone "America/Whitehorse"} {:offset "-06:00" :zone "America/Winnipeg"} {:offset "-09:00" :zone "America/Yakutat"} {:offset "-07:00" :zone "America/Yellowknife"} {:offset "+11:00" :zone "Antarctica/Casey"} {:offset "+07:00" :zone "Antarctica/Davis"} {:offset "+10:00" :zone "Antarctica/DumontDUrville"} {:offset "+11:00" :zone "Antarctica/Macquarie"} {:offset "+05:00" :zone "Antarctica/Mawson"} {:offset "+13:00" :zone "Antarctica/McMurdo"} {:offset "-03:00" :zone "Antarctica/Palmer"} {:offset "-03:00" :zone "Antarctica/Rothera"} {:offset "+13:00" :zone "Antarctica/South_Pole"} {:offset "+03:00" :zone "Antarctica/Syowa"} {:offset "Z" :zone "Antarctica/Troll"} {:offset "+06:00" :zone "Antarctica/Vostok"} {:offset "+01:00" :zone "Arctic/Longyearbyen"} {:offset "+03:00" :zone "Asia/Aden"} {:offset "+06:00" :zone "Asia/Almaty"} {:offset "+02:00" :zone "Asia/Amman"} {:offset "+12:00" :zone "Asia/Anadyr"} {:offset "+05:00" :zone "Asia/Aqtau"} {:offset "+05:00" :zone "Asia/Aqtobe"} {:offset "+05:00" :zone "Asia/Ashgabat"} {:offset "+05:00" :zone "Asia/Ashkhabad"} {:offset "+05:00" :zone "Asia/Atyrau"} {:offset "+03:00" :zone "Asia/Baghdad"} {:offset "+03:00" :zone "Asia/Bahrain"} {:offset "+04:00" :zone "Asia/Baku"} {:offset "+07:00" :zone "Asia/Bangkok"} {:offset "+07:00" :zone "Asia/Barnaul"} {:offset "+02:00" :zone "Asia/Beirut"} {:offset "+06:00" :zone "Asia/Bishkek"} {:offset "+08:00" :zone "Asia/Brunei"} {:offset "+05:30" :zone "Asia/Calcutta"} {:offset "+09:00" :zone "Asia/Chita"} {:offset "+08:00" :zone "Asia/Choibalsan"} {:offset "+08:00" :zone "Asia/Chongqing"} {:offset "+08:00" :zone "Asia/Chungking"} {:offset "+05:30" :zone "Asia/Colombo"} {:offset "+06:00" :zone "Asia/Dacca"} {:offset "+02:00" :zone "Asia/Damascus"} {:offset "+06:00" :zone "Asia/Dhaka"} {:offset "+09:00" :zone "Asia/Dili"} {:offset "+04:00" :zone "Asia/Dubai"} {:offset "+05:00" :zone "Asia/Dushanbe"} {:offset "+03:00" :zone "Asia/Famagusta"} {:offset "+02:00" :zone "Asia/Gaza"} {:offset "+08:00" :zone "Asia/Harbin"} {:offset "+02:00" :zone "Asia/Hebron"} {:offset "+07:00" :zone "Asia/Ho_Chi_Minh"} {:offset "+08:00" :zone "Asia/Hong_Kong"} {:offset "+07:00" :zone "Asia/Hovd"} {:offset "+08:00" :zone "Asia/Irkutsk"} {:offset "+03:00" :zone "Asia/Istanbul"} {:offset "+07:00" :zone "Asia/Jakarta"} {:offset "+09:00" :zone "Asia/Jayapura"} {:offset "+02:00" :zone "Asia/Jerusalem"} {:offset "+04:30" :zone "Asia/Kabul"} {:offset "+12:00" :zone "Asia/Kamchatka"} {:offset "+05:00" :zone "Asia/Karachi"} {:offset "+06:00" :zone "Asia/Kashgar"} {:offset "+05:45" :zone "Asia/Kathmandu"} {:offset "+05:45" :zone "Asia/Katmandu"} {:offset "+09:00" :zone "Asia/Khandyga"} {:offset "+05:30" :zone "Asia/Kolkata"} {:offset "+07:00" :zone "Asia/Krasnoyarsk"} {:offset "+08:00" :zone "Asia/Kuala_Lumpur"} {:offset "+08:00" :zone "Asia/Kuching"} {:offset "+03:00" :zone "Asia/Kuwait"} {:offset "+08:00" :zone "Asia/Macao"} {:offset "+08:00" :zone "Asia/Macau"} {:offset "+11:00" :zone "Asia/Magadan"} {:offset "+08:00" :zone "Asia/Makassar"} {:offset "+08:00" :zone "Asia/Manila"} {:offset "+04:00" :zone "Asia/Muscat"} {:offset "+02:00" :zone "Asia/Nicosia"} {:offset "+07:00" :zone "Asia/Novokuznetsk"} {:offset "+07:00" :zone "Asia/Novosibirsk"} {:offset "+06:00" :zone "Asia/Omsk"} {:offset "+05:00" :zone "Asia/Oral"} {:offset "+07:00" :zone "Asia/Phnom_Penh"} {:offset "+07:00" :zone "Asia/Pontianak"} {:offset "+08:30" :zone "Asia/Pyongyang"} {:offset "+03:00" :zone "Asia/Qatar"} {:offset "+06:00" :zone "Asia/Qyzylorda"} {:offset "+06:30" :zone "Asia/Rangoon"} {:offset "+03:00" :zone "Asia/Riyadh"} {:offset "+07:00" :zone "Asia/Saigon"} {:offset "+11:00" :zone "Asia/Sakhalin"} {:offset "+05:00" :zone "Asia/Samarkand"} {:offset "+09:00" :zone "Asia/Seoul"} {:offset "+08:00" :zone "Asia/Shanghai"} {:offset "+08:00" :zone "Asia/Singapore"} {:offset "+11:00" :zone "Asia/Srednekolymsk"} {:offset "+08:00" :zone "Asia/Taipei"} {:offset "+05:00" :zone "Asia/Tashkent"} {:offset "+04:00" :zone "Asia/Tbilisi"} {:offset "+03:30" :zone "Asia/Tehran"} {:offset "+02:00" :zone "Asia/Tel_Aviv"} {:offset "+06:00" :zone "Asia/Thimbu"} {:offset "+06:00" :zone "Asia/Thimphu"} {:offset "+09:00" :zone "Asia/Tokyo"} {:offset "+07:00" :zone "Asia/Tomsk"} {:offset "+08:00" :zone "Asia/Ujung_Pandang"} {:offset "+08:00" :zone "Asia/Ulaanbaatar"} {:offset "+08:00" :zone "Asia/Ulan_Bator"} {:offset "+06:00" :zone "Asia/Urumqi"} {:offset "+10:00" :zone "Asia/Ust-Nera"} {:offset "+07:00" :zone "Asia/Vientiane"} {:offset "+10:00" :zone "Asia/Vladivostok"} {:offset "+09:00" :zone "Asia/Yakutsk"} {:offset "+06:30" :zone "Asia/Yangon"} {:offset "+05:00" :zone "Asia/Yekaterinburg"} {:offset "+04:00" :zone "Asia/Yerevan"} {:offset "-01:00" :zone "Atlantic/Azores"} {:offset "-04:00" :zone "Atlantic/Bermuda"} {:offset "Z" :zone "Atlantic/Canary"} {:offset "-01:00" :zone "Atlantic/Cape_Verde"} {:offset "Z" :zone "Atlantic/Faeroe"} {:offset "Z" :zone "Atlantic/Faroe"} {:offset "+01:00" :zone "Atlantic/Jan_Mayen"} {:offset "Z" :zone "Atlantic/Madeira"} {:offset "Z" :zone "Atlantic/Reykjavik"} {:offset "-02:00" :zone "Atlantic/South_Georgia"} {:offset "Z" :zone "Atlantic/St_Helena"} {:offset "-03:00" :zone "Atlantic/Stanley"} {:offset "+11:00" :zone "Australia/ACT"} {:offset "+10:30" :zone "Australia/Adelaide"} {:offset "+10:00" :zone "Australia/Brisbane"} {:offset "+10:30" :zone "Australia/Broken_Hill"} {:offset "+11:00" :zone "Australia/Canberra"} {:offset "+11:00" :zone "Australia/Currie"} {:offset "+09:30" :zone "Australia/Darwin"} {:offset "+08:45" :zone "Australia/Eucla"} {:offset "+11:00" :zone "Australia/Hobart"} {:offset "+11:00" :zone "Australia/LHI"} {:offset "+10:00" :zone "Australia/Lindeman"} {:offset "+11:00" :zone "Australia/Lord_Howe"} {:offset "+11:00" :zone "Australia/Melbourne"} {:offset "+11:00" :zone "Australia/NSW"} {:offset "+09:30" :zone "Australia/North"} {:offset "+08:00" :zone "Australia/Perth"} {:offset "+10:00" :zone "Australia/Queensland"} {:offset "+10:30" :zone "Australia/South"} {:offset "+11:00" :zone "Australia/Sydney"} {:offset "+11:00" :zone "Australia/Tasmania"} {:offset "+11:00" :zone "Australia/Victoria"} {:offset "+08:00" :zone "Australia/West"} {:offset "+10:30" :zone "Australia/Yancowinna"} {:offset "-05:00" :zone "Brazil/Acre"} {:offset "-02:00" :zone "Brazil/DeNoronha"} {:offset "-02:00" :zone "Brazil/East"} {:offset "-04:00" :zone "Brazil/West"} {:offset "+01:00" :zone "CET"} {:offset "-06:00" :zone "CST6CDT"} {:offset "-04:00" :zone "Canada/Atlantic"} {:offset "-06:00" :zone "Canada/Central"} {:offset "-06:00" :zone "Canada/East-Saskatchewan"} {:offset "-05:00" :zone "Canada/Eastern"} {:offset "-07:00" :zone "Canada/Mountain"} {:offset "-03:30" :zone "Canada/Newfoundland"} {:offset "-08:00" :zone "Canada/Pacific"} {:offset "-06:00" :zone "Canada/Saskatchewan"} {:offset "-08:00" :zone "Canada/Yukon"} {:offset "-03:00" :zone "Chile/Continental"} {:offset "-05:00" :zone "Chile/EasterIsland"} {:offset "-05:00" :zone "Cuba"} {:offset "+02:00" :zone "EET"} {:offset "-05:00" :zone "EST5EDT"} {:offset "+02:00" :zone "Egypt"} {:offset "Z" :zone "Eire"} {:offset "Z" :zone "Etc/GMT"} {:offset "Z" :zone "Etc/GMT+0"} {:offset "-01:00" :zone "Etc/GMT+1"} {:offset "-10:00" :zone "Etc/GMT+10"} {:offset "-11:00" :zone "Etc/GMT+11"} {:offset "-12:00" :zone "Etc/GMT+12"} {:offset "-02:00" :zone "Etc/GMT+2"} {:offset "-03:00" :zone "Etc/GMT+3"} {:offset "-04:00" :zone "Etc/GMT+4"} {:offset "-05:00" :zone "Etc/GMT+5"} {:offset "-06:00" :zone "Etc/GMT+6"} {:offset "-07:00" :zone "Etc/GMT+7"} {:offset "-08:00" :zone "Etc/GMT+8"} {:offset "-09:00" :zone "Etc/GMT+9"} {:offset "Z" :zone "Etc/GMT-0"} {:offset "+01:00" :zone "Etc/GMT-1"} {:offset "+10:00" :zone "Etc/GMT-10"} {:offset "+11:00" :zone "Etc/GMT-11"} {:offset "+12:00" :zone "Etc/GMT-12"} {:offset "+13:00" :zone "Etc/GMT-13"} {:offset "+14:00" :zone "Etc/GMT-14"} {:offset "+02:00" :zone "Etc/GMT-2"} {:offset "+03:00" :zone "Etc/GMT-3"} {:offset "+04:00" :zone "Etc/GMT-4"} {:offset "+05:00" :zone "Etc/GMT-5"} {:offset "+06:00" :zone "Etc/GMT-6"} {:offset "+07:00" :zone "Etc/GMT-7"} {:offset "+08:00" :zone "Etc/GMT-8"} {:offset "+09:00" :zone "Etc/GMT-9"} {:offset "Z" :zone "Etc/GMT0"} {:offset "Z" :zone "Etc/Greenwich"} {:offset "Z" :zone "Etc/UCT"} {:offset "Z" :zone "Etc/UTC"} {:offset "Z" :zone "Etc/Universal"} {:offset "Z" :zone "Etc/Zulu"} {:offset "+01:00" :zone "Europe/Amsterdam"} {:offset "+01:00" :zone "Europe/Andorra"} {:offset "+04:00" :zone "Europe/Astrakhan"} {:offset "+02:00" :zone "Europe/Athens"} {:offset "Z" :zone "Europe/Belfast"} {:offset "+01:00" :zone "Europe/Belgrade"} {:offset "+01:00" :zone "Europe/Berlin"} {:offset "+01:00" :zone "Europe/Bratislava"} {:offset "+01:00" :zone "Europe/Brussels"} {:offset "+02:00" :zone "Europe/Bucharest"} {:offset "+01:00" :zone "Europe/Budapest"} {:offset "+01:00" :zone "Europe/Busingen"} {:offset "+02:00" :zone "Europe/Chisinau"} {:offset "+01:00" :zone "Europe/Copenhagen"} {:offset "Z" :zone "Europe/Dublin"} {:offset "+01:00" :zone "Europe/Gibraltar"} {:offset "Z" :zone "Europe/Guernsey"} {:offset "+02:00" :zone "Europe/Helsinki"} {:offset "Z" :zone "Europe/Isle_of_Man"} {:offset "+03:00" :zone "Europe/Istanbul"} {:offset "Z" :zone "Europe/Jersey"} {:offset "+02:00" :zone "Europe/Kaliningrad"} {:offset "+02:00" :zone "Europe/Kiev"} {:offset "+03:00" :zone "Europe/Kirov"} {:offset "Z" :zone "Europe/Lisbon"} {:offset "+01:00" :zone "Europe/Ljubljana"} {:offset "Z" :zone "Europe/London"} {:offset "+01:00" :zone "Europe/Luxembourg"} {:offset "+01:00" :zone "Europe/Madrid"} {:offset "+01:00" :zone "Europe/Malta"} {:offset "+02:00" :zone "Europe/Mariehamn"} {:offset "+03:00" :zone "Europe/Minsk"} {:offset "+01:00" :zone "Europe/Monaco"} {:offset "+03:00" :zone "Europe/Moscow"} {:offset "+02:00" :zone "Europe/Nicosia"} {:offset "+01:00" :zone "Europe/Oslo"} {:offset "+01:00" :zone "Europe/Paris"} {:offset "+01:00" :zone "Europe/Podgorica"} {:offset "+01:00" :zone "Europe/Prague"} {:offset "+02:00" :zone "Europe/Riga"} {:offset "+01:00" :zone "Europe/Rome"} {:offset "+04:00" :zone "Europe/Samara"} {:offset "+01:00" :zone "Europe/San_Marino"} {:offset "+01:00" :zone "Europe/Sarajevo"} {:offset "+04:00" :zone "Europe/Saratov"} {:offset "+03:00" :zone "Europe/Simferopol"} {:offset "+01:00" :zone "Europe/Skopje"} {:offset "+02:00" :zone "Europe/Sofia"} {:offset "+01:00" :zone "Europe/Stockholm"} {:offset "+02:00" :zone "Europe/Tallinn"} {:offset "+01:00" :zone "Europe/Tirane"} {:offset "+02:00" :zone "Europe/Tiraspol"} {:offset "+04:00" :zone "Europe/Ulyanovsk"} {:offset "+02:00" :zone "Europe/Uzhgorod"} {:offset "+01:00" :zone "Europe/Vaduz"} {:offset "+01:00" :zone "Europe/Vatican"} {:offset "+01:00" :zone "Europe/Vienna"} {:offset "+02:00" :zone "Europe/Vilnius"} {:offset "+03:00" :zone "Europe/Volgograd"} {:offset "+01:00" :zone "Europe/Warsaw"} {:offset "+01:00" :zone "Europe/Zagreb"} {:offset "+02:00" :zone "Europe/Zaporozhye"} {:offset "+01:00" :zone "Europe/Zurich"} {:offset "Z" :zone "GB"} {:offset "Z" :zone "GB-Eire"} {:offset "Z" :zone "GMT"} {:offset "Z" :zone "GMT0"} {:offset "Z" :zone "Greenwich"} {:offset "+08:00" :zone "Hongkong"} {:offset "Z" :zone "Iceland"} {:offset "+03:00" :zone "Indian/Antananarivo"} {:offset "+06:00" :zone "Indian/Chagos"} {:offset "+07:00" :zone "Indian/Christmas"} {:offset "+06:30" :zone "Indian/Cocos"} {:offset "+03:00" :zone "Indian/Comoro"} {:offset "+05:00" :zone "Indian/Kerguelen"} {:offset "+04:00" :zone "Indian/Mahe"} {:offset "+05:00" :zone "Indian/Maldives"} {:offset "+04:00" :zone "Indian/Mauritius"} {:offset "+03:00" :zone "Indian/Mayotte"} {:offset "+04:00" :zone "Indian/Reunion"} {:offset "+03:30" :zone "Iran"} {:offset "+02:00" :zone "Israel"} {:offset "-05:00" :zone "Jamaica"} {:offset "+09:00" :zone "Japan"} {:offset "+12:00" :zone "Kwajalein"} {:offset "+02:00" :zone "Libya"} {:offset "+01:00" :zone "MET"} {:offset "-07:00" :zone "MST7MDT"} {:offset "-08:00" :zone "Mexico/BajaNorte"} {:offset "-07:00" :zone "Mexico/BajaSur"} {:offset "-06:00" :zone "Mexico/General"} {:offset "+13:00" :zone "NZ"} {:offset "+13:45" :zone "NZ-CHAT"} {:offset "-07:00" :zone "Navajo"} {:offset "+08:00" :zone "PRC"} {:offset "-08:00" :zone "PST8PDT"} {:offset "+14:00" :zone "Pacific/Apia"} {:offset "+13:00" :zone "Pacific/Auckland"} {:offset "+11:00" :zone "Pacific/Bougainville"} {:offset "+13:45" :zone "Pacific/Chatham"} {:offset "+10:00" :zone "Pacific/Chuuk"} {:offset "-05:00" :zone "Pacific/Easter"} {:offset "+11:00" :zone "Pacific/Efate"} {:offset "+13:00" :zone "Pacific/Enderbury"} {:offset "+13:00" :zone "Pacific/Fakaofo"} {:offset "+12:00" :zone "Pacific/Fiji"} {:offset "+12:00" :zone "Pacific/Funafuti"} {:offset "-06:00" :zone "Pacific/Galapagos"} {:offset "-09:00" :zone "Pacific/Gambier"} {:offset "+11:00" :zone "Pacific/Guadalcanal"} {:offset "+10:00" :zone "Pacific/Guam"} {:offset "-10:00" :zone "Pacific/Honolulu"} {:offset "-10:00" :zone "Pacific/Johnston"} {:offset "+14:00" :zone "Pacific/Kiritimati"} {:offset "+11:00" :zone "Pacific/Kosrae"} {:offset "+12:00" :zone "Pacific/Kwajalein"} {:offset "+12:00" :zone "Pacific/Majuro"} {:offset "-09:30" :zone "Pacific/Marquesas"} {:offset "-11:00" :zone "Pacific/Midway"} {:offset "+12:00" :zone "Pacific/Nauru"} {:offset "-11:00" :zone "Pacific/Niue"} {:offset "+11:00" :zone "Pacific/Norfolk"} {:offset "+11:00" :zone "Pacific/Noumea"} {:offset "-11:00" :zone "Pacific/Pago_Pago"} {:offset "+09:00" :zone "Pacific/Palau"} {:offset "-08:00" :zone "Pacific/Pitcairn"} {:offset "+11:00" :zone "Pacific/Pohnpei"} {:offset "+11:00" :zone "Pacific/Ponape"} {:offset "+10:00" :zone "Pacific/Port_Moresby"} {:offset "-10:00" :zone "Pacific/Rarotonga"} {:offset "+10:00" :zone "Pacific/Saipan"} {:offset "-11:00" :zone "Pacific/Samoa"} {:offset "-10:00" :zone "Pacific/Tahiti"} {:offset "+12:00" :zone "Pacific/Tarawa"} {:offset "+13:00" :zone "Pacific/Tongatapu"} {:offset "+10:00" :zone "Pacific/Truk"} {:offset "+12:00" :zone "Pacific/Wake"} {:offset "+12:00" :zone "Pacific/Wallis"} {:offset "+10:00" :zone "Pacific/Yap"} {:offset "+01:00" :zone "Poland"} {:offset "Z" :zone "Portugal"} {:offset "+09:00" :zone "ROK"} {:offset "+08:00" :zone "Singapore"} {:offset "-04:00" :zone "SystemV/AST4"} {:offset "-04:00" :zone "SystemV/AST4ADT"} {:offset "-06:00" :zone "SystemV/CST6"} {:offset "-06:00" :zone "SystemV/CST6CDT"} {:offset "-05:00" :zone "SystemV/EST5"} {:offset "-05:00" :zone "SystemV/EST5EDT"} {:offset "-10:00" :zone "SystemV/HST10"} {:offset "-07:00" :zone "SystemV/MST7"} {:offset "-07:00" :zone "SystemV/MST7MDT"} {:offset "-08:00" :zone "SystemV/PST8"} {:offset "-08:00" :zone "SystemV/PST8PDT"} {:offset "-09:00" :zone "SystemV/YST9"} {:offset "-09:00" :zone "SystemV/YST9YDT"} {:offset "+03:00" :zone "Turkey"} {:offset "Z" :zone "UCT"} {:offset "-09:00" :zone "US/Alaska"} {:offset "-10:00" :zone "US/Aleutian"} {:offset "-07:00" :zone "US/Arizona"} {:offset "-06:00" :zone "US/Central"} {:offset "-05:00" :zone "US/East-Indiana"} {:offset "-05:00" :zone "US/Eastern"} {:offset "-10:00" :zone "US/Hawaii"} {:offset "-06:00" :zone "US/Indiana-Starke"} {:offset "-05:00" :zone "US/Michigan"} {:offset "-07:00" :zone "US/Mountain"} {:offset "-08:00" :zone "US/Pacific"} {:offset "-08:00" :zone "US/Pacific-New"} {:offset "-11:00" :zone "US/Samoa"} {:offset "Z" :zone "UTC"} {:offset "Z" :zone "Universal"} {:offset "+03:00" :zone "W-SU"} {:offset "Z" :zone "WET"} {:offset "Z" :zone "Zulu"}])
3224
(ns datasim-ui.timezone) (def timezones [{:offset "Z" :zone "Africa/Abidjan"} {:offset "Z" :zone "Africa/Accra"} {:offset "+03:00" :zone "Africa/Addis_Ababa"} {:offset "+01:00" :zone "Africa/Algiers"} {:offset "+03:00" :zone "Africa/Asmara"} {:offset "+03:00" :zone "Africa/Asmera"} {:offset "Z" :zone "Africa/Bamako"} {:offset "+01:00" :zone "Africa/Bangui"} {:offset "Z" :zone "Africa/Banjul"} {:offset "Z" :zone "Africa/Bissau"} {:offset "+02:00" :zone "Africa/Blantyre"} {:offset "+01:00" :zone "Africa/Brazzaville"} {:offset "+02:00" :zone "Africa/Bujumbura"} {:offset "+02:00" :zone "Africa/Cairo"} {:offset "Z" :zone "Africa/Casablanca"} {:offset "+01:00" :zone "Africa/Ceuta"} {:offset "Z" :zone "Africa/Conakry"} {:offset "Z" :zone "Africa/Dakar"} {:offset "+03:00" :zone "Africa/Dar_es_Salaam"} {:offset "+03:00" :zone "Africa/Djibouti"} {:offset "+01:00" :zone "Africa/Douala"} {:offset "Z" :zone "Africa/El_Aaiun"} {:offset "Z" :zone "Africa/Freetown"} {:offset "+02:00" :zone "Africa/Gaborone"} {:offset "+02:00" :zone "Africa/Harare"} {:offset "+02:00" :zone "Africa/Johannesburg"} {:offset "+03:00" :zone "Africa/Juba"} {:offset "+03:00" :zone "Africa/Kampala"} {:offset "+03:00" :zone "Africa/Khartoum"} {:offset "+02:00" :zone "Africa/Kigali"} {:offset "+01:00" :zone "Africa/Kinshasa"} {:offset "+01:00" :zone "Africa/Lagos"} {:offset "+01:00" :zone "Africa/Libreville"} {:offset "Z" :zone "Africa/Lome"} {:offset "+01:00" :zone "Africa/Luanda"} {:offset "+02:00" :zone "Africa/Lubumbashi"} {:offset "+02:00" :zone "Africa/Lusaka"} {:offset "+01:00" :zone "Africa/Malabo"} {:offset "+02:00" :zone "Africa/Maputo"} {:offset "+02:00" :zone "Africa/Maseru"} {:offset "+02:00" :zone "Africa/Mbabane"} {:offset "+03:00" :zone "Africa/Mogadishu"} {:offset "Z" :zone "Africa/Monrovia"} {:offset "+03:00" :zone "Africa/Nairobi"} {:offset "+01:00" :zone "Africa/Ndjamena"} {:offset "+01:00" :zone "Africa/Niamey"} {:offset "Z" :zone "Africa/Nouakchott"} {:offset "Z" :zone "Africa/Ouagadougou"} {:offset "+01:00" :zone "Africa/Porto-Novo"} {:offset "Z" :zone "Africa/Sao_Tome"} {:offset "Z" :zone "Africa/Timbuktu"} {:offset "+02:00" :zone "Africa/Tripoli"} {:offset "+01:00" :zone "Africa/Tunis"} {:offset "+02:00" :zone "Africa/Windhoek"} {:offset "-10:00" :zone "America/Adak"} {:offset "-09:00" :zone "America/Anchorage"} {:offset "-04:00" :zone "America/Anguilla"} {:offset "-04:00" :zone "America/Antigua"} {:offset "-03:00" :zone "America/Araguaina"} {:offset "-03:00" :zone "America/Argentina/Buenos_Aires"} {:offset "-03:00" :zone "America/Argentina/Catamarca"} {:offset "-03:00" :zone "America/Argentina/ComodRivadavia"} {:offset "-03:00" :zone "America/Argentina/Cordoba"} {:offset "-03:00" :zone "America/Argentina/Jujuy"} {:offset "-03:00" :zone "America/Argentina/La_Rioja"} {:offset "-03:00" :zone "America/Argentina/Mendoza"} {:offset "-03:00" :zone "America/Argentina/Rio_Gallegos"} {:offset "-03:00" :zone "America/Argentina/Salta"} {:offset "-03:00" :zone "America/Argentina/San_Juan"} {:offset "-03:00" :zone "America/Argentina/San_Luis"} {:offset "-03:00" :zone "America/Argentina/Tucuman"} {:offset "-03:00" :zone "America/Argentina/Ushuaia"} {:offset "-04:00" :zone "America/Aruba"} {:offset "-03:00" :zone "America/Asuncion"} {:offset "-05:00" :zone "America/Atikokan"} {:offset "-10:00" :zone "America/Atka"} {:offset "-03:00" :zone "America/Bahia"} {:offset "-06:00" :zone "America/Bahia_Banderas"} {:offset "-04:00" :zone "America/Barbados"} {:offset "-03:00" :zone "America/Belem"} {:offset "-06:00" :zone "America/Belize"} {:offset "-04:00" :zone "America/Blanc-Sablon"} {:offset "-04:00" :zone "America/Boa_Vista"} {:offset "-05:00" :zone "America/Bogota"} {:offset "-07:00" :zone "America/Boise"} {:offset "-03:00" :zone "America/Buenos_Aires"} {:offset "-07:00" :zone "America/Cambridge_Bay"} {:offset "-03:00" :zone "America/Campo_Grande"} {:offset "-05:00" :zone "America/Cancun"} {:offset "-04:00" :zone "America/Caracas"} {:offset "-03:00" :zone "America/Catamarca"} {:offset "-03:00" :zone "America/Cayenne"} {:offset "-05:00" :zone "America/Cayman"} {:offset "-06:00" :zone "America/Chicago"} {:offset "-07:00" :zone "America/Chihuahua"} {:offset "-05:00" :zone "America/Coral_Harbour"} {:offset "-03:00" :zone "America/Cordoba"} {:offset "-06:00" :zone "America/Costa_Rica"} {:offset "-07:00" :zone "America/Creston"} {:offset "-03:00" :zone "America/Cuiaba"} {:offset "-04:00" :zone "America/Curacao"} {:offset "Z" :zone "America/Danmarkshavn"} {:offset "-08:00" :zone "America/Dawson"} {:offset "-07:00" :zone "America/Dawson_Creek"} {:offset "-07:00" :zone "America/Denver"} {:offset "-05:00" :zone "America/Detroit"} {:offset "-04:00" :zone "America/Dominica"} {:offset "-07:00" :zone "America/Edmonton"} {:offset "-05:00" :zone "America/Eirunepe"} {:offset "-06:00" :zone "America/El_Salvador"} {:offset "-08:00" :zone "America/Ensenada"} {:offset "-07:00" :zone "America/Fort_Nelson"} {:offset "-05:00" :zone "America/Fort_Wayne"} {:offset "-03:00" :zone "America/Fortaleza"} {:offset "-04:00" :zone "America/Glace_Bay"} {:offset "-03:00" :zone "America/Godthab"} {:offset "-04:00" :zone "America/Goose_Bay"} {:offset "-04:00" :zone "America/Grand_Turk"} {:offset "-04:00" :zone "America/Grenada"} {:offset "-04:00" :zone "America/Guadeloupe"} {:offset "-06:00" :zone "America/Guatemala"} {:offset "-05:00" :zone "America/Guayaquil"} {:offset "-04:00" :zone "America/Guyana"} {:offset "-04:00" :zone "America/Halifax"} {:offset "-05:00" :zone "America/Havana"} {:offset "-07:00" :zone "America/Hermosillo"} {:offset "-05:00" :zone "America/Indiana/Indianapolis"} {:offset "-06:00" :zone "America/Indiana/Knox"} {:offset "-05:00" :zone "America/Indiana/Marengo"} {:offset "-05:00" :zone "America/Indiana/Petersburg"} {:offset "-06:00" :zone "America/Indiana/Tell_City"} {:offset "-05:00" :zone "America/Indiana/Vevay"} {:offset "-05:00" :zone "America/Indiana/Vincennes"} {:offset "-05:00" :zone "America/Indiana/Winamac"} {:offset "-05:00" :zone "America/Indianapolis"} {:offset "-07:00" :zone "America/Inuvik"} {:offset "-05:00" :zone "America/Iqaluit"} {:offset "-05:00" :zone "America/Jamaica"} {:offset "-03:00" :zone "America/Jujuy"} {:offset "-09:00" :zone "America/Juneau"} {:offset "-05:00" :zone "America/Kentucky/Louisville"} {:offset "-05:00" :zone "America/Kentucky/Monticello"} {:offset "-06:00" :zone "America/Knox_IN"} {:offset "-04:00" :zone "America/Kralendijk"} {:offset "-04:00" :zone "America/La_Paz"} {:offset "-05:00" :zone "America/Lima"} {:offset "-08:00" :zone "America/Los_Angeles"} {:offset "-05:00" :zone "America/Louisville"} {:offset "-04:00" :zone "America/Lower_Princes"} {:offset "-03:00" :zone "America/Maceio"} {:offset "-06:00" :zone "America/Managua"} {:offset "-04:00" :zone "America/Manaus"} {:offset "-04:00" :zone "America/Marigot"} {:offset "-04:00" :zone "America/Martinique"} {:offset "-06:00" :zone "America/Matamoros"} {:offset "-07:00" :zone "America/Mazatlan"} {:offset "-03:00" :zone "America/Mendoza"} {:offset "-06:00" :zone "America/Menominee"} {:offset "-06:00" :zone "America/Merida"} {:offset "-09:00" :zone "America/Metlakatla"} {:offset "-06:00" :zone "America/Mexico_City"} {:offset "-03:00" :zone "America/Miquelon"} {:offset "-04:00" :zone "America/Moncton"} {:offset "-06:00" :zone "America/Monterrey"} {:offset "-03:00" :zone "America/Montevideo"} {:offset "-05:00" :zone "America/Montreal"} {:offset "-04:00" :zone "America/Montserrat"} {:offset "-05:00" :zone "America/Nassau"} {:offset "-05:00" :zone "America/New_York"} {:offset "-05:00" :zone "America/Nipigon"} {:offset "-09:00" :zone "America/Nome"} {:offset "-02:00" :zone "America/Noronha"} {:offset "-06:00" :zone "America/North_Dakota/Beulah"} {:offset "-06:00" :zone "America/North_Dakota/Center"} {:offset "-06:00" :zone "America/North_Dakota/New_Salem"} {:offset "-07:00" :zone "America/Ojinaga"} {:offset "-05:00" :zone "America/Panama"} {:offset "-05:00" :zone "America/Pangnirtung"} {:offset "-03:00" :zone "America/Paramaribo"} {:offset "-07:00" :zone "America/Phoenix"} {:offset "-05:00" :zone "America/Port-au-Prince"} {:offset "-04:00" :zone "America/Port_of_Spain"} {:offset "-05:00" :zone "America/Porto_Acre"} {:offset "-04:00" :zone "America/Porto_Velho"} {:offset "-04:00" :zone "America/Puerto_Rico"} {:offset "-03:00" :zone "America/Punta_Arenas"} {:offset "-06:00" :zone "America/Rainy_River"} {:offset "-06:00" :zone "America/Rankin_Inlet"} {:offset "-03:00" :zone "America/Recife"} {:offset "-06:00" :zone "America/Regina"} {:offset "-06:00" :zone "America/Resolute"} {:offset "-05:00" :zone "America/Rio_Branco"} {:offset "-03:00" :zone "America/Rosario"} {:offset "-08:00" :zone "America/Santa_Isabel"} {:offset "-03:00" :zone "America/Santarem"} {:offset "-03:00" :zone "America/Santiago"} {:offset "-04:00" :zone "America/Santo_Domingo"} {:offset "-02:00" :zone "America/Sao_Paulo"} {:offset "-01:00" :zone "America/Scoresbysund"} {:offset "-07:00" :zone "America/Shiprock"} {:offset "-09:00" :zone "America/Sitka"} {:offset "-04:00" :zone "America/St_Barthelemy"} {:offset "-03:30" :zone "America/St_Johns"} {:offset "-04:00" :zone "America/St_<NAME>"} {:offset "-04:00" :zone "America/St_Lucia"} {:offset "-04:00" :zone "America/St_Thomas"} {:offset "-04:00" :zone "America/St_Vincent"} {:offset "-06:00" :zone "America/Swift_Current"} {:offset "-06:00" :zone "America/Tegucigalpa"} {:offset "-04:00" :zone "America/Thule"} {:offset "-05:00" :zone "America/Thunder_Bay"} {:offset "-08:00" :zone "America/Tijuana"} {:offset "-05:00" :zone "America/Toronto"} {:offset "-04:00" :zone "America/Tortola"} {:offset "-08:00" :zone "America/Vancouver"} {:offset "-04:00" :zone "America/Virgin"} {:offset "-08:00" :zone "America/Whitehorse"} {:offset "-06:00" :zone "America/Winnipeg"} {:offset "-09:00" :zone "America/Yakutat"} {:offset "-07:00" :zone "America/Yellowknife"} {:offset "+11:00" :zone "Antarctica/Casey"} {:offset "+07:00" :zone "Antarctica/Davis"} {:offset "+10:00" :zone "Antarctica/DumontDUrville"} {:offset "+11:00" :zone "Antarctica/Macquarie"} {:offset "+05:00" :zone "Antarctica/Mawson"} {:offset "+13:00" :zone "Antarctica/McMurdo"} {:offset "-03:00" :zone "Antarctica/Palmer"} {:offset "-03:00" :zone "Antarctica/Rothera"} {:offset "+13:00" :zone "Antarctica/South_<NAME>"} {:offset "+03:00" :zone "Antarctica/Syowa"} {:offset "Z" :zone "Antarctica/Troll"} {:offset "+06:00" :zone "Antarctica/Vostok"} {:offset "+01:00" :zone "Arctic/Longyearbyen"} {:offset "+03:00" :zone "Asia/Aden"} {:offset "+06:00" :zone "Asia/Almaty"} {:offset "+02:00" :zone "Asia/Amman"} {:offset "+12:00" :zone "Asia/Anadyr"} {:offset "+05:00" :zone "Asia/Aqtau"} {:offset "+05:00" :zone "Asia/Aqtobe"} {:offset "+05:00" :zone "Asia/Ashgabat"} {:offset "+05:00" :zone "Asia/Ashkhabad"} {:offset "+05:00" :zone "Asia/Atyrau"} {:offset "+03:00" :zone "Asia/Baghdad"} {:offset "+03:00" :zone "Asia/Bahrain"} {:offset "+04:00" :zone "Asia/Baku"} {:offset "+07:00" :zone "Asia/Bangkok"} {:offset "+07:00" :zone "Asia/Barnaul"} {:offset "+02:00" :zone "Asia/Beirut"} {:offset "+06:00" :zone "Asia/Bishkek"} {:offset "+08:00" :zone "Asia/Brunei"} {:offset "+05:30" :zone "Asia/Calcutta"} {:offset "+09:00" :zone "Asia/Chita"} {:offset "+08:00" :zone "Asia/Choibalsan"} {:offset "+08:00" :zone "Asia/Chongqing"} {:offset "+08:00" :zone "Asia/Chungking"} {:offset "+05:30" :zone "Asia/Colombo"} {:offset "+06:00" :zone "Asia/Dacca"} {:offset "+02:00" :zone "Asia/Damascus"} {:offset "+06:00" :zone "Asia/Dhaka"} {:offset "+09:00" :zone "Asia/Dili"} {:offset "+04:00" :zone "Asia/Dubai"} {:offset "+05:00" :zone "Asia/Dushanbe"} {:offset "+03:00" :zone "Asia/Famagusta"} {:offset "+02:00" :zone "Asia/Gaza"} {:offset "+08:00" :zone "Asia/Harbin"} {:offset "+02:00" :zone "Asia/Hebron"} {:offset "+07:00" :zone "Asia/Ho_Chi_Minh"} {:offset "+08:00" :zone "Asia/Hong_Kong"} {:offset "+07:00" :zone "Asia/Hovd"} {:offset "+08:00" :zone "Asia/Irkutsk"} {:offset "+03:00" :zone "Asia/Istanbul"} {:offset "+07:00" :zone "Asia/Jakarta"} {:offset "+09:00" :zone "Asia/Jayapura"} {:offset "+02:00" :zone "Asia/Jerusalem"} {:offset "+04:30" :zone "Asia/Kabul"} {:offset "+12:00" :zone "Asia/Kamchatka"} {:offset "+05:00" :zone "Asia/Karachi"} {:offset "+06:00" :zone "Asia/Kashgar"} {:offset "+05:45" :zone "Asia/Kathmandu"} {:offset "+05:45" :zone "Asia/Katmandu"} {:offset "+09:00" :zone "Asia/Khandyga"} {:offset "+05:30" :zone "Asia/Kolkata"} {:offset "+07:00" :zone "Asia/Krasnoyarsk"} {:offset "+08:00" :zone "Asia/Kuala_Lumpur"} {:offset "+08:00" :zone "Asia/Kuching"} {:offset "+03:00" :zone "Asia/Kuwait"} {:offset "+08:00" :zone "Asia/Macao"} {:offset "+08:00" :zone "Asia/Macau"} {:offset "+11:00" :zone "Asia/Magadan"} {:offset "+08:00" :zone "Asia/Makassar"} {:offset "+08:00" :zone "Asia/Manila"} {:offset "+04:00" :zone "Asia/Muscat"} {:offset "+02:00" :zone "Asia/Nicosia"} {:offset "+07:00" :zone "Asia/Novokuznetsk"} {:offset "+07:00" :zone "Asia/Novosibirsk"} {:offset "+06:00" :zone "Asia/Omsk"} {:offset "+05:00" :zone "Asia/Oral"} {:offset "+07:00" :zone "Asia/Phnom_Penh"} {:offset "+07:00" :zone "Asia/Pontianak"} {:offset "+08:30" :zone "Asia/Pyongyang"} {:offset "+03:00" :zone "Asia/Qatar"} {:offset "+06:00" :zone "Asia/Qyzylorda"} {:offset "+06:30" :zone "Asia/Rangoon"} {:offset "+03:00" :zone "Asia/Riyadh"} {:offset "+07:00" :zone "Asia/Saigon"} {:offset "+11:00" :zone "Asia/Sakhalin"} {:offset "+05:00" :zone "Asia/Samarkand"} {:offset "+09:00" :zone "Asia/Seoul"} {:offset "+08:00" :zone "Asia/Shanghai"} {:offset "+08:00" :zone "Asia/Singapore"} {:offset "+11:00" :zone "Asia/Srednekolymsk"} {:offset "+08:00" :zone "Asia/Taipei"} {:offset "+05:00" :zone "Asia/Tashkent"} {:offset "+04:00" :zone "Asia/Tbilisi"} {:offset "+03:30" :zone "Asia/Tehran"} {:offset "+02:00" :zone "Asia/Tel_Aviv"} {:offset "+06:00" :zone "Asia/Thimbu"} {:offset "+06:00" :zone "Asia/Thimphu"} {:offset "+09:00" :zone "Asia/Tokyo"} {:offset "+07:00" :zone "Asia/Tomsk"} {:offset "+08:00" :zone "Asia/Ujung_Pandang"} {:offset "+08:00" :zone "Asia/Ulaanbaatar"} {:offset "+08:00" :zone "Asia/Ulan_Bator"} {:offset "+06:00" :zone "Asia/Urumqi"} {:offset "+10:00" :zone "Asia/Ust-Nera"} {:offset "+07:00" :zone "Asia/Vientiane"} {:offset "+10:00" :zone "Asia/Vladivostok"} {:offset "+09:00" :zone "Asia/Yakutsk"} {:offset "+06:30" :zone "Asia/Yangon"} {:offset "+05:00" :zone "Asia/Yekaterinburg"} {:offset "+04:00" :zone "Asia/Yerevan"} {:offset "-01:00" :zone "Atlantic/Azores"} {:offset "-04:00" :zone "Atlantic/Bermuda"} {:offset "Z" :zone "Atlantic/Canary"} {:offset "-01:00" :zone "Atlantic/Cape_Verde"} {:offset "Z" :zone "Atlantic/Faeroe"} {:offset "Z" :zone "Atlantic/Faroe"} {:offset "+01:00" :zone "Atlantic/Jan_Mayen"} {:offset "Z" :zone "Atlantic/Madeira"} {:offset "Z" :zone "Atlantic/Reykjavik"} {:offset "-02:00" :zone "Atlantic/South_Georgia"} {:offset "Z" :zone "Atlantic/St_Helena"} {:offset "-03:00" :zone "Atlantic/Stanley"} {:offset "+11:00" :zone "Australia/ACT"} {:offset "+10:30" :zone "Australia/Adelaide"} {:offset "+10:00" :zone "Australia/Brisbane"} {:offset "+10:30" :zone "Australia/Broken_Hill"} {:offset "+11:00" :zone "Australia/Canberra"} {:offset "+11:00" :zone "Australia/Currie"} {:offset "+09:30" :zone "Australia/Darwin"} {:offset "+08:45" :zone "Australia/Eucla"} {:offset "+11:00" :zone "Australia/Hobart"} {:offset "+11:00" :zone "Australia/LHI"} {:offset "+10:00" :zone "Australia/Lindeman"} {:offset "+11:00" :zone "Australia/Lord_Howe"} {:offset "+11:00" :zone "Australia/Melbourne"} {:offset "+11:00" :zone "Australia/NSW"} {:offset "+09:30" :zone "Australia/North"} {:offset "+08:00" :zone "Australia/Perth"} {:offset "+10:00" :zone "Australia/Queensland"} {:offset "+10:30" :zone "Australia/South"} {:offset "+11:00" :zone "Australia/Sydney"} {:offset "+11:00" :zone "Australia/Tasmania"} {:offset "+11:00" :zone "Australia/Victoria"} {:offset "+08:00" :zone "Australia/West"} {:offset "+10:30" :zone "Australia/Yancowinna"} {:offset "-05:00" :zone "Brazil/Acre"} {:offset "-02:00" :zone "Brazil/DeNoronha"} {:offset "-02:00" :zone "Brazil/East"} {:offset "-04:00" :zone "Brazil/West"} {:offset "+01:00" :zone "CET"} {:offset "-06:00" :zone "CST6CDT"} {:offset "-04:00" :zone "Canada/Atlantic"} {:offset "-06:00" :zone "Canada/Central"} {:offset "-06:00" :zone "Canada/East-Saskatchewan"} {:offset "-05:00" :zone "Canada/Eastern"} {:offset "-07:00" :zone "Canada/Mountain"} {:offset "-03:30" :zone "Canada/Newfoundland"} {:offset "-08:00" :zone "Canada/Pacific"} {:offset "-06:00" :zone "Canada/Saskatchewan"} {:offset "-08:00" :zone "Canada/Yukon"} {:offset "-03:00" :zone "Chile/Continental"} {:offset "-05:00" :zone "Chile/EasterIsland"} {:offset "-05:00" :zone "Cuba"} {:offset "+02:00" :zone "EET"} {:offset "-05:00" :zone "EST5EDT"} {:offset "+02:00" :zone "Egypt"} {:offset "Z" :zone "Eire"} {:offset "Z" :zone "Etc/GMT"} {:offset "Z" :zone "Etc/GMT+0"} {:offset "-01:00" :zone "Etc/GMT+1"} {:offset "-10:00" :zone "Etc/GMT+10"} {:offset "-11:00" :zone "Etc/GMT+11"} {:offset "-12:00" :zone "Etc/GMT+12"} {:offset "-02:00" :zone "Etc/GMT+2"} {:offset "-03:00" :zone "Etc/GMT+3"} {:offset "-04:00" :zone "Etc/GMT+4"} {:offset "-05:00" :zone "Etc/GMT+5"} {:offset "-06:00" :zone "Etc/GMT+6"} {:offset "-07:00" :zone "Etc/GMT+7"} {:offset "-08:00" :zone "Etc/GMT+8"} {:offset "-09:00" :zone "Etc/GMT+9"} {:offset "Z" :zone "Etc/GMT-0"} {:offset "+01:00" :zone "Etc/GMT-1"} {:offset "+10:00" :zone "Etc/GMT-10"} {:offset "+11:00" :zone "Etc/GMT-11"} {:offset "+12:00" :zone "Etc/GMT-12"} {:offset "+13:00" :zone "Etc/GMT-13"} {:offset "+14:00" :zone "Etc/GMT-14"} {:offset "+02:00" :zone "Etc/GMT-2"} {:offset "+03:00" :zone "Etc/GMT-3"} {:offset "+04:00" :zone "Etc/GMT-4"} {:offset "+05:00" :zone "Etc/GMT-5"} {:offset "+06:00" :zone "Etc/GMT-6"} {:offset "+07:00" :zone "Etc/GMT-7"} {:offset "+08:00" :zone "Etc/GMT-8"} {:offset "+09:00" :zone "Etc/GMT-9"} {:offset "Z" :zone "Etc/GMT0"} {:offset "Z" :zone "Etc/Greenwich"} {:offset "Z" :zone "Etc/UCT"} {:offset "Z" :zone "Etc/UTC"} {:offset "Z" :zone "Etc/Universal"} {:offset "Z" :zone "Etc/Zulu"} {:offset "+01:00" :zone "Europe/Amsterdam"} {:offset "+01:00" :zone "Europe/Andorra"} {:offset "+04:00" :zone "Europe/Astrakhan"} {:offset "+02:00" :zone "Europe/Athens"} {:offset "Z" :zone "Europe/Belfast"} {:offset "+01:00" :zone "Europe/Belgrade"} {:offset "+01:00" :zone "Europe/Berlin"} {:offset "+01:00" :zone "Europe/Bratislava"} {:offset "+01:00" :zone "Europe/Brussels"} {:offset "+02:00" :zone "Europe/Bucharest"} {:offset "+01:00" :zone "Europe/Budapest"} {:offset "+01:00" :zone "Europe/Busingen"} {:offset "+02:00" :zone "Europe/Chisinau"} {:offset "+01:00" :zone "Europe/Copenhagen"} {:offset "Z" :zone "Europe/Dublin"} {:offset "+01:00" :zone "Europe/Gibraltar"} {:offset "Z" :zone "Europe/Guernsey"} {:offset "+02:00" :zone "Europe/Helsinki"} {:offset "Z" :zone "Europe/Isle_of_Man"} {:offset "+03:00" :zone "Europe/Istanbul"} {:offset "Z" :zone "Europe/Jersey"} {:offset "+02:00" :zone "Europe/Kaliningrad"} {:offset "+02:00" :zone "Europe/Kiev"} {:offset "+03:00" :zone "Europe/Kirov"} {:offset "Z" :zone "Europe/Lisbon"} {:offset "+01:00" :zone "Europe/Ljubljana"} {:offset "Z" :zone "Europe/London"} {:offset "+01:00" :zone "Europe/Luxembourg"} {:offset "+01:00" :zone "Europe/Madrid"} {:offset "+01:00" :zone "Europe/Malta"} {:offset "+02:00" :zone "Europe/Mariehamn"} {:offset "+03:00" :zone "Europe/Minsk"} {:offset "+01:00" :zone "Europe/Monaco"} {:offset "+03:00" :zone "Europe/Moscow"} {:offset "+02:00" :zone "Europe/Nicosia"} {:offset "+01:00" :zone "Europe/Oslo"} {:offset "+01:00" :zone "Europe/Paris"} {:offset "+01:00" :zone "Europe/Podgorica"} {:offset "+01:00" :zone "Europe/Prague"} {:offset "+02:00" :zone "Europe/Riga"} {:offset "+01:00" :zone "Europe/Rome"} {:offset "+04:00" :zone "Europe/Samara"} {:offset "+01:00" :zone "Europe/San_Marino"} {:offset "+01:00" :zone "Europe/Sarajevo"} {:offset "+04:00" :zone "Europe/Saratov"} {:offset "+03:00" :zone "Europe/Simferopol"} {:offset "+01:00" :zone "Europe/Skopje"} {:offset "+02:00" :zone "Europe/Sofia"} {:offset "+01:00" :zone "Europe/Stockholm"} {:offset "+02:00" :zone "Europe/Tallinn"} {:offset "+01:00" :zone "Europe/Tirane"} {:offset "+02:00" :zone "Europe/Tiraspol"} {:offset "+04:00" :zone "Europe/Ulyanovsk"} {:offset "+02:00" :zone "Europe/Uzhgorod"} {:offset "+01:00" :zone "Europe/Vaduz"} {:offset "+01:00" :zone "Europe/Vatican"} {:offset "+01:00" :zone "Europe/Vienna"} {:offset "+02:00" :zone "Europe/Vilnius"} {:offset "+03:00" :zone "Europe/Volgograd"} {:offset "+01:00" :zone "Europe/Warsaw"} {:offset "+01:00" :zone "Europe/Zagreb"} {:offset "+02:00" :zone "Europe/Zaporozhye"} {:offset "+01:00" :zone "Europe/Zurich"} {:offset "Z" :zone "GB"} {:offset "Z" :zone "GB-Eire"} {:offset "Z" :zone "GMT"} {:offset "Z" :zone "GMT0"} {:offset "Z" :zone "Greenwich"} {:offset "+08:00" :zone "Hongkong"} {:offset "Z" :zone "Iceland"} {:offset "+03:00" :zone "Indian/Antananarivo"} {:offset "+06:00" :zone "Indian/Chagos"} {:offset "+07:00" :zone "Indian/Christmas"} {:offset "+06:30" :zone "Indian/Cocos"} {:offset "+03:00" :zone "Indian/Comoro"} {:offset "+05:00" :zone "Indian/Kerguelen"} {:offset "+04:00" :zone "Indian/Mahe"} {:offset "+05:00" :zone "Indian/Maldives"} {:offset "+04:00" :zone "Indian/Mauritius"} {:offset "+03:00" :zone "Indian/Mayotte"} {:offset "+04:00" :zone "Indian/Reunion"} {:offset "+03:30" :zone "Iran"} {:offset "+02:00" :zone "Israel"} {:offset "-05:00" :zone "Jamaica"} {:offset "+09:00" :zone "Japan"} {:offset "+12:00" :zone "Kwajalein"} {:offset "+02:00" :zone "Libya"} {:offset "+01:00" :zone "MET"} {:offset "-07:00" :zone "MST7MDT"} {:offset "-08:00" :zone "Mexico/BajaNorte"} {:offset "-07:00" :zone "Mexico/BajaSur"} {:offset "-06:00" :zone "Mexico/General"} {:offset "+13:00" :zone "NZ"} {:offset "+13:45" :zone "NZ-CHAT"} {:offset "-07:00" :zone "Navajo"} {:offset "+08:00" :zone "PRC"} {:offset "-08:00" :zone "PST8PDT"} {:offset "+14:00" :zone "Pacific/Apia"} {:offset "+13:00" :zone "Pacific/Auckland"} {:offset "+11:00" :zone "Pacific/Bougainville"} {:offset "+13:45" :zone "Pacific/Chatham"} {:offset "+10:00" :zone "Pacific/Chuuk"} {:offset "-05:00" :zone "Pacific/Easter"} {:offset "+11:00" :zone "Pacific/Efate"} {:offset "+13:00" :zone "Pacific/Enderbury"} {:offset "+13:00" :zone "Pacific/Fakaofo"} {:offset "+12:00" :zone "Pacific/Fiji"} {:offset "+12:00" :zone "Pacific/Funafuti"} {:offset "-06:00" :zone "Pacific/Galapagos"} {:offset "-09:00" :zone "Pacific/Gambier"} {:offset "+11:00" :zone "Pacific/Guadalcanal"} {:offset "+10:00" :zone "Pacific/Guam"} {:offset "-10:00" :zone "Pacific/Honolulu"} {:offset "-10:00" :zone "Pacific/Johnston"} {:offset "+14:00" :zone "Pacific/Kiritimati"} {:offset "+11:00" :zone "Pacific/Kosrae"} {:offset "+12:00" :zone "Pacific/Kwajalein"} {:offset "+12:00" :zone "Pacific/Majuro"} {:offset "-09:30" :zone "Pacific/Marquesas"} {:offset "-11:00" :zone "Pacific/Midway"} {:offset "+12:00" :zone "Pacific/Nauru"} {:offset "-11:00" :zone "Pacific/Niue"} {:offset "+11:00" :zone "Pacific/Norfolk"} {:offset "+11:00" :zone "Pacific/Noumea"} {:offset "-11:00" :zone "Pacific/Pago_Pago"} {:offset "+09:00" :zone "Pacific/Palau"} {:offset "-08:00" :zone "Pacific/Pitcairn"} {:offset "+11:00" :zone "Pacific/Pohnpei"} {:offset "+11:00" :zone "Pacific/Ponape"} {:offset "+10:00" :zone "Pacific/Port_Moresby"} {:offset "-10:00" :zone "Pacific/Rarotonga"} {:offset "+10:00" :zone "Pacific/Saipan"} {:offset "-11:00" :zone "Pacific/Samoa"} {:offset "-10:00" :zone "Pacific/Tahiti"} {:offset "+12:00" :zone "Pacific/Tarawa"} {:offset "+13:00" :zone "Pacific/Tongatapu"} {:offset "+10:00" :zone "Pacific/Truk"} {:offset "+12:00" :zone "Pacific/Wake"} {:offset "+12:00" :zone "Pacific/Wallis"} {:offset "+10:00" :zone "Pacific/Yap"} {:offset "+01:00" :zone "Poland"} {:offset "Z" :zone "Portugal"} {:offset "+09:00" :zone "ROK"} {:offset "+08:00" :zone "Singapore"} {:offset "-04:00" :zone "SystemV/AST4"} {:offset "-04:00" :zone "SystemV/AST4ADT"} {:offset "-06:00" :zone "SystemV/CST6"} {:offset "-06:00" :zone "SystemV/CST6CDT"} {:offset "-05:00" :zone "SystemV/EST5"} {:offset "-05:00" :zone "SystemV/EST5EDT"} {:offset "-10:00" :zone "SystemV/HST10"} {:offset "-07:00" :zone "SystemV/MST7"} {:offset "-07:00" :zone "SystemV/MST7MDT"} {:offset "-08:00" :zone "SystemV/PST8"} {:offset "-08:00" :zone "SystemV/PST8PDT"} {:offset "-09:00" :zone "SystemV/YST9"} {:offset "-09:00" :zone "SystemV/YST9YDT"} {:offset "+03:00" :zone "Turkey"} {:offset "Z" :zone "UCT"} {:offset "-09:00" :zone "US/Alaska"} {:offset "-10:00" :zone "US/Aleutian"} {:offset "-07:00" :zone "US/Arizona"} {:offset "-06:00" :zone "US/Central"} {:offset "-05:00" :zone "US/East-Indiana"} {:offset "-05:00" :zone "US/Eastern"} {:offset "-10:00" :zone "US/Hawaii"} {:offset "-06:00" :zone "US/Indiana-Starke"} {:offset "-05:00" :zone "US/Michigan"} {:offset "-07:00" :zone "US/Mountain"} {:offset "-08:00" :zone "US/Pacific"} {:offset "-08:00" :zone "US/Pacific-New"} {:offset "-11:00" :zone "US/Samoa"} {:offset "Z" :zone "UTC"} {:offset "Z" :zone "Universal"} {:offset "+03:00" :zone "W-SU"} {:offset "Z" :zone "WET"} {:offset "Z" :zone "Zulu"}])
true
(ns datasim-ui.timezone) (def timezones [{:offset "Z" :zone "Africa/Abidjan"} {:offset "Z" :zone "Africa/Accra"} {:offset "+03:00" :zone "Africa/Addis_Ababa"} {:offset "+01:00" :zone "Africa/Algiers"} {:offset "+03:00" :zone "Africa/Asmara"} {:offset "+03:00" :zone "Africa/Asmera"} {:offset "Z" :zone "Africa/Bamako"} {:offset "+01:00" :zone "Africa/Bangui"} {:offset "Z" :zone "Africa/Banjul"} {:offset "Z" :zone "Africa/Bissau"} {:offset "+02:00" :zone "Africa/Blantyre"} {:offset "+01:00" :zone "Africa/Brazzaville"} {:offset "+02:00" :zone "Africa/Bujumbura"} {:offset "+02:00" :zone "Africa/Cairo"} {:offset "Z" :zone "Africa/Casablanca"} {:offset "+01:00" :zone "Africa/Ceuta"} {:offset "Z" :zone "Africa/Conakry"} {:offset "Z" :zone "Africa/Dakar"} {:offset "+03:00" :zone "Africa/Dar_es_Salaam"} {:offset "+03:00" :zone "Africa/Djibouti"} {:offset "+01:00" :zone "Africa/Douala"} {:offset "Z" :zone "Africa/El_Aaiun"} {:offset "Z" :zone "Africa/Freetown"} {:offset "+02:00" :zone "Africa/Gaborone"} {:offset "+02:00" :zone "Africa/Harare"} {:offset "+02:00" :zone "Africa/Johannesburg"} {:offset "+03:00" :zone "Africa/Juba"} {:offset "+03:00" :zone "Africa/Kampala"} {:offset "+03:00" :zone "Africa/Khartoum"} {:offset "+02:00" :zone "Africa/Kigali"} {:offset "+01:00" :zone "Africa/Kinshasa"} {:offset "+01:00" :zone "Africa/Lagos"} {:offset "+01:00" :zone "Africa/Libreville"} {:offset "Z" :zone "Africa/Lome"} {:offset "+01:00" :zone "Africa/Luanda"} {:offset "+02:00" :zone "Africa/Lubumbashi"} {:offset "+02:00" :zone "Africa/Lusaka"} {:offset "+01:00" :zone "Africa/Malabo"} {:offset "+02:00" :zone "Africa/Maputo"} {:offset "+02:00" :zone "Africa/Maseru"} {:offset "+02:00" :zone "Africa/Mbabane"} {:offset "+03:00" :zone "Africa/Mogadishu"} {:offset "Z" :zone "Africa/Monrovia"} {:offset "+03:00" :zone "Africa/Nairobi"} {:offset "+01:00" :zone "Africa/Ndjamena"} {:offset "+01:00" :zone "Africa/Niamey"} {:offset "Z" :zone "Africa/Nouakchott"} {:offset "Z" :zone "Africa/Ouagadougou"} {:offset "+01:00" :zone "Africa/Porto-Novo"} {:offset "Z" :zone "Africa/Sao_Tome"} {:offset "Z" :zone "Africa/Timbuktu"} {:offset "+02:00" :zone "Africa/Tripoli"} {:offset "+01:00" :zone "Africa/Tunis"} {:offset "+02:00" :zone "Africa/Windhoek"} {:offset "-10:00" :zone "America/Adak"} {:offset "-09:00" :zone "America/Anchorage"} {:offset "-04:00" :zone "America/Anguilla"} {:offset "-04:00" :zone "America/Antigua"} {:offset "-03:00" :zone "America/Araguaina"} {:offset "-03:00" :zone "America/Argentina/Buenos_Aires"} {:offset "-03:00" :zone "America/Argentina/Catamarca"} {:offset "-03:00" :zone "America/Argentina/ComodRivadavia"} {:offset "-03:00" :zone "America/Argentina/Cordoba"} {:offset "-03:00" :zone "America/Argentina/Jujuy"} {:offset "-03:00" :zone "America/Argentina/La_Rioja"} {:offset "-03:00" :zone "America/Argentina/Mendoza"} {:offset "-03:00" :zone "America/Argentina/Rio_Gallegos"} {:offset "-03:00" :zone "America/Argentina/Salta"} {:offset "-03:00" :zone "America/Argentina/San_Juan"} {:offset "-03:00" :zone "America/Argentina/San_Luis"} {:offset "-03:00" :zone "America/Argentina/Tucuman"} {:offset "-03:00" :zone "America/Argentina/Ushuaia"} {:offset "-04:00" :zone "America/Aruba"} {:offset "-03:00" :zone "America/Asuncion"} {:offset "-05:00" :zone "America/Atikokan"} {:offset "-10:00" :zone "America/Atka"} {:offset "-03:00" :zone "America/Bahia"} {:offset "-06:00" :zone "America/Bahia_Banderas"} {:offset "-04:00" :zone "America/Barbados"} {:offset "-03:00" :zone "America/Belem"} {:offset "-06:00" :zone "America/Belize"} {:offset "-04:00" :zone "America/Blanc-Sablon"} {:offset "-04:00" :zone "America/Boa_Vista"} {:offset "-05:00" :zone "America/Bogota"} {:offset "-07:00" :zone "America/Boise"} {:offset "-03:00" :zone "America/Buenos_Aires"} {:offset "-07:00" :zone "America/Cambridge_Bay"} {:offset "-03:00" :zone "America/Campo_Grande"} {:offset "-05:00" :zone "America/Cancun"} {:offset "-04:00" :zone "America/Caracas"} {:offset "-03:00" :zone "America/Catamarca"} {:offset "-03:00" :zone "America/Cayenne"} {:offset "-05:00" :zone "America/Cayman"} {:offset "-06:00" :zone "America/Chicago"} {:offset "-07:00" :zone "America/Chihuahua"} {:offset "-05:00" :zone "America/Coral_Harbour"} {:offset "-03:00" :zone "America/Cordoba"} {:offset "-06:00" :zone "America/Costa_Rica"} {:offset "-07:00" :zone "America/Creston"} {:offset "-03:00" :zone "America/Cuiaba"} {:offset "-04:00" :zone "America/Curacao"} {:offset "Z" :zone "America/Danmarkshavn"} {:offset "-08:00" :zone "America/Dawson"} {:offset "-07:00" :zone "America/Dawson_Creek"} {:offset "-07:00" :zone "America/Denver"} {:offset "-05:00" :zone "America/Detroit"} {:offset "-04:00" :zone "America/Dominica"} {:offset "-07:00" :zone "America/Edmonton"} {:offset "-05:00" :zone "America/Eirunepe"} {:offset "-06:00" :zone "America/El_Salvador"} {:offset "-08:00" :zone "America/Ensenada"} {:offset "-07:00" :zone "America/Fort_Nelson"} {:offset "-05:00" :zone "America/Fort_Wayne"} {:offset "-03:00" :zone "America/Fortaleza"} {:offset "-04:00" :zone "America/Glace_Bay"} {:offset "-03:00" :zone "America/Godthab"} {:offset "-04:00" :zone "America/Goose_Bay"} {:offset "-04:00" :zone "America/Grand_Turk"} {:offset "-04:00" :zone "America/Grenada"} {:offset "-04:00" :zone "America/Guadeloupe"} {:offset "-06:00" :zone "America/Guatemala"} {:offset "-05:00" :zone "America/Guayaquil"} {:offset "-04:00" :zone "America/Guyana"} {:offset "-04:00" :zone "America/Halifax"} {:offset "-05:00" :zone "America/Havana"} {:offset "-07:00" :zone "America/Hermosillo"} {:offset "-05:00" :zone "America/Indiana/Indianapolis"} {:offset "-06:00" :zone "America/Indiana/Knox"} {:offset "-05:00" :zone "America/Indiana/Marengo"} {:offset "-05:00" :zone "America/Indiana/Petersburg"} {:offset "-06:00" :zone "America/Indiana/Tell_City"} {:offset "-05:00" :zone "America/Indiana/Vevay"} {:offset "-05:00" :zone "America/Indiana/Vincennes"} {:offset "-05:00" :zone "America/Indiana/Winamac"} {:offset "-05:00" :zone "America/Indianapolis"} {:offset "-07:00" :zone "America/Inuvik"} {:offset "-05:00" :zone "America/Iqaluit"} {:offset "-05:00" :zone "America/Jamaica"} {:offset "-03:00" :zone "America/Jujuy"} {:offset "-09:00" :zone "America/Juneau"} {:offset "-05:00" :zone "America/Kentucky/Louisville"} {:offset "-05:00" :zone "America/Kentucky/Monticello"} {:offset "-06:00" :zone "America/Knox_IN"} {:offset "-04:00" :zone "America/Kralendijk"} {:offset "-04:00" :zone "America/La_Paz"} {:offset "-05:00" :zone "America/Lima"} {:offset "-08:00" :zone "America/Los_Angeles"} {:offset "-05:00" :zone "America/Louisville"} {:offset "-04:00" :zone "America/Lower_Princes"} {:offset "-03:00" :zone "America/Maceio"} {:offset "-06:00" :zone "America/Managua"} {:offset "-04:00" :zone "America/Manaus"} {:offset "-04:00" :zone "America/Marigot"} {:offset "-04:00" :zone "America/Martinique"} {:offset "-06:00" :zone "America/Matamoros"} {:offset "-07:00" :zone "America/Mazatlan"} {:offset "-03:00" :zone "America/Mendoza"} {:offset "-06:00" :zone "America/Menominee"} {:offset "-06:00" :zone "America/Merida"} {:offset "-09:00" :zone "America/Metlakatla"} {:offset "-06:00" :zone "America/Mexico_City"} {:offset "-03:00" :zone "America/Miquelon"} {:offset "-04:00" :zone "America/Moncton"} {:offset "-06:00" :zone "America/Monterrey"} {:offset "-03:00" :zone "America/Montevideo"} {:offset "-05:00" :zone "America/Montreal"} {:offset "-04:00" :zone "America/Montserrat"} {:offset "-05:00" :zone "America/Nassau"} {:offset "-05:00" :zone "America/New_York"} {:offset "-05:00" :zone "America/Nipigon"} {:offset "-09:00" :zone "America/Nome"} {:offset "-02:00" :zone "America/Noronha"} {:offset "-06:00" :zone "America/North_Dakota/Beulah"} {:offset "-06:00" :zone "America/North_Dakota/Center"} {:offset "-06:00" :zone "America/North_Dakota/New_Salem"} {:offset "-07:00" :zone "America/Ojinaga"} {:offset "-05:00" :zone "America/Panama"} {:offset "-05:00" :zone "America/Pangnirtung"} {:offset "-03:00" :zone "America/Paramaribo"} {:offset "-07:00" :zone "America/Phoenix"} {:offset "-05:00" :zone "America/Port-au-Prince"} {:offset "-04:00" :zone "America/Port_of_Spain"} {:offset "-05:00" :zone "America/Porto_Acre"} {:offset "-04:00" :zone "America/Porto_Velho"} {:offset "-04:00" :zone "America/Puerto_Rico"} {:offset "-03:00" :zone "America/Punta_Arenas"} {:offset "-06:00" :zone "America/Rainy_River"} {:offset "-06:00" :zone "America/Rankin_Inlet"} {:offset "-03:00" :zone "America/Recife"} {:offset "-06:00" :zone "America/Regina"} {:offset "-06:00" :zone "America/Resolute"} {:offset "-05:00" :zone "America/Rio_Branco"} {:offset "-03:00" :zone "America/Rosario"} {:offset "-08:00" :zone "America/Santa_Isabel"} {:offset "-03:00" :zone "America/Santarem"} {:offset "-03:00" :zone "America/Santiago"} {:offset "-04:00" :zone "America/Santo_Domingo"} {:offset "-02:00" :zone "America/Sao_Paulo"} {:offset "-01:00" :zone "America/Scoresbysund"} {:offset "-07:00" :zone "America/Shiprock"} {:offset "-09:00" :zone "America/Sitka"} {:offset "-04:00" :zone "America/St_Barthelemy"} {:offset "-03:30" :zone "America/St_Johns"} {:offset "-04:00" :zone "America/St_PI:NAME:<NAME>END_PI"} {:offset "-04:00" :zone "America/St_Lucia"} {:offset "-04:00" :zone "America/St_Thomas"} {:offset "-04:00" :zone "America/St_Vincent"} {:offset "-06:00" :zone "America/Swift_Current"} {:offset "-06:00" :zone "America/Tegucigalpa"} {:offset "-04:00" :zone "America/Thule"} {:offset "-05:00" :zone "America/Thunder_Bay"} {:offset "-08:00" :zone "America/Tijuana"} {:offset "-05:00" :zone "America/Toronto"} {:offset "-04:00" :zone "America/Tortola"} {:offset "-08:00" :zone "America/Vancouver"} {:offset "-04:00" :zone "America/Virgin"} {:offset "-08:00" :zone "America/Whitehorse"} {:offset "-06:00" :zone "America/Winnipeg"} {:offset "-09:00" :zone "America/Yakutat"} {:offset "-07:00" :zone "America/Yellowknife"} {:offset "+11:00" :zone "Antarctica/Casey"} {:offset "+07:00" :zone "Antarctica/Davis"} {:offset "+10:00" :zone "Antarctica/DumontDUrville"} {:offset "+11:00" :zone "Antarctica/Macquarie"} {:offset "+05:00" :zone "Antarctica/Mawson"} {:offset "+13:00" :zone "Antarctica/McMurdo"} {:offset "-03:00" :zone "Antarctica/Palmer"} {:offset "-03:00" :zone "Antarctica/Rothera"} {:offset "+13:00" :zone "Antarctica/South_PI:NAME:<NAME>END_PI"} {:offset "+03:00" :zone "Antarctica/Syowa"} {:offset "Z" :zone "Antarctica/Troll"} {:offset "+06:00" :zone "Antarctica/Vostok"} {:offset "+01:00" :zone "Arctic/Longyearbyen"} {:offset "+03:00" :zone "Asia/Aden"} {:offset "+06:00" :zone "Asia/Almaty"} {:offset "+02:00" :zone "Asia/Amman"} {:offset "+12:00" :zone "Asia/Anadyr"} {:offset "+05:00" :zone "Asia/Aqtau"} {:offset "+05:00" :zone "Asia/Aqtobe"} {:offset "+05:00" :zone "Asia/Ashgabat"} {:offset "+05:00" :zone "Asia/Ashkhabad"} {:offset "+05:00" :zone "Asia/Atyrau"} {:offset "+03:00" :zone "Asia/Baghdad"} {:offset "+03:00" :zone "Asia/Bahrain"} {:offset "+04:00" :zone "Asia/Baku"} {:offset "+07:00" :zone "Asia/Bangkok"} {:offset "+07:00" :zone "Asia/Barnaul"} {:offset "+02:00" :zone "Asia/Beirut"} {:offset "+06:00" :zone "Asia/Bishkek"} {:offset "+08:00" :zone "Asia/Brunei"} {:offset "+05:30" :zone "Asia/Calcutta"} {:offset "+09:00" :zone "Asia/Chita"} {:offset "+08:00" :zone "Asia/Choibalsan"} {:offset "+08:00" :zone "Asia/Chongqing"} {:offset "+08:00" :zone "Asia/Chungking"} {:offset "+05:30" :zone "Asia/Colombo"} {:offset "+06:00" :zone "Asia/Dacca"} {:offset "+02:00" :zone "Asia/Damascus"} {:offset "+06:00" :zone "Asia/Dhaka"} {:offset "+09:00" :zone "Asia/Dili"} {:offset "+04:00" :zone "Asia/Dubai"} {:offset "+05:00" :zone "Asia/Dushanbe"} {:offset "+03:00" :zone "Asia/Famagusta"} {:offset "+02:00" :zone "Asia/Gaza"} {:offset "+08:00" :zone "Asia/Harbin"} {:offset "+02:00" :zone "Asia/Hebron"} {:offset "+07:00" :zone "Asia/Ho_Chi_Minh"} {:offset "+08:00" :zone "Asia/Hong_Kong"} {:offset "+07:00" :zone "Asia/Hovd"} {:offset "+08:00" :zone "Asia/Irkutsk"} {:offset "+03:00" :zone "Asia/Istanbul"} {:offset "+07:00" :zone "Asia/Jakarta"} {:offset "+09:00" :zone "Asia/Jayapura"} {:offset "+02:00" :zone "Asia/Jerusalem"} {:offset "+04:30" :zone "Asia/Kabul"} {:offset "+12:00" :zone "Asia/Kamchatka"} {:offset "+05:00" :zone "Asia/Karachi"} {:offset "+06:00" :zone "Asia/Kashgar"} {:offset "+05:45" :zone "Asia/Kathmandu"} {:offset "+05:45" :zone "Asia/Katmandu"} {:offset "+09:00" :zone "Asia/Khandyga"} {:offset "+05:30" :zone "Asia/Kolkata"} {:offset "+07:00" :zone "Asia/Krasnoyarsk"} {:offset "+08:00" :zone "Asia/Kuala_Lumpur"} {:offset "+08:00" :zone "Asia/Kuching"} {:offset "+03:00" :zone "Asia/Kuwait"} {:offset "+08:00" :zone "Asia/Macao"} {:offset "+08:00" :zone "Asia/Macau"} {:offset "+11:00" :zone "Asia/Magadan"} {:offset "+08:00" :zone "Asia/Makassar"} {:offset "+08:00" :zone "Asia/Manila"} {:offset "+04:00" :zone "Asia/Muscat"} {:offset "+02:00" :zone "Asia/Nicosia"} {:offset "+07:00" :zone "Asia/Novokuznetsk"} {:offset "+07:00" :zone "Asia/Novosibirsk"} {:offset "+06:00" :zone "Asia/Omsk"} {:offset "+05:00" :zone "Asia/Oral"} {:offset "+07:00" :zone "Asia/Phnom_Penh"} {:offset "+07:00" :zone "Asia/Pontianak"} {:offset "+08:30" :zone "Asia/Pyongyang"} {:offset "+03:00" :zone "Asia/Qatar"} {:offset "+06:00" :zone "Asia/Qyzylorda"} {:offset "+06:30" :zone "Asia/Rangoon"} {:offset "+03:00" :zone "Asia/Riyadh"} {:offset "+07:00" :zone "Asia/Saigon"} {:offset "+11:00" :zone "Asia/Sakhalin"} {:offset "+05:00" :zone "Asia/Samarkand"} {:offset "+09:00" :zone "Asia/Seoul"} {:offset "+08:00" :zone "Asia/Shanghai"} {:offset "+08:00" :zone "Asia/Singapore"} {:offset "+11:00" :zone "Asia/Srednekolymsk"} {:offset "+08:00" :zone "Asia/Taipei"} {:offset "+05:00" :zone "Asia/Tashkent"} {:offset "+04:00" :zone "Asia/Tbilisi"} {:offset "+03:30" :zone "Asia/Tehran"} {:offset "+02:00" :zone "Asia/Tel_Aviv"} {:offset "+06:00" :zone "Asia/Thimbu"} {:offset "+06:00" :zone "Asia/Thimphu"} {:offset "+09:00" :zone "Asia/Tokyo"} {:offset "+07:00" :zone "Asia/Tomsk"} {:offset "+08:00" :zone "Asia/Ujung_Pandang"} {:offset "+08:00" :zone "Asia/Ulaanbaatar"} {:offset "+08:00" :zone "Asia/Ulan_Bator"} {:offset "+06:00" :zone "Asia/Urumqi"} {:offset "+10:00" :zone "Asia/Ust-Nera"} {:offset "+07:00" :zone "Asia/Vientiane"} {:offset "+10:00" :zone "Asia/Vladivostok"} {:offset "+09:00" :zone "Asia/Yakutsk"} {:offset "+06:30" :zone "Asia/Yangon"} {:offset "+05:00" :zone "Asia/Yekaterinburg"} {:offset "+04:00" :zone "Asia/Yerevan"} {:offset "-01:00" :zone "Atlantic/Azores"} {:offset "-04:00" :zone "Atlantic/Bermuda"} {:offset "Z" :zone "Atlantic/Canary"} {:offset "-01:00" :zone "Atlantic/Cape_Verde"} {:offset "Z" :zone "Atlantic/Faeroe"} {:offset "Z" :zone "Atlantic/Faroe"} {:offset "+01:00" :zone "Atlantic/Jan_Mayen"} {:offset "Z" :zone "Atlantic/Madeira"} {:offset "Z" :zone "Atlantic/Reykjavik"} {:offset "-02:00" :zone "Atlantic/South_Georgia"} {:offset "Z" :zone "Atlantic/St_Helena"} {:offset "-03:00" :zone "Atlantic/Stanley"} {:offset "+11:00" :zone "Australia/ACT"} {:offset "+10:30" :zone "Australia/Adelaide"} {:offset "+10:00" :zone "Australia/Brisbane"} {:offset "+10:30" :zone "Australia/Broken_Hill"} {:offset "+11:00" :zone "Australia/Canberra"} {:offset "+11:00" :zone "Australia/Currie"} {:offset "+09:30" :zone "Australia/Darwin"} {:offset "+08:45" :zone "Australia/Eucla"} {:offset "+11:00" :zone "Australia/Hobart"} {:offset "+11:00" :zone "Australia/LHI"} {:offset "+10:00" :zone "Australia/Lindeman"} {:offset "+11:00" :zone "Australia/Lord_Howe"} {:offset "+11:00" :zone "Australia/Melbourne"} {:offset "+11:00" :zone "Australia/NSW"} {:offset "+09:30" :zone "Australia/North"} {:offset "+08:00" :zone "Australia/Perth"} {:offset "+10:00" :zone "Australia/Queensland"} {:offset "+10:30" :zone "Australia/South"} {:offset "+11:00" :zone "Australia/Sydney"} {:offset "+11:00" :zone "Australia/Tasmania"} {:offset "+11:00" :zone "Australia/Victoria"} {:offset "+08:00" :zone "Australia/West"} {:offset "+10:30" :zone "Australia/Yancowinna"} {:offset "-05:00" :zone "Brazil/Acre"} {:offset "-02:00" :zone "Brazil/DeNoronha"} {:offset "-02:00" :zone "Brazil/East"} {:offset "-04:00" :zone "Brazil/West"} {:offset "+01:00" :zone "CET"} {:offset "-06:00" :zone "CST6CDT"} {:offset "-04:00" :zone "Canada/Atlantic"} {:offset "-06:00" :zone "Canada/Central"} {:offset "-06:00" :zone "Canada/East-Saskatchewan"} {:offset "-05:00" :zone "Canada/Eastern"} {:offset "-07:00" :zone "Canada/Mountain"} {:offset "-03:30" :zone "Canada/Newfoundland"} {:offset "-08:00" :zone "Canada/Pacific"} {:offset "-06:00" :zone "Canada/Saskatchewan"} {:offset "-08:00" :zone "Canada/Yukon"} {:offset "-03:00" :zone "Chile/Continental"} {:offset "-05:00" :zone "Chile/EasterIsland"} {:offset "-05:00" :zone "Cuba"} {:offset "+02:00" :zone "EET"} {:offset "-05:00" :zone "EST5EDT"} {:offset "+02:00" :zone "Egypt"} {:offset "Z" :zone "Eire"} {:offset "Z" :zone "Etc/GMT"} {:offset "Z" :zone "Etc/GMT+0"} {:offset "-01:00" :zone "Etc/GMT+1"} {:offset "-10:00" :zone "Etc/GMT+10"} {:offset "-11:00" :zone "Etc/GMT+11"} {:offset "-12:00" :zone "Etc/GMT+12"} {:offset "-02:00" :zone "Etc/GMT+2"} {:offset "-03:00" :zone "Etc/GMT+3"} {:offset "-04:00" :zone "Etc/GMT+4"} {:offset "-05:00" :zone "Etc/GMT+5"} {:offset "-06:00" :zone "Etc/GMT+6"} {:offset "-07:00" :zone "Etc/GMT+7"} {:offset "-08:00" :zone "Etc/GMT+8"} {:offset "-09:00" :zone "Etc/GMT+9"} {:offset "Z" :zone "Etc/GMT-0"} {:offset "+01:00" :zone "Etc/GMT-1"} {:offset "+10:00" :zone "Etc/GMT-10"} {:offset "+11:00" :zone "Etc/GMT-11"} {:offset "+12:00" :zone "Etc/GMT-12"} {:offset "+13:00" :zone "Etc/GMT-13"} {:offset "+14:00" :zone "Etc/GMT-14"} {:offset "+02:00" :zone "Etc/GMT-2"} {:offset "+03:00" :zone "Etc/GMT-3"} {:offset "+04:00" :zone "Etc/GMT-4"} {:offset "+05:00" :zone "Etc/GMT-5"} {:offset "+06:00" :zone "Etc/GMT-6"} {:offset "+07:00" :zone "Etc/GMT-7"} {:offset "+08:00" :zone "Etc/GMT-8"} {:offset "+09:00" :zone "Etc/GMT-9"} {:offset "Z" :zone "Etc/GMT0"} {:offset "Z" :zone "Etc/Greenwich"} {:offset "Z" :zone "Etc/UCT"} {:offset "Z" :zone "Etc/UTC"} {:offset "Z" :zone "Etc/Universal"} {:offset "Z" :zone "Etc/Zulu"} {:offset "+01:00" :zone "Europe/Amsterdam"} {:offset "+01:00" :zone "Europe/Andorra"} {:offset "+04:00" :zone "Europe/Astrakhan"} {:offset "+02:00" :zone "Europe/Athens"} {:offset "Z" :zone "Europe/Belfast"} {:offset "+01:00" :zone "Europe/Belgrade"} {:offset "+01:00" :zone "Europe/Berlin"} {:offset "+01:00" :zone "Europe/Bratislava"} {:offset "+01:00" :zone "Europe/Brussels"} {:offset "+02:00" :zone "Europe/Bucharest"} {:offset "+01:00" :zone "Europe/Budapest"} {:offset "+01:00" :zone "Europe/Busingen"} {:offset "+02:00" :zone "Europe/Chisinau"} {:offset "+01:00" :zone "Europe/Copenhagen"} {:offset "Z" :zone "Europe/Dublin"} {:offset "+01:00" :zone "Europe/Gibraltar"} {:offset "Z" :zone "Europe/Guernsey"} {:offset "+02:00" :zone "Europe/Helsinki"} {:offset "Z" :zone "Europe/Isle_of_Man"} {:offset "+03:00" :zone "Europe/Istanbul"} {:offset "Z" :zone "Europe/Jersey"} {:offset "+02:00" :zone "Europe/Kaliningrad"} {:offset "+02:00" :zone "Europe/Kiev"} {:offset "+03:00" :zone "Europe/Kirov"} {:offset "Z" :zone "Europe/Lisbon"} {:offset "+01:00" :zone "Europe/Ljubljana"} {:offset "Z" :zone "Europe/London"} {:offset "+01:00" :zone "Europe/Luxembourg"} {:offset "+01:00" :zone "Europe/Madrid"} {:offset "+01:00" :zone "Europe/Malta"} {:offset "+02:00" :zone "Europe/Mariehamn"} {:offset "+03:00" :zone "Europe/Minsk"} {:offset "+01:00" :zone "Europe/Monaco"} {:offset "+03:00" :zone "Europe/Moscow"} {:offset "+02:00" :zone "Europe/Nicosia"} {:offset "+01:00" :zone "Europe/Oslo"} {:offset "+01:00" :zone "Europe/Paris"} {:offset "+01:00" :zone "Europe/Podgorica"} {:offset "+01:00" :zone "Europe/Prague"} {:offset "+02:00" :zone "Europe/Riga"} {:offset "+01:00" :zone "Europe/Rome"} {:offset "+04:00" :zone "Europe/Samara"} {:offset "+01:00" :zone "Europe/San_Marino"} {:offset "+01:00" :zone "Europe/Sarajevo"} {:offset "+04:00" :zone "Europe/Saratov"} {:offset "+03:00" :zone "Europe/Simferopol"} {:offset "+01:00" :zone "Europe/Skopje"} {:offset "+02:00" :zone "Europe/Sofia"} {:offset "+01:00" :zone "Europe/Stockholm"} {:offset "+02:00" :zone "Europe/Tallinn"} {:offset "+01:00" :zone "Europe/Tirane"} {:offset "+02:00" :zone "Europe/Tiraspol"} {:offset "+04:00" :zone "Europe/Ulyanovsk"} {:offset "+02:00" :zone "Europe/Uzhgorod"} {:offset "+01:00" :zone "Europe/Vaduz"} {:offset "+01:00" :zone "Europe/Vatican"} {:offset "+01:00" :zone "Europe/Vienna"} {:offset "+02:00" :zone "Europe/Vilnius"} {:offset "+03:00" :zone "Europe/Volgograd"} {:offset "+01:00" :zone "Europe/Warsaw"} {:offset "+01:00" :zone "Europe/Zagreb"} {:offset "+02:00" :zone "Europe/Zaporozhye"} {:offset "+01:00" :zone "Europe/Zurich"} {:offset "Z" :zone "GB"} {:offset "Z" :zone "GB-Eire"} {:offset "Z" :zone "GMT"} {:offset "Z" :zone "GMT0"} {:offset "Z" :zone "Greenwich"} {:offset "+08:00" :zone "Hongkong"} {:offset "Z" :zone "Iceland"} {:offset "+03:00" :zone "Indian/Antananarivo"} {:offset "+06:00" :zone "Indian/Chagos"} {:offset "+07:00" :zone "Indian/Christmas"} {:offset "+06:30" :zone "Indian/Cocos"} {:offset "+03:00" :zone "Indian/Comoro"} {:offset "+05:00" :zone "Indian/Kerguelen"} {:offset "+04:00" :zone "Indian/Mahe"} {:offset "+05:00" :zone "Indian/Maldives"} {:offset "+04:00" :zone "Indian/Mauritius"} {:offset "+03:00" :zone "Indian/Mayotte"} {:offset "+04:00" :zone "Indian/Reunion"} {:offset "+03:30" :zone "Iran"} {:offset "+02:00" :zone "Israel"} {:offset "-05:00" :zone "Jamaica"} {:offset "+09:00" :zone "Japan"} {:offset "+12:00" :zone "Kwajalein"} {:offset "+02:00" :zone "Libya"} {:offset "+01:00" :zone "MET"} {:offset "-07:00" :zone "MST7MDT"} {:offset "-08:00" :zone "Mexico/BajaNorte"} {:offset "-07:00" :zone "Mexico/BajaSur"} {:offset "-06:00" :zone "Mexico/General"} {:offset "+13:00" :zone "NZ"} {:offset "+13:45" :zone "NZ-CHAT"} {:offset "-07:00" :zone "Navajo"} {:offset "+08:00" :zone "PRC"} {:offset "-08:00" :zone "PST8PDT"} {:offset "+14:00" :zone "Pacific/Apia"} {:offset "+13:00" :zone "Pacific/Auckland"} {:offset "+11:00" :zone "Pacific/Bougainville"} {:offset "+13:45" :zone "Pacific/Chatham"} {:offset "+10:00" :zone "Pacific/Chuuk"} {:offset "-05:00" :zone "Pacific/Easter"} {:offset "+11:00" :zone "Pacific/Efate"} {:offset "+13:00" :zone "Pacific/Enderbury"} {:offset "+13:00" :zone "Pacific/Fakaofo"} {:offset "+12:00" :zone "Pacific/Fiji"} {:offset "+12:00" :zone "Pacific/Funafuti"} {:offset "-06:00" :zone "Pacific/Galapagos"} {:offset "-09:00" :zone "Pacific/Gambier"} {:offset "+11:00" :zone "Pacific/Guadalcanal"} {:offset "+10:00" :zone "Pacific/Guam"} {:offset "-10:00" :zone "Pacific/Honolulu"} {:offset "-10:00" :zone "Pacific/Johnston"} {:offset "+14:00" :zone "Pacific/Kiritimati"} {:offset "+11:00" :zone "Pacific/Kosrae"} {:offset "+12:00" :zone "Pacific/Kwajalein"} {:offset "+12:00" :zone "Pacific/Majuro"} {:offset "-09:30" :zone "Pacific/Marquesas"} {:offset "-11:00" :zone "Pacific/Midway"} {:offset "+12:00" :zone "Pacific/Nauru"} {:offset "-11:00" :zone "Pacific/Niue"} {:offset "+11:00" :zone "Pacific/Norfolk"} {:offset "+11:00" :zone "Pacific/Noumea"} {:offset "-11:00" :zone "Pacific/Pago_Pago"} {:offset "+09:00" :zone "Pacific/Palau"} {:offset "-08:00" :zone "Pacific/Pitcairn"} {:offset "+11:00" :zone "Pacific/Pohnpei"} {:offset "+11:00" :zone "Pacific/Ponape"} {:offset "+10:00" :zone "Pacific/Port_Moresby"} {:offset "-10:00" :zone "Pacific/Rarotonga"} {:offset "+10:00" :zone "Pacific/Saipan"} {:offset "-11:00" :zone "Pacific/Samoa"} {:offset "-10:00" :zone "Pacific/Tahiti"} {:offset "+12:00" :zone "Pacific/Tarawa"} {:offset "+13:00" :zone "Pacific/Tongatapu"} {:offset "+10:00" :zone "Pacific/Truk"} {:offset "+12:00" :zone "Pacific/Wake"} {:offset "+12:00" :zone "Pacific/Wallis"} {:offset "+10:00" :zone "Pacific/Yap"} {:offset "+01:00" :zone "Poland"} {:offset "Z" :zone "Portugal"} {:offset "+09:00" :zone "ROK"} {:offset "+08:00" :zone "Singapore"} {:offset "-04:00" :zone "SystemV/AST4"} {:offset "-04:00" :zone "SystemV/AST4ADT"} {:offset "-06:00" :zone "SystemV/CST6"} {:offset "-06:00" :zone "SystemV/CST6CDT"} {:offset "-05:00" :zone "SystemV/EST5"} {:offset "-05:00" :zone "SystemV/EST5EDT"} {:offset "-10:00" :zone "SystemV/HST10"} {:offset "-07:00" :zone "SystemV/MST7"} {:offset "-07:00" :zone "SystemV/MST7MDT"} {:offset "-08:00" :zone "SystemV/PST8"} {:offset "-08:00" :zone "SystemV/PST8PDT"} {:offset "-09:00" :zone "SystemV/YST9"} {:offset "-09:00" :zone "SystemV/YST9YDT"} {:offset "+03:00" :zone "Turkey"} {:offset "Z" :zone "UCT"} {:offset "-09:00" :zone "US/Alaska"} {:offset "-10:00" :zone "US/Aleutian"} {:offset "-07:00" :zone "US/Arizona"} {:offset "-06:00" :zone "US/Central"} {:offset "-05:00" :zone "US/East-Indiana"} {:offset "-05:00" :zone "US/Eastern"} {:offset "-10:00" :zone "US/Hawaii"} {:offset "-06:00" :zone "US/Indiana-Starke"} {:offset "-05:00" :zone "US/Michigan"} {:offset "-07:00" :zone "US/Mountain"} {:offset "-08:00" :zone "US/Pacific"} {:offset "-08:00" :zone "US/Pacific-New"} {:offset "-11:00" :zone "US/Samoa"} {:offset "Z" :zone "UTC"} {:offset "Z" :zone "Universal"} {:offset "+03:00" :zone "W-SU"} {:offset "Z" :zone "WET"} {:offset "Z" :zone "Zulu"}])
[ { "context": "-------------------------------\n;;\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;; Version: 0.1\n;; Source: ht", "end": 202, "score": 0.9998476505279541, "start": 186, "tag": "NAME", "value": "PLIQUE Guillaume" }, { "context": "------------\n;;\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;; Version: 0.1\n;; Source: https://gist.gith", "end": 217, "score": 0.9981171488761902, "start": 204, "tag": "USERNAME", "value": "Yomguithereal" }, { "context": "Version: 0.1\n;; Source: https://gist.github.com/vishnuvyas/958488\n;;\n(ns clj-fuzzy.levenshtein)\n\n(defn- next", "end": 284, "score": 0.9980828166007996, "start": 274, "tag": "USERNAME", "value": "vishnuvyas" } ]
src/clj_fuzzy/levenshtein.cljc
sooheon/clj-fuzzy
222
;; ------------------------------------------------------------------- ;; clj-fuzzy Levenshtein ;; ------------------------------------------------------------------- ;; ;; ;; Author: PLIQUE Guillaume (Yomguithereal) ;; Version: 0.1 ;; Source: https://gist.github.com/vishnuvyas/958488 ;; (ns clj-fuzzy.levenshtein) (defn- next-row [previous current other-seq] (reduce (fn [row [diagonal above other]] (let [update-val (if (= other current) diagonal (inc (min diagonal above (peek row))))] (conj row update-val))) [(inc (first previous))] (map vector previous (next previous) other-seq))) (defn distance "Compute the levenshtein distance between two [sequences]." [sequence1 sequence2] (cond (and (empty? sequence1) (empty? sequence2)) 0 (empty? sequence1) (count sequence2) (empty? sequence2) (count sequence1) :else (peek (reduce (fn [previous current] (next-row previous current sequence2)) (map #(identity %2) (cons nil sequence2) (range)) sequence1))))
61604
;; ------------------------------------------------------------------- ;; clj-fuzzy Levenshtein ;; ------------------------------------------------------------------- ;; ;; ;; Author: <NAME> (Yomguithereal) ;; Version: 0.1 ;; Source: https://gist.github.com/vishnuvyas/958488 ;; (ns clj-fuzzy.levenshtein) (defn- next-row [previous current other-seq] (reduce (fn [row [diagonal above other]] (let [update-val (if (= other current) diagonal (inc (min diagonal above (peek row))))] (conj row update-val))) [(inc (first previous))] (map vector previous (next previous) other-seq))) (defn distance "Compute the levenshtein distance between two [sequences]." [sequence1 sequence2] (cond (and (empty? sequence1) (empty? sequence2)) 0 (empty? sequence1) (count sequence2) (empty? sequence2) (count sequence1) :else (peek (reduce (fn [previous current] (next-row previous current sequence2)) (map #(identity %2) (cons nil sequence2) (range)) sequence1))))
true
;; ------------------------------------------------------------------- ;; clj-fuzzy Levenshtein ;; ------------------------------------------------------------------- ;; ;; ;; Author: PI:NAME:<NAME>END_PI (Yomguithereal) ;; Version: 0.1 ;; Source: https://gist.github.com/vishnuvyas/958488 ;; (ns clj-fuzzy.levenshtein) (defn- next-row [previous current other-seq] (reduce (fn [row [diagonal above other]] (let [update-val (if (= other current) diagonal (inc (min diagonal above (peek row))))] (conj row update-val))) [(inc (first previous))] (map vector previous (next previous) other-seq))) (defn distance "Compute the levenshtein distance between two [sequences]." [sequence1 sequence2] (cond (and (empty? sequence1) (empty? sequence2)) 0 (empty? sequence1) (count sequence2) (empty? sequence2) (count sequence1) :else (peek (reduce (fn [previous current] (next-row previous current sequence2)) (map #(identity %2) (cons nil sequence2) (range)) sequence1))))
[ { "context": ";; Copyright 2021 Zane Littrell\n;;\n;; Licensed under the Apache License, Version ", "end": 31, "score": 0.9998682141304016, "start": 18, "tag": "NAME", "value": "Zane Littrell" } ]
src/app/cells.cljc
CapitalistLepton/nomenclature
0
;; Copyright 2021 Zane Littrell ;; ;; 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 app.cells (:require [app.lib :as lib])) (defn make-entity "Make an entity from a name, owner and form" [name owner form] {:name name :owner owner :form form}) (defn move-index "Calculate the next index from the current index, the move, and the width/height of the grid" [index [dx dy] size] (let [x (mod index size) y (quot index size) nx (+ x dx) ny (+ y dy)] (mod (+ (* ny size) nx) (* size size)))) (defn move-cells "Moves the cells in the game. Returns a list of entities and their indexes" [prev-game size] (map-indexed (fn [i entity] (if (not (nil? entity)) (let [move (lib/movement (:name entity)) ni (move-index i move size)] [ni entity]) [i entity])) prev-game)) (defn filter-collisions "Group cells by their index. Collided cells will be in a list" [indexed-cells size] (reduce (fn [cell-map [i cell]] (if (not (nil? cell)) (assoc cell-map i (cons cell (get cell-map i))) cell-map)) (vec (repeat (* size size) '())) indexed-cells)) (defn handle-collisions "Handle cells that have collided. Return list of all cells, nil where there are no names." [cells] (map (fn [cell-list] (if (= cell-list '()) nil (first cell-list))) ; TODO replace with actual collision logic cells))
109040
;; Copyright 2021 <NAME> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns app.cells (:require [app.lib :as lib])) (defn make-entity "Make an entity from a name, owner and form" [name owner form] {:name name :owner owner :form form}) (defn move-index "Calculate the next index from the current index, the move, and the width/height of the grid" [index [dx dy] size] (let [x (mod index size) y (quot index size) nx (+ x dx) ny (+ y dy)] (mod (+ (* ny size) nx) (* size size)))) (defn move-cells "Moves the cells in the game. Returns a list of entities and their indexes" [prev-game size] (map-indexed (fn [i entity] (if (not (nil? entity)) (let [move (lib/movement (:name entity)) ni (move-index i move size)] [ni entity]) [i entity])) prev-game)) (defn filter-collisions "Group cells by their index. Collided cells will be in a list" [indexed-cells size] (reduce (fn [cell-map [i cell]] (if (not (nil? cell)) (assoc cell-map i (cons cell (get cell-map i))) cell-map)) (vec (repeat (* size size) '())) indexed-cells)) (defn handle-collisions "Handle cells that have collided. Return list of all cells, nil where there are no names." [cells] (map (fn [cell-list] (if (= cell-list '()) nil (first cell-list))) ; TODO replace with actual collision logic cells))
true
;; Copyright 2021 PI:NAME:<NAME>END_PI ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns app.cells (:require [app.lib :as lib])) (defn make-entity "Make an entity from a name, owner and form" [name owner form] {:name name :owner owner :form form}) (defn move-index "Calculate the next index from the current index, the move, and the width/height of the grid" [index [dx dy] size] (let [x (mod index size) y (quot index size) nx (+ x dx) ny (+ y dy)] (mod (+ (* ny size) nx) (* size size)))) (defn move-cells "Moves the cells in the game. Returns a list of entities and their indexes" [prev-game size] (map-indexed (fn [i entity] (if (not (nil? entity)) (let [move (lib/movement (:name entity)) ni (move-index i move size)] [ni entity]) [i entity])) prev-game)) (defn filter-collisions "Group cells by their index. Collided cells will be in a list" [indexed-cells size] (reduce (fn [cell-map [i cell]] (if (not (nil? cell)) (assoc cell-map i (cons cell (get cell-map i))) cell-map)) (vec (repeat (* size size) '())) indexed-cells)) (defn handle-collisions "Handle cells that have collided. Return list of all cells, nil where there are no names." [cells] (map (fn [cell-list] (if (= cell-list '()) nil (first cell-list))) ; TODO replace with actual collision logic cells))
[ { "context": "E FOR LANGUAGES WITH OVERLOADING AND SUBTYPING\" by Geoffrey Smith\n ;; https://users.cs.fiu.edu/~smithg/papers/thes", "end": 6095, "score": 0.9998338222503662, "start": 6081, "tag": "NAME", "value": "Geoffrey Smith" }, { "context": " by Geoffrey Smith\n ;; https://users.cs.fiu.edu/~smithg/papers/thesis91.pdf\n (match (lcg [:=> [:cat char", "end": 6133, "score": 0.9834109544754028, "start": 6127, "tag": "USERNAME", "value": "smithg" } ]
test/erp12/schema_inference/schema_test.cljc
erp12/schema-inference
12
(ns erp12.schema-inference.schema-test (:require [clojure.test :refer [deftest is testing]] [erp12.schema-inference.schema :refer :all] [clojure.core.match :refer [match]])) (deftest free-type-vars-test (is (= #{'t1} (free-type-vars '[:s-var t1]))) (is (= #{} (free-type-vars int?))) (is (= #{'t1 't2} (free-type-vars '[:=> [:cat [:s-var t1]] [:s-var t2]]))) (is (= #{'t1 't2} (free-type-vars '[:=> [:cat [:s-var t1] [:s-var t2]] [:s-var t1]]))) (testing "scheme" (is (= #{'t2} (free-type-vars {:s-vars ['t1] :body [:=> [:cat [:s-var 't1]] [:s-var 't2]]})))) (testing "environments" (is (= #{'t1 't3} (free-type-vars '[[:= x [:s-var t1]] [:= y {:s-vars [t2] :body [:s-var t3]}]]))))) (deftest substitute-type-test (is (= '[:s-var t2] (substitute-types '{t1 [:s-var t2]} '[:s-var t1]))) (is (= '[:s-var s] (substitute-types '{t1 [:s-var t2]} '[:s-var s]))) (is (= int? (substitute-types '{t1 [:s-var t2]} int?))) (testing "function types" (is (= '[:=> [:cat [:s-var t2]] [:s-var t2]] (substitute-types '{t1 [:s-var t2]} '[:=> [:cat [:s-var t1]] [:s-var t1]])))) (testing "schemes" (match (substitute-types '{t1 [:s-var t2]} '{:s-vars [a] :body [:s-var t1]}) {:s-vars [S] :with [] :body [:s-var T1]} (do (is (gen-s-var? S)) (is (= T1 't2)))) (match (substitute-types '{t1 [:s-var t2]} {:s-vars ['t1] :body [:s-var 't1]}) {:s-vars [S] :body [:s-var S1]} (do (is (gen-s-var? S)) (is (= S S1))))) (testing "environments" (let [actual (substitute-types '{t1 [:s-var t2] s1 [:s-var s2]} [[:= 'x int?] [:= 'y [:s-var 't1]] [:= 'z {:s-vars ['a] :body [:s-var 's1]}]])] (is (= (typings-of actual 'x) [int?])) (is (= (typings-of actual 'y) [[:s-var 't2]])) (is (= 1 (count (typings-of actual 'z)))) (let [{:keys [s-vars with body]} (first (typings-of actual 'z))] (is (= 1 (count s-vars))) (is (gen-s-var? (first s-vars))) (is (= with [])) (is (= body [:s-var 's2])))))) (deftest compose-substitutions-test (is (= {'t1 string? 't2 string?} (compose-substitutions {'t1 string? 't2 int?} {'t2 [:s-var 't1]})))) (deftest generalize-test (let [env [[:= 'x int?] [:= 'y [:s-var 't1]]]] (is (= int? (generalize env int?))) (is (= [:s-var 't1] (generalize env [:s-var 't1]))) (is (= {:s-vars ['t2] :body [:s-var 't2]} (generalize env '[:s-var t2]))))) (deftest instantiate-test (is (= int? (instantiate int?))) (is (= [:s-var 't] (instantiate [:s-var 't]))) (match (instantiate {:s-vars ['t] :body [:s-var 't]}) [:s-var s-var] (is (gen-s-var? s-var))) (is (= int? (instantiate {:s-vars ['t] :body int?})))) (deftest bind-type-var-test (is (= {'t int?} (bind-type-var 't int?))) (is (= {'f [:=> [:cat int?] int?]} (bind-type-var 'f [:=> [:cat int?] int?]))) (is (= {} (bind-type-var 't [:s-var 't]))) (is (thrown? clojure.lang.ExceptionInfo (bind-type-var 't [:=> [:cat [:s-var 't]] [:s-var 't]])))) (deftest mgu-test (is (= {'t int?} (mgu [:s-var 't] int?))) (is (= {'t int?} (mgu int? [:s-var 't]))) (is (= {} (mgu [:=> [:cat int?] string?] [:=> [:cat int?] string?]))) (is (= {'t int?} (mgu [:=> [:cat [:s-var 't]] string?] [:=> [:cat int?] string?]))) (is (thrown? clojure.lang.ExceptionInfo (mgu [:=> [:cat [:s-var 't]] [:s-var 't]] [:=> [:cat int?] string?]))) (is (= '{t [:s-var s]} (mgu [:=> [:cat [:s-var 't]] [:s-var 't]] [:=> [:cat [:s-var 's]] [:s-var 's]]))) (is (= {'t string?} (mgu [:=> [:cat int?] string?] [:=> [:cat int?] [:s-var 't]]))) (is (= {'a [:vector char?]} (mgu [:vector [:vector char?]] [:vector [:s-var 'a]]))) (testing "multiple occurrences of s-var" (is (= {'a int? 'b string? 'c [:vector string?]} (mgu [:=> [:cat [:=> [:cat [:s-var 'a]] [:s-var 'b]] [:vector [:s-var 'a]]] [:vector [:s-var 'b]]] [:=> [:cat [:=> [:cat int?] string?] [:vector int?]] [:s-var 'c]]))) (is (thrown? clojure.lang.ExceptionInfo (mgu [:=> [:cat [:=> [:cat [:s-var 'a]] [:s-var 'b]] [:vector [:s-var 'a]]] [:vector [:s-var 'a]]] [:=> [:cat [:=> [:cat float?] string?] [:vector int?]] [:s-var 'c]]))))) (deftest lcg-test (is (= int? (lcg int? int?))) (match (lcg int? [:vector string?]) {:s-vars [S] :body [:s-var S1]} (do (is (gen-s-var? S)) (is (= S S1)))) (match (lcg [:map-of int? [:vector string?]] [:map-of int? [:vector boolean?]]) {:s-vars [S] :body [:map-of int? [:vector [:s-var S1]]]} (do (is (gen-s-var? S)) (is (= S S1)))) (match (lcg [:map-of string? [:vector string?]] [:map-of int? [:vector boolean?]]) {:s-vars [S T] :body [:map-of [:s-var V1] [:vector [:s-var V2]]]} (do (is (gen-s-var? S)) (is (gen-s-var? T)) (is (not= S T)) (is (contains? #{S T} V1)) (is (contains? #{S T} V2)))) (match (lcg [:map-of string? [:vector string?]] [:map-of boolean? [:vector boolean?]]) {:s-vars [S] :body [:map-of [:s-var S1] [:vector [:s-var S2]]]} (do (is (gen-s-var? S)) (is (= S S1 S2)))) ;; From "POLYMORPHIC TYPE INFERENCE FOR LANGUAGES WITH OVERLOADING AND SUBTYPING" by Geoffrey Smith ;; https://users.cs.fiu.edu/~smithg/papers/thesis91.pdf (match (lcg [:=> [:cat char? char?] boolean?] [:=> [:cat :number :number] boolean?] {:s-vars ['a] :with [[:= '<= [:=> [:cat [:s-var 'a] [:s-var 'a]] boolean?]]] :body [:=> [:cat [:vector [:s-var 'a]] [:vector [:s-var 'a]]] boolean?]}) {:s-vars [S] :body [:=> [:cat [:s-var S1] [:s-var S2]] boolean?]} (do (is (gen-s-var? S)) (is (= S S1 S2))))) (deftest overlapping?-test (is (not (overlapping? int? float?))) (is (overlapping? int? int?)) (is (overlapping? int? {:s-vars ['a] :body [:s-var 'a]})) (is (not (overlapping? int? {:s-vars ['a] :body [:vector [:s-var 'a]]}))) (is (not (overlapping? [[:= 'x int?] [:= 'y {:s-vars ['a] :body [:vector [:s-var 'a]]}] [:= 'z string?]]))) (is (overlapping? [[:= 'x int?] [:= 'y {:s-vars ['a] :body [:s-var 'a]}] [:= 'z string?]]))) (deftest satisfiable?-test (is (satisfiable? [[:= 'c char?] [:= 'c {:s-vars ['a] :with [[:= 'c [:s-var 'a]]] :body [:vector [:s-var 'a]]}]] [[:= 'c [:vector [:vector char?]]]])) (is (not (satisfiable? [[:= 'c char?] [:= 'c {:s-vars ['a] :with [[:= 'c [:s-var 'a]]] :body [:vector [:s-var 'a]]}]] [[:= 'c [:vector [:vector int?]]]]))))
94865
(ns erp12.schema-inference.schema-test (:require [clojure.test :refer [deftest is testing]] [erp12.schema-inference.schema :refer :all] [clojure.core.match :refer [match]])) (deftest free-type-vars-test (is (= #{'t1} (free-type-vars '[:s-var t1]))) (is (= #{} (free-type-vars int?))) (is (= #{'t1 't2} (free-type-vars '[:=> [:cat [:s-var t1]] [:s-var t2]]))) (is (= #{'t1 't2} (free-type-vars '[:=> [:cat [:s-var t1] [:s-var t2]] [:s-var t1]]))) (testing "scheme" (is (= #{'t2} (free-type-vars {:s-vars ['t1] :body [:=> [:cat [:s-var 't1]] [:s-var 't2]]})))) (testing "environments" (is (= #{'t1 't3} (free-type-vars '[[:= x [:s-var t1]] [:= y {:s-vars [t2] :body [:s-var t3]}]]))))) (deftest substitute-type-test (is (= '[:s-var t2] (substitute-types '{t1 [:s-var t2]} '[:s-var t1]))) (is (= '[:s-var s] (substitute-types '{t1 [:s-var t2]} '[:s-var s]))) (is (= int? (substitute-types '{t1 [:s-var t2]} int?))) (testing "function types" (is (= '[:=> [:cat [:s-var t2]] [:s-var t2]] (substitute-types '{t1 [:s-var t2]} '[:=> [:cat [:s-var t1]] [:s-var t1]])))) (testing "schemes" (match (substitute-types '{t1 [:s-var t2]} '{:s-vars [a] :body [:s-var t1]}) {:s-vars [S] :with [] :body [:s-var T1]} (do (is (gen-s-var? S)) (is (= T1 't2)))) (match (substitute-types '{t1 [:s-var t2]} {:s-vars ['t1] :body [:s-var 't1]}) {:s-vars [S] :body [:s-var S1]} (do (is (gen-s-var? S)) (is (= S S1))))) (testing "environments" (let [actual (substitute-types '{t1 [:s-var t2] s1 [:s-var s2]} [[:= 'x int?] [:= 'y [:s-var 't1]] [:= 'z {:s-vars ['a] :body [:s-var 's1]}]])] (is (= (typings-of actual 'x) [int?])) (is (= (typings-of actual 'y) [[:s-var 't2]])) (is (= 1 (count (typings-of actual 'z)))) (let [{:keys [s-vars with body]} (first (typings-of actual 'z))] (is (= 1 (count s-vars))) (is (gen-s-var? (first s-vars))) (is (= with [])) (is (= body [:s-var 's2])))))) (deftest compose-substitutions-test (is (= {'t1 string? 't2 string?} (compose-substitutions {'t1 string? 't2 int?} {'t2 [:s-var 't1]})))) (deftest generalize-test (let [env [[:= 'x int?] [:= 'y [:s-var 't1]]]] (is (= int? (generalize env int?))) (is (= [:s-var 't1] (generalize env [:s-var 't1]))) (is (= {:s-vars ['t2] :body [:s-var 't2]} (generalize env '[:s-var t2]))))) (deftest instantiate-test (is (= int? (instantiate int?))) (is (= [:s-var 't] (instantiate [:s-var 't]))) (match (instantiate {:s-vars ['t] :body [:s-var 't]}) [:s-var s-var] (is (gen-s-var? s-var))) (is (= int? (instantiate {:s-vars ['t] :body int?})))) (deftest bind-type-var-test (is (= {'t int?} (bind-type-var 't int?))) (is (= {'f [:=> [:cat int?] int?]} (bind-type-var 'f [:=> [:cat int?] int?]))) (is (= {} (bind-type-var 't [:s-var 't]))) (is (thrown? clojure.lang.ExceptionInfo (bind-type-var 't [:=> [:cat [:s-var 't]] [:s-var 't]])))) (deftest mgu-test (is (= {'t int?} (mgu [:s-var 't] int?))) (is (= {'t int?} (mgu int? [:s-var 't]))) (is (= {} (mgu [:=> [:cat int?] string?] [:=> [:cat int?] string?]))) (is (= {'t int?} (mgu [:=> [:cat [:s-var 't]] string?] [:=> [:cat int?] string?]))) (is (thrown? clojure.lang.ExceptionInfo (mgu [:=> [:cat [:s-var 't]] [:s-var 't]] [:=> [:cat int?] string?]))) (is (= '{t [:s-var s]} (mgu [:=> [:cat [:s-var 't]] [:s-var 't]] [:=> [:cat [:s-var 's]] [:s-var 's]]))) (is (= {'t string?} (mgu [:=> [:cat int?] string?] [:=> [:cat int?] [:s-var 't]]))) (is (= {'a [:vector char?]} (mgu [:vector [:vector char?]] [:vector [:s-var 'a]]))) (testing "multiple occurrences of s-var" (is (= {'a int? 'b string? 'c [:vector string?]} (mgu [:=> [:cat [:=> [:cat [:s-var 'a]] [:s-var 'b]] [:vector [:s-var 'a]]] [:vector [:s-var 'b]]] [:=> [:cat [:=> [:cat int?] string?] [:vector int?]] [:s-var 'c]]))) (is (thrown? clojure.lang.ExceptionInfo (mgu [:=> [:cat [:=> [:cat [:s-var 'a]] [:s-var 'b]] [:vector [:s-var 'a]]] [:vector [:s-var 'a]]] [:=> [:cat [:=> [:cat float?] string?] [:vector int?]] [:s-var 'c]]))))) (deftest lcg-test (is (= int? (lcg int? int?))) (match (lcg int? [:vector string?]) {:s-vars [S] :body [:s-var S1]} (do (is (gen-s-var? S)) (is (= S S1)))) (match (lcg [:map-of int? [:vector string?]] [:map-of int? [:vector boolean?]]) {:s-vars [S] :body [:map-of int? [:vector [:s-var S1]]]} (do (is (gen-s-var? S)) (is (= S S1)))) (match (lcg [:map-of string? [:vector string?]] [:map-of int? [:vector boolean?]]) {:s-vars [S T] :body [:map-of [:s-var V1] [:vector [:s-var V2]]]} (do (is (gen-s-var? S)) (is (gen-s-var? T)) (is (not= S T)) (is (contains? #{S T} V1)) (is (contains? #{S T} V2)))) (match (lcg [:map-of string? [:vector string?]] [:map-of boolean? [:vector boolean?]]) {:s-vars [S] :body [:map-of [:s-var S1] [:vector [:s-var S2]]]} (do (is (gen-s-var? S)) (is (= S S1 S2)))) ;; From "POLYMORPHIC TYPE INFERENCE FOR LANGUAGES WITH OVERLOADING AND SUBTYPING" by <NAME> ;; https://users.cs.fiu.edu/~smithg/papers/thesis91.pdf (match (lcg [:=> [:cat char? char?] boolean?] [:=> [:cat :number :number] boolean?] {:s-vars ['a] :with [[:= '<= [:=> [:cat [:s-var 'a] [:s-var 'a]] boolean?]]] :body [:=> [:cat [:vector [:s-var 'a]] [:vector [:s-var 'a]]] boolean?]}) {:s-vars [S] :body [:=> [:cat [:s-var S1] [:s-var S2]] boolean?]} (do (is (gen-s-var? S)) (is (= S S1 S2))))) (deftest overlapping?-test (is (not (overlapping? int? float?))) (is (overlapping? int? int?)) (is (overlapping? int? {:s-vars ['a] :body [:s-var 'a]})) (is (not (overlapping? int? {:s-vars ['a] :body [:vector [:s-var 'a]]}))) (is (not (overlapping? [[:= 'x int?] [:= 'y {:s-vars ['a] :body [:vector [:s-var 'a]]}] [:= 'z string?]]))) (is (overlapping? [[:= 'x int?] [:= 'y {:s-vars ['a] :body [:s-var 'a]}] [:= 'z string?]]))) (deftest satisfiable?-test (is (satisfiable? [[:= 'c char?] [:= 'c {:s-vars ['a] :with [[:= 'c [:s-var 'a]]] :body [:vector [:s-var 'a]]}]] [[:= 'c [:vector [:vector char?]]]])) (is (not (satisfiable? [[:= 'c char?] [:= 'c {:s-vars ['a] :with [[:= 'c [:s-var 'a]]] :body [:vector [:s-var 'a]]}]] [[:= 'c [:vector [:vector int?]]]]))))
true
(ns erp12.schema-inference.schema-test (:require [clojure.test :refer [deftest is testing]] [erp12.schema-inference.schema :refer :all] [clojure.core.match :refer [match]])) (deftest free-type-vars-test (is (= #{'t1} (free-type-vars '[:s-var t1]))) (is (= #{} (free-type-vars int?))) (is (= #{'t1 't2} (free-type-vars '[:=> [:cat [:s-var t1]] [:s-var t2]]))) (is (= #{'t1 't2} (free-type-vars '[:=> [:cat [:s-var t1] [:s-var t2]] [:s-var t1]]))) (testing "scheme" (is (= #{'t2} (free-type-vars {:s-vars ['t1] :body [:=> [:cat [:s-var 't1]] [:s-var 't2]]})))) (testing "environments" (is (= #{'t1 't3} (free-type-vars '[[:= x [:s-var t1]] [:= y {:s-vars [t2] :body [:s-var t3]}]]))))) (deftest substitute-type-test (is (= '[:s-var t2] (substitute-types '{t1 [:s-var t2]} '[:s-var t1]))) (is (= '[:s-var s] (substitute-types '{t1 [:s-var t2]} '[:s-var s]))) (is (= int? (substitute-types '{t1 [:s-var t2]} int?))) (testing "function types" (is (= '[:=> [:cat [:s-var t2]] [:s-var t2]] (substitute-types '{t1 [:s-var t2]} '[:=> [:cat [:s-var t1]] [:s-var t1]])))) (testing "schemes" (match (substitute-types '{t1 [:s-var t2]} '{:s-vars [a] :body [:s-var t1]}) {:s-vars [S] :with [] :body [:s-var T1]} (do (is (gen-s-var? S)) (is (= T1 't2)))) (match (substitute-types '{t1 [:s-var t2]} {:s-vars ['t1] :body [:s-var 't1]}) {:s-vars [S] :body [:s-var S1]} (do (is (gen-s-var? S)) (is (= S S1))))) (testing "environments" (let [actual (substitute-types '{t1 [:s-var t2] s1 [:s-var s2]} [[:= 'x int?] [:= 'y [:s-var 't1]] [:= 'z {:s-vars ['a] :body [:s-var 's1]}]])] (is (= (typings-of actual 'x) [int?])) (is (= (typings-of actual 'y) [[:s-var 't2]])) (is (= 1 (count (typings-of actual 'z)))) (let [{:keys [s-vars with body]} (first (typings-of actual 'z))] (is (= 1 (count s-vars))) (is (gen-s-var? (first s-vars))) (is (= with [])) (is (= body [:s-var 's2])))))) (deftest compose-substitutions-test (is (= {'t1 string? 't2 string?} (compose-substitutions {'t1 string? 't2 int?} {'t2 [:s-var 't1]})))) (deftest generalize-test (let [env [[:= 'x int?] [:= 'y [:s-var 't1]]]] (is (= int? (generalize env int?))) (is (= [:s-var 't1] (generalize env [:s-var 't1]))) (is (= {:s-vars ['t2] :body [:s-var 't2]} (generalize env '[:s-var t2]))))) (deftest instantiate-test (is (= int? (instantiate int?))) (is (= [:s-var 't] (instantiate [:s-var 't]))) (match (instantiate {:s-vars ['t] :body [:s-var 't]}) [:s-var s-var] (is (gen-s-var? s-var))) (is (= int? (instantiate {:s-vars ['t] :body int?})))) (deftest bind-type-var-test (is (= {'t int?} (bind-type-var 't int?))) (is (= {'f [:=> [:cat int?] int?]} (bind-type-var 'f [:=> [:cat int?] int?]))) (is (= {} (bind-type-var 't [:s-var 't]))) (is (thrown? clojure.lang.ExceptionInfo (bind-type-var 't [:=> [:cat [:s-var 't]] [:s-var 't]])))) (deftest mgu-test (is (= {'t int?} (mgu [:s-var 't] int?))) (is (= {'t int?} (mgu int? [:s-var 't]))) (is (= {} (mgu [:=> [:cat int?] string?] [:=> [:cat int?] string?]))) (is (= {'t int?} (mgu [:=> [:cat [:s-var 't]] string?] [:=> [:cat int?] string?]))) (is (thrown? clojure.lang.ExceptionInfo (mgu [:=> [:cat [:s-var 't]] [:s-var 't]] [:=> [:cat int?] string?]))) (is (= '{t [:s-var s]} (mgu [:=> [:cat [:s-var 't]] [:s-var 't]] [:=> [:cat [:s-var 's]] [:s-var 's]]))) (is (= {'t string?} (mgu [:=> [:cat int?] string?] [:=> [:cat int?] [:s-var 't]]))) (is (= {'a [:vector char?]} (mgu [:vector [:vector char?]] [:vector [:s-var 'a]]))) (testing "multiple occurrences of s-var" (is (= {'a int? 'b string? 'c [:vector string?]} (mgu [:=> [:cat [:=> [:cat [:s-var 'a]] [:s-var 'b]] [:vector [:s-var 'a]]] [:vector [:s-var 'b]]] [:=> [:cat [:=> [:cat int?] string?] [:vector int?]] [:s-var 'c]]))) (is (thrown? clojure.lang.ExceptionInfo (mgu [:=> [:cat [:=> [:cat [:s-var 'a]] [:s-var 'b]] [:vector [:s-var 'a]]] [:vector [:s-var 'a]]] [:=> [:cat [:=> [:cat float?] string?] [:vector int?]] [:s-var 'c]]))))) (deftest lcg-test (is (= int? (lcg int? int?))) (match (lcg int? [:vector string?]) {:s-vars [S] :body [:s-var S1]} (do (is (gen-s-var? S)) (is (= S S1)))) (match (lcg [:map-of int? [:vector string?]] [:map-of int? [:vector boolean?]]) {:s-vars [S] :body [:map-of int? [:vector [:s-var S1]]]} (do (is (gen-s-var? S)) (is (= S S1)))) (match (lcg [:map-of string? [:vector string?]] [:map-of int? [:vector boolean?]]) {:s-vars [S T] :body [:map-of [:s-var V1] [:vector [:s-var V2]]]} (do (is (gen-s-var? S)) (is (gen-s-var? T)) (is (not= S T)) (is (contains? #{S T} V1)) (is (contains? #{S T} V2)))) (match (lcg [:map-of string? [:vector string?]] [:map-of boolean? [:vector boolean?]]) {:s-vars [S] :body [:map-of [:s-var S1] [:vector [:s-var S2]]]} (do (is (gen-s-var? S)) (is (= S S1 S2)))) ;; From "POLYMORPHIC TYPE INFERENCE FOR LANGUAGES WITH OVERLOADING AND SUBTYPING" by PI:NAME:<NAME>END_PI ;; https://users.cs.fiu.edu/~smithg/papers/thesis91.pdf (match (lcg [:=> [:cat char? char?] boolean?] [:=> [:cat :number :number] boolean?] {:s-vars ['a] :with [[:= '<= [:=> [:cat [:s-var 'a] [:s-var 'a]] boolean?]]] :body [:=> [:cat [:vector [:s-var 'a]] [:vector [:s-var 'a]]] boolean?]}) {:s-vars [S] :body [:=> [:cat [:s-var S1] [:s-var S2]] boolean?]} (do (is (gen-s-var? S)) (is (= S S1 S2))))) (deftest overlapping?-test (is (not (overlapping? int? float?))) (is (overlapping? int? int?)) (is (overlapping? int? {:s-vars ['a] :body [:s-var 'a]})) (is (not (overlapping? int? {:s-vars ['a] :body [:vector [:s-var 'a]]}))) (is (not (overlapping? [[:= 'x int?] [:= 'y {:s-vars ['a] :body [:vector [:s-var 'a]]}] [:= 'z string?]]))) (is (overlapping? [[:= 'x int?] [:= 'y {:s-vars ['a] :body [:s-var 'a]}] [:= 'z string?]]))) (deftest satisfiable?-test (is (satisfiable? [[:= 'c char?] [:= 'c {:s-vars ['a] :with [[:= 'c [:s-var 'a]]] :body [:vector [:s-var 'a]]}]] [[:= 'c [:vector [:vector char?]]]])) (is (not (satisfiable? [[:= 'c char?] [:= 'c {:s-vars ['a] :with [[:= 'c [:s-var 'a]]] :body [:vector [:s-var 'a]]}]] [[:= 'c [:vector [:vector int?]]]]))))
[ { "context": " :name \"jonas\"}})))\n (is (nil? (schema-checker {:somethi", "end": 5584, "score": 0.982818603515625, "start": 5579, "tag": "NAME", "value": "jonas" }, { "context": " :name \"jonas\"}})))\n (is (nil? (schema-checker {:somethi", "end": 5725, "score": 0.9861997961997986, "start": 5720, "tag": "NAME", "value": "jonas" }, { "context": " :name \"jonas\"}})))\n (is (nil? (schema-checker {:somethi", "end": 5933, "score": 0.9953776001930237, "start": 5928, "tag": "NAME", "value": "jonas" }, { "context": " :name \"jonas\"}})))\n (is (= {:something {:model 'disa", "end": 6537, "score": 0.9841451644897461, "start": 6532, "tag": "NAME", "value": "jonas" }, { "context": " :name \"jonas\"\n :pos", "end": 7041, "score": 0.9994744062423706, "start": 7036, "tag": "NAME", "value": "jonas" } ]
test/prismatic_graphql/core_test.clj
nubank/prismatic-graphql
1
(ns prismatic-graphql.core-test (:require [clojure.test :refer :all] [prismatic-graphql.core :as core] [clojure.java.io :as io] [matcher-combinators.test :refer [match?]] [schema.core :as s]) (:import [schema.core ConditionalSchema])) (defn load-query [query-name] (slurp (io/resource (str "prismatic-graphql/test-data/" (name query-name) ".graphql")))) (def schema (slurp (io/resource "prismatic-graphql/test-data/schema.graphql"))) (def options {:scalars {:Keyword s/Keyword}}) (deftest valid-schema?-test (testing "it returns true to a valid GraphQL schema" (is (true? (core/valid-schema? schema)))) (testing "it returns false to an invalid GraphQL schema" (is (false? (core/valid-schema? "invalid schema"))))) (deftest valid-query?-test (testing "it returns true to a valid GraphQL Query" (is (true? (core/valid-query? (load-query :testQuery))))) (testing "it returns false to an invalid GraphQL Query" (is (false? (core/valid-query? "invalid query"))))) (deftest query->data-schema-test (testing "when creating data prismatic schema from a GraphQL query + schema" (testing "simple query" (is (= {:employee {:id s/Str :name s/Str :organizationRole s/Str :requirePermission s/Bool}} (core/query->data-schema schema (load-query :employeeQuery) options)))) (testing "query with custom scalar" (is (= {:car {:brand s/Keyword :model s/Str}} (core/query->data-schema schema (load-query :customScalarQuery) options)))) (testing "query with aliases" (is (= {:car {:manufacture s/Keyword :model s/Str}} (core/query->data-schema schema (load-query :aliasQuery) options)))) (testing "query with list result" (is (= {:task {:name (s/maybe s/Str) :tags [(s/maybe s/Str)]}} (core/query->data-schema schema (load-query :listQuery) options)))) (testing "on a mutation result" (is (= {:newPerson {:__typename (s/enum "Partner" "Customer" "Employee") :name s/Str}} (core/query->data-schema schema (load-query :newPersonMutation) options)))) (testing "on a mutation with scalar result" (is (= {:newLoan (s/maybe s/Str)} (core/query->data-schema schema (load-query :camelCaseInputMutation) options)))) ;; TODO: Test better conditional schemas (testing "with one interface" (is (match? {:customer {:id s/Str :name s/Str} :person (partial instance? ConditionalSchema)} (core/query->data-schema schema (load-query :testQuery) options)))) (testing "query with union result" (is (match? {:something (partial instance? ConditionalSchema)} (core/query->data-schema schema (load-query :unionQuery) options)))) (testing "when doing an interface or union query it required asking the __typename" (is (thrown-with-msg? AssertionError #"Assert failed: Unions and Interface Types Require __typename on query" (core/query->data-schema schema (load-query :interfaceNoTypename) options)))) (testing "does not accept queries with two ops" (is (thrown-with-msg? IllegalArgumentException #"no operation name supplied" (core/query->data-schema schema (load-query :twoOps) options)))) (testing "throws AssertionError on invalid query" (is (thrown-with-msg? AssertionError #"field not in scope: wololo" (core/query->data-schema schema (load-query :invalidQuery) options)))))) (deftest conditional-schemas-test (testing "on simple interface schemas" (let [schema-checker (s/checker (core/query->data-schema schema (load-query :testQuery) options))] (testing "we can coerce valid values" (is (nil? (schema-checker {:customer {:id "123" :name "test"} :person {:__typename "Employee" :name "test" :position "position"}}))) (is (nil? (schema-checker {:customer {:id "123" :name "test"} :person {:__typename "Customer" :name "test"}})))) (testing "wrong values are not accepted" (is (= {:person {:position 'disallowed-key}} (schema-checker {:customer {:id "123" :name "test"} :person {:__typename "Customer" :name "test" :position "position"}}))) (is (= {:person {:position 'missing-required-key}} (schema-checker {:customer {:id "123" :name "test"} :person {:__typename "Employee" :name "test"}})))))) (testing "on complex union and interface schemas" (let [schema-checker (s/checker (core/query->data-schema schema (load-query :unionQuery) options))] (testing "we can coerce valid values" (is (nil? (schema-checker {:something {:__typename "Car" :model "corsa"}}))) (is (nil? (schema-checker {:something {:__typename "Customer" :name "jonas"}}))) (is (nil? (schema-checker {:something {:__typename "Partner" :name "jonas"}}))) (is (nil? (schema-checker {:something {:__typename "Employee" :position "test" :name "jonas"}}))) (is (nil? (schema-checker {:something {:__typename nil}})))) (testing "wrong values are not accepted" (is (= {:something {:model 'disallowed-key :name 'missing-required-key}} (schema-checker {:something {:__typename "Customer" :model "corsa"}}))) (is (= {:something {:model 'missing-required-key :name 'disallowed-key}} (schema-checker {:something {:__typename "Car" :name "jonas"}}))) (is (= {:something {:model 'disallowed-key :name 'missing-required-key :position 'missing-required-key}} (schema-checker {:something {:__typename "Employee" :model "corsa"}}))) (is (= {:something {:position 'disallowed-key}} (schema-checker {:something {:__typename "Customer" :name "jonas" :position "test"}}))))))) (deftest query->variables-schema-test (testing "when creating variables prismatic schemas from GraphQL Query + Schema" (testing "simple query" (is (= {:id s/Str} (core/query->variables-schema schema (load-query :employeeQuery) options)))) (testing "on query without variables - returns an empty map" (is (= {} (core/query->variables-schema schema (load-query :aliasQuery) options)))) (testing "on a mutation with input type" (is (= {:input {:name s/Str :age s/Int :tags [s/Str]}} (core/query->variables-schema schema (load-query :newPersonMutation) options))))))
113995
(ns prismatic-graphql.core-test (:require [clojure.test :refer :all] [prismatic-graphql.core :as core] [clojure.java.io :as io] [matcher-combinators.test :refer [match?]] [schema.core :as s]) (:import [schema.core ConditionalSchema])) (defn load-query [query-name] (slurp (io/resource (str "prismatic-graphql/test-data/" (name query-name) ".graphql")))) (def schema (slurp (io/resource "prismatic-graphql/test-data/schema.graphql"))) (def options {:scalars {:Keyword s/Keyword}}) (deftest valid-schema?-test (testing "it returns true to a valid GraphQL schema" (is (true? (core/valid-schema? schema)))) (testing "it returns false to an invalid GraphQL schema" (is (false? (core/valid-schema? "invalid schema"))))) (deftest valid-query?-test (testing "it returns true to a valid GraphQL Query" (is (true? (core/valid-query? (load-query :testQuery))))) (testing "it returns false to an invalid GraphQL Query" (is (false? (core/valid-query? "invalid query"))))) (deftest query->data-schema-test (testing "when creating data prismatic schema from a GraphQL query + schema" (testing "simple query" (is (= {:employee {:id s/Str :name s/Str :organizationRole s/Str :requirePermission s/Bool}} (core/query->data-schema schema (load-query :employeeQuery) options)))) (testing "query with custom scalar" (is (= {:car {:brand s/Keyword :model s/Str}} (core/query->data-schema schema (load-query :customScalarQuery) options)))) (testing "query with aliases" (is (= {:car {:manufacture s/Keyword :model s/Str}} (core/query->data-schema schema (load-query :aliasQuery) options)))) (testing "query with list result" (is (= {:task {:name (s/maybe s/Str) :tags [(s/maybe s/Str)]}} (core/query->data-schema schema (load-query :listQuery) options)))) (testing "on a mutation result" (is (= {:newPerson {:__typename (s/enum "Partner" "Customer" "Employee") :name s/Str}} (core/query->data-schema schema (load-query :newPersonMutation) options)))) (testing "on a mutation with scalar result" (is (= {:newLoan (s/maybe s/Str)} (core/query->data-schema schema (load-query :camelCaseInputMutation) options)))) ;; TODO: Test better conditional schemas (testing "with one interface" (is (match? {:customer {:id s/Str :name s/Str} :person (partial instance? ConditionalSchema)} (core/query->data-schema schema (load-query :testQuery) options)))) (testing "query with union result" (is (match? {:something (partial instance? ConditionalSchema)} (core/query->data-schema schema (load-query :unionQuery) options)))) (testing "when doing an interface or union query it required asking the __typename" (is (thrown-with-msg? AssertionError #"Assert failed: Unions and Interface Types Require __typename on query" (core/query->data-schema schema (load-query :interfaceNoTypename) options)))) (testing "does not accept queries with two ops" (is (thrown-with-msg? IllegalArgumentException #"no operation name supplied" (core/query->data-schema schema (load-query :twoOps) options)))) (testing "throws AssertionError on invalid query" (is (thrown-with-msg? AssertionError #"field not in scope: wololo" (core/query->data-schema schema (load-query :invalidQuery) options)))))) (deftest conditional-schemas-test (testing "on simple interface schemas" (let [schema-checker (s/checker (core/query->data-schema schema (load-query :testQuery) options))] (testing "we can coerce valid values" (is (nil? (schema-checker {:customer {:id "123" :name "test"} :person {:__typename "Employee" :name "test" :position "position"}}))) (is (nil? (schema-checker {:customer {:id "123" :name "test"} :person {:__typename "Customer" :name "test"}})))) (testing "wrong values are not accepted" (is (= {:person {:position 'disallowed-key}} (schema-checker {:customer {:id "123" :name "test"} :person {:__typename "Customer" :name "test" :position "position"}}))) (is (= {:person {:position 'missing-required-key}} (schema-checker {:customer {:id "123" :name "test"} :person {:__typename "Employee" :name "test"}})))))) (testing "on complex union and interface schemas" (let [schema-checker (s/checker (core/query->data-schema schema (load-query :unionQuery) options))] (testing "we can coerce valid values" (is (nil? (schema-checker {:something {:__typename "Car" :model "corsa"}}))) (is (nil? (schema-checker {:something {:__typename "Customer" :name "<NAME>"}}))) (is (nil? (schema-checker {:something {:__typename "Partner" :name "<NAME>"}}))) (is (nil? (schema-checker {:something {:__typename "Employee" :position "test" :name "<NAME>"}}))) (is (nil? (schema-checker {:something {:__typename nil}})))) (testing "wrong values are not accepted" (is (= {:something {:model 'disallowed-key :name 'missing-required-key}} (schema-checker {:something {:__typename "Customer" :model "corsa"}}))) (is (= {:something {:model 'missing-required-key :name 'disallowed-key}} (schema-checker {:something {:__typename "Car" :name "<NAME>"}}))) (is (= {:something {:model 'disallowed-key :name 'missing-required-key :position 'missing-required-key}} (schema-checker {:something {:__typename "Employee" :model "corsa"}}))) (is (= {:something {:position 'disallowed-key}} (schema-checker {:something {:__typename "Customer" :name "<NAME>" :position "test"}}))))))) (deftest query->variables-schema-test (testing "when creating variables prismatic schemas from GraphQL Query + Schema" (testing "simple query" (is (= {:id s/Str} (core/query->variables-schema schema (load-query :employeeQuery) options)))) (testing "on query without variables - returns an empty map" (is (= {} (core/query->variables-schema schema (load-query :aliasQuery) options)))) (testing "on a mutation with input type" (is (= {:input {:name s/Str :age s/Int :tags [s/Str]}} (core/query->variables-schema schema (load-query :newPersonMutation) options))))))
true
(ns prismatic-graphql.core-test (:require [clojure.test :refer :all] [prismatic-graphql.core :as core] [clojure.java.io :as io] [matcher-combinators.test :refer [match?]] [schema.core :as s]) (:import [schema.core ConditionalSchema])) (defn load-query [query-name] (slurp (io/resource (str "prismatic-graphql/test-data/" (name query-name) ".graphql")))) (def schema (slurp (io/resource "prismatic-graphql/test-data/schema.graphql"))) (def options {:scalars {:Keyword s/Keyword}}) (deftest valid-schema?-test (testing "it returns true to a valid GraphQL schema" (is (true? (core/valid-schema? schema)))) (testing "it returns false to an invalid GraphQL schema" (is (false? (core/valid-schema? "invalid schema"))))) (deftest valid-query?-test (testing "it returns true to a valid GraphQL Query" (is (true? (core/valid-query? (load-query :testQuery))))) (testing "it returns false to an invalid GraphQL Query" (is (false? (core/valid-query? "invalid query"))))) (deftest query->data-schema-test (testing "when creating data prismatic schema from a GraphQL query + schema" (testing "simple query" (is (= {:employee {:id s/Str :name s/Str :organizationRole s/Str :requirePermission s/Bool}} (core/query->data-schema schema (load-query :employeeQuery) options)))) (testing "query with custom scalar" (is (= {:car {:brand s/Keyword :model s/Str}} (core/query->data-schema schema (load-query :customScalarQuery) options)))) (testing "query with aliases" (is (= {:car {:manufacture s/Keyword :model s/Str}} (core/query->data-schema schema (load-query :aliasQuery) options)))) (testing "query with list result" (is (= {:task {:name (s/maybe s/Str) :tags [(s/maybe s/Str)]}} (core/query->data-schema schema (load-query :listQuery) options)))) (testing "on a mutation result" (is (= {:newPerson {:__typename (s/enum "Partner" "Customer" "Employee") :name s/Str}} (core/query->data-schema schema (load-query :newPersonMutation) options)))) (testing "on a mutation with scalar result" (is (= {:newLoan (s/maybe s/Str)} (core/query->data-schema schema (load-query :camelCaseInputMutation) options)))) ;; TODO: Test better conditional schemas (testing "with one interface" (is (match? {:customer {:id s/Str :name s/Str} :person (partial instance? ConditionalSchema)} (core/query->data-schema schema (load-query :testQuery) options)))) (testing "query with union result" (is (match? {:something (partial instance? ConditionalSchema)} (core/query->data-schema schema (load-query :unionQuery) options)))) (testing "when doing an interface or union query it required asking the __typename" (is (thrown-with-msg? AssertionError #"Assert failed: Unions and Interface Types Require __typename on query" (core/query->data-schema schema (load-query :interfaceNoTypename) options)))) (testing "does not accept queries with two ops" (is (thrown-with-msg? IllegalArgumentException #"no operation name supplied" (core/query->data-schema schema (load-query :twoOps) options)))) (testing "throws AssertionError on invalid query" (is (thrown-with-msg? AssertionError #"field not in scope: wololo" (core/query->data-schema schema (load-query :invalidQuery) options)))))) (deftest conditional-schemas-test (testing "on simple interface schemas" (let [schema-checker (s/checker (core/query->data-schema schema (load-query :testQuery) options))] (testing "we can coerce valid values" (is (nil? (schema-checker {:customer {:id "123" :name "test"} :person {:__typename "Employee" :name "test" :position "position"}}))) (is (nil? (schema-checker {:customer {:id "123" :name "test"} :person {:__typename "Customer" :name "test"}})))) (testing "wrong values are not accepted" (is (= {:person {:position 'disallowed-key}} (schema-checker {:customer {:id "123" :name "test"} :person {:__typename "Customer" :name "test" :position "position"}}))) (is (= {:person {:position 'missing-required-key}} (schema-checker {:customer {:id "123" :name "test"} :person {:__typename "Employee" :name "test"}})))))) (testing "on complex union and interface schemas" (let [schema-checker (s/checker (core/query->data-schema schema (load-query :unionQuery) options))] (testing "we can coerce valid values" (is (nil? (schema-checker {:something {:__typename "Car" :model "corsa"}}))) (is (nil? (schema-checker {:something {:__typename "Customer" :name "PI:NAME:<NAME>END_PI"}}))) (is (nil? (schema-checker {:something {:__typename "Partner" :name "PI:NAME:<NAME>END_PI"}}))) (is (nil? (schema-checker {:something {:__typename "Employee" :position "test" :name "PI:NAME:<NAME>END_PI"}}))) (is (nil? (schema-checker {:something {:__typename nil}})))) (testing "wrong values are not accepted" (is (= {:something {:model 'disallowed-key :name 'missing-required-key}} (schema-checker {:something {:__typename "Customer" :model "corsa"}}))) (is (= {:something {:model 'missing-required-key :name 'disallowed-key}} (schema-checker {:something {:__typename "Car" :name "PI:NAME:<NAME>END_PI"}}))) (is (= {:something {:model 'disallowed-key :name 'missing-required-key :position 'missing-required-key}} (schema-checker {:something {:__typename "Employee" :model "corsa"}}))) (is (= {:something {:position 'disallowed-key}} (schema-checker {:something {:__typename "Customer" :name "PI:NAME:<NAME>END_PI" :position "test"}}))))))) (deftest query->variables-schema-test (testing "when creating variables prismatic schemas from GraphQL Query + Schema" (testing "simple query" (is (= {:id s/Str} (core/query->variables-schema schema (load-query :employeeQuery) options)))) (testing "on query without variables - returns an empty map" (is (= {} (core/query->variables-schema schema (load-query :aliasQuery) options)))) (testing "on a mutation with input type" (is (= {:input {:name s/Str :age s/Int :tags [s/Str]}} (core/query->variables-schema schema (load-query :newPersonMutation) options))))))
[ { "context": "ere-expr \"length > 3 AND height < 4.5 OR name = \\\"Pete\\\"\") \n {:left {:left {:comparison [:length ", "end": 3302, "score": 0.7826464176177979, "start": 3301, "tag": "NAME", "value": "P" }, { "context": " :op :OR\n :right {:comparison [:name := \"Pete\"]}}))\n \n (testing \"can parse a query with four ", "end": 3488, "score": 0.9997599720954895, "start": 3484, "tag": "NAME", "value": "Pete" }, { "context": "re-expr \"length > 3 AND (height < 4.5 OR name = \\\"Pete\\\")\") \n {:left {:comparison [:length :> 3]}\n ", "end": 4282, "score": 0.9997442960739136, "start": 4278, "tag": "NAME", "value": "Pete" }, { "context": " :OR\n :right {:comparison [:name := \"Pete\"]}}})))\n\n(deftest test-select-expressions\n (test", "end": 4467, "score": 0.9997529983520508, "start": 4463, "tag": "NAME", "value": "Pete" } ]
test/qu/test/query/parser.clj
marcesher/qu
325
(ns qu.test.query.parser (:require [clojure.test :refer :all] [qu.test-util :refer :all] [protoflex.parse :as p] [qu.query.parser :refer :all] [clj-time.core :as time])) (defmacro has-parse-error [& body] `(try ~@body (is false) (catch Exception ex# (is (re-find #"^Parse Error" (.getMessage ex#)))))) (deftest test-value (testing "can parse numbers" (is (= (p/parse value "4.5"))) 4.5) (testing "can parse strings with single or double quotes" (is (= (p/parse value "\"hello world\"") "hello world")) (is (= (p/parse value "'hello world'") "hello world"))) (testing "can parse boolean literals" (is (= (p/parse value "true") {:bool true})) (is (= (p/parse value "false") {:bool false}))) (testing "can parse dates" (is (= (p/parse value "2013-04-01") (time/date-time 2013 4 1))) (is (= (p/parse value "1999/12/31") (time/date-time 1999 12 31))))) (deftest test-identifiers (testing "identifiers can be made up of letters, numbers, dashes, and underscores" (does= (p/parse identifier "hello") :hello (p/parse identifier "hello-world") :hello-world (p/parse identifier "HelloWorld") :HelloWorld (p/parse identifier "h3110_w0r1d") :h3110_w0r1d)) (testing "identifiers must start with a letter" (has-parse-error (p/parse identifier "3times")))) (deftest test-comparisons (testing "simple comparisons can be parsed" (does= (p/parse comparison "length > 3") {:comparison [:length :> 3]} (p/parse comparison "length < 3") {:comparison [:length :< 3]} (p/parse comparison "size != 12.5") {:comparison [:size :!= 12.5]})) (testing "IS NULL and IS NOT NULL comparisons can be parsed" (does= (p/parse comparison "length IS NULL") {:comparison [:length := nil]} (p/parse comparison "length IS NOT NULL") {:comparison [:length :!= nil]})) (testing "LIKE and ILIKE comparisons can be parsed" (does= (p/parse comparison "name LIKE 'Mar%'") {:comparison [:name :LIKE "Mar%"]} (p/parse comparison "name ILIKE 'mar%'") {:comparison [:name :ILIKE "mar%"]})) (testing "IN comparisons can be parsed" (is (= (p/parse comparison "length IN (1, 2, 3)") {:comparison [:length :IN [1 2 3]]}))) (testing "spaces are irrelevant" (is (= (p/parse comparison "length>3") {:comparison [:length :> 3]})))) (deftest test-where-expressions (testing "can be comparisons" (does= (p/parse where-expr "length > 3") {:comparison [:length :> 3]} (p/parse where-expr "tax_returns > 20000") {:comparison [:tax_returns :> 20000]})) (testing "can have NOT operators" (does= (p/parse where-expr "NOT length > 3") {:not {:comparison [:length :> 3]}} (p/parse where-expr "NOT (length > 3 AND height < 4.5)") {:not {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}}})) (testing "can have AND and OR operators" (does= (p/parse where-expr "length > 3 AND height < 4.5") {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}} (p/parse where-expr "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"]}})) (testing "can parse a query with four parts" (does= (p/parse where-expr "as_of_year=2011 AND state_abbr=\"CA\" AND applicant_race_1=1 AND applicant_ethnicity=1") {:left {:left {:left {:comparison [:as_of_year := 2011]} :op :AND :right {:comparison [:state_abbr := "CA"]}} :op :AND :right {:comparison [:applicant_race_1 := 1]}} :op :AND :right {:comparison [:applicant_ethnicity := 1]}})) (testing "can have parentheses for precedence" (does= (p/parse where-expr "(length > 3 AND height < 4.5)") {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}} (p/parse where-expr "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-select-expressions (testing "can have one column" (is (= (p/parse select-expr "length")) [{:select :length}])) (testing "can have multiple columns" (is (= (p/parse select-expr "length, height") [{:select :length} {:select :height}]))) (testing "can have aggregations" (is (= (p/parse select-expr "state, SUM(population)") [{:select :state} {:aggregation [:SUM :population] :select :sum_population}]))) (testing "COUNT aggregations do not need an identifier" (does= (p/parse select-expr "state, COUNT()") [{:select :state} {:aggregation [:COUNT :_id] :select :count}] (p/parse select-expr "state, count()") [{:select :state} {:aggregation [:COUNT :_id] :select :count}])) (testing "aggregations are case-insensitive" (does= (p/parse select-expr "state, sum(population)") [{:select :state} {:aggregation [:SUM :population] :select :sum_population}] (p/parse select-expr "state, cOuNt(population)") [{:select :state} {:aggregation [:COUNT :population] :select :count_population}])) (testing "invalid aggregations do not work" (has-parse-error (p/parse select-expr "state, TOTAL(population)")))) (deftest test-group-expressions (testing "can have one column" (is (= (p/parse group-expr "state") [:state]))) (testing "can have multiple columns" (is (= (p/parse group-expr "state, county") [:state :county])))) ;; (run-tests)
100773
(ns qu.test.query.parser (:require [clojure.test :refer :all] [qu.test-util :refer :all] [protoflex.parse :as p] [qu.query.parser :refer :all] [clj-time.core :as time])) (defmacro has-parse-error [& body] `(try ~@body (is false) (catch Exception ex# (is (re-find #"^Parse Error" (.getMessage ex#)))))) (deftest test-value (testing "can parse numbers" (is (= (p/parse value "4.5"))) 4.5) (testing "can parse strings with single or double quotes" (is (= (p/parse value "\"hello world\"") "hello world")) (is (= (p/parse value "'hello world'") "hello world"))) (testing "can parse boolean literals" (is (= (p/parse value "true") {:bool true})) (is (= (p/parse value "false") {:bool false}))) (testing "can parse dates" (is (= (p/parse value "2013-04-01") (time/date-time 2013 4 1))) (is (= (p/parse value "1999/12/31") (time/date-time 1999 12 31))))) (deftest test-identifiers (testing "identifiers can be made up of letters, numbers, dashes, and underscores" (does= (p/parse identifier "hello") :hello (p/parse identifier "hello-world") :hello-world (p/parse identifier "HelloWorld") :HelloWorld (p/parse identifier "h3110_w0r1d") :h3110_w0r1d)) (testing "identifiers must start with a letter" (has-parse-error (p/parse identifier "3times")))) (deftest test-comparisons (testing "simple comparisons can be parsed" (does= (p/parse comparison "length > 3") {:comparison [:length :> 3]} (p/parse comparison "length < 3") {:comparison [:length :< 3]} (p/parse comparison "size != 12.5") {:comparison [:size :!= 12.5]})) (testing "IS NULL and IS NOT NULL comparisons can be parsed" (does= (p/parse comparison "length IS NULL") {:comparison [:length := nil]} (p/parse comparison "length IS NOT NULL") {:comparison [:length :!= nil]})) (testing "LIKE and ILIKE comparisons can be parsed" (does= (p/parse comparison "name LIKE 'Mar%'") {:comparison [:name :LIKE "Mar%"]} (p/parse comparison "name ILIKE 'mar%'") {:comparison [:name :ILIKE "mar%"]})) (testing "IN comparisons can be parsed" (is (= (p/parse comparison "length IN (1, 2, 3)") {:comparison [:length :IN [1 2 3]]}))) (testing "spaces are irrelevant" (is (= (p/parse comparison "length>3") {:comparison [:length :> 3]})))) (deftest test-where-expressions (testing "can be comparisons" (does= (p/parse where-expr "length > 3") {:comparison [:length :> 3]} (p/parse where-expr "tax_returns > 20000") {:comparison [:tax_returns :> 20000]})) (testing "can have NOT operators" (does= (p/parse where-expr "NOT length > 3") {:not {:comparison [:length :> 3]}} (p/parse where-expr "NOT (length > 3 AND height < 4.5)") {:not {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}}})) (testing "can have AND and OR operators" (does= (p/parse where-expr "length > 3 AND height < 4.5") {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}} (p/parse where-expr "length > 3 AND height < 4.5 OR name = \"<NAME>ete\"") {:left {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}} :op :OR :right {:comparison [:name := "<NAME>"]}})) (testing "can parse a query with four parts" (does= (p/parse where-expr "as_of_year=2011 AND state_abbr=\"CA\" AND applicant_race_1=1 AND applicant_ethnicity=1") {:left {:left {:left {:comparison [:as_of_year := 2011]} :op :AND :right {:comparison [:state_abbr := "CA"]}} :op :AND :right {:comparison [:applicant_race_1 := 1]}} :op :AND :right {:comparison [:applicant_ethnicity := 1]}})) (testing "can have parentheses for precedence" (does= (p/parse where-expr "(length > 3 AND height < 4.5)") {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}} (p/parse where-expr "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-select-expressions (testing "can have one column" (is (= (p/parse select-expr "length")) [{:select :length}])) (testing "can have multiple columns" (is (= (p/parse select-expr "length, height") [{:select :length} {:select :height}]))) (testing "can have aggregations" (is (= (p/parse select-expr "state, SUM(population)") [{:select :state} {:aggregation [:SUM :population] :select :sum_population}]))) (testing "COUNT aggregations do not need an identifier" (does= (p/parse select-expr "state, COUNT()") [{:select :state} {:aggregation [:COUNT :_id] :select :count}] (p/parse select-expr "state, count()") [{:select :state} {:aggregation [:COUNT :_id] :select :count}])) (testing "aggregations are case-insensitive" (does= (p/parse select-expr "state, sum(population)") [{:select :state} {:aggregation [:SUM :population] :select :sum_population}] (p/parse select-expr "state, cOuNt(population)") [{:select :state} {:aggregation [:COUNT :population] :select :count_population}])) (testing "invalid aggregations do not work" (has-parse-error (p/parse select-expr "state, TOTAL(population)")))) (deftest test-group-expressions (testing "can have one column" (is (= (p/parse group-expr "state") [:state]))) (testing "can have multiple columns" (is (= (p/parse group-expr "state, county") [:state :county])))) ;; (run-tests)
true
(ns qu.test.query.parser (:require [clojure.test :refer :all] [qu.test-util :refer :all] [protoflex.parse :as p] [qu.query.parser :refer :all] [clj-time.core :as time])) (defmacro has-parse-error [& body] `(try ~@body (is false) (catch Exception ex# (is (re-find #"^Parse Error" (.getMessage ex#)))))) (deftest test-value (testing "can parse numbers" (is (= (p/parse value "4.5"))) 4.5) (testing "can parse strings with single or double quotes" (is (= (p/parse value "\"hello world\"") "hello world")) (is (= (p/parse value "'hello world'") "hello world"))) (testing "can parse boolean literals" (is (= (p/parse value "true") {:bool true})) (is (= (p/parse value "false") {:bool false}))) (testing "can parse dates" (is (= (p/parse value "2013-04-01") (time/date-time 2013 4 1))) (is (= (p/parse value "1999/12/31") (time/date-time 1999 12 31))))) (deftest test-identifiers (testing "identifiers can be made up of letters, numbers, dashes, and underscores" (does= (p/parse identifier "hello") :hello (p/parse identifier "hello-world") :hello-world (p/parse identifier "HelloWorld") :HelloWorld (p/parse identifier "h3110_w0r1d") :h3110_w0r1d)) (testing "identifiers must start with a letter" (has-parse-error (p/parse identifier "3times")))) (deftest test-comparisons (testing "simple comparisons can be parsed" (does= (p/parse comparison "length > 3") {:comparison [:length :> 3]} (p/parse comparison "length < 3") {:comparison [:length :< 3]} (p/parse comparison "size != 12.5") {:comparison [:size :!= 12.5]})) (testing "IS NULL and IS NOT NULL comparisons can be parsed" (does= (p/parse comparison "length IS NULL") {:comparison [:length := nil]} (p/parse comparison "length IS NOT NULL") {:comparison [:length :!= nil]})) (testing "LIKE and ILIKE comparisons can be parsed" (does= (p/parse comparison "name LIKE 'Mar%'") {:comparison [:name :LIKE "Mar%"]} (p/parse comparison "name ILIKE 'mar%'") {:comparison [:name :ILIKE "mar%"]})) (testing "IN comparisons can be parsed" (is (= (p/parse comparison "length IN (1, 2, 3)") {:comparison [:length :IN [1 2 3]]}))) (testing "spaces are irrelevant" (is (= (p/parse comparison "length>3") {:comparison [:length :> 3]})))) (deftest test-where-expressions (testing "can be comparisons" (does= (p/parse where-expr "length > 3") {:comparison [:length :> 3]} (p/parse where-expr "tax_returns > 20000") {:comparison [:tax_returns :> 20000]})) (testing "can have NOT operators" (does= (p/parse where-expr "NOT length > 3") {:not {:comparison [:length :> 3]}} (p/parse where-expr "NOT (length > 3 AND height < 4.5)") {:not {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}}})) (testing "can have AND and OR operators" (does= (p/parse where-expr "length > 3 AND height < 4.5") {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}} (p/parse where-expr "length > 3 AND height < 4.5 OR name = \"PI:NAME:<NAME>END_PIete\"") {:left {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}} :op :OR :right {:comparison [:name := "PI:NAME:<NAME>END_PI"]}})) (testing "can parse a query with four parts" (does= (p/parse where-expr "as_of_year=2011 AND state_abbr=\"CA\" AND applicant_race_1=1 AND applicant_ethnicity=1") {:left {:left {:left {:comparison [:as_of_year := 2011]} :op :AND :right {:comparison [:state_abbr := "CA"]}} :op :AND :right {:comparison [:applicant_race_1 := 1]}} :op :AND :right {:comparison [:applicant_ethnicity := 1]}})) (testing "can have parentheses for precedence" (does= (p/parse where-expr "(length > 3 AND height < 4.5)") {:left {:comparison [:length :> 3]} :op :AND :right {:comparison [:height :< 4.5]}} (p/parse where-expr "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-select-expressions (testing "can have one column" (is (= (p/parse select-expr "length")) [{:select :length}])) (testing "can have multiple columns" (is (= (p/parse select-expr "length, height") [{:select :length} {:select :height}]))) (testing "can have aggregations" (is (= (p/parse select-expr "state, SUM(population)") [{:select :state} {:aggregation [:SUM :population] :select :sum_population}]))) (testing "COUNT aggregations do not need an identifier" (does= (p/parse select-expr "state, COUNT()") [{:select :state} {:aggregation [:COUNT :_id] :select :count}] (p/parse select-expr "state, count()") [{:select :state} {:aggregation [:COUNT :_id] :select :count}])) (testing "aggregations are case-insensitive" (does= (p/parse select-expr "state, sum(population)") [{:select :state} {:aggregation [:SUM :population] :select :sum_population}] (p/parse select-expr "state, cOuNt(population)") [{:select :state} {:aggregation [:COUNT :population] :select :count_population}])) (testing "invalid aggregations do not work" (has-parse-error (p/parse select-expr "state, TOTAL(population)")))) (deftest test-group-expressions (testing "can have one column" (is (= (p/parse group-expr "state") [:state]))) (testing "can have multiple columns" (is (= (p/parse group-expr "state, county") [:state :county])))) ;; (run-tests)
[ { "context": " 8]\n [\"Krua Siri\" 9]\n ", "end": 958, "score": 0.6199544072151184, "start": 956, "tag": "NAME", "value": "ru" }, { "context": "i\" 9]\n [\"Fred 62\" 10]]\n :cols", "end": 1016, "score": 0.6277380585670471, "start": 1013, "tag": "NAME", "value": "red" } ]
c#-metabase/test/metabase/query_processor_test/fields_test.clj
hanakhry/Crime_Admin
0
(ns metabase.query-processor-test.fields-test "Tests for the `:fields` clause." (:require [clojure.test :refer :all] [metabase.query-processor-test :as qp.test] [metabase.test :as mt])) (deftest fields-clause-test (mt/test-drivers (mt/normal-drivers) (testing (str "Test that we can restrict the Fields that get returned to the ones specified, and that results come " "back in the order of the IDs in the `fields` clause") (is (= {:rows [["Red Medicine" 1] ["Stout Burgers & Beers" 2] ["The Apple Pan" 3] ["Wurstküche" 4] ["Brite Spot Family Restaurant" 5] ["The 101 Coffee Shop" 6] ["Don Day Korean Restaurant" 7] ["25°" 8] ["Krua Siri" 9] ["Fred 62" 10]] :cols [(mt/col :venues :name) (mt/col :venues :id)]} (mt/format-rows-by [str int] (qp.test/rows-and-cols (mt/run-mbql-query venues {:fields [$name $id] :limit 10 :order-by [[:asc $id]]}))))))))
107940
(ns metabase.query-processor-test.fields-test "Tests for the `:fields` clause." (:require [clojure.test :refer :all] [metabase.query-processor-test :as qp.test] [metabase.test :as mt])) (deftest fields-clause-test (mt/test-drivers (mt/normal-drivers) (testing (str "Test that we can restrict the Fields that get returned to the ones specified, and that results come " "back in the order of the IDs in the `fields` clause") (is (= {:rows [["Red Medicine" 1] ["Stout Burgers & Beers" 2] ["The Apple Pan" 3] ["Wurstküche" 4] ["Brite Spot Family Restaurant" 5] ["The 101 Coffee Shop" 6] ["Don Day Korean Restaurant" 7] ["25°" 8] ["K<NAME>a Siri" 9] ["F<NAME> 62" 10]] :cols [(mt/col :venues :name) (mt/col :venues :id)]} (mt/format-rows-by [str int] (qp.test/rows-and-cols (mt/run-mbql-query venues {:fields [$name $id] :limit 10 :order-by [[:asc $id]]}))))))))
true
(ns metabase.query-processor-test.fields-test "Tests for the `:fields` clause." (:require [clojure.test :refer :all] [metabase.query-processor-test :as qp.test] [metabase.test :as mt])) (deftest fields-clause-test (mt/test-drivers (mt/normal-drivers) (testing (str "Test that we can restrict the Fields that get returned to the ones specified, and that results come " "back in the order of the IDs in the `fields` clause") (is (= {:rows [["Red Medicine" 1] ["Stout Burgers & Beers" 2] ["The Apple Pan" 3] ["Wurstküche" 4] ["Brite Spot Family Restaurant" 5] ["The 101 Coffee Shop" 6] ["Don Day Korean Restaurant" 7] ["25°" 8] ["KPI:NAME:<NAME>END_PIa Siri" 9] ["FPI:NAME:<NAME>END_PI 62" 10]] :cols [(mt/col :venues :name) (mt/col :venues :id)]} (mt/format-rows-by [str int] (qp.test/rows-and-cols (mt/run-mbql-query venues {:fields [$name $id] :limit 10 :order-by [[:asc $id]]}))))))))
[ { "context": "cro network\n NetworkRoot\n {})\n\n(s/def ::name #{\"Arnold\" \"Bea\" \"Dude\" \"Girl\"})\n\n(mutations/defmutation se", "end": 8638, "score": 0.9995992183685303, "start": 8632, "tag": "NAME", "value": "Arnold" }, { "context": "rk\n NetworkRoot\n {})\n\n(s/def ::name #{\"Arnold\" \"Bea\" \"Dude\" \"Girl\"})\n\n(mutations/defmutation send-som", "end": 8644, "score": 0.998935341835022, "start": 8641, "tag": "NAME", "value": "Bea" }, { "context": "etworkRoot\n {})\n\n(s/def ::name #{\"Arnold\" \"Bea\" \"Dude\" \"Girl\"})\n\n(mutations/defmutation send-something ", "end": 8651, "score": 0.9963091015815735, "start": 8647, "tag": "NAME", "value": "Dude" }, { "context": "oot\n {})\n\n(s/def ::name #{\"Arnold\" \"Bea\" \"Dude\" \"Girl\"})\n\n(mutations/defmutation send-something [_]\n (", "end": 8658, "score": 0.9700130820274353, "start": 8654, "tag": "NAME", "value": "Girl" } ]
devcards/fulcro/inspect/ui/network_cards.cljs
Lokeh/fulcro-inspect
67
(ns fulcro.inspect.ui.network-cards (:require [devcards.core :refer-macros [defcard]] [fulcro-css.css :as css] [fulcro.client.cards :refer-macros [defcard-fulcro]] [fulcro.inspect.ui.network :as network] [fulcro.client.primitives :as fp] [fulcro.client.network :as f.network] [fulcro.client.data-fetch :as fetch] [fulcro.client.mutations :as mutations] [clojure.test.check.generators :as gen] [fulcro.client.dom :as dom] [cljs.spec.alpha :as s] [cljs.core.async :as async :refer [go <!]] [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.core :as p] [com.wsscode.pathom.profile :as pp] [com.wsscode.pathom.fulcro.network :as pfn])) (def request-samples [{:in [:hello :world] :out {:hello "data" :world "value"}} `{:in [(do-something {:foo "bar"})] :out {do-something {}}} {:in [{:ui/root [{:ui/inspector [:fulcro.inspect.core/inspectors {:fulcro.inspect.core/current-app [:fulcro.inspect.ui.inspector/tab :fulcro.inspect.ui.inspector/id {:fulcro.inspect.ui.inspector/app-state [:fulcro.inspect.ui.data-watcher/id {:fulcro.inspect.ui.data-watcher/root-data [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:fulcro.inspect.ui.data-watcher/watches [:ui/expanded? :fulcro.inspect.ui.data-watcher/watch-id :fulcro.inspect.ui.data-watcher/watch-path {:fulcro.inspect.ui.data-watcher/data-viewer [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]}]}]} {:fulcro.inspect.ui.inspector/network [:fulcro.inspect.ui.network/history-id {:fulcro.inspect.ui.network/requests [:fulcro.inspect.ui.network/request-id :fulcro.inspect.ui.network/request-edn :fulcro.inspect.ui.network/request-edn-row-view :fulcro.inspect.ui.network/response-edn :fulcro.inspect.ui.network/request-started-at :fulcro.inspect.ui.network/request-finished-at :fulcro.inspect.ui.network/error]} {:fulcro.inspect.ui.network/active-request [:fulcro.inspect.ui.network/request-id :fulcro.inspect.ui.network/request-edn :fulcro.inspect.ui.network/response-edn :fulcro.inspect.ui.network/request-started-at :fulcro.inspect.ui.network/request-finished-at :fulcro.inspect.ui.network/error {:ui/request-edn-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/response-edn-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/error-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]}]}]} {:fulcro.inspect.ui.inspector/transactions [:fulcro.inspect.ui.transactions/tx-list-id :fulcro.inspect.ui.transactions/tx-filter {:fulcro.inspect.ui.transactions/active-tx [:fulcro.inspect.ui.transactions/tx-id :fulcro.inspect.ui.transactions/timestamp :tx :ret :sends :old-state :new-state :ref :component {:ui/tx-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/ret-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/tx-row-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/sends-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/old-state-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/new-state-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/diff-add-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/diff-rem-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]}]} {:fulcro.inspect.ui.transactions/tx-list [:fulcro.inspect.ui.transactions/tx-id :fulcro.inspect.ui.transactions/timestamp :ref :tx {:ui/tx-row-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]}]}]}]}]} :ui/size :ui/visible?]} :ui/react-key] :out {}}]) (defn gen-remote [] (gen/generate (gen/frequency [[6 (gen/return :remote)] [1 (gen/return :other)]]))) (defn success? [] (gen/generate (gen/frequency [[8 (gen/return true)] [1 (gen/return false)]]))) (defn gen-request [this] (let [id (random-uuid) reconciler (fp/get-reconciler this) remote (gen-remote) {:keys [in out]} (rand-nth request-samples)] (fp/transact! reconciler [::network/history-id "main"] [`(network/request-start ~{::network/remote remote ::network/request-id id ::network/request-edn in})]) (js/setTimeout (fn [] (let [suc? (success?)] (fp/transact! reconciler [::network/history-id "main"] [`(network/request-finish ~(cond-> {::network/remote remote ::network/request-id id} suc? (assoc ::network/response-edn out) (not suc?) (assoc ::network/error {:error "bad"})))]))) (gen/generate (gen/large-integer* {:min 30 :max 7000}))))) (fp/defui ^:once NetworkRoot static fp/InitialAppState (initial-state [_ _] {:ui/react-key (random-uuid) :ui/root (assoc (fp/get-initial-state network/NetworkHistory {}) ::network/history-id "main")}) static fp/IQuery (query [_] [{:ui/root (fp/get-query network/NetworkHistory)} :ui/react-key]) static css/CSS (local-rules [_] [[:.container {:height "500px" :display "flex" :flex-direction "column"}]]) (include-children [_] [network/NetworkHistory]) Object (render [this] (let [{:keys [ui/react-key ui/root]} (fp/props this) css (css/get-classnames NetworkRoot)] (dom/div #js {:key react-key :className (:container css)} (dom/button #js {:onClick #(gen-request this)} "Generate request") (network/network-history root))))) (defcard-fulcro network NetworkRoot {}) (s/def ::name #{"Arnold" "Bea" "Dude" "Girl"}) (mutations/defmutation send-something [_] (action [_] (js/console.log "send something")) (remote [_] true)) (fp/defsc NameLoader [this {::keys [name]} computed] {:initial-state {::id "name-loader"} :ident [::id ::id] :query [::id ::name]} (let [css (css/get-classnames NameLoader)] (dom/div nil (dom/button #js {:onClick #(fetch/load-field this ::name)} "Load name") (if name (str "The name is: " name)) (dom/div nil (dom/button #js {:onClick #(fp/transact! this [`(send-something {})])} "Send"))))) (def name-loader (fp/factory NameLoader)) (fp/defui ^:once NameLoaderRoot static fp/InitialAppState (initial-state [_ _] {:ui/react-key (random-uuid) :ui/root (fp/get-initial-state NameLoader {}) :fulcro.inspect.core/app-id "NameLoader"}) static fp/IQuery (query [_] [{:ui/root (fp/get-query NameLoader)} :ui/react-key]) static css/CSS (local-rules [_] []) (include-children [_] [NameLoader]) Object (render [this] (let [{:keys [ui/react-key ui/root]} (fp/props this)] (dom/div #js {:key react-key} (name-loader root))))) (def indexes (atom {})) (defmulti resolver-fn pc/resolver-dispatch) (def defresolver (pc/resolver-factory resolver-fn indexes)) (defmulti mutation-fn pc/mutation-dispatch) (def defmutation (pc/mutation-factory mutation-fn indexes)) (defresolver 'name {::pc/output [::name]} (fn [_ _] (go (<! (async/timeout 300)) {::name (gen/generate (s/gen ::name))}))) (defresolver 'id-name {::pc/input #{::id} ::pc/output [::name]} (fn [_ _] (go (<! (async/timeout 300)) {::name (gen/generate (s/gen ::name))}))) (def parser (p/async-parser {::p/env {::p/reader [p/map-reader pc/all-async-readers] ::pc/resolver-dispatch resolver-fn ::pc/mutate-dispatch mutation-fn ::pc/indexes @indexes} ::p/mutate pc/mutate-async ::p/plugins [p/request-cache-plugin pp/profile-plugin]})) (defcard-fulcro network-sampler NameLoaderRoot {} {:fulcro {:networking (pfn/local-network parser)}}) (defcard-fulcro network-sampler-remote-i NameLoaderRoot {} {:fulcro {:networking (reify f.network/FulcroRemoteI (transmit [this {::f.network/keys [edn ok-handler]}] (ok-handler {:transaction edn :body {[::id "name-loader"] {::name (gen/generate (s/gen ::name))}}})) (abort [_ _]))}}) (defcard-fulcro multi-network NameLoaderRoot {} {:fulcro {:networking {:remote (pfn/local-network parser) :other (reify f.network/FulcroRemoteI (transmit [this {::f.network/keys [edn ok-handler]}] (ok-handler {:transaction edn :body {[::id "name-loader"] {::name (gen/generate (s/gen ::name))}}})) (abort [_ _]))}}}) (css/upsert-css "network" NetworkRoot)
76891
(ns fulcro.inspect.ui.network-cards (:require [devcards.core :refer-macros [defcard]] [fulcro-css.css :as css] [fulcro.client.cards :refer-macros [defcard-fulcro]] [fulcro.inspect.ui.network :as network] [fulcro.client.primitives :as fp] [fulcro.client.network :as f.network] [fulcro.client.data-fetch :as fetch] [fulcro.client.mutations :as mutations] [clojure.test.check.generators :as gen] [fulcro.client.dom :as dom] [cljs.spec.alpha :as s] [cljs.core.async :as async :refer [go <!]] [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.core :as p] [com.wsscode.pathom.profile :as pp] [com.wsscode.pathom.fulcro.network :as pfn])) (def request-samples [{:in [:hello :world] :out {:hello "data" :world "value"}} `{:in [(do-something {:foo "bar"})] :out {do-something {}}} {:in [{:ui/root [{:ui/inspector [:fulcro.inspect.core/inspectors {:fulcro.inspect.core/current-app [:fulcro.inspect.ui.inspector/tab :fulcro.inspect.ui.inspector/id {:fulcro.inspect.ui.inspector/app-state [:fulcro.inspect.ui.data-watcher/id {:fulcro.inspect.ui.data-watcher/root-data [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:fulcro.inspect.ui.data-watcher/watches [:ui/expanded? :fulcro.inspect.ui.data-watcher/watch-id :fulcro.inspect.ui.data-watcher/watch-path {:fulcro.inspect.ui.data-watcher/data-viewer [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]}]}]} {:fulcro.inspect.ui.inspector/network [:fulcro.inspect.ui.network/history-id {:fulcro.inspect.ui.network/requests [:fulcro.inspect.ui.network/request-id :fulcro.inspect.ui.network/request-edn :fulcro.inspect.ui.network/request-edn-row-view :fulcro.inspect.ui.network/response-edn :fulcro.inspect.ui.network/request-started-at :fulcro.inspect.ui.network/request-finished-at :fulcro.inspect.ui.network/error]} {:fulcro.inspect.ui.network/active-request [:fulcro.inspect.ui.network/request-id :fulcro.inspect.ui.network/request-edn :fulcro.inspect.ui.network/response-edn :fulcro.inspect.ui.network/request-started-at :fulcro.inspect.ui.network/request-finished-at :fulcro.inspect.ui.network/error {:ui/request-edn-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/response-edn-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/error-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]}]}]} {:fulcro.inspect.ui.inspector/transactions [:fulcro.inspect.ui.transactions/tx-list-id :fulcro.inspect.ui.transactions/tx-filter {:fulcro.inspect.ui.transactions/active-tx [:fulcro.inspect.ui.transactions/tx-id :fulcro.inspect.ui.transactions/timestamp :tx :ret :sends :old-state :new-state :ref :component {:ui/tx-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/ret-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/tx-row-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/sends-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/old-state-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/new-state-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/diff-add-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/diff-rem-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]}]} {:fulcro.inspect.ui.transactions/tx-list [:fulcro.inspect.ui.transactions/tx-id :fulcro.inspect.ui.transactions/timestamp :ref :tx {:ui/tx-row-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]}]}]}]}]} :ui/size :ui/visible?]} :ui/react-key] :out {}}]) (defn gen-remote [] (gen/generate (gen/frequency [[6 (gen/return :remote)] [1 (gen/return :other)]]))) (defn success? [] (gen/generate (gen/frequency [[8 (gen/return true)] [1 (gen/return false)]]))) (defn gen-request [this] (let [id (random-uuid) reconciler (fp/get-reconciler this) remote (gen-remote) {:keys [in out]} (rand-nth request-samples)] (fp/transact! reconciler [::network/history-id "main"] [`(network/request-start ~{::network/remote remote ::network/request-id id ::network/request-edn in})]) (js/setTimeout (fn [] (let [suc? (success?)] (fp/transact! reconciler [::network/history-id "main"] [`(network/request-finish ~(cond-> {::network/remote remote ::network/request-id id} suc? (assoc ::network/response-edn out) (not suc?) (assoc ::network/error {:error "bad"})))]))) (gen/generate (gen/large-integer* {:min 30 :max 7000}))))) (fp/defui ^:once NetworkRoot static fp/InitialAppState (initial-state [_ _] {:ui/react-key (random-uuid) :ui/root (assoc (fp/get-initial-state network/NetworkHistory {}) ::network/history-id "main")}) static fp/IQuery (query [_] [{:ui/root (fp/get-query network/NetworkHistory)} :ui/react-key]) static css/CSS (local-rules [_] [[:.container {:height "500px" :display "flex" :flex-direction "column"}]]) (include-children [_] [network/NetworkHistory]) Object (render [this] (let [{:keys [ui/react-key ui/root]} (fp/props this) css (css/get-classnames NetworkRoot)] (dom/div #js {:key react-key :className (:container css)} (dom/button #js {:onClick #(gen-request this)} "Generate request") (network/network-history root))))) (defcard-fulcro network NetworkRoot {}) (s/def ::name #{"<NAME>" "<NAME>" "<NAME>" "<NAME>"}) (mutations/defmutation send-something [_] (action [_] (js/console.log "send something")) (remote [_] true)) (fp/defsc NameLoader [this {::keys [name]} computed] {:initial-state {::id "name-loader"} :ident [::id ::id] :query [::id ::name]} (let [css (css/get-classnames NameLoader)] (dom/div nil (dom/button #js {:onClick #(fetch/load-field this ::name)} "Load name") (if name (str "The name is: " name)) (dom/div nil (dom/button #js {:onClick #(fp/transact! this [`(send-something {})])} "Send"))))) (def name-loader (fp/factory NameLoader)) (fp/defui ^:once NameLoaderRoot static fp/InitialAppState (initial-state [_ _] {:ui/react-key (random-uuid) :ui/root (fp/get-initial-state NameLoader {}) :fulcro.inspect.core/app-id "NameLoader"}) static fp/IQuery (query [_] [{:ui/root (fp/get-query NameLoader)} :ui/react-key]) static css/CSS (local-rules [_] []) (include-children [_] [NameLoader]) Object (render [this] (let [{:keys [ui/react-key ui/root]} (fp/props this)] (dom/div #js {:key react-key} (name-loader root))))) (def indexes (atom {})) (defmulti resolver-fn pc/resolver-dispatch) (def defresolver (pc/resolver-factory resolver-fn indexes)) (defmulti mutation-fn pc/mutation-dispatch) (def defmutation (pc/mutation-factory mutation-fn indexes)) (defresolver 'name {::pc/output [::name]} (fn [_ _] (go (<! (async/timeout 300)) {::name (gen/generate (s/gen ::name))}))) (defresolver 'id-name {::pc/input #{::id} ::pc/output [::name]} (fn [_ _] (go (<! (async/timeout 300)) {::name (gen/generate (s/gen ::name))}))) (def parser (p/async-parser {::p/env {::p/reader [p/map-reader pc/all-async-readers] ::pc/resolver-dispatch resolver-fn ::pc/mutate-dispatch mutation-fn ::pc/indexes @indexes} ::p/mutate pc/mutate-async ::p/plugins [p/request-cache-plugin pp/profile-plugin]})) (defcard-fulcro network-sampler NameLoaderRoot {} {:fulcro {:networking (pfn/local-network parser)}}) (defcard-fulcro network-sampler-remote-i NameLoaderRoot {} {:fulcro {:networking (reify f.network/FulcroRemoteI (transmit [this {::f.network/keys [edn ok-handler]}] (ok-handler {:transaction edn :body {[::id "name-loader"] {::name (gen/generate (s/gen ::name))}}})) (abort [_ _]))}}) (defcard-fulcro multi-network NameLoaderRoot {} {:fulcro {:networking {:remote (pfn/local-network parser) :other (reify f.network/FulcroRemoteI (transmit [this {::f.network/keys [edn ok-handler]}] (ok-handler {:transaction edn :body {[::id "name-loader"] {::name (gen/generate (s/gen ::name))}}})) (abort [_ _]))}}}) (css/upsert-css "network" NetworkRoot)
true
(ns fulcro.inspect.ui.network-cards (:require [devcards.core :refer-macros [defcard]] [fulcro-css.css :as css] [fulcro.client.cards :refer-macros [defcard-fulcro]] [fulcro.inspect.ui.network :as network] [fulcro.client.primitives :as fp] [fulcro.client.network :as f.network] [fulcro.client.data-fetch :as fetch] [fulcro.client.mutations :as mutations] [clojure.test.check.generators :as gen] [fulcro.client.dom :as dom] [cljs.spec.alpha :as s] [cljs.core.async :as async :refer [go <!]] [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.core :as p] [com.wsscode.pathom.profile :as pp] [com.wsscode.pathom.fulcro.network :as pfn])) (def request-samples [{:in [:hello :world] :out {:hello "data" :world "value"}} `{:in [(do-something {:foo "bar"})] :out {do-something {}}} {:in [{:ui/root [{:ui/inspector [:fulcro.inspect.core/inspectors {:fulcro.inspect.core/current-app [:fulcro.inspect.ui.inspector/tab :fulcro.inspect.ui.inspector/id {:fulcro.inspect.ui.inspector/app-state [:fulcro.inspect.ui.data-watcher/id {:fulcro.inspect.ui.data-watcher/root-data [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:fulcro.inspect.ui.data-watcher/watches [:ui/expanded? :fulcro.inspect.ui.data-watcher/watch-id :fulcro.inspect.ui.data-watcher/watch-path {:fulcro.inspect.ui.data-watcher/data-viewer [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]}]}]} {:fulcro.inspect.ui.inspector/network [:fulcro.inspect.ui.network/history-id {:fulcro.inspect.ui.network/requests [:fulcro.inspect.ui.network/request-id :fulcro.inspect.ui.network/request-edn :fulcro.inspect.ui.network/request-edn-row-view :fulcro.inspect.ui.network/response-edn :fulcro.inspect.ui.network/request-started-at :fulcro.inspect.ui.network/request-finished-at :fulcro.inspect.ui.network/error]} {:fulcro.inspect.ui.network/active-request [:fulcro.inspect.ui.network/request-id :fulcro.inspect.ui.network/request-edn :fulcro.inspect.ui.network/response-edn :fulcro.inspect.ui.network/request-started-at :fulcro.inspect.ui.network/request-finished-at :fulcro.inspect.ui.network/error {:ui/request-edn-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/response-edn-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/error-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]}]}]} {:fulcro.inspect.ui.inspector/transactions [:fulcro.inspect.ui.transactions/tx-list-id :fulcro.inspect.ui.transactions/tx-filter {:fulcro.inspect.ui.transactions/active-tx [:fulcro.inspect.ui.transactions/tx-id :fulcro.inspect.ui.transactions/timestamp :tx :ret :sends :old-state :new-state :ref :component {:ui/tx-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/ret-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/tx-row-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/sends-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/old-state-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/new-state-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/diff-add-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]} {:ui/diff-rem-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]}]} {:fulcro.inspect.ui.transactions/tx-list [:fulcro.inspect.ui.transactions/tx-id :fulcro.inspect.ui.transactions/timestamp :ref :tx {:ui/tx-row-view [:fulcro.inspect.ui.data-viewer/id :fulcro.inspect.ui.data-viewer/content :fulcro.inspect.ui.data-viewer/expanded]}]}]}]}]} :ui/size :ui/visible?]} :ui/react-key] :out {}}]) (defn gen-remote [] (gen/generate (gen/frequency [[6 (gen/return :remote)] [1 (gen/return :other)]]))) (defn success? [] (gen/generate (gen/frequency [[8 (gen/return true)] [1 (gen/return false)]]))) (defn gen-request [this] (let [id (random-uuid) reconciler (fp/get-reconciler this) remote (gen-remote) {:keys [in out]} (rand-nth request-samples)] (fp/transact! reconciler [::network/history-id "main"] [`(network/request-start ~{::network/remote remote ::network/request-id id ::network/request-edn in})]) (js/setTimeout (fn [] (let [suc? (success?)] (fp/transact! reconciler [::network/history-id "main"] [`(network/request-finish ~(cond-> {::network/remote remote ::network/request-id id} suc? (assoc ::network/response-edn out) (not suc?) (assoc ::network/error {:error "bad"})))]))) (gen/generate (gen/large-integer* {:min 30 :max 7000}))))) (fp/defui ^:once NetworkRoot static fp/InitialAppState (initial-state [_ _] {:ui/react-key (random-uuid) :ui/root (assoc (fp/get-initial-state network/NetworkHistory {}) ::network/history-id "main")}) static fp/IQuery (query [_] [{:ui/root (fp/get-query network/NetworkHistory)} :ui/react-key]) static css/CSS (local-rules [_] [[:.container {:height "500px" :display "flex" :flex-direction "column"}]]) (include-children [_] [network/NetworkHistory]) Object (render [this] (let [{:keys [ui/react-key ui/root]} (fp/props this) css (css/get-classnames NetworkRoot)] (dom/div #js {:key react-key :className (:container css)} (dom/button #js {:onClick #(gen-request this)} "Generate request") (network/network-history root))))) (defcard-fulcro network NetworkRoot {}) (s/def ::name #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"}) (mutations/defmutation send-something [_] (action [_] (js/console.log "send something")) (remote [_] true)) (fp/defsc NameLoader [this {::keys [name]} computed] {:initial-state {::id "name-loader"} :ident [::id ::id] :query [::id ::name]} (let [css (css/get-classnames NameLoader)] (dom/div nil (dom/button #js {:onClick #(fetch/load-field this ::name)} "Load name") (if name (str "The name is: " name)) (dom/div nil (dom/button #js {:onClick #(fp/transact! this [`(send-something {})])} "Send"))))) (def name-loader (fp/factory NameLoader)) (fp/defui ^:once NameLoaderRoot static fp/InitialAppState (initial-state [_ _] {:ui/react-key (random-uuid) :ui/root (fp/get-initial-state NameLoader {}) :fulcro.inspect.core/app-id "NameLoader"}) static fp/IQuery (query [_] [{:ui/root (fp/get-query NameLoader)} :ui/react-key]) static css/CSS (local-rules [_] []) (include-children [_] [NameLoader]) Object (render [this] (let [{:keys [ui/react-key ui/root]} (fp/props this)] (dom/div #js {:key react-key} (name-loader root))))) (def indexes (atom {})) (defmulti resolver-fn pc/resolver-dispatch) (def defresolver (pc/resolver-factory resolver-fn indexes)) (defmulti mutation-fn pc/mutation-dispatch) (def defmutation (pc/mutation-factory mutation-fn indexes)) (defresolver 'name {::pc/output [::name]} (fn [_ _] (go (<! (async/timeout 300)) {::name (gen/generate (s/gen ::name))}))) (defresolver 'id-name {::pc/input #{::id} ::pc/output [::name]} (fn [_ _] (go (<! (async/timeout 300)) {::name (gen/generate (s/gen ::name))}))) (def parser (p/async-parser {::p/env {::p/reader [p/map-reader pc/all-async-readers] ::pc/resolver-dispatch resolver-fn ::pc/mutate-dispatch mutation-fn ::pc/indexes @indexes} ::p/mutate pc/mutate-async ::p/plugins [p/request-cache-plugin pp/profile-plugin]})) (defcard-fulcro network-sampler NameLoaderRoot {} {:fulcro {:networking (pfn/local-network parser)}}) (defcard-fulcro network-sampler-remote-i NameLoaderRoot {} {:fulcro {:networking (reify f.network/FulcroRemoteI (transmit [this {::f.network/keys [edn ok-handler]}] (ok-handler {:transaction edn :body {[::id "name-loader"] {::name (gen/generate (s/gen ::name))}}})) (abort [_ _]))}}) (defcard-fulcro multi-network NameLoaderRoot {} {:fulcro {:networking {:remote (pfn/local-network parser) :other (reify f.network/FulcroRemoteI (transmit [this {::f.network/keys [edn ok-handler]}] (ok-handler {:transaction edn :body {[::id "name-loader"] {::name (gen/generate (s/gen ::name))}}})) (abort [_ _]))}}}) (css/upsert-css "network" NetworkRoot)
[ { "context": "--------------------\n;; File cps.clj\n;; Written by Chris Frisz\n;; \n;; Created 10 Apr 2012\n;; Last modified 5 Oc", "end": 114, "score": 0.9998207092285156, "start": 103, "tag": "NAME", "value": "Chris Frisz" } ]
test/ctco/test/cps.clj
cjfrisz/clojure-tco
64
;;---------------------------------------------------------------------- ;; File cps.clj ;; Written by Chris Frisz ;; ;; Created 10 Apr 2012 ;; Last modified 5 Oct 2012 ;; ;; Testing for the CPSer in the record+protocol'd version of the TCO ;; compiler. ;;---------------------------------------------------------------------- (ns ctco.test.cps (:use [clojure.test] [clojure.pprint]) (:require [ctco.expr app simple cont def fn if simple-op] [ctco.protocol :as proto] [ctco.util :as util]) (:import [ctco.expr.app App] [ctco.expr.simple Simple] [ctco.expr.cont Cont AppCont] [ctco.expr.def DefCps DefSrs DefTriv] [ctco.expr.fn Fn FnBody] [ctco.expr.if IfCps IfSrs IfTriv] [ctco.expr.simple_op SimpleOpCps SimpleOpSrs SimpleOpTriv])) (let [test-bool (Simple. true)] (deftest simple-bool (is (extends? proto/PCpsTriv (type test-bool))) (is (not (extends? proto/PCpsSrs (type test-bool)))) (is (= (proto/cps-triv test-bool) test-bool)))) (let [test-num (Simple. 5)] (deftest simple-num (is (extends? proto/PCpsTriv (type test-num))) (is (not (extends? proto/PCpsSrs (type test-num)))) (is (= (proto/cps-triv test-num) test-num)))) (let [test-sym (Simple. '(quote s))] (deftest simple-sym (is (extends? proto/PCpsTriv (type test-sym))) (is (not (extends? proto/PCpsSrs (type test-sym)))) (is (= (proto/cps-triv test-sym) test-sym)))) (let [test-var (Simple. 'x)] (deftest simple-var (is (extends? proto/PCpsTriv (type test-var))) (is (not (extends? proto/PCpsSrs (type test-var)))) (is (= (proto/cps-triv test-var) test-var)))) (let [test-fn-triv (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])])] (deftest fn-triv (is (extends? proto/PCpsTriv (type test-fn-triv))) (is (not (extends? proto/PCpsSrs (type test-fn-triv)))) (is (= (count (:fml* (first (:body* test-fn-triv)))) 1)) (let [test-fn-cps (proto/cps-triv test-fn-triv)] (is (not (= test-fn-triv test-fn-cps))) (is (= (count (:fml* (fnext (:body* test-fn-cps)))) 2)) (is (instance? AppCont (first (:bexpr* (fnext (:body* test-fn-cps))))))))) (let [test-if-triv (IfTriv. (Simple. 3) (Simple. 4) (Simple. 5))] (deftest if-triv (is (extends? proto/PCpsTriv (type test-if-triv))) (is (not (extends? proto/PCpsSrs (type test-if-triv)))) (let [test-if-cps (proto/cps-triv test-if-triv)] (is (= (:test test-if-triv) (:test test-if-cps))) (is (= (:conseq test-if-triv) (:conseq test-if-cps))) (is (= (:alt test-if-triv) (:alt test-if-cps))) (is (instance? IfCps test-if-cps))))) ;; Since changing the internal representation of defn, this is kind of a pun ;; now. (let [test-defn (DefTriv. (Simple. 'id) (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]))] (deftest defn-triv (is (extends? proto/PCpsTriv (type test-defn))) (is (not (extends? proto/PCpsSrs (type test-defn)))) (let [test-defn-cps (proto/cps-triv test-defn)] (is (instance? AppCont (first (:bexpr* (fnext (:body* (:init test-defn-cps)))))))))) (let [test-op (SimpleOpTriv. '+ [(Simple. 3) (Simple. 4) (Simple. 5)])] (deftest simple-op-triv (is (extends? proto/PCpsTriv (type test-op))) (is (not (extends? proto/PCpsSrs (type test-op)))) (let [test-op-cps (proto/cps-triv test-op)] (for [opnd (:opnd* test-op) opnd-cps (:opnd* test-op-cps)] (is (= opnd opnd-cps)))))) (let [test-app (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]) [(Simple. 5)])] (deftest app (is (extends? proto/PCpsSrs (type test-app))) (let [k (util/new-var 'k) app-cps (proto/cps-srs test-app k)] (is (instance? App app-cps))))) (let [test-if-srs (IfSrs. (SimpleOpTriv. 'zero? [(Simple. 'x)]) (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]) [(Simple. 5)]) (Simple. 12))] (deftest if-srs (is (extends? proto/PCpsSrs (type test-if-srs))) (is (extends? proto/PCpsTriv (type (:test test-if-srs)))) (is (extends? proto/PCpsSrs (type (:conseq test-if-srs)))) (is (extends? proto/PCpsTriv (type (:alt test-if-srs)))))) (let [test-if-srs (IfSrs. (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(SimpleOpTriv. 'zero? [(Simple. 'x)])])]) [(Simple. 35)]) (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]) [(Simple. 5)]) (Simple. 12))] (deftest if-srs2 (is (extends? proto/PCpsSrs (type test-if-srs))) (is (extends? proto/PCpsSrs (type (:test test-if-srs)))) (is (extends? proto/PCpsSrs (type (:conseq test-if-srs)))) (is (extends? proto/PCpsTriv (type (:alt test-if-srs)))))) (let [test-op-srs (SimpleOpSrs. '+ [(Simple. 3) (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]) [(Simple. 5)]) (Simple. 5)])] (deftest simple-op-srs (is (extends? proto/PCpsSrs (type test-op-srs))) (is (extends? proto/PCpsTriv (type (nth (:opnd* test-op-srs) 0)))) (is (extends? proto/PCpsSrs (type (nth (:opnd* test-op-srs) 1)))) (is (extends? proto/PCpsTriv (type (nth (:opnd* test-op-srs) 2))))))
23834
;;---------------------------------------------------------------------- ;; File cps.clj ;; Written by <NAME> ;; ;; Created 10 Apr 2012 ;; Last modified 5 Oct 2012 ;; ;; Testing for the CPSer in the record+protocol'd version of the TCO ;; compiler. ;;---------------------------------------------------------------------- (ns ctco.test.cps (:use [clojure.test] [clojure.pprint]) (:require [ctco.expr app simple cont def fn if simple-op] [ctco.protocol :as proto] [ctco.util :as util]) (:import [ctco.expr.app App] [ctco.expr.simple Simple] [ctco.expr.cont Cont AppCont] [ctco.expr.def DefCps DefSrs DefTriv] [ctco.expr.fn Fn FnBody] [ctco.expr.if IfCps IfSrs IfTriv] [ctco.expr.simple_op SimpleOpCps SimpleOpSrs SimpleOpTriv])) (let [test-bool (Simple. true)] (deftest simple-bool (is (extends? proto/PCpsTriv (type test-bool))) (is (not (extends? proto/PCpsSrs (type test-bool)))) (is (= (proto/cps-triv test-bool) test-bool)))) (let [test-num (Simple. 5)] (deftest simple-num (is (extends? proto/PCpsTriv (type test-num))) (is (not (extends? proto/PCpsSrs (type test-num)))) (is (= (proto/cps-triv test-num) test-num)))) (let [test-sym (Simple. '(quote s))] (deftest simple-sym (is (extends? proto/PCpsTriv (type test-sym))) (is (not (extends? proto/PCpsSrs (type test-sym)))) (is (= (proto/cps-triv test-sym) test-sym)))) (let [test-var (Simple. 'x)] (deftest simple-var (is (extends? proto/PCpsTriv (type test-var))) (is (not (extends? proto/PCpsSrs (type test-var)))) (is (= (proto/cps-triv test-var) test-var)))) (let [test-fn-triv (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])])] (deftest fn-triv (is (extends? proto/PCpsTriv (type test-fn-triv))) (is (not (extends? proto/PCpsSrs (type test-fn-triv)))) (is (= (count (:fml* (first (:body* test-fn-triv)))) 1)) (let [test-fn-cps (proto/cps-triv test-fn-triv)] (is (not (= test-fn-triv test-fn-cps))) (is (= (count (:fml* (fnext (:body* test-fn-cps)))) 2)) (is (instance? AppCont (first (:bexpr* (fnext (:body* test-fn-cps))))))))) (let [test-if-triv (IfTriv. (Simple. 3) (Simple. 4) (Simple. 5))] (deftest if-triv (is (extends? proto/PCpsTriv (type test-if-triv))) (is (not (extends? proto/PCpsSrs (type test-if-triv)))) (let [test-if-cps (proto/cps-triv test-if-triv)] (is (= (:test test-if-triv) (:test test-if-cps))) (is (= (:conseq test-if-triv) (:conseq test-if-cps))) (is (= (:alt test-if-triv) (:alt test-if-cps))) (is (instance? IfCps test-if-cps))))) ;; Since changing the internal representation of defn, this is kind of a pun ;; now. (let [test-defn (DefTriv. (Simple. 'id) (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]))] (deftest defn-triv (is (extends? proto/PCpsTriv (type test-defn))) (is (not (extends? proto/PCpsSrs (type test-defn)))) (let [test-defn-cps (proto/cps-triv test-defn)] (is (instance? AppCont (first (:bexpr* (fnext (:body* (:init test-defn-cps)))))))))) (let [test-op (SimpleOpTriv. '+ [(Simple. 3) (Simple. 4) (Simple. 5)])] (deftest simple-op-triv (is (extends? proto/PCpsTriv (type test-op))) (is (not (extends? proto/PCpsSrs (type test-op)))) (let [test-op-cps (proto/cps-triv test-op)] (for [opnd (:opnd* test-op) opnd-cps (:opnd* test-op-cps)] (is (= opnd opnd-cps)))))) (let [test-app (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]) [(Simple. 5)])] (deftest app (is (extends? proto/PCpsSrs (type test-app))) (let [k (util/new-var 'k) app-cps (proto/cps-srs test-app k)] (is (instance? App app-cps))))) (let [test-if-srs (IfSrs. (SimpleOpTriv. 'zero? [(Simple. 'x)]) (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]) [(Simple. 5)]) (Simple. 12))] (deftest if-srs (is (extends? proto/PCpsSrs (type test-if-srs))) (is (extends? proto/PCpsTriv (type (:test test-if-srs)))) (is (extends? proto/PCpsSrs (type (:conseq test-if-srs)))) (is (extends? proto/PCpsTriv (type (:alt test-if-srs)))))) (let [test-if-srs (IfSrs. (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(SimpleOpTriv. 'zero? [(Simple. 'x)])])]) [(Simple. 35)]) (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]) [(Simple. 5)]) (Simple. 12))] (deftest if-srs2 (is (extends? proto/PCpsSrs (type test-if-srs))) (is (extends? proto/PCpsSrs (type (:test test-if-srs)))) (is (extends? proto/PCpsSrs (type (:conseq test-if-srs)))) (is (extends? proto/PCpsTriv (type (:alt test-if-srs)))))) (let [test-op-srs (SimpleOpSrs. '+ [(Simple. 3) (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]) [(Simple. 5)]) (Simple. 5)])] (deftest simple-op-srs (is (extends? proto/PCpsSrs (type test-op-srs))) (is (extends? proto/PCpsTriv (type (nth (:opnd* test-op-srs) 0)))) (is (extends? proto/PCpsSrs (type (nth (:opnd* test-op-srs) 1)))) (is (extends? proto/PCpsTriv (type (nth (:opnd* test-op-srs) 2))))))
true
;;---------------------------------------------------------------------- ;; File cps.clj ;; Written by PI:NAME:<NAME>END_PI ;; ;; Created 10 Apr 2012 ;; Last modified 5 Oct 2012 ;; ;; Testing for the CPSer in the record+protocol'd version of the TCO ;; compiler. ;;---------------------------------------------------------------------- (ns ctco.test.cps (:use [clojure.test] [clojure.pprint]) (:require [ctco.expr app simple cont def fn if simple-op] [ctco.protocol :as proto] [ctco.util :as util]) (:import [ctco.expr.app App] [ctco.expr.simple Simple] [ctco.expr.cont Cont AppCont] [ctco.expr.def DefCps DefSrs DefTriv] [ctco.expr.fn Fn FnBody] [ctco.expr.if IfCps IfSrs IfTriv] [ctco.expr.simple_op SimpleOpCps SimpleOpSrs SimpleOpTriv])) (let [test-bool (Simple. true)] (deftest simple-bool (is (extends? proto/PCpsTriv (type test-bool))) (is (not (extends? proto/PCpsSrs (type test-bool)))) (is (= (proto/cps-triv test-bool) test-bool)))) (let [test-num (Simple. 5)] (deftest simple-num (is (extends? proto/PCpsTriv (type test-num))) (is (not (extends? proto/PCpsSrs (type test-num)))) (is (= (proto/cps-triv test-num) test-num)))) (let [test-sym (Simple. '(quote s))] (deftest simple-sym (is (extends? proto/PCpsTriv (type test-sym))) (is (not (extends? proto/PCpsSrs (type test-sym)))) (is (= (proto/cps-triv test-sym) test-sym)))) (let [test-var (Simple. 'x)] (deftest simple-var (is (extends? proto/PCpsTriv (type test-var))) (is (not (extends? proto/PCpsSrs (type test-var)))) (is (= (proto/cps-triv test-var) test-var)))) (let [test-fn-triv (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])])] (deftest fn-triv (is (extends? proto/PCpsTriv (type test-fn-triv))) (is (not (extends? proto/PCpsSrs (type test-fn-triv)))) (is (= (count (:fml* (first (:body* test-fn-triv)))) 1)) (let [test-fn-cps (proto/cps-triv test-fn-triv)] (is (not (= test-fn-triv test-fn-cps))) (is (= (count (:fml* (fnext (:body* test-fn-cps)))) 2)) (is (instance? AppCont (first (:bexpr* (fnext (:body* test-fn-cps))))))))) (let [test-if-triv (IfTriv. (Simple. 3) (Simple. 4) (Simple. 5))] (deftest if-triv (is (extends? proto/PCpsTriv (type test-if-triv))) (is (not (extends? proto/PCpsSrs (type test-if-triv)))) (let [test-if-cps (proto/cps-triv test-if-triv)] (is (= (:test test-if-triv) (:test test-if-cps))) (is (= (:conseq test-if-triv) (:conseq test-if-cps))) (is (= (:alt test-if-triv) (:alt test-if-cps))) (is (instance? IfCps test-if-cps))))) ;; Since changing the internal representation of defn, this is kind of a pun ;; now. (let [test-defn (DefTriv. (Simple. 'id) (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]))] (deftest defn-triv (is (extends? proto/PCpsTriv (type test-defn))) (is (not (extends? proto/PCpsSrs (type test-defn)))) (let [test-defn-cps (proto/cps-triv test-defn)] (is (instance? AppCont (first (:bexpr* (fnext (:body* (:init test-defn-cps)))))))))) (let [test-op (SimpleOpTriv. '+ [(Simple. 3) (Simple. 4) (Simple. 5)])] (deftest simple-op-triv (is (extends? proto/PCpsTriv (type test-op))) (is (not (extends? proto/PCpsSrs (type test-op)))) (let [test-op-cps (proto/cps-triv test-op)] (for [opnd (:opnd* test-op) opnd-cps (:opnd* test-op-cps)] (is (= opnd opnd-cps)))))) (let [test-app (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]) [(Simple. 5)])] (deftest app (is (extends? proto/PCpsSrs (type test-app))) (let [k (util/new-var 'k) app-cps (proto/cps-srs test-app k)] (is (instance? App app-cps))))) (let [test-if-srs (IfSrs. (SimpleOpTriv. 'zero? [(Simple. 'x)]) (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]) [(Simple. 5)]) (Simple. 12))] (deftest if-srs (is (extends? proto/PCpsSrs (type test-if-srs))) (is (extends? proto/PCpsTriv (type (:test test-if-srs)))) (is (extends? proto/PCpsSrs (type (:conseq test-if-srs)))) (is (extends? proto/PCpsTriv (type (:alt test-if-srs)))))) (let [test-if-srs (IfSrs. (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(SimpleOpTriv. 'zero? [(Simple. 'x)])])]) [(Simple. 35)]) (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]) [(Simple. 5)]) (Simple. 12))] (deftest if-srs2 (is (extends? proto/PCpsSrs (type test-if-srs))) (is (extends? proto/PCpsSrs (type (:test test-if-srs)))) (is (extends? proto/PCpsSrs (type (:conseq test-if-srs)))) (is (extends? proto/PCpsTriv (type (:alt test-if-srs)))))) (let [test-op-srs (SimpleOpSrs. '+ [(Simple. 3) (App. (Fn. nil [(FnBody. [(Simple. 'x)] nil [(Simple. 'x)])]) [(Simple. 5)]) (Simple. 5)])] (deftest simple-op-srs (is (extends? proto/PCpsSrs (type test-op-srs))) (is (extends? proto/PCpsTriv (type (nth (:opnd* test-op-srs) 0)))) (is (extends? proto/PCpsSrs (type (nth (:opnd* test-op-srs) 1)))) (is (extends? proto/PCpsTriv (type (nth (:opnd* test-op-srs) 2))))))
[ { "context": " ;;\n;; Author: Jon Anthony ", "end": 2076, "score": 0.9998542070388794, "start": 2065, "tag": "NAME", "value": "Jon Anthony" } ]
src/edu/bc/log4clj.clj
jsa-aerial/gaisr
1
;;--------------------------------------------------------------------------;; ;; ;; ;; L O G 4 C L J ;; ;; ;; ;; ;; ;; Copyright (c) 2011-2012 Trustees of Boston College ;; ;; ;; ;; Permission is hereby granted, free of charge, to any person obtaining ;; ;; a copy of this software and associated documentation files (the ;; ;; "Software"), to deal in the Software without restriction, including ;; ;; without limitation the rights to use, copy, modify, merge, publish, ;; ;; distribute, sublicense, and/or sell copies of the Software, and to ;; ;; permit persons to whom the Software is furnished to do so, subject to ;; ;; the following conditions: ;; ;; ;; ;; The above copyright notice and this permission notice shall be ;; ;; included in all copies or substantial portions of the Software. ;; ;; ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE ;; ;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION ;; ;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION ;; ;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ;; ;; ;; ;; Author: Jon Anthony ;; ;; ;; ;;--------------------------------------------------------------------------;; ;; (ns edu.bc.log4clj "Attempt to make some sort of reasonable abstraction over log4j. Or maybe we will give up and just reimplement log4cl in clj. Java logging a gigantic awful mess of over complexity to attain what is actually pretty simple and straightforward. Log4cl does everything log4j does, while also being more extensible and dynamic, yet is about 1/10 the complexity. Clojure, being JVM based, seems like it would be reasonable to just use log4j, but the underlying lib complexity is nuts." (:require [clojure.contrib.string :as str] [clojure.set :as set] [clojure.contrib.properties :as prop] [edu.bc.fs :as fs]) (:use clojure.contrib.math edu.bc.utils [clojure.pprint :only [cl-format]]) (:import (java.util Properties Vector) ;; Useless... (org.apache.commons.logging Log) (org.apache.log4j PropertyConfigurator LogManager Logger))) ;;; Logging levels for log4j and with c.c.logging. As with ;;; c.c.logging these are case as keywords as that is saner ;;; ;;; lowest ... highest ;;; ;;; :ALL :TRACE :DEBUG :INFO :WARN :ERROR :FATAL :OFF (defparameter *levels* {:all org.apache.log4j.Level/ALL :trace org.apache.log4j.Level/TRACE :debug org.apache.log4j.Level/DEBUG :info org.apache.log4j.Level/INFO :warn org.apache.log4j.Level/WARN :error org.apache.log4j.Level/ERROR :fatal org.apache.log4j.Level/FATAL :off org.apache.log4j.Level/OFF}) (defparameter *appenders* {:console "org.apache.log4j.ConsoleAppender" :file "org.apache.log4j.FileAppender" :rolling "org.apache.log4j.RollingFileAppender"}) (defparameter *options* {:level "Level" ; Don't need now, but will when reimpl :name "Name" ; " :layout "layout.ConversionPattern" :pat "org.apache.log4j.PatternLayout" :filespec "File" :buf-size "BufferSize" :buf-io "BufferedIO" :append "Append" :max-size "MaxFileSize" :max-version "MaxBackupIndex"}) (defn config-logging "Initial startup logging configuration. Uses property file PROP-DESIGNATOR, or if not given, defaults to log4j.properties. ***NOTE: more or less obsolete now we have configure-logging." ([] (config-logging "log4j.properties")) ([prop-designator] (if (string? prop-designator) (PropertyConfigurator/configure (fs/fullpath prop-designator)) (PropertyConfigurator/configure prop-designator)))) ;;; Not really useful. The Commons logging wrapper sucks anyway and ;;; since this is log4clj, it is already more or less wedded to either ;;; 1. log4j or 2. its own direct implementation of more or less what ;;; log4j is/does. Currently it is 1. Either way, the commons access ;;; api is confusing and a useless/worthless layer. ;;; (defn get-log ;;; ([] ;;; (get-log (str *ns*))) ;;; ([name] ;;; (LogFactory/getLog name))) (defn get-logger "Return the logger named NAME (a string or a logger) or if NAME is not given, use the name of the current name space. If NAME is a logger, just return it." ([] (get-logger (str *ns*))) ([name] (if (string? name) (if (= name "root") (LogManager/getRootLogger) (LogManager/getLogger name)) name))) (defn get-root-logger [] (get-logger "root")) (defn get-all-loggers "Return a vector of all the current loggers" [] (loop [jloggers (LogManager/getCurrentLoggers) loggers [(LogManager/getRootLogger)]] (if (not (. jloggers hasMoreElements)) loggers (recur jloggers (conj loggers (. jloggers nextElement)))))) (defn all-loggers-map "Return a map of all current loggers indexed by their name" [] (reduce (fn [m l] (assoc m (. l getName) l)) {} (get-all-loggers))) (defn logger-appenders "Return all the appenders for logger LOGGER, a string naming the logger or a logger" [logger] (let [logger (get-logger logger)] (loop [jappenders (. logger getAllAppenders) appenders []] (if (not (. jappenders hasMoreElements)) appenders (recur jappenders (conj appenders (. jappenders nextElement))))))) (defn all-appenders "Return all the current appenders. This set is the union of all the appenders of all the current loggers" [] (apply set/union (map logger-appenders (get-all-loggers)))) (defn close-appender "Close the appender A (an appender as obtained from logger-appenders or all-appenders). Once, closed, this appender instance is no longer useable, however it is always possible to reconfigure logging with corresponding new appenders - with same names and on same loggers" [a] (doto a .close)) (defn close-all-appenders "For all A in (all-appenders), (close-appender A)" [] (doseq [a (all-appenders)] (close-appender a))) ;;; (logger-decl "refseq-ftp" {:level :info :appenders "netutils"}) ;;; (logger-decl ;;; "rootLogger" ;;; {:level :info :appenders "console"}) ;;; (defn logger-decl [name attrs] (let [lname (if (not= name "rootLogger") (str "log4j.logger." name) (str "log4j." name)) level (. (*levels* (get attrs :level :info)) toString) additivity (str "log4j.additivity." name) appenders (get attrs :appenders "console") appenders (if (coll? appenders) (str/join ", " appenders) appenders)] [lname (str/join ", " [level appenders]) (list [additivity "false"])])) (defn file-attrs [type attrs] (if (= type :console) [] (let [buf-io (get attrs :buf-io "true") buf-size (get attrs :buf-size "1024") filespec (get attrs :filespec (str "./" (ns-name *ns*) ".log")) append (get attrs :append "true")] (map (fn [k v] [(str "." (get *options* k)) v]) [:buf-io :buf-size :filespec :append] [buf-io buf-size filespec append])))) (defn rolling-attrs [type attrs] (if (not= :rolling type) [] (let [max-size (str (get attrs :max-size "5MB")) max-version (str (get attrs :max-version 2))] (map (fn [k v] [(str "." (get *options* k)) v]) [:max-size :max-version] [max-size max-version])))) (defn appender-decl [name attrs] (let [name (str "log4j.appender." name) config-type (get attrs :type :console) config-type (if (*appenders* config-type) config-type :console) type (*appenders* config-type) layout-key ".layout" layout-val (get *options* :pat) convpat-key ".layout.ConversionPattern" convpat-val (get attrs :pat "%-5p %c %d{DATE}: %m%n") base-attrs [[layout-key layout-val] [convpat-key convpat-val]] file-attrs (file-attrs config-type attrs) rolling-attrs (rolling-attrs config-type attrs)] [name type (concat base-attrs file-attrs rolling-attrs)])) (defn javaize-log-decl [decl props] (let [[kind name attrs] decl] (assert (#{:logger :appender} kind)) (if (= kind :logger) (let [[name kind attrs] (logger-decl name attrs)] (.setProperty props name kind) (doseq [[k v] attrs] (.setProperty props k v))) ;; Need to refactor now that loggers have attrs... (let [[name kind attrs] (appender-decl name attrs)] (.setProperty props name kind) (doseq [[k v] attrs] (.setProperty props (str name k) v))))) props) (defn make-log-props [decls] (let [log-props (Properties.)] (doseq [decl decls] (javaize-log-decl decl log-props)) log-props)) (defn configure-logging [decls] (PropertyConfigurator/configure (make-log-props decls))) (defn activate-logging [] (doseq [a (all-appenders)] (. a activateOptions))) (defn create-loggers [decls] (configure-logging decls) (activate-logging)) ;;; (create-loggers ;;; [[:logger "rootLogger" ;;; {:level :info :appenders "console"}] ;;; [:appender "console" ;;; {:type :console :pat "%-5p %d{DATE}: %m%n"}] ;;; [:logger "refseq-ftp" ;;; {:level :info :appenders "netutils"}] ;;; [:appender "netutils" ;;; {:type :rolling ;;; :filespec "./Logs/netutils.log" ;;; :max-version 4 ;;; :max-size 1000 ; TESTING!! ;;; }] ;;; ]) (defn get-level "Return the logging level for LOGGER. If not given, the default is to try a logger for the current name space name and then a parent for that. If LOGGER is a logger just use it, if it is a string use (get-logger LOGGER)" ([] (keyword (.. (or (.. (get-logger) getLevel) (.. (get-logger) getParent getLevel)) toString toLowerCase))) ([logger] (let [logger (get-logger logger)] (keyword (.. logger getLevel toString toLowerCase))))) (defn set-level! "Sets the logger level. If not given, logger defaults to the root logger. Levels are given as keywords and are from lowest to highest: :all :trace :debug :info :warn :error :fatal :off" ([level] (let [root-logger (Logger/getRootLogger)] (set-level! root-logger (*levels* level)))) ([logger level] (.setLevel logger (*levels* level)))) (defn set-debug! "Sets log level of LOGGER to :debug. If LOGGER is not given defaults to the root logger" ([] (set-level! :debug)) ([logger] (set-level! logger :debug))) (defn set-info! "Sets log level of LOGGER to :info. If LOGGER is not given defaults to the root logger" ([] (set-level! :info)) ([logger] (set-level! logger :info))) (defn log> "Request LOGGER to log a message of level LEVEL, with message given as the resulting string of applying format string to ARGS (as defined by cl-format" [logger level message & args] (assert (*levels* level)) (let [logger (get-logger logger)] (. logger log (*levels* level) (apply cl-format nil message args))))
68362
;;--------------------------------------------------------------------------;; ;; ;; ;; L O G 4 C L J ;; ;; ;; ;; ;; ;; Copyright (c) 2011-2012 Trustees of Boston College ;; ;; ;; ;; Permission is hereby granted, free of charge, to any person obtaining ;; ;; a copy of this software and associated documentation files (the ;; ;; "Software"), to deal in the Software without restriction, including ;; ;; without limitation the rights to use, copy, modify, merge, publish, ;; ;; distribute, sublicense, and/or sell copies of the Software, and to ;; ;; permit persons to whom the Software is furnished to do so, subject to ;; ;; the following conditions: ;; ;; ;; ;; The above copyright notice and this permission notice shall be ;; ;; included in all copies or substantial portions of the Software. ;; ;; ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE ;; ;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION ;; ;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION ;; ;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ;; ;; ;; ;; Author: <NAME> ;; ;; ;; ;;--------------------------------------------------------------------------;; ;; (ns edu.bc.log4clj "Attempt to make some sort of reasonable abstraction over log4j. Or maybe we will give up and just reimplement log4cl in clj. Java logging a gigantic awful mess of over complexity to attain what is actually pretty simple and straightforward. Log4cl does everything log4j does, while also being more extensible and dynamic, yet is about 1/10 the complexity. Clojure, being JVM based, seems like it would be reasonable to just use log4j, but the underlying lib complexity is nuts." (:require [clojure.contrib.string :as str] [clojure.set :as set] [clojure.contrib.properties :as prop] [edu.bc.fs :as fs]) (:use clojure.contrib.math edu.bc.utils [clojure.pprint :only [cl-format]]) (:import (java.util Properties Vector) ;; Useless... (org.apache.commons.logging Log) (org.apache.log4j PropertyConfigurator LogManager Logger))) ;;; Logging levels for log4j and with c.c.logging. As with ;;; c.c.logging these are case as keywords as that is saner ;;; ;;; lowest ... highest ;;; ;;; :ALL :TRACE :DEBUG :INFO :WARN :ERROR :FATAL :OFF (defparameter *levels* {:all org.apache.log4j.Level/ALL :trace org.apache.log4j.Level/TRACE :debug org.apache.log4j.Level/DEBUG :info org.apache.log4j.Level/INFO :warn org.apache.log4j.Level/WARN :error org.apache.log4j.Level/ERROR :fatal org.apache.log4j.Level/FATAL :off org.apache.log4j.Level/OFF}) (defparameter *appenders* {:console "org.apache.log4j.ConsoleAppender" :file "org.apache.log4j.FileAppender" :rolling "org.apache.log4j.RollingFileAppender"}) (defparameter *options* {:level "Level" ; Don't need now, but will when reimpl :name "Name" ; " :layout "layout.ConversionPattern" :pat "org.apache.log4j.PatternLayout" :filespec "File" :buf-size "BufferSize" :buf-io "BufferedIO" :append "Append" :max-size "MaxFileSize" :max-version "MaxBackupIndex"}) (defn config-logging "Initial startup logging configuration. Uses property file PROP-DESIGNATOR, or if not given, defaults to log4j.properties. ***NOTE: more or less obsolete now we have configure-logging." ([] (config-logging "log4j.properties")) ([prop-designator] (if (string? prop-designator) (PropertyConfigurator/configure (fs/fullpath prop-designator)) (PropertyConfigurator/configure prop-designator)))) ;;; Not really useful. The Commons logging wrapper sucks anyway and ;;; since this is log4clj, it is already more or less wedded to either ;;; 1. log4j or 2. its own direct implementation of more or less what ;;; log4j is/does. Currently it is 1. Either way, the commons access ;;; api is confusing and a useless/worthless layer. ;;; (defn get-log ;;; ([] ;;; (get-log (str *ns*))) ;;; ([name] ;;; (LogFactory/getLog name))) (defn get-logger "Return the logger named NAME (a string or a logger) or if NAME is not given, use the name of the current name space. If NAME is a logger, just return it." ([] (get-logger (str *ns*))) ([name] (if (string? name) (if (= name "root") (LogManager/getRootLogger) (LogManager/getLogger name)) name))) (defn get-root-logger [] (get-logger "root")) (defn get-all-loggers "Return a vector of all the current loggers" [] (loop [jloggers (LogManager/getCurrentLoggers) loggers [(LogManager/getRootLogger)]] (if (not (. jloggers hasMoreElements)) loggers (recur jloggers (conj loggers (. jloggers nextElement)))))) (defn all-loggers-map "Return a map of all current loggers indexed by their name" [] (reduce (fn [m l] (assoc m (. l getName) l)) {} (get-all-loggers))) (defn logger-appenders "Return all the appenders for logger LOGGER, a string naming the logger or a logger" [logger] (let [logger (get-logger logger)] (loop [jappenders (. logger getAllAppenders) appenders []] (if (not (. jappenders hasMoreElements)) appenders (recur jappenders (conj appenders (. jappenders nextElement))))))) (defn all-appenders "Return all the current appenders. This set is the union of all the appenders of all the current loggers" [] (apply set/union (map logger-appenders (get-all-loggers)))) (defn close-appender "Close the appender A (an appender as obtained from logger-appenders or all-appenders). Once, closed, this appender instance is no longer useable, however it is always possible to reconfigure logging with corresponding new appenders - with same names and on same loggers" [a] (doto a .close)) (defn close-all-appenders "For all A in (all-appenders), (close-appender A)" [] (doseq [a (all-appenders)] (close-appender a))) ;;; (logger-decl "refseq-ftp" {:level :info :appenders "netutils"}) ;;; (logger-decl ;;; "rootLogger" ;;; {:level :info :appenders "console"}) ;;; (defn logger-decl [name attrs] (let [lname (if (not= name "rootLogger") (str "log4j.logger." name) (str "log4j." name)) level (. (*levels* (get attrs :level :info)) toString) additivity (str "log4j.additivity." name) appenders (get attrs :appenders "console") appenders (if (coll? appenders) (str/join ", " appenders) appenders)] [lname (str/join ", " [level appenders]) (list [additivity "false"])])) (defn file-attrs [type attrs] (if (= type :console) [] (let [buf-io (get attrs :buf-io "true") buf-size (get attrs :buf-size "1024") filespec (get attrs :filespec (str "./" (ns-name *ns*) ".log")) append (get attrs :append "true")] (map (fn [k v] [(str "." (get *options* k)) v]) [:buf-io :buf-size :filespec :append] [buf-io buf-size filespec append])))) (defn rolling-attrs [type attrs] (if (not= :rolling type) [] (let [max-size (str (get attrs :max-size "5MB")) max-version (str (get attrs :max-version 2))] (map (fn [k v] [(str "." (get *options* k)) v]) [:max-size :max-version] [max-size max-version])))) (defn appender-decl [name attrs] (let [name (str "log4j.appender." name) config-type (get attrs :type :console) config-type (if (*appenders* config-type) config-type :console) type (*appenders* config-type) layout-key ".layout" layout-val (get *options* :pat) convpat-key ".layout.ConversionPattern" convpat-val (get attrs :pat "%-5p %c %d{DATE}: %m%n") base-attrs [[layout-key layout-val] [convpat-key convpat-val]] file-attrs (file-attrs config-type attrs) rolling-attrs (rolling-attrs config-type attrs)] [name type (concat base-attrs file-attrs rolling-attrs)])) (defn javaize-log-decl [decl props] (let [[kind name attrs] decl] (assert (#{:logger :appender} kind)) (if (= kind :logger) (let [[name kind attrs] (logger-decl name attrs)] (.setProperty props name kind) (doseq [[k v] attrs] (.setProperty props k v))) ;; Need to refactor now that loggers have attrs... (let [[name kind attrs] (appender-decl name attrs)] (.setProperty props name kind) (doseq [[k v] attrs] (.setProperty props (str name k) v))))) props) (defn make-log-props [decls] (let [log-props (Properties.)] (doseq [decl decls] (javaize-log-decl decl log-props)) log-props)) (defn configure-logging [decls] (PropertyConfigurator/configure (make-log-props decls))) (defn activate-logging [] (doseq [a (all-appenders)] (. a activateOptions))) (defn create-loggers [decls] (configure-logging decls) (activate-logging)) ;;; (create-loggers ;;; [[:logger "rootLogger" ;;; {:level :info :appenders "console"}] ;;; [:appender "console" ;;; {:type :console :pat "%-5p %d{DATE}: %m%n"}] ;;; [:logger "refseq-ftp" ;;; {:level :info :appenders "netutils"}] ;;; [:appender "netutils" ;;; {:type :rolling ;;; :filespec "./Logs/netutils.log" ;;; :max-version 4 ;;; :max-size 1000 ; TESTING!! ;;; }] ;;; ]) (defn get-level "Return the logging level for LOGGER. If not given, the default is to try a logger for the current name space name and then a parent for that. If LOGGER is a logger just use it, if it is a string use (get-logger LOGGER)" ([] (keyword (.. (or (.. (get-logger) getLevel) (.. (get-logger) getParent getLevel)) toString toLowerCase))) ([logger] (let [logger (get-logger logger)] (keyword (.. logger getLevel toString toLowerCase))))) (defn set-level! "Sets the logger level. If not given, logger defaults to the root logger. Levels are given as keywords and are from lowest to highest: :all :trace :debug :info :warn :error :fatal :off" ([level] (let [root-logger (Logger/getRootLogger)] (set-level! root-logger (*levels* level)))) ([logger level] (.setLevel logger (*levels* level)))) (defn set-debug! "Sets log level of LOGGER to :debug. If LOGGER is not given defaults to the root logger" ([] (set-level! :debug)) ([logger] (set-level! logger :debug))) (defn set-info! "Sets log level of LOGGER to :info. If LOGGER is not given defaults to the root logger" ([] (set-level! :info)) ([logger] (set-level! logger :info))) (defn log> "Request LOGGER to log a message of level LEVEL, with message given as the resulting string of applying format string to ARGS (as defined by cl-format" [logger level message & args] (assert (*levels* level)) (let [logger (get-logger logger)] (. logger log (*levels* level) (apply cl-format nil message args))))
true
;;--------------------------------------------------------------------------;; ;; ;; ;; L O G 4 C L J ;; ;; ;; ;; ;; ;; Copyright (c) 2011-2012 Trustees of Boston College ;; ;; ;; ;; Permission is hereby granted, free of charge, to any person obtaining ;; ;; a copy of this software and associated documentation files (the ;; ;; "Software"), to deal in the Software without restriction, including ;; ;; without limitation the rights to use, copy, modify, merge, publish, ;; ;; distribute, sublicense, and/or sell copies of the Software, and to ;; ;; permit persons to whom the Software is furnished to do so, subject to ;; ;; the following conditions: ;; ;; ;; ;; The above copyright notice and this permission notice shall be ;; ;; included in all copies or substantial portions of the Software. ;; ;; ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE ;; ;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION ;; ;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION ;; ;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ;; ;; ;; ;; Author: PI:NAME:<NAME>END_PI ;; ;; ;; ;;--------------------------------------------------------------------------;; ;; (ns edu.bc.log4clj "Attempt to make some sort of reasonable abstraction over log4j. Or maybe we will give up and just reimplement log4cl in clj. Java logging a gigantic awful mess of over complexity to attain what is actually pretty simple and straightforward. Log4cl does everything log4j does, while also being more extensible and dynamic, yet is about 1/10 the complexity. Clojure, being JVM based, seems like it would be reasonable to just use log4j, but the underlying lib complexity is nuts." (:require [clojure.contrib.string :as str] [clojure.set :as set] [clojure.contrib.properties :as prop] [edu.bc.fs :as fs]) (:use clojure.contrib.math edu.bc.utils [clojure.pprint :only [cl-format]]) (:import (java.util Properties Vector) ;; Useless... (org.apache.commons.logging Log) (org.apache.log4j PropertyConfigurator LogManager Logger))) ;;; Logging levels for log4j and with c.c.logging. As with ;;; c.c.logging these are case as keywords as that is saner ;;; ;;; lowest ... highest ;;; ;;; :ALL :TRACE :DEBUG :INFO :WARN :ERROR :FATAL :OFF (defparameter *levels* {:all org.apache.log4j.Level/ALL :trace org.apache.log4j.Level/TRACE :debug org.apache.log4j.Level/DEBUG :info org.apache.log4j.Level/INFO :warn org.apache.log4j.Level/WARN :error org.apache.log4j.Level/ERROR :fatal org.apache.log4j.Level/FATAL :off org.apache.log4j.Level/OFF}) (defparameter *appenders* {:console "org.apache.log4j.ConsoleAppender" :file "org.apache.log4j.FileAppender" :rolling "org.apache.log4j.RollingFileAppender"}) (defparameter *options* {:level "Level" ; Don't need now, but will when reimpl :name "Name" ; " :layout "layout.ConversionPattern" :pat "org.apache.log4j.PatternLayout" :filespec "File" :buf-size "BufferSize" :buf-io "BufferedIO" :append "Append" :max-size "MaxFileSize" :max-version "MaxBackupIndex"}) (defn config-logging "Initial startup logging configuration. Uses property file PROP-DESIGNATOR, or if not given, defaults to log4j.properties. ***NOTE: more or less obsolete now we have configure-logging." ([] (config-logging "log4j.properties")) ([prop-designator] (if (string? prop-designator) (PropertyConfigurator/configure (fs/fullpath prop-designator)) (PropertyConfigurator/configure prop-designator)))) ;;; Not really useful. The Commons logging wrapper sucks anyway and ;;; since this is log4clj, it is already more or less wedded to either ;;; 1. log4j or 2. its own direct implementation of more or less what ;;; log4j is/does. Currently it is 1. Either way, the commons access ;;; api is confusing and a useless/worthless layer. ;;; (defn get-log ;;; ([] ;;; (get-log (str *ns*))) ;;; ([name] ;;; (LogFactory/getLog name))) (defn get-logger "Return the logger named NAME (a string or a logger) or if NAME is not given, use the name of the current name space. If NAME is a logger, just return it." ([] (get-logger (str *ns*))) ([name] (if (string? name) (if (= name "root") (LogManager/getRootLogger) (LogManager/getLogger name)) name))) (defn get-root-logger [] (get-logger "root")) (defn get-all-loggers "Return a vector of all the current loggers" [] (loop [jloggers (LogManager/getCurrentLoggers) loggers [(LogManager/getRootLogger)]] (if (not (. jloggers hasMoreElements)) loggers (recur jloggers (conj loggers (. jloggers nextElement)))))) (defn all-loggers-map "Return a map of all current loggers indexed by their name" [] (reduce (fn [m l] (assoc m (. l getName) l)) {} (get-all-loggers))) (defn logger-appenders "Return all the appenders for logger LOGGER, a string naming the logger or a logger" [logger] (let [logger (get-logger logger)] (loop [jappenders (. logger getAllAppenders) appenders []] (if (not (. jappenders hasMoreElements)) appenders (recur jappenders (conj appenders (. jappenders nextElement))))))) (defn all-appenders "Return all the current appenders. This set is the union of all the appenders of all the current loggers" [] (apply set/union (map logger-appenders (get-all-loggers)))) (defn close-appender "Close the appender A (an appender as obtained from logger-appenders or all-appenders). Once, closed, this appender instance is no longer useable, however it is always possible to reconfigure logging with corresponding new appenders - with same names and on same loggers" [a] (doto a .close)) (defn close-all-appenders "For all A in (all-appenders), (close-appender A)" [] (doseq [a (all-appenders)] (close-appender a))) ;;; (logger-decl "refseq-ftp" {:level :info :appenders "netutils"}) ;;; (logger-decl ;;; "rootLogger" ;;; {:level :info :appenders "console"}) ;;; (defn logger-decl [name attrs] (let [lname (if (not= name "rootLogger") (str "log4j.logger." name) (str "log4j." name)) level (. (*levels* (get attrs :level :info)) toString) additivity (str "log4j.additivity." name) appenders (get attrs :appenders "console") appenders (if (coll? appenders) (str/join ", " appenders) appenders)] [lname (str/join ", " [level appenders]) (list [additivity "false"])])) (defn file-attrs [type attrs] (if (= type :console) [] (let [buf-io (get attrs :buf-io "true") buf-size (get attrs :buf-size "1024") filespec (get attrs :filespec (str "./" (ns-name *ns*) ".log")) append (get attrs :append "true")] (map (fn [k v] [(str "." (get *options* k)) v]) [:buf-io :buf-size :filespec :append] [buf-io buf-size filespec append])))) (defn rolling-attrs [type attrs] (if (not= :rolling type) [] (let [max-size (str (get attrs :max-size "5MB")) max-version (str (get attrs :max-version 2))] (map (fn [k v] [(str "." (get *options* k)) v]) [:max-size :max-version] [max-size max-version])))) (defn appender-decl [name attrs] (let [name (str "log4j.appender." name) config-type (get attrs :type :console) config-type (if (*appenders* config-type) config-type :console) type (*appenders* config-type) layout-key ".layout" layout-val (get *options* :pat) convpat-key ".layout.ConversionPattern" convpat-val (get attrs :pat "%-5p %c %d{DATE}: %m%n") base-attrs [[layout-key layout-val] [convpat-key convpat-val]] file-attrs (file-attrs config-type attrs) rolling-attrs (rolling-attrs config-type attrs)] [name type (concat base-attrs file-attrs rolling-attrs)])) (defn javaize-log-decl [decl props] (let [[kind name attrs] decl] (assert (#{:logger :appender} kind)) (if (= kind :logger) (let [[name kind attrs] (logger-decl name attrs)] (.setProperty props name kind) (doseq [[k v] attrs] (.setProperty props k v))) ;; Need to refactor now that loggers have attrs... (let [[name kind attrs] (appender-decl name attrs)] (.setProperty props name kind) (doseq [[k v] attrs] (.setProperty props (str name k) v))))) props) (defn make-log-props [decls] (let [log-props (Properties.)] (doseq [decl decls] (javaize-log-decl decl log-props)) log-props)) (defn configure-logging [decls] (PropertyConfigurator/configure (make-log-props decls))) (defn activate-logging [] (doseq [a (all-appenders)] (. a activateOptions))) (defn create-loggers [decls] (configure-logging decls) (activate-logging)) ;;; (create-loggers ;;; [[:logger "rootLogger" ;;; {:level :info :appenders "console"}] ;;; [:appender "console" ;;; {:type :console :pat "%-5p %d{DATE}: %m%n"}] ;;; [:logger "refseq-ftp" ;;; {:level :info :appenders "netutils"}] ;;; [:appender "netutils" ;;; {:type :rolling ;;; :filespec "./Logs/netutils.log" ;;; :max-version 4 ;;; :max-size 1000 ; TESTING!! ;;; }] ;;; ]) (defn get-level "Return the logging level for LOGGER. If not given, the default is to try a logger for the current name space name and then a parent for that. If LOGGER is a logger just use it, if it is a string use (get-logger LOGGER)" ([] (keyword (.. (or (.. (get-logger) getLevel) (.. (get-logger) getParent getLevel)) toString toLowerCase))) ([logger] (let [logger (get-logger logger)] (keyword (.. logger getLevel toString toLowerCase))))) (defn set-level! "Sets the logger level. If not given, logger defaults to the root logger. Levels are given as keywords and are from lowest to highest: :all :trace :debug :info :warn :error :fatal :off" ([level] (let [root-logger (Logger/getRootLogger)] (set-level! root-logger (*levels* level)))) ([logger level] (.setLevel logger (*levels* level)))) (defn set-debug! "Sets log level of LOGGER to :debug. If LOGGER is not given defaults to the root logger" ([] (set-level! :debug)) ([logger] (set-level! logger :debug))) (defn set-info! "Sets log level of LOGGER to :info. If LOGGER is not given defaults to the root logger" ([] (set-level! :info)) ([logger] (set-level! logger :info))) (defn log> "Request LOGGER to log a message of level LEVEL, with message given as the resulting string of applying format string to ARGS (as defined by cl-format" [logger level message & args] (assert (*levels* level)) (let [logger (get-logger logger)] (. logger log (*levels* level) (apply cl-format nil message args))))
[ { "context": "l\" \n {:home-active \"active\"\n :title-tag \"Charlton Austin's Blog Technical Dazed And Confused Home Page\"\n ", "end": 915, "score": 0.9993864893913269, "start": 900, "tag": "NAME", "value": "Charlton Austin" }, { "context": "/render \n \"home.html\" \n {:title-tag (str \"Charlton's Blog Post About: \" name)\n :blog-posts-w", "end": 1547, "score": 0.598487377166748, "start": 1542, "tag": "NAME", "value": "Charl" }, { "context": "'m doing with this blog.\"\n :title-tag (:title \"Charlton Austin's Blog Technical Dazed And Confused Ab", "end": 2991, "score": 0.7351698279380798, "start": 2987, "tag": "NAME", "value": "Char" } ]
src/clj/blog/routes/home.clj
charltonaustin/blog
0
(ns blog.routes.home (:require [blog.layout :as layout] [blog.db.core :as db] [compojure.core :refer [defroutes GET]] [ring.util.http-response :as response] [clojure.java.io :as io] [clojure.string :as str] [blog.helpers.core :refer [get-published-files get-name content-for parse-year-month about-page-content]])) (defn get-archive-links [] (into [] (into (sorted-set) (map #(:archive-date %) (get-published-files))))) (defn home-page [] (let [first-three (take 3 (get-published-files)) with-content (map #(assoc % :content (content-for (:location %))) first-three)] (layout/render "home.html" {:home-active "active" :title-tag "Charlton Austin's Blog Technical Dazed And Confused Home Page" :description-tag "The landing page for my blog. It contains the three latest blog posts that I have written." :blog-posts-with-content with-content :next (:url (nth (get-published-files) 3)) :previous "/" :archive-links (get-archive-links) }))) (defn blog-post [year month day blog-post-name] (let [name (get-name blog-post-name) filtered (filter #(= (:name %) name) (get-published-files)) with-content (map #(assoc % :content (content-for (:location %))) filtered)] (layout/render "home.html" {:title-tag (str "Charlton's Blog Post About: " name) :blog-posts-with-content with-content :description-tag (first (str/split (:content (first with-content)) #"\.")) :single? "single-" :next (get (nth (get-published-files) (+ 1 (:index (first filtered))) {}) :url "/") :previous (get (nth (get-published-files) (- (:index (first filtered)) 1) {}) :url "/") :archive-links (get-archive-links) }))) (defn format-date [date] (if (= (type date) java.util.Date) (.format (java.text.SimpleDateFormat. "/yyyy/M") date) date)) (defn archive-posts [year month] (let [url (str "/" year "/" month) filtered (filter #(= (format-date (:archive-date %)) url) (get-published-files)) url-index (.indexOf (map #(format-date %) (get-archive-links)) url) with-content (map #(assoc % :content (content-for (:location %))) filtered)] (layout/render "home.html" {:title-tag (str "Charlton's Archive of Blog Posts from: " year "/" month) :blog-posts-with-content with-content :next (format-date (nth (get-archive-links) (+ 1 url-index) "/")) :previous (format-date (nth (get-archive-links) (- url-index 1) "/")) :archive-links (get-archive-links)}))) (defn about-page [] (layout/render "about.html" {:about-active "active" :description-tag "A page describin who I am and what I'm doing with this blog." :title-tag (:title "Charlton Austin's Blog Technical Dazed And Confused About Page") :content (about-page-content)})) (defroutes home-routes (GET "/" [] (home-page)) (GET "/about" [] (about-page)) (GET "/:year/:month" [year month] (archive-posts year month)) (GET "/:year/:month/:day/:blog-post-name" [year month day blog-post-name] (blog-post year month day blog-post-name)))
29796
(ns blog.routes.home (:require [blog.layout :as layout] [blog.db.core :as db] [compojure.core :refer [defroutes GET]] [ring.util.http-response :as response] [clojure.java.io :as io] [clojure.string :as str] [blog.helpers.core :refer [get-published-files get-name content-for parse-year-month about-page-content]])) (defn get-archive-links [] (into [] (into (sorted-set) (map #(:archive-date %) (get-published-files))))) (defn home-page [] (let [first-three (take 3 (get-published-files)) with-content (map #(assoc % :content (content-for (:location %))) first-three)] (layout/render "home.html" {:home-active "active" :title-tag "<NAME>'s Blog Technical Dazed And Confused Home Page" :description-tag "The landing page for my blog. It contains the three latest blog posts that I have written." :blog-posts-with-content with-content :next (:url (nth (get-published-files) 3)) :previous "/" :archive-links (get-archive-links) }))) (defn blog-post [year month day blog-post-name] (let [name (get-name blog-post-name) filtered (filter #(= (:name %) name) (get-published-files)) with-content (map #(assoc % :content (content-for (:location %))) filtered)] (layout/render "home.html" {:title-tag (str "<NAME>ton's Blog Post About: " name) :blog-posts-with-content with-content :description-tag (first (str/split (:content (first with-content)) #"\.")) :single? "single-" :next (get (nth (get-published-files) (+ 1 (:index (first filtered))) {}) :url "/") :previous (get (nth (get-published-files) (- (:index (first filtered)) 1) {}) :url "/") :archive-links (get-archive-links) }))) (defn format-date [date] (if (= (type date) java.util.Date) (.format (java.text.SimpleDateFormat. "/yyyy/M") date) date)) (defn archive-posts [year month] (let [url (str "/" year "/" month) filtered (filter #(= (format-date (:archive-date %)) url) (get-published-files)) url-index (.indexOf (map #(format-date %) (get-archive-links)) url) with-content (map #(assoc % :content (content-for (:location %))) filtered)] (layout/render "home.html" {:title-tag (str "Charlton's Archive of Blog Posts from: " year "/" month) :blog-posts-with-content with-content :next (format-date (nth (get-archive-links) (+ 1 url-index) "/")) :previous (format-date (nth (get-archive-links) (- url-index 1) "/")) :archive-links (get-archive-links)}))) (defn about-page [] (layout/render "about.html" {:about-active "active" :description-tag "A page describin who I am and what I'm doing with this blog." :title-tag (:title "<NAME>lton Austin's Blog Technical Dazed And Confused About Page") :content (about-page-content)})) (defroutes home-routes (GET "/" [] (home-page)) (GET "/about" [] (about-page)) (GET "/:year/:month" [year month] (archive-posts year month)) (GET "/:year/:month/:day/:blog-post-name" [year month day blog-post-name] (blog-post year month day blog-post-name)))
true
(ns blog.routes.home (:require [blog.layout :as layout] [blog.db.core :as db] [compojure.core :refer [defroutes GET]] [ring.util.http-response :as response] [clojure.java.io :as io] [clojure.string :as str] [blog.helpers.core :refer [get-published-files get-name content-for parse-year-month about-page-content]])) (defn get-archive-links [] (into [] (into (sorted-set) (map #(:archive-date %) (get-published-files))))) (defn home-page [] (let [first-three (take 3 (get-published-files)) with-content (map #(assoc % :content (content-for (:location %))) first-three)] (layout/render "home.html" {:home-active "active" :title-tag "PI:NAME:<NAME>END_PI's Blog Technical Dazed And Confused Home Page" :description-tag "The landing page for my blog. It contains the three latest blog posts that I have written." :blog-posts-with-content with-content :next (:url (nth (get-published-files) 3)) :previous "/" :archive-links (get-archive-links) }))) (defn blog-post [year month day blog-post-name] (let [name (get-name blog-post-name) filtered (filter #(= (:name %) name) (get-published-files)) with-content (map #(assoc % :content (content-for (:location %))) filtered)] (layout/render "home.html" {:title-tag (str "PI:NAME:<NAME>END_PIton's Blog Post About: " name) :blog-posts-with-content with-content :description-tag (first (str/split (:content (first with-content)) #"\.")) :single? "single-" :next (get (nth (get-published-files) (+ 1 (:index (first filtered))) {}) :url "/") :previous (get (nth (get-published-files) (- (:index (first filtered)) 1) {}) :url "/") :archive-links (get-archive-links) }))) (defn format-date [date] (if (= (type date) java.util.Date) (.format (java.text.SimpleDateFormat. "/yyyy/M") date) date)) (defn archive-posts [year month] (let [url (str "/" year "/" month) filtered (filter #(= (format-date (:archive-date %)) url) (get-published-files)) url-index (.indexOf (map #(format-date %) (get-archive-links)) url) with-content (map #(assoc % :content (content-for (:location %))) filtered)] (layout/render "home.html" {:title-tag (str "Charlton's Archive of Blog Posts from: " year "/" month) :blog-posts-with-content with-content :next (format-date (nth (get-archive-links) (+ 1 url-index) "/")) :previous (format-date (nth (get-archive-links) (- url-index 1) "/")) :archive-links (get-archive-links)}))) (defn about-page [] (layout/render "about.html" {:about-active "active" :description-tag "A page describin who I am and what I'm doing with this blog." :title-tag (:title "PI:NAME:<NAME>END_PIlton Austin's Blog Technical Dazed And Confused About Page") :content (about-page-content)})) (defroutes home-routes (GET "/" [] (home-page)) (GET "/about" [] (about-page)) (GET "/:year/:month" [year month] (archive-posts year month)) (GET "/:year/:month/:day/:blog-post-name" [year month day blog-post-name] (blog-post year month day blog-post-name)))
[ { "context": "me name})\n\n(println \"Patient 1: \" (new-patient 1 \"Victor\"))\n\n(defn gte-zero? [x] (>= x 0))\n(def MoneyValue", "end": 475, "score": 0.998145341873169, "start": 469, "tag": "NAME", "value": "Victor" }, { "context": "rintln \"Request 1: \" (new-request (new-patient 1 \"Victor\") 99.99 :x-ray))\n\n\n\n(def NumbersSeq [s/Num])\n(pri", "end": 878, "score": 0.9974178671836853, "start": 872, "tag": "NAME", "value": "Victor" }, { "context": "\"Patient ok: \" (s/validate Patient2 {:id 1 :name \"Victor\" :plan [:x-ray]}))\n(println \"Patient ok 2: \" (s/v", "end": 1607, "score": 0.9997704029083252, "start": 1601, "tag": "NAME", "value": "Victor" }, { "context": "atient ok 2: \" (s/validate Patient2 {:id 1 :name \"Victor\" :plan []}))\n; :plan is required to exist in the ", "end": 1694, "score": 0.9996515512466431, "start": 1688, "tag": "NAME", "value": "Victor" }, { "context": "atient ok 3: \" (s/validate Patient2 {:id 1 :name \"Victor\" :plan nil}))", "end": 1857, "score": 0.9996196031570435, "start": 1851, "tag": "NAME", "value": "Victor" } ]
hospital_schema/src/hospital_schema/class3.clj
vgeorgo/courses-alura-clojure
0
(ns hospital-schema.class3 (:use clojure.pprint) (:require [schema.core :as s])) ; Forces an error if the schema is not followed (s/set-fn-validation! true) ; Just a shortcut because we are using in more than one place (def PosInt (s/pred pos-int? 'positive-integer)) (def Patient "Schema of a patient" {:id PosInt, :name s/Str}) (s/defn new-patient :- Patient [id :- PosInt, name :- s/Str] {:id id, :name name}) (println "Patient 1: " (new-patient 1 "Victor")) (defn gte-zero? [x] (>= x 0)) (def MoneyValue (s/constrained s/Num gte-zero?)) (def Request "Request of a patient" {:patient Patient, :value MoneyValue, :procedure s/Keyword}) (s/defn new-request :- Request [patient :- Patient, value :- MoneyValue, procedure :- s/Keyword] {:patient patient, :value value, :procedure procedure}) (println "Request 1: " (new-request (new-patient 1 "Victor") 99.99 :x-ray)) (def NumbersSeq [s/Num]) (println "Sequence numbers int: " (s/validate NumbersSeq [1])) (println "Sequence numbers with float: " (s/validate NumbersSeq [1, 12.2])) ;Will throw exception ;(println "Sequence numbers vector of nil: " (s/validate NumbersVector [nil])) (println "Sequence numbers zero: " (s/validate NumbersSeq [0])) (println "Sequence numbers empty seq: " (s/validate NumbersSeq [])) ; nil is considered an empty vector, so it will not throw exception (println "Sequence numbers nil: " (s/validate NumbersSeq nil)) (def Plan [s/Keyword]) (def Patient2 "Schema of a patient with plan" {:id PosInt, :name s/Str, :plan Plan}) (println "Patient ok: " (s/validate Patient2 {:id 1 :name "Victor" :plan [:x-ray]})) (println "Patient ok 2: " (s/validate Patient2 {:id 1 :name "Victor" :plan []})) ; :plan is required to exist in the map, but nil is a valid sequence of s/Keyword (println "Patient ok 3: " (s/validate Patient2 {:id 1 :name "Victor" :plan nil}))
36588
(ns hospital-schema.class3 (:use clojure.pprint) (:require [schema.core :as s])) ; Forces an error if the schema is not followed (s/set-fn-validation! true) ; Just a shortcut because we are using in more than one place (def PosInt (s/pred pos-int? 'positive-integer)) (def Patient "Schema of a patient" {:id PosInt, :name s/Str}) (s/defn new-patient :- Patient [id :- PosInt, name :- s/Str] {:id id, :name name}) (println "Patient 1: " (new-patient 1 "<NAME>")) (defn gte-zero? [x] (>= x 0)) (def MoneyValue (s/constrained s/Num gte-zero?)) (def Request "Request of a patient" {:patient Patient, :value MoneyValue, :procedure s/Keyword}) (s/defn new-request :- Request [patient :- Patient, value :- MoneyValue, procedure :- s/Keyword] {:patient patient, :value value, :procedure procedure}) (println "Request 1: " (new-request (new-patient 1 "<NAME>") 99.99 :x-ray)) (def NumbersSeq [s/Num]) (println "Sequence numbers int: " (s/validate NumbersSeq [1])) (println "Sequence numbers with float: " (s/validate NumbersSeq [1, 12.2])) ;Will throw exception ;(println "Sequence numbers vector of nil: " (s/validate NumbersVector [nil])) (println "Sequence numbers zero: " (s/validate NumbersSeq [0])) (println "Sequence numbers empty seq: " (s/validate NumbersSeq [])) ; nil is considered an empty vector, so it will not throw exception (println "Sequence numbers nil: " (s/validate NumbersSeq nil)) (def Plan [s/Keyword]) (def Patient2 "Schema of a patient with plan" {:id PosInt, :name s/Str, :plan Plan}) (println "Patient ok: " (s/validate Patient2 {:id 1 :name "<NAME>" :plan [:x-ray]})) (println "Patient ok 2: " (s/validate Patient2 {:id 1 :name "<NAME>" :plan []})) ; :plan is required to exist in the map, but nil is a valid sequence of s/Keyword (println "Patient ok 3: " (s/validate Patient2 {:id 1 :name "<NAME>" :plan nil}))
true
(ns hospital-schema.class3 (:use clojure.pprint) (:require [schema.core :as s])) ; Forces an error if the schema is not followed (s/set-fn-validation! true) ; Just a shortcut because we are using in more than one place (def PosInt (s/pred pos-int? 'positive-integer)) (def Patient "Schema of a patient" {:id PosInt, :name s/Str}) (s/defn new-patient :- Patient [id :- PosInt, name :- s/Str] {:id id, :name name}) (println "Patient 1: " (new-patient 1 "PI:NAME:<NAME>END_PI")) (defn gte-zero? [x] (>= x 0)) (def MoneyValue (s/constrained s/Num gte-zero?)) (def Request "Request of a patient" {:patient Patient, :value MoneyValue, :procedure s/Keyword}) (s/defn new-request :- Request [patient :- Patient, value :- MoneyValue, procedure :- s/Keyword] {:patient patient, :value value, :procedure procedure}) (println "Request 1: " (new-request (new-patient 1 "PI:NAME:<NAME>END_PI") 99.99 :x-ray)) (def NumbersSeq [s/Num]) (println "Sequence numbers int: " (s/validate NumbersSeq [1])) (println "Sequence numbers with float: " (s/validate NumbersSeq [1, 12.2])) ;Will throw exception ;(println "Sequence numbers vector of nil: " (s/validate NumbersVector [nil])) (println "Sequence numbers zero: " (s/validate NumbersSeq [0])) (println "Sequence numbers empty seq: " (s/validate NumbersSeq [])) ; nil is considered an empty vector, so it will not throw exception (println "Sequence numbers nil: " (s/validate NumbersSeq nil)) (def Plan [s/Keyword]) (def Patient2 "Schema of a patient with plan" {:id PosInt, :name s/Str, :plan Plan}) (println "Patient ok: " (s/validate Patient2 {:id 1 :name "PI:NAME:<NAME>END_PI" :plan [:x-ray]})) (println "Patient ok 2: " (s/validate Patient2 {:id 1 :name "PI:NAME:<NAME>END_PI" :plan []})) ; :plan is required to exist in the map, but nil is a valid sequence of s/Keyword (println "Patient ok 3: " (s/validate Patient2 {:id 1 :name "PI:NAME:<NAME>END_PI" :plan nil}))
[ { "context": "{}))\n; Command Operation generators\n(def people [\"Damaris\" \"Liyam\" \"Wye\" \"Isbelle\" \"Rebexa\" \"Aebby\"])\n(def ", "end": 539, "score": 0.9997914433479309, "start": 532, "tag": "NAME", "value": "Damaris" }, { "context": "mand Operation generators\n(def people [\"Damaris\" \"Liyam\" \"Wye\" \"Isbelle\" \"Rebexa\" \"Aebby\"])\n(def operatio", "end": 547, "score": 0.9996993541717529, "start": 542, "tag": "NAME", "value": "Liyam" }, { "context": "ration generators\n(def people [\"Damaris\" \"Liyam\" \"Wye\" \"Isbelle\" \"Rebexa\" \"Aebby\"])\n(def operation\n (g", "end": 553, "score": 0.9994159936904907, "start": 550, "tag": "NAME", "value": "Wye" }, { "context": " generators\n(def people [\"Damaris\" \"Liyam\" \"Wye\" \"Isbelle\" \"Rebexa\" \"Aebby\"])\n(def operation\n (gen/tuple\n ", "end": 563, "score": 0.99964839220047, "start": 556, "tag": "NAME", "value": "Isbelle" }, { "context": "s\n(def people [\"Damaris\" \"Liyam\" \"Wye\" \"Isbelle\" \"Rebexa\" \"Aebby\"])\n(def operation\n (gen/tuple\n (gen/e", "end": 572, "score": 0.9995869398117065, "start": 566, "tag": "NAME", "value": "Rebexa" }, { "context": "ople [\"Damaris\" \"Liyam\" \"Wye\" \"Isbelle\" \"Rebexa\" \"Aebby\"])\n(def operation\n (gen/tuple\n (gen/elements ", "end": 580, "score": 0.9987674355506897, "start": 575, "tag": "NAME", "value": "Aebby" } ]
src/madison/test/friendship.clj
spinningtopsofdoom/property-test-madison-clojure
0
(ns madison.test.friendship (:require [clojure.string :as string] [clojure.pprint :as pprint] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [clojure.test.check :as tc])) (defn create-friendship-db [] (atom {})) ; Querying Helper Methods (defn get-people [db] (keys @db)) (defn friends? [db person friend] ((get @db person #{}) friend)) (defn person-friends [db person] (get @db person #{})) ; Command Operation generators (def people ["Damaris" "Liyam" "Wye" "Isbelle" "Rebexa" "Aebby"]) (def operation (gen/tuple (gen/elements [:add-friendship :remove-friendship]) (gen/elements people) (gen/elements people))) (def operations (gen/vector operation)) (declare add-friendship! remove-friendship!) (defn apply-operations [operations] (let [db (create-friendship-db)] (doseq [op operations] (case (first op) :add-friendship (apply add-friendship! (cons db (rest op))) :remove-friendship (apply remove-friendship! (cons db (rest op))))) db)) ; Properties (def no-self-friend (prop/for-all [ops operations] (let [db (apply-operations ops)] (not-any? #(friends? db % %) (get-people db))))) (def symetrical-friendship (prop/for-all [ops operations] (let [db (apply-operations ops)] (every? (fn [person] (every? #(friends? db % person) (person-friends db person))) (get-people db))))) ; Command (stateful) Operaions (defn bad-add-friendship! [db person new-friend] (let [friends (conj (person-friends db person) new-friend)] (swap! db #(assoc % person friends)) db)) (defn bad-remove-friendship! [db person friend] (let [friends (disj (person-friends db person) friend)] (swap! db #(assoc % person friends)) db)) (defn good-add-friendship! [db person new-friend] (when (not= person new-friend) (let [friends (conj (person-friends db person) new-friend) persons (conj (person-friends db new-friend) person)] (swap! db #(assoc % person friends new-friend persons)))) db) (defn good-remove-friendship! [db person friend] (let [friends (disj (person-friends db person) friend) persons (disj (person-friends db friend) person)] (swap! db #(assoc % person friends friend persons)) db)) (with-redefs [add-friendship! good-add-friendship! remove-friendship! good-remove-friendship!] (print "No Self Friending\n") (pprint/pprint (tc/quick-check 100 no-self-friend)) (print "Symetrical Friendship\n") (pprint/pprint (tc/quick-check 100 symetrical-friendship)))
62271
(ns madison.test.friendship (:require [clojure.string :as string] [clojure.pprint :as pprint] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [clojure.test.check :as tc])) (defn create-friendship-db [] (atom {})) ; Querying Helper Methods (defn get-people [db] (keys @db)) (defn friends? [db person friend] ((get @db person #{}) friend)) (defn person-friends [db person] (get @db person #{})) ; Command Operation generators (def people ["<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"]) (def operation (gen/tuple (gen/elements [:add-friendship :remove-friendship]) (gen/elements people) (gen/elements people))) (def operations (gen/vector operation)) (declare add-friendship! remove-friendship!) (defn apply-operations [operations] (let [db (create-friendship-db)] (doseq [op operations] (case (first op) :add-friendship (apply add-friendship! (cons db (rest op))) :remove-friendship (apply remove-friendship! (cons db (rest op))))) db)) ; Properties (def no-self-friend (prop/for-all [ops operations] (let [db (apply-operations ops)] (not-any? #(friends? db % %) (get-people db))))) (def symetrical-friendship (prop/for-all [ops operations] (let [db (apply-operations ops)] (every? (fn [person] (every? #(friends? db % person) (person-friends db person))) (get-people db))))) ; Command (stateful) Operaions (defn bad-add-friendship! [db person new-friend] (let [friends (conj (person-friends db person) new-friend)] (swap! db #(assoc % person friends)) db)) (defn bad-remove-friendship! [db person friend] (let [friends (disj (person-friends db person) friend)] (swap! db #(assoc % person friends)) db)) (defn good-add-friendship! [db person new-friend] (when (not= person new-friend) (let [friends (conj (person-friends db person) new-friend) persons (conj (person-friends db new-friend) person)] (swap! db #(assoc % person friends new-friend persons)))) db) (defn good-remove-friendship! [db person friend] (let [friends (disj (person-friends db person) friend) persons (disj (person-friends db friend) person)] (swap! db #(assoc % person friends friend persons)) db)) (with-redefs [add-friendship! good-add-friendship! remove-friendship! good-remove-friendship!] (print "No Self Friending\n") (pprint/pprint (tc/quick-check 100 no-self-friend)) (print "Symetrical Friendship\n") (pprint/pprint (tc/quick-check 100 symetrical-friendship)))
true
(ns madison.test.friendship (:require [clojure.string :as string] [clojure.pprint :as pprint] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [clojure.test.check :as tc])) (defn create-friendship-db [] (atom {})) ; Querying Helper Methods (defn get-people [db] (keys @db)) (defn friends? [db person friend] ((get @db person #{}) friend)) (defn person-friends [db person] (get @db person #{})) ; Command Operation generators (def people ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) (def operation (gen/tuple (gen/elements [:add-friendship :remove-friendship]) (gen/elements people) (gen/elements people))) (def operations (gen/vector operation)) (declare add-friendship! remove-friendship!) (defn apply-operations [operations] (let [db (create-friendship-db)] (doseq [op operations] (case (first op) :add-friendship (apply add-friendship! (cons db (rest op))) :remove-friendship (apply remove-friendship! (cons db (rest op))))) db)) ; Properties (def no-self-friend (prop/for-all [ops operations] (let [db (apply-operations ops)] (not-any? #(friends? db % %) (get-people db))))) (def symetrical-friendship (prop/for-all [ops operations] (let [db (apply-operations ops)] (every? (fn [person] (every? #(friends? db % person) (person-friends db person))) (get-people db))))) ; Command (stateful) Operaions (defn bad-add-friendship! [db person new-friend] (let [friends (conj (person-friends db person) new-friend)] (swap! db #(assoc % person friends)) db)) (defn bad-remove-friendship! [db person friend] (let [friends (disj (person-friends db person) friend)] (swap! db #(assoc % person friends)) db)) (defn good-add-friendship! [db person new-friend] (when (not= person new-friend) (let [friends (conj (person-friends db person) new-friend) persons (conj (person-friends db new-friend) person)] (swap! db #(assoc % person friends new-friend persons)))) db) (defn good-remove-friendship! [db person friend] (let [friends (disj (person-friends db person) friend) persons (disj (person-friends db friend) person)] (swap! db #(assoc % person friends friend persons)) db)) (with-redefs [add-friendship! good-add-friendship! remove-friendship! good-remove-friendship!] (print "No Self Friending\n") (pprint/pprint (tc/quick-check 100 no-self-friend)) (print "Symetrical Friendship\n") (pprint/pprint (tc/quick-check 100 symetrical-friendship)))
[ { "context": "reset! users [])\n (swap! users conj {:last-name \"last\",\n :first-name \"first\",\n ", "end": 347, "score": 0.9981572031974792, "start": 343, "tag": "NAME", "value": "last" }, { "context": "st-name \"last\",\n :first-name \"first\",\n :date-of-birth \"07/01/1978", "end": 389, "score": 0.997791588306427, "start": 384, "tag": "NAME", "value": "first" } ]
test/user_storage_app/handler_test.clj
briangorman/record-storage
0
(ns user-storage-app.handler-test (:require [clojure.test :refer :all] [ring.mock.request :as mock] [user-storage-app.handler :refer :all] [user-storage-app.db :refer [users]] [cheshire.core :refer [parse-string]])) (defn db-fixture [f] (reset! users []) (swap! users conj {:last-name "last", :first-name "first", :date-of-birth "07/01/1978", :favorite-color "Yellow", :gender "Female"}) (f) (reset! users [])) (use-fixtures :each db-fixture) (deftest gender-handler-test (testing "gender" (let [response (app (mock/request :get "/records/gender"))] (is (= 0 (compare (:last-name (first (parse-string (:body response) true))) "last"))) (is (= (:status response) 200))))) (deftest birth-date-handler-test (testing "birth date" (let [response (app (mock/request :get "/records/birthdate"))] (is (= 0 (compare (:last-name (first (parse-string (:body response) true))) "last"))) (is (= (:status response) 200))))) (deftest name-handler-test (testing "name" (let [response (app (mock/request :get "/records/name"))] (is (= 0 (compare (:last-name (first (parse-string (:body response) true))) "last"))) (is (= (:status response) 200))))) (deftest not-found-test (testing "not-found route" (let [response (app (mock/request :get "/invalid"))] (is (= (:status response) 404))))) (deftest record-insertion-handler-test (testing "records insert" (let [response (app (mock/request :post "/records" "abc,def,female,teal,\"07/02/1990\""))] (is (= (:status response) 200)) (is (= (count @users) 2)))))
1548
(ns user-storage-app.handler-test (:require [clojure.test :refer :all] [ring.mock.request :as mock] [user-storage-app.handler :refer :all] [user-storage-app.db :refer [users]] [cheshire.core :refer [parse-string]])) (defn db-fixture [f] (reset! users []) (swap! users conj {:last-name "<NAME>", :first-name "<NAME>", :date-of-birth "07/01/1978", :favorite-color "Yellow", :gender "Female"}) (f) (reset! users [])) (use-fixtures :each db-fixture) (deftest gender-handler-test (testing "gender" (let [response (app (mock/request :get "/records/gender"))] (is (= 0 (compare (:last-name (first (parse-string (:body response) true))) "last"))) (is (= (:status response) 200))))) (deftest birth-date-handler-test (testing "birth date" (let [response (app (mock/request :get "/records/birthdate"))] (is (= 0 (compare (:last-name (first (parse-string (:body response) true))) "last"))) (is (= (:status response) 200))))) (deftest name-handler-test (testing "name" (let [response (app (mock/request :get "/records/name"))] (is (= 0 (compare (:last-name (first (parse-string (:body response) true))) "last"))) (is (= (:status response) 200))))) (deftest not-found-test (testing "not-found route" (let [response (app (mock/request :get "/invalid"))] (is (= (:status response) 404))))) (deftest record-insertion-handler-test (testing "records insert" (let [response (app (mock/request :post "/records" "abc,def,female,teal,\"07/02/1990\""))] (is (= (:status response) 200)) (is (= (count @users) 2)))))
true
(ns user-storage-app.handler-test (:require [clojure.test :refer :all] [ring.mock.request :as mock] [user-storage-app.handler :refer :all] [user-storage-app.db :refer [users]] [cheshire.core :refer [parse-string]])) (defn db-fixture [f] (reset! users []) (swap! users conj {:last-name "PI:NAME:<NAME>END_PI", :first-name "PI:NAME:<NAME>END_PI", :date-of-birth "07/01/1978", :favorite-color "Yellow", :gender "Female"}) (f) (reset! users [])) (use-fixtures :each db-fixture) (deftest gender-handler-test (testing "gender" (let [response (app (mock/request :get "/records/gender"))] (is (= 0 (compare (:last-name (first (parse-string (:body response) true))) "last"))) (is (= (:status response) 200))))) (deftest birth-date-handler-test (testing "birth date" (let [response (app (mock/request :get "/records/birthdate"))] (is (= 0 (compare (:last-name (first (parse-string (:body response) true))) "last"))) (is (= (:status response) 200))))) (deftest name-handler-test (testing "name" (let [response (app (mock/request :get "/records/name"))] (is (= 0 (compare (:last-name (first (parse-string (:body response) true))) "last"))) (is (= (:status response) 200))))) (deftest not-found-test (testing "not-found route" (let [response (app (mock/request :get "/invalid"))] (is (= (:status response) 404))))) (deftest record-insertion-handler-test (testing "records insert" (let [response (app (mock/request :post "/records" "abc,def,female,teal,\"07/02/1990\""))] (is (= (:status response) 200)) (is (= (count @users) 2)))))
[ { "context": "WORK:\n;;\n;; * Why did we have to do all this?\n;; Ben Vandgrift has a nice explanation at:\n;; \"Clojure: 'Hello ", "end": 6783, "score": 0.9998632669448853, "start": 6770, "tag": "NAME", "value": "Ben Vandgrift" } ]
src/clojure_by_example/ex07_boldly_go.clj
madhuri5279/clojure-by-example
122
(ns clojure-by-example.ex07-boldly-go) ;; EX07: Lesson Goals ;; ;; - Quickly see how to start and architect your own project. ;; - namespaces, dependencies, project structuring etc... ;; ;; - To be able to run your project as a binary (jar) like this: ;; ;; java -jar ./path/to/the_library_jarfile.jar "arg1" "arg2" "arg3" ;; Your First Clojure Library ;; - Let's turn code from ex06 into a library for planetary exploration. ;; - Follow the procedure below, step by step. ;; ;; ;; * Use leiningen to create a new project skeleton. ;; ;; - Open a terminal session and execute: ;; ;; lein new planet_coloniser ;; ;; ;; * Open the directory in your IDE and observe its structure. ;; ;; ;; * Create a `utils` directory in which to put I/O utility functions. ;; (Putting utility functions in `utils` is only a convention, ;; not a rule.) ;; ;; - Terminal: ;; mkdir src/planet_coloniser/utils ;; ;; - Or, in your IDE: ;; - right-click on src/planet_coloniser, and create new folder ;; ;; ;; * Inside this new `utils` directory, create two new files: ;; - `ingest.clj` and ;; - `export.clj` ;; ;; - Again, you can right-click on your `utils` dir in your IDE, ;; and create New File from the pop-up menu. ;; ;; ;; * Update `ingest.clj` with ingest utility functions. ;; ;; - Open the file and add this "ns declaration" at the top: ;; ;; (ns planet-coloniser.utils.ingest) ;; ;; - Observe the dir name is planet_coloniser, but the ns ;; declaration has planet-coloniser. This is the convention: ;; - hyphens separate words in ns names ;; - dots separate directories and files in ns names ;; - underscores from dir or file names become hyphens in ns names ;; - and ns names are all lower case ;; ;; - Copy-paste the "input" function definitions from ex06, ;; below the ns declaration. ;; ;; ;; * Update `ingest.clj`, and project, for external dependency ;; ;; - `ingest` uses `clojure.data.json`, which is an external ;; dependency that we have to specify explicitly. ;; ;; - Inside `project.clj`, update :dependencies value to look like: ;; ;; :dependencies [[org.clojure/clojure "1.10.0" ; latest as of 01 Jan 2019 ;; [org.clojure/data.json "0.2.6"]] ; add for `ingest` ;; ;; - Inside `injest.clj`, update the ns declaration to look like: ;; ;; (ns planet-coloniser.utils.ingest ;; (:require [clojure.data.json :as json] ;; [clojure.java.io :as io])) ;; ;; ;; * Update `export.clj`. Open the file and: ;; ;; - Add the appropriate "ns declaration" at the top ;; ;; - Copy-paste only the `write-out-json-file` function here. ;; ;; - Later, we will port code from the other function to another file. ;; ;; - Also ensure, the ns form looks like this: ;; ;; (ns planet-coloniser.utils.ingest ;; (:require [clojure.data.json :as json] ;; [clojure.java.io :as io])) ;; ;; ;; * Create `sensor_processor.clj`, for our core "pure" logic: ;; ;; - Create it under `src/planet_coloniser/` ;; ;; - Add the appropriate ns declaration ;; ;; - Copy-paste all the pure functions in there ;; ;; - Update the ns form to also require clojure.walk ;; ;; ;; * Update `src/planet_coloniser/core.clj` ;; - This will contain the entry point for the outside world, ;; into our planet processor. ;; ;; - Delete the dummy function from the namespace ;; ;; - Update the `ns` declaration to look like this: ;; ;; (ns planet-coloniser.core ;; (:gen-class) ; add this, and the :require expression below: ;; (:require [planet-coloniser.sensor-processor :as sensproc] ;; [planet-coloniser.utils.ingest :as ingest] ;; [planet-coloniser.utils.export :as export])) ;; ;; - Copy `ingest-export-sensor-data!` from ex06 ;; ;; - Rename it to `-main`. ;; ;; - Now, make the body of `-main` look like the function below: ;; - notice prefixes to functions, like export/, ingest/, sensproc/ ;; - Why do we do this? ;; ;; (defn -main ;; [data-dir source-data-files dest-data-file] ;; (let [source-data-files (ingest/ingest-json-file! data-dir ;; source-data-files) ;; export-as-json (partial export/write-out-json-file! ;; data-dir ;; dest-data-file)] ;; (export-as-json ;; (sensproc/denormalise-planetary-data ;; (ingest/gather-all-sensor-data! data-dir ;; source-data-files))))) ;; ;; ;; * Let's bring in sensor data, for convenience: ;; - Copy over `sensor_data` directory from clojure-by-example. ;; - From: ;; /Path/To/clojure-by-example/resources/sensor_data/ ;; - To: ;; /Path/To/planet_coloniser/resources/sensor_data/ ;; ;; ;; * In the new `sensor_data` directory, create a new JSON file: ;; ;; - call it `sensor_data_files.json` ;; ;; - add the following JSON to it: ;; ;; {"planets":"planet_detector.json", ;; "moons":"moon_detector.json", ;; "atmosphere":"atmospheric_detector.json"} ;; ;; ;; * Let's make the project runnable: ;; ;; - Update `project.clj` to specify entry point. ;; ;; - After :dependencies, add the location of the main function: ;; ;; :main planet-coloniser.core ;; ;; ;; * Check if the project has indeed become runnable: ;; ;; - In the terminal, cd to the root directory of your ;; `planet_coloniser` project. ;; ;; - Use leiningen to run the library: ;; ;; lein run "resources/sensor_data/" "sensor_data_files.json" "lein_out.json" ;; ;; - Did that work? ;; - Check resources/lein_out.json ;; ;; ;; * Let's bump our project version to `0.1.0` :-D ;; - In project.clj, delete `-SNAPSHOT` from the project version ;; (see it at the top of the project definition) ;; ;; ;; * Finally, let's prep the project for building a java executable. ;; - Update `project.clj` for Ahead-Of-Time compilation, ;; required in order to produce a standalone Java executable jar. ;; ;; - Below :main, add this: ;; ;; :aot :all ;; ;; - Use leiningen to Build the jar: ;; - In your terminal, cd into the root of your project, ;; and execute: ;; ;; lein uberjar ;; ;; - Observe the build output in your terminal. ;; ;; - Do you see two jar files created under `planet_coloniser/target`? ;; ;; ;; * Now run the "standalone" jar as: ;; ;; java -jar target/planet_coloniser-0.1.0-standalone.jar "resources/sensor_data/" "sensor_data_files.json" "jar_out.json" ;; ;; - Did that work? ;; - Check the output file ;; ;; ;; * If you've reached this far... ;; - Congratulations, you just built a brand new Clojure project ;; from scratch! ;; ;; ;; HOMEWORK: ;; ;; * Why did we have to do all this? ;; Ben Vandgrift has a nice explanation at: ;; "Clojure: 'Hello World' from the Command Line" ;; http://ben.vandgrift.com/2013/03/13/clojure-hello-world.html
54684
(ns clojure-by-example.ex07-boldly-go) ;; EX07: Lesson Goals ;; ;; - Quickly see how to start and architect your own project. ;; - namespaces, dependencies, project structuring etc... ;; ;; - To be able to run your project as a binary (jar) like this: ;; ;; java -jar ./path/to/the_library_jarfile.jar "arg1" "arg2" "arg3" ;; Your First Clojure Library ;; - Let's turn code from ex06 into a library for planetary exploration. ;; - Follow the procedure below, step by step. ;; ;; ;; * Use leiningen to create a new project skeleton. ;; ;; - Open a terminal session and execute: ;; ;; lein new planet_coloniser ;; ;; ;; * Open the directory in your IDE and observe its structure. ;; ;; ;; * Create a `utils` directory in which to put I/O utility functions. ;; (Putting utility functions in `utils` is only a convention, ;; not a rule.) ;; ;; - Terminal: ;; mkdir src/planet_coloniser/utils ;; ;; - Or, in your IDE: ;; - right-click on src/planet_coloniser, and create new folder ;; ;; ;; * Inside this new `utils` directory, create two new files: ;; - `ingest.clj` and ;; - `export.clj` ;; ;; - Again, you can right-click on your `utils` dir in your IDE, ;; and create New File from the pop-up menu. ;; ;; ;; * Update `ingest.clj` with ingest utility functions. ;; ;; - Open the file and add this "ns declaration" at the top: ;; ;; (ns planet-coloniser.utils.ingest) ;; ;; - Observe the dir name is planet_coloniser, but the ns ;; declaration has planet-coloniser. This is the convention: ;; - hyphens separate words in ns names ;; - dots separate directories and files in ns names ;; - underscores from dir or file names become hyphens in ns names ;; - and ns names are all lower case ;; ;; - Copy-paste the "input" function definitions from ex06, ;; below the ns declaration. ;; ;; ;; * Update `ingest.clj`, and project, for external dependency ;; ;; - `ingest` uses `clojure.data.json`, which is an external ;; dependency that we have to specify explicitly. ;; ;; - Inside `project.clj`, update :dependencies value to look like: ;; ;; :dependencies [[org.clojure/clojure "1.10.0" ; latest as of 01 Jan 2019 ;; [org.clojure/data.json "0.2.6"]] ; add for `ingest` ;; ;; - Inside `injest.clj`, update the ns declaration to look like: ;; ;; (ns planet-coloniser.utils.ingest ;; (:require [clojure.data.json :as json] ;; [clojure.java.io :as io])) ;; ;; ;; * Update `export.clj`. Open the file and: ;; ;; - Add the appropriate "ns declaration" at the top ;; ;; - Copy-paste only the `write-out-json-file` function here. ;; ;; - Later, we will port code from the other function to another file. ;; ;; - Also ensure, the ns form looks like this: ;; ;; (ns planet-coloniser.utils.ingest ;; (:require [clojure.data.json :as json] ;; [clojure.java.io :as io])) ;; ;; ;; * Create `sensor_processor.clj`, for our core "pure" logic: ;; ;; - Create it under `src/planet_coloniser/` ;; ;; - Add the appropriate ns declaration ;; ;; - Copy-paste all the pure functions in there ;; ;; - Update the ns form to also require clojure.walk ;; ;; ;; * Update `src/planet_coloniser/core.clj` ;; - This will contain the entry point for the outside world, ;; into our planet processor. ;; ;; - Delete the dummy function from the namespace ;; ;; - Update the `ns` declaration to look like this: ;; ;; (ns planet-coloniser.core ;; (:gen-class) ; add this, and the :require expression below: ;; (:require [planet-coloniser.sensor-processor :as sensproc] ;; [planet-coloniser.utils.ingest :as ingest] ;; [planet-coloniser.utils.export :as export])) ;; ;; - Copy `ingest-export-sensor-data!` from ex06 ;; ;; - Rename it to `-main`. ;; ;; - Now, make the body of `-main` look like the function below: ;; - notice prefixes to functions, like export/, ingest/, sensproc/ ;; - Why do we do this? ;; ;; (defn -main ;; [data-dir source-data-files dest-data-file] ;; (let [source-data-files (ingest/ingest-json-file! data-dir ;; source-data-files) ;; export-as-json (partial export/write-out-json-file! ;; data-dir ;; dest-data-file)] ;; (export-as-json ;; (sensproc/denormalise-planetary-data ;; (ingest/gather-all-sensor-data! data-dir ;; source-data-files))))) ;; ;; ;; * Let's bring in sensor data, for convenience: ;; - Copy over `sensor_data` directory from clojure-by-example. ;; - From: ;; /Path/To/clojure-by-example/resources/sensor_data/ ;; - To: ;; /Path/To/planet_coloniser/resources/sensor_data/ ;; ;; ;; * In the new `sensor_data` directory, create a new JSON file: ;; ;; - call it `sensor_data_files.json` ;; ;; - add the following JSON to it: ;; ;; {"planets":"planet_detector.json", ;; "moons":"moon_detector.json", ;; "atmosphere":"atmospheric_detector.json"} ;; ;; ;; * Let's make the project runnable: ;; ;; - Update `project.clj` to specify entry point. ;; ;; - After :dependencies, add the location of the main function: ;; ;; :main planet-coloniser.core ;; ;; ;; * Check if the project has indeed become runnable: ;; ;; - In the terminal, cd to the root directory of your ;; `planet_coloniser` project. ;; ;; - Use leiningen to run the library: ;; ;; lein run "resources/sensor_data/" "sensor_data_files.json" "lein_out.json" ;; ;; - Did that work? ;; - Check resources/lein_out.json ;; ;; ;; * Let's bump our project version to `0.1.0` :-D ;; - In project.clj, delete `-SNAPSHOT` from the project version ;; (see it at the top of the project definition) ;; ;; ;; * Finally, let's prep the project for building a java executable. ;; - Update `project.clj` for Ahead-Of-Time compilation, ;; required in order to produce a standalone Java executable jar. ;; ;; - Below :main, add this: ;; ;; :aot :all ;; ;; - Use leiningen to Build the jar: ;; - In your terminal, cd into the root of your project, ;; and execute: ;; ;; lein uberjar ;; ;; - Observe the build output in your terminal. ;; ;; - Do you see two jar files created under `planet_coloniser/target`? ;; ;; ;; * Now run the "standalone" jar as: ;; ;; java -jar target/planet_coloniser-0.1.0-standalone.jar "resources/sensor_data/" "sensor_data_files.json" "jar_out.json" ;; ;; - Did that work? ;; - Check the output file ;; ;; ;; * If you've reached this far... ;; - Congratulations, you just built a brand new Clojure project ;; from scratch! ;; ;; ;; HOMEWORK: ;; ;; * Why did we have to do all this? ;; <NAME> has a nice explanation at: ;; "Clojure: 'Hello World' from the Command Line" ;; http://ben.vandgrift.com/2013/03/13/clojure-hello-world.html
true
(ns clojure-by-example.ex07-boldly-go) ;; EX07: Lesson Goals ;; ;; - Quickly see how to start and architect your own project. ;; - namespaces, dependencies, project structuring etc... ;; ;; - To be able to run your project as a binary (jar) like this: ;; ;; java -jar ./path/to/the_library_jarfile.jar "arg1" "arg2" "arg3" ;; Your First Clojure Library ;; - Let's turn code from ex06 into a library for planetary exploration. ;; - Follow the procedure below, step by step. ;; ;; ;; * Use leiningen to create a new project skeleton. ;; ;; - Open a terminal session and execute: ;; ;; lein new planet_coloniser ;; ;; ;; * Open the directory in your IDE and observe its structure. ;; ;; ;; * Create a `utils` directory in which to put I/O utility functions. ;; (Putting utility functions in `utils` is only a convention, ;; not a rule.) ;; ;; - Terminal: ;; mkdir src/planet_coloniser/utils ;; ;; - Or, in your IDE: ;; - right-click on src/planet_coloniser, and create new folder ;; ;; ;; * Inside this new `utils` directory, create two new files: ;; - `ingest.clj` and ;; - `export.clj` ;; ;; - Again, you can right-click on your `utils` dir in your IDE, ;; and create New File from the pop-up menu. ;; ;; ;; * Update `ingest.clj` with ingest utility functions. ;; ;; - Open the file and add this "ns declaration" at the top: ;; ;; (ns planet-coloniser.utils.ingest) ;; ;; - Observe the dir name is planet_coloniser, but the ns ;; declaration has planet-coloniser. This is the convention: ;; - hyphens separate words in ns names ;; - dots separate directories and files in ns names ;; - underscores from dir or file names become hyphens in ns names ;; - and ns names are all lower case ;; ;; - Copy-paste the "input" function definitions from ex06, ;; below the ns declaration. ;; ;; ;; * Update `ingest.clj`, and project, for external dependency ;; ;; - `ingest` uses `clojure.data.json`, which is an external ;; dependency that we have to specify explicitly. ;; ;; - Inside `project.clj`, update :dependencies value to look like: ;; ;; :dependencies [[org.clojure/clojure "1.10.0" ; latest as of 01 Jan 2019 ;; [org.clojure/data.json "0.2.6"]] ; add for `ingest` ;; ;; - Inside `injest.clj`, update the ns declaration to look like: ;; ;; (ns planet-coloniser.utils.ingest ;; (:require [clojure.data.json :as json] ;; [clojure.java.io :as io])) ;; ;; ;; * Update `export.clj`. Open the file and: ;; ;; - Add the appropriate "ns declaration" at the top ;; ;; - Copy-paste only the `write-out-json-file` function here. ;; ;; - Later, we will port code from the other function to another file. ;; ;; - Also ensure, the ns form looks like this: ;; ;; (ns planet-coloniser.utils.ingest ;; (:require [clojure.data.json :as json] ;; [clojure.java.io :as io])) ;; ;; ;; * Create `sensor_processor.clj`, for our core "pure" logic: ;; ;; - Create it under `src/planet_coloniser/` ;; ;; - Add the appropriate ns declaration ;; ;; - Copy-paste all the pure functions in there ;; ;; - Update the ns form to also require clojure.walk ;; ;; ;; * Update `src/planet_coloniser/core.clj` ;; - This will contain the entry point for the outside world, ;; into our planet processor. ;; ;; - Delete the dummy function from the namespace ;; ;; - Update the `ns` declaration to look like this: ;; ;; (ns planet-coloniser.core ;; (:gen-class) ; add this, and the :require expression below: ;; (:require [planet-coloniser.sensor-processor :as sensproc] ;; [planet-coloniser.utils.ingest :as ingest] ;; [planet-coloniser.utils.export :as export])) ;; ;; - Copy `ingest-export-sensor-data!` from ex06 ;; ;; - Rename it to `-main`. ;; ;; - Now, make the body of `-main` look like the function below: ;; - notice prefixes to functions, like export/, ingest/, sensproc/ ;; - Why do we do this? ;; ;; (defn -main ;; [data-dir source-data-files dest-data-file] ;; (let [source-data-files (ingest/ingest-json-file! data-dir ;; source-data-files) ;; export-as-json (partial export/write-out-json-file! ;; data-dir ;; dest-data-file)] ;; (export-as-json ;; (sensproc/denormalise-planetary-data ;; (ingest/gather-all-sensor-data! data-dir ;; source-data-files))))) ;; ;; ;; * Let's bring in sensor data, for convenience: ;; - Copy over `sensor_data` directory from clojure-by-example. ;; - From: ;; /Path/To/clojure-by-example/resources/sensor_data/ ;; - To: ;; /Path/To/planet_coloniser/resources/sensor_data/ ;; ;; ;; * In the new `sensor_data` directory, create a new JSON file: ;; ;; - call it `sensor_data_files.json` ;; ;; - add the following JSON to it: ;; ;; {"planets":"planet_detector.json", ;; "moons":"moon_detector.json", ;; "atmosphere":"atmospheric_detector.json"} ;; ;; ;; * Let's make the project runnable: ;; ;; - Update `project.clj` to specify entry point. ;; ;; - After :dependencies, add the location of the main function: ;; ;; :main planet-coloniser.core ;; ;; ;; * Check if the project has indeed become runnable: ;; ;; - In the terminal, cd to the root directory of your ;; `planet_coloniser` project. ;; ;; - Use leiningen to run the library: ;; ;; lein run "resources/sensor_data/" "sensor_data_files.json" "lein_out.json" ;; ;; - Did that work? ;; - Check resources/lein_out.json ;; ;; ;; * Let's bump our project version to `0.1.0` :-D ;; - In project.clj, delete `-SNAPSHOT` from the project version ;; (see it at the top of the project definition) ;; ;; ;; * Finally, let's prep the project for building a java executable. ;; - Update `project.clj` for Ahead-Of-Time compilation, ;; required in order to produce a standalone Java executable jar. ;; ;; - Below :main, add this: ;; ;; :aot :all ;; ;; - Use leiningen to Build the jar: ;; - In your terminal, cd into the root of your project, ;; and execute: ;; ;; lein uberjar ;; ;; - Observe the build output in your terminal. ;; ;; - Do you see two jar files created under `planet_coloniser/target`? ;; ;; ;; * Now run the "standalone" jar as: ;; ;; java -jar target/planet_coloniser-0.1.0-standalone.jar "resources/sensor_data/" "sensor_data_files.json" "jar_out.json" ;; ;; - Did that work? ;; - Check the output file ;; ;; ;; * If you've reached this far... ;; - Congratulations, you just built a brand new Clojure project ;; from scratch! ;; ;; ;; HOMEWORK: ;; ;; * Why did we have to do all this? ;; PI:NAME:<NAME>END_PI has a nice explanation at: ;; "Clojure: 'Hello World' from the Command Line" ;; http://ben.vandgrift.com/2013/03/13/clojure-hello-world.html
[ { "context": "dra-backed object storage\"\n :maintainer {:email \"Pierre-Yves Ritschard <pyr@spootnik.org>\"}\n :url \"http://pithos.io\"\n ", "end": 139, "score": 0.9998764395713806, "start": 118, "tag": "NAME", "value": "Pierre-Yves Ritschard" }, { "context": "ge\"\n :maintainer {:email \"Pierre-Yves Ritschard <pyr@spootnik.org>\"}\n :url \"http://pithos.io\"\n :license {:name \"A", "end": 157, "score": 0.9999305009841919, "start": 141, "tag": "EMAIL", "value": "pyr@spootnik.org" } ]
project.clj
exoscale/pithos
222
(defproject io.pithos/pithos "0.7.6-SNAPSHOT" :description "cassandra-backed object storage" :maintainer {:email "Pierre-Yves Ritschard <pyr@spootnik.org>"} :url "http://pithos.io" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :aot :all :main io.pithos :jvm-opts ["-Xmx2g"] :profiles {:dev {:resource-paths ["test/data"]}} :dependencies [[org.clojure/clojure "1.9.0-alpha14"] [org.clojure/data.codec "0.1.0"] [org.clojure/data.xml "0.0.8"] [org.clojure/data.zip "0.1.1"] [org.clojure/tools.cli "0.3.5"] [org.clojure/tools.logging "0.3.1"] [org.clojure/core.async "0.2.374"] [spootnik/unilog "0.7.17"] [spootnik/constance "0.5.3"] [spootnik/raven "0.1.1"] [spootnik/uncaught "0.5.3"] [clj-yaml "0.4.0"] [clout "2.1.2"] [cheshire "5.6.3"] [clj-time "0.9.0"] [ring/ring-core "1.3.2" :exclusions [org.clojure/tools.reader]] [ring/ring-codec "1.0.0"] [com.eaio.uuid/uuid "3.2"] [cc.qbits/alia-all "3.3.0" :exclusions [com.eaio.uuid/uuid]] [cc.qbits/hayt "3.0.1"] [cc.qbits/jet "0.7.9" :exclusions [org.clojure/tools.reader]] [net.jpountz.lz4/lz4 "1.3.0"] [org.xerial.snappy/snappy-java "1.1.2.4"]])
38100
(defproject io.pithos/pithos "0.7.6-SNAPSHOT" :description "cassandra-backed object storage" :maintainer {:email "<NAME> <<EMAIL>>"} :url "http://pithos.io" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :aot :all :main io.pithos :jvm-opts ["-Xmx2g"] :profiles {:dev {:resource-paths ["test/data"]}} :dependencies [[org.clojure/clojure "1.9.0-alpha14"] [org.clojure/data.codec "0.1.0"] [org.clojure/data.xml "0.0.8"] [org.clojure/data.zip "0.1.1"] [org.clojure/tools.cli "0.3.5"] [org.clojure/tools.logging "0.3.1"] [org.clojure/core.async "0.2.374"] [spootnik/unilog "0.7.17"] [spootnik/constance "0.5.3"] [spootnik/raven "0.1.1"] [spootnik/uncaught "0.5.3"] [clj-yaml "0.4.0"] [clout "2.1.2"] [cheshire "5.6.3"] [clj-time "0.9.0"] [ring/ring-core "1.3.2" :exclusions [org.clojure/tools.reader]] [ring/ring-codec "1.0.0"] [com.eaio.uuid/uuid "3.2"] [cc.qbits/alia-all "3.3.0" :exclusions [com.eaio.uuid/uuid]] [cc.qbits/hayt "3.0.1"] [cc.qbits/jet "0.7.9" :exclusions [org.clojure/tools.reader]] [net.jpountz.lz4/lz4 "1.3.0"] [org.xerial.snappy/snappy-java "1.1.2.4"]])
true
(defproject io.pithos/pithos "0.7.6-SNAPSHOT" :description "cassandra-backed object storage" :maintainer {:email "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"} :url "http://pithos.io" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :aot :all :main io.pithos :jvm-opts ["-Xmx2g"] :profiles {:dev {:resource-paths ["test/data"]}} :dependencies [[org.clojure/clojure "1.9.0-alpha14"] [org.clojure/data.codec "0.1.0"] [org.clojure/data.xml "0.0.8"] [org.clojure/data.zip "0.1.1"] [org.clojure/tools.cli "0.3.5"] [org.clojure/tools.logging "0.3.1"] [org.clojure/core.async "0.2.374"] [spootnik/unilog "0.7.17"] [spootnik/constance "0.5.3"] [spootnik/raven "0.1.1"] [spootnik/uncaught "0.5.3"] [clj-yaml "0.4.0"] [clout "2.1.2"] [cheshire "5.6.3"] [clj-time "0.9.0"] [ring/ring-core "1.3.2" :exclusions [org.clojure/tools.reader]] [ring/ring-codec "1.0.0"] [com.eaio.uuid/uuid "3.2"] [cc.qbits/alia-all "3.3.0" :exclusions [com.eaio.uuid/uuid]] [cc.qbits/hayt "3.0.1"] [cc.qbits/jet "0.7.9" :exclusions [org.clojure/tools.reader]] [net.jpountz.lz4/lz4 "1.3.0"] [org.xerial.snappy/snappy-java "1.1.2.4"]])
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :since \"2017-11-10\"\n :date \"2017-11-", "end": 113, "score": 0.822047233581543, "start": 87, "tag": "EMAIL", "value": "wahpenayo at gmail dot com" } ]
src/scripts/clojure/taiga/scripts/quantiles/data.clj
wahpenayo/taiga
4
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "wahpenayo at gmail dot com" :since "2017-11-10" :date "2017-11-15" :doc "Generate data for mean regression training, probability measure regression training, and test."} taiga.scripts.quantiles.data (:require [zana.api :as z] [taiga.scripts.quantiles.defs :as defs])) ;;---------------------------------------------------------------- (z/seconds (str *ns*) (defs/generate-data defs/n)) ;;----------------------------------------------------------------
71846
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<EMAIL>" :since "2017-11-10" :date "2017-11-15" :doc "Generate data for mean regression training, probability measure regression training, and test."} taiga.scripts.quantiles.data (:require [zana.api :as z] [taiga.scripts.quantiles.defs :as defs])) ;;---------------------------------------------------------------- (z/seconds (str *ns*) (defs/generate-data defs/n)) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:EMAIL:<EMAIL>END_PI" :since "2017-11-10" :date "2017-11-15" :doc "Generate data for mean regression training, probability measure regression training, and test."} taiga.scripts.quantiles.data (:require [zana.api :as z] [taiga.scripts.quantiles.defs :as defs])) ;;---------------------------------------------------------------- (z/seconds (str *ns*) (defs/generate-data defs/n)) ;;----------------------------------------------------------------
[ { "context": "ocker-api.util :as util]))\n(def param-map {:name \"kim\", :age 20, :password \"helloworld\"})\n\n(expect \"htt", "end": 198, "score": 0.5256458520889282, "start": 195, "tag": "USERNAME", "value": "kim" }, { "context": "\n(def param-map {:name \"kim\", :age 20, :password \"helloworld\"})\n\n(expect \"http://www.google.com/\" (util/wrap-u", "end": 231, "score": 0.9992755055427551, "start": 221, "tag": "PASSWORD", "value": "helloworld" }, { "context": ".google.com/\"))\n(expect \"name=kim&age=20&password=helloworld\" (util/map-param-str param-map))\n", "end": 429, "score": 0.999081015586853, "start": 419, "tag": "PASSWORD", "value": "helloworld" } ]
test/clojure_docker_api/core_test.clj
joshua-jin/clojure-docker-api
1
(ns clojure-docker-api.core-test (:require [expectations :refer :all] [clojure-docker-api.core :as api-core] [clojure-docker-api.util :as util])) (def param-map {:name "kim", :age 20, :password "helloworld"}) (expect "http://www.google.com/" (util/wrap-url "http://www.google.com")) (expect "http://www.google.com/" (util/wrap-url "http://www.google.com/")) (expect "name=kim&age=20&password=helloworld" (util/map-param-str param-map))
8665
(ns clojure-docker-api.core-test (:require [expectations :refer :all] [clojure-docker-api.core :as api-core] [clojure-docker-api.util :as util])) (def param-map {:name "kim", :age 20, :password "<PASSWORD>"}) (expect "http://www.google.com/" (util/wrap-url "http://www.google.com")) (expect "http://www.google.com/" (util/wrap-url "http://www.google.com/")) (expect "name=kim&age=20&password=<PASSWORD>" (util/map-param-str param-map))
true
(ns clojure-docker-api.core-test (:require [expectations :refer :all] [clojure-docker-api.core :as api-core] [clojure-docker-api.util :as util])) (def param-map {:name "kim", :age 20, :password "PI:PASSWORD:<PASSWORD>END_PI"}) (expect "http://www.google.com/" (util/wrap-url "http://www.google.com")) (expect "http://www.google.com/" (util/wrap-url "http://www.google.com/")) (expect "name=kim&age=20&password=PI:PASSWORD:<PASSWORD>END_PI" (util/map-param-str param-map))
[ { "context": ";;;;;;;;;;\n; change to your api key\n(def API-KEY \"b25b959554ed76058ac220b7b2e0a026\")\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 686, "score": 0.9996797442436218, "start": 654, "tag": "KEY", "value": "b25b959554ed76058ac220b7b2e0a026" }, { "context": "ore is:\" (bieberscore (partial tracks-for-artist \"rihanna\")))\n\n\n ; to get the bieberscore for a particular", "end": 7756, "score": 0.9604505896568298, "start": 7749, "tag": "NAME", "value": "rihanna" }, { "context": "score is:\" (bieberscore (partial tracks-for-user \"dgorissen\")))\n\n)\n", "end": 7901, "score": 0.9996370673179626, "start": 7892, "tag": "USERNAME", "value": "dgorissen" } ]
src/bieberscore/core.clj
dgorissen/bieberscore
1
"Analyzing lyrical complexity, a toy example for learning clojure" (ns bieberscore.core (:require [clj-http.client :as client] [clojure.xml :as xml] [clojure.zip :as zip] [net.cgrand.enlive-html :as html] [stemmers.core] ) (:use clojure.pprint) (:use clojure.data.zip.xml) (:use [clojure.java.io :only [reader]]) ) (import java.net.URLEncoder) ;debugging macro from http://stackoverflow.com/questions/2352020/debugging-in-clojure (defmacro dbg[x] `(let [x# ~x] (println "dbg:" '~x "=" x#) x#)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; change to your api key (def API-KEY "b25b959554ed76058ac220b7b2e0a026") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn read-lines "read the given file into a sequence, one line per element" [fname] (with-open [r (reader fname)] (doall (line-seq r)))) (defn string-to-xml "parse the string into an xml zipper structure" [string] (zip/xml-zip (xml/parse (java.io.ByteArrayInputStream. (.getBytes (.trim string)))))) (defn get-lastfm-url "Invoke a method on the LastFm API, takes a map representing the URL query parameters and an api key" [params] (let [api-key API-KEY query-params (assoc params "api_key" api-key) ; add the api key to the query params ps (assoc {} :query-params query-params :throw-exceptions false) ; dont throw exceptions response (client/get "http://ws.audioscrobbler.com/2.0/" ps)] ; the raw response (if (= (response :status) 200) (string-to-xml (response :body)) (do (println "* Problem using lastfm api, parameters") (pprint ps) (println "* Response:") (pprint (response :body)) nil)))) (defn top-artists "Get the top artists for a given lastfm user" [user] (let [period "3month" data (get-lastfm-url {"method" "user.gettopartists" "user" user "limit" "5" "period" period})] (if (nil? data) [] (xml-> data :topartists :artist :name text)))) (defn top-albums "Get the top albums for a given artist" [artist] (let [data (get-lastfm-url {"method" "artist.gettopalbums" "artist" artist "limit" "4"})] (if (nil? data) [] (xml-> data :topalbums :album :mbid text)))) (defn album-tracks "Get all the tracks on a particular album, denoted by the musicbrainz id" [mbid] (let [data (get-lastfm-url {"method" "album.getinfo" "mbid" mbid})] (if (nil? data) [] (let [artist (first (xml-> data :album :artist text)) ] (map vector (repeat artist) (xml-> data :album :tracks :track :name text)))))) (defn tracks-for-user "Get the tracks from the top albums of a lastfm user" [user] (map album-tracks (flatten (map top-albums (top-artists user))))) (defn tracks-for-artist "Get the tracks from the top albums of an artist" [artist] (map album-tracks (top-albums artist))) (defn gen-wikia-url "Generate a wikia url for the given track" [artist title] (str "http://lyrics.wikia.com/" (URLEncoder/encode (clojure.string/replace artist " " "_")) ":" (URLEncoder/encode (clojure.string/replace title " " "_")))) (defn scrape-lyrics "Scrape the lyrics off wikia for the given track" [artist title] (let [url (gen-wikia-url artist title)] (try (let [data (html/html-resource (java.net.URL. url)) ; Im sure this can be done more concisely, get the lyricbox div, remove the rtMatcher div ; and select the text nodes from whats left lines (html/select (html/at (html/select data [:div.lyricbox]) [:div.rtMatcher] nil) [html/text-node]) ; lowercase all words, strip whitespace, and remove punctuation clean-lines (for [line lines] (clojure.string/trim (clojure.string/replace (clojure.string/lower-case line) #"\p{Punct}" "")))] (println "* Got lyrics for" artist title) (filter #(> (count %) 1) clean-lines)) ; ignore empty lines (catch java.io.FileNotFoundException e (println "* Failed to get lyrics for" artist title))))) (defn build-syllable-map "Build up a hashmap that maps a word to the number of syllables it has, based on the CMU Pronouncing Dictionary" [] (let [ ; only keep the lines we actually care about lines (filter #(re-matches #"^[A-Z].*" %) (read-lines "src/bieberscore/cmudict.0.7a.txt")) ; create a list of [word num-syllables] pairs using list comprehension word-counts (for [line lines :let [parts (clojure.string/split line #"\s+" 2) ; split into word and pronounciation parts word (clojure.string/lower-case (first parts)) ; the first part is the word sylcount (count (re-seq #"\d" (second parts)))]] ; from the second part extract all the digits ; the number of digits indicates the number of syllables [word sylcount])] (println "Loaded syllable map with" (count word-counts) "words") (reduce conj {} word-counts))) ; turn the sequence of pairs into a map "Define the global syllable map, what's the proper way for doing this in clojure?" (def syllable-map (build-syllable-map)) (defn approx-syllables "A very (!) simple approximation for counting syllables" [word] (let [w (stemmers.porter/stem word) ; first reduce to the stem vsplits (count (re-seq #"[aeiouy]+" w))] ; split on vowels (if (= (last word) "e") (- vsplits 1) vsplits))) (defn count-syllables "How many syllables in the given word" [word] (if (< (count word) 3) ; simple speed optimization, words with less than 3 letters only have 1 syllable 1 (get syllable-map word (approx-syllables word)))) (defn calc-score "Calculate the score for the given lyrics, the higher the score the, more bieberesque the lyrics: score = (1 - (proporion of unique words)) + (1 - proportion of unique sentences) + (Flesch-Kincaid readibility score)/100 This is just arbitrary really and shouldn't be taken seriously as there are lots of issues (e.g., non-english lyrics) Think of it more as spielerei. " [lyrics] (if (empty? lyrics) 0 (let [words (flatten (for [line lyrics] (clojure.string/split line #"\s+"))) ; split into a sequence of words num-sentences (count lyrics) num-unique-sentences (count (set lyrics)) num-words (count words) num-unique-words (count (set words)) num-syls (reduce + (map count-syllables words)) lexical-density (/ num-unique-words num-words) sentence-density (/ num-unique-sentences num-sentences) flesch-score (+ 206.825 (* -1.015 (/ num-words num-sentences)) (* -84.6 (/ num-syls num-words))) ] (+ (- 1 lexical-density) (- 1 sentence-density) (/ flesch-score 100))))) (defn bieberscore "Top level function, calculate the bieberscore using the given function as a source of tracks." [track-source] (let [lyrics (for [albums (track-source) tracks albums :let [artist (first tracks) title (second tracks)]] (scrape-lyrics artist title)) num-tracks (count lyrics)] (if (< num-tracks 1) "Sorry, artist unknown" ; calculate the score for every song and average (/ (reduce + (map calc-score lyrics)) num-tracks)))) (defn -main "Main function." [& args] (println "") ; to get the bieberscore for a particular artist (println "The bieberscore is:" (bieberscore (partial tracks-for-artist "rihanna"))) ; to get the bieberscore for a particular lastfm user ;(println "The bieberscore is:" (bieberscore (partial tracks-for-user "dgorissen"))) )
101534
"Analyzing lyrical complexity, a toy example for learning clojure" (ns bieberscore.core (:require [clj-http.client :as client] [clojure.xml :as xml] [clojure.zip :as zip] [net.cgrand.enlive-html :as html] [stemmers.core] ) (:use clojure.pprint) (:use clojure.data.zip.xml) (:use [clojure.java.io :only [reader]]) ) (import java.net.URLEncoder) ;debugging macro from http://stackoverflow.com/questions/2352020/debugging-in-clojure (defmacro dbg[x] `(let [x# ~x] (println "dbg:" '~x "=" x#) x#)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; change to your api key (def API-KEY "<KEY>") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn read-lines "read the given file into a sequence, one line per element" [fname] (with-open [r (reader fname)] (doall (line-seq r)))) (defn string-to-xml "parse the string into an xml zipper structure" [string] (zip/xml-zip (xml/parse (java.io.ByteArrayInputStream. (.getBytes (.trim string)))))) (defn get-lastfm-url "Invoke a method on the LastFm API, takes a map representing the URL query parameters and an api key" [params] (let [api-key API-KEY query-params (assoc params "api_key" api-key) ; add the api key to the query params ps (assoc {} :query-params query-params :throw-exceptions false) ; dont throw exceptions response (client/get "http://ws.audioscrobbler.com/2.0/" ps)] ; the raw response (if (= (response :status) 200) (string-to-xml (response :body)) (do (println "* Problem using lastfm api, parameters") (pprint ps) (println "* Response:") (pprint (response :body)) nil)))) (defn top-artists "Get the top artists for a given lastfm user" [user] (let [period "3month" data (get-lastfm-url {"method" "user.gettopartists" "user" user "limit" "5" "period" period})] (if (nil? data) [] (xml-> data :topartists :artist :name text)))) (defn top-albums "Get the top albums for a given artist" [artist] (let [data (get-lastfm-url {"method" "artist.gettopalbums" "artist" artist "limit" "4"})] (if (nil? data) [] (xml-> data :topalbums :album :mbid text)))) (defn album-tracks "Get all the tracks on a particular album, denoted by the musicbrainz id" [mbid] (let [data (get-lastfm-url {"method" "album.getinfo" "mbid" mbid})] (if (nil? data) [] (let [artist (first (xml-> data :album :artist text)) ] (map vector (repeat artist) (xml-> data :album :tracks :track :name text)))))) (defn tracks-for-user "Get the tracks from the top albums of a lastfm user" [user] (map album-tracks (flatten (map top-albums (top-artists user))))) (defn tracks-for-artist "Get the tracks from the top albums of an artist" [artist] (map album-tracks (top-albums artist))) (defn gen-wikia-url "Generate a wikia url for the given track" [artist title] (str "http://lyrics.wikia.com/" (URLEncoder/encode (clojure.string/replace artist " " "_")) ":" (URLEncoder/encode (clojure.string/replace title " " "_")))) (defn scrape-lyrics "Scrape the lyrics off wikia for the given track" [artist title] (let [url (gen-wikia-url artist title)] (try (let [data (html/html-resource (java.net.URL. url)) ; Im sure this can be done more concisely, get the lyricbox div, remove the rtMatcher div ; and select the text nodes from whats left lines (html/select (html/at (html/select data [:div.lyricbox]) [:div.rtMatcher] nil) [html/text-node]) ; lowercase all words, strip whitespace, and remove punctuation clean-lines (for [line lines] (clojure.string/trim (clojure.string/replace (clojure.string/lower-case line) #"\p{Punct}" "")))] (println "* Got lyrics for" artist title) (filter #(> (count %) 1) clean-lines)) ; ignore empty lines (catch java.io.FileNotFoundException e (println "* Failed to get lyrics for" artist title))))) (defn build-syllable-map "Build up a hashmap that maps a word to the number of syllables it has, based on the CMU Pronouncing Dictionary" [] (let [ ; only keep the lines we actually care about lines (filter #(re-matches #"^[A-Z].*" %) (read-lines "src/bieberscore/cmudict.0.7a.txt")) ; create a list of [word num-syllables] pairs using list comprehension word-counts (for [line lines :let [parts (clojure.string/split line #"\s+" 2) ; split into word and pronounciation parts word (clojure.string/lower-case (first parts)) ; the first part is the word sylcount (count (re-seq #"\d" (second parts)))]] ; from the second part extract all the digits ; the number of digits indicates the number of syllables [word sylcount])] (println "Loaded syllable map with" (count word-counts) "words") (reduce conj {} word-counts))) ; turn the sequence of pairs into a map "Define the global syllable map, what's the proper way for doing this in clojure?" (def syllable-map (build-syllable-map)) (defn approx-syllables "A very (!) simple approximation for counting syllables" [word] (let [w (stemmers.porter/stem word) ; first reduce to the stem vsplits (count (re-seq #"[aeiouy]+" w))] ; split on vowels (if (= (last word) "e") (- vsplits 1) vsplits))) (defn count-syllables "How many syllables in the given word" [word] (if (< (count word) 3) ; simple speed optimization, words with less than 3 letters only have 1 syllable 1 (get syllable-map word (approx-syllables word)))) (defn calc-score "Calculate the score for the given lyrics, the higher the score the, more bieberesque the lyrics: score = (1 - (proporion of unique words)) + (1 - proportion of unique sentences) + (Flesch-Kincaid readibility score)/100 This is just arbitrary really and shouldn't be taken seriously as there are lots of issues (e.g., non-english lyrics) Think of it more as spielerei. " [lyrics] (if (empty? lyrics) 0 (let [words (flatten (for [line lyrics] (clojure.string/split line #"\s+"))) ; split into a sequence of words num-sentences (count lyrics) num-unique-sentences (count (set lyrics)) num-words (count words) num-unique-words (count (set words)) num-syls (reduce + (map count-syllables words)) lexical-density (/ num-unique-words num-words) sentence-density (/ num-unique-sentences num-sentences) flesch-score (+ 206.825 (* -1.015 (/ num-words num-sentences)) (* -84.6 (/ num-syls num-words))) ] (+ (- 1 lexical-density) (- 1 sentence-density) (/ flesch-score 100))))) (defn bieberscore "Top level function, calculate the bieberscore using the given function as a source of tracks." [track-source] (let [lyrics (for [albums (track-source) tracks albums :let [artist (first tracks) title (second tracks)]] (scrape-lyrics artist title)) num-tracks (count lyrics)] (if (< num-tracks 1) "Sorry, artist unknown" ; calculate the score for every song and average (/ (reduce + (map calc-score lyrics)) num-tracks)))) (defn -main "Main function." [& args] (println "") ; to get the bieberscore for a particular artist (println "The bieberscore is:" (bieberscore (partial tracks-for-artist "<NAME>"))) ; to get the bieberscore for a particular lastfm user ;(println "The bieberscore is:" (bieberscore (partial tracks-for-user "dgorissen"))) )
true
"Analyzing lyrical complexity, a toy example for learning clojure" (ns bieberscore.core (:require [clj-http.client :as client] [clojure.xml :as xml] [clojure.zip :as zip] [net.cgrand.enlive-html :as html] [stemmers.core] ) (:use clojure.pprint) (:use clojure.data.zip.xml) (:use [clojure.java.io :only [reader]]) ) (import java.net.URLEncoder) ;debugging macro from http://stackoverflow.com/questions/2352020/debugging-in-clojure (defmacro dbg[x] `(let [x# ~x] (println "dbg:" '~x "=" x#) x#)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; change to your api key (def API-KEY "PI:KEY:<KEY>END_PI") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn read-lines "read the given file into a sequence, one line per element" [fname] (with-open [r (reader fname)] (doall (line-seq r)))) (defn string-to-xml "parse the string into an xml zipper structure" [string] (zip/xml-zip (xml/parse (java.io.ByteArrayInputStream. (.getBytes (.trim string)))))) (defn get-lastfm-url "Invoke a method on the LastFm API, takes a map representing the URL query parameters and an api key" [params] (let [api-key API-KEY query-params (assoc params "api_key" api-key) ; add the api key to the query params ps (assoc {} :query-params query-params :throw-exceptions false) ; dont throw exceptions response (client/get "http://ws.audioscrobbler.com/2.0/" ps)] ; the raw response (if (= (response :status) 200) (string-to-xml (response :body)) (do (println "* Problem using lastfm api, parameters") (pprint ps) (println "* Response:") (pprint (response :body)) nil)))) (defn top-artists "Get the top artists for a given lastfm user" [user] (let [period "3month" data (get-lastfm-url {"method" "user.gettopartists" "user" user "limit" "5" "period" period})] (if (nil? data) [] (xml-> data :topartists :artist :name text)))) (defn top-albums "Get the top albums for a given artist" [artist] (let [data (get-lastfm-url {"method" "artist.gettopalbums" "artist" artist "limit" "4"})] (if (nil? data) [] (xml-> data :topalbums :album :mbid text)))) (defn album-tracks "Get all the tracks on a particular album, denoted by the musicbrainz id" [mbid] (let [data (get-lastfm-url {"method" "album.getinfo" "mbid" mbid})] (if (nil? data) [] (let [artist (first (xml-> data :album :artist text)) ] (map vector (repeat artist) (xml-> data :album :tracks :track :name text)))))) (defn tracks-for-user "Get the tracks from the top albums of a lastfm user" [user] (map album-tracks (flatten (map top-albums (top-artists user))))) (defn tracks-for-artist "Get the tracks from the top albums of an artist" [artist] (map album-tracks (top-albums artist))) (defn gen-wikia-url "Generate a wikia url for the given track" [artist title] (str "http://lyrics.wikia.com/" (URLEncoder/encode (clojure.string/replace artist " " "_")) ":" (URLEncoder/encode (clojure.string/replace title " " "_")))) (defn scrape-lyrics "Scrape the lyrics off wikia for the given track" [artist title] (let [url (gen-wikia-url artist title)] (try (let [data (html/html-resource (java.net.URL. url)) ; Im sure this can be done more concisely, get the lyricbox div, remove the rtMatcher div ; and select the text nodes from whats left lines (html/select (html/at (html/select data [:div.lyricbox]) [:div.rtMatcher] nil) [html/text-node]) ; lowercase all words, strip whitespace, and remove punctuation clean-lines (for [line lines] (clojure.string/trim (clojure.string/replace (clojure.string/lower-case line) #"\p{Punct}" "")))] (println "* Got lyrics for" artist title) (filter #(> (count %) 1) clean-lines)) ; ignore empty lines (catch java.io.FileNotFoundException e (println "* Failed to get lyrics for" artist title))))) (defn build-syllable-map "Build up a hashmap that maps a word to the number of syllables it has, based on the CMU Pronouncing Dictionary" [] (let [ ; only keep the lines we actually care about lines (filter #(re-matches #"^[A-Z].*" %) (read-lines "src/bieberscore/cmudict.0.7a.txt")) ; create a list of [word num-syllables] pairs using list comprehension word-counts (for [line lines :let [parts (clojure.string/split line #"\s+" 2) ; split into word and pronounciation parts word (clojure.string/lower-case (first parts)) ; the first part is the word sylcount (count (re-seq #"\d" (second parts)))]] ; from the second part extract all the digits ; the number of digits indicates the number of syllables [word sylcount])] (println "Loaded syllable map with" (count word-counts) "words") (reduce conj {} word-counts))) ; turn the sequence of pairs into a map "Define the global syllable map, what's the proper way for doing this in clojure?" (def syllable-map (build-syllable-map)) (defn approx-syllables "A very (!) simple approximation for counting syllables" [word] (let [w (stemmers.porter/stem word) ; first reduce to the stem vsplits (count (re-seq #"[aeiouy]+" w))] ; split on vowels (if (= (last word) "e") (- vsplits 1) vsplits))) (defn count-syllables "How many syllables in the given word" [word] (if (< (count word) 3) ; simple speed optimization, words with less than 3 letters only have 1 syllable 1 (get syllable-map word (approx-syllables word)))) (defn calc-score "Calculate the score for the given lyrics, the higher the score the, more bieberesque the lyrics: score = (1 - (proporion of unique words)) + (1 - proportion of unique sentences) + (Flesch-Kincaid readibility score)/100 This is just arbitrary really and shouldn't be taken seriously as there are lots of issues (e.g., non-english lyrics) Think of it more as spielerei. " [lyrics] (if (empty? lyrics) 0 (let [words (flatten (for [line lyrics] (clojure.string/split line #"\s+"))) ; split into a sequence of words num-sentences (count lyrics) num-unique-sentences (count (set lyrics)) num-words (count words) num-unique-words (count (set words)) num-syls (reduce + (map count-syllables words)) lexical-density (/ num-unique-words num-words) sentence-density (/ num-unique-sentences num-sentences) flesch-score (+ 206.825 (* -1.015 (/ num-words num-sentences)) (* -84.6 (/ num-syls num-words))) ] (+ (- 1 lexical-density) (- 1 sentence-density) (/ flesch-score 100))))) (defn bieberscore "Top level function, calculate the bieberscore using the given function as a source of tracks." [track-source] (let [lyrics (for [albums (track-source) tracks albums :let [artist (first tracks) title (second tracks)]] (scrape-lyrics artist title)) num-tracks (count lyrics)] (if (< num-tracks 1) "Sorry, artist unknown" ; calculate the score for every song and average (/ (reduce + (map calc-score lyrics)) num-tracks)))) (defn -main "Main function." [& args] (println "") ; to get the bieberscore for a particular artist (println "The bieberscore is:" (bieberscore (partial tracks-for-artist "PI:NAME:<NAME>END_PI"))) ; to get the bieberscore for a particular lastfm user ;(println "The bieberscore is:" (bieberscore (partial tracks-for-user "dgorissen"))) )
[ { "context": ";; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and\n;; distributi", "end": 36, "score": 0.9998877048492432, "start": 18, "tag": "NAME", "value": "Stephen C. Gilardi" }, { "context": "lardi (gmail)\n;; 17 May 2008\n\n(ns \n #^{:author \"Stephen C. Gilardi\",\n :doc \"def.clj provides variants of def that", "end": 695, "score": 0.9998897314071655, "start": 677, "tag": "NAME", "value": "Stephen C. Gilardi" }, { "context": "soc (meta name) :doc doc)) orig)))\n\n; defhinted by Chouser:\n(defmacro defhinted\n \"Defines a var with a type", "end": 2838, "score": 0.9223918318748474, "start": 2831, "tag": "USERNAME", "value": "Chouser" }, { "context": "sym))\n (var ~sym)))\n\n; name-with-attributes by Konrad Hinsen:\n(defn name-with-attributes\n \"To be used in macr", "end": 3219, "score": 0.9998318552970886, "start": 3206, "tag": "NAME", "value": "Konrad Hinsen" }, { "context": " [(with-meta name attr) macro-args]))\n\n; defnk by Meikel Brandmeyer:\n(defmacro defnk\n \"Define a function accepting ke", "end": 4554, "score": 0.9998904466629028, "start": 4537, "tag": "NAME", "value": "Meikel Brandmeyer" } ]
ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/def.clj
allertonm/Couverjure
3
;; Copyright (c) Stephen C. Gilardi. 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. ;; ;; File: def.clj ;; ;; def.clj provides variants of def that make including doc strings and ;; making private definitions more succinct. ;; ;; scgilardi (gmail) ;; 17 May 2008 (ns #^{:author "Stephen C. Gilardi", :doc "def.clj provides variants of def that make including doc strings and making private definitions more succinct."} clojure.contrib.def) (defmacro defvar "Defines a var with an optional intializer and doc string" ([name] (list `def name)) ([name init] (list `def name init)) ([name init doc] (list `def (with-meta name (assoc (meta name) :doc doc)) init))) (defmacro defunbound "Defines an unbound var with optional doc string" ([name] (list `def name)) ([name doc] (list `def (with-meta name (assoc (meta name) :doc doc))))) (defmacro defmacro- "Same as defmacro but yields a private definition" [name & decls] (list* `defmacro (with-meta name (assoc (meta name) :private true)) decls)) (defmacro defvar- "Same as defvar but yields a private definition" [name & decls] (list* `defvar (with-meta name (assoc (meta name) :private true)) decls)) (defmacro defunbound- "Same as defunbound but yields a private definition" [name & decls] (list* `defunbound (with-meta name (assoc (meta name) :private true)) decls)) (defmacro defstruct- "Same as defstruct but yields a private definition" [name & decls] (list* `defstruct (with-meta name (assoc (meta name) :private true)) decls)) (defmacro defonce- "Same as defonce but yields a private definition" ([name expr] (list `defonce (with-meta name (assoc (meta name) :private true)) expr)) ([name expr doc] (list `defonce (with-meta name (assoc (meta name) :private true :doc doc)) expr))) (defmacro defalias "Defines an alias for a var: a new var with the same root binding (if any) and similar metadata. The metadata of the alias is its initial metadata (as provided by def) merged into the metadata of the original." ([name orig] `(do (alter-meta! (if (.hasRoot (var ~orig)) (def ~name (.getRoot (var ~orig))) (def ~name)) conj (apply dissoc (meta (var ~orig)) (keys (meta (var ~name))))) (var ~name))) ([name orig doc] (list `defalias (with-meta name (assoc (meta name) :doc doc)) orig))) ; defhinted by Chouser: (defmacro defhinted "Defines a var with a type hint matching the class of the given init. Be careful about using any form of 'def' or 'binding' to a value of a different type. See http://paste.lisp.org/display/73344" [sym init] `(do (def ~sym ~init) (alter-meta! (var ~sym) assoc :tag (class ~sym)) (var ~sym))) ; name-with-attributes by Konrad Hinsen: (defn name-with-attributes "To be used in macro definitions. Handles optional docstrings and attribute maps for a name to be defined in a list of macro arguments. If the first macro argument is a string, it is added as a docstring to name and removed from the macro argument list. If afterwards the first macro argument is a map, its entries are added to the name's metadata map and the map is removed from the macro argument list. The return value is a vector containing the name with its extended metadata map and the list of unprocessed macro arguments." [name macro-args] (let [[docstring macro-args] (if (string? (first macro-args)) [(first macro-args) (next macro-args)] [nil macro-args]) [attr macro-args] (if (map? (first macro-args)) [(first macro-args) (next macro-args)] [{} macro-args]) attr (if docstring (assoc attr :doc docstring) attr) attr (if (meta name) (conj (meta name) attr) attr)] [(with-meta name attr) macro-args])) ; defnk by Meikel Brandmeyer: (defmacro defnk "Define a function accepting keyword arguments. Symbols up to the first keyword in the parameter list are taken as positional arguments. Then an alternating sequence of keywords and defaults values is expected. The values of the keyword arguments are available in the function body by virtue of the symbol corresponding to the keyword (cf. :keys destructuring). defnk accepts an optional docstring as well as an optional metadata map." [fn-name & fn-tail] (let [[fn-name [args & body]] (name-with-attributes fn-name fn-tail) [pos kw-vals] (split-with symbol? args) syms (map #(-> % name symbol) (take-nth 2 kw-vals)) values (take-nth 2 (rest kw-vals)) sym-vals (apply hash-map (interleave syms values)) de-map {:keys (vec syms) :or sym-vals}] `(defn ~fn-name [~@pos & options#] (let [~de-map (apply hash-map options#)] ~@body)))) ; defn-memo by Chouser: (defmacro defn-memo "Just like defn, but memoizes the function using clojure.core/memoize" [fn-name & defn-stuff] `(do (defn ~fn-name ~@defn-stuff) (alter-var-root (var ~fn-name) memoize) (var ~fn-name)))
89465
;; Copyright (c) <NAME>. All rights reserved. The use and ;; distribution terms for this software are covered by the Eclipse Public ;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can ;; be found in the file epl-v10.html at the root of this distribution. By ;; using this software in any fashion, you are agreeing to be bound by the ;; terms of this license. You must not remove this notice, or any other, ;; from this software. ;; ;; File: def.clj ;; ;; def.clj provides variants of def that make including doc strings and ;; making private definitions more succinct. ;; ;; scgilardi (gmail) ;; 17 May 2008 (ns #^{:author "<NAME>", :doc "def.clj provides variants of def that make including doc strings and making private definitions more succinct."} clojure.contrib.def) (defmacro defvar "Defines a var with an optional intializer and doc string" ([name] (list `def name)) ([name init] (list `def name init)) ([name init doc] (list `def (with-meta name (assoc (meta name) :doc doc)) init))) (defmacro defunbound "Defines an unbound var with optional doc string" ([name] (list `def name)) ([name doc] (list `def (with-meta name (assoc (meta name) :doc doc))))) (defmacro defmacro- "Same as defmacro but yields a private definition" [name & decls] (list* `defmacro (with-meta name (assoc (meta name) :private true)) decls)) (defmacro defvar- "Same as defvar but yields a private definition" [name & decls] (list* `defvar (with-meta name (assoc (meta name) :private true)) decls)) (defmacro defunbound- "Same as defunbound but yields a private definition" [name & decls] (list* `defunbound (with-meta name (assoc (meta name) :private true)) decls)) (defmacro defstruct- "Same as defstruct but yields a private definition" [name & decls] (list* `defstruct (with-meta name (assoc (meta name) :private true)) decls)) (defmacro defonce- "Same as defonce but yields a private definition" ([name expr] (list `defonce (with-meta name (assoc (meta name) :private true)) expr)) ([name expr doc] (list `defonce (with-meta name (assoc (meta name) :private true :doc doc)) expr))) (defmacro defalias "Defines an alias for a var: a new var with the same root binding (if any) and similar metadata. The metadata of the alias is its initial metadata (as provided by def) merged into the metadata of the original." ([name orig] `(do (alter-meta! (if (.hasRoot (var ~orig)) (def ~name (.getRoot (var ~orig))) (def ~name)) conj (apply dissoc (meta (var ~orig)) (keys (meta (var ~name))))) (var ~name))) ([name orig doc] (list `defalias (with-meta name (assoc (meta name) :doc doc)) orig))) ; defhinted by Chouser: (defmacro defhinted "Defines a var with a type hint matching the class of the given init. Be careful about using any form of 'def' or 'binding' to a value of a different type. See http://paste.lisp.org/display/73344" [sym init] `(do (def ~sym ~init) (alter-meta! (var ~sym) assoc :tag (class ~sym)) (var ~sym))) ; name-with-attributes by <NAME>: (defn name-with-attributes "To be used in macro definitions. Handles optional docstrings and attribute maps for a name to be defined in a list of macro arguments. If the first macro argument is a string, it is added as a docstring to name and removed from the macro argument list. If afterwards the first macro argument is a map, its entries are added to the name's metadata map and the map is removed from the macro argument list. The return value is a vector containing the name with its extended metadata map and the list of unprocessed macro arguments." [name macro-args] (let [[docstring macro-args] (if (string? (first macro-args)) [(first macro-args) (next macro-args)] [nil macro-args]) [attr macro-args] (if (map? (first macro-args)) [(first macro-args) (next macro-args)] [{} macro-args]) attr (if docstring (assoc attr :doc docstring) attr) attr (if (meta name) (conj (meta name) attr) attr)] [(with-meta name attr) macro-args])) ; defnk by <NAME>: (defmacro defnk "Define a function accepting keyword arguments. Symbols up to the first keyword in the parameter list are taken as positional arguments. Then an alternating sequence of keywords and defaults values is expected. The values of the keyword arguments are available in the function body by virtue of the symbol corresponding to the keyword (cf. :keys destructuring). defnk accepts an optional docstring as well as an optional metadata map." [fn-name & fn-tail] (let [[fn-name [args & body]] (name-with-attributes fn-name fn-tail) [pos kw-vals] (split-with symbol? args) syms (map #(-> % name symbol) (take-nth 2 kw-vals)) values (take-nth 2 (rest kw-vals)) sym-vals (apply hash-map (interleave syms values)) de-map {:keys (vec syms) :or sym-vals}] `(defn ~fn-name [~@pos & options#] (let [~de-map (apply hash-map options#)] ~@body)))) ; defn-memo by Chouser: (defmacro defn-memo "Just like defn, but memoizes the function using clojure.core/memoize" [fn-name & defn-stuff] `(do (defn ~fn-name ~@defn-stuff) (alter-var-root (var ~fn-name) memoize) (var ~fn-name)))
true
;; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. The use and ;; distribution terms for this software are covered by the Eclipse Public ;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can ;; be found in the file epl-v10.html at the root of this distribution. By ;; using this software in any fashion, you are agreeing to be bound by the ;; terms of this license. You must not remove this notice, or any other, ;; from this software. ;; ;; File: def.clj ;; ;; def.clj provides variants of def that make including doc strings and ;; making private definitions more succinct. ;; ;; scgilardi (gmail) ;; 17 May 2008 (ns #^{:author "PI:NAME:<NAME>END_PI", :doc "def.clj provides variants of def that make including doc strings and making private definitions more succinct."} clojure.contrib.def) (defmacro defvar "Defines a var with an optional intializer and doc string" ([name] (list `def name)) ([name init] (list `def name init)) ([name init doc] (list `def (with-meta name (assoc (meta name) :doc doc)) init))) (defmacro defunbound "Defines an unbound var with optional doc string" ([name] (list `def name)) ([name doc] (list `def (with-meta name (assoc (meta name) :doc doc))))) (defmacro defmacro- "Same as defmacro but yields a private definition" [name & decls] (list* `defmacro (with-meta name (assoc (meta name) :private true)) decls)) (defmacro defvar- "Same as defvar but yields a private definition" [name & decls] (list* `defvar (with-meta name (assoc (meta name) :private true)) decls)) (defmacro defunbound- "Same as defunbound but yields a private definition" [name & decls] (list* `defunbound (with-meta name (assoc (meta name) :private true)) decls)) (defmacro defstruct- "Same as defstruct but yields a private definition" [name & decls] (list* `defstruct (with-meta name (assoc (meta name) :private true)) decls)) (defmacro defonce- "Same as defonce but yields a private definition" ([name expr] (list `defonce (with-meta name (assoc (meta name) :private true)) expr)) ([name expr doc] (list `defonce (with-meta name (assoc (meta name) :private true :doc doc)) expr))) (defmacro defalias "Defines an alias for a var: a new var with the same root binding (if any) and similar metadata. The metadata of the alias is its initial metadata (as provided by def) merged into the metadata of the original." ([name orig] `(do (alter-meta! (if (.hasRoot (var ~orig)) (def ~name (.getRoot (var ~orig))) (def ~name)) conj (apply dissoc (meta (var ~orig)) (keys (meta (var ~name))))) (var ~name))) ([name orig doc] (list `defalias (with-meta name (assoc (meta name) :doc doc)) orig))) ; defhinted by Chouser: (defmacro defhinted "Defines a var with a type hint matching the class of the given init. Be careful about using any form of 'def' or 'binding' to a value of a different type. See http://paste.lisp.org/display/73344" [sym init] `(do (def ~sym ~init) (alter-meta! (var ~sym) assoc :tag (class ~sym)) (var ~sym))) ; name-with-attributes by PI:NAME:<NAME>END_PI: (defn name-with-attributes "To be used in macro definitions. Handles optional docstrings and attribute maps for a name to be defined in a list of macro arguments. If the first macro argument is a string, it is added as a docstring to name and removed from the macro argument list. If afterwards the first macro argument is a map, its entries are added to the name's metadata map and the map is removed from the macro argument list. The return value is a vector containing the name with its extended metadata map and the list of unprocessed macro arguments." [name macro-args] (let [[docstring macro-args] (if (string? (first macro-args)) [(first macro-args) (next macro-args)] [nil macro-args]) [attr macro-args] (if (map? (first macro-args)) [(first macro-args) (next macro-args)] [{} macro-args]) attr (if docstring (assoc attr :doc docstring) attr) attr (if (meta name) (conj (meta name) attr) attr)] [(with-meta name attr) macro-args])) ; defnk by PI:NAME:<NAME>END_PI: (defmacro defnk "Define a function accepting keyword arguments. Symbols up to the first keyword in the parameter list are taken as positional arguments. Then an alternating sequence of keywords and defaults values is expected. The values of the keyword arguments are available in the function body by virtue of the symbol corresponding to the keyword (cf. :keys destructuring). defnk accepts an optional docstring as well as an optional metadata map." [fn-name & fn-tail] (let [[fn-name [args & body]] (name-with-attributes fn-name fn-tail) [pos kw-vals] (split-with symbol? args) syms (map #(-> % name symbol) (take-nth 2 kw-vals)) values (take-nth 2 (rest kw-vals)) sym-vals (apply hash-map (interleave syms values)) de-map {:keys (vec syms) :or sym-vals}] `(defn ~fn-name [~@pos & options#] (let [~de-map (apply hash-map options#)] ~@body)))) ; defn-memo by Chouser: (defmacro defn-memo "Just like defn, but memoizes the function using clojure.core/memoize" [fn-name & defn-stuff] `(do (defn ~fn-name ~@defn-stuff) (alter-var-root (var ~fn-name) memoize) (var ~fn-name)))
[ { "context": ")\n\n(deftest application-api-test\n (let [api-key \"42\"\n user-id \"alice\"\n another-user \"al", "end": 419, "score": 0.9986184239387512, "start": 417, "tag": "KEY", "value": "42" }, { "context": "on-api-test\n (let [api-key \"42\"\n user-id \"alice\"\n another-user \"alice_smith\"\n catid", "end": 443, "score": 0.9994397163391113, "start": 438, "tag": "USERNAME", "value": "alice" }, { "context": "42\"\n user-id \"alice\"\n another-user \"alice_smith\"\n catid 2]\n (let [response (-> (request", "end": 478, "score": 0.9996477961540222, "start": 467, "tag": "USERNAME", "value": "alice_smith" }, { "context": "test application-validation-test\n (let [api-key \"42\"\n user-id \"alice\"\n catid 2]\n (le", "end": 5112, "score": 0.9989628791809082, "start": 5110, "tag": "KEY", "value": "42" }, { "context": "dation-test\n (let [api-key \"42\"\n user-id \"alice\"\n catid 2]\n (let [response (-> (request", "end": 5136, "score": 0.9941174983978271, "start": 5131, "tag": "USERNAME", "value": "alice" }, { "context": "(deftest disabled-catalogue-item\n (let [api-key \"42\"\n user-id \"developer\"\n catid 6]\n ", "end": 9530, "score": 0.9991658926010132, "start": 9528, "tag": "KEY", "value": "42" }, { "context": "alogue-item\n (let [api-key \"42\"\n user-id \"developer\"\n catid 6]\n (testing \"save draft for di", "end": 9558, "score": 0.9389744400978088, "start": 9549, "tag": "USERNAME", "value": "developer" }, { "context": "\n\n(deftest application-api-roles\n (let [api-key \"42\"\n applicant \"alice\"\n approver \"deve", "end": 10956, "score": 0.9936366081237793, "start": 10954, "tag": "KEY", "value": "42" }, { "context": "ation actions that are available\n (let [api-key \"42\"\n user \"developer\"\n catid 2\n ", "end": 13783, "score": 0.980197548866272, "start": 13781, "tag": "KEY", "value": "42" }, { "context": " are available\n (let [api-key \"42\"\n user \"developer\"\n catid 2\n app-id (-> (request :put", "end": 13808, "score": 0.9987236261367798, "start": 13799, "tag": "USERNAME", "value": "developer" }, { "context": "tion-api-third-party-review-test\n (let [api-key \"42\"\n applicant \"alice\"\n approver \"deve", "end": 16089, "score": 0.9932657480239868, "start": 16087, "tag": "KEY", "value": "42" }, { "context": "view-test\n (let [api-key \"42\"\n applicant \"alice\"\n approver \"developer\"\n reviewer \"c", "end": 16115, "score": 0.68086838722229, "start": 16110, "tag": "USERNAME", "value": "alice" }, { "context": "e\"\n approver \"developer\"\n reviewer \"carl\"\n catid 2\n app-id (-> (request :put", "end": 16168, "score": 0.7122389674186707, "start": 16164, "tag": "NAME", "value": "carl" }, { "context": " read-body)]\n (is (= [\"alice\" \"bob\" \"carl\" \"developer\" \"owner\"] (sort (map :us", "end": 16868, "score": 0.7702922224998474, "start": 16863, "tag": "USERNAME", "value": "alice" }, { "context": " read-body)]\n (is (= [\"alice\" \"bob\" \"carl\" \"developer\" \"owner\"] (sort (map :userid r", "end": 16874, "score": 0.9183854460716248, "start": 16871, "tag": "USERNAME", "value": "bob" }, { "context": " read-body)]\n (is (= [\"alice\" \"bob\" \"carl\" \"developer\" \"owner\"] (sort (map :userid reviewer", "end": 16881, "score": 0.7949302196502686, "start": 16877, "tag": "NAME", "value": "carl" }, { "context": "st application-api-session-test\n (let [username \"alice\"\n login-headers (-> (request :get \"/Shibbo", "end": 20489, "score": 0.967035710811615, "start": 20484, "tag": "USERNAME", "value": "alice" } ]
test/clj/rems/test/api/application.clj
JerryTraskelin/rems
0
(ns ^:integration rems.test.api.application (:require [clojure.string :as str] [clojure.test :refer :all] [rems.handler :refer [app]] [rems.test.api :refer :all] [rems.test.tempura :refer [fake-tempura-fixture]] [ring.mock.request :refer :all])) (use-fixtures :once fake-tempura-fixture api-fixture) (deftest application-api-test (let [api-key "42" user-id "alice" another-user "alice_smith" catid 2] (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :catalogue-items [catid] :items {1 "REST-Test"}}) app) cmd-response (read-body response) application-id (:id cmd-response)] (testing "saving" (is (:success cmd-response)) (is (not (:errors cmd-response))) (is (= "draft" (:state cmd-response))) (is (not (:valid cmd-response))) (is (= [{:type "item" :id 2 :title {:en "Purpose of the project" :fi "Projektin tarkoitus"} :key "t.form.validation/required" :text "Field \"Purpose of the project\" is required."} {:type "license" :id 1 :title {:en "CC Attribution 4.0" :fi "CC Nimeä 4.0"} :key "t.form.validation/required" :text "Field \"non-localized link license\" is required."} {:type "license" :id 2 :title {:en "General Terms of Use", :fi "Yleiset käyttöehdot"} :key "t.form.validation/required" :text "Field \"non-localized text license\" is required."}] (:validation cmd-response)))) (testing "retrieving" (let [response (-> (request :get (str "/api/application/" application-id)) (authenticate api-key user-id) app) application (read-body response)] (is (not (:errors application))) (is (= application-id (:id (:application application)))) (is (= "draft" (:state (:application application)))) (is (= 2 (count (:licenses application)))) (is (= 3 (count (:items application)))))) (testing "retrieving as other user" (let [response (-> (request :get (str "/api/application/" application-id)) (authenticate api-key another-user) app) application (read-body response)] (is (= 401 (:status response))))) (testing "saving as other user" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key another-user) (json-body {:command "save" :application-id application-id :items {1 "REST-Test"}}) app)] (is (= 401 (:status response))))) (testing "submitting" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "submit" :application-id application-id :items {1 "REST-Test" 2 "2017-2018" 3 "The purpose is to test this REST service.}"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response)] (is (:success cmd-response)) (is (not (:errors cmd-response))) (is (= application-id (:id cmd-response))) (is (= "applied" (:state cmd-response))) (is (:valid cmd-response)) (is (empty? (:validation cmd-response))))) (testing "approving" (let [response (-> (request :put (str "/api/application/judge")) (authenticate api-key "developer") (json-body {:command "approve" :application-id application-id :round 0 :comment "msg"}) app) cmd-response (read-body response) application-response (-> (request :get (str "/api/application/" application-id)) (authenticate api-key user-id) app) application (:application (read-body application-response))] (is (:success cmd-response)) (is (= "approved" (:state application))) (is (= [nil "msg"] (map :comment (:events application))))))))) (deftest application-validation-test (let [api-key "42" user-id "alice" catid 2] (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :catalogue-items [catid] ;; "" should fail validation just like nil :items {1 ""}}) app) cmd-response (read-body response) validations (:validation cmd-response) application-id (:id cmd-response)] (testing "empty draft" (is (:success cmd-response)) ;; 2 fields, 2 licenses (is (= 4 (count validations))) (is (some #(.contains (:text %) "Project name") validations)) (is (some #(.contains (:text %) "Purpose of the project") validations)) (is (some #(.contains (:text %) "non-localized link license") validations)) (is (some #(.contains (:text %) "non-localized text license") validations))) (testing "add one field" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :application-id application-id :items {1 "FOO"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (:success cmd-response)) (is (not (:valid cmd-response))) (is (= 3 (count validations))))) (testing "add one license" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :application-id application-id :items {1 "FOO"} :licenses {1 "approved"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (:success cmd-response)) (is (not (:valid cmd-response))) (is (= 2 (count validations))))) (testing "submit partial form" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "submit" :application-id application-id :items {1 "FOO"} :licenses {1 "approved"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (not (:success cmd-response))) (is (not (:valid cmd-response))) (is (= 2 (count validations))))) (testing "save full form" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :application-id application-id :items {1 "FOO" 2 "ding" 3 "plong"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (:success cmd-response)) (is (:valid cmd-response)) (is (empty? validations)))) (testing "submit full form" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "submit" :application-id application-id :items {1 "FOO" 2 "ding" 3 "plong"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (:success cmd-response)) (is (:valid cmd-response)) (is (empty? validations))))))) (deftest disabled-catalogue-item (let [api-key "42" user-id "developer" catid 6] (testing "save draft for disabled item" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :catalogue-items [catid] :items {1 ""}}) app) cmd-response (read-body response)] ;; TODO should we actually return a nice error message here? (is (= 400 (:status response)) "should not be able to save draft with disbled item"))) (testing "submit for application with disabled item" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:application-id 6 ;; application-id 6 is already created, but catalogue-item was disabled later :command "submit" :catalogue-items [catid] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response)] (is (= 400 (:status response)) "should not be possible to submit with disabled item"))))) (deftest application-api-roles (let [api-key "42" applicant "alice" approver "developer" catid 2] (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key applicant) (json-body {:command "submit" :catalogue-items [catid] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response) app-id (:id cmd-response)] (is (number? app-id)) (testing "get application as applicant" (let [application (-> (request :get (str "/api/application/" app-id)) (authenticate api-key applicant) app read-body :application)] (is (:can-withdraw? application)) (is (:can-close? application)) (is (not (:can-approve? application))))) (testing "get application as approver" (let [application (-> (request :get (str "/api/application/" app-id)) (authenticate api-key approver) app read-body :application)] (is (not (:can-close? application))) (is (:can-approve? application)))) ;; TODO tests for :review-type (testing "approve application" (is (= 200 (-> (request :put (str "/api/application/judge")) (authenticate api-key approver) (json-body {:command "approve" :application-id app-id :round 0 :comment "msg"}) app :status)))) (testing "get approved application as applicant" (let [application (-> (request :get (str "/api/application/" app-id)) (authenticate api-key applicant) app read-body :application)] (is (:can-close? application)) (is (not (:can-approve? application))))) (testing "get approved application as approver" (let [application (-> (request :get (str "/api/application/" app-id)) (authenticate api-key approver) app read-body :application)] (is (:can-close? application)) (is (not (:can-approve? application)))))))) (deftest application-api-action-test ;; Run through all the application actions that are available (let [api-key "42" user "developer" catid 2 app-id (-> (request :put (str "/api/application/save")) (authenticate api-key user) (json-body {:command "save" :catalogue-items [catid] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app read-body :id) submit (fn [] (is (= 200 (-> (request :put (str "/api/application/save")) (authenticate api-key user) (json-body {:command "submit" :application-id app-id :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app :status)))) action (fn [body] (is (= 200 (-> (request :put (str "/api/application/judge")) (authenticate api-key user) (json-body (merge {:application-id app-id :round 0} body)) app :status))))] (submit) (action {:command "return" :comment "returned"}) (submit) (action {:command "withdraw" :comment "withdrawn"}) (submit) (action {:command "approve" :comment "approved"}) (action {:command "close" :comment "closed"}) (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key user) app read-body :application :events)] (is (= [["apply" nil] ["return" "returned"] ["apply" nil] ["withdraw" "withdrawn"] ["apply" nil] ["approve" "approved"] ["close" "closed"]] (map (juxt :event :comment) events)))))) (deftest application-api-third-party-review-test (let [api-key "42" applicant "alice" approver "developer" reviewer "carl" catid 2 app-id (-> (request :put (str "/api/application/save")) (authenticate api-key applicant) (json-body {:command "submit" :catalogue-items [catid] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app read-body :id)] (testing "fetch reviewers" (let [reviewers (-> (request :get (str "/api/application/reviewers")) (authenticate api-key approver) app read-body)] (is (= ["alice" "bob" "carl" "developer" "owner"] (sort (map :userid reviewers)))) (is (not (contains? (set (map :userid reviewers)) "invalid"))))) (testing "send review request" (is (= 200 (-> (request :put (str "/api/application/review_request")) (authenticate api-key approver) (json-body {:application-id app-id :round 0 :comment "pls revu" :recipients [reviewer]}) app :status)))) (testing "check review event" (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key reviewer) app read-body :application :events)] (is (= [{:userid applicant :comment nil :event "apply"} {:userid reviewer :comment "pls revu" :event "review-request"}] (map #(select-keys % [:userid :comment :event]) events))))) (testing "send review" (is (= 200 (-> (request :put (str "/api/application/judge")) (authenticate api-key reviewer) (json-body {:command "third-party-review" :application-id app-id :round 0 :comment "is ok"}) app :status)))) (testing "events of approver" (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key approver) app read-body :application :events)] (is (= [{:userid applicant :comment nil :event "apply"} {:userid reviewer :comment "pls revu" :event "review-request"} {:userid reviewer :comment "is ok" :event "third-party-review"}] (map #(select-keys % [:userid :comment :event]) events))))) (testing "events of reviewer" (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key reviewer) app read-body :application :events)] (is (= [{:userid applicant :comment nil :event "apply"} {:userid reviewer :comment "pls revu" :event "review-request"} {:userid reviewer :comment "is ok" :event "third-party-review"}] (map #(select-keys % [:userid :comment :event]) events))))) (testing "events of applicant" (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key applicant) app read-body :application :events)] (is (= [{:userid applicant :comment nil :event "apply"} {:userid reviewer :comment nil :event "review-request"} {:userid reviewer :comment nil :event "third-party-review"}] (map #(select-keys % [:userid :comment :event]) events)) "does not see review event comments"))))) ;; TODO non-happy path tests for review? ;; TODO test for event filtering when it gets implemented (defn- strip-cookie-attributes [cookie] (re-find #"[^;]*" cookie)) (defn- get-csrf-token [response] (let [token-regex #"var csrfToken = '([^\']*)'" [_ token] (re-find token-regex (:body response))] token)) (deftest application-api-session-test (let [username "alice" login-headers (-> (request :get "/Shibboleth.sso/Login" {:username username}) app :headers) cookie (-> (get login-headers "Set-Cookie") first strip-cookie-attributes) csrf (-> (request :get "/") (header "Cookie" cookie) app get-csrf-token)] (is cookie) (is csrf) (testing "submit with session" (let [response (-> (request :put (str "/api/application/save")) (header "Cookie" cookie) (header "x-csrf-token" csrf) (json-body {:command "submit" :catalogue-items [2] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app) body (read-body response)] (is (= 200 (:status response))) (is (:success body)))) (testing "submit with session but without csrf" (let [response (-> (request :put (str "/api/application/save")) (header "Cookie" cookie) (json-body {:command "submit" :catalogue-items [2] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app)] (is (= 403 (:status response))))) (testing "submit with session and csrf and wrong api-key" (let [response (-> (request :put (str "/api/application/save")) (header "Cookie" cookie) (header "x-csrf-token" csrf) (header "x-rems-api-key" "WRONG") (json-body {:command "submit" :catalogue-items [2] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app) body (read-body response)] (is (= 401 (:status response))) (is (= "invalid api key" body)))))) (deftest application-api-security-test (testing "fetch application without authentication" (let [response (-> (request :get (str "/api/application/1")) app) body (read-body response)] (is (= body "unauthorized")))) (testing "fetch reviewers without authentication" (let [response (-> (request :get (str "/api/application/reviewers")) app) body (read-body response)] (is (= body "unauthorized")))) (testing "save without authentication" (let [response (-> (request :put (str "/api/application/save")) (json-body {:command "save" :catalogue-items [2] :items {1 "REST-Test"}}) app) body (read-body response)] (is (str/includes? body "Invalid anti-forgery token")))) (testing "save with wrong API-Key" (let [response (-> (request :put (str "/api/application/save")) (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") (json-body {:command "save" :catalogue-items [2] :items {1 "REST-Test"}}) app) body (read-body response)] (is (= "invalid api key" body)))) (testing "judge without authentication" (let [body (-> (request :put (str "/api/application/judge")) (json-body {:command "approve" :application-id 2 :round 0 :comment "msg"}) app read-body)] (is (str/includes? body "Invalid anti-forgery token")))) (testing "judge with wrong API-Key" (let [body (-> (request :put (str "/api/application/judge")) (authenticate "invalid-api-key" "developer") (json-body {:command "approve" :application-id 2 :round 0 :comment "msg"}) app read-body)] (is (= "invalid api key" body)))))
61831
(ns ^:integration rems.test.api.application (:require [clojure.string :as str] [clojure.test :refer :all] [rems.handler :refer [app]] [rems.test.api :refer :all] [rems.test.tempura :refer [fake-tempura-fixture]] [ring.mock.request :refer :all])) (use-fixtures :once fake-tempura-fixture api-fixture) (deftest application-api-test (let [api-key "<KEY>" user-id "alice" another-user "alice_smith" catid 2] (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :catalogue-items [catid] :items {1 "REST-Test"}}) app) cmd-response (read-body response) application-id (:id cmd-response)] (testing "saving" (is (:success cmd-response)) (is (not (:errors cmd-response))) (is (= "draft" (:state cmd-response))) (is (not (:valid cmd-response))) (is (= [{:type "item" :id 2 :title {:en "Purpose of the project" :fi "Projektin tarkoitus"} :key "t.form.validation/required" :text "Field \"Purpose of the project\" is required."} {:type "license" :id 1 :title {:en "CC Attribution 4.0" :fi "CC Nimeä 4.0"} :key "t.form.validation/required" :text "Field \"non-localized link license\" is required."} {:type "license" :id 2 :title {:en "General Terms of Use", :fi "Yleiset käyttöehdot"} :key "t.form.validation/required" :text "Field \"non-localized text license\" is required."}] (:validation cmd-response)))) (testing "retrieving" (let [response (-> (request :get (str "/api/application/" application-id)) (authenticate api-key user-id) app) application (read-body response)] (is (not (:errors application))) (is (= application-id (:id (:application application)))) (is (= "draft" (:state (:application application)))) (is (= 2 (count (:licenses application)))) (is (= 3 (count (:items application)))))) (testing "retrieving as other user" (let [response (-> (request :get (str "/api/application/" application-id)) (authenticate api-key another-user) app) application (read-body response)] (is (= 401 (:status response))))) (testing "saving as other user" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key another-user) (json-body {:command "save" :application-id application-id :items {1 "REST-Test"}}) app)] (is (= 401 (:status response))))) (testing "submitting" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "submit" :application-id application-id :items {1 "REST-Test" 2 "2017-2018" 3 "The purpose is to test this REST service.}"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response)] (is (:success cmd-response)) (is (not (:errors cmd-response))) (is (= application-id (:id cmd-response))) (is (= "applied" (:state cmd-response))) (is (:valid cmd-response)) (is (empty? (:validation cmd-response))))) (testing "approving" (let [response (-> (request :put (str "/api/application/judge")) (authenticate api-key "developer") (json-body {:command "approve" :application-id application-id :round 0 :comment "msg"}) app) cmd-response (read-body response) application-response (-> (request :get (str "/api/application/" application-id)) (authenticate api-key user-id) app) application (:application (read-body application-response))] (is (:success cmd-response)) (is (= "approved" (:state application))) (is (= [nil "msg"] (map :comment (:events application))))))))) (deftest application-validation-test (let [api-key "<KEY>" user-id "alice" catid 2] (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :catalogue-items [catid] ;; "" should fail validation just like nil :items {1 ""}}) app) cmd-response (read-body response) validations (:validation cmd-response) application-id (:id cmd-response)] (testing "empty draft" (is (:success cmd-response)) ;; 2 fields, 2 licenses (is (= 4 (count validations))) (is (some #(.contains (:text %) "Project name") validations)) (is (some #(.contains (:text %) "Purpose of the project") validations)) (is (some #(.contains (:text %) "non-localized link license") validations)) (is (some #(.contains (:text %) "non-localized text license") validations))) (testing "add one field" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :application-id application-id :items {1 "FOO"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (:success cmd-response)) (is (not (:valid cmd-response))) (is (= 3 (count validations))))) (testing "add one license" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :application-id application-id :items {1 "FOO"} :licenses {1 "approved"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (:success cmd-response)) (is (not (:valid cmd-response))) (is (= 2 (count validations))))) (testing "submit partial form" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "submit" :application-id application-id :items {1 "FOO"} :licenses {1 "approved"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (not (:success cmd-response))) (is (not (:valid cmd-response))) (is (= 2 (count validations))))) (testing "save full form" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :application-id application-id :items {1 "FOO" 2 "ding" 3 "plong"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (:success cmd-response)) (is (:valid cmd-response)) (is (empty? validations)))) (testing "submit full form" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "submit" :application-id application-id :items {1 "FOO" 2 "ding" 3 "plong"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (:success cmd-response)) (is (:valid cmd-response)) (is (empty? validations))))))) (deftest disabled-catalogue-item (let [api-key "<KEY>" user-id "developer" catid 6] (testing "save draft for disabled item" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :catalogue-items [catid] :items {1 ""}}) app) cmd-response (read-body response)] ;; TODO should we actually return a nice error message here? (is (= 400 (:status response)) "should not be able to save draft with disbled item"))) (testing "submit for application with disabled item" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:application-id 6 ;; application-id 6 is already created, but catalogue-item was disabled later :command "submit" :catalogue-items [catid] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response)] (is (= 400 (:status response)) "should not be possible to submit with disabled item"))))) (deftest application-api-roles (let [api-key "<KEY>" applicant "alice" approver "developer" catid 2] (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key applicant) (json-body {:command "submit" :catalogue-items [catid] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response) app-id (:id cmd-response)] (is (number? app-id)) (testing "get application as applicant" (let [application (-> (request :get (str "/api/application/" app-id)) (authenticate api-key applicant) app read-body :application)] (is (:can-withdraw? application)) (is (:can-close? application)) (is (not (:can-approve? application))))) (testing "get application as approver" (let [application (-> (request :get (str "/api/application/" app-id)) (authenticate api-key approver) app read-body :application)] (is (not (:can-close? application))) (is (:can-approve? application)))) ;; TODO tests for :review-type (testing "approve application" (is (= 200 (-> (request :put (str "/api/application/judge")) (authenticate api-key approver) (json-body {:command "approve" :application-id app-id :round 0 :comment "msg"}) app :status)))) (testing "get approved application as applicant" (let [application (-> (request :get (str "/api/application/" app-id)) (authenticate api-key applicant) app read-body :application)] (is (:can-close? application)) (is (not (:can-approve? application))))) (testing "get approved application as approver" (let [application (-> (request :get (str "/api/application/" app-id)) (authenticate api-key approver) app read-body :application)] (is (:can-close? application)) (is (not (:can-approve? application)))))))) (deftest application-api-action-test ;; Run through all the application actions that are available (let [api-key "<KEY>" user "developer" catid 2 app-id (-> (request :put (str "/api/application/save")) (authenticate api-key user) (json-body {:command "save" :catalogue-items [catid] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app read-body :id) submit (fn [] (is (= 200 (-> (request :put (str "/api/application/save")) (authenticate api-key user) (json-body {:command "submit" :application-id app-id :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app :status)))) action (fn [body] (is (= 200 (-> (request :put (str "/api/application/judge")) (authenticate api-key user) (json-body (merge {:application-id app-id :round 0} body)) app :status))))] (submit) (action {:command "return" :comment "returned"}) (submit) (action {:command "withdraw" :comment "withdrawn"}) (submit) (action {:command "approve" :comment "approved"}) (action {:command "close" :comment "closed"}) (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key user) app read-body :application :events)] (is (= [["apply" nil] ["return" "returned"] ["apply" nil] ["withdraw" "withdrawn"] ["apply" nil] ["approve" "approved"] ["close" "closed"]] (map (juxt :event :comment) events)))))) (deftest application-api-third-party-review-test (let [api-key "<KEY>" applicant "alice" approver "developer" reviewer "<NAME>" catid 2 app-id (-> (request :put (str "/api/application/save")) (authenticate api-key applicant) (json-body {:command "submit" :catalogue-items [catid] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app read-body :id)] (testing "fetch reviewers" (let [reviewers (-> (request :get (str "/api/application/reviewers")) (authenticate api-key approver) app read-body)] (is (= ["alice" "bob" "<NAME>" "developer" "owner"] (sort (map :userid reviewers)))) (is (not (contains? (set (map :userid reviewers)) "invalid"))))) (testing "send review request" (is (= 200 (-> (request :put (str "/api/application/review_request")) (authenticate api-key approver) (json-body {:application-id app-id :round 0 :comment "pls revu" :recipients [reviewer]}) app :status)))) (testing "check review event" (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key reviewer) app read-body :application :events)] (is (= [{:userid applicant :comment nil :event "apply"} {:userid reviewer :comment "pls revu" :event "review-request"}] (map #(select-keys % [:userid :comment :event]) events))))) (testing "send review" (is (= 200 (-> (request :put (str "/api/application/judge")) (authenticate api-key reviewer) (json-body {:command "third-party-review" :application-id app-id :round 0 :comment "is ok"}) app :status)))) (testing "events of approver" (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key approver) app read-body :application :events)] (is (= [{:userid applicant :comment nil :event "apply"} {:userid reviewer :comment "pls revu" :event "review-request"} {:userid reviewer :comment "is ok" :event "third-party-review"}] (map #(select-keys % [:userid :comment :event]) events))))) (testing "events of reviewer" (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key reviewer) app read-body :application :events)] (is (= [{:userid applicant :comment nil :event "apply"} {:userid reviewer :comment "pls revu" :event "review-request"} {:userid reviewer :comment "is ok" :event "third-party-review"}] (map #(select-keys % [:userid :comment :event]) events))))) (testing "events of applicant" (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key applicant) app read-body :application :events)] (is (= [{:userid applicant :comment nil :event "apply"} {:userid reviewer :comment nil :event "review-request"} {:userid reviewer :comment nil :event "third-party-review"}] (map #(select-keys % [:userid :comment :event]) events)) "does not see review event comments"))))) ;; TODO non-happy path tests for review? ;; TODO test for event filtering when it gets implemented (defn- strip-cookie-attributes [cookie] (re-find #"[^;]*" cookie)) (defn- get-csrf-token [response] (let [token-regex #"var csrfToken = '([^\']*)'" [_ token] (re-find token-regex (:body response))] token)) (deftest application-api-session-test (let [username "alice" login-headers (-> (request :get "/Shibboleth.sso/Login" {:username username}) app :headers) cookie (-> (get login-headers "Set-Cookie") first strip-cookie-attributes) csrf (-> (request :get "/") (header "Cookie" cookie) app get-csrf-token)] (is cookie) (is csrf) (testing "submit with session" (let [response (-> (request :put (str "/api/application/save")) (header "Cookie" cookie) (header "x-csrf-token" csrf) (json-body {:command "submit" :catalogue-items [2] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app) body (read-body response)] (is (= 200 (:status response))) (is (:success body)))) (testing "submit with session but without csrf" (let [response (-> (request :put (str "/api/application/save")) (header "Cookie" cookie) (json-body {:command "submit" :catalogue-items [2] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app)] (is (= 403 (:status response))))) (testing "submit with session and csrf and wrong api-key" (let [response (-> (request :put (str "/api/application/save")) (header "Cookie" cookie) (header "x-csrf-token" csrf) (header "x-rems-api-key" "WRONG") (json-body {:command "submit" :catalogue-items [2] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app) body (read-body response)] (is (= 401 (:status response))) (is (= "invalid api key" body)))))) (deftest application-api-security-test (testing "fetch application without authentication" (let [response (-> (request :get (str "/api/application/1")) app) body (read-body response)] (is (= body "unauthorized")))) (testing "fetch reviewers without authentication" (let [response (-> (request :get (str "/api/application/reviewers")) app) body (read-body response)] (is (= body "unauthorized")))) (testing "save without authentication" (let [response (-> (request :put (str "/api/application/save")) (json-body {:command "save" :catalogue-items [2] :items {1 "REST-Test"}}) app) body (read-body response)] (is (str/includes? body "Invalid anti-forgery token")))) (testing "save with wrong API-Key" (let [response (-> (request :put (str "/api/application/save")) (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") (json-body {:command "save" :catalogue-items [2] :items {1 "REST-Test"}}) app) body (read-body response)] (is (= "invalid api key" body)))) (testing "judge without authentication" (let [body (-> (request :put (str "/api/application/judge")) (json-body {:command "approve" :application-id 2 :round 0 :comment "msg"}) app read-body)] (is (str/includes? body "Invalid anti-forgery token")))) (testing "judge with wrong API-Key" (let [body (-> (request :put (str "/api/application/judge")) (authenticate "invalid-api-key" "developer") (json-body {:command "approve" :application-id 2 :round 0 :comment "msg"}) app read-body)] (is (= "invalid api key" body)))))
true
(ns ^:integration rems.test.api.application (:require [clojure.string :as str] [clojure.test :refer :all] [rems.handler :refer [app]] [rems.test.api :refer :all] [rems.test.tempura :refer [fake-tempura-fixture]] [ring.mock.request :refer :all])) (use-fixtures :once fake-tempura-fixture api-fixture) (deftest application-api-test (let [api-key "PI:KEY:<KEY>END_PI" user-id "alice" another-user "alice_smith" catid 2] (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :catalogue-items [catid] :items {1 "REST-Test"}}) app) cmd-response (read-body response) application-id (:id cmd-response)] (testing "saving" (is (:success cmd-response)) (is (not (:errors cmd-response))) (is (= "draft" (:state cmd-response))) (is (not (:valid cmd-response))) (is (= [{:type "item" :id 2 :title {:en "Purpose of the project" :fi "Projektin tarkoitus"} :key "t.form.validation/required" :text "Field \"Purpose of the project\" is required."} {:type "license" :id 1 :title {:en "CC Attribution 4.0" :fi "CC Nimeä 4.0"} :key "t.form.validation/required" :text "Field \"non-localized link license\" is required."} {:type "license" :id 2 :title {:en "General Terms of Use", :fi "Yleiset käyttöehdot"} :key "t.form.validation/required" :text "Field \"non-localized text license\" is required."}] (:validation cmd-response)))) (testing "retrieving" (let [response (-> (request :get (str "/api/application/" application-id)) (authenticate api-key user-id) app) application (read-body response)] (is (not (:errors application))) (is (= application-id (:id (:application application)))) (is (= "draft" (:state (:application application)))) (is (= 2 (count (:licenses application)))) (is (= 3 (count (:items application)))))) (testing "retrieving as other user" (let [response (-> (request :get (str "/api/application/" application-id)) (authenticate api-key another-user) app) application (read-body response)] (is (= 401 (:status response))))) (testing "saving as other user" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key another-user) (json-body {:command "save" :application-id application-id :items {1 "REST-Test"}}) app)] (is (= 401 (:status response))))) (testing "submitting" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "submit" :application-id application-id :items {1 "REST-Test" 2 "2017-2018" 3 "The purpose is to test this REST service.}"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response)] (is (:success cmd-response)) (is (not (:errors cmd-response))) (is (= application-id (:id cmd-response))) (is (= "applied" (:state cmd-response))) (is (:valid cmd-response)) (is (empty? (:validation cmd-response))))) (testing "approving" (let [response (-> (request :put (str "/api/application/judge")) (authenticate api-key "developer") (json-body {:command "approve" :application-id application-id :round 0 :comment "msg"}) app) cmd-response (read-body response) application-response (-> (request :get (str "/api/application/" application-id)) (authenticate api-key user-id) app) application (:application (read-body application-response))] (is (:success cmd-response)) (is (= "approved" (:state application))) (is (= [nil "msg"] (map :comment (:events application))))))))) (deftest application-validation-test (let [api-key "PI:KEY:<KEY>END_PI" user-id "alice" catid 2] (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :catalogue-items [catid] ;; "" should fail validation just like nil :items {1 ""}}) app) cmd-response (read-body response) validations (:validation cmd-response) application-id (:id cmd-response)] (testing "empty draft" (is (:success cmd-response)) ;; 2 fields, 2 licenses (is (= 4 (count validations))) (is (some #(.contains (:text %) "Project name") validations)) (is (some #(.contains (:text %) "Purpose of the project") validations)) (is (some #(.contains (:text %) "non-localized link license") validations)) (is (some #(.contains (:text %) "non-localized text license") validations))) (testing "add one field" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :application-id application-id :items {1 "FOO"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (:success cmd-response)) (is (not (:valid cmd-response))) (is (= 3 (count validations))))) (testing "add one license" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :application-id application-id :items {1 "FOO"} :licenses {1 "approved"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (:success cmd-response)) (is (not (:valid cmd-response))) (is (= 2 (count validations))))) (testing "submit partial form" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "submit" :application-id application-id :items {1 "FOO"} :licenses {1 "approved"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (not (:success cmd-response))) (is (not (:valid cmd-response))) (is (= 2 (count validations))))) (testing "save full form" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :application-id application-id :items {1 "FOO" 2 "ding" 3 "plong"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (:success cmd-response)) (is (:valid cmd-response)) (is (empty? validations)))) (testing "submit full form" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "submit" :application-id application-id :items {1 "FOO" 2 "ding" 3 "plong"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response) validations (:validation cmd-response)] (is (:success cmd-response)) (is (:valid cmd-response)) (is (empty? validations))))))) (deftest disabled-catalogue-item (let [api-key "PI:KEY:<KEY>END_PI" user-id "developer" catid 6] (testing "save draft for disabled item" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:command "save" :catalogue-items [catid] :items {1 ""}}) app) cmd-response (read-body response)] ;; TODO should we actually return a nice error message here? (is (= 400 (:status response)) "should not be able to save draft with disbled item"))) (testing "submit for application with disabled item" (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key user-id) (json-body {:application-id 6 ;; application-id 6 is already created, but catalogue-item was disabled later :command "submit" :catalogue-items [catid] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response)] (is (= 400 (:status response)) "should not be possible to submit with disabled item"))))) (deftest application-api-roles (let [api-key "PI:KEY:<KEY>END_PI" applicant "alice" approver "developer" catid 2] (let [response (-> (request :put (str "/api/application/save")) (authenticate api-key applicant) (json-body {:command "submit" :catalogue-items [catid] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app) cmd-response (read-body response) app-id (:id cmd-response)] (is (number? app-id)) (testing "get application as applicant" (let [application (-> (request :get (str "/api/application/" app-id)) (authenticate api-key applicant) app read-body :application)] (is (:can-withdraw? application)) (is (:can-close? application)) (is (not (:can-approve? application))))) (testing "get application as approver" (let [application (-> (request :get (str "/api/application/" app-id)) (authenticate api-key approver) app read-body :application)] (is (not (:can-close? application))) (is (:can-approve? application)))) ;; TODO tests for :review-type (testing "approve application" (is (= 200 (-> (request :put (str "/api/application/judge")) (authenticate api-key approver) (json-body {:command "approve" :application-id app-id :round 0 :comment "msg"}) app :status)))) (testing "get approved application as applicant" (let [application (-> (request :get (str "/api/application/" app-id)) (authenticate api-key applicant) app read-body :application)] (is (:can-close? application)) (is (not (:can-approve? application))))) (testing "get approved application as approver" (let [application (-> (request :get (str "/api/application/" app-id)) (authenticate api-key approver) app read-body :application)] (is (:can-close? application)) (is (not (:can-approve? application)))))))) (deftest application-api-action-test ;; Run through all the application actions that are available (let [api-key "PI:KEY:<KEY>END_PI" user "developer" catid 2 app-id (-> (request :put (str "/api/application/save")) (authenticate api-key user) (json-body {:command "save" :catalogue-items [catid] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app read-body :id) submit (fn [] (is (= 200 (-> (request :put (str "/api/application/save")) (authenticate api-key user) (json-body {:command "submit" :application-id app-id :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app :status)))) action (fn [body] (is (= 200 (-> (request :put (str "/api/application/judge")) (authenticate api-key user) (json-body (merge {:application-id app-id :round 0} body)) app :status))))] (submit) (action {:command "return" :comment "returned"}) (submit) (action {:command "withdraw" :comment "withdrawn"}) (submit) (action {:command "approve" :comment "approved"}) (action {:command "close" :comment "closed"}) (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key user) app read-body :application :events)] (is (= [["apply" nil] ["return" "returned"] ["apply" nil] ["withdraw" "withdrawn"] ["apply" nil] ["approve" "approved"] ["close" "closed"]] (map (juxt :event :comment) events)))))) (deftest application-api-third-party-review-test (let [api-key "PI:KEY:<KEY>END_PI" applicant "alice" approver "developer" reviewer "PI:NAME:<NAME>END_PI" catid 2 app-id (-> (request :put (str "/api/application/save")) (authenticate api-key applicant) (json-body {:command "submit" :catalogue-items [catid] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app read-body :id)] (testing "fetch reviewers" (let [reviewers (-> (request :get (str "/api/application/reviewers")) (authenticate api-key approver) app read-body)] (is (= ["alice" "bob" "PI:NAME:<NAME>END_PI" "developer" "owner"] (sort (map :userid reviewers)))) (is (not (contains? (set (map :userid reviewers)) "invalid"))))) (testing "send review request" (is (= 200 (-> (request :put (str "/api/application/review_request")) (authenticate api-key approver) (json-body {:application-id app-id :round 0 :comment "pls revu" :recipients [reviewer]}) app :status)))) (testing "check review event" (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key reviewer) app read-body :application :events)] (is (= [{:userid applicant :comment nil :event "apply"} {:userid reviewer :comment "pls revu" :event "review-request"}] (map #(select-keys % [:userid :comment :event]) events))))) (testing "send review" (is (= 200 (-> (request :put (str "/api/application/judge")) (authenticate api-key reviewer) (json-body {:command "third-party-review" :application-id app-id :round 0 :comment "is ok"}) app :status)))) (testing "events of approver" (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key approver) app read-body :application :events)] (is (= [{:userid applicant :comment nil :event "apply"} {:userid reviewer :comment "pls revu" :event "review-request"} {:userid reviewer :comment "is ok" :event "third-party-review"}] (map #(select-keys % [:userid :comment :event]) events))))) (testing "events of reviewer" (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key reviewer) app read-body :application :events)] (is (= [{:userid applicant :comment nil :event "apply"} {:userid reviewer :comment "pls revu" :event "review-request"} {:userid reviewer :comment "is ok" :event "third-party-review"}] (map #(select-keys % [:userid :comment :event]) events))))) (testing "events of applicant" (let [events (-> (request :get (str "/api/application/" app-id)) (authenticate api-key applicant) app read-body :application :events)] (is (= [{:userid applicant :comment nil :event "apply"} {:userid reviewer :comment nil :event "review-request"} {:userid reviewer :comment nil :event "third-party-review"}] (map #(select-keys % [:userid :comment :event]) events)) "does not see review event comments"))))) ;; TODO non-happy path tests for review? ;; TODO test for event filtering when it gets implemented (defn- strip-cookie-attributes [cookie] (re-find #"[^;]*" cookie)) (defn- get-csrf-token [response] (let [token-regex #"var csrfToken = '([^\']*)'" [_ token] (re-find token-regex (:body response))] token)) (deftest application-api-session-test (let [username "alice" login-headers (-> (request :get "/Shibboleth.sso/Login" {:username username}) app :headers) cookie (-> (get login-headers "Set-Cookie") first strip-cookie-attributes) csrf (-> (request :get "/") (header "Cookie" cookie) app get-csrf-token)] (is cookie) (is csrf) (testing "submit with session" (let [response (-> (request :put (str "/api/application/save")) (header "Cookie" cookie) (header "x-csrf-token" csrf) (json-body {:command "submit" :catalogue-items [2] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app) body (read-body response)] (is (= 200 (:status response))) (is (:success body)))) (testing "submit with session but without csrf" (let [response (-> (request :put (str "/api/application/save")) (header "Cookie" cookie) (json-body {:command "submit" :catalogue-items [2] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app)] (is (= 403 (:status response))))) (testing "submit with session and csrf and wrong api-key" (let [response (-> (request :put (str "/api/application/save")) (header "Cookie" cookie) (header "x-csrf-token" csrf) (header "x-rems-api-key" "WRONG") (json-body {:command "submit" :catalogue-items [2] :items {1 "x" 2 "y" 3 "z"} :licenses {1 "approved" 2 "approved"}}) app) body (read-body response)] (is (= 401 (:status response))) (is (= "invalid api key" body)))))) (deftest application-api-security-test (testing "fetch application without authentication" (let [response (-> (request :get (str "/api/application/1")) app) body (read-body response)] (is (= body "unauthorized")))) (testing "fetch reviewers without authentication" (let [response (-> (request :get (str "/api/application/reviewers")) app) body (read-body response)] (is (= body "unauthorized")))) (testing "save without authentication" (let [response (-> (request :put (str "/api/application/save")) (json-body {:command "save" :catalogue-items [2] :items {1 "REST-Test"}}) app) body (read-body response)] (is (str/includes? body "Invalid anti-forgery token")))) (testing "save with wrong API-Key" (let [response (-> (request :put (str "/api/application/save")) (assoc-in [:headers "x-rems-api-key"] "invalid-api-key") (json-body {:command "save" :catalogue-items [2] :items {1 "REST-Test"}}) app) body (read-body response)] (is (= "invalid api key" body)))) (testing "judge without authentication" (let [body (-> (request :put (str "/api/application/judge")) (json-body {:command "approve" :application-id 2 :round 0 :comment "msg"}) app read-body)] (is (str/includes? body "Invalid anti-forgery token")))) (testing "judge with wrong API-Key" (let [body (-> (request :put (str "/api/application/judge")) (authenticate "invalid-api-key" "developer") (json-body {:command "approve" :application-id 2 :round 0 :comment "msg"}) app read-body)] (is (= "invalid api key" body)))))
[ { "context": " :port 27017\n :name \"netrunner\"}\n :web/app (ig/ref :mongodb/connection)\n :we", "end": 951, "score": 0.9830710887908936, "start": 942, "tag": "USERNAME", "value": "netrunner" }, { "context": " {} (:cards fmt))))\n\n(defmethod ig/init-key :jinteki/cards [_ {:keys [db]}]\n (let [cards (mc/find-map", "end": 3115, "score": 0.9657986760139465, "start": 3108, "tag": "KEY", "value": "jinteki" } ]
src/clj/web/system.clj
kjchiu/netrunner
0
(ns web.system (:require [web.config :refer [frontend-version server-mode]] [clj-time.format :as f] [game.cards.agendas] [game.cards.assets] [game.cards.basic] [game.cards.events] [game.cards.hardware] [game.cards.ice] [game.cards.identities] [game.cards.operations] [game.cards.programs] [game.cards.resources] [game.cards.upgrades] [game.quotes :refer [load-quotes!]] [integrant.core :as ig] [jinteki.cards :as cards] [monger.collection :as mc] [monger.core :as mg] [org.httpkit.server :refer [run-server server-stop!]] [taoensso.sente :as sente] [web.angel-arena :as angel-arena] [web.api :refer [make-app]] [web.lobby :as lobby] [web.utils :refer [tick]] [web.ws :refer [ch-chsk event-msg-handler]])) (defn build-config [] {:mongodb/connection {:address "localhost" :port 27017 :name "netrunner"} :web/app (ig/ref :mongodb/connection) :web/server {:port 1042 :app (ig/ref :web/app)} :web/lobby {:interval 1000 :mongo (ig/ref :mongodb/connection) :time-inactive 1800} :frontend-version (ig/ref :mongodb/connection) :server-mode "dev" :sente/router nil :game/quotes nil :jinteki/cards (ig/ref :mongodb/connection)}) (defmethod ig/init-key :mongodb/connection [_ opts] (let [{:keys [address port name]} opts] (mg/connect-via-uri (str "mongodb://" address ":" port "/" name)))) (defmethod ig/halt-key! :mongodb/connection [_ {:keys [conn]}] (mg/disconnect conn)) (defmethod ig/init-key :web/app [_ opts] (make-app opts)) (defmethod ig/init-key :web/server [_ {:keys [app port]}] (run-server app {:port port :legacy-return-value? false})) (defmethod ig/halt-key! :web/server [_ server] (when server (server-stop! server nil))) (defmethod ig/init-key :web/lobby [_ {:keys [interval mongo time-inactive]}] (let [db (:db mongo)] [(tick #(lobby/clear-inactive-lobbies db time-inactive) interval) (tick #(angel-arena/check-for-inactivity db) interval) (tick #(lobby/reset-send-lobby) interval)])) (defmethod ig/halt-key! :web/lobby [_ futures] (run! future-cancel futures)) (defmethod ig/init-key :frontend-version [_ {:keys [db]}] (if-let [config (mc/find-one-as-map db "config" nil)] (reset! frontend-version (:version config)) (-> db (mc/create "config" nil) (mc/insert "config" {:version @frontend-version :cards-version 0})))) (defmethod ig/init-key :server-mode [_ mode] (reset! server-mode mode)) (defmethod ig/init-key :sente/router [_ _opts] (sente/start-server-chsk-router! ch-chsk event-msg-handler)) (defmethod ig/halt-key! :sente/router [_ stop-fn] (when (fn? stop-fn) (stop-fn))) (defmethod ig/init-key :game/quotes [_ _opts] (load-quotes!)) (defn- format-card-key->string [fmt] (assoc fmt :cards (reduce-kv (fn [m k v] (assoc m (name k) v)) {} (:cards fmt)))) (defmethod ig/init-key :jinteki/cards [_ {:keys [db]}] (let [cards (mc/find-maps db "cards" nil) stripped-cards (map #(update % :_id str) cards) all-cards (into {} (map (juxt :title identity) stripped-cards)) sets (mc/find-maps db "sets" nil) cycles (mc/find-maps db "cycles" nil) mwl (mc/find-maps db "mwls" nil) latest-mwl (->> mwl (map (fn [e] (update e :date-start #(f/parse (f/formatters :date) %)))) (group-by #(keyword (:format %))) (mapv (fn [[k, v]] [k (->> v (sort-by :date-start) (last) (format-card-key->string))])) (into {}))] (reset! cards/all-cards all-cards) (reset! cards/sets sets) (reset! cards/cycles cycles) (reset! cards/mwl latest-mwl) {:all-cards all-cards :sets sets :cycles cycles :mwl latest-mwl})) (defmethod ig/halt-key! :jinteki/cards [_ _opts] (reset! cards/all-cards nil) (reset! cards/sets nil) (reset! cards/cycles nil) (reset! cards/mwl nil)) (defn start [& [{:keys [only]}]] (let [config (build-config)] (if only (ig/init config only) (ig/init config)))) (defn stop [system & [{:keys [only]}]] (when system (if only (ig/halt! system only) (ig/halt! system))) nil) (comment (def system (start)) (stop system) )
38125
(ns web.system (:require [web.config :refer [frontend-version server-mode]] [clj-time.format :as f] [game.cards.agendas] [game.cards.assets] [game.cards.basic] [game.cards.events] [game.cards.hardware] [game.cards.ice] [game.cards.identities] [game.cards.operations] [game.cards.programs] [game.cards.resources] [game.cards.upgrades] [game.quotes :refer [load-quotes!]] [integrant.core :as ig] [jinteki.cards :as cards] [monger.collection :as mc] [monger.core :as mg] [org.httpkit.server :refer [run-server server-stop!]] [taoensso.sente :as sente] [web.angel-arena :as angel-arena] [web.api :refer [make-app]] [web.lobby :as lobby] [web.utils :refer [tick]] [web.ws :refer [ch-chsk event-msg-handler]])) (defn build-config [] {:mongodb/connection {:address "localhost" :port 27017 :name "netrunner"} :web/app (ig/ref :mongodb/connection) :web/server {:port 1042 :app (ig/ref :web/app)} :web/lobby {:interval 1000 :mongo (ig/ref :mongodb/connection) :time-inactive 1800} :frontend-version (ig/ref :mongodb/connection) :server-mode "dev" :sente/router nil :game/quotes nil :jinteki/cards (ig/ref :mongodb/connection)}) (defmethod ig/init-key :mongodb/connection [_ opts] (let [{:keys [address port name]} opts] (mg/connect-via-uri (str "mongodb://" address ":" port "/" name)))) (defmethod ig/halt-key! :mongodb/connection [_ {:keys [conn]}] (mg/disconnect conn)) (defmethod ig/init-key :web/app [_ opts] (make-app opts)) (defmethod ig/init-key :web/server [_ {:keys [app port]}] (run-server app {:port port :legacy-return-value? false})) (defmethod ig/halt-key! :web/server [_ server] (when server (server-stop! server nil))) (defmethod ig/init-key :web/lobby [_ {:keys [interval mongo time-inactive]}] (let [db (:db mongo)] [(tick #(lobby/clear-inactive-lobbies db time-inactive) interval) (tick #(angel-arena/check-for-inactivity db) interval) (tick #(lobby/reset-send-lobby) interval)])) (defmethod ig/halt-key! :web/lobby [_ futures] (run! future-cancel futures)) (defmethod ig/init-key :frontend-version [_ {:keys [db]}] (if-let [config (mc/find-one-as-map db "config" nil)] (reset! frontend-version (:version config)) (-> db (mc/create "config" nil) (mc/insert "config" {:version @frontend-version :cards-version 0})))) (defmethod ig/init-key :server-mode [_ mode] (reset! server-mode mode)) (defmethod ig/init-key :sente/router [_ _opts] (sente/start-server-chsk-router! ch-chsk event-msg-handler)) (defmethod ig/halt-key! :sente/router [_ stop-fn] (when (fn? stop-fn) (stop-fn))) (defmethod ig/init-key :game/quotes [_ _opts] (load-quotes!)) (defn- format-card-key->string [fmt] (assoc fmt :cards (reduce-kv (fn [m k v] (assoc m (name k) v)) {} (:cards fmt)))) (defmethod ig/init-key :<KEY>/cards [_ {:keys [db]}] (let [cards (mc/find-maps db "cards" nil) stripped-cards (map #(update % :_id str) cards) all-cards (into {} (map (juxt :title identity) stripped-cards)) sets (mc/find-maps db "sets" nil) cycles (mc/find-maps db "cycles" nil) mwl (mc/find-maps db "mwls" nil) latest-mwl (->> mwl (map (fn [e] (update e :date-start #(f/parse (f/formatters :date) %)))) (group-by #(keyword (:format %))) (mapv (fn [[k, v]] [k (->> v (sort-by :date-start) (last) (format-card-key->string))])) (into {}))] (reset! cards/all-cards all-cards) (reset! cards/sets sets) (reset! cards/cycles cycles) (reset! cards/mwl latest-mwl) {:all-cards all-cards :sets sets :cycles cycles :mwl latest-mwl})) (defmethod ig/halt-key! :jinteki/cards [_ _opts] (reset! cards/all-cards nil) (reset! cards/sets nil) (reset! cards/cycles nil) (reset! cards/mwl nil)) (defn start [& [{:keys [only]}]] (let [config (build-config)] (if only (ig/init config only) (ig/init config)))) (defn stop [system & [{:keys [only]}]] (when system (if only (ig/halt! system only) (ig/halt! system))) nil) (comment (def system (start)) (stop system) )
true
(ns web.system (:require [web.config :refer [frontend-version server-mode]] [clj-time.format :as f] [game.cards.agendas] [game.cards.assets] [game.cards.basic] [game.cards.events] [game.cards.hardware] [game.cards.ice] [game.cards.identities] [game.cards.operations] [game.cards.programs] [game.cards.resources] [game.cards.upgrades] [game.quotes :refer [load-quotes!]] [integrant.core :as ig] [jinteki.cards :as cards] [monger.collection :as mc] [monger.core :as mg] [org.httpkit.server :refer [run-server server-stop!]] [taoensso.sente :as sente] [web.angel-arena :as angel-arena] [web.api :refer [make-app]] [web.lobby :as lobby] [web.utils :refer [tick]] [web.ws :refer [ch-chsk event-msg-handler]])) (defn build-config [] {:mongodb/connection {:address "localhost" :port 27017 :name "netrunner"} :web/app (ig/ref :mongodb/connection) :web/server {:port 1042 :app (ig/ref :web/app)} :web/lobby {:interval 1000 :mongo (ig/ref :mongodb/connection) :time-inactive 1800} :frontend-version (ig/ref :mongodb/connection) :server-mode "dev" :sente/router nil :game/quotes nil :jinteki/cards (ig/ref :mongodb/connection)}) (defmethod ig/init-key :mongodb/connection [_ opts] (let [{:keys [address port name]} opts] (mg/connect-via-uri (str "mongodb://" address ":" port "/" name)))) (defmethod ig/halt-key! :mongodb/connection [_ {:keys [conn]}] (mg/disconnect conn)) (defmethod ig/init-key :web/app [_ opts] (make-app opts)) (defmethod ig/init-key :web/server [_ {:keys [app port]}] (run-server app {:port port :legacy-return-value? false})) (defmethod ig/halt-key! :web/server [_ server] (when server (server-stop! server nil))) (defmethod ig/init-key :web/lobby [_ {:keys [interval mongo time-inactive]}] (let [db (:db mongo)] [(tick #(lobby/clear-inactive-lobbies db time-inactive) interval) (tick #(angel-arena/check-for-inactivity db) interval) (tick #(lobby/reset-send-lobby) interval)])) (defmethod ig/halt-key! :web/lobby [_ futures] (run! future-cancel futures)) (defmethod ig/init-key :frontend-version [_ {:keys [db]}] (if-let [config (mc/find-one-as-map db "config" nil)] (reset! frontend-version (:version config)) (-> db (mc/create "config" nil) (mc/insert "config" {:version @frontend-version :cards-version 0})))) (defmethod ig/init-key :server-mode [_ mode] (reset! server-mode mode)) (defmethod ig/init-key :sente/router [_ _opts] (sente/start-server-chsk-router! ch-chsk event-msg-handler)) (defmethod ig/halt-key! :sente/router [_ stop-fn] (when (fn? stop-fn) (stop-fn))) (defmethod ig/init-key :game/quotes [_ _opts] (load-quotes!)) (defn- format-card-key->string [fmt] (assoc fmt :cards (reduce-kv (fn [m k v] (assoc m (name k) v)) {} (:cards fmt)))) (defmethod ig/init-key :PI:KEY:<KEY>END_PI/cards [_ {:keys [db]}] (let [cards (mc/find-maps db "cards" nil) stripped-cards (map #(update % :_id str) cards) all-cards (into {} (map (juxt :title identity) stripped-cards)) sets (mc/find-maps db "sets" nil) cycles (mc/find-maps db "cycles" nil) mwl (mc/find-maps db "mwls" nil) latest-mwl (->> mwl (map (fn [e] (update e :date-start #(f/parse (f/formatters :date) %)))) (group-by #(keyword (:format %))) (mapv (fn [[k, v]] [k (->> v (sort-by :date-start) (last) (format-card-key->string))])) (into {}))] (reset! cards/all-cards all-cards) (reset! cards/sets sets) (reset! cards/cycles cycles) (reset! cards/mwl latest-mwl) {:all-cards all-cards :sets sets :cycles cycles :mwl latest-mwl})) (defmethod ig/halt-key! :jinteki/cards [_ _opts] (reset! cards/all-cards nil) (reset! cards/sets nil) (reset! cards/cycles nil) (reset! cards/mwl nil)) (defn start [& [{:keys [only]}]] (let [config (build-config)] (if only (ig/init config only) (ig/init config)))) (defn stop [system & [{:keys [only]}]] (when system (if only (ig/halt! system only) (ig/halt! system))) nil) (comment (def system (start)) (stop system) )
[ { "context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License", "end": 49, "score": 0.9998816251754761, "start": 37, "tag": "NAME", "value": "Ronen Narkis" }, { "context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,\n Version ", "end": 62, "score": 0.8627559542655945, "start": 51, "tag": "EMAIL", "value": "narkisr.com" }, { "context": " (throw+ {:type ::non-legal-env :message (<< \"~{username} tried to query in ~{es} he has access only to ~{", "end": 2200, "score": 0.5987381935119629, "start": 2192, "tag": "USERNAME", "value": "username" } ]
src/es/systems.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 es.systems "Systems indexing/searching" (:refer-clojure :exclude [get]) (:require [es.common :refer (flush- index map-env-terms clear initialize)] [es.node :as node :refer (ES)] [clojure.set :refer (subset?)] [clojure.core.strint :refer (<<)] [slingshot.slingshot :refer [throw+]] [re-core.persistency.users :as u] [re-core.common :refer (envs import-logging)] [re-core.roles :refer (su?)] [clojurewerkz.elastisch.query :as q] [clojurewerkz.elastisch.native.document :as doc])) (import-logging) (def ^:dynamic flush? false) (defmacro set-flush [flush* & body] `(binding [flush? ~flush*] ~@body)) (defn put "Add/Update a system into ES" [id system] (doc/put @ES index "system" id system) (when flush? (flush-))) (defn delete "delete a system from ES" [id & {:keys [flush?]}] (doc/delete @ES index "system" id) (when flush? (flush-))) (defn get "Grabs a system by an id" [id] (doc/get @ES index "system" id)) (defn query "basic query string" [query & {:keys [from size] :or {size 100 from 0}}] (doc/search @ES index "system" { :from from :size size :query query :fields ["owner" "env"] })) (defn query-envs [q] (into #{} (filter identity (map #(keyword (get-in % [:term :env])) (get-in q [:bool :should]))))) (defn envs-set "Set should envs on query" [q {:keys [envs username]}] (let [es (query-envs q)] (if-not (empty? es) (if (subset? es (into #{} envs)) (map-env-terms q) (throw+ {:type ::non-legal-env :message (<< "~{username} tried to query in ~{es} he has access only to ~{envs}")})) (update-in q [:bool :should] (fn [v] (into v (mapv #(hash-map :term {:env (name %)}) envs))))))) (defn- query-for [username q] (let [{:keys [envs username] :as user} (u/get-user! username)] (if (su? user) (-> q (envs-set user) (assoc-in [:bool :minimum_should_match] 1)) (update-in q [:bool :must] (fn [v] (into v {:term {"owner" username}})))))) (defn systems-for "grabs all the systems ids that this user can manipulate from ES" [username q from size] (info "query for" (query-for username q)) (query (query-for username q) :from from :size size)) (defn re-index "Re-indexes a bulk of systems" [systems] (clear) (initialize) (doseq [[id s] systems] (put id s)) (let [[id s] (first systems)] (put id s)))
12915
(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 es.systems "Systems indexing/searching" (:refer-clojure :exclude [get]) (:require [es.common :refer (flush- index map-env-terms clear initialize)] [es.node :as node :refer (ES)] [clojure.set :refer (subset?)] [clojure.core.strint :refer (<<)] [slingshot.slingshot :refer [throw+]] [re-core.persistency.users :as u] [re-core.common :refer (envs import-logging)] [re-core.roles :refer (su?)] [clojurewerkz.elastisch.query :as q] [clojurewerkz.elastisch.native.document :as doc])) (import-logging) (def ^:dynamic flush? false) (defmacro set-flush [flush* & body] `(binding [flush? ~flush*] ~@body)) (defn put "Add/Update a system into ES" [id system] (doc/put @ES index "system" id system) (when flush? (flush-))) (defn delete "delete a system from ES" [id & {:keys [flush?]}] (doc/delete @ES index "system" id) (when flush? (flush-))) (defn get "Grabs a system by an id" [id] (doc/get @ES index "system" id)) (defn query "basic query string" [query & {:keys [from size] :or {size 100 from 0}}] (doc/search @ES index "system" { :from from :size size :query query :fields ["owner" "env"] })) (defn query-envs [q] (into #{} (filter identity (map #(keyword (get-in % [:term :env])) (get-in q [:bool :should]))))) (defn envs-set "Set should envs on query" [q {:keys [envs username]}] (let [es (query-envs q)] (if-not (empty? es) (if (subset? es (into #{} envs)) (map-env-terms q) (throw+ {:type ::non-legal-env :message (<< "~{username} tried to query in ~{es} he has access only to ~{envs}")})) (update-in q [:bool :should] (fn [v] (into v (mapv #(hash-map :term {:env (name %)}) envs))))))) (defn- query-for [username q] (let [{:keys [envs username] :as user} (u/get-user! username)] (if (su? user) (-> q (envs-set user) (assoc-in [:bool :minimum_should_match] 1)) (update-in q [:bool :must] (fn [v] (into v {:term {"owner" username}})))))) (defn systems-for "grabs all the systems ids that this user can manipulate from ES" [username q from size] (info "query for" (query-for username q)) (query (query-for username q) :from from :size size)) (defn re-index "Re-indexes a bulk of systems" [systems] (clear) (initialize) (doseq [[id s] systems] (put id s)) (let [[id s] (first systems)] (put id s)))
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 es.systems "Systems indexing/searching" (:refer-clojure :exclude [get]) (:require [es.common :refer (flush- index map-env-terms clear initialize)] [es.node :as node :refer (ES)] [clojure.set :refer (subset?)] [clojure.core.strint :refer (<<)] [slingshot.slingshot :refer [throw+]] [re-core.persistency.users :as u] [re-core.common :refer (envs import-logging)] [re-core.roles :refer (su?)] [clojurewerkz.elastisch.query :as q] [clojurewerkz.elastisch.native.document :as doc])) (import-logging) (def ^:dynamic flush? false) (defmacro set-flush [flush* & body] `(binding [flush? ~flush*] ~@body)) (defn put "Add/Update a system into ES" [id system] (doc/put @ES index "system" id system) (when flush? (flush-))) (defn delete "delete a system from ES" [id & {:keys [flush?]}] (doc/delete @ES index "system" id) (when flush? (flush-))) (defn get "Grabs a system by an id" [id] (doc/get @ES index "system" id)) (defn query "basic query string" [query & {:keys [from size] :or {size 100 from 0}}] (doc/search @ES index "system" { :from from :size size :query query :fields ["owner" "env"] })) (defn query-envs [q] (into #{} (filter identity (map #(keyword (get-in % [:term :env])) (get-in q [:bool :should]))))) (defn envs-set "Set should envs on query" [q {:keys [envs username]}] (let [es (query-envs q)] (if-not (empty? es) (if (subset? es (into #{} envs)) (map-env-terms q) (throw+ {:type ::non-legal-env :message (<< "~{username} tried to query in ~{es} he has access only to ~{envs}")})) (update-in q [:bool :should] (fn [v] (into v (mapv #(hash-map :term {:env (name %)}) envs))))))) (defn- query-for [username q] (let [{:keys [envs username] :as user} (u/get-user! username)] (if (su? user) (-> q (envs-set user) (assoc-in [:bool :minimum_should_match] 1)) (update-in q [:bool :must] (fn [v] (into v {:term {"owner" username}})))))) (defn systems-for "grabs all the systems ids that this user can manipulate from ES" [username q from size] (info "query for" (query-for username q)) (query (query-for username q) :from from :size size)) (defn re-index "Re-indexes a bulk of systems" [systems] (clear) (initialize) (doseq [[id s] systems] (put id s)) (let [[id s] (first systems)] (put id s)))
[ { "context": "euler.net>\n;; Problem: 1\n;; Solution: 3\n;; Author: Sean Broderick <hakutsuru@mac.com>\n;; Date: 2015-06-09\n\n\n(def th", "end": 98, "score": 0.9998761415481567, "start": 84, "tag": "NAME", "value": "Sean Broderick" }, { "context": "blem: 1\n;; Solution: 3\n;; Author: Sean Broderick <hakutsuru@mac.com>\n;; Date: 2015-06-09\n\n\n(def threshold (Integer/pa", "end": 117, "score": 0.9999340176582336, "start": 100, "tag": "EMAIL", "value": "hakutsuru@mac.com" } ]
solutions/clojure/pe_001_03.clj
hakutsuru/euler_001
0
;; Project Euler <https://projecteuler.net> ;; Problem: 1 ;; Solution: 3 ;; Author: Sean Broderick <hakutsuru@mac.com> ;; Date: 2015-06-09 (def threshold (Integer/parseInt (second *command-line-args*))) ;; whole-number summation ;; ((n^2)/2) + (n/2) (defn summation_to_number [x] (quot (+ (* x x) x) 2)) (def sum03 (* 3 (summation_to_number (quot threshold 3)))) (def sum05 (* 5 (summation_to_number (quot threshold 5)))) (def sum15 (* 15 (summation_to_number (quot threshold 15)))) (def sum (+ sum03 sum05 (- sum15))) (println sum) ;; Result (sum): ;; /opt/euler/clojure$ lein exec pe_001_03.clj 9 ;; 23 ;; /opt/euler/clojure$ lein exec pe_001_03.clj 999 ;; 233168 ;; /opt/euler/clojure$ lein exec pe_001_03.clj 999999 ;; 233333166668
110926
;; Project Euler <https://projecteuler.net> ;; Problem: 1 ;; Solution: 3 ;; Author: <NAME> <<EMAIL>> ;; Date: 2015-06-09 (def threshold (Integer/parseInt (second *command-line-args*))) ;; whole-number summation ;; ((n^2)/2) + (n/2) (defn summation_to_number [x] (quot (+ (* x x) x) 2)) (def sum03 (* 3 (summation_to_number (quot threshold 3)))) (def sum05 (* 5 (summation_to_number (quot threshold 5)))) (def sum15 (* 15 (summation_to_number (quot threshold 15)))) (def sum (+ sum03 sum05 (- sum15))) (println sum) ;; Result (sum): ;; /opt/euler/clojure$ lein exec pe_001_03.clj 9 ;; 23 ;; /opt/euler/clojure$ lein exec pe_001_03.clj 999 ;; 233168 ;; /opt/euler/clojure$ lein exec pe_001_03.clj 999999 ;; 233333166668
true
;; Project Euler <https://projecteuler.net> ;; Problem: 1 ;; Solution: 3 ;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; Date: 2015-06-09 (def threshold (Integer/parseInt (second *command-line-args*))) ;; whole-number summation ;; ((n^2)/2) + (n/2) (defn summation_to_number [x] (quot (+ (* x x) x) 2)) (def sum03 (* 3 (summation_to_number (quot threshold 3)))) (def sum05 (* 5 (summation_to_number (quot threshold 5)))) (def sum15 (* 15 (summation_to_number (quot threshold 15)))) (def sum (+ sum03 sum05 (- sum15))) (println sum) ;; Result (sum): ;; /opt/euler/clojure$ lein exec pe_001_03.clj 9 ;; 23 ;; /opt/euler/clojure$ lein exec pe_001_03.clj 999 ;; 233168 ;; /opt/euler/clojure$ lein exec pe_001_03.clj 999999 ;; 233333166668
[ { "context": "nt-longest-path input-graph)\n (let [node-name \"Author\"\n og-nodes (ug/nodes input-graph)\n ", "end": 2397, "score": 0.9990679621696472, "start": 2391, "tag": "NAME", "value": "Author" } ]
2015/day13/src/day13/main.clj
Anatolij-Grigorjev/AdventOfCode
0
(ns day13.main (:require [aoc-commons.core :refer :all]) (:require [clojure.string :as str]) (:require [ubergraph.core :as ug])) (defn word-sign [word] (case word "gain" 1 "lose" -1)) (defn items-pairs-ring [col] (let [start-finish-pairs (partition 2 1 col) first-node ((comp first first) start-finish-pairs) last-node ((comp last last) start-finish-pairs)] (conj (apply vector start-finish-pairs) [last-node first-node]))) (defn parse-people-relations [line] (let [sentence-words (str/split line #"\s") person-sitting (first sentence-words) points-sign (word-sign (nth sentence-words 2)) points-amount (* points-sign (parse-int (nth sentence-words 3))) next-to-person (apply str (butlast (last sentence-words)))] [person-sitting next-to-person points-amount])) (defn segment-length [g [node1 node2]] (let [ edge (ug/find-edge g node1 node2) weight (ug/weight g edge)] weight)) (defn segments-lengths [g node-pairs] (map (partial segment-length g) node-pairs)) (defn invert-pairs [col] (map reverse (reverse col))) (defn total-path-length [g nodes] (let [nodes-ring (items-pairs-ring nodes) segment-lengths-fwd (doall (segments-lengths g nodes-ring)) segment-lengths-back (doall (segments-lengths g (invert-pairs nodes-ring)))] (reduce + (concat segment-lengths-fwd segment-lengths-back)))) (defn all-paths [g] (let [node-lists (permutations (ug/nodes g))] (map #(vector % (total-path-length g %)) node-lists))) (defn path->str [path-pair] (let [nodes (first path-pair) ring-nodes (conj (apply vector nodes) (first nodes))] (str "longest 2-way path is: " ring-nodes " -> " (second path-pair)))) (defn calc-longest-path [g] (let [all-paths-map (all-paths g) longest-path (max-by second all-paths-map)] longest-path)) (defn calc-print-longest-path [g] (let [longest-path (calc-longest-path g)] (println (path->str longest-path)))) (defn build-graph [path] (apply ug/multidigraph (read-input-lines parse-people-relations path))) (defn edges-weight-0 [nodes-from nodes-to] (map (fn [node1 node2] [node1 node2 0]) nodes-from nodes-to)) (defn -main [& args] (let [path (first args) input-graph (build-graph path)] (ug/pprint input-graph) (calc-print-longest-path input-graph) (let [node-name "Author" og-nodes (ug/nodes input-graph) repeated-new-node (repeat (count og-nodes) node-name) graph-with-author (ug/add-nodes input-graph node-name) graph-connected (ug/add-directed-edges* graph-with-author (concat (edges-weight-0 repeated-new-node og-nodes) (edges-weight-0 og-nodes repeated-new-node)))] (ug/pprint graph-connected) (calc-print-longest-path graph-connected))))
7987
(ns day13.main (:require [aoc-commons.core :refer :all]) (:require [clojure.string :as str]) (:require [ubergraph.core :as ug])) (defn word-sign [word] (case word "gain" 1 "lose" -1)) (defn items-pairs-ring [col] (let [start-finish-pairs (partition 2 1 col) first-node ((comp first first) start-finish-pairs) last-node ((comp last last) start-finish-pairs)] (conj (apply vector start-finish-pairs) [last-node first-node]))) (defn parse-people-relations [line] (let [sentence-words (str/split line #"\s") person-sitting (first sentence-words) points-sign (word-sign (nth sentence-words 2)) points-amount (* points-sign (parse-int (nth sentence-words 3))) next-to-person (apply str (butlast (last sentence-words)))] [person-sitting next-to-person points-amount])) (defn segment-length [g [node1 node2]] (let [ edge (ug/find-edge g node1 node2) weight (ug/weight g edge)] weight)) (defn segments-lengths [g node-pairs] (map (partial segment-length g) node-pairs)) (defn invert-pairs [col] (map reverse (reverse col))) (defn total-path-length [g nodes] (let [nodes-ring (items-pairs-ring nodes) segment-lengths-fwd (doall (segments-lengths g nodes-ring)) segment-lengths-back (doall (segments-lengths g (invert-pairs nodes-ring)))] (reduce + (concat segment-lengths-fwd segment-lengths-back)))) (defn all-paths [g] (let [node-lists (permutations (ug/nodes g))] (map #(vector % (total-path-length g %)) node-lists))) (defn path->str [path-pair] (let [nodes (first path-pair) ring-nodes (conj (apply vector nodes) (first nodes))] (str "longest 2-way path is: " ring-nodes " -> " (second path-pair)))) (defn calc-longest-path [g] (let [all-paths-map (all-paths g) longest-path (max-by second all-paths-map)] longest-path)) (defn calc-print-longest-path [g] (let [longest-path (calc-longest-path g)] (println (path->str longest-path)))) (defn build-graph [path] (apply ug/multidigraph (read-input-lines parse-people-relations path))) (defn edges-weight-0 [nodes-from nodes-to] (map (fn [node1 node2] [node1 node2 0]) nodes-from nodes-to)) (defn -main [& args] (let [path (first args) input-graph (build-graph path)] (ug/pprint input-graph) (calc-print-longest-path input-graph) (let [node-name "<NAME>" og-nodes (ug/nodes input-graph) repeated-new-node (repeat (count og-nodes) node-name) graph-with-author (ug/add-nodes input-graph node-name) graph-connected (ug/add-directed-edges* graph-with-author (concat (edges-weight-0 repeated-new-node og-nodes) (edges-weight-0 og-nodes repeated-new-node)))] (ug/pprint graph-connected) (calc-print-longest-path graph-connected))))
true
(ns day13.main (:require [aoc-commons.core :refer :all]) (:require [clojure.string :as str]) (:require [ubergraph.core :as ug])) (defn word-sign [word] (case word "gain" 1 "lose" -1)) (defn items-pairs-ring [col] (let [start-finish-pairs (partition 2 1 col) first-node ((comp first first) start-finish-pairs) last-node ((comp last last) start-finish-pairs)] (conj (apply vector start-finish-pairs) [last-node first-node]))) (defn parse-people-relations [line] (let [sentence-words (str/split line #"\s") person-sitting (first sentence-words) points-sign (word-sign (nth sentence-words 2)) points-amount (* points-sign (parse-int (nth sentence-words 3))) next-to-person (apply str (butlast (last sentence-words)))] [person-sitting next-to-person points-amount])) (defn segment-length [g [node1 node2]] (let [ edge (ug/find-edge g node1 node2) weight (ug/weight g edge)] weight)) (defn segments-lengths [g node-pairs] (map (partial segment-length g) node-pairs)) (defn invert-pairs [col] (map reverse (reverse col))) (defn total-path-length [g nodes] (let [nodes-ring (items-pairs-ring nodes) segment-lengths-fwd (doall (segments-lengths g nodes-ring)) segment-lengths-back (doall (segments-lengths g (invert-pairs nodes-ring)))] (reduce + (concat segment-lengths-fwd segment-lengths-back)))) (defn all-paths [g] (let [node-lists (permutations (ug/nodes g))] (map #(vector % (total-path-length g %)) node-lists))) (defn path->str [path-pair] (let [nodes (first path-pair) ring-nodes (conj (apply vector nodes) (first nodes))] (str "longest 2-way path is: " ring-nodes " -> " (second path-pair)))) (defn calc-longest-path [g] (let [all-paths-map (all-paths g) longest-path (max-by second all-paths-map)] longest-path)) (defn calc-print-longest-path [g] (let [longest-path (calc-longest-path g)] (println (path->str longest-path)))) (defn build-graph [path] (apply ug/multidigraph (read-input-lines parse-people-relations path))) (defn edges-weight-0 [nodes-from nodes-to] (map (fn [node1 node2] [node1 node2 0]) nodes-from nodes-to)) (defn -main [& args] (let [path (first args) input-graph (build-graph path)] (ug/pprint input-graph) (calc-print-longest-path input-graph) (let [node-name "PI:NAME:<NAME>END_PI" og-nodes (ug/nodes input-graph) repeated-new-node (repeat (count og-nodes) node-name) graph-with-author (ug/add-nodes input-graph node-name) graph-connected (ug/add-directed-edges* graph-with-author (concat (edges-weight-0 repeated-new-node og-nodes) (edges-weight-0 og-nodes repeated-new-node)))] (ug/pprint graph-connected) (calc-print-longest-path graph-connected))))
[ { "context": ":id 1 :name \"root\" :expanded true} [{:id 2 :name \"Herlev\" :expanded true} [{:id 3 :name \"Akut\" :expanded f", "end": 1810, "score": 0.9994907975196838, "start": 1804, "tag": "NAME", "value": "Herlev" }, { "context": "d 2 :name \"Herlev\" :expanded true} [{:id 3 :name \"Akut\" :expanded false} {:id 4 :name \"Sandkas\" :expande", "end": 1847, "score": 0.9994474649429321, "start": 1843, "tag": "NAME", "value": "Akut" }, { "context": ":id 3 :name \"Akut\" :expanded false} {:id 4 :name \"Sandkas\" :expanded false}]] {:id 5 :name \"hive\" :expanded", "end": 1887, "score": 0.9994897842407227, "start": 1880, "tag": "NAME", "value": "Sandkas" }, { "context": " :name \"Sandkas\" :expanded false}]] {:id 5 :name \"hive\" :expanded false}]))\n", "end": 1926, "score": 0.9784020781517029, "start": 1922, "tag": "NAME", "value": "hive" } ]
src/cljs/reframe_test/handlers.cljs
jargon/ts-admin
0
(ns reframe-test.handlers (:require [re-frame.core :as re-frame] [reframe-test.db :as db] [clojure.zip :as zip])) (defn- edit-group-node [zipper id edit-fn & args] (let [match? (fn [loc] (and (not (zip/branch? loc)) (= (:id (zip/node loc)) id)))] (loop [loc zipper] (when (not (zip/end? loc)) (if (match? loc) (zip/root (apply zip/edit loc edit-fn args)) (recur (zip/next loc))))))) (def common-middlewares (if ^boolean goog.DEBUG (comp re-frame/debug (re-frame/after db/valid-schema?)) [])) (re-frame/register-handler :initialize-db common-middlewares (fn [_ _] db/default-db)) (re-frame/register-handler :load-users common-middlewares (fn [appdb _] (merge appdb {:initialized true, :users db/dummy-users}))) (re-frame/register-handler :load-groups common-middlewares (fn [appdb _] (let [root (first db/dummy-groups) groups (db/build-group-map db/dummy-groups) hierarchy (db/build-group-hierarchy root 0 true db/dummy-groups)] (merge appdb {:groups-initialized true :groups groups :group-hierarchy hierarchy :location [:groups]})))) (re-frame/register-handler :toggle-group-row common-middlewares (fn [appdb [_ group-id expand]] (let [groups (zip/vector-zip (:group-hierarchy appdb))] (if-let [new-groups (edit-group-node groups group-id assoc :expanded expand)] (assoc appdb :group-hierarchy new-groups) appdb)))) (re-frame/register-handler :navigate-to common-middlewares (fn [appdb view-and-args] (assoc appdb :location (subvec view-and-args 1)))) (def zipper1 (zip/vector-zip [{:id 1 :name "root" :expanded true} [{:id 2 :name "Herlev" :expanded true} [{:id 3 :name "Akut" :expanded false} {:id 4 :name "Sandkas" :expanded false}]] {:id 5 :name "hive" :expanded false}]))
22000
(ns reframe-test.handlers (:require [re-frame.core :as re-frame] [reframe-test.db :as db] [clojure.zip :as zip])) (defn- edit-group-node [zipper id edit-fn & args] (let [match? (fn [loc] (and (not (zip/branch? loc)) (= (:id (zip/node loc)) id)))] (loop [loc zipper] (when (not (zip/end? loc)) (if (match? loc) (zip/root (apply zip/edit loc edit-fn args)) (recur (zip/next loc))))))) (def common-middlewares (if ^boolean goog.DEBUG (comp re-frame/debug (re-frame/after db/valid-schema?)) [])) (re-frame/register-handler :initialize-db common-middlewares (fn [_ _] db/default-db)) (re-frame/register-handler :load-users common-middlewares (fn [appdb _] (merge appdb {:initialized true, :users db/dummy-users}))) (re-frame/register-handler :load-groups common-middlewares (fn [appdb _] (let [root (first db/dummy-groups) groups (db/build-group-map db/dummy-groups) hierarchy (db/build-group-hierarchy root 0 true db/dummy-groups)] (merge appdb {:groups-initialized true :groups groups :group-hierarchy hierarchy :location [:groups]})))) (re-frame/register-handler :toggle-group-row common-middlewares (fn [appdb [_ group-id expand]] (let [groups (zip/vector-zip (:group-hierarchy appdb))] (if-let [new-groups (edit-group-node groups group-id assoc :expanded expand)] (assoc appdb :group-hierarchy new-groups) appdb)))) (re-frame/register-handler :navigate-to common-middlewares (fn [appdb view-and-args] (assoc appdb :location (subvec view-and-args 1)))) (def zipper1 (zip/vector-zip [{:id 1 :name "root" :expanded true} [{:id 2 :name "<NAME>" :expanded true} [{:id 3 :name "<NAME>" :expanded false} {:id 4 :name "<NAME>" :expanded false}]] {:id 5 :name "<NAME>" :expanded false}]))
true
(ns reframe-test.handlers (:require [re-frame.core :as re-frame] [reframe-test.db :as db] [clojure.zip :as zip])) (defn- edit-group-node [zipper id edit-fn & args] (let [match? (fn [loc] (and (not (zip/branch? loc)) (= (:id (zip/node loc)) id)))] (loop [loc zipper] (when (not (zip/end? loc)) (if (match? loc) (zip/root (apply zip/edit loc edit-fn args)) (recur (zip/next loc))))))) (def common-middlewares (if ^boolean goog.DEBUG (comp re-frame/debug (re-frame/after db/valid-schema?)) [])) (re-frame/register-handler :initialize-db common-middlewares (fn [_ _] db/default-db)) (re-frame/register-handler :load-users common-middlewares (fn [appdb _] (merge appdb {:initialized true, :users db/dummy-users}))) (re-frame/register-handler :load-groups common-middlewares (fn [appdb _] (let [root (first db/dummy-groups) groups (db/build-group-map db/dummy-groups) hierarchy (db/build-group-hierarchy root 0 true db/dummy-groups)] (merge appdb {:groups-initialized true :groups groups :group-hierarchy hierarchy :location [:groups]})))) (re-frame/register-handler :toggle-group-row common-middlewares (fn [appdb [_ group-id expand]] (let [groups (zip/vector-zip (:group-hierarchy appdb))] (if-let [new-groups (edit-group-node groups group-id assoc :expanded expand)] (assoc appdb :group-hierarchy new-groups) appdb)))) (re-frame/register-handler :navigate-to common-middlewares (fn [appdb view-and-args] (assoc appdb :location (subvec view-and-args 1)))) (def zipper1 (zip/vector-zip [{:id 1 :name "root" :expanded true} [{:id 2 :name "PI:NAME:<NAME>END_PI" :expanded true} [{:id 3 :name "PI:NAME:<NAME>END_PI" :expanded false} {:id 4 :name "PI:NAME:<NAME>END_PI" :expanded false}]] {:id 5 :name "PI:NAME:<NAME>END_PI" :expanded false}]))
[ { "context": " \"postgresql\"\n :subname \"//127.0.0.1:5432/hugtest\"\n :user \"hugt", "end": 797, "score": 0.9996014833450317, "start": 788, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": ".0.1:5432/hugtest\"\n :user \"hugtest\"\n :password \"hugtest\"}\n\n ", "end": 850, "score": 0.806989848613739, "start": 843, "tag": "USERNAME", "value": "hugtest" }, { "context": "user \"hugtest\"\n :password \"hugtest\"}\n\n ;; mysql -u root -p\n ;; mys", "end": 894, "score": 0.9994316697120667, "start": 887, "tag": "PASSWORD", "value": "hugtest" }, { "context": "ubprotocol \"mysql\"\n :subname \"//127.0.0.1:3306/hugtest?useSSL=false\"\n :us", "end": 1132, "score": 0.9995840787887573, "start": 1123, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "6/hugtest?useSSL=false\"\n :user \"hugtest\"\n :password \"hugtest\"}\n\n ", "end": 1193, "score": 0.8971338868141174, "start": 1186, "tag": "USERNAME", "value": "hugtest" }, { "context": " :user \"hugtest\"\n :password \"hugtest\"}\n\n :sqlite {:subprotocol \"sqlite\"\n ", "end": 1232, "score": 0.9994415640830994, "start": 1225, "tag": "PASSWORD", "value": "hugtest" }, { "context": "elect * from test\\nwhere id = ?\\nand name = ?\" 1 \"Ed\"]\n (multi-value-params-sqlvec {:id 1 :n", "end": 3367, "score": 0.9936065673828125, "start": 3365, "tag": "NAME", "value": "Ed" }, { "context": " (multi-value-params-sqlvec {:id 1 :name \"Ed\"})))\n (is (= [\"select * from test\\nwhere id in", "end": 3424, "score": 0.9940820932388306, "start": 3422, "tag": "NAME", "value": "Ed" }, { "context": "nto test (id, name)\\nvalues (?,?),(?,?),(?,?)\" 1 \"Ed\" 2 \"Al\" 3 \"Bo\"]\n (tuple-param-list-sqlv", "end": 3737, "score": 0.9851540327072144, "start": 3735, "tag": "NAME", "value": "Ed" }, { "context": " (tuple-param-list-sqlvec {:people [[1 \"Ed\"] [2 \"Al\"] [3 \"Bo\"]]})))\n (is (= [\"select * fr", "end": 3806, "score": 0.9944597482681274, "start": 3804, "tag": "NAME", "value": "Ed" }, { "context": " (tuple-param-list-sqlvec {:people [[1 \"Ed\"] [2 \"Al\"] [3 \"Bo\"]]})))\n (is (= [\"select * from test\"]", "end": 3815, "score": 0.9432278275489807, "start": 3813, "tag": "NAME", "value": "Al" }, { "context": "param-list-sqlvec {:people [[1 \"Ed\"] [2 \"Al\"] [3 \"Bo\"]]})))\n (is (= [\"select * from test\"]\n ", "end": 3824, "score": 0.8372550010681152, "start": 3822, "tag": "NAME", "value": "Bo" } ]
hugsql-core/test/hugsql/core_test.clj
bwalex/hugsql
0
(ns hugsql.core-test (:require [clojure.test :refer :all] [hugsql.core :as hugsql] [hugsql.adapter] [hugsql.adapter.clojure-java-jdbc :as cjj-adapter] [hugsql.adapter.clojure-jdbc :as cj-adapter] [clojure.java.io :as io]) (:import [clojure.lang ExceptionInfo])) (def adapters {:clojure.java.jdbc (cjj-adapter/hugsql-adapter-clojure-java-jdbc) :clojure.jdbc (cj-adapter/hugsql-adapter-clojure-jdbc)}) (def tmpdir (System/getProperty "java.io.tmpdir")) (def dbs { ;; sudo su - postgres ;; switch to postgres user ;; createuser -P hugtest ;; enter "hugtest" when prompted ;; createdb -O hugtest hugtest :postgresql {:subprotocol "postgresql" :subname "//127.0.0.1:5432/hugtest" :user "hugtest" :password "hugtest"} ;; mysql -u root -p ;; mysql> create database hugtest; ;; mysql> grant all on hugtest.* to hugtest identified by "hugtest"; :mysql {:subprotocol "mysql" :subname "//127.0.0.1:3306/hugtest?useSSL=false" :user "hugtest" :password "hugtest"} :sqlite {:subprotocol "sqlite" :subname (str tmpdir "/hugtest.sqlite")} :h2 {:subprotocol "h2" :subname (str tmpdir "/hugtest.h2")} :hsqldb {:subprotocol "hsqldb" :subname (str tmpdir "/hugtest.hsqldb")} :derby {:subprotocol "derby" :subname (str tmpdir "/hugtest.derby") :create true} }) ;; Call def-db-fns outside of deftest so that namespace is 'hugsql.core-test ;; Use a file path in the classpath (hugsql/def-db-fns "hugsql/sql/test.sql") (hugsql/def-sqlvec-fns "hugsql/sql/test.sql") ;; Use a java.io.File object (let [tmpfile (io/file (str tmpdir "/test.sql"))] (io/copy (io/file (io/resource "hugsql/sql/test2.sql")) tmpfile) (hugsql/def-db-fns tmpfile)) ;; Use a string (def hugsql-string-defs (str "-- :name test3-select\n select * from test3" "-- :snip snip1\n select *")) (hugsql/def-db-fns-from-string hugsql-string-defs) (deftest core (testing "adapter was not set during fn def" (is (= nil @hugsql/adapter))) (testing "File outside of classpath with java.io.File worked" (is (fn? test2-select))) (testing "defs from string worked" (is (fn? test3-select)) (is (fn? snip1))) (testing "sql file does not exist/can't be read" (is (thrown-with-msg? ExceptionInfo #"Can not read file" (eval '(hugsql.core/def-db-fns "non/existent/file.sql"))))) (testing "fn definition" (is (fn? no-params-select)) (is (fn? no-params-select-sqlvec)) (is (= "No params" (:doc (meta #'no-params-select)))) (is (= "No params (sqlvec)" (:doc (meta #'no-params-select-sqlvec)))) (is (= "hugsql/sql/test.sql" (:file (meta #'no-params-select)))) (is (= 6 (:line (meta #'no-params-select))))) (testing "sql fns" (is (= ["select * from test"] (no-params-select-sqlvec))) (is (= ["select * from test"] (no-params-select-sqlvec {}))) (is (= ["select * from test where id = ?" 1] (one-value-param-sqlvec {:id 1}))) (is (= ["select * from test\nwhere id = ?\nand name = ?" 1 "Ed"] (multi-value-params-sqlvec {:id 1 :name "Ed"}))) (is (= ["select * from test\nwhere id in (?,?,?)" 1 2 3] (value-list-param-sqlvec {:ids [1,2,3]}))) (is (= ["select * from test\nwhere (id, name) = (?,?)" 1 "A"] (tuple-param-sqlvec {:id-name [1 "A"]}))) (is (= ["insert into test (id, name)\nvalues (?,?),(?,?),(?,?)" 1 "Ed" 2 "Al" 3 "Bo"] (tuple-param-list-sqlvec {:people [[1 "Ed"] [2 "Al"] [3 "Bo"]]}))) (is (= ["select * from test"] (identifier-param-sqlvec {:table-name "test"}))) (is (= ["select id, name from test"] (identifier-param-list-sqlvec {:columns ["id", "name"]}))) (is (= ["select * from test as my_test"] (identifier-param-sqlvec {:table-name ["test" "my_test"]}))) (is (= ["select id as my_id, name as my_name from test"] (identifier-param-list-sqlvec {:columns [["id" "my_id"], ["name" "my_name"]]}))) (is (= ["select * from test as my_test"] (identifier-param-sqlvec {:table-name {"test" "my_test"}}))) (is (let [r (identifier-param-list-sqlvec {:columns {"id" "my_id" "name" "my_name"}})] (or (= r ["select id as my_id, name as my_name from test"]) (= r ["select name as my_name, id as my_id from test"])))) (is (= ["select * from test order by id desc"] (sql-param-sqlvec {:id-order "desc"})))) (testing "identifier quoting" (is (= ["select * from \"schema\".\"te\"\"st\""] (identifier-param-sqlvec {:table-name "schema.te\"st"} {:quoting :ansi}))) (is (= ["select * from \"schema\".\"te\"\"st\" as \"my.test\""] (identifier-param-sqlvec {:table-name ["schema.te\"st" "my.test"]} {:quoting :ansi}))) (is (= ["select * from `schema`.`te``st`"] (identifier-param-sqlvec {:table-name "schema.te`st"} {:quoting :mysql}))) (is (= ["select * from [schema].[te]]st]"] (identifier-param-sqlvec {:table-name "schema.te]st"} {:quoting :mssql}))) (is (= ["select \"test\".\"id\", \"test\".\"name\" from test"] (identifier-param-list-sqlvec {:columns ["test.id", "test.name"]} {:quoting :ansi}))) (is (= ["select \"test\".\"id\" as \"my.id\", \"test\".\"name\" as \"my.name\" from test"] (identifier-param-list-sqlvec {:columns [["test.id" "my.id"], ["test.name" "my.name"]]} {:quoting :ansi}))) (is (= ["select `test`.`id`, `test`.`name` from test"] (identifier-param-list-sqlvec {:columns ["test.id", "test.name"]} {:quoting :mysql}))) (is (= ["select [test].[id], [test].[name] from test"] (identifier-param-list-sqlvec {:columns ["test.id", "test.name"]} {:quoting :mssql})))) (testing "sqlvec" (is (= ["select * from test where id = ?" 1] (hugsql/sqlvec "select * from test where id = :id" {:id 1})))) (testing "Snippets" (is (= ["select id, name"] (select-snip {:cols ["id","name"]}))) (is (= ["from test"] (from-snip {:tables ["test"]}))) (is (= ["select id, name\nfrom test\nwhere id = ? or id = ?\norder by id" 1 2] (snip-query-sqlvec {:select (select-snip {:cols ["id","name"]}) :from (from-snip {:tables ["test"]}) :where (where-snip {:cond [(cond-snip {:conj "" :cond ["id" "=" 1]}) (cond-snip {:conj "or" :cond ["id" "=" 2]})]}) :order (order-snip {:fields ["id"]})})))) (testing "metadata" (is (:private (meta #'a-private-fn))) (is (:private (meta #'another-private-fn))) (is (= 1 (:one (meta #'user-meta)))) (is (= 2 (:two (meta #'user-meta))))) (testing "command & result as metadata" (is (= :? (:command (meta #'select-one-test-by-id)))) (is (= :1 (:result (meta #'select-one-test-by-id)))) (is (= :? (:command (meta #'a-private-fn)))) (is (= :* (:result (meta #'a-private-fn))))) (testing "map of fns" (let [db-fns (hugsql/map-of-db-fns "hugsql/sql/test.sql") sql-fns (hugsql/map-of-sqlvec-fns "hugsql/sql/test.sql") db-fns-str (hugsql/map-of-db-fns-from-string hugsql-string-defs) sql-fns-str (hugsql/map-of-sqlvec-fns-from-string hugsql-string-defs)] (is (fn? (get-in db-fns [:one-value-param :fn]))) (is (fn? (get-in db-fns [:select-snip :fn]))) (is (= "One value param" (get-in db-fns [:one-value-param :meta :doc]))) (is (not (get-in db-fns [:one-value-param :meta :snip?]))) (is (get-in db-fns [:select-snip :meta :snip?])) (is (fn? (get-in sql-fns [:one-value-param-sqlvec :fn]))) (is (fn? (get-in sql-fns [:select-snip :fn]))) (is (= "One value param (sqlvec)" (get-in sql-fns [:one-value-param-sqlvec :meta :doc]))) (is (fn? (get-in db-fns-str [:test3-select :fn]))) (is (fn? (get-in sql-fns-str [:test3-select-sqlvec :fn]))))) (testing "missing header :name, :name-, :snip, or :snip-" (is (thrown-with-msg? ExceptionInfo #"Missing HugSQL Header of " (hugsql/def-db-fns-from-string "-- :name: almost-a-yesql-name-hdr\nselect * from test")))) (testing "nil header :name, :name-, :snip, or :snip-" (is (thrown-with-msg? ExceptionInfo #"HugSQL Header .* not given." (hugsql/def-db-fns-from-string "-- :name \nselect * from test")))) (testing "value parameters allow vectors for ISQLParameter/etc overrides" (is (= ["insert into test (id, myarr) values (?, ?)" 1 [1 2 3]] (hugsql/sqlvec "insert into test (id, myarr) values (:id, :v:myarr)" {:id 1 :myarr [1 2 3]}))) (is (= ["insert into test (id, myarr) values (?,?),(?,?)" 1 [1 2 3] 2 [4 5 6]] (hugsql/sqlvec "insert into test (id, myarr) values :t*:records" {:records [[1 [1 2 3]] [2 [4 5 6]]]})))) (testing "spacing around Raw SQL parameters" (is (= ["select col_1 from test"] (hugsql/sqlvec "select col_:sql:col_num from test" {:col_num 1})))) (doseq [[db-name db] dbs] (doseq [[adapter-name adapter] adapters] (testing "adapter set" (is (satisfies? hugsql.adapter/HugsqlAdapter (hugsql/set-adapter! adapter)))) (testing "parameter placeholder vs data mismatch" (is (thrown-with-msg? ExceptionInfo #"Parameter Mismatch: :id parameter data not found." (one-value-param-sqlvec {:x 1}))) (is (thrown-with-msg? ExceptionInfo #"Parameter Mismatch: :id parameter data not found." (one-value-param db {:x 1}))) ;; does not throw on false (is (= ["select * from test where id = ?" false] (one-value-param-sqlvec {:id false}))) ;; deep-get check (is (thrown-with-msg? ExceptionInfo #"Parameter Mismatch: :emps.0.id parameter data not found." (hugsql/sqlvec "select * from emp where id = :emps.0.id" {:emps [{:not-id 1}]})))) (testing "database commands/queries" (condp = db-name :mysql (is (= 0 (create-test-table-mysql db))) :h2 (is (= 0 (create-test-table-h2 db))) :hsqldb (is (= 0 (create-test-table-hsqldb db))) (is (= 0 (create-test-table db)))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (testing "tuple" ;; tuple use is not supported by certain dbs (when (not-any? #(= % db-name) [:derby :sqlite :hsqldb]) (is (= [{:id 1 :name "A"}] (tuple-param db {:id-name [1 "A"]}))))) (testing "insert multiple values" ;; only hsqldb appears to not support multi-insert values for :tuple* (when (not (= db-name :hsqldb)) (is (= 3 (insert-multi-into-test-table db {:values [[4 "D"] [5 "E"] [6 "F"]]}))))) (testing "returning" ;; returning support is lacking in many dbs (when (not-any? #(= % db-name) [:mysql :h2 :derby :sqlite :hsqldb]) (is (= [{:id 7}] (insert-into-test-table-returning db {:id 7 :name "G"}))))) (testing "insert w/ return of .getGeneratedKeys" ;; return generated keys, which has varying support and return values ;; clojure.java.jdbc returns a hashmap, clojure.jdbc returns a vector of hashmaps (when (= adapter-name :clojure.java.jdbc) (condp = db-name :postgresql (is (= {:id 8 :name "H"} (insert-into-test-table-return-keys db {:id 8 :name "H"} {}))) :mysql (is (= {:generated_key 9} (insert-into-test-table-return-keys db {:id 9 :name "I"}))) :sqlite (is (= {(keyword "last_insert_rowid()") 10} (insert-into-test-table-return-keys db {:id 10 :name "J"} {}))) :h2 (is (= {(keyword "scope_identity()") 11} (insert-into-test-table-return-keys db {:id 11 :name "J"} {}))) ;; hsql and derby don't seem to support .getGeneratedKeys nil)) (when (= adapter-name :clojure.jdbc) (condp = db-name :postgresql (is (= [{:id 8 :name "H"}] (insert-into-test-table-return-keys db {:id 8 :name "H"} {}))) :mysql (is (= [{:generated_key 9}] (insert-into-test-table-return-keys db {:id 9 :name "I"}))) :sqlite (is (= [{(keyword "last_insert_rowid()") 10}] (insert-into-test-table-return-keys db {:id 10 :name "J"} {}))) :h2 (is (= [{(keyword "scope_identity()") 11}] (insert-into-test-table-return-keys db {:id 11 :name "J"} {}))) ;; hsql and derby don't seem to support .getGeneratedKeys nil))) (is (= 1 (update-test-table db {:id 1 :name "C"}))) (is (= {:id 1 :name "C"} (select-one-test-by-id db {:id 1}))) (is (= {:id 1 :name "C"} (select-deep-get db {:records [{:id 1}]}))) (is (= 0 (drop-test-table db)))) (testing "db-fn" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (fn? (hugsql/db-fn "select * from test where id = :id" :? :1))) (is (= "A" (:name (let [f (hugsql/db-fn "select * from test where id = :id" :? :1)] (f db {:id 1}))))) (is (= 0 (drop-test-table db)))) (testing "db-run" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= "A" (:name (hugsql/db-run db "select * from test where id = :id" {:id 1} :? :1)))) (is (= 0 (drop-test-table db)))) (testing "adapter-specific command option pass-through" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (when (= adapter-name :clojure.java.jdbc) (is (= [[:name] ["A"] ["B"]] (select-ordered db {:cols ["name"] :sort-by ["name"]} {} {:as-arrays? true})))) (is (= 0 (drop-test-table db)))) (testing "Clojure expressions" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (is (= 1 (insert-into-test-table db {:id 3 :name "C"}))) (is (= {:name "A"} (clj-expr-single db {:cols ["name"]}))) (is (= {:id 1 :name "A"} (clj-expr-single db))) (is (= {:name "A"} (clj-expr-multi db {:cols ["name"]}))) (is (= {:id 1 :name "A"} (clj-expr-multi db))) (is (= {:id 1 :name "A"} (clj-expr-multi-when db))) (is (= {:id 2 :name "B"} (clj-expr-multi-when db {:id 2}))) (is (= 1 (clj-expr-generic-update db {:table "test" :updates {:name "X"} :id 3}))) (is (= 0 (drop-test-table db)))) (testing "snippets" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (is (= [{:id 1 :name "A"} {:id 2 :name "B"}] (snip-query db {:select (select-snip {:cols ["id","name"]}) :from (from-snip {:tables ["test"]}) :where (where-snip {:cond [(cond-snip {:conj "" :cond ["id" "=" 1]}) (cond-snip {:conj "or" :cond ["id" "=" 2]})]}) :order (order-snip {:fields ["id"]})}))) (is (= 0 (drop-test-table db)))) (when (and (= db-name :postgresql) (= adapter-name :clojure.java.jdbc)) (testing "command & result used in public and private fns" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (is (= {:id 1} (update-test-table-returning db {:id 1 :name "C"}))) (is (= {:id 2} (update-test-table-returning-private db {:id 2 :name "D"}))) (is (= 0 (drop-test-table db))))))))
10703
(ns hugsql.core-test (:require [clojure.test :refer :all] [hugsql.core :as hugsql] [hugsql.adapter] [hugsql.adapter.clojure-java-jdbc :as cjj-adapter] [hugsql.adapter.clojure-jdbc :as cj-adapter] [clojure.java.io :as io]) (:import [clojure.lang ExceptionInfo])) (def adapters {:clojure.java.jdbc (cjj-adapter/hugsql-adapter-clojure-java-jdbc) :clojure.jdbc (cj-adapter/hugsql-adapter-clojure-jdbc)}) (def tmpdir (System/getProperty "java.io.tmpdir")) (def dbs { ;; sudo su - postgres ;; switch to postgres user ;; createuser -P hugtest ;; enter "hugtest" when prompted ;; createdb -O hugtest hugtest :postgresql {:subprotocol "postgresql" :subname "//127.0.0.1:5432/hugtest" :user "hugtest" :password "<PASSWORD>"} ;; mysql -u root -p ;; mysql> create database hugtest; ;; mysql> grant all on hugtest.* to hugtest identified by "hugtest"; :mysql {:subprotocol "mysql" :subname "//127.0.0.1:3306/hugtest?useSSL=false" :user "hugtest" :password "<PASSWORD>"} :sqlite {:subprotocol "sqlite" :subname (str tmpdir "/hugtest.sqlite")} :h2 {:subprotocol "h2" :subname (str tmpdir "/hugtest.h2")} :hsqldb {:subprotocol "hsqldb" :subname (str tmpdir "/hugtest.hsqldb")} :derby {:subprotocol "derby" :subname (str tmpdir "/hugtest.derby") :create true} }) ;; Call def-db-fns outside of deftest so that namespace is 'hugsql.core-test ;; Use a file path in the classpath (hugsql/def-db-fns "hugsql/sql/test.sql") (hugsql/def-sqlvec-fns "hugsql/sql/test.sql") ;; Use a java.io.File object (let [tmpfile (io/file (str tmpdir "/test.sql"))] (io/copy (io/file (io/resource "hugsql/sql/test2.sql")) tmpfile) (hugsql/def-db-fns tmpfile)) ;; Use a string (def hugsql-string-defs (str "-- :name test3-select\n select * from test3" "-- :snip snip1\n select *")) (hugsql/def-db-fns-from-string hugsql-string-defs) (deftest core (testing "adapter was not set during fn def" (is (= nil @hugsql/adapter))) (testing "File outside of classpath with java.io.File worked" (is (fn? test2-select))) (testing "defs from string worked" (is (fn? test3-select)) (is (fn? snip1))) (testing "sql file does not exist/can't be read" (is (thrown-with-msg? ExceptionInfo #"Can not read file" (eval '(hugsql.core/def-db-fns "non/existent/file.sql"))))) (testing "fn definition" (is (fn? no-params-select)) (is (fn? no-params-select-sqlvec)) (is (= "No params" (:doc (meta #'no-params-select)))) (is (= "No params (sqlvec)" (:doc (meta #'no-params-select-sqlvec)))) (is (= "hugsql/sql/test.sql" (:file (meta #'no-params-select)))) (is (= 6 (:line (meta #'no-params-select))))) (testing "sql fns" (is (= ["select * from test"] (no-params-select-sqlvec))) (is (= ["select * from test"] (no-params-select-sqlvec {}))) (is (= ["select * from test where id = ?" 1] (one-value-param-sqlvec {:id 1}))) (is (= ["select * from test\nwhere id = ?\nand name = ?" 1 "<NAME>"] (multi-value-params-sqlvec {:id 1 :name "<NAME>"}))) (is (= ["select * from test\nwhere id in (?,?,?)" 1 2 3] (value-list-param-sqlvec {:ids [1,2,3]}))) (is (= ["select * from test\nwhere (id, name) = (?,?)" 1 "A"] (tuple-param-sqlvec {:id-name [1 "A"]}))) (is (= ["insert into test (id, name)\nvalues (?,?),(?,?),(?,?)" 1 "<NAME>" 2 "Al" 3 "Bo"] (tuple-param-list-sqlvec {:people [[1 "<NAME>"] [2 "<NAME>"] [3 "<NAME>"]]}))) (is (= ["select * from test"] (identifier-param-sqlvec {:table-name "test"}))) (is (= ["select id, name from test"] (identifier-param-list-sqlvec {:columns ["id", "name"]}))) (is (= ["select * from test as my_test"] (identifier-param-sqlvec {:table-name ["test" "my_test"]}))) (is (= ["select id as my_id, name as my_name from test"] (identifier-param-list-sqlvec {:columns [["id" "my_id"], ["name" "my_name"]]}))) (is (= ["select * from test as my_test"] (identifier-param-sqlvec {:table-name {"test" "my_test"}}))) (is (let [r (identifier-param-list-sqlvec {:columns {"id" "my_id" "name" "my_name"}})] (or (= r ["select id as my_id, name as my_name from test"]) (= r ["select name as my_name, id as my_id from test"])))) (is (= ["select * from test order by id desc"] (sql-param-sqlvec {:id-order "desc"})))) (testing "identifier quoting" (is (= ["select * from \"schema\".\"te\"\"st\""] (identifier-param-sqlvec {:table-name "schema.te\"st"} {:quoting :ansi}))) (is (= ["select * from \"schema\".\"te\"\"st\" as \"my.test\""] (identifier-param-sqlvec {:table-name ["schema.te\"st" "my.test"]} {:quoting :ansi}))) (is (= ["select * from `schema`.`te``st`"] (identifier-param-sqlvec {:table-name "schema.te`st"} {:quoting :mysql}))) (is (= ["select * from [schema].[te]]st]"] (identifier-param-sqlvec {:table-name "schema.te]st"} {:quoting :mssql}))) (is (= ["select \"test\".\"id\", \"test\".\"name\" from test"] (identifier-param-list-sqlvec {:columns ["test.id", "test.name"]} {:quoting :ansi}))) (is (= ["select \"test\".\"id\" as \"my.id\", \"test\".\"name\" as \"my.name\" from test"] (identifier-param-list-sqlvec {:columns [["test.id" "my.id"], ["test.name" "my.name"]]} {:quoting :ansi}))) (is (= ["select `test`.`id`, `test`.`name` from test"] (identifier-param-list-sqlvec {:columns ["test.id", "test.name"]} {:quoting :mysql}))) (is (= ["select [test].[id], [test].[name] from test"] (identifier-param-list-sqlvec {:columns ["test.id", "test.name"]} {:quoting :mssql})))) (testing "sqlvec" (is (= ["select * from test where id = ?" 1] (hugsql/sqlvec "select * from test where id = :id" {:id 1})))) (testing "Snippets" (is (= ["select id, name"] (select-snip {:cols ["id","name"]}))) (is (= ["from test"] (from-snip {:tables ["test"]}))) (is (= ["select id, name\nfrom test\nwhere id = ? or id = ?\norder by id" 1 2] (snip-query-sqlvec {:select (select-snip {:cols ["id","name"]}) :from (from-snip {:tables ["test"]}) :where (where-snip {:cond [(cond-snip {:conj "" :cond ["id" "=" 1]}) (cond-snip {:conj "or" :cond ["id" "=" 2]})]}) :order (order-snip {:fields ["id"]})})))) (testing "metadata" (is (:private (meta #'a-private-fn))) (is (:private (meta #'another-private-fn))) (is (= 1 (:one (meta #'user-meta)))) (is (= 2 (:two (meta #'user-meta))))) (testing "command & result as metadata" (is (= :? (:command (meta #'select-one-test-by-id)))) (is (= :1 (:result (meta #'select-one-test-by-id)))) (is (= :? (:command (meta #'a-private-fn)))) (is (= :* (:result (meta #'a-private-fn))))) (testing "map of fns" (let [db-fns (hugsql/map-of-db-fns "hugsql/sql/test.sql") sql-fns (hugsql/map-of-sqlvec-fns "hugsql/sql/test.sql") db-fns-str (hugsql/map-of-db-fns-from-string hugsql-string-defs) sql-fns-str (hugsql/map-of-sqlvec-fns-from-string hugsql-string-defs)] (is (fn? (get-in db-fns [:one-value-param :fn]))) (is (fn? (get-in db-fns [:select-snip :fn]))) (is (= "One value param" (get-in db-fns [:one-value-param :meta :doc]))) (is (not (get-in db-fns [:one-value-param :meta :snip?]))) (is (get-in db-fns [:select-snip :meta :snip?])) (is (fn? (get-in sql-fns [:one-value-param-sqlvec :fn]))) (is (fn? (get-in sql-fns [:select-snip :fn]))) (is (= "One value param (sqlvec)" (get-in sql-fns [:one-value-param-sqlvec :meta :doc]))) (is (fn? (get-in db-fns-str [:test3-select :fn]))) (is (fn? (get-in sql-fns-str [:test3-select-sqlvec :fn]))))) (testing "missing header :name, :name-, :snip, or :snip-" (is (thrown-with-msg? ExceptionInfo #"Missing HugSQL Header of " (hugsql/def-db-fns-from-string "-- :name: almost-a-yesql-name-hdr\nselect * from test")))) (testing "nil header :name, :name-, :snip, or :snip-" (is (thrown-with-msg? ExceptionInfo #"HugSQL Header .* not given." (hugsql/def-db-fns-from-string "-- :name \nselect * from test")))) (testing "value parameters allow vectors for ISQLParameter/etc overrides" (is (= ["insert into test (id, myarr) values (?, ?)" 1 [1 2 3]] (hugsql/sqlvec "insert into test (id, myarr) values (:id, :v:myarr)" {:id 1 :myarr [1 2 3]}))) (is (= ["insert into test (id, myarr) values (?,?),(?,?)" 1 [1 2 3] 2 [4 5 6]] (hugsql/sqlvec "insert into test (id, myarr) values :t*:records" {:records [[1 [1 2 3]] [2 [4 5 6]]]})))) (testing "spacing around Raw SQL parameters" (is (= ["select col_1 from test"] (hugsql/sqlvec "select col_:sql:col_num from test" {:col_num 1})))) (doseq [[db-name db] dbs] (doseq [[adapter-name adapter] adapters] (testing "adapter set" (is (satisfies? hugsql.adapter/HugsqlAdapter (hugsql/set-adapter! adapter)))) (testing "parameter placeholder vs data mismatch" (is (thrown-with-msg? ExceptionInfo #"Parameter Mismatch: :id parameter data not found." (one-value-param-sqlvec {:x 1}))) (is (thrown-with-msg? ExceptionInfo #"Parameter Mismatch: :id parameter data not found." (one-value-param db {:x 1}))) ;; does not throw on false (is (= ["select * from test where id = ?" false] (one-value-param-sqlvec {:id false}))) ;; deep-get check (is (thrown-with-msg? ExceptionInfo #"Parameter Mismatch: :emps.0.id parameter data not found." (hugsql/sqlvec "select * from emp where id = :emps.0.id" {:emps [{:not-id 1}]})))) (testing "database commands/queries" (condp = db-name :mysql (is (= 0 (create-test-table-mysql db))) :h2 (is (= 0 (create-test-table-h2 db))) :hsqldb (is (= 0 (create-test-table-hsqldb db))) (is (= 0 (create-test-table db)))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (testing "tuple" ;; tuple use is not supported by certain dbs (when (not-any? #(= % db-name) [:derby :sqlite :hsqldb]) (is (= [{:id 1 :name "A"}] (tuple-param db {:id-name [1 "A"]}))))) (testing "insert multiple values" ;; only hsqldb appears to not support multi-insert values for :tuple* (when (not (= db-name :hsqldb)) (is (= 3 (insert-multi-into-test-table db {:values [[4 "D"] [5 "E"] [6 "F"]]}))))) (testing "returning" ;; returning support is lacking in many dbs (when (not-any? #(= % db-name) [:mysql :h2 :derby :sqlite :hsqldb]) (is (= [{:id 7}] (insert-into-test-table-returning db {:id 7 :name "G"}))))) (testing "insert w/ return of .getGeneratedKeys" ;; return generated keys, which has varying support and return values ;; clojure.java.jdbc returns a hashmap, clojure.jdbc returns a vector of hashmaps (when (= adapter-name :clojure.java.jdbc) (condp = db-name :postgresql (is (= {:id 8 :name "H"} (insert-into-test-table-return-keys db {:id 8 :name "H"} {}))) :mysql (is (= {:generated_key 9} (insert-into-test-table-return-keys db {:id 9 :name "I"}))) :sqlite (is (= {(keyword "last_insert_rowid()") 10} (insert-into-test-table-return-keys db {:id 10 :name "J"} {}))) :h2 (is (= {(keyword "scope_identity()") 11} (insert-into-test-table-return-keys db {:id 11 :name "J"} {}))) ;; hsql and derby don't seem to support .getGeneratedKeys nil)) (when (= adapter-name :clojure.jdbc) (condp = db-name :postgresql (is (= [{:id 8 :name "H"}] (insert-into-test-table-return-keys db {:id 8 :name "H"} {}))) :mysql (is (= [{:generated_key 9}] (insert-into-test-table-return-keys db {:id 9 :name "I"}))) :sqlite (is (= [{(keyword "last_insert_rowid()") 10}] (insert-into-test-table-return-keys db {:id 10 :name "J"} {}))) :h2 (is (= [{(keyword "scope_identity()") 11}] (insert-into-test-table-return-keys db {:id 11 :name "J"} {}))) ;; hsql and derby don't seem to support .getGeneratedKeys nil))) (is (= 1 (update-test-table db {:id 1 :name "C"}))) (is (= {:id 1 :name "C"} (select-one-test-by-id db {:id 1}))) (is (= {:id 1 :name "C"} (select-deep-get db {:records [{:id 1}]}))) (is (= 0 (drop-test-table db)))) (testing "db-fn" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (fn? (hugsql/db-fn "select * from test where id = :id" :? :1))) (is (= "A" (:name (let [f (hugsql/db-fn "select * from test where id = :id" :? :1)] (f db {:id 1}))))) (is (= 0 (drop-test-table db)))) (testing "db-run" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= "A" (:name (hugsql/db-run db "select * from test where id = :id" {:id 1} :? :1)))) (is (= 0 (drop-test-table db)))) (testing "adapter-specific command option pass-through" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (when (= adapter-name :clojure.java.jdbc) (is (= [[:name] ["A"] ["B"]] (select-ordered db {:cols ["name"] :sort-by ["name"]} {} {:as-arrays? true})))) (is (= 0 (drop-test-table db)))) (testing "Clojure expressions" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (is (= 1 (insert-into-test-table db {:id 3 :name "C"}))) (is (= {:name "A"} (clj-expr-single db {:cols ["name"]}))) (is (= {:id 1 :name "A"} (clj-expr-single db))) (is (= {:name "A"} (clj-expr-multi db {:cols ["name"]}))) (is (= {:id 1 :name "A"} (clj-expr-multi db))) (is (= {:id 1 :name "A"} (clj-expr-multi-when db))) (is (= {:id 2 :name "B"} (clj-expr-multi-when db {:id 2}))) (is (= 1 (clj-expr-generic-update db {:table "test" :updates {:name "X"} :id 3}))) (is (= 0 (drop-test-table db)))) (testing "snippets" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (is (= [{:id 1 :name "A"} {:id 2 :name "B"}] (snip-query db {:select (select-snip {:cols ["id","name"]}) :from (from-snip {:tables ["test"]}) :where (where-snip {:cond [(cond-snip {:conj "" :cond ["id" "=" 1]}) (cond-snip {:conj "or" :cond ["id" "=" 2]})]}) :order (order-snip {:fields ["id"]})}))) (is (= 0 (drop-test-table db)))) (when (and (= db-name :postgresql) (= adapter-name :clojure.java.jdbc)) (testing "command & result used in public and private fns" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (is (= {:id 1} (update-test-table-returning db {:id 1 :name "C"}))) (is (= {:id 2} (update-test-table-returning-private db {:id 2 :name "D"}))) (is (= 0 (drop-test-table db))))))))
true
(ns hugsql.core-test (:require [clojure.test :refer :all] [hugsql.core :as hugsql] [hugsql.adapter] [hugsql.adapter.clojure-java-jdbc :as cjj-adapter] [hugsql.adapter.clojure-jdbc :as cj-adapter] [clojure.java.io :as io]) (:import [clojure.lang ExceptionInfo])) (def adapters {:clojure.java.jdbc (cjj-adapter/hugsql-adapter-clojure-java-jdbc) :clojure.jdbc (cj-adapter/hugsql-adapter-clojure-jdbc)}) (def tmpdir (System/getProperty "java.io.tmpdir")) (def dbs { ;; sudo su - postgres ;; switch to postgres user ;; createuser -P hugtest ;; enter "hugtest" when prompted ;; createdb -O hugtest hugtest :postgresql {:subprotocol "postgresql" :subname "//127.0.0.1:5432/hugtest" :user "hugtest" :password "PI:PASSWORD:<PASSWORD>END_PI"} ;; mysql -u root -p ;; mysql> create database hugtest; ;; mysql> grant all on hugtest.* to hugtest identified by "hugtest"; :mysql {:subprotocol "mysql" :subname "//127.0.0.1:3306/hugtest?useSSL=false" :user "hugtest" :password "PI:PASSWORD:<PASSWORD>END_PI"} :sqlite {:subprotocol "sqlite" :subname (str tmpdir "/hugtest.sqlite")} :h2 {:subprotocol "h2" :subname (str tmpdir "/hugtest.h2")} :hsqldb {:subprotocol "hsqldb" :subname (str tmpdir "/hugtest.hsqldb")} :derby {:subprotocol "derby" :subname (str tmpdir "/hugtest.derby") :create true} }) ;; Call def-db-fns outside of deftest so that namespace is 'hugsql.core-test ;; Use a file path in the classpath (hugsql/def-db-fns "hugsql/sql/test.sql") (hugsql/def-sqlvec-fns "hugsql/sql/test.sql") ;; Use a java.io.File object (let [tmpfile (io/file (str tmpdir "/test.sql"))] (io/copy (io/file (io/resource "hugsql/sql/test2.sql")) tmpfile) (hugsql/def-db-fns tmpfile)) ;; Use a string (def hugsql-string-defs (str "-- :name test3-select\n select * from test3" "-- :snip snip1\n select *")) (hugsql/def-db-fns-from-string hugsql-string-defs) (deftest core (testing "adapter was not set during fn def" (is (= nil @hugsql/adapter))) (testing "File outside of classpath with java.io.File worked" (is (fn? test2-select))) (testing "defs from string worked" (is (fn? test3-select)) (is (fn? snip1))) (testing "sql file does not exist/can't be read" (is (thrown-with-msg? ExceptionInfo #"Can not read file" (eval '(hugsql.core/def-db-fns "non/existent/file.sql"))))) (testing "fn definition" (is (fn? no-params-select)) (is (fn? no-params-select-sqlvec)) (is (= "No params" (:doc (meta #'no-params-select)))) (is (= "No params (sqlvec)" (:doc (meta #'no-params-select-sqlvec)))) (is (= "hugsql/sql/test.sql" (:file (meta #'no-params-select)))) (is (= 6 (:line (meta #'no-params-select))))) (testing "sql fns" (is (= ["select * from test"] (no-params-select-sqlvec))) (is (= ["select * from test"] (no-params-select-sqlvec {}))) (is (= ["select * from test where id = ?" 1] (one-value-param-sqlvec {:id 1}))) (is (= ["select * from test\nwhere id = ?\nand name = ?" 1 "PI:NAME:<NAME>END_PI"] (multi-value-params-sqlvec {:id 1 :name "PI:NAME:<NAME>END_PI"}))) (is (= ["select * from test\nwhere id in (?,?,?)" 1 2 3] (value-list-param-sqlvec {:ids [1,2,3]}))) (is (= ["select * from test\nwhere (id, name) = (?,?)" 1 "A"] (tuple-param-sqlvec {:id-name [1 "A"]}))) (is (= ["insert into test (id, name)\nvalues (?,?),(?,?),(?,?)" 1 "PI:NAME:<NAME>END_PI" 2 "Al" 3 "Bo"] (tuple-param-list-sqlvec {:people [[1 "PI:NAME:<NAME>END_PI"] [2 "PI:NAME:<NAME>END_PI"] [3 "PI:NAME:<NAME>END_PI"]]}))) (is (= ["select * from test"] (identifier-param-sqlvec {:table-name "test"}))) (is (= ["select id, name from test"] (identifier-param-list-sqlvec {:columns ["id", "name"]}))) (is (= ["select * from test as my_test"] (identifier-param-sqlvec {:table-name ["test" "my_test"]}))) (is (= ["select id as my_id, name as my_name from test"] (identifier-param-list-sqlvec {:columns [["id" "my_id"], ["name" "my_name"]]}))) (is (= ["select * from test as my_test"] (identifier-param-sqlvec {:table-name {"test" "my_test"}}))) (is (let [r (identifier-param-list-sqlvec {:columns {"id" "my_id" "name" "my_name"}})] (or (= r ["select id as my_id, name as my_name from test"]) (= r ["select name as my_name, id as my_id from test"])))) (is (= ["select * from test order by id desc"] (sql-param-sqlvec {:id-order "desc"})))) (testing "identifier quoting" (is (= ["select * from \"schema\".\"te\"\"st\""] (identifier-param-sqlvec {:table-name "schema.te\"st"} {:quoting :ansi}))) (is (= ["select * from \"schema\".\"te\"\"st\" as \"my.test\""] (identifier-param-sqlvec {:table-name ["schema.te\"st" "my.test"]} {:quoting :ansi}))) (is (= ["select * from `schema`.`te``st`"] (identifier-param-sqlvec {:table-name "schema.te`st"} {:quoting :mysql}))) (is (= ["select * from [schema].[te]]st]"] (identifier-param-sqlvec {:table-name "schema.te]st"} {:quoting :mssql}))) (is (= ["select \"test\".\"id\", \"test\".\"name\" from test"] (identifier-param-list-sqlvec {:columns ["test.id", "test.name"]} {:quoting :ansi}))) (is (= ["select \"test\".\"id\" as \"my.id\", \"test\".\"name\" as \"my.name\" from test"] (identifier-param-list-sqlvec {:columns [["test.id" "my.id"], ["test.name" "my.name"]]} {:quoting :ansi}))) (is (= ["select `test`.`id`, `test`.`name` from test"] (identifier-param-list-sqlvec {:columns ["test.id", "test.name"]} {:quoting :mysql}))) (is (= ["select [test].[id], [test].[name] from test"] (identifier-param-list-sqlvec {:columns ["test.id", "test.name"]} {:quoting :mssql})))) (testing "sqlvec" (is (= ["select * from test where id = ?" 1] (hugsql/sqlvec "select * from test where id = :id" {:id 1})))) (testing "Snippets" (is (= ["select id, name"] (select-snip {:cols ["id","name"]}))) (is (= ["from test"] (from-snip {:tables ["test"]}))) (is (= ["select id, name\nfrom test\nwhere id = ? or id = ?\norder by id" 1 2] (snip-query-sqlvec {:select (select-snip {:cols ["id","name"]}) :from (from-snip {:tables ["test"]}) :where (where-snip {:cond [(cond-snip {:conj "" :cond ["id" "=" 1]}) (cond-snip {:conj "or" :cond ["id" "=" 2]})]}) :order (order-snip {:fields ["id"]})})))) (testing "metadata" (is (:private (meta #'a-private-fn))) (is (:private (meta #'another-private-fn))) (is (= 1 (:one (meta #'user-meta)))) (is (= 2 (:two (meta #'user-meta))))) (testing "command & result as metadata" (is (= :? (:command (meta #'select-one-test-by-id)))) (is (= :1 (:result (meta #'select-one-test-by-id)))) (is (= :? (:command (meta #'a-private-fn)))) (is (= :* (:result (meta #'a-private-fn))))) (testing "map of fns" (let [db-fns (hugsql/map-of-db-fns "hugsql/sql/test.sql") sql-fns (hugsql/map-of-sqlvec-fns "hugsql/sql/test.sql") db-fns-str (hugsql/map-of-db-fns-from-string hugsql-string-defs) sql-fns-str (hugsql/map-of-sqlvec-fns-from-string hugsql-string-defs)] (is (fn? (get-in db-fns [:one-value-param :fn]))) (is (fn? (get-in db-fns [:select-snip :fn]))) (is (= "One value param" (get-in db-fns [:one-value-param :meta :doc]))) (is (not (get-in db-fns [:one-value-param :meta :snip?]))) (is (get-in db-fns [:select-snip :meta :snip?])) (is (fn? (get-in sql-fns [:one-value-param-sqlvec :fn]))) (is (fn? (get-in sql-fns [:select-snip :fn]))) (is (= "One value param (sqlvec)" (get-in sql-fns [:one-value-param-sqlvec :meta :doc]))) (is (fn? (get-in db-fns-str [:test3-select :fn]))) (is (fn? (get-in sql-fns-str [:test3-select-sqlvec :fn]))))) (testing "missing header :name, :name-, :snip, or :snip-" (is (thrown-with-msg? ExceptionInfo #"Missing HugSQL Header of " (hugsql/def-db-fns-from-string "-- :name: almost-a-yesql-name-hdr\nselect * from test")))) (testing "nil header :name, :name-, :snip, or :snip-" (is (thrown-with-msg? ExceptionInfo #"HugSQL Header .* not given." (hugsql/def-db-fns-from-string "-- :name \nselect * from test")))) (testing "value parameters allow vectors for ISQLParameter/etc overrides" (is (= ["insert into test (id, myarr) values (?, ?)" 1 [1 2 3]] (hugsql/sqlvec "insert into test (id, myarr) values (:id, :v:myarr)" {:id 1 :myarr [1 2 3]}))) (is (= ["insert into test (id, myarr) values (?,?),(?,?)" 1 [1 2 3] 2 [4 5 6]] (hugsql/sqlvec "insert into test (id, myarr) values :t*:records" {:records [[1 [1 2 3]] [2 [4 5 6]]]})))) (testing "spacing around Raw SQL parameters" (is (= ["select col_1 from test"] (hugsql/sqlvec "select col_:sql:col_num from test" {:col_num 1})))) (doseq [[db-name db] dbs] (doseq [[adapter-name adapter] adapters] (testing "adapter set" (is (satisfies? hugsql.adapter/HugsqlAdapter (hugsql/set-adapter! adapter)))) (testing "parameter placeholder vs data mismatch" (is (thrown-with-msg? ExceptionInfo #"Parameter Mismatch: :id parameter data not found." (one-value-param-sqlvec {:x 1}))) (is (thrown-with-msg? ExceptionInfo #"Parameter Mismatch: :id parameter data not found." (one-value-param db {:x 1}))) ;; does not throw on false (is (= ["select * from test where id = ?" false] (one-value-param-sqlvec {:id false}))) ;; deep-get check (is (thrown-with-msg? ExceptionInfo #"Parameter Mismatch: :emps.0.id parameter data not found." (hugsql/sqlvec "select * from emp where id = :emps.0.id" {:emps [{:not-id 1}]})))) (testing "database commands/queries" (condp = db-name :mysql (is (= 0 (create-test-table-mysql db))) :h2 (is (= 0 (create-test-table-h2 db))) :hsqldb (is (= 0 (create-test-table-hsqldb db))) (is (= 0 (create-test-table db)))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (testing "tuple" ;; tuple use is not supported by certain dbs (when (not-any? #(= % db-name) [:derby :sqlite :hsqldb]) (is (= [{:id 1 :name "A"}] (tuple-param db {:id-name [1 "A"]}))))) (testing "insert multiple values" ;; only hsqldb appears to not support multi-insert values for :tuple* (when (not (= db-name :hsqldb)) (is (= 3 (insert-multi-into-test-table db {:values [[4 "D"] [5 "E"] [6 "F"]]}))))) (testing "returning" ;; returning support is lacking in many dbs (when (not-any? #(= % db-name) [:mysql :h2 :derby :sqlite :hsqldb]) (is (= [{:id 7}] (insert-into-test-table-returning db {:id 7 :name "G"}))))) (testing "insert w/ return of .getGeneratedKeys" ;; return generated keys, which has varying support and return values ;; clojure.java.jdbc returns a hashmap, clojure.jdbc returns a vector of hashmaps (when (= adapter-name :clojure.java.jdbc) (condp = db-name :postgresql (is (= {:id 8 :name "H"} (insert-into-test-table-return-keys db {:id 8 :name "H"} {}))) :mysql (is (= {:generated_key 9} (insert-into-test-table-return-keys db {:id 9 :name "I"}))) :sqlite (is (= {(keyword "last_insert_rowid()") 10} (insert-into-test-table-return-keys db {:id 10 :name "J"} {}))) :h2 (is (= {(keyword "scope_identity()") 11} (insert-into-test-table-return-keys db {:id 11 :name "J"} {}))) ;; hsql and derby don't seem to support .getGeneratedKeys nil)) (when (= adapter-name :clojure.jdbc) (condp = db-name :postgresql (is (= [{:id 8 :name "H"}] (insert-into-test-table-return-keys db {:id 8 :name "H"} {}))) :mysql (is (= [{:generated_key 9}] (insert-into-test-table-return-keys db {:id 9 :name "I"}))) :sqlite (is (= [{(keyword "last_insert_rowid()") 10}] (insert-into-test-table-return-keys db {:id 10 :name "J"} {}))) :h2 (is (= [{(keyword "scope_identity()") 11}] (insert-into-test-table-return-keys db {:id 11 :name "J"} {}))) ;; hsql and derby don't seem to support .getGeneratedKeys nil))) (is (= 1 (update-test-table db {:id 1 :name "C"}))) (is (= {:id 1 :name "C"} (select-one-test-by-id db {:id 1}))) (is (= {:id 1 :name "C"} (select-deep-get db {:records [{:id 1}]}))) (is (= 0 (drop-test-table db)))) (testing "db-fn" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (fn? (hugsql/db-fn "select * from test where id = :id" :? :1))) (is (= "A" (:name (let [f (hugsql/db-fn "select * from test where id = :id" :? :1)] (f db {:id 1}))))) (is (= 0 (drop-test-table db)))) (testing "db-run" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= "A" (:name (hugsql/db-run db "select * from test where id = :id" {:id 1} :? :1)))) (is (= 0 (drop-test-table db)))) (testing "adapter-specific command option pass-through" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (when (= adapter-name :clojure.java.jdbc) (is (= [[:name] ["A"] ["B"]] (select-ordered db {:cols ["name"] :sort-by ["name"]} {} {:as-arrays? true})))) (is (= 0 (drop-test-table db)))) (testing "Clojure expressions" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (is (= 1 (insert-into-test-table db {:id 3 :name "C"}))) (is (= {:name "A"} (clj-expr-single db {:cols ["name"]}))) (is (= {:id 1 :name "A"} (clj-expr-single db))) (is (= {:name "A"} (clj-expr-multi db {:cols ["name"]}))) (is (= {:id 1 :name "A"} (clj-expr-multi db))) (is (= {:id 1 :name "A"} (clj-expr-multi-when db))) (is (= {:id 2 :name "B"} (clj-expr-multi-when db {:id 2}))) (is (= 1 (clj-expr-generic-update db {:table "test" :updates {:name "X"} :id 3}))) (is (= 0 (drop-test-table db)))) (testing "snippets" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (is (= [{:id 1 :name "A"} {:id 2 :name "B"}] (snip-query db {:select (select-snip {:cols ["id","name"]}) :from (from-snip {:tables ["test"]}) :where (where-snip {:cond [(cond-snip {:conj "" :cond ["id" "=" 1]}) (cond-snip {:conj "or" :cond ["id" "=" 2]})]}) :order (order-snip {:fields ["id"]})}))) (is (= 0 (drop-test-table db)))) (when (and (= db-name :postgresql) (= adapter-name :clojure.java.jdbc)) (testing "command & result used in public and private fns" (is (= 0 (create-test-table db))) (is (= 1 (insert-into-test-table db {:id 1 :name "A"}))) (is (= 1 (insert-into-test-table db {:id 2 :name "B"}))) (is (= {:id 1} (update-test-table-returning db {:id 1 :name "C"}))) (is (= {:id 2} (update-test-table-returning-private db {:id 2 :name "D"}))) (is (= 0 (drop-test-table db))))))))
[ { "context": ";;\n;; Copyright © 2020 Sam Ritchie.\n;; This work is based on the Scmutils system of ", "end": 34, "score": 0.9998284578323364, "start": 23, "tag": "NAME", "value": "Sam Ritchie" } ]
test/numerical/interpolate/richardson_test.cljc
dynamic-notebook/functional-numerics
4
;; ;; Copyright © 2020 Sam Ritchie. ;; This work is based on the Scmutils system of MIT/GNU Scheme: ;; Copyright © 2002 Massachusetts Institute of Technology ;; ;; This is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3 of the License, or (at ;; your option) any later version. ;; ;; This software is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this code; if not, see <http://www.gnu.org/licenses/>. ;; (ns sicmutils.numerical.interpolate.richardson-test (:require [clojure.test :refer [is deftest testing]] [same :refer [ish?]] [sicmutils.numerical.interpolate.polynomial :as ip] [sicmutils.numerical.interpolate.richardson :as ir] [sicmutils.numbers] [sicmutils.util.stream :as us] [sicmutils.value :as v])) (deftest richardson-limit-tests (let [pi-seq @#'ir/archimedean-pi-sequence] (testing "without richardson extrapolation, the sequence takes a long time." (is (ish? {:converged? true :terms-checked 26 :result 3.1415926535897944} (us/seq-limit pi-seq {:tolerance v/machine-epsilon})))) (testing "with richardson, we go faster." (is (ish? {:converged? true :terms-checked 7 :result 3.1415926535897936} (-> (ir/richardson-sequence pi-seq 2 2 2) (us/seq-limit {:tolerance v/machine-epsilon})))) (is (ish? {:converged? false :terms-checked 3 :result 3.1415903931299374} (-> (take 3 pi-seq) (ir/richardson-sequence 2 2 2) (us/seq-limit {:tolerance v/machine-epsilon}))) "richardson-sequence bails if the input sequence runs out of terms.") (is (ish? [2.8284271247461903 3.1391475703122276 3.1415903931299374 3.141592653286045 3.1415926535897865] (take 5 (ir/richardson-sequence pi-seq 4))))) (testing "richardson extrapolation is equivalent to polynomial extrapolation to 0" (let [h**2 (fn [i] ;; (1/t^{i + 1})^2 (-> (/ 1 (Math/pow 2 (inc i))) (Math/pow 2))) xs (map-indexed (fn [i fx] [(h**2 i) fx]) pi-seq)] (is (ish? (take 7 (us/seq-limit (ir/richardson-sequence pi-seq 4 1 1))) (take 7 (us/seq-limit (ip/modified-neville xs 0.0)))))))))
47843
;; ;; Copyright © 2020 <NAME>. ;; This work is based on the Scmutils system of MIT/GNU Scheme: ;; Copyright © 2002 Massachusetts Institute of Technology ;; ;; This is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3 of the License, or (at ;; your option) any later version. ;; ;; This software is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this code; if not, see <http://www.gnu.org/licenses/>. ;; (ns sicmutils.numerical.interpolate.richardson-test (:require [clojure.test :refer [is deftest testing]] [same :refer [ish?]] [sicmutils.numerical.interpolate.polynomial :as ip] [sicmutils.numerical.interpolate.richardson :as ir] [sicmutils.numbers] [sicmutils.util.stream :as us] [sicmutils.value :as v])) (deftest richardson-limit-tests (let [pi-seq @#'ir/archimedean-pi-sequence] (testing "without richardson extrapolation, the sequence takes a long time." (is (ish? {:converged? true :terms-checked 26 :result 3.1415926535897944} (us/seq-limit pi-seq {:tolerance v/machine-epsilon})))) (testing "with richardson, we go faster." (is (ish? {:converged? true :terms-checked 7 :result 3.1415926535897936} (-> (ir/richardson-sequence pi-seq 2 2 2) (us/seq-limit {:tolerance v/machine-epsilon})))) (is (ish? {:converged? false :terms-checked 3 :result 3.1415903931299374} (-> (take 3 pi-seq) (ir/richardson-sequence 2 2 2) (us/seq-limit {:tolerance v/machine-epsilon}))) "richardson-sequence bails if the input sequence runs out of terms.") (is (ish? [2.8284271247461903 3.1391475703122276 3.1415903931299374 3.141592653286045 3.1415926535897865] (take 5 (ir/richardson-sequence pi-seq 4))))) (testing "richardson extrapolation is equivalent to polynomial extrapolation to 0" (let [h**2 (fn [i] ;; (1/t^{i + 1})^2 (-> (/ 1 (Math/pow 2 (inc i))) (Math/pow 2))) xs (map-indexed (fn [i fx] [(h**2 i) fx]) pi-seq)] (is (ish? (take 7 (us/seq-limit (ir/richardson-sequence pi-seq 4 1 1))) (take 7 (us/seq-limit (ip/modified-neville xs 0.0)))))))))
true
;; ;; Copyright © 2020 PI:NAME:<NAME>END_PI. ;; This work is based on the Scmutils system of MIT/GNU Scheme: ;; Copyright © 2002 Massachusetts Institute of Technology ;; ;; This is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3 of the License, or (at ;; your option) any later version. ;; ;; This software is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this code; if not, see <http://www.gnu.org/licenses/>. ;; (ns sicmutils.numerical.interpolate.richardson-test (:require [clojure.test :refer [is deftest testing]] [same :refer [ish?]] [sicmutils.numerical.interpolate.polynomial :as ip] [sicmutils.numerical.interpolate.richardson :as ir] [sicmutils.numbers] [sicmutils.util.stream :as us] [sicmutils.value :as v])) (deftest richardson-limit-tests (let [pi-seq @#'ir/archimedean-pi-sequence] (testing "without richardson extrapolation, the sequence takes a long time." (is (ish? {:converged? true :terms-checked 26 :result 3.1415926535897944} (us/seq-limit pi-seq {:tolerance v/machine-epsilon})))) (testing "with richardson, we go faster." (is (ish? {:converged? true :terms-checked 7 :result 3.1415926535897936} (-> (ir/richardson-sequence pi-seq 2 2 2) (us/seq-limit {:tolerance v/machine-epsilon})))) (is (ish? {:converged? false :terms-checked 3 :result 3.1415903931299374} (-> (take 3 pi-seq) (ir/richardson-sequence 2 2 2) (us/seq-limit {:tolerance v/machine-epsilon}))) "richardson-sequence bails if the input sequence runs out of terms.") (is (ish? [2.8284271247461903 3.1391475703122276 3.1415903931299374 3.141592653286045 3.1415926535897865] (take 5 (ir/richardson-sequence pi-seq 4))))) (testing "richardson extrapolation is equivalent to polynomial extrapolation to 0" (let [h**2 (fn [i] ;; (1/t^{i + 1})^2 (-> (/ 1 (Math/pow 2 (inc i))) (Math/pow 2))) xs (map-indexed (fn [i fx] [(h**2 i) fx]) pi-seq)] (is (ish? (take 7 (us/seq-limit (ir/richardson-sequence pi-seq 4 1 1))) (take 7 (us/seq-limit (ip/modified-neville xs 0.0)))))))))
[ { "context": "ted-topic\n (let [test-db (reagent/atom {:name \"Lean Caffeine\"\n :persistent {:t", "end": 377, "score": 0.940699577331543, "start": 364, "tag": "NAME", "value": "Lean Caffeine" }, { "context": "-by-sorting\n (let [test-db (reagent/atom {:name \"Lean Caffeine\"\n :persistent {:top", "end": 1345, "score": 0.9620599746704102, "start": 1332, "tag": "NAME", "value": "Lean Caffeine" }, { "context": "-same-count\n (let [test-db (reagent/atom {:name \"Lean Caffeine\"\n :persistent {:top", "end": 2133, "score": 0.9947133660316467, "start": 2120, "tag": "NAME", "value": "Lean Caffeine" } ]
test/cljs/lean_discussion/subs_test.cljs
ericstewart/lean-discussion
3
(ns lean-discussion.subs-test (:require [cljs.test :refer-macros [deftest testing is]] [reagent.debug :refer-macros [dbg println log]] [reagent.core :as reagent] [lean-discussion.subs :as subs]) (:require-macros [reagent.ratom :refer [reaction]])) (deftest test-handler-sorted-topic (let [test-db (reagent/atom {:name "Lean Caffeine" :persistent {:topics {1 {:id 1 :label "An Example Topic" :state :to-do} 2 {:id 2 :label "Another Example Topic" :state :to-do} 3 {:id 3 :label "Example of somethng to discuss" :state :to-do}} :column-order {:to-do [3 1 2]}} :session-mode :collect})] (testing "doesn't retrieve topics with incorrect state" (is (= [] (subs/sorted-topics-with-state @test-db :fake-topic)))) (testing "does retrive topics of the right state" (is (= 3 (count (subs/sorted-topics-with-state @test-db :to-do)))) (is (= [3 1 2] (map #(:id %) (subs/sorted-topics-with-state @test-db :to-do))))))) (deftest test-topics-sorted-by-sorting (let [test-db (reagent/atom {:name "Lean Caffeine" :persistent {:topics {1 {:id 1 :label "An Example Topic" :state :to-do :votes 2} 2 {:id 2 :label "Another Example Topic" :state :to-do :votes 3} 3 {:id 3 :label "Example of somethng to discuss" :state :to-do :votes 1}} :column-order {:to-do [3 1 2]}} :session-mode :collect})] (testing "returns in correct order" (let [results (subs/topics-sorted-by @test-db :to-do :votes)] (is (= [2 1 3] (into [] (map #(:id %)) results))))))) (deftest test-topics-sorted-same-count (let [test-db (reagent/atom {:name "Lean Caffeine" :persistent {:topics {1 {:id 1 :label "An Example Topic" :state :to-do :votes 3} 2 {:id 2 :label "Another Example Topic" :state :to-do :votes 3} 3 {:id 3 :label "Example of somethng to discuss" :state :to-do :votes 1}} :column-order {:to-do [3 1 2]}} :session-mode :collect})] (testing "returns in correct order" (let [results (subs/topics-sorted-by @test-db :to-do :votes)] (is (= 3 (count (vals results)))) (is (= [2 1 3] (into [] (map #(:id %)) results)))))))
123104
(ns lean-discussion.subs-test (:require [cljs.test :refer-macros [deftest testing is]] [reagent.debug :refer-macros [dbg println log]] [reagent.core :as reagent] [lean-discussion.subs :as subs]) (:require-macros [reagent.ratom :refer [reaction]])) (deftest test-handler-sorted-topic (let [test-db (reagent/atom {:name "<NAME>" :persistent {:topics {1 {:id 1 :label "An Example Topic" :state :to-do} 2 {:id 2 :label "Another Example Topic" :state :to-do} 3 {:id 3 :label "Example of somethng to discuss" :state :to-do}} :column-order {:to-do [3 1 2]}} :session-mode :collect})] (testing "doesn't retrieve topics with incorrect state" (is (= [] (subs/sorted-topics-with-state @test-db :fake-topic)))) (testing "does retrive topics of the right state" (is (= 3 (count (subs/sorted-topics-with-state @test-db :to-do)))) (is (= [3 1 2] (map #(:id %) (subs/sorted-topics-with-state @test-db :to-do))))))) (deftest test-topics-sorted-by-sorting (let [test-db (reagent/atom {:name "<NAME>" :persistent {:topics {1 {:id 1 :label "An Example Topic" :state :to-do :votes 2} 2 {:id 2 :label "Another Example Topic" :state :to-do :votes 3} 3 {:id 3 :label "Example of somethng to discuss" :state :to-do :votes 1}} :column-order {:to-do [3 1 2]}} :session-mode :collect})] (testing "returns in correct order" (let [results (subs/topics-sorted-by @test-db :to-do :votes)] (is (= [2 1 3] (into [] (map #(:id %)) results))))))) (deftest test-topics-sorted-same-count (let [test-db (reagent/atom {:name "<NAME>" :persistent {:topics {1 {:id 1 :label "An Example Topic" :state :to-do :votes 3} 2 {:id 2 :label "Another Example Topic" :state :to-do :votes 3} 3 {:id 3 :label "Example of somethng to discuss" :state :to-do :votes 1}} :column-order {:to-do [3 1 2]}} :session-mode :collect})] (testing "returns in correct order" (let [results (subs/topics-sorted-by @test-db :to-do :votes)] (is (= 3 (count (vals results)))) (is (= [2 1 3] (into [] (map #(:id %)) results)))))))
true
(ns lean-discussion.subs-test (:require [cljs.test :refer-macros [deftest testing is]] [reagent.debug :refer-macros [dbg println log]] [reagent.core :as reagent] [lean-discussion.subs :as subs]) (:require-macros [reagent.ratom :refer [reaction]])) (deftest test-handler-sorted-topic (let [test-db (reagent/atom {:name "PI:NAME:<NAME>END_PI" :persistent {:topics {1 {:id 1 :label "An Example Topic" :state :to-do} 2 {:id 2 :label "Another Example Topic" :state :to-do} 3 {:id 3 :label "Example of somethng to discuss" :state :to-do}} :column-order {:to-do [3 1 2]}} :session-mode :collect})] (testing "doesn't retrieve topics with incorrect state" (is (= [] (subs/sorted-topics-with-state @test-db :fake-topic)))) (testing "does retrive topics of the right state" (is (= 3 (count (subs/sorted-topics-with-state @test-db :to-do)))) (is (= [3 1 2] (map #(:id %) (subs/sorted-topics-with-state @test-db :to-do))))))) (deftest test-topics-sorted-by-sorting (let [test-db (reagent/atom {:name "PI:NAME:<NAME>END_PI" :persistent {:topics {1 {:id 1 :label "An Example Topic" :state :to-do :votes 2} 2 {:id 2 :label "Another Example Topic" :state :to-do :votes 3} 3 {:id 3 :label "Example of somethng to discuss" :state :to-do :votes 1}} :column-order {:to-do [3 1 2]}} :session-mode :collect})] (testing "returns in correct order" (let [results (subs/topics-sorted-by @test-db :to-do :votes)] (is (= [2 1 3] (into [] (map #(:id %)) results))))))) (deftest test-topics-sorted-same-count (let [test-db (reagent/atom {:name "PI:NAME:<NAME>END_PI" :persistent {:topics {1 {:id 1 :label "An Example Topic" :state :to-do :votes 3} 2 {:id 2 :label "Another Example Topic" :state :to-do :votes 3} 3 {:id 3 :label "Example of somethng to discuss" :state :to-do :votes 1}} :column-order {:to-do [3 1 2]}} :session-mode :collect})] (testing "returns in correct order" (let [results (subs/topics-sorted-by @test-db :to-do :votes)] (is (= 3 (count (vals results)))) (is (= [2 1 3] (into [] (map #(:id %)) results)))))))
[ { "context": "iss \"https://rems.example/\"\n :sub \"user@example.com\"\n :iat (clj-time.coerce/to-epoch \"", "end": 503, "score": 0.999904453754425, "start": 487, "tag": "EMAIL", "value": "user@example.com" }, { "context": " \"urn:1234\" :start (time/date-time 2009) :userid \"user@example.com\"})))\n (is (= {:iss \"https://rems.example/\"", "end": 1034, "score": 0.9998985528945923, "start": 1018, "tag": "EMAIL", "value": "user@example.com" }, { "context": "iss \"https://rems.example/\"\n :sub \"user@example.com\"\n :iat (clj-time.coerce/to-epoch \"", "end": 1123, "score": 0.9999076724052429, "start": 1107, "tag": "EMAIL", "value": "user@example.com" }, { "context": "ime 2009) :end (time/date-time 2010 6 2) :userid \"user@example.com\"})))))))\n", "end": 1691, "score": 0.9999154210090637, "start": 1675, "tag": "EMAIL", "value": "user@example.com" } ]
test/clj/rems/test_ga4gh.clj
tjb/rems
31
(ns rems.test-ga4gh (:require [clj-time.coerce] [clj-time.core :as time] [clojure.test :refer :all] [rems.config :refer [env]] [rems.ga4gh :as ga4gh] [rems.testing-util :refer [with-fixed-time]])) (deftest test-entitlement->visa-claims (with-redefs [env {:public-url "https://rems.example/"}] (with-fixed-time (time/date-time 2010 01 01) (fn [] (is (= {:iss "https://rems.example/" :sub "user@example.com" :iat (clj-time.coerce/to-epoch "2010") :exp (clj-time.coerce/to-epoch "2011") :ga4gh_visa_v1 {:type "ControlledAccessGrants" :value "urn:1234" :source "https://rems.example/" :by "dac" :asserted (clj-time.coerce/to-epoch "2009")}} (#'ga4gh/entitlement->visa-claims {:resid "urn:1234" :start (time/date-time 2009) :userid "user@example.com"}))) (is (= {:iss "https://rems.example/" :sub "user@example.com" :iat (clj-time.coerce/to-epoch "2010") :exp (clj-time.coerce/to-epoch "2010-06-02") :ga4gh_visa_v1 {:type "ControlledAccessGrants" :value "urn:1234" :source "https://rems.example/" :by "dac" :asserted (clj-time.coerce/to-epoch "2009")}} (#'ga4gh/entitlement->visa-claims {:resid "urn:1234" :start (time/date-time 2009) :end (time/date-time 2010 6 2) :userid "user@example.com"})))))))
70335
(ns rems.test-ga4gh (:require [clj-time.coerce] [clj-time.core :as time] [clojure.test :refer :all] [rems.config :refer [env]] [rems.ga4gh :as ga4gh] [rems.testing-util :refer [with-fixed-time]])) (deftest test-entitlement->visa-claims (with-redefs [env {:public-url "https://rems.example/"}] (with-fixed-time (time/date-time 2010 01 01) (fn [] (is (= {:iss "https://rems.example/" :sub "<EMAIL>" :iat (clj-time.coerce/to-epoch "2010") :exp (clj-time.coerce/to-epoch "2011") :ga4gh_visa_v1 {:type "ControlledAccessGrants" :value "urn:1234" :source "https://rems.example/" :by "dac" :asserted (clj-time.coerce/to-epoch "2009")}} (#'ga4gh/entitlement->visa-claims {:resid "urn:1234" :start (time/date-time 2009) :userid "<EMAIL>"}))) (is (= {:iss "https://rems.example/" :sub "<EMAIL>" :iat (clj-time.coerce/to-epoch "2010") :exp (clj-time.coerce/to-epoch "2010-06-02") :ga4gh_visa_v1 {:type "ControlledAccessGrants" :value "urn:1234" :source "https://rems.example/" :by "dac" :asserted (clj-time.coerce/to-epoch "2009")}} (#'ga4gh/entitlement->visa-claims {:resid "urn:1234" :start (time/date-time 2009) :end (time/date-time 2010 6 2) :userid "<EMAIL>"})))))))
true
(ns rems.test-ga4gh (:require [clj-time.coerce] [clj-time.core :as time] [clojure.test :refer :all] [rems.config :refer [env]] [rems.ga4gh :as ga4gh] [rems.testing-util :refer [with-fixed-time]])) (deftest test-entitlement->visa-claims (with-redefs [env {:public-url "https://rems.example/"}] (with-fixed-time (time/date-time 2010 01 01) (fn [] (is (= {:iss "https://rems.example/" :sub "PI:EMAIL:<EMAIL>END_PI" :iat (clj-time.coerce/to-epoch "2010") :exp (clj-time.coerce/to-epoch "2011") :ga4gh_visa_v1 {:type "ControlledAccessGrants" :value "urn:1234" :source "https://rems.example/" :by "dac" :asserted (clj-time.coerce/to-epoch "2009")}} (#'ga4gh/entitlement->visa-claims {:resid "urn:1234" :start (time/date-time 2009) :userid "PI:EMAIL:<EMAIL>END_PI"}))) (is (= {:iss "https://rems.example/" :sub "PI:EMAIL:<EMAIL>END_PI" :iat (clj-time.coerce/to-epoch "2010") :exp (clj-time.coerce/to-epoch "2010-06-02") :ga4gh_visa_v1 {:type "ControlledAccessGrants" :value "urn:1234" :source "https://rems.example/" :by "dac" :asserted (clj-time.coerce/to-epoch "2009")}} (#'ga4gh/entitlement->visa-claims {:resid "urn:1234" :start (time/date-time 2009) :end (time/date-time 2010 6 2) :userid "PI:EMAIL:<EMAIL>END_PI"})))))))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.99981290102005, "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.9998220205307007, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/src/clj/editor/resource_io.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-io (:require [editor.resource :as resource] [dynamo.graph :as g]) (:import [java.io FileNotFoundException])) (defn file-not-found-error [node-id label severity resource] (g/->error node-id label severity nil (format "The file '%s' could not be found." (resource/proj-path resource)) {:type :file-not-found :resource resource})) (defn invalid-content-error [node-id label severity resource] (g/->error node-id label severity nil (format "The file '%s' could not be loaded." (resource/proj-path resource)) {:type :invalid-content :resource resource})) (defmacro with-error-translation "Perform body, translate io exceptions to g/errors" [resource node-id label & body] `(try ~@body (catch java.io.FileNotFoundException e# (file-not-found-error ~node-id ~label :fatal ~resource)) (catch Exception ~'_ (invalid-content-error ~node-id ~label :fatal ~resource))))
1255
;; 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-io (:require [editor.resource :as resource] [dynamo.graph :as g]) (:import [java.io FileNotFoundException])) (defn file-not-found-error [node-id label severity resource] (g/->error node-id label severity nil (format "The file '%s' could not be found." (resource/proj-path resource)) {:type :file-not-found :resource resource})) (defn invalid-content-error [node-id label severity resource] (g/->error node-id label severity nil (format "The file '%s' could not be loaded." (resource/proj-path resource)) {:type :invalid-content :resource resource})) (defmacro with-error-translation "Perform body, translate io exceptions to g/errors" [resource node-id label & body] `(try ~@body (catch java.io.FileNotFoundException e# (file-not-found-error ~node-id ~label :fatal ~resource)) (catch Exception ~'_ (invalid-content-error ~node-id ~label :fatal ~resource))))
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-io (:require [editor.resource :as resource] [dynamo.graph :as g]) (:import [java.io FileNotFoundException])) (defn file-not-found-error [node-id label severity resource] (g/->error node-id label severity nil (format "The file '%s' could not be found." (resource/proj-path resource)) {:type :file-not-found :resource resource})) (defn invalid-content-error [node-id label severity resource] (g/->error node-id label severity nil (format "The file '%s' could not be loaded." (resource/proj-path resource)) {:type :invalid-content :resource resource})) (defmacro with-error-translation "Perform body, translate io exceptions to g/errors" [resource node-id label & body] `(try ~@body (catch java.io.FileNotFoundException e# (file-not-found-error ~node-id ~label :fatal ~resource)) (catch Exception ~'_ (invalid-content-error ~node-id ~label :fatal ~resource))))
[ { "context": ";; Copyright 2018 Chris Rink\n;;\n;; Licensed under the Apache License, Version ", "end": 28, "score": 0.9998573660850525, "start": 18, "tag": "NAME", "value": "Chris Rink" } ]
src/clojure/slackbot/database/migrations.clj
chrisrink10/slackbot-clj
0
;; Copyright 2018 Chris Rink ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns slackbot.database.migrations (:require [ragtime.jdbc] [ragtime.repl] [slackbot.config :as config])) (defn jdbc-config [] (let [jdbc-url (config/config [:database :connection-string])] {:datastore (ragtime.jdbc/sql-database {:connection-uri jdbc-url}) :migrations (ragtime.jdbc/load-resources "migrations")})) (defn migrate [] (ragtime.repl/migrate (jdbc-config))) (defn rollback [] (ragtime.repl/rollback (jdbc-config)))
32520
;; Copyright 2018 <NAME> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns slackbot.database.migrations (:require [ragtime.jdbc] [ragtime.repl] [slackbot.config :as config])) (defn jdbc-config [] (let [jdbc-url (config/config [:database :connection-string])] {:datastore (ragtime.jdbc/sql-database {:connection-uri jdbc-url}) :migrations (ragtime.jdbc/load-resources "migrations")})) (defn migrate [] (ragtime.repl/migrate (jdbc-config))) (defn rollback [] (ragtime.repl/rollback (jdbc-config)))
true
;; Copyright 2018 PI:NAME:<NAME>END_PI ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns slackbot.database.migrations (:require [ragtime.jdbc] [ragtime.repl] [slackbot.config :as config])) (defn jdbc-config [] (let [jdbc-url (config/config [:database :connection-string])] {:datastore (ragtime.jdbc/sql-database {:connection-uri jdbc-url}) :migrations (ragtime.jdbc/load-resources "migrations")})) (defn migrate [] (ragtime.repl/migrate (jdbc-config))) (defn rollback [] (ragtime.repl/rollback (jdbc-config)))
[ { "context": ";;\n;; Common utilities and functions\n;; @author Antonio Garrote\n;;\n\n(ns #^{:author \"Antonio Garrote <antoniogarro", "end": 63, "score": 0.9998929500579834, "start": 48, "tag": "NAME", "value": "Antonio Garrote" }, { "context": "ns\n;; @author Antonio Garrote\n;;\n\n(ns #^{:author \"Antonio Garrote <antoniogarrote@gmail.com>\"\n :skip-wiki tru", "end": 99, "score": 0.9998923540115356, "start": 84, "tag": "NAME", "value": "Antonio Garrote" }, { "context": "onio Garrote\n;;\n\n(ns #^{:author \"Antonio Garrote <antoniogarrote@gmail.com>\"\n :skip-wiki true}\n clj-ml.utils\n (:impo", "end": 125, "score": 0.9999306797981262, "start": 101, "tag": "EMAIL", "value": "antoniogarrote@gmail.com" } ]
src/clj_ml/utils.clj
yogsototh/clj-ml
114
;; ;; Common utilities and functions ;; @author Antonio Garrote ;; (ns #^{:author "Antonio Garrote <antoniogarrote@gmail.com>" :skip-wiki true} clj-ml.utils (:import (java.io ObjectOutputStream ByteArrayOutputStream ByteArrayInputStream ObjectInputStream FileOutputStream FileInputStream) (java.security NoSuchAlgorithmException MessageDigest))) ;; taken from clojure.contrib.seq (defn find-first "Returns the first item of coll for which (pred item) returns logical true. Consumes sequences up to the first match, will consume the entire sequence and return nil if no match is found." [pred coll] (first (filter pred coll))) (defn first-or-default "Returns the first element in the collection or the default value" ([col default] (if (empty? col) default (first col)))) (defn into-fast-vector "Similar to into-array but returns a weka.core.FastVector" [coll] (let [fv (weka.core.FastVector.)] (doseq [item coll] (.addElement fv item)) fv)) (defn map-fast-vec [^weka.core.FastVector fast-vector f] (->> (.elements fast-vector) enumeration-seq (map f) into-fast-vector)) (defn update-in-when "Similar to update-in, but returns m unmodified if any levels do not exist" ([m [k & ks] f & args] (if (contains? m k) (if ks (assoc m k (apply update-in-when (get m k) ks f args)) (assoc m k (apply f (get m k) args))) m))) ;; trying metrics (defn try-metric [f] (try (f) (catch Exception ex {:nan (.getMessage ex)}))) (defn try-multiple-values-metric [class-values f] (loop [acum {} ks (keys class-values)] (if (empty? ks) acum (let [index (get class-values (first ks)) val (f index)] (recur (conj acum {(first ks) val}) (rest ks)))))) (defn md5-sum "Compute the hex MD5 sum of a string." [#^String str] (let [alg (doto (MessageDigest/getInstance "MD5") (.reset) (.update (.getBytes str)))] (try (.toString (new BigInteger 1 (.digest alg)) 16) (catch NoSuchAlgorithmException e (throw (new RuntimeException e)))))) ;; Serializing classifiers (defn serialize "Writes an object to memory" ([obj] (let [bs (new ByteArrayOutputStream) os (new ObjectOutputStream bs)] (.writeObject os obj) (.close os) (.toByteArray bs)))) (defn deserialize "Reads an object from memory" ([bytes] (let [bs (new ByteArrayInputStream bytes) is (new ObjectInputStream bs) obj (.readObject is)] (.close is) obj))) (defn serialize-to-file "Writes an object to a file" ([obj path] (let [fs (new FileOutputStream path) os (new ObjectOutputStream fs)] (.writeObject os obj) (.close os)) path)) (defn deserialize-from-file "Reads an object from a file" ([path] (let [fs (new FileInputStream path) is (new ObjectInputStream fs) obj (.readObject is)] (.close is) obj))) ;; capture stdout and stderr for noisy operations (defmacro capture-out-err [& body] `(let [console-out# System/out console-err# System/err ps# (java.io.PrintStream. (java.io.ByteArrayOutputStream.))] (System/setErr ps#) (System/setOut ps#) (let [result# (do ~@body)] (System/setErr console-err#) (System/setOut console-out#) result#)))
63395
;; ;; Common utilities and functions ;; @author <NAME> ;; (ns #^{:author "<NAME> <<EMAIL>>" :skip-wiki true} clj-ml.utils (:import (java.io ObjectOutputStream ByteArrayOutputStream ByteArrayInputStream ObjectInputStream FileOutputStream FileInputStream) (java.security NoSuchAlgorithmException MessageDigest))) ;; taken from clojure.contrib.seq (defn find-first "Returns the first item of coll for which (pred item) returns logical true. Consumes sequences up to the first match, will consume the entire sequence and return nil if no match is found." [pred coll] (first (filter pred coll))) (defn first-or-default "Returns the first element in the collection or the default value" ([col default] (if (empty? col) default (first col)))) (defn into-fast-vector "Similar to into-array but returns a weka.core.FastVector" [coll] (let [fv (weka.core.FastVector.)] (doseq [item coll] (.addElement fv item)) fv)) (defn map-fast-vec [^weka.core.FastVector fast-vector f] (->> (.elements fast-vector) enumeration-seq (map f) into-fast-vector)) (defn update-in-when "Similar to update-in, but returns m unmodified if any levels do not exist" ([m [k & ks] f & args] (if (contains? m k) (if ks (assoc m k (apply update-in-when (get m k) ks f args)) (assoc m k (apply f (get m k) args))) m))) ;; trying metrics (defn try-metric [f] (try (f) (catch Exception ex {:nan (.getMessage ex)}))) (defn try-multiple-values-metric [class-values f] (loop [acum {} ks (keys class-values)] (if (empty? ks) acum (let [index (get class-values (first ks)) val (f index)] (recur (conj acum {(first ks) val}) (rest ks)))))) (defn md5-sum "Compute the hex MD5 sum of a string." [#^String str] (let [alg (doto (MessageDigest/getInstance "MD5") (.reset) (.update (.getBytes str)))] (try (.toString (new BigInteger 1 (.digest alg)) 16) (catch NoSuchAlgorithmException e (throw (new RuntimeException e)))))) ;; Serializing classifiers (defn serialize "Writes an object to memory" ([obj] (let [bs (new ByteArrayOutputStream) os (new ObjectOutputStream bs)] (.writeObject os obj) (.close os) (.toByteArray bs)))) (defn deserialize "Reads an object from memory" ([bytes] (let [bs (new ByteArrayInputStream bytes) is (new ObjectInputStream bs) obj (.readObject is)] (.close is) obj))) (defn serialize-to-file "Writes an object to a file" ([obj path] (let [fs (new FileOutputStream path) os (new ObjectOutputStream fs)] (.writeObject os obj) (.close os)) path)) (defn deserialize-from-file "Reads an object from a file" ([path] (let [fs (new FileInputStream path) is (new ObjectInputStream fs) obj (.readObject is)] (.close is) obj))) ;; capture stdout and stderr for noisy operations (defmacro capture-out-err [& body] `(let [console-out# System/out console-err# System/err ps# (java.io.PrintStream. (java.io.ByteArrayOutputStream.))] (System/setErr ps#) (System/setOut ps#) (let [result# (do ~@body)] (System/setErr console-err#) (System/setOut console-out#) result#)))
true
;; ;; Common utilities and functions ;; @author PI:NAME:<NAME>END_PI ;; (ns #^{:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :skip-wiki true} clj-ml.utils (:import (java.io ObjectOutputStream ByteArrayOutputStream ByteArrayInputStream ObjectInputStream FileOutputStream FileInputStream) (java.security NoSuchAlgorithmException MessageDigest))) ;; taken from clojure.contrib.seq (defn find-first "Returns the first item of coll for which (pred item) returns logical true. Consumes sequences up to the first match, will consume the entire sequence and return nil if no match is found." [pred coll] (first (filter pred coll))) (defn first-or-default "Returns the first element in the collection or the default value" ([col default] (if (empty? col) default (first col)))) (defn into-fast-vector "Similar to into-array but returns a weka.core.FastVector" [coll] (let [fv (weka.core.FastVector.)] (doseq [item coll] (.addElement fv item)) fv)) (defn map-fast-vec [^weka.core.FastVector fast-vector f] (->> (.elements fast-vector) enumeration-seq (map f) into-fast-vector)) (defn update-in-when "Similar to update-in, but returns m unmodified if any levels do not exist" ([m [k & ks] f & args] (if (contains? m k) (if ks (assoc m k (apply update-in-when (get m k) ks f args)) (assoc m k (apply f (get m k) args))) m))) ;; trying metrics (defn try-metric [f] (try (f) (catch Exception ex {:nan (.getMessage ex)}))) (defn try-multiple-values-metric [class-values f] (loop [acum {} ks (keys class-values)] (if (empty? ks) acum (let [index (get class-values (first ks)) val (f index)] (recur (conj acum {(first ks) val}) (rest ks)))))) (defn md5-sum "Compute the hex MD5 sum of a string." [#^String str] (let [alg (doto (MessageDigest/getInstance "MD5") (.reset) (.update (.getBytes str)))] (try (.toString (new BigInteger 1 (.digest alg)) 16) (catch NoSuchAlgorithmException e (throw (new RuntimeException e)))))) ;; Serializing classifiers (defn serialize "Writes an object to memory" ([obj] (let [bs (new ByteArrayOutputStream) os (new ObjectOutputStream bs)] (.writeObject os obj) (.close os) (.toByteArray bs)))) (defn deserialize "Reads an object from memory" ([bytes] (let [bs (new ByteArrayInputStream bytes) is (new ObjectInputStream bs) obj (.readObject is)] (.close is) obj))) (defn serialize-to-file "Writes an object to a file" ([obj path] (let [fs (new FileOutputStream path) os (new ObjectOutputStream fs)] (.writeObject os obj) (.close os)) path)) (defn deserialize-from-file "Reads an object from a file" ([path] (let [fs (new FileInputStream path) is (new ObjectInputStream fs) obj (.readObject is)] (.close is) obj))) ;; capture stdout and stderr for noisy operations (defmacro capture-out-err [& body] `(let [console-out# System/out console-err# System/err ps# (java.io.PrintStream. (java.io.ByteArrayOutputStream.))] (System/setErr ps#) (System/setOut ps#) (let [result# (do ~@body)] (System/setErr console-err#) (System/setOut console-out#) result#)))
[ { "context": "tched prefix\")\n (is (nil? (#'s3/key->id nil \"x1040123abcd\"))\n \"should return nil for non-hex key\")", "end": 3748, "score": 0.9279553890228271, "start": 3736, "tag": "KEY", "value": "x1040123abcd" }, { "context": "tName \"test-bucket\")\n (.setKey \"foo/bar/abcxyz\")\n (.setSize 32)\n ", "end": 4483, "score": 0.9945673942565918, "start": 4469, "tag": "KEY", "value": "foo/bar/abcxyz" }, { "context": "ame \"test-bucket\")\n (.setKey \"foo/bar/11040123abcd\")\n (.setSize 45)\n ", "end": 4781, "score": 0.9787551164627075, "start": 4761, "tag": "KEY", "value": "foo/bar/11040123abcd" }, { "context": "s3/bucket \"test-bucket\"\n ::s3/key \"foo/bar/11040123abcd\"}\n (meta stats)))))\n (testing \"m", "end": 5065, "score": 0.9615277647972107, "start": 5045, "tag": "KEY", "value": "foo/bar/11040123abcd" }, { "context": "bucket \"test-bucket\"\n ::s3/key \"foo/bar/11040123abcd\"\n ::s3/metadata {}}\n ", "end": 5589, "score": 0.8580973148345947, "start": 5586, "tag": "KEY", "value": "bar" }, { "context": " \"test-bucket\"\n ::s3/key \"foo/bar/11040123abcd\"\n ::s3/metadata {}}\n ", "end": 5592, "score": 0.5539165735244751, "start": 5591, "tag": "KEY", "value": "1" }, { "context": "test-bucket\"\n ::s3/key \"foo/bar/11040123abcd\"\n ::s3/metadata {}}\n ", "end": 5602, "score": 0.9035714268684387, "start": 5593, "tag": "KEY", "value": "40123abcd" }, { "context": "t@foo-bar-data/foo/bar?region=us-west-2&sse=aes-256\")]\n (is (satisfies? blocks.store/BlockStore ", "end": 6775, "score": 0.9572249054908752, "start": 6774, "tag": "KEY", "value": "6" } ]
test/blocks/store/s3_test.clj
greglook/blocks-s3
13
(ns blocks.store.s3-test (:require [blocks.core :as block] [blocks.store :as store] [blocks.store.s3 :as s3 :refer [s3-block-store]] [blocks.store.tests :as tests] [clojure.test :refer [deftest testing is]] [com.stuartsierra.component :as component] [multiformats.hash :as multihash]) (:import (com.amazonaws.auth AWSCredentialsProvider BasicAWSCredentials) (com.amazonaws.services.s3 AmazonS3) (com.amazonaws.services.s3.model ObjectMetadata S3ObjectSummary) java.net.URI)) ;; ## S3 Utilities (deftest sse-algorithm-selection (is (thrown-with-msg? Exception #"Unsupported SSE algorithm :foo-bar" (#'s3/get-sse-algorithm :foo-bar))) (is (= "AES256" (#'s3/get-sse-algorithm :aes-256)))) (deftest region-selection (is (thrown-with-msg? Exception #"No supported region matching :foo" (#'s3/aws-region :foo))) (is (instance? com.amazonaws.regions.Regions (#'s3/aws-region :us-east-1))) (is (= "US_WEST_2" (str (#'s3/aws-region :us-west-2))))) (deftest auth-credentials (testing "default credentials" (is (instance? AWSCredentialsProvider (#'s3/credentials-provider nil)))) (testing "custom provider" (let [provider (reify AWSCredentialsProvider)] (is (identical? provider (#'s3/credentials-provider provider))))) (testing "static credentials" (let [creds (BasicAWSCredentials. "key" "secret") provider (#'s3/credentials-provider creds)] (is (instance? AWSCredentialsProvider provider)) (is (identical? creds (.getCredentials provider))))) (testing "map credentials" (is (thrown? Exception (#'s3/credentials-provider {:access-key "", :secret-key "secret"}))) (is (thrown? Exception (#'s3/credentials-provider {:access-key "key"}))) (testing "basic" (let [provider (#'s3/credentials-provider {:access-key "key" :secret-key "secret"})] (is (instance? AWSCredentialsProvider provider)) (let [creds (.getCredentials provider)] (is (= "key" (.getAWSAccessKeyId creds))) (is (= "secret" (.getAWSSecretKey creds)))))) (testing "session" (let [provider (#'s3/credentials-provider {:access-key "key" :secret-key "secret" :session-token "session"})] (is (instance? AWSCredentialsProvider provider)) (let [creds (.getCredentials provider)] (is (= "key" (.getAWSAccessKeyId creds))) (is (= "secret" (.getAWSSecretKey creds))) (is (= "session" (.getSessionToken creds))))))) (testing "bad creds" (is (thrown-with-msg? Exception #"Unknown credentials value type" (#'s3/credentials-provider "unintelligible"))))) (deftest client-construction (is (instance? AmazonS3 (#'s3/s3-client nil nil))) (is (instance? AmazonS3 (#'s3/s3-client nil :us-west-2)))) ;; ## S3 Keys (deftest uri-manipulation (testing "URI construction" (is (= (URI. "s3://my-data/foo/blocks/123abc") (#'s3/s3-uri "my-data" "foo/blocks/123abc")))) (testing "slash-trimming" (is (nil? (#'s3/trim-slashes ""))) (is (nil? (#'s3/trim-slashes " /// "))) (is (= "foo/bar" (#'s3/trim-slashes "/foo/bar/ "))))) (deftest key-parsing (testing "id->key" (is (= "foo/bar/11040123abcd" (#'s3/id->key "foo/bar/" (multihash/parse "11040123abcd"))) "id maps to hex encoding under prefix")) (testing "key->id" (let [mhash (multihash/parse "11040123abcd")] (is (nil? (#'s3/key->id "baz/" "foo/bar/11040123abcd")) "should return nil for mismatched prefix") (is (nil? (#'s3/key->id nil "x1040123abcd")) "should return nil for non-hex key") (is (= mhash (#'s3/key->id nil "11040123abcd")) "should return mhash for valid key with no prefix") (is (= mhash (#'s3/key->id "foo/" "foo/11040123abcd")) "should return mhash for valid key with prefix")))) ;; ## Stat Metadata (deftest stat-conversion (let [mhash (multihash/parse "11040123abcd") instant (java.time.Instant/parse "2019-03-10T19:59:00Z") date (java.util.Date. (.toEpochMilli instant))] (testing "summary-stats" (is (nil? (#'s3/summary-stats "foo/bar/" (doto (S3ObjectSummary.) (.setBucketName "test-bucket") (.setKey "foo/bar/abcxyz") (.setSize 32) (.setLastModified date))))) (let [stats (#'s3/summary-stats "foo/bar/" (doto (S3ObjectSummary.) (.setBucketName "test-bucket") (.setKey "foo/bar/11040123abcd") (.setSize 45) (.setLastModified date)))] (is (= {:id mhash :size 45 :stored-at instant} stats)) (is (= {::s3/bucket "test-bucket" ::s3/key "foo/bar/11040123abcd"} (meta stats))))) (testing "metadata-stats" (let [stats (#'s3/metadata-stats mhash "test-bucket" "foo/bar/11040123abcd" (doto (ObjectMetadata.) (.setContentLength 45) (.setLastModified date)))] (is (= {:id mhash :size 45 :stored-at instant} stats)) (is (= {::s3/bucket "test-bucket" ::s3/key "foo/bar/11040123abcd" ::s3/metadata {}} (meta stats))))))) ;; ## Object Content ,,, ;; ## Store Construction (deftest store-construction (is (thrown-with-msg? Exception #"Bucket name must be a non-empty string" (s3-block-store nil)) "bucket name should be required") (is (thrown-with-msg? Exception #"Bucket name must be a non-empty string" (s3-block-store " ")) "bucket name cannot be empty") (is (satisfies? store/BlockStore (s3-block-store "foo-bar-data"))) (is (nil? (:prefix (s3-block-store "foo-bucket" :prefix "")))) (is (nil? (:prefix (s3-block-store "foo-bucket" :prefix "/")))) (is (= "foo/" (:prefix (s3-block-store "foo-bucket" :prefix "foo")))) (is (= "bar/" (:prefix (s3-block-store "foo-bucket" :prefix "bar/"))))) (deftest uri-initialization (testing "simple spec" (let [store (block/->store "s3://foo-bar-data/foo/bar")] (is (satisfies? blocks.store/BlockStore store)) (is (= "foo-bar-data" (:bucket store))) (is (= "foo/bar/" (:prefix store))))) (testing "full spec" (let [store (block/->store "s3://key:secret@foo-bar-data/foo/bar?region=us-west-2&sse=aes-256")] (is (satisfies? blocks.store/BlockStore store)) (is (= "foo-bar-data" (:bucket store))) (is (= "foo/bar/" (:prefix store))) (is (= {:access-key "key", :secret-key "secret"} (:credentials store))) (is (= :us-west-2 (:region store))) (is (= :aes-256 (:sse store)))))) ;; ## Legacy Tests #_ (deftest block-creation (let [object->block @#'s3/object->block reference (block/read! "this is a block") calls (atom []) client (reify AmazonS3 (^S3Object getObject [this ^String bucket ^String object-key] (swap! calls conj [:getObject bucket object-key]) (doto (S3Object.) (.setObjectContent (block/open reference))))) block (object->block client "blocket" "data/test/" {:id (:id reference), :size (:size reference)})] (is (block/lazy? block) "should return lazy block") (is (= (:id reference) (:id block)) "returns correct id") (is (= (:size reference) (:size block)) "returns correct size") (is (empty? @calls) "no calls to S3 on block init") (is (= "this is a block" (slurp (block/open block))) "returns correct content from mock open") (is (= [[:getObject "blocket" (str "data/test/" (multihash/hex (:id reference)))]] @calls) "makes one call to getObject for open"))) #_ (deftest lazy-object-listing (let [list-objects-seq @#'s3/list-objects-seq bucket "blocket" prefix "data/" calls (atom nil) object-listing (fn [truncated? summaries] (proxy [ObjectListing] [] (getObjectSummaries [] summaries) (getBucketName [] bucket) (getPrefix [] prefix) (isTruncated [] (boolean truncated?)))) list-client (fn [results] (let [responses (atom (seq results))] (reify AmazonS3 (^ObjectListing listObjects [this ^ListObjectsRequest request] (swap! calls conj [:listObject request]) (let [result (first @responses)] (swap! responses next) result)))))] (testing "empty listing" (reset! calls []) (let [client (list-client [(object-listing false [])]) request (doto (ListObjectsRequest.) (.setBucketName bucket) (.setPrefix prefix)) listing (list-objects-seq client request)] (is (not (realized? listing)) "should create a lazy sequence") (is (empty? @calls) "should not make any calls until accessed") (is (empty? listing) "listing is empty seq") (is (= 1 (count @calls)) "should make one call") (is (= :listObject (first (first @calls))) "should make one listObjects call") (is (= request (second (first @calls))) "should use initial list request"))) (testing "full listing with no limit" (reset! calls []) (let [client (list-client [(object-listing false [::one ::two ::three])]) request (doto (ListObjectsRequest.) (.setBucketName bucket) (.setPrefix prefix)) listing (list-objects-seq client request)] (is (empty? @calls) "should not make any calls until accessed") (is (= [::one ::two ::three] listing) "listing has three elements") (is (= 1 (count @calls)) "should make one call"))) (testing "full listing with limited results" (reset! calls []) (let [client (list-client [(object-listing true [::one ::two]) (object-listing false [::three ::four])]) request (doto (ListObjectsRequest.) (.setBucketName bucket) (.setPrefix prefix) (.setMaxKeys (int 4))) listing (list-objects-seq client request)] (is (empty? @calls) "should not make any calls until accessed") (is (= ::one (first listing)) "first element from listing") (is (= 1 (count @calls)) "should make one call for first element") (is (= [::one ::two ::three ::four] listing) "full listing has four elements") (is (= 2 (count @calls)) "should make second call for full listing") (let [req (second (second @calls))] (is (= 2 (.getMaxKeys req)) "second call should reduce limit")))) (testing "full listing with truncated results" (reset! calls []) (let [client (list-client [(object-listing true [::one ::two]) (object-listing false [::three ::four])]) request (doto (ListObjectsRequest.) (.setBucketName bucket) (.setPrefix prefix)) listing (list-objects-seq client request)] (is (empty? @calls) "should not make any calls until accessed") (is (= ::one (first listing)) "first element from listing") (is (= 1 (count @calls)) "should make one call for first element") (is (= [::one ::two ::three ::four] listing) "full listing has four elements") (is (= 2 (count @calls)) "should make second call for full listing") (let [req (second (second @calls))] (is (nil? (.getMaxKeys req)) "second call should not have limit")))))) ;; ## Integration Tests (def access-key-var "AWS_ACCESS_KEY_ID") (def s3-bucket-var "BLOCKS_S3_BUCKET") (deftest ^:integration check-behavior (if (System/getenv access-key-var) (if-let [bucket (System/getenv s3-bucket-var)] (let [prefix (str *ns* "/" (System/currentTimeMillis))] (tests/check-store #(let [store (component/start (s3-block-store bucket :prefix prefix :region :us-west-2 :sse :aes-256))] @(block/erase! store) store))) (println "No" s3-bucket-var "in environment, skipping integration test!")) (println "No" access-key-var "in environment, skipping integration test!")))
10023
(ns blocks.store.s3-test (:require [blocks.core :as block] [blocks.store :as store] [blocks.store.s3 :as s3 :refer [s3-block-store]] [blocks.store.tests :as tests] [clojure.test :refer [deftest testing is]] [com.stuartsierra.component :as component] [multiformats.hash :as multihash]) (:import (com.amazonaws.auth AWSCredentialsProvider BasicAWSCredentials) (com.amazonaws.services.s3 AmazonS3) (com.amazonaws.services.s3.model ObjectMetadata S3ObjectSummary) java.net.URI)) ;; ## S3 Utilities (deftest sse-algorithm-selection (is (thrown-with-msg? Exception #"Unsupported SSE algorithm :foo-bar" (#'s3/get-sse-algorithm :foo-bar))) (is (= "AES256" (#'s3/get-sse-algorithm :aes-256)))) (deftest region-selection (is (thrown-with-msg? Exception #"No supported region matching :foo" (#'s3/aws-region :foo))) (is (instance? com.amazonaws.regions.Regions (#'s3/aws-region :us-east-1))) (is (= "US_WEST_2" (str (#'s3/aws-region :us-west-2))))) (deftest auth-credentials (testing "default credentials" (is (instance? AWSCredentialsProvider (#'s3/credentials-provider nil)))) (testing "custom provider" (let [provider (reify AWSCredentialsProvider)] (is (identical? provider (#'s3/credentials-provider provider))))) (testing "static credentials" (let [creds (BasicAWSCredentials. "key" "secret") provider (#'s3/credentials-provider creds)] (is (instance? AWSCredentialsProvider provider)) (is (identical? creds (.getCredentials provider))))) (testing "map credentials" (is (thrown? Exception (#'s3/credentials-provider {:access-key "", :secret-key "secret"}))) (is (thrown? Exception (#'s3/credentials-provider {:access-key "key"}))) (testing "basic" (let [provider (#'s3/credentials-provider {:access-key "key" :secret-key "secret"})] (is (instance? AWSCredentialsProvider provider)) (let [creds (.getCredentials provider)] (is (= "key" (.getAWSAccessKeyId creds))) (is (= "secret" (.getAWSSecretKey creds)))))) (testing "session" (let [provider (#'s3/credentials-provider {:access-key "key" :secret-key "secret" :session-token "session"})] (is (instance? AWSCredentialsProvider provider)) (let [creds (.getCredentials provider)] (is (= "key" (.getAWSAccessKeyId creds))) (is (= "secret" (.getAWSSecretKey creds))) (is (= "session" (.getSessionToken creds))))))) (testing "bad creds" (is (thrown-with-msg? Exception #"Unknown credentials value type" (#'s3/credentials-provider "unintelligible"))))) (deftest client-construction (is (instance? AmazonS3 (#'s3/s3-client nil nil))) (is (instance? AmazonS3 (#'s3/s3-client nil :us-west-2)))) ;; ## S3 Keys (deftest uri-manipulation (testing "URI construction" (is (= (URI. "s3://my-data/foo/blocks/123abc") (#'s3/s3-uri "my-data" "foo/blocks/123abc")))) (testing "slash-trimming" (is (nil? (#'s3/trim-slashes ""))) (is (nil? (#'s3/trim-slashes " /// "))) (is (= "foo/bar" (#'s3/trim-slashes "/foo/bar/ "))))) (deftest key-parsing (testing "id->key" (is (= "foo/bar/11040123abcd" (#'s3/id->key "foo/bar/" (multihash/parse "11040123abcd"))) "id maps to hex encoding under prefix")) (testing "key->id" (let [mhash (multihash/parse "11040123abcd")] (is (nil? (#'s3/key->id "baz/" "foo/bar/11040123abcd")) "should return nil for mismatched prefix") (is (nil? (#'s3/key->id nil "<KEY>")) "should return nil for non-hex key") (is (= mhash (#'s3/key->id nil "11040123abcd")) "should return mhash for valid key with no prefix") (is (= mhash (#'s3/key->id "foo/" "foo/11040123abcd")) "should return mhash for valid key with prefix")))) ;; ## Stat Metadata (deftest stat-conversion (let [mhash (multihash/parse "11040123abcd") instant (java.time.Instant/parse "2019-03-10T19:59:00Z") date (java.util.Date. (.toEpochMilli instant))] (testing "summary-stats" (is (nil? (#'s3/summary-stats "foo/bar/" (doto (S3ObjectSummary.) (.setBucketName "test-bucket") (.setKey "<KEY>") (.setSize 32) (.setLastModified date))))) (let [stats (#'s3/summary-stats "foo/bar/" (doto (S3ObjectSummary.) (.setBucketName "test-bucket") (.setKey "<KEY>") (.setSize 45) (.setLastModified date)))] (is (= {:id mhash :size 45 :stored-at instant} stats)) (is (= {::s3/bucket "test-bucket" ::s3/key "<KEY>"} (meta stats))))) (testing "metadata-stats" (let [stats (#'s3/metadata-stats mhash "test-bucket" "foo/bar/11040123abcd" (doto (ObjectMetadata.) (.setContentLength 45) (.setLastModified date)))] (is (= {:id mhash :size 45 :stored-at instant} stats)) (is (= {::s3/bucket "test-bucket" ::s3/key "foo/<KEY>/1<KEY>0<KEY>" ::s3/metadata {}} (meta stats))))))) ;; ## Object Content ,,, ;; ## Store Construction (deftest store-construction (is (thrown-with-msg? Exception #"Bucket name must be a non-empty string" (s3-block-store nil)) "bucket name should be required") (is (thrown-with-msg? Exception #"Bucket name must be a non-empty string" (s3-block-store " ")) "bucket name cannot be empty") (is (satisfies? store/BlockStore (s3-block-store "foo-bar-data"))) (is (nil? (:prefix (s3-block-store "foo-bucket" :prefix "")))) (is (nil? (:prefix (s3-block-store "foo-bucket" :prefix "/")))) (is (= "foo/" (:prefix (s3-block-store "foo-bucket" :prefix "foo")))) (is (= "bar/" (:prefix (s3-block-store "foo-bucket" :prefix "bar/"))))) (deftest uri-initialization (testing "simple spec" (let [store (block/->store "s3://foo-bar-data/foo/bar")] (is (satisfies? blocks.store/BlockStore store)) (is (= "foo-bar-data" (:bucket store))) (is (= "foo/bar/" (:prefix store))))) (testing "full spec" (let [store (block/->store "s3://key:secret@foo-bar-data/foo/bar?region=us-west-2&sse=aes-25<KEY>")] (is (satisfies? blocks.store/BlockStore store)) (is (= "foo-bar-data" (:bucket store))) (is (= "foo/bar/" (:prefix store))) (is (= {:access-key "key", :secret-key "secret"} (:credentials store))) (is (= :us-west-2 (:region store))) (is (= :aes-256 (:sse store)))))) ;; ## Legacy Tests #_ (deftest block-creation (let [object->block @#'s3/object->block reference (block/read! "this is a block") calls (atom []) client (reify AmazonS3 (^S3Object getObject [this ^String bucket ^String object-key] (swap! calls conj [:getObject bucket object-key]) (doto (S3Object.) (.setObjectContent (block/open reference))))) block (object->block client "blocket" "data/test/" {:id (:id reference), :size (:size reference)})] (is (block/lazy? block) "should return lazy block") (is (= (:id reference) (:id block)) "returns correct id") (is (= (:size reference) (:size block)) "returns correct size") (is (empty? @calls) "no calls to S3 on block init") (is (= "this is a block" (slurp (block/open block))) "returns correct content from mock open") (is (= [[:getObject "blocket" (str "data/test/" (multihash/hex (:id reference)))]] @calls) "makes one call to getObject for open"))) #_ (deftest lazy-object-listing (let [list-objects-seq @#'s3/list-objects-seq bucket "blocket" prefix "data/" calls (atom nil) object-listing (fn [truncated? summaries] (proxy [ObjectListing] [] (getObjectSummaries [] summaries) (getBucketName [] bucket) (getPrefix [] prefix) (isTruncated [] (boolean truncated?)))) list-client (fn [results] (let [responses (atom (seq results))] (reify AmazonS3 (^ObjectListing listObjects [this ^ListObjectsRequest request] (swap! calls conj [:listObject request]) (let [result (first @responses)] (swap! responses next) result)))))] (testing "empty listing" (reset! calls []) (let [client (list-client [(object-listing false [])]) request (doto (ListObjectsRequest.) (.setBucketName bucket) (.setPrefix prefix)) listing (list-objects-seq client request)] (is (not (realized? listing)) "should create a lazy sequence") (is (empty? @calls) "should not make any calls until accessed") (is (empty? listing) "listing is empty seq") (is (= 1 (count @calls)) "should make one call") (is (= :listObject (first (first @calls))) "should make one listObjects call") (is (= request (second (first @calls))) "should use initial list request"))) (testing "full listing with no limit" (reset! calls []) (let [client (list-client [(object-listing false [::one ::two ::three])]) request (doto (ListObjectsRequest.) (.setBucketName bucket) (.setPrefix prefix)) listing (list-objects-seq client request)] (is (empty? @calls) "should not make any calls until accessed") (is (= [::one ::two ::three] listing) "listing has three elements") (is (= 1 (count @calls)) "should make one call"))) (testing "full listing with limited results" (reset! calls []) (let [client (list-client [(object-listing true [::one ::two]) (object-listing false [::three ::four])]) request (doto (ListObjectsRequest.) (.setBucketName bucket) (.setPrefix prefix) (.setMaxKeys (int 4))) listing (list-objects-seq client request)] (is (empty? @calls) "should not make any calls until accessed") (is (= ::one (first listing)) "first element from listing") (is (= 1 (count @calls)) "should make one call for first element") (is (= [::one ::two ::three ::four] listing) "full listing has four elements") (is (= 2 (count @calls)) "should make second call for full listing") (let [req (second (second @calls))] (is (= 2 (.getMaxKeys req)) "second call should reduce limit")))) (testing "full listing with truncated results" (reset! calls []) (let [client (list-client [(object-listing true [::one ::two]) (object-listing false [::three ::four])]) request (doto (ListObjectsRequest.) (.setBucketName bucket) (.setPrefix prefix)) listing (list-objects-seq client request)] (is (empty? @calls) "should not make any calls until accessed") (is (= ::one (first listing)) "first element from listing") (is (= 1 (count @calls)) "should make one call for first element") (is (= [::one ::two ::three ::four] listing) "full listing has four elements") (is (= 2 (count @calls)) "should make second call for full listing") (let [req (second (second @calls))] (is (nil? (.getMaxKeys req)) "second call should not have limit")))))) ;; ## Integration Tests (def access-key-var "AWS_ACCESS_KEY_ID") (def s3-bucket-var "BLOCKS_S3_BUCKET") (deftest ^:integration check-behavior (if (System/getenv access-key-var) (if-let [bucket (System/getenv s3-bucket-var)] (let [prefix (str *ns* "/" (System/currentTimeMillis))] (tests/check-store #(let [store (component/start (s3-block-store bucket :prefix prefix :region :us-west-2 :sse :aes-256))] @(block/erase! store) store))) (println "No" s3-bucket-var "in environment, skipping integration test!")) (println "No" access-key-var "in environment, skipping integration test!")))
true
(ns blocks.store.s3-test (:require [blocks.core :as block] [blocks.store :as store] [blocks.store.s3 :as s3 :refer [s3-block-store]] [blocks.store.tests :as tests] [clojure.test :refer [deftest testing is]] [com.stuartsierra.component :as component] [multiformats.hash :as multihash]) (:import (com.amazonaws.auth AWSCredentialsProvider BasicAWSCredentials) (com.amazonaws.services.s3 AmazonS3) (com.amazonaws.services.s3.model ObjectMetadata S3ObjectSummary) java.net.URI)) ;; ## S3 Utilities (deftest sse-algorithm-selection (is (thrown-with-msg? Exception #"Unsupported SSE algorithm :foo-bar" (#'s3/get-sse-algorithm :foo-bar))) (is (= "AES256" (#'s3/get-sse-algorithm :aes-256)))) (deftest region-selection (is (thrown-with-msg? Exception #"No supported region matching :foo" (#'s3/aws-region :foo))) (is (instance? com.amazonaws.regions.Regions (#'s3/aws-region :us-east-1))) (is (= "US_WEST_2" (str (#'s3/aws-region :us-west-2))))) (deftest auth-credentials (testing "default credentials" (is (instance? AWSCredentialsProvider (#'s3/credentials-provider nil)))) (testing "custom provider" (let [provider (reify AWSCredentialsProvider)] (is (identical? provider (#'s3/credentials-provider provider))))) (testing "static credentials" (let [creds (BasicAWSCredentials. "key" "secret") provider (#'s3/credentials-provider creds)] (is (instance? AWSCredentialsProvider provider)) (is (identical? creds (.getCredentials provider))))) (testing "map credentials" (is (thrown? Exception (#'s3/credentials-provider {:access-key "", :secret-key "secret"}))) (is (thrown? Exception (#'s3/credentials-provider {:access-key "key"}))) (testing "basic" (let [provider (#'s3/credentials-provider {:access-key "key" :secret-key "secret"})] (is (instance? AWSCredentialsProvider provider)) (let [creds (.getCredentials provider)] (is (= "key" (.getAWSAccessKeyId creds))) (is (= "secret" (.getAWSSecretKey creds)))))) (testing "session" (let [provider (#'s3/credentials-provider {:access-key "key" :secret-key "secret" :session-token "session"})] (is (instance? AWSCredentialsProvider provider)) (let [creds (.getCredentials provider)] (is (= "key" (.getAWSAccessKeyId creds))) (is (= "secret" (.getAWSSecretKey creds))) (is (= "session" (.getSessionToken creds))))))) (testing "bad creds" (is (thrown-with-msg? Exception #"Unknown credentials value type" (#'s3/credentials-provider "unintelligible"))))) (deftest client-construction (is (instance? AmazonS3 (#'s3/s3-client nil nil))) (is (instance? AmazonS3 (#'s3/s3-client nil :us-west-2)))) ;; ## S3 Keys (deftest uri-manipulation (testing "URI construction" (is (= (URI. "s3://my-data/foo/blocks/123abc") (#'s3/s3-uri "my-data" "foo/blocks/123abc")))) (testing "slash-trimming" (is (nil? (#'s3/trim-slashes ""))) (is (nil? (#'s3/trim-slashes " /// "))) (is (= "foo/bar" (#'s3/trim-slashes "/foo/bar/ "))))) (deftest key-parsing (testing "id->key" (is (= "foo/bar/11040123abcd" (#'s3/id->key "foo/bar/" (multihash/parse "11040123abcd"))) "id maps to hex encoding under prefix")) (testing "key->id" (let [mhash (multihash/parse "11040123abcd")] (is (nil? (#'s3/key->id "baz/" "foo/bar/11040123abcd")) "should return nil for mismatched prefix") (is (nil? (#'s3/key->id nil "PI:KEY:<KEY>END_PI")) "should return nil for non-hex key") (is (= mhash (#'s3/key->id nil "11040123abcd")) "should return mhash for valid key with no prefix") (is (= mhash (#'s3/key->id "foo/" "foo/11040123abcd")) "should return mhash for valid key with prefix")))) ;; ## Stat Metadata (deftest stat-conversion (let [mhash (multihash/parse "11040123abcd") instant (java.time.Instant/parse "2019-03-10T19:59:00Z") date (java.util.Date. (.toEpochMilli instant))] (testing "summary-stats" (is (nil? (#'s3/summary-stats "foo/bar/" (doto (S3ObjectSummary.) (.setBucketName "test-bucket") (.setKey "PI:KEY:<KEY>END_PI") (.setSize 32) (.setLastModified date))))) (let [stats (#'s3/summary-stats "foo/bar/" (doto (S3ObjectSummary.) (.setBucketName "test-bucket") (.setKey "PI:KEY:<KEY>END_PI") (.setSize 45) (.setLastModified date)))] (is (= {:id mhash :size 45 :stored-at instant} stats)) (is (= {::s3/bucket "test-bucket" ::s3/key "PI:KEY:<KEY>END_PI"} (meta stats))))) (testing "metadata-stats" (let [stats (#'s3/metadata-stats mhash "test-bucket" "foo/bar/11040123abcd" (doto (ObjectMetadata.) (.setContentLength 45) (.setLastModified date)))] (is (= {:id mhash :size 45 :stored-at instant} stats)) (is (= {::s3/bucket "test-bucket" ::s3/key "foo/PI:KEY:<KEY>END_PI/1PI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PI" ::s3/metadata {}} (meta stats))))))) ;; ## Object Content ,,, ;; ## Store Construction (deftest store-construction (is (thrown-with-msg? Exception #"Bucket name must be a non-empty string" (s3-block-store nil)) "bucket name should be required") (is (thrown-with-msg? Exception #"Bucket name must be a non-empty string" (s3-block-store " ")) "bucket name cannot be empty") (is (satisfies? store/BlockStore (s3-block-store "foo-bar-data"))) (is (nil? (:prefix (s3-block-store "foo-bucket" :prefix "")))) (is (nil? (:prefix (s3-block-store "foo-bucket" :prefix "/")))) (is (= "foo/" (:prefix (s3-block-store "foo-bucket" :prefix "foo")))) (is (= "bar/" (:prefix (s3-block-store "foo-bucket" :prefix "bar/"))))) (deftest uri-initialization (testing "simple spec" (let [store (block/->store "s3://foo-bar-data/foo/bar")] (is (satisfies? blocks.store/BlockStore store)) (is (= "foo-bar-data" (:bucket store))) (is (= "foo/bar/" (:prefix store))))) (testing "full spec" (let [store (block/->store "s3://key:secret@foo-bar-data/foo/bar?region=us-west-2&sse=aes-25PI:KEY:<KEY>END_PI")] (is (satisfies? blocks.store/BlockStore store)) (is (= "foo-bar-data" (:bucket store))) (is (= "foo/bar/" (:prefix store))) (is (= {:access-key "key", :secret-key "secret"} (:credentials store))) (is (= :us-west-2 (:region store))) (is (= :aes-256 (:sse store)))))) ;; ## Legacy Tests #_ (deftest block-creation (let [object->block @#'s3/object->block reference (block/read! "this is a block") calls (atom []) client (reify AmazonS3 (^S3Object getObject [this ^String bucket ^String object-key] (swap! calls conj [:getObject bucket object-key]) (doto (S3Object.) (.setObjectContent (block/open reference))))) block (object->block client "blocket" "data/test/" {:id (:id reference), :size (:size reference)})] (is (block/lazy? block) "should return lazy block") (is (= (:id reference) (:id block)) "returns correct id") (is (= (:size reference) (:size block)) "returns correct size") (is (empty? @calls) "no calls to S3 on block init") (is (= "this is a block" (slurp (block/open block))) "returns correct content from mock open") (is (= [[:getObject "blocket" (str "data/test/" (multihash/hex (:id reference)))]] @calls) "makes one call to getObject for open"))) #_ (deftest lazy-object-listing (let [list-objects-seq @#'s3/list-objects-seq bucket "blocket" prefix "data/" calls (atom nil) object-listing (fn [truncated? summaries] (proxy [ObjectListing] [] (getObjectSummaries [] summaries) (getBucketName [] bucket) (getPrefix [] prefix) (isTruncated [] (boolean truncated?)))) list-client (fn [results] (let [responses (atom (seq results))] (reify AmazonS3 (^ObjectListing listObjects [this ^ListObjectsRequest request] (swap! calls conj [:listObject request]) (let [result (first @responses)] (swap! responses next) result)))))] (testing "empty listing" (reset! calls []) (let [client (list-client [(object-listing false [])]) request (doto (ListObjectsRequest.) (.setBucketName bucket) (.setPrefix prefix)) listing (list-objects-seq client request)] (is (not (realized? listing)) "should create a lazy sequence") (is (empty? @calls) "should not make any calls until accessed") (is (empty? listing) "listing is empty seq") (is (= 1 (count @calls)) "should make one call") (is (= :listObject (first (first @calls))) "should make one listObjects call") (is (= request (second (first @calls))) "should use initial list request"))) (testing "full listing with no limit" (reset! calls []) (let [client (list-client [(object-listing false [::one ::two ::three])]) request (doto (ListObjectsRequest.) (.setBucketName bucket) (.setPrefix prefix)) listing (list-objects-seq client request)] (is (empty? @calls) "should not make any calls until accessed") (is (= [::one ::two ::three] listing) "listing has three elements") (is (= 1 (count @calls)) "should make one call"))) (testing "full listing with limited results" (reset! calls []) (let [client (list-client [(object-listing true [::one ::two]) (object-listing false [::three ::four])]) request (doto (ListObjectsRequest.) (.setBucketName bucket) (.setPrefix prefix) (.setMaxKeys (int 4))) listing (list-objects-seq client request)] (is (empty? @calls) "should not make any calls until accessed") (is (= ::one (first listing)) "first element from listing") (is (= 1 (count @calls)) "should make one call for first element") (is (= [::one ::two ::three ::four] listing) "full listing has four elements") (is (= 2 (count @calls)) "should make second call for full listing") (let [req (second (second @calls))] (is (= 2 (.getMaxKeys req)) "second call should reduce limit")))) (testing "full listing with truncated results" (reset! calls []) (let [client (list-client [(object-listing true [::one ::two]) (object-listing false [::three ::four])]) request (doto (ListObjectsRequest.) (.setBucketName bucket) (.setPrefix prefix)) listing (list-objects-seq client request)] (is (empty? @calls) "should not make any calls until accessed") (is (= ::one (first listing)) "first element from listing") (is (= 1 (count @calls)) "should make one call for first element") (is (= [::one ::two ::three ::four] listing) "full listing has four elements") (is (= 2 (count @calls)) "should make second call for full listing") (let [req (second (second @calls))] (is (nil? (.getMaxKeys req)) "second call should not have limit")))))) ;; ## Integration Tests (def access-key-var "AWS_ACCESS_KEY_ID") (def s3-bucket-var "BLOCKS_S3_BUCKET") (deftest ^:integration check-behavior (if (System/getenv access-key-var) (if-let [bucket (System/getenv s3-bucket-var)] (let [prefix (str *ns* "/" (System/currentTimeMillis))] (tests/check-store #(let [store (component/start (s3-block-store bucket :prefix prefix :region :us-west-2 :sse :aes-256))] @(block/erase! store) store))) (println "No" s3-bucket-var "in environment, skipping integration test!")) (println "No" access-key-var "in environment, skipping integration test!")))
[ { "context": "unctions to midi->cps conversion.\"\n :author \"Jeff Rose & Sam Aaron\"}\n\n overtone.sc.machinery.ugen.speci", "end": 304, "score": 0.9998847842216492, "start": 295, "tag": "NAME", "value": "Jeff Rose" }, { "context": " midi->cps conversion.\"\n :author \"Jeff Rose & Sam Aaron\"}\n\n overtone.sc.machinery.ugen.special-ops)\n\n(de", "end": 316, "score": 0.9998847842216492, "start": 307, "tag": "NAME", "value": "Sam Aaron" } ]
src/overtone/sc/machinery/ugen/special_ops.clj
josephwilk/overtone
1
(ns ^{:doc "Metadata regarding the various functionalities of the unary and binary ugens. These ugens are different to typical ugens in that they receive an 'opcode' as a parameter which defines its behviour - ranging from addition to trig functions to midi->cps conversion." :author "Jeff Rose & Sam Aaron"} overtone.sc.machinery.ugen.special-ops) (def UNARY-OPS {"neg" 0 ; inversion "not-pos?" 1 ; 0 when a < 0, +1 when a > 0, 1 when a is 0 ;;"is-nil" 2 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"not-nil" 3 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"bitNot" 4 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server "abs" 5 ; absolute value ;;"asFloat" 6 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"asInt" 7 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server "ceil" 8 ; next higher integer "floor" 9 ; next lower integer "frac" 10 ; fractional part "sign" 11 ; -1 when a < 0, +1 when a > 0, 0 when a is 0 "squared" 12 ; a*a "cubed" 13 ; a*a*a "sqrt" 14 ; square root "exp" 15 ; exponential "reciprocal" 16 ; reciprocal "midicps" 17 ; MIDI note number to cycles per second "cpsmidi" 18 ; cycles per second to MIDI note number "midiratio" 19 ; convert an interval in MIDI notes into a frequency ratio "ratiomidi" 20 ; convert a frequency ratio to an interval in MIDI notes "dbamp" 21 ; decibels to linear amplitude "ampdb" 22 ; linear amplitude to decibels "octcps" 23 ; decimal octaves to cycles per second "cpsoct" 24 ; cycles per second to decimal octaves "log" 25 ; natural logarithm "log2" 26 ; base 2 logarithm "log10" 27 ; base 10 logarithm "sin" 28 ; sine "cos" 29 ; cosine "tan" 30 ; tangent "asin" 31 ; arcsine "acos" 32 ; arccosine "atan" 33 ; arctangent "sinh" 34 ; hyperbolic sine "cosh" 35 ; hyperbolic cosine "tanh" 36 ; hyperbolic tangent ;;"rand" 37 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"rand2" 38 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"linrand" 39 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"bilinrand" 40; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"sum3rand" 41 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server "distort" 42 ; distortion "softclip" 43 ; distortion ;;"coin" 44 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"digit-val" 45; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"silence" 46 ; outputs 0 - no need to include it as we already have the silent ugen ;;"thru" 47 ; outputs what was received - not useful "rectWindow" 48 ; rectangular window "hanWindow" 49 ; hanning window "welWindow" 50 ; welch window "triWindow" 51 ; triangle window ;;"ramp" 52 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"scurve" 53 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server }) (def REVERSE-UNARY-OPS (zipmap (vals UNARY-OPS) (keys UNARY-OPS))) ; Commented out ops are implemented with generics instead of generated ; see sc/ops.clj (def BINARY-OPS { "+" 0 ; Addition "-" 1 ; Subtraction "*" 2 ; Multiplication ;;"div" 3 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server "/" 4 ; Division "mod" 5 ; Modulus "=" 6 ; Equality "not=" 7 ; Inequality "<" 8 ; Less than ">" 9 ; Greater than "<=" 10 ; Less than or equal to ">=" 11 ; Greater than or equal to "min" 12 ; minimum "max" 13 ; maximum "and" 14 ; and (where pos sig is true) "or" 15 ; or (where pos sig is true "xor" 16 ; xor (where pos sig is true) ;;"lcm" 17 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"gcd" 18 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server "round" 19 ; Round to nearest multiple "round-up" 20 ; Round up to next multiple "round-down" 21 ; Round down to previous multiple "atan2" 22 ; arctangent of a/b "hypot" 23 ; length of hypotenuse via Pythag "hypot-aprox" 24 ; approximation of length of hypotenuse "pow" 25 ; exponentiation ;;"leftShift" 26 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"rightShift" 27 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"un-r-shift" 28 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"fill" 29 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server "ring1" 30 ; a * (b + 1) == a * b + a "ring2" 31 ; a * b + a + b "ring3" 32 ; a*a*b "ring4" 33 ; a*a*b - a*b*b "difsqr" 34 ; a*a - b*b "sumsqr" 35 ; a*a + b*b "sqrsum" 36 ; (a + b)^2 "sqrdif" 37 ; (a - b)^2 "absdif" 38 ; |a - b| "thresh" 39 ; Signal thresholding "amclip" 40 ; Two quadrant multiply "scale-neg" 41 ; scale negative part of input wave "clip2" 42 ; bilateral clipping "excess" 43 ; clipping residual "fold2" 44 ; bilateral folding "wrap2" 45 ; bilateral wrapping ;;"first-arg" 46 ; Returns the first arg unchanged - not useful. ;;"rrand" 47 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"exprand" 48 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server }) (def FOLDABLE-BINARY-OPS #{"+" "-" "*" "/" "<" ">" "<=" ">=" "min" "max" "and" "or"}) ;;the following are Clojure fns that can only take numerical args (def NUMERICAL-CLOJURE-FNS #{"+" "*" "-" "/" "<" ">" "<=" ">=" "min" "max" "mod"}) (def REVERSE-BINARY-OPS (zipmap (vals BINARY-OPS) (keys BINARY-OPS))) (defn unary-op-num [name] (get UNARY-OPS (str name) false)) (defn binary-op-num [name] (get BINARY-OPS (str name) false)) (def binary-op-unary-modes {"+" (fn [ugen-fn arg] (ugen-fn 0 arg)) "-" (fn [ugen-fn arg] (ugen-fn 0 arg)) "*" (fn [ugen-fn arg] (ugen-fn 1 arg)) "/" (fn [ugen-fn arg] (ugen-fn 1 arg)) "=" (fn [ugen-fn arg] (ugen-fn arg arg)) "not=" (fn [ugen-fn arg] (ugen-fn arg arg))})
57529
(ns ^{:doc "Metadata regarding the various functionalities of the unary and binary ugens. These ugens are different to typical ugens in that they receive an 'opcode' as a parameter which defines its behviour - ranging from addition to trig functions to midi->cps conversion." :author "<NAME> & <NAME>"} overtone.sc.machinery.ugen.special-ops) (def UNARY-OPS {"neg" 0 ; inversion "not-pos?" 1 ; 0 when a < 0, +1 when a > 0, 1 when a is 0 ;;"is-nil" 2 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"not-nil" 3 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"bitNot" 4 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server "abs" 5 ; absolute value ;;"asFloat" 6 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"asInt" 7 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server "ceil" 8 ; next higher integer "floor" 9 ; next lower integer "frac" 10 ; fractional part "sign" 11 ; -1 when a < 0, +1 when a > 0, 0 when a is 0 "squared" 12 ; a*a "cubed" 13 ; a*a*a "sqrt" 14 ; square root "exp" 15 ; exponential "reciprocal" 16 ; reciprocal "midicps" 17 ; MIDI note number to cycles per second "cpsmidi" 18 ; cycles per second to MIDI note number "midiratio" 19 ; convert an interval in MIDI notes into a frequency ratio "ratiomidi" 20 ; convert a frequency ratio to an interval in MIDI notes "dbamp" 21 ; decibels to linear amplitude "ampdb" 22 ; linear amplitude to decibels "octcps" 23 ; decimal octaves to cycles per second "cpsoct" 24 ; cycles per second to decimal octaves "log" 25 ; natural logarithm "log2" 26 ; base 2 logarithm "log10" 27 ; base 10 logarithm "sin" 28 ; sine "cos" 29 ; cosine "tan" 30 ; tangent "asin" 31 ; arcsine "acos" 32 ; arccosine "atan" 33 ; arctangent "sinh" 34 ; hyperbolic sine "cosh" 35 ; hyperbolic cosine "tanh" 36 ; hyperbolic tangent ;;"rand" 37 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"rand2" 38 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"linrand" 39 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"bilinrand" 40; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"sum3rand" 41 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server "distort" 42 ; distortion "softclip" 43 ; distortion ;;"coin" 44 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"digit-val" 45; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"silence" 46 ; outputs 0 - no need to include it as we already have the silent ugen ;;"thru" 47 ; outputs what was received - not useful "rectWindow" 48 ; rectangular window "hanWindow" 49 ; hanning window "welWindow" 50 ; welch window "triWindow" 51 ; triangle window ;;"ramp" 52 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"scurve" 53 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server }) (def REVERSE-UNARY-OPS (zipmap (vals UNARY-OPS) (keys UNARY-OPS))) ; Commented out ops are implemented with generics instead of generated ; see sc/ops.clj (def BINARY-OPS { "+" 0 ; Addition "-" 1 ; Subtraction "*" 2 ; Multiplication ;;"div" 3 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server "/" 4 ; Division "mod" 5 ; Modulus "=" 6 ; Equality "not=" 7 ; Inequality "<" 8 ; Less than ">" 9 ; Greater than "<=" 10 ; Less than or equal to ">=" 11 ; Greater than or equal to "min" 12 ; minimum "max" 13 ; maximum "and" 14 ; and (where pos sig is true) "or" 15 ; or (where pos sig is true "xor" 16 ; xor (where pos sig is true) ;;"lcm" 17 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"gcd" 18 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server "round" 19 ; Round to nearest multiple "round-up" 20 ; Round up to next multiple "round-down" 21 ; Round down to previous multiple "atan2" 22 ; arctangent of a/b "hypot" 23 ; length of hypotenuse via Pythag "hypot-aprox" 24 ; approximation of length of hypotenuse "pow" 25 ; exponentiation ;;"leftShift" 26 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"rightShift" 27 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"un-r-shift" 28 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"fill" 29 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server "ring1" 30 ; a * (b + 1) == a * b + a "ring2" 31 ; a * b + a + b "ring3" 32 ; a*a*b "ring4" 33 ; a*a*b - a*b*b "difsqr" 34 ; a*a - b*b "sumsqr" 35 ; a*a + b*b "sqrsum" 36 ; (a + b)^2 "sqrdif" 37 ; (a - b)^2 "absdif" 38 ; |a - b| "thresh" 39 ; Signal thresholding "amclip" 40 ; Two quadrant multiply "scale-neg" 41 ; scale negative part of input wave "clip2" 42 ; bilateral clipping "excess" 43 ; clipping residual "fold2" 44 ; bilateral folding "wrap2" 45 ; bilateral wrapping ;;"first-arg" 46 ; Returns the first arg unchanged - not useful. ;;"rrand" 47 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"exprand" 48 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server }) (def FOLDABLE-BINARY-OPS #{"+" "-" "*" "/" "<" ">" "<=" ">=" "min" "max" "and" "or"}) ;;the following are Clojure fns that can only take numerical args (def NUMERICAL-CLOJURE-FNS #{"+" "*" "-" "/" "<" ">" "<=" ">=" "min" "max" "mod"}) (def REVERSE-BINARY-OPS (zipmap (vals BINARY-OPS) (keys BINARY-OPS))) (defn unary-op-num [name] (get UNARY-OPS (str name) false)) (defn binary-op-num [name] (get BINARY-OPS (str name) false)) (def binary-op-unary-modes {"+" (fn [ugen-fn arg] (ugen-fn 0 arg)) "-" (fn [ugen-fn arg] (ugen-fn 0 arg)) "*" (fn [ugen-fn arg] (ugen-fn 1 arg)) "/" (fn [ugen-fn arg] (ugen-fn 1 arg)) "=" (fn [ugen-fn arg] (ugen-fn arg arg)) "not=" (fn [ugen-fn arg] (ugen-fn arg arg))})
true
(ns ^{:doc "Metadata regarding the various functionalities of the unary and binary ugens. These ugens are different to typical ugens in that they receive an 'opcode' as a parameter which defines its behviour - ranging from addition to trig functions to midi->cps conversion." :author "PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI"} overtone.sc.machinery.ugen.special-ops) (def UNARY-OPS {"neg" 0 ; inversion "not-pos?" 1 ; 0 when a < 0, +1 when a > 0, 1 when a is 0 ;;"is-nil" 2 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"not-nil" 3 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"bitNot" 4 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server "abs" 5 ; absolute value ;;"asFloat" 6 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"asInt" 7 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server "ceil" 8 ; next higher integer "floor" 9 ; next lower integer "frac" 10 ; fractional part "sign" 11 ; -1 when a < 0, +1 when a > 0, 0 when a is 0 "squared" 12 ; a*a "cubed" 13 ; a*a*a "sqrt" 14 ; square root "exp" 15 ; exponential "reciprocal" 16 ; reciprocal "midicps" 17 ; MIDI note number to cycles per second "cpsmidi" 18 ; cycles per second to MIDI note number "midiratio" 19 ; convert an interval in MIDI notes into a frequency ratio "ratiomidi" 20 ; convert a frequency ratio to an interval in MIDI notes "dbamp" 21 ; decibels to linear amplitude "ampdb" 22 ; linear amplitude to decibels "octcps" 23 ; decimal octaves to cycles per second "cpsoct" 24 ; cycles per second to decimal octaves "log" 25 ; natural logarithm "log2" 26 ; base 2 logarithm "log10" 27 ; base 10 logarithm "sin" 28 ; sine "cos" 29 ; cosine "tan" 30 ; tangent "asin" 31 ; arcsine "acos" 32 ; arccosine "atan" 33 ; arctangent "sinh" 34 ; hyperbolic sine "cosh" 35 ; hyperbolic cosine "tanh" 36 ; hyperbolic tangent ;;"rand" 37 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"rand2" 38 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"linrand" 39 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"bilinrand" 40; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"sum3rand" 41 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server "distort" 42 ; distortion "softclip" 43 ; distortion ;;"coin" 44 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"digit-val" 45; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"silence" 46 ; outputs 0 - no need to include it as we already have the silent ugen ;;"thru" 47 ; outputs what was received - not useful "rectWindow" 48 ; rectangular window "hanWindow" 49 ; hanning window "welWindow" 50 ; welch window "triWindow" 51 ; triangle window ;;"ramp" 52 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server ;;"scurve" 53 ; Defined in UnaryOpUGens.cpp enum but not implemented on the server }) (def REVERSE-UNARY-OPS (zipmap (vals UNARY-OPS) (keys UNARY-OPS))) ; Commented out ops are implemented with generics instead of generated ; see sc/ops.clj (def BINARY-OPS { "+" 0 ; Addition "-" 1 ; Subtraction "*" 2 ; Multiplication ;;"div" 3 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server "/" 4 ; Division "mod" 5 ; Modulus "=" 6 ; Equality "not=" 7 ; Inequality "<" 8 ; Less than ">" 9 ; Greater than "<=" 10 ; Less than or equal to ">=" 11 ; Greater than or equal to "min" 12 ; minimum "max" 13 ; maximum "and" 14 ; and (where pos sig is true) "or" 15 ; or (where pos sig is true "xor" 16 ; xor (where pos sig is true) ;;"lcm" 17 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"gcd" 18 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server "round" 19 ; Round to nearest multiple "round-up" 20 ; Round up to next multiple "round-down" 21 ; Round down to previous multiple "atan2" 22 ; arctangent of a/b "hypot" 23 ; length of hypotenuse via Pythag "hypot-aprox" 24 ; approximation of length of hypotenuse "pow" 25 ; exponentiation ;;"leftShift" 26 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"rightShift" 27 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"un-r-shift" 28 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"fill" 29 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server "ring1" 30 ; a * (b + 1) == a * b + a "ring2" 31 ; a * b + a + b "ring3" 32 ; a*a*b "ring4" 33 ; a*a*b - a*b*b "difsqr" 34 ; a*a - b*b "sumsqr" 35 ; a*a + b*b "sqrsum" 36 ; (a + b)^2 "sqrdif" 37 ; (a - b)^2 "absdif" 38 ; |a - b| "thresh" 39 ; Signal thresholding "amclip" 40 ; Two quadrant multiply "scale-neg" 41 ; scale negative part of input wave "clip2" 42 ; bilateral clipping "excess" 43 ; clipping residual "fold2" 44 ; bilateral folding "wrap2" 45 ; bilateral wrapping ;;"first-arg" 46 ; Returns the first arg unchanged - not useful. ;;"rrand" 47 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server ;;"exprand" 48 ; Defined in BinaryOpUGens.cpp enum but not implemented on the server }) (def FOLDABLE-BINARY-OPS #{"+" "-" "*" "/" "<" ">" "<=" ">=" "min" "max" "and" "or"}) ;;the following are Clojure fns that can only take numerical args (def NUMERICAL-CLOJURE-FNS #{"+" "*" "-" "/" "<" ">" "<=" ">=" "min" "max" "mod"}) (def REVERSE-BINARY-OPS (zipmap (vals BINARY-OPS) (keys BINARY-OPS))) (defn unary-op-num [name] (get UNARY-OPS (str name) false)) (defn binary-op-num [name] (get BINARY-OPS (str name) false)) (def binary-op-unary-modes {"+" (fn [ugen-fn arg] (ugen-fn 0 arg)) "-" (fn [ugen-fn arg] (ugen-fn 0 arg)) "*" (fn [ugen-fn arg] (ugen-fn 1 arg)) "/" (fn [ugen-fn arg] (ugen-fn 1 arg)) "=" (fn [ugen-fn arg] (ugen-fn arg arg)) "not=" (fn [ugen-fn arg] (ugen-fn arg arg))})
[ { "context": " (dosync\n (person-arrives-ref-set! hospital \"victor\")\n (person-arrives-ref-set! hospital \"alessa", "end": 904, "score": 0.9288738965988159, "start": 898, "tag": "NAME", "value": "victor" }, { "context": "victor\")\n (person-arrives-ref-set! hospital \"alessandra\")\n (person-arrives-alter! hospital \"billy\")\n", "end": 958, "score": 0.9990315437316895, "start": 948, "tag": "NAME", "value": "alessandra" }, { "context": "essandra\")\n (person-arrives-alter! hospital \"billy\")\n (person-arrives-alter! hospital \"leo\")\n ", "end": 1005, "score": 0.9983303546905518, "start": 1000, "tag": "NAME", "value": "billy" }, { "context": "l \"billy\")\n (person-arrives-alter! hospital \"leo\")\n (person-arrives-alter! hospital \"fred\")\n ", "end": 1050, "score": 0.998145580291748, "start": 1047, "tag": "NAME", "value": "leo" }, { "context": "tal \"leo\")\n (person-arrives-alter! hospital \"fred\")\n ;(person-arrives-ref-set! hospital \"predo", "end": 1096, "score": 0.997185230255127, "start": 1092, "tag": "NAME", "value": "fred" } ]
hospital/src/hospital/class6.clj
vgeorgo/courses-alura-clojure
0
(ns hospital.class6 (:use [clojure pprint]) (:require [hospital.model :as h.model] [hospital.logic :as h.logic])) (defn person-arrives-ref-set! "Update the queue with set-ref, need to run inside transaction" [hospital, person] (let [queue (get hospital :waiting)] (ref-set queue (h.logic/person-arrives-queue @queue person)))) (defn person-arrives-alter! "Update the queue with alter, need to run inside transaction" [hospital, person] (let [queue (get hospital :waiting)] (alter queue h.logic/person-arrives-queue person))) (defn async-person-arrives! [hospital, person] (future (Thread/sleep (rand 5000)) (dosync (println "Trying to synchronize person: " person) (person-arrives-alter! hospital person)))) (defn simulate-day-1 [] (let [hospital (h.model/new-hospital-with-ref)] (dosync (person-arrives-ref-set! hospital "victor") (person-arrives-ref-set! hospital "alessandra") (person-arrives-alter! hospital "billy") (person-arrives-alter! hospital "leo") (person-arrives-alter! hospital "fred") ;(person-arrives-ref-set! hospital "predo") ; Will throw Queue is full error ) (pprint hospital))) ; (simulate-day-1) (defn simulate-day-2-async [] (let [hospital (h.model/new-hospital-with-ref)] ; Some of these futures will have the state as ready, others will have exceptions ; since the queue max size is 5 ; This is defined as global just to see the value on console after execution ; (just typing (use 'hospital.class6) and futures after) (def futures (mapv #(async-person-arrives! hospital %) (range 10))) (future (Thread/sleep 8000) (pprint hospital)))) (simulate-day-2-async)
96909
(ns hospital.class6 (:use [clojure pprint]) (:require [hospital.model :as h.model] [hospital.logic :as h.logic])) (defn person-arrives-ref-set! "Update the queue with set-ref, need to run inside transaction" [hospital, person] (let [queue (get hospital :waiting)] (ref-set queue (h.logic/person-arrives-queue @queue person)))) (defn person-arrives-alter! "Update the queue with alter, need to run inside transaction" [hospital, person] (let [queue (get hospital :waiting)] (alter queue h.logic/person-arrives-queue person))) (defn async-person-arrives! [hospital, person] (future (Thread/sleep (rand 5000)) (dosync (println "Trying to synchronize person: " person) (person-arrives-alter! hospital person)))) (defn simulate-day-1 [] (let [hospital (h.model/new-hospital-with-ref)] (dosync (person-arrives-ref-set! hospital "<NAME>") (person-arrives-ref-set! hospital "<NAME>") (person-arrives-alter! hospital "<NAME>") (person-arrives-alter! hospital "<NAME>") (person-arrives-alter! hospital "<NAME>") ;(person-arrives-ref-set! hospital "predo") ; Will throw Queue is full error ) (pprint hospital))) ; (simulate-day-1) (defn simulate-day-2-async [] (let [hospital (h.model/new-hospital-with-ref)] ; Some of these futures will have the state as ready, others will have exceptions ; since the queue max size is 5 ; This is defined as global just to see the value on console after execution ; (just typing (use 'hospital.class6) and futures after) (def futures (mapv #(async-person-arrives! hospital %) (range 10))) (future (Thread/sleep 8000) (pprint hospital)))) (simulate-day-2-async)
true
(ns hospital.class6 (:use [clojure pprint]) (:require [hospital.model :as h.model] [hospital.logic :as h.logic])) (defn person-arrives-ref-set! "Update the queue with set-ref, need to run inside transaction" [hospital, person] (let [queue (get hospital :waiting)] (ref-set queue (h.logic/person-arrives-queue @queue person)))) (defn person-arrives-alter! "Update the queue with alter, need to run inside transaction" [hospital, person] (let [queue (get hospital :waiting)] (alter queue h.logic/person-arrives-queue person))) (defn async-person-arrives! [hospital, person] (future (Thread/sleep (rand 5000)) (dosync (println "Trying to synchronize person: " person) (person-arrives-alter! hospital person)))) (defn simulate-day-1 [] (let [hospital (h.model/new-hospital-with-ref)] (dosync (person-arrives-ref-set! hospital "PI:NAME:<NAME>END_PI") (person-arrives-ref-set! hospital "PI:NAME:<NAME>END_PI") (person-arrives-alter! hospital "PI:NAME:<NAME>END_PI") (person-arrives-alter! hospital "PI:NAME:<NAME>END_PI") (person-arrives-alter! hospital "PI:NAME:<NAME>END_PI") ;(person-arrives-ref-set! hospital "predo") ; Will throw Queue is full error ) (pprint hospital))) ; (simulate-day-1) (defn simulate-day-2-async [] (let [hospital (h.model/new-hospital-with-ref)] ; Some of these futures will have the state as ready, others will have exceptions ; since the queue max size is 5 ; This is defined as global just to see the value on console after execution ; (just typing (use 'hospital.class6) and futures after) (def futures (mapv #(async-person-arrives! hospital %) (range 10))) (future (Thread/sleep 8000) (pprint hospital)))) (simulate-day-2-async)
[ { "context": "e paper A Neural Algorithm of Artistic Style\n ;;by Leon A. Gatys, Alexander S. Ecker, and Matthias Bethge\n\n(def co", "end": 1592, "score": 0.9998940229415894, "start": 1579, "tag": "NAME", "value": "Leon A. Gatys" }, { "context": "l Algorithm of Artistic Style\n ;;by Leon A. Gatys, Alexander S. Ecker, and Matthias Bethge\n\n(def content-image \"input/I", "end": 1612, "score": 0.9998891949653625, "start": 1594, "tag": "NAME", "value": "Alexander S. Ecker" }, { "context": "Style\n ;;by Leon A. Gatys, Alexander S. Ecker, and Matthias Bethge\n\n(def content-image \"input/IMG_4343.jpg\")\n(def st", "end": 1633, "score": 0.9998881220817566, "start": 1618, "tag": "NAME", "value": "Matthias Bethge" } ]
contrib/clojure-package/examples/neural-style/src/neural_style/core.clj
Vikas-kum/incubator-mxnet
0
;; ;; Licensed to the Apache Software Foundation (ASF) under one or more ;; contributor license agreements. See the NOTICE file distributed with ;; this work for additional information regarding copyright ownership. ;; The ASF licenses this file to You under the Apache License, Version 2.0 ;; (the "License"); you may not use this file except in compliance with ;; the License. You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns neural-style.core (:require [org.apache.clojure-mxnet.context :as context] [org.apache.clojure-mxnet.executor :as executor] [org.apache.clojure-mxnet.lr-scheduler :as lr-scheduler] [org.apache.clojure-mxnet.ndarray :as ndarray] [org.apache.clojure-mxnet.optimizer :as opt] [org.apache.clojure-mxnet.random :as random] [org.apache.clojure-mxnet.shape :as mx-shape] [org.apache.clojure-mxnet.symbol :as sym] [mikera.image.core :as img] [mikera.image.filters :as img-filter] [think.image.pixel :as pixel] [neural-style.model-vgg-19 :as model-vgg-19]) (:gen-class));; An Implementation of the paper A Neural Algorithm of Artistic Style ;;by Leon A. Gatys, Alexander S. Ecker, and Matthias Bethge (def content-image "input/IMG_4343.jpg") (def style-image "input/starry_night.jpg") (def model-path "model/vgg19.params") (def max-long-edge 600) ;; resize the content image (def style-weight 1) ;; the weight for the style image (def content-weight 5) ;; the weight for the content image (def blur-radius 1) ;; the blur filter radius (def output-dir "output") (def lr 10) ;; the learning rate (def tv-weight 0.01) ;; the magnitude on the tv loss (def num-epochs 1000) (def num-channels 3) (defn image->ndarray [simg] (let [h (img/height simg) w (img/width simg) pixels (img/get-pixels simg) ;; normalize the pixels for vgg19 rgb-pixels (reduce (fn [result pixel] (let [[rs gs bs] result [r g b _] (pixel/unpack-pixel pixel)] [(conj rs (- r 123.68)) (conj gs (- g 116.779)) (conj bs (- b 103.939))])) [[] [] []] pixels)] (println "The resized image is size " {:height h :width w}) (-> rgb-pixels (flatten) (ndarray/array [1 num-channels h w])))) (defn preprocess-content-image [path short-edge] (let [simg (img/load-image path) _ (println "The content image is size " {:height (img/height simg) :width (img/width simg)}) factor (/ short-edge (img/width simg)) resized-img (img/resize simg (* (img/width simg) factor) (* (img/height simg) factor)) new-height (img/height resized-img) new-width (img/width resized-img)] (image->ndarray resized-img))) (defn preprocess-style-image [path shape-vec] (let [[_ _ h w] shape-vec simg (img/load-image path) _ (println "The image is size " {:height (img/height simg) :width (img/width simg)}) resized-img (img/resize simg w h)] (image->ndarray resized-img))) (defn postprocess-image [img] (let [datas (ndarray/->vec img) image-shape (mx-shape/->vec (ndarray/shape img)) spatial-size (* (get image-shape 2) (get image-shape 3)) [rs gs bs] (doall (partition spatial-size datas)) pixels (mapv (fn [r g b] (pixel/pack-pixel (int (+ r 123.68)) (int (+ g 116.779)) (int (+ b 103.939)) (int 255))) rs gs bs) new-image (img/new-image (get image-shape 3) (get image-shape 2)) _ (img/set-pixels new-image (int-array pixels))] new-image)) (defn style-gram-symbol [input-size style] (let [[_ output-shape _] (sym/infer-shape style {:data [1 3 (first input-size) (second input-size)]}) output-shapes (mx-shape/->vec output-shape) {:keys [gram-list grad-scale]} (doall (reduce (fn [result i] (let [shape (get output-shapes i) [s0 s1 s2 s3] shape x (sym/reshape {:data (sym/get style i) :target-shape [s1 (* s2 s3)]}) ;; use fully connected to quickly do dot(x x^T) gram (sym/fully-connected {:data x :weight x :no-bias true :num-hidden s1})] (-> result (update :gram-list conj gram) (update :grad-scale conj (* s1 s2 s3 s1))))) {:gram-list [] :grad-scale []} (range (count (sym/list-outputs style)))))] {:gram (sym/group (into [] gram-list)) :g-scale grad-scale})) (defn get-loss [gram content] (let [gram-loss (doall (mapv (fn [i] (let [gvar (sym/variable (str "target_gram_" i))] (sym/sum (sym/square (sym/- gvar (sym/get gram i)))))) (range (count (sym/list-outputs gram))))) cvar (sym/variable "target_content") content-loss (sym/sum (sym/square (sym/- cvar content)))] {:style-loss (sym/group gram-loss) :content-loss content-loss})) (defn old-clip [v] (mapv (fn [a] (cond (neg? a) 0 (> a 255) 255 :else a)) v)) (defn clip [a] (cond (neg? a) 0 (> a 255) 255 :else a)) (defn save-image [img filename radius blur?] (let [filtered-image (if blur? ((img-filter/box-blur blur-radius blur-radius) (postprocess-image img)) (postprocess-image img))] (do ;(img/show filtered-image) ;; Uncomment to have the image display (img/write filtered-image filename "png")))) (defn get-tv-grad-executor [img ctx tv-weight] (when (pos? tv-weight) (let [img-shape (mx-shape/->vec (ndarray/shape img)) n-channel (get img-shape 1) s-img (sym/variable "img") s-kernel (sym/variable "kernel") channels (sym/split {:data s-img :axis 1 :num-outputs n-channel}) out (sym/concat (doall (mapv (fn [i] (sym/convolution {:data (sym/get channels i) :weight s-kernel :num-filter 1 :kernel [3 3] :pad [1 1] :no-bias true :stride [1 1]})) (range n-channel)))) kernel (ndarray/* (ndarray/array [0 -1 0 -1 4 -1 0 -1 0] [1 1 3 3] {:ctx ctx}) 0.8) out (ndarray/* out tv-weight)] (sym/bind out ctx {"img" img "kernel" kernel})))) (defn train [devs] (let [dev (first devs) content-np (preprocess-content-image content-image max-long-edge) content-np-shape (mx-shape/->vec (ndarray/shape content-np)) style-np (preprocess-style-image style-image content-np-shape) size [(get content-np-shape 2) (get content-np-shape 3)] {:keys [style content]} (model-vgg-19/get-symbol) {:keys [gram g-scale]} (style-gram-symbol size style) model-executor (model-vgg-19/get-executor gram content model-path size dev) _ (ndarray/set (:data model-executor) style-np) _ (executor/forward (:executor model-executor)) style-array (mapv #(ndarray/copy %) (:style model-executor)) mode-executor nil _ (ndarray/set (:data model-executor) content-np) _ (executor/forward (:executor model-executor)) content-array (ndarray/copy (:content model-executor)) {:keys [style-loss content-loss]} (get-loss gram content) model-executor (model-vgg-19/get-executor style-loss content-loss model-path size dev) grad-array (-> (doall (mapv (fn [i] (do (ndarray/set (get (:arg-map model-executor) (str "target_gram_" i)) (get style-array i)) (ndarray/* (ndarray/ones [1] {:ctx dev}) (/ style-weight (get g-scale i))))) (range (count style-array)))) (conj (ndarray/* (ndarray/ones [1] {:ctx dev}) content-weight))) _ (ndarray/copy-to content-array (get (:arg-map model-executor) "target_content")) ;;;train ;;initialize with random noise img (ndarray/- (random/uniform 0 255 content-np-shape {:ctx dev}) 128) ;;; img (random/uniform -0.1 0.1 content-np-shape dev) ;; img content-np lr-sched (lr-scheduler/factor-scheduler 10 0.9) _ (save-image content-np (str output-dir "/input.png") blur-radius false) _ (save-image style-np (str output-dir "/style.png") blur-radius false) optimizer (opt/adam {:learning-rate lr :wd 0.005 :lr-scheduler lr-sched}) optim-state (opt/create-state optimizer 0 img) _ (println "Starting training....") old-img (ndarray/copy-to img dev) clip-norm (apply * (mx-shape/->vec (ndarray/shape img))) tv-grad-executor (get-tv-grad-executor img dev tv-weight) eps 0.0 e 0] (doseq [i (range 20)] (ndarray/set (:data model-executor) img) (-> (:executor model-executor) (executor/forward) (executor/backward grad-array)) (let [g-norm (ndarray/to-scalar (ndarray/norm (:data-grad model-executor)))] (if (> g-norm clip-norm) (ndarray/set (:data-grad model-executor) (ndarray/* (:data-grad model-executor) (/ clip-norm g-norm))))) (if tv-grad-executor (do (executor/forward tv-grad-executor) (opt/update optimizer 0 img (ndarray/+ (:data-grad model-executor) (first (executor/outputs tv-grad-executor))) optim-state)) (opt/update optimizer 0 img (:data-grad model-executor) optim-state)) (let [eps (ndarray/to-scalar (ndarray/div (ndarray/norm (ndarray/- old-img img)) (ndarray/norm img)))] (println "Epoch " i "relative change " eps) (when (zero? (mod i 2)) (save-image (ndarray/copy img) (str output-dir "/out_" i ".png") blur-radius true))) (ndarray/set old-img img)))) (defn -main [& args] ;;; Note this only works on cpu right now (let [[dev dev-num] args devs (if (= dev ":gpu") (mapv #(context/gpu %) (range (Integer/parseInt (or dev-num "1")))) (mapv #(context/cpu %) (range (Integer/parseInt (or dev-num "1")))))] (println "Running with context devices of" devs) (train devs))) (comment (train [(context/cpu)]))
115995
;; ;; Licensed to the Apache Software Foundation (ASF) under one or more ;; contributor license agreements. See the NOTICE file distributed with ;; this work for additional information regarding copyright ownership. ;; The ASF licenses this file to You under the Apache License, Version 2.0 ;; (the "License"); you may not use this file except in compliance with ;; the License. You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns neural-style.core (:require [org.apache.clojure-mxnet.context :as context] [org.apache.clojure-mxnet.executor :as executor] [org.apache.clojure-mxnet.lr-scheduler :as lr-scheduler] [org.apache.clojure-mxnet.ndarray :as ndarray] [org.apache.clojure-mxnet.optimizer :as opt] [org.apache.clojure-mxnet.random :as random] [org.apache.clojure-mxnet.shape :as mx-shape] [org.apache.clojure-mxnet.symbol :as sym] [mikera.image.core :as img] [mikera.image.filters :as img-filter] [think.image.pixel :as pixel] [neural-style.model-vgg-19 :as model-vgg-19]) (:gen-class));; An Implementation of the paper A Neural Algorithm of Artistic Style ;;by <NAME>, <NAME>, and <NAME> (def content-image "input/IMG_4343.jpg") (def style-image "input/starry_night.jpg") (def model-path "model/vgg19.params") (def max-long-edge 600) ;; resize the content image (def style-weight 1) ;; the weight for the style image (def content-weight 5) ;; the weight for the content image (def blur-radius 1) ;; the blur filter radius (def output-dir "output") (def lr 10) ;; the learning rate (def tv-weight 0.01) ;; the magnitude on the tv loss (def num-epochs 1000) (def num-channels 3) (defn image->ndarray [simg] (let [h (img/height simg) w (img/width simg) pixels (img/get-pixels simg) ;; normalize the pixels for vgg19 rgb-pixels (reduce (fn [result pixel] (let [[rs gs bs] result [r g b _] (pixel/unpack-pixel pixel)] [(conj rs (- r 123.68)) (conj gs (- g 116.779)) (conj bs (- b 103.939))])) [[] [] []] pixels)] (println "The resized image is size " {:height h :width w}) (-> rgb-pixels (flatten) (ndarray/array [1 num-channels h w])))) (defn preprocess-content-image [path short-edge] (let [simg (img/load-image path) _ (println "The content image is size " {:height (img/height simg) :width (img/width simg)}) factor (/ short-edge (img/width simg)) resized-img (img/resize simg (* (img/width simg) factor) (* (img/height simg) factor)) new-height (img/height resized-img) new-width (img/width resized-img)] (image->ndarray resized-img))) (defn preprocess-style-image [path shape-vec] (let [[_ _ h w] shape-vec simg (img/load-image path) _ (println "The image is size " {:height (img/height simg) :width (img/width simg)}) resized-img (img/resize simg w h)] (image->ndarray resized-img))) (defn postprocess-image [img] (let [datas (ndarray/->vec img) image-shape (mx-shape/->vec (ndarray/shape img)) spatial-size (* (get image-shape 2) (get image-shape 3)) [rs gs bs] (doall (partition spatial-size datas)) pixels (mapv (fn [r g b] (pixel/pack-pixel (int (+ r 123.68)) (int (+ g 116.779)) (int (+ b 103.939)) (int 255))) rs gs bs) new-image (img/new-image (get image-shape 3) (get image-shape 2)) _ (img/set-pixels new-image (int-array pixels))] new-image)) (defn style-gram-symbol [input-size style] (let [[_ output-shape _] (sym/infer-shape style {:data [1 3 (first input-size) (second input-size)]}) output-shapes (mx-shape/->vec output-shape) {:keys [gram-list grad-scale]} (doall (reduce (fn [result i] (let [shape (get output-shapes i) [s0 s1 s2 s3] shape x (sym/reshape {:data (sym/get style i) :target-shape [s1 (* s2 s3)]}) ;; use fully connected to quickly do dot(x x^T) gram (sym/fully-connected {:data x :weight x :no-bias true :num-hidden s1})] (-> result (update :gram-list conj gram) (update :grad-scale conj (* s1 s2 s3 s1))))) {:gram-list [] :grad-scale []} (range (count (sym/list-outputs style)))))] {:gram (sym/group (into [] gram-list)) :g-scale grad-scale})) (defn get-loss [gram content] (let [gram-loss (doall (mapv (fn [i] (let [gvar (sym/variable (str "target_gram_" i))] (sym/sum (sym/square (sym/- gvar (sym/get gram i)))))) (range (count (sym/list-outputs gram))))) cvar (sym/variable "target_content") content-loss (sym/sum (sym/square (sym/- cvar content)))] {:style-loss (sym/group gram-loss) :content-loss content-loss})) (defn old-clip [v] (mapv (fn [a] (cond (neg? a) 0 (> a 255) 255 :else a)) v)) (defn clip [a] (cond (neg? a) 0 (> a 255) 255 :else a)) (defn save-image [img filename radius blur?] (let [filtered-image (if blur? ((img-filter/box-blur blur-radius blur-radius) (postprocess-image img)) (postprocess-image img))] (do ;(img/show filtered-image) ;; Uncomment to have the image display (img/write filtered-image filename "png")))) (defn get-tv-grad-executor [img ctx tv-weight] (when (pos? tv-weight) (let [img-shape (mx-shape/->vec (ndarray/shape img)) n-channel (get img-shape 1) s-img (sym/variable "img") s-kernel (sym/variable "kernel") channels (sym/split {:data s-img :axis 1 :num-outputs n-channel}) out (sym/concat (doall (mapv (fn [i] (sym/convolution {:data (sym/get channels i) :weight s-kernel :num-filter 1 :kernel [3 3] :pad [1 1] :no-bias true :stride [1 1]})) (range n-channel)))) kernel (ndarray/* (ndarray/array [0 -1 0 -1 4 -1 0 -1 0] [1 1 3 3] {:ctx ctx}) 0.8) out (ndarray/* out tv-weight)] (sym/bind out ctx {"img" img "kernel" kernel})))) (defn train [devs] (let [dev (first devs) content-np (preprocess-content-image content-image max-long-edge) content-np-shape (mx-shape/->vec (ndarray/shape content-np)) style-np (preprocess-style-image style-image content-np-shape) size [(get content-np-shape 2) (get content-np-shape 3)] {:keys [style content]} (model-vgg-19/get-symbol) {:keys [gram g-scale]} (style-gram-symbol size style) model-executor (model-vgg-19/get-executor gram content model-path size dev) _ (ndarray/set (:data model-executor) style-np) _ (executor/forward (:executor model-executor)) style-array (mapv #(ndarray/copy %) (:style model-executor)) mode-executor nil _ (ndarray/set (:data model-executor) content-np) _ (executor/forward (:executor model-executor)) content-array (ndarray/copy (:content model-executor)) {:keys [style-loss content-loss]} (get-loss gram content) model-executor (model-vgg-19/get-executor style-loss content-loss model-path size dev) grad-array (-> (doall (mapv (fn [i] (do (ndarray/set (get (:arg-map model-executor) (str "target_gram_" i)) (get style-array i)) (ndarray/* (ndarray/ones [1] {:ctx dev}) (/ style-weight (get g-scale i))))) (range (count style-array)))) (conj (ndarray/* (ndarray/ones [1] {:ctx dev}) content-weight))) _ (ndarray/copy-to content-array (get (:arg-map model-executor) "target_content")) ;;;train ;;initialize with random noise img (ndarray/- (random/uniform 0 255 content-np-shape {:ctx dev}) 128) ;;; img (random/uniform -0.1 0.1 content-np-shape dev) ;; img content-np lr-sched (lr-scheduler/factor-scheduler 10 0.9) _ (save-image content-np (str output-dir "/input.png") blur-radius false) _ (save-image style-np (str output-dir "/style.png") blur-radius false) optimizer (opt/adam {:learning-rate lr :wd 0.005 :lr-scheduler lr-sched}) optim-state (opt/create-state optimizer 0 img) _ (println "Starting training....") old-img (ndarray/copy-to img dev) clip-norm (apply * (mx-shape/->vec (ndarray/shape img))) tv-grad-executor (get-tv-grad-executor img dev tv-weight) eps 0.0 e 0] (doseq [i (range 20)] (ndarray/set (:data model-executor) img) (-> (:executor model-executor) (executor/forward) (executor/backward grad-array)) (let [g-norm (ndarray/to-scalar (ndarray/norm (:data-grad model-executor)))] (if (> g-norm clip-norm) (ndarray/set (:data-grad model-executor) (ndarray/* (:data-grad model-executor) (/ clip-norm g-norm))))) (if tv-grad-executor (do (executor/forward tv-grad-executor) (opt/update optimizer 0 img (ndarray/+ (:data-grad model-executor) (first (executor/outputs tv-grad-executor))) optim-state)) (opt/update optimizer 0 img (:data-grad model-executor) optim-state)) (let [eps (ndarray/to-scalar (ndarray/div (ndarray/norm (ndarray/- old-img img)) (ndarray/norm img)))] (println "Epoch " i "relative change " eps) (when (zero? (mod i 2)) (save-image (ndarray/copy img) (str output-dir "/out_" i ".png") blur-radius true))) (ndarray/set old-img img)))) (defn -main [& args] ;;; Note this only works on cpu right now (let [[dev dev-num] args devs (if (= dev ":gpu") (mapv #(context/gpu %) (range (Integer/parseInt (or dev-num "1")))) (mapv #(context/cpu %) (range (Integer/parseInt (or dev-num "1")))))] (println "Running with context devices of" devs) (train devs))) (comment (train [(context/cpu)]))
true
;; ;; Licensed to the Apache Software Foundation (ASF) under one or more ;; contributor license agreements. See the NOTICE file distributed with ;; this work for additional information regarding copyright ownership. ;; The ASF licenses this file to You under the Apache License, Version 2.0 ;; (the "License"); you may not use this file except in compliance with ;; the License. You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns neural-style.core (:require [org.apache.clojure-mxnet.context :as context] [org.apache.clojure-mxnet.executor :as executor] [org.apache.clojure-mxnet.lr-scheduler :as lr-scheduler] [org.apache.clojure-mxnet.ndarray :as ndarray] [org.apache.clojure-mxnet.optimizer :as opt] [org.apache.clojure-mxnet.random :as random] [org.apache.clojure-mxnet.shape :as mx-shape] [org.apache.clojure-mxnet.symbol :as sym] [mikera.image.core :as img] [mikera.image.filters :as img-filter] [think.image.pixel :as pixel] [neural-style.model-vgg-19 :as model-vgg-19]) (:gen-class));; An Implementation of the paper A Neural Algorithm of Artistic Style ;;by PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and PI:NAME:<NAME>END_PI (def content-image "input/IMG_4343.jpg") (def style-image "input/starry_night.jpg") (def model-path "model/vgg19.params") (def max-long-edge 600) ;; resize the content image (def style-weight 1) ;; the weight for the style image (def content-weight 5) ;; the weight for the content image (def blur-radius 1) ;; the blur filter radius (def output-dir "output") (def lr 10) ;; the learning rate (def tv-weight 0.01) ;; the magnitude on the tv loss (def num-epochs 1000) (def num-channels 3) (defn image->ndarray [simg] (let [h (img/height simg) w (img/width simg) pixels (img/get-pixels simg) ;; normalize the pixels for vgg19 rgb-pixels (reduce (fn [result pixel] (let [[rs gs bs] result [r g b _] (pixel/unpack-pixel pixel)] [(conj rs (- r 123.68)) (conj gs (- g 116.779)) (conj bs (- b 103.939))])) [[] [] []] pixels)] (println "The resized image is size " {:height h :width w}) (-> rgb-pixels (flatten) (ndarray/array [1 num-channels h w])))) (defn preprocess-content-image [path short-edge] (let [simg (img/load-image path) _ (println "The content image is size " {:height (img/height simg) :width (img/width simg)}) factor (/ short-edge (img/width simg)) resized-img (img/resize simg (* (img/width simg) factor) (* (img/height simg) factor)) new-height (img/height resized-img) new-width (img/width resized-img)] (image->ndarray resized-img))) (defn preprocess-style-image [path shape-vec] (let [[_ _ h w] shape-vec simg (img/load-image path) _ (println "The image is size " {:height (img/height simg) :width (img/width simg)}) resized-img (img/resize simg w h)] (image->ndarray resized-img))) (defn postprocess-image [img] (let [datas (ndarray/->vec img) image-shape (mx-shape/->vec (ndarray/shape img)) spatial-size (* (get image-shape 2) (get image-shape 3)) [rs gs bs] (doall (partition spatial-size datas)) pixels (mapv (fn [r g b] (pixel/pack-pixel (int (+ r 123.68)) (int (+ g 116.779)) (int (+ b 103.939)) (int 255))) rs gs bs) new-image (img/new-image (get image-shape 3) (get image-shape 2)) _ (img/set-pixels new-image (int-array pixels))] new-image)) (defn style-gram-symbol [input-size style] (let [[_ output-shape _] (sym/infer-shape style {:data [1 3 (first input-size) (second input-size)]}) output-shapes (mx-shape/->vec output-shape) {:keys [gram-list grad-scale]} (doall (reduce (fn [result i] (let [shape (get output-shapes i) [s0 s1 s2 s3] shape x (sym/reshape {:data (sym/get style i) :target-shape [s1 (* s2 s3)]}) ;; use fully connected to quickly do dot(x x^T) gram (sym/fully-connected {:data x :weight x :no-bias true :num-hidden s1})] (-> result (update :gram-list conj gram) (update :grad-scale conj (* s1 s2 s3 s1))))) {:gram-list [] :grad-scale []} (range (count (sym/list-outputs style)))))] {:gram (sym/group (into [] gram-list)) :g-scale grad-scale})) (defn get-loss [gram content] (let [gram-loss (doall (mapv (fn [i] (let [gvar (sym/variable (str "target_gram_" i))] (sym/sum (sym/square (sym/- gvar (sym/get gram i)))))) (range (count (sym/list-outputs gram))))) cvar (sym/variable "target_content") content-loss (sym/sum (sym/square (sym/- cvar content)))] {:style-loss (sym/group gram-loss) :content-loss content-loss})) (defn old-clip [v] (mapv (fn [a] (cond (neg? a) 0 (> a 255) 255 :else a)) v)) (defn clip [a] (cond (neg? a) 0 (> a 255) 255 :else a)) (defn save-image [img filename radius blur?] (let [filtered-image (if blur? ((img-filter/box-blur blur-radius blur-radius) (postprocess-image img)) (postprocess-image img))] (do ;(img/show filtered-image) ;; Uncomment to have the image display (img/write filtered-image filename "png")))) (defn get-tv-grad-executor [img ctx tv-weight] (when (pos? tv-weight) (let [img-shape (mx-shape/->vec (ndarray/shape img)) n-channel (get img-shape 1) s-img (sym/variable "img") s-kernel (sym/variable "kernel") channels (sym/split {:data s-img :axis 1 :num-outputs n-channel}) out (sym/concat (doall (mapv (fn [i] (sym/convolution {:data (sym/get channels i) :weight s-kernel :num-filter 1 :kernel [3 3] :pad [1 1] :no-bias true :stride [1 1]})) (range n-channel)))) kernel (ndarray/* (ndarray/array [0 -1 0 -1 4 -1 0 -1 0] [1 1 3 3] {:ctx ctx}) 0.8) out (ndarray/* out tv-weight)] (sym/bind out ctx {"img" img "kernel" kernel})))) (defn train [devs] (let [dev (first devs) content-np (preprocess-content-image content-image max-long-edge) content-np-shape (mx-shape/->vec (ndarray/shape content-np)) style-np (preprocess-style-image style-image content-np-shape) size [(get content-np-shape 2) (get content-np-shape 3)] {:keys [style content]} (model-vgg-19/get-symbol) {:keys [gram g-scale]} (style-gram-symbol size style) model-executor (model-vgg-19/get-executor gram content model-path size dev) _ (ndarray/set (:data model-executor) style-np) _ (executor/forward (:executor model-executor)) style-array (mapv #(ndarray/copy %) (:style model-executor)) mode-executor nil _ (ndarray/set (:data model-executor) content-np) _ (executor/forward (:executor model-executor)) content-array (ndarray/copy (:content model-executor)) {:keys [style-loss content-loss]} (get-loss gram content) model-executor (model-vgg-19/get-executor style-loss content-loss model-path size dev) grad-array (-> (doall (mapv (fn [i] (do (ndarray/set (get (:arg-map model-executor) (str "target_gram_" i)) (get style-array i)) (ndarray/* (ndarray/ones [1] {:ctx dev}) (/ style-weight (get g-scale i))))) (range (count style-array)))) (conj (ndarray/* (ndarray/ones [1] {:ctx dev}) content-weight))) _ (ndarray/copy-to content-array (get (:arg-map model-executor) "target_content")) ;;;train ;;initialize with random noise img (ndarray/- (random/uniform 0 255 content-np-shape {:ctx dev}) 128) ;;; img (random/uniform -0.1 0.1 content-np-shape dev) ;; img content-np lr-sched (lr-scheduler/factor-scheduler 10 0.9) _ (save-image content-np (str output-dir "/input.png") blur-radius false) _ (save-image style-np (str output-dir "/style.png") blur-radius false) optimizer (opt/adam {:learning-rate lr :wd 0.005 :lr-scheduler lr-sched}) optim-state (opt/create-state optimizer 0 img) _ (println "Starting training....") old-img (ndarray/copy-to img dev) clip-norm (apply * (mx-shape/->vec (ndarray/shape img))) tv-grad-executor (get-tv-grad-executor img dev tv-weight) eps 0.0 e 0] (doseq [i (range 20)] (ndarray/set (:data model-executor) img) (-> (:executor model-executor) (executor/forward) (executor/backward grad-array)) (let [g-norm (ndarray/to-scalar (ndarray/norm (:data-grad model-executor)))] (if (> g-norm clip-norm) (ndarray/set (:data-grad model-executor) (ndarray/* (:data-grad model-executor) (/ clip-norm g-norm))))) (if tv-grad-executor (do (executor/forward tv-grad-executor) (opt/update optimizer 0 img (ndarray/+ (:data-grad model-executor) (first (executor/outputs tv-grad-executor))) optim-state)) (opt/update optimizer 0 img (:data-grad model-executor) optim-state)) (let [eps (ndarray/to-scalar (ndarray/div (ndarray/norm (ndarray/- old-img img)) (ndarray/norm img)))] (println "Epoch " i "relative change " eps) (when (zero? (mod i 2)) (save-image (ndarray/copy img) (str output-dir "/out_" i ".png") blur-radius true))) (ndarray/set old-img img)))) (defn -main [& args] ;;; Note this only works on cpu right now (let [[dev dev-num] args devs (if (= dev ":gpu") (mapv #(context/gpu %) (range (Integer/parseInt (or dev-num "1")))) (mapv #(context/cpu %) (range (Integer/parseInt (or dev-num "1")))))] (println "Running with context devices of" devs) (train devs))) (comment (train [(context/cpu)]))
[ { "context": "(ns river.seq\n\n ^{\n :author \"Roman Gonzalez\"\n }\n\n (:refer-clojure :exclude\n [take take-w", "end": 47, "score": 0.9998700022697449, "start": 33, "tag": "NAME", "value": "Roman Gonzalez" } ]
data/train/clojure/4d3b3c402ee856fecd18bb8107b2ee03b747ae6bseq.clj
harshp8l/deep-learning-lang-detection
84
(ns river.seq ^{ :author "Roman Gonzalez" } (:refer-clojure :exclude [take take-while drop drop-while reduce first peek]) (:require [clojure.core :as core]) (:use river.core)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ## Utility Functions ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- span [pred xs] ((core/juxt #(core/take-while pred %) #(core/drop-while pred %)) xs)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ## Consumers ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn take "Returns a seq of the first `n` elements in the stream, or all items if there are fewer than `n`. When `buffer` is given, the result is going to be concatenated to it." ([n0] (take [] n0)) ([buffer0 n0] (letfn [ (consumer [buffer n stream] (cond (eof? stream) (yield buffer eof) (empty-chunk? stream) (continue #((take buffer n) %)) :else (let [taken-elems (concat buffer (core/take n stream)) new-size (- n (count stream))] (if (> new-size 0) (continue #(consumer taken-elems new-size %)) (yield taken-elems (core/drop n stream)))))) ] #(consumer buffer0 n0 %)))) (defn take-while "Returns a seq of successive items from the stream while `(pred stream-item)` returns true. When `buffer` is given, the result is going to be concatenated to it." ([pred] (take-while [] pred)) ([buffer0 pred] (letfn [ (consumer [buffer stream] (cond (eof? stream) (yield buffer eof) (empty-chunk? stream) (continue #(consumer buffer %)) :else (let [taken-elems (core/take-while pred stream) remainder (core/drop-while pred stream) new-buffer (concat buffer taken-elems)] (cond (empty? remainder) (continue #(consumer new-buffer %)) :else (yield new-buffer remainder))))) ] #(consumer buffer0 %)))) (defn drop "Drops from the stream the first `n` elements." [n0] (letfn [ (consumer [n stream] (cond (eof? stream) (yield nil stream) (empty-chunk? stream) (continue #(consumer n %)) :else (let [new-n (- n (count stream))] (if (> new-n 0) (continue #(consumer new-n %)) (yield nil (core/drop n stream)))))) ] #(consumer n0 %))) (defn drop-while "Drops elements from the stream until `(pred stream-item)` returns a falsy value." [pred] (fn consumer [stream] (cond (eof? stream) (yield nil eof) (empty-chunk? stream) (continue #(consumer %)) :else (let [new-stream (core/drop-while pred stream)] (if (not (empty? new-stream)) (yield nil new-stream) (continue #(consumer %))))))) (defn consume "Consumes all the stream and returns it in a seq, when `buffer` is given, the result is going to bo concatenated to it." ([] (consume [])) ([buffer] (take-while buffer (constantly true)))) (defn reduce "Consumes the stream item by item supplying each of them to the `f` function. `f` should receive two arguments, the accumulated result and the current element from the stream, if no `zero` is provided, then it will use the first element of the stream as the zero value for the accumulator." ([f] (fn consumer [stream] (cond (eof? stream) (yield nil eof) (empty-chunk? stream) (continue #(consumer %)) :else ((reduce f (core/first stream)) (core/rest stream))))) ([f zero0] (letfn [ (consumer [zero stream] (cond (eof? stream) (yield zero eof) (empty-chunk? stream) (continue #(consumer zero %)) :else (let [new-zero (core/reduce f zero stream)] (continue #(consumer new-zero %))))) ] #(consumer zero0 %)))) (def first "Returns the first item from the stream, when stream has reached EOF this consumer will yield a nil value." (fn consumer [stream] (cond (eof? stream) (yield nil eof) (empty-chunk? stream) (continue consumer) :else (yield (core/first stream) (core/rest stream))))) (def peek "Returns the first item in the stream without actually removing it, when the stream has reached EOF it will yield a nil value." (fn consumer [stream] (cond (eof? stream) (yield nil eof) (empty-chunk? stream) (continue consumer) :else (yield (core/first stream) stream)))) (defn zip "Multiplexes the stream into multiple consumers, each of the consumers will be feed with the stream that this consumer receives, this will return a list of consumer of yields/continuations." [& inner-consumers] (letfn [ (consumer [inner-consumers stream] (cond (eof? stream) (yield (map (comp :result produce-eof) inner-consumers) stream) (empty-chunk? stream) (continue #(consumer inner-consumers %)) :else (continue #(consumer (for [c inner-consumers] (ensure-done c stream)) %))))] #(consumer inner-consumers %))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ## Producers ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn produce-seq "Produces a stream from a seq, and feeds it to the given consumer, when `chunk-size` is given the seq will be streamed every `chunk-size` elements, it will stream 8 items per chunk by default when not given." ([a-seq] (produce-seq 8 a-seq)) ([chunk-size a-seq0] (fn producer [consumer0] (loop [consumer consumer0 a-seq a-seq0] (cond (yield? consumer) consumer (continue? consumer) (let [[input remainder] (core/split-at chunk-size a-seq) next-consumer (consumer input)] (if (empty? remainder) (continue next-consumer) (recur next-consumer remainder)))))))) (defn produce-iterate "Produces an infinite stream by applying the `f` function on the zero value indefinitely. Each chunk is going to have `chunk-size` items, 8 by default." ([f zero] (produce-iterate 8 f zero)) ([chunk-size f zero] (produce-seq chunk-size (core/iterate f zero)))) (defn produce-repeat "Produces an infinite stream that will have the value `elem` indefinitely. Each chunk is going to have `chunk-size` items, 8 by default." ([elem] (produce-repeat 8 elem)) ([chunk-size elem] (produce-seq chunk-size (core/repeat elem)))) (defn produce-replicate "Produces a stream that will have the `elem` value `n` times. Each chunk is going to have `chunk-size` items, 8 by default." ([n elem] (produce-replicate 8 n elem)) ([chunk-size n elem] (produce-seq chunk-size (core/replicate n elem)))) (defn produce-generate "Produces a stream with the `f` function, `f` will likely have side effects because it will return a new value each time. When the `f` function returns a falsy value, the function will stop producing values to the stream." [f] (fn producer [consumer] (if-let [result (f)] (if (continue? consumer) (recur (consumer [result])) consumer) consumer))) (defn- unfold [f zero] (if-let [whole-result (f zero)] (let [[result new-zero] whole-result] (cons result (core/lazy-seq (unfold f new-zero)))) [])) (defn produce-unfold "Produces a stream with the `f` function, `f` will be a function that receives an initial `zero` value, and it will return a tuple with a result and a \"new `zero`\", the result will be fed to the consumer. The stream will stop when the `f` function returns a falsy value. Each chunk is going to have `chunk-size` items, 8 by default." ([f zero] (produce-unfold 8 f zero)) ([chunk-size f zero] (produce-seq chunk-size (unfold f zero)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ## Filters ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mapcat* "Transform the stream by applying function `f` to each element in the stream. `f` will be a function that receives an item and will return a seq, the resulting seqs will be later concatenated and streamed to the consumer." [f] (letfn [ (feed-inner-loop [inner-consumer [item & items :as stream]] (cond (empty-chunk? stream) [inner-consumer stream] (yield? inner-consumer) [inner-consumer stream] (continue? inner-consumer) (recur (inner-consumer (f item)) items))) (outer-consumer [inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) ;(yield (inner-consumer stream) stream) (yield inner-consumer stream) (empty-chunk? stream) (continue #(outer-consumer inner-consumer %)) :else (let [[inner-consumer remainder] (feed-inner-loop inner-consumer stream)] (recur inner-consumer remainder))) :else (throw (Exception. "mapcat*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [inner-consumer] (continue #(outer-consumer inner-consumer %))))) (defn map* "Transform the stream by applying function `f` to each element in the stream. `f` will be a function that receives an item and return another of a (possibly) different type that later will be streamed to the consumer." [f] (fn to-outer-consumer [inner-consumer] ((mapcat* (comp vector f)) inner-consumer))) (defn filter* "Removes elements from the stream by using the function `pred`. `pred` will receive an element from the stream and will return a boolean indicating if the element should be kept in the stream or not. The consumer will be feed with the elements of the stream in which `pred` returns true." [pred] (fn to-outer-consumer [inner-consumer] ((mapcat* (comp #(core/filter pred %) vector)) inner-consumer))) (defn drop-while* "Works similarly to the `drop-while` consumer, it will drop elements from the stream until `pred` holds false, at that point the consumer will be feed with the receiving stream." [pred] (letfn [ (outer-consumer [inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) (yield (inner-consumer stream) stream) (empty-chunk? stream) (continue #(outer-consumer inner-consumer %)) :else (let [new-stream (core/drop-while pred stream)] (if (not (empty-chunk? new-stream)) (yield (inner-consumer new-stream) []) (continue #(outer-consumer inner-consumer %))))) :else (throw (Exception. "drop-while*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [inner-consumer] (continue #(outer-consumer inner-consumer %))))) (defn isolate* "Prevents the consumer from receiving more stream than the specified in `n`, as soon as `n` elements had been feed, the filter will stream an `eof` to the consumer." [n] (letfn [ (outer-consumer [total-count inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) (yield inner-consumer eof) (empty-chunk? stream) (continue #(outer-consumer total-count inner-consumer %)) :else (let [stream-count (count stream) total-count1 (- total-count stream-count)] (if (> stream-count total-count) (yield (inner-consumer (core/take total-count stream)) (core/drop total-count stream)) (continue #(outer-consumer total-count1 (inner-consumer stream) %))))) :else (throw (Exception. "isolate*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [consumer] (continue #(outer-consumer n consumer %))))) (defn require* "Throws an exception if there is not at least `n` elements streamed to the consumer." [n] (letfn [ (outer-consumer [total-count inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) (if (> total-count 0) (throw (Exception. "require*: minimum count wasn't satisifed")) (yield inner-consumer stream)) (empty-chunk? stream) (continue #(outer-consumer total-count inner-consumer %)) :else (let [total-count1 (- total-count (count stream))] (if (<= total-count 0) (yield (inner-consumer stream) []) (continue #(outer-consumer total-count1 (inner-consumer stream) %))))) :else (throw (Exception. "require*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [inner-consumer] (continue #(outer-consumer n inner-consumer %))))) (defn stream-while* "Streams elements to the consumer until the `f` function returns a falsy for item in the stream." [f] (letfn [ (outer-consumer [inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) (yield (inner-consumer stream) stream) (empty-chunk? stream) (continue #(outer-consumer inner-consumer %)) :else (let [[to-feed to-drop] (span f stream)] (if (empty? to-drop) (continue #(outer-consumer (inner-consumer to-feed) %)) (yield (inner-consumer to-feed) to-drop)))) :else (throw (Exception. "stream-while*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [inner-consumer] (continue #(outer-consumer inner-consumer %))))) (defn- split-when-consumer [f] (do-consumer [first-chunks (take-while (complement f)) last-chunk (take 1)] (if (nil? last-chunk) first-chunks (concat first-chunks last-chunk)))) (defn split-when* [f] "Splits on stream elements satisfiying the given `f` function, the consumer will receive a stream of chunks of seqs." (to-filter (split-when-consumer f)))
43525
(ns river.seq ^{ :author "<NAME>" } (:refer-clojure :exclude [take take-while drop drop-while reduce first peek]) (:require [clojure.core :as core]) (:use river.core)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ## Utility Functions ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- span [pred xs] ((core/juxt #(core/take-while pred %) #(core/drop-while pred %)) xs)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ## Consumers ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn take "Returns a seq of the first `n` elements in the stream, or all items if there are fewer than `n`. When `buffer` is given, the result is going to be concatenated to it." ([n0] (take [] n0)) ([buffer0 n0] (letfn [ (consumer [buffer n stream] (cond (eof? stream) (yield buffer eof) (empty-chunk? stream) (continue #((take buffer n) %)) :else (let [taken-elems (concat buffer (core/take n stream)) new-size (- n (count stream))] (if (> new-size 0) (continue #(consumer taken-elems new-size %)) (yield taken-elems (core/drop n stream)))))) ] #(consumer buffer0 n0 %)))) (defn take-while "Returns a seq of successive items from the stream while `(pred stream-item)` returns true. When `buffer` is given, the result is going to be concatenated to it." ([pred] (take-while [] pred)) ([buffer0 pred] (letfn [ (consumer [buffer stream] (cond (eof? stream) (yield buffer eof) (empty-chunk? stream) (continue #(consumer buffer %)) :else (let [taken-elems (core/take-while pred stream) remainder (core/drop-while pred stream) new-buffer (concat buffer taken-elems)] (cond (empty? remainder) (continue #(consumer new-buffer %)) :else (yield new-buffer remainder))))) ] #(consumer buffer0 %)))) (defn drop "Drops from the stream the first `n` elements." [n0] (letfn [ (consumer [n stream] (cond (eof? stream) (yield nil stream) (empty-chunk? stream) (continue #(consumer n %)) :else (let [new-n (- n (count stream))] (if (> new-n 0) (continue #(consumer new-n %)) (yield nil (core/drop n stream)))))) ] #(consumer n0 %))) (defn drop-while "Drops elements from the stream until `(pred stream-item)` returns a falsy value." [pred] (fn consumer [stream] (cond (eof? stream) (yield nil eof) (empty-chunk? stream) (continue #(consumer %)) :else (let [new-stream (core/drop-while pred stream)] (if (not (empty? new-stream)) (yield nil new-stream) (continue #(consumer %))))))) (defn consume "Consumes all the stream and returns it in a seq, when `buffer` is given, the result is going to bo concatenated to it." ([] (consume [])) ([buffer] (take-while buffer (constantly true)))) (defn reduce "Consumes the stream item by item supplying each of them to the `f` function. `f` should receive two arguments, the accumulated result and the current element from the stream, if no `zero` is provided, then it will use the first element of the stream as the zero value for the accumulator." ([f] (fn consumer [stream] (cond (eof? stream) (yield nil eof) (empty-chunk? stream) (continue #(consumer %)) :else ((reduce f (core/first stream)) (core/rest stream))))) ([f zero0] (letfn [ (consumer [zero stream] (cond (eof? stream) (yield zero eof) (empty-chunk? stream) (continue #(consumer zero %)) :else (let [new-zero (core/reduce f zero stream)] (continue #(consumer new-zero %))))) ] #(consumer zero0 %)))) (def first "Returns the first item from the stream, when stream has reached EOF this consumer will yield a nil value." (fn consumer [stream] (cond (eof? stream) (yield nil eof) (empty-chunk? stream) (continue consumer) :else (yield (core/first stream) (core/rest stream))))) (def peek "Returns the first item in the stream without actually removing it, when the stream has reached EOF it will yield a nil value." (fn consumer [stream] (cond (eof? stream) (yield nil eof) (empty-chunk? stream) (continue consumer) :else (yield (core/first stream) stream)))) (defn zip "Multiplexes the stream into multiple consumers, each of the consumers will be feed with the stream that this consumer receives, this will return a list of consumer of yields/continuations." [& inner-consumers] (letfn [ (consumer [inner-consumers stream] (cond (eof? stream) (yield (map (comp :result produce-eof) inner-consumers) stream) (empty-chunk? stream) (continue #(consumer inner-consumers %)) :else (continue #(consumer (for [c inner-consumers] (ensure-done c stream)) %))))] #(consumer inner-consumers %))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ## Producers ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn produce-seq "Produces a stream from a seq, and feeds it to the given consumer, when `chunk-size` is given the seq will be streamed every `chunk-size` elements, it will stream 8 items per chunk by default when not given." ([a-seq] (produce-seq 8 a-seq)) ([chunk-size a-seq0] (fn producer [consumer0] (loop [consumer consumer0 a-seq a-seq0] (cond (yield? consumer) consumer (continue? consumer) (let [[input remainder] (core/split-at chunk-size a-seq) next-consumer (consumer input)] (if (empty? remainder) (continue next-consumer) (recur next-consumer remainder)))))))) (defn produce-iterate "Produces an infinite stream by applying the `f` function on the zero value indefinitely. Each chunk is going to have `chunk-size` items, 8 by default." ([f zero] (produce-iterate 8 f zero)) ([chunk-size f zero] (produce-seq chunk-size (core/iterate f zero)))) (defn produce-repeat "Produces an infinite stream that will have the value `elem` indefinitely. Each chunk is going to have `chunk-size` items, 8 by default." ([elem] (produce-repeat 8 elem)) ([chunk-size elem] (produce-seq chunk-size (core/repeat elem)))) (defn produce-replicate "Produces a stream that will have the `elem` value `n` times. Each chunk is going to have `chunk-size` items, 8 by default." ([n elem] (produce-replicate 8 n elem)) ([chunk-size n elem] (produce-seq chunk-size (core/replicate n elem)))) (defn produce-generate "Produces a stream with the `f` function, `f` will likely have side effects because it will return a new value each time. When the `f` function returns a falsy value, the function will stop producing values to the stream." [f] (fn producer [consumer] (if-let [result (f)] (if (continue? consumer) (recur (consumer [result])) consumer) consumer))) (defn- unfold [f zero] (if-let [whole-result (f zero)] (let [[result new-zero] whole-result] (cons result (core/lazy-seq (unfold f new-zero)))) [])) (defn produce-unfold "Produces a stream with the `f` function, `f` will be a function that receives an initial `zero` value, and it will return a tuple with a result and a \"new `zero`\", the result will be fed to the consumer. The stream will stop when the `f` function returns a falsy value. Each chunk is going to have `chunk-size` items, 8 by default." ([f zero] (produce-unfold 8 f zero)) ([chunk-size f zero] (produce-seq chunk-size (unfold f zero)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ## Filters ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mapcat* "Transform the stream by applying function `f` to each element in the stream. `f` will be a function that receives an item and will return a seq, the resulting seqs will be later concatenated and streamed to the consumer." [f] (letfn [ (feed-inner-loop [inner-consumer [item & items :as stream]] (cond (empty-chunk? stream) [inner-consumer stream] (yield? inner-consumer) [inner-consumer stream] (continue? inner-consumer) (recur (inner-consumer (f item)) items))) (outer-consumer [inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) ;(yield (inner-consumer stream) stream) (yield inner-consumer stream) (empty-chunk? stream) (continue #(outer-consumer inner-consumer %)) :else (let [[inner-consumer remainder] (feed-inner-loop inner-consumer stream)] (recur inner-consumer remainder))) :else (throw (Exception. "mapcat*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [inner-consumer] (continue #(outer-consumer inner-consumer %))))) (defn map* "Transform the stream by applying function `f` to each element in the stream. `f` will be a function that receives an item and return another of a (possibly) different type that later will be streamed to the consumer." [f] (fn to-outer-consumer [inner-consumer] ((mapcat* (comp vector f)) inner-consumer))) (defn filter* "Removes elements from the stream by using the function `pred`. `pred` will receive an element from the stream and will return a boolean indicating if the element should be kept in the stream or not. The consumer will be feed with the elements of the stream in which `pred` returns true." [pred] (fn to-outer-consumer [inner-consumer] ((mapcat* (comp #(core/filter pred %) vector)) inner-consumer))) (defn drop-while* "Works similarly to the `drop-while` consumer, it will drop elements from the stream until `pred` holds false, at that point the consumer will be feed with the receiving stream." [pred] (letfn [ (outer-consumer [inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) (yield (inner-consumer stream) stream) (empty-chunk? stream) (continue #(outer-consumer inner-consumer %)) :else (let [new-stream (core/drop-while pred stream)] (if (not (empty-chunk? new-stream)) (yield (inner-consumer new-stream) []) (continue #(outer-consumer inner-consumer %))))) :else (throw (Exception. "drop-while*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [inner-consumer] (continue #(outer-consumer inner-consumer %))))) (defn isolate* "Prevents the consumer from receiving more stream than the specified in `n`, as soon as `n` elements had been feed, the filter will stream an `eof` to the consumer." [n] (letfn [ (outer-consumer [total-count inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) (yield inner-consumer eof) (empty-chunk? stream) (continue #(outer-consumer total-count inner-consumer %)) :else (let [stream-count (count stream) total-count1 (- total-count stream-count)] (if (> stream-count total-count) (yield (inner-consumer (core/take total-count stream)) (core/drop total-count stream)) (continue #(outer-consumer total-count1 (inner-consumer stream) %))))) :else (throw (Exception. "isolate*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [consumer] (continue #(outer-consumer n consumer %))))) (defn require* "Throws an exception if there is not at least `n` elements streamed to the consumer." [n] (letfn [ (outer-consumer [total-count inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) (if (> total-count 0) (throw (Exception. "require*: minimum count wasn't satisifed")) (yield inner-consumer stream)) (empty-chunk? stream) (continue #(outer-consumer total-count inner-consumer %)) :else (let [total-count1 (- total-count (count stream))] (if (<= total-count 0) (yield (inner-consumer stream) []) (continue #(outer-consumer total-count1 (inner-consumer stream) %))))) :else (throw (Exception. "require*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [inner-consumer] (continue #(outer-consumer n inner-consumer %))))) (defn stream-while* "Streams elements to the consumer until the `f` function returns a falsy for item in the stream." [f] (letfn [ (outer-consumer [inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) (yield (inner-consumer stream) stream) (empty-chunk? stream) (continue #(outer-consumer inner-consumer %)) :else (let [[to-feed to-drop] (span f stream)] (if (empty? to-drop) (continue #(outer-consumer (inner-consumer to-feed) %)) (yield (inner-consumer to-feed) to-drop)))) :else (throw (Exception. "stream-while*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [inner-consumer] (continue #(outer-consumer inner-consumer %))))) (defn- split-when-consumer [f] (do-consumer [first-chunks (take-while (complement f)) last-chunk (take 1)] (if (nil? last-chunk) first-chunks (concat first-chunks last-chunk)))) (defn split-when* [f] "Splits on stream elements satisfiying the given `f` function, the consumer will receive a stream of chunks of seqs." (to-filter (split-when-consumer f)))
true
(ns river.seq ^{ :author "PI:NAME:<NAME>END_PI" } (:refer-clojure :exclude [take take-while drop drop-while reduce first peek]) (:require [clojure.core :as core]) (:use river.core)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ## Utility Functions ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- span [pred xs] ((core/juxt #(core/take-while pred %) #(core/drop-while pred %)) xs)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ## Consumers ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn take "Returns a seq of the first `n` elements in the stream, or all items if there are fewer than `n`. When `buffer` is given, the result is going to be concatenated to it." ([n0] (take [] n0)) ([buffer0 n0] (letfn [ (consumer [buffer n stream] (cond (eof? stream) (yield buffer eof) (empty-chunk? stream) (continue #((take buffer n) %)) :else (let [taken-elems (concat buffer (core/take n stream)) new-size (- n (count stream))] (if (> new-size 0) (continue #(consumer taken-elems new-size %)) (yield taken-elems (core/drop n stream)))))) ] #(consumer buffer0 n0 %)))) (defn take-while "Returns a seq of successive items from the stream while `(pred stream-item)` returns true. When `buffer` is given, the result is going to be concatenated to it." ([pred] (take-while [] pred)) ([buffer0 pred] (letfn [ (consumer [buffer stream] (cond (eof? stream) (yield buffer eof) (empty-chunk? stream) (continue #(consumer buffer %)) :else (let [taken-elems (core/take-while pred stream) remainder (core/drop-while pred stream) new-buffer (concat buffer taken-elems)] (cond (empty? remainder) (continue #(consumer new-buffer %)) :else (yield new-buffer remainder))))) ] #(consumer buffer0 %)))) (defn drop "Drops from the stream the first `n` elements." [n0] (letfn [ (consumer [n stream] (cond (eof? stream) (yield nil stream) (empty-chunk? stream) (continue #(consumer n %)) :else (let [new-n (- n (count stream))] (if (> new-n 0) (continue #(consumer new-n %)) (yield nil (core/drop n stream)))))) ] #(consumer n0 %))) (defn drop-while "Drops elements from the stream until `(pred stream-item)` returns a falsy value." [pred] (fn consumer [stream] (cond (eof? stream) (yield nil eof) (empty-chunk? stream) (continue #(consumer %)) :else (let [new-stream (core/drop-while pred stream)] (if (not (empty? new-stream)) (yield nil new-stream) (continue #(consumer %))))))) (defn consume "Consumes all the stream and returns it in a seq, when `buffer` is given, the result is going to bo concatenated to it." ([] (consume [])) ([buffer] (take-while buffer (constantly true)))) (defn reduce "Consumes the stream item by item supplying each of them to the `f` function. `f` should receive two arguments, the accumulated result and the current element from the stream, if no `zero` is provided, then it will use the first element of the stream as the zero value for the accumulator." ([f] (fn consumer [stream] (cond (eof? stream) (yield nil eof) (empty-chunk? stream) (continue #(consumer %)) :else ((reduce f (core/first stream)) (core/rest stream))))) ([f zero0] (letfn [ (consumer [zero stream] (cond (eof? stream) (yield zero eof) (empty-chunk? stream) (continue #(consumer zero %)) :else (let [new-zero (core/reduce f zero stream)] (continue #(consumer new-zero %))))) ] #(consumer zero0 %)))) (def first "Returns the first item from the stream, when stream has reached EOF this consumer will yield a nil value." (fn consumer [stream] (cond (eof? stream) (yield nil eof) (empty-chunk? stream) (continue consumer) :else (yield (core/first stream) (core/rest stream))))) (def peek "Returns the first item in the stream without actually removing it, when the stream has reached EOF it will yield a nil value." (fn consumer [stream] (cond (eof? stream) (yield nil eof) (empty-chunk? stream) (continue consumer) :else (yield (core/first stream) stream)))) (defn zip "Multiplexes the stream into multiple consumers, each of the consumers will be feed with the stream that this consumer receives, this will return a list of consumer of yields/continuations." [& inner-consumers] (letfn [ (consumer [inner-consumers stream] (cond (eof? stream) (yield (map (comp :result produce-eof) inner-consumers) stream) (empty-chunk? stream) (continue #(consumer inner-consumers %)) :else (continue #(consumer (for [c inner-consumers] (ensure-done c stream)) %))))] #(consumer inner-consumers %))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ## Producers ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn produce-seq "Produces a stream from a seq, and feeds it to the given consumer, when `chunk-size` is given the seq will be streamed every `chunk-size` elements, it will stream 8 items per chunk by default when not given." ([a-seq] (produce-seq 8 a-seq)) ([chunk-size a-seq0] (fn producer [consumer0] (loop [consumer consumer0 a-seq a-seq0] (cond (yield? consumer) consumer (continue? consumer) (let [[input remainder] (core/split-at chunk-size a-seq) next-consumer (consumer input)] (if (empty? remainder) (continue next-consumer) (recur next-consumer remainder)))))))) (defn produce-iterate "Produces an infinite stream by applying the `f` function on the zero value indefinitely. Each chunk is going to have `chunk-size` items, 8 by default." ([f zero] (produce-iterate 8 f zero)) ([chunk-size f zero] (produce-seq chunk-size (core/iterate f zero)))) (defn produce-repeat "Produces an infinite stream that will have the value `elem` indefinitely. Each chunk is going to have `chunk-size` items, 8 by default." ([elem] (produce-repeat 8 elem)) ([chunk-size elem] (produce-seq chunk-size (core/repeat elem)))) (defn produce-replicate "Produces a stream that will have the `elem` value `n` times. Each chunk is going to have `chunk-size` items, 8 by default." ([n elem] (produce-replicate 8 n elem)) ([chunk-size n elem] (produce-seq chunk-size (core/replicate n elem)))) (defn produce-generate "Produces a stream with the `f` function, `f` will likely have side effects because it will return a new value each time. When the `f` function returns a falsy value, the function will stop producing values to the stream." [f] (fn producer [consumer] (if-let [result (f)] (if (continue? consumer) (recur (consumer [result])) consumer) consumer))) (defn- unfold [f zero] (if-let [whole-result (f zero)] (let [[result new-zero] whole-result] (cons result (core/lazy-seq (unfold f new-zero)))) [])) (defn produce-unfold "Produces a stream with the `f` function, `f` will be a function that receives an initial `zero` value, and it will return a tuple with a result and a \"new `zero`\", the result will be fed to the consumer. The stream will stop when the `f` function returns a falsy value. Each chunk is going to have `chunk-size` items, 8 by default." ([f zero] (produce-unfold 8 f zero)) ([chunk-size f zero] (produce-seq chunk-size (unfold f zero)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ## Filters ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mapcat* "Transform the stream by applying function `f` to each element in the stream. `f` will be a function that receives an item and will return a seq, the resulting seqs will be later concatenated and streamed to the consumer." [f] (letfn [ (feed-inner-loop [inner-consumer [item & items :as stream]] (cond (empty-chunk? stream) [inner-consumer stream] (yield? inner-consumer) [inner-consumer stream] (continue? inner-consumer) (recur (inner-consumer (f item)) items))) (outer-consumer [inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) ;(yield (inner-consumer stream) stream) (yield inner-consumer stream) (empty-chunk? stream) (continue #(outer-consumer inner-consumer %)) :else (let [[inner-consumer remainder] (feed-inner-loop inner-consumer stream)] (recur inner-consumer remainder))) :else (throw (Exception. "mapcat*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [inner-consumer] (continue #(outer-consumer inner-consumer %))))) (defn map* "Transform the stream by applying function `f` to each element in the stream. `f` will be a function that receives an item and return another of a (possibly) different type that later will be streamed to the consumer." [f] (fn to-outer-consumer [inner-consumer] ((mapcat* (comp vector f)) inner-consumer))) (defn filter* "Removes elements from the stream by using the function `pred`. `pred` will receive an element from the stream and will return a boolean indicating if the element should be kept in the stream or not. The consumer will be feed with the elements of the stream in which `pred` returns true." [pred] (fn to-outer-consumer [inner-consumer] ((mapcat* (comp #(core/filter pred %) vector)) inner-consumer))) (defn drop-while* "Works similarly to the `drop-while` consumer, it will drop elements from the stream until `pred` holds false, at that point the consumer will be feed with the receiving stream." [pred] (letfn [ (outer-consumer [inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) (yield (inner-consumer stream) stream) (empty-chunk? stream) (continue #(outer-consumer inner-consumer %)) :else (let [new-stream (core/drop-while pred stream)] (if (not (empty-chunk? new-stream)) (yield (inner-consumer new-stream) []) (continue #(outer-consumer inner-consumer %))))) :else (throw (Exception. "drop-while*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [inner-consumer] (continue #(outer-consumer inner-consumer %))))) (defn isolate* "Prevents the consumer from receiving more stream than the specified in `n`, as soon as `n` elements had been feed, the filter will stream an `eof` to the consumer." [n] (letfn [ (outer-consumer [total-count inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) (yield inner-consumer eof) (empty-chunk? stream) (continue #(outer-consumer total-count inner-consumer %)) :else (let [stream-count (count stream) total-count1 (- total-count stream-count)] (if (> stream-count total-count) (yield (inner-consumer (core/take total-count stream)) (core/drop total-count stream)) (continue #(outer-consumer total-count1 (inner-consumer stream) %))))) :else (throw (Exception. "isolate*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [consumer] (continue #(outer-consumer n consumer %))))) (defn require* "Throws an exception if there is not at least `n` elements streamed to the consumer." [n] (letfn [ (outer-consumer [total-count inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) (if (> total-count 0) (throw (Exception. "require*: minimum count wasn't satisifed")) (yield inner-consumer stream)) (empty-chunk? stream) (continue #(outer-consumer total-count inner-consumer %)) :else (let [total-count1 (- total-count (count stream))] (if (<= total-count 0) (yield (inner-consumer stream) []) (continue #(outer-consumer total-count1 (inner-consumer stream) %))))) :else (throw (Exception. "require*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [inner-consumer] (continue #(outer-consumer n inner-consumer %))))) (defn stream-while* "Streams elements to the consumer until the `f` function returns a falsy for item in the stream." [f] (letfn [ (outer-consumer [inner-consumer stream] (cond (yield? inner-consumer) (yield inner-consumer stream) (continue? inner-consumer) (cond (eof? stream) (yield (inner-consumer stream) stream) (empty-chunk? stream) (continue #(outer-consumer inner-consumer %)) :else (let [[to-feed to-drop] (span f stream)] (if (empty? to-drop) (continue #(outer-consumer (inner-consumer to-feed) %)) (yield (inner-consumer to-feed) to-drop)))) :else (throw (Exception. "stream-while*: invalid consumer (not yield nor continue)"))))] (fn to-outer-consumer [inner-consumer] (continue #(outer-consumer inner-consumer %))))) (defn- split-when-consumer [f] (do-consumer [first-chunks (take-while (complement f)) last-chunk (take 1)] (if (nil? last-chunk) first-chunks (concat first-chunks last-chunk)))) (defn split-when* [f] "Splits on stream elements satisfiying the given `f` function, the consumer will receive a stream of chunks of seqs." (to-filter (split-when-consumer f)))
[ { "context": "as response]))\n\n(defpage \"/\" []\n (layout/layout \"Brian Jesse\"\n [:div.wrapper\n [:div.title.hidden-phone", "end": 317, "score": 0.9993941783905029, "start": 306, "tag": "NAME", "value": "Brian Jesse" }, { "context": "n10\n [:div.row\n [:h1 \"Brian Jesse\"]]\n [:div.row\n [:a.bt", "end": 607, "score": 0.9998133182525635, "start": 596, "tag": "NAME", "value": "Brian Jesse" }, { "context": "rimary.btn-large {:href \"https://www.facebook.com/BJesse90\"} \n [:i.icon-facebook-sign.icon-", "end": 722, "score": 0.999675452709198, "start": 714, "tag": "USERNAME", "value": "BJesse90" }, { "context": "ary.btn-large {:href \"http://www.linkedin.com/pub/brian-jesse/57/769/136\"} \n [:i.icon-linkedin", "end": 916, "score": 0.9996669888496399, "start": 905, "tag": "USERNAME", "value": "brian-jesse" }, { "context": "on-reorder]]\n [:a.brand {:href \"#\"} \"Brian Jesse\"]\n [:div.nav-collapse\n ", "end": 1349, "score": 0.9997241497039795, "start": 1338, "tag": "NAME", "value": "Brian Jesse" }, { "context": " [:li [:a {:href \"http://www.linkedin.com/pub/brian-jesse/57/769/136\"} [:i.icon-linkedin-sign.pull-right] \"", "end": 1484, "score": 0.9997112154960632, "start": 1473, "tag": "USERNAME", "value": "brian-jesse" }, { "context": " [:li [:a {:href \"https://www.facebook.com/BJesse90\"} [:i.icon-facebook-sign.pull-right] \"Facebook\"]]", "end": 1614, "score": 0.9996752142906189, "start": 1606, "tag": "USERNAME", "value": "BJesse90" }, { "context": ":footer\n [:div.container\n [:h4 \"&copy; Brian Jesse 2012\"]]]))\n\n(defpage \"/partials/home\" []\n (html\n", "end": 3714, "score": 0.9995589256286621, "start": 3703, "tag": "NAME", "value": "Brian Jesse" }, { "context": " [:a.fb-badge {:href \"https://www.facebook.com/BJesse90\" :target \"_TOP\" :title \"Brian Jesse\"}\n [:img", "end": 3870, "score": 0.9993813633918762, "start": 3862, "tag": "USERNAME", "value": "BJesse90" }, { "context": "www.facebook.com/BJesse90\" :target \"_TOP\" :title \"Brian Jesse\"}\n [:img.img-rounded {:src \"https://www.face", "end": 3906, "score": 0.9939822554588318, "start": 3895, "tag": "NAME", "value": "Brian Jesse" }, { "context": "facebook.com/badge.php?id=1463500045&bid=2846&key=783105830&format=png&z=1373594599\" :style \"border: 0px;\"}]]", "end": 4011, "score": 0.9561945796012878, "start": 4002, "tag": "KEY", "value": "783105830" }, { "context": "ary.btn-large {:href \"http://www.linkedin.com/pub/brian-jesse/57/769/136\"} \n [:i.icon-linkedin", "end": 9424, "score": 0.9993835687637329, "start": 9413, "tag": "USERNAME", "value": "brian-jesse" } ]
data/clojure/379e8c764374a7ed930ba76227c3b8ab_index.clj
maxim5/code-inspector
5
(ns it354.views.index (:use [noir.core :only [defpage defpartial]] [hiccup.core :only [html]]) (:require [it354.views.layout :as layout] [it354.views.utils :as utils] [it354.models.db :as db] [noir.response :as response])) (defpage "/" [] (layout/layout "Brian Jesse" [:div.wrapper [:div.title.hidden-phone [:div.container [:div.row [:div.span2.hidden-phone [:img.img-polaroid {:src (utils/add-context "/img/me.jpg")}]] [:div.span10 [:div.row [:h1 "Brian Jesse"]] [:div.row [:a.btn.btn-primary.btn-large {:href "https://www.facebook.com/BJesse90"} [:i.icon-facebook-sign.icon-large] "View Facebook Profile"] [:a.btn.btn-primary.btn-large {:href "http://www.linkedin.com/pub/brian-jesse/57/769/136"} [:i.icon-linkedin-sign.icon-large] "View Linkedin Profile"]]]]]] [:div#main_content.content [:div.navbar.navbar-fixed-top.visible-phone [:div.navbar-inner [:div.container [:a.btn.btn-navbar {:data-toggle "collapse" :data-target ".nav-collapse"} [:span.icon-reorder]] [:a.brand {:href "#"} "Brian Jesse"] [:div.nav-collapse [:ul.nav [:li [:a {:href "http://www.linkedin.com/pub/brian-jesse/57/769/136"} [:i.icon-linkedin-sign.pull-right] "LinkedIn"]] [:li [:a {:href "https://www.facebook.com/BJesse90"} [:i.icon-facebook-sign.pull-right] "Facebook"]] [:li [:a {:href "#/home"} [:i.icon-chevron-right.pull-right] "Home"]] [:li [:a {:href "#/resume"} [:i.icon-chevron-right.pull-right] "Resume"]] [:li [:a {:href "#/links"} [:i.icon-chevron-right.pull-right] "Links"]] [:li [:a {:href "#/pipes"} [:i.icon-chevron-right.pull-right] "Pipes"]] [:li [:a {:href "#/restaurants"} [:i.icon-chevron-right.pull-right] "Restaurants"]] [:li [:a {:href "#/places"} [:i.icon-chevron-right.pull-right] "Places"]] [:li [:a {:href "#/examples"} [:i.icon-chevron-right.pull-right] "Examples"]] [:li [:a {:href "#/gallery"} [:i.icon-chevron-right.pull-right] "Gallery"]] [:li [:a {:href "#/videos"} [:i.icon-chevron-right.pull-right] "Videos"]]]]]]] [:div.container [:div.row [:div.span3.hidden-phone [:ul.nav.nav-list [:li [:a {:href "#/home" :class "{{homeLink}}"} [:i.icon-chevron-right] "Home"]] [:li [:a {:href "#/resume" :class "{{resumeLink}}"} [:i.icon-chevron-right] "Resume"]] [:li [:a {:href "#/links" :class "{{linksLink}}"} [:i.icon-chevron-right] "Links"]] [:li [:a {:href "#/pipes" :class "{{pipesLink}}"} [:i.icon-chevron-right] "Pipes"]] [:li [:a {:href "#/restaurants" :class "{{restaurantsLink}}"} [:i.icon-chevron-right] "Restaurants"]] [:li [:a {:href "#/places" :class "{{placesLink}}"} [:i.icon-chevron-right] "Places"]] [:li [:a {:href "#/examples" :class "{{examplesLink}}"} [:i.icon-chevron-right] "Examples"]] [:li [:a {:href "#/gallery" :class "{{galleryLink}}"} [:i.icon-chevron-right] "Gallery"]] [:li [:a {:href "#/videos" :class "{{videosLink}}"} [:i.icon-chevron-right] "Videos"]]]] [:div.span9 [:div.well {:ng-view ""}]]]]] [:div.push]] [:footer [:div.container [:h4 "&copy; Brian Jesse 2012"]]])) (defpage "/partials/home" [] (html (utils/comment-html "Facebook Badge START") [:a.fb-badge {:href "https://www.facebook.com/BJesse90" :target "_TOP" :title "Brian Jesse"} [:img.img-rounded {:src "https://www.facebook.com/badge.php?id=1463500045&bid=2846&key=783105830&format=png&z=1373594599" :style "border: 0px;"}]] (utils/comment-html "Facebook Badge END") [:h2 "About Me"] [:p "I am currently pursuing a bachelor's degreen in Computer Science at Illinois State University. I work for the department of Business Intelligence and Technology Solutions at ISU as a Java web programmer. I have experience working in tech support in a small business and an enterprise environment. Last spring I was selected as a finalist in the State Farm Mobile App Development competition for my social goal tracking app Goalcharge"] [:p [:a.btn {:href "#/videos"} "Check out the Goalcharge video &raquo;"]])) (defpage "/partials/resume" [] (html [:h2 "Resume"] [:hr] [:h3 "Objective"] [:table.table.table-bordered.table-striped [:tr [:td "To enhance my web development expertise, further my programming skills, and improve my general computer knowledge in a challenging, fast paced, and team-oriented environment."]]] [:h3 "Education"] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Illinois State University, "] "Normal IL (2010-Present)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Major:"]] [:td "Computer Science"]] [:tr [:td [:u "Curriculum:"]] [:td "Mathematics, technical and group skills, programming, and web development"]] [:tr [:td [:u "Involvement:"]] [:td "IT club; performed as webmaster for various clubs"]]]] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Illinois Valley Community College, "] "Oglesby IL (2008-2010)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Curriculum:"]] [:td "Programming, Electronic Theory, Chemistry, Calculus"]] [:tr [:td [:u "Involvement:"]] [:td "Association of Information Technology Professionals (AITP), Psychology Club, theater, political activism, and civic organizations"]]]] [:h3 "Qualifications"] [:table.table.table-bordered.table-striped.table-hover [:tr [:td "Two years of Java experience including use of JPA, JSF, and restful web services"]] [:tr [:td "Finalist in a mobile app development contest"]] [:tr [:td "Website design skills using HTML 5 and CSS 3 for desktops and mobile devices"]] [:tr [:td "Apache, Glassfish, PHP, and JavaScript development skills"]] [:tr [:td "Unix server administration on Debian and Red Hat installations"]] [:tr [:td "C++ proficiency and extensive knowledge of data structures and algorithms"]] [:tr [:td "Experience working with collaborative build tools such as Maven, Subversion, and Git"]] [:tr [:td "Talents with graphic arts and video editing utilizing Adobe suites"]]] [:h3 "Experience"] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Business Intelligence and Technology Solutions - Illinois State University, "] "Normal IL"]] [:tr [:th {:colspan "2"} "Web Team Intern (Aug 2011-Present)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Duties:"]] [:td "Java web app programming and rewriting, CMS integration with website"]] [:tr [:td [:u "Skills Gained:"]] [:td "Project management and development in a highly skilled environment, multiple development environments"]]]] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Enterprise Systems Support - Illinois State University, "] "Normal IL"]] [:tr [:th {:colspan "2"} "Senior Technician (Mar 2011 - Aug 2011)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Duties:"]] [:td "IT support, secure computer deployment, mobile development, and supervising techs"]] [:tr [:td [:u "Skills Gained:"]] [:td "Managing multiple open tickets, and solving customer’s issues"]]]] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Computer Spa, "] "Ottawa IL"]] [:tr [:th {:colspan "2"} "(Jun 2009 - May 2010)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Duties:"]] [:td "Computer repair and maintenance, maintaining Windows and Novell networks"]] [:tr [:td [:u "Skills Gained:"]] [:td "Personal interaction with business clients"]]]] [:a.btn.btn-primary.btn-large {:href "http://www.linkedin.com/pub/brian-jesse/57/769/136"} [:i.icon-linkedin-sign.icon-large] "View Linkedin Profile"])) (defpage "/partials/links" [] (html [:h2 "My Favorite Links"] [:div#links.accordion [:div.accordion-group [:div.accordion-heading [:a.accordion-toggle {:data-toggle "collapse" :data-parent "#links" :href "#links1"} "Blogs"]] [:div#links1.accordion-body.collapse.in [:div.accordion-inner [:ul [:li [:a {:href "//theverge.com" :target "_blank"} "The Verge"]] [:li [:a {:href "//xkcd.com/" :target "_blank"} "XKCD"]] [:li [:a {:href "//blog.hash-of-codes.com" :target "_blank"} "Hash of Codes"]]]]]] [:div.accordion-group [:div.accordion-heading [:a.accordion-toggle {:data-toggle "collapse" :data-parent "#links" :href "#links2"} "Social Media"]] [:div#links2.accordion-body.collapse [:div.accordion-inner [:ul [:li [:a {:href "//reddit.com" :target "_blank"} "Reddit"]] [:li [:a {:href "//coderwall.com" :target "_blank"} "Coderwall"]] [:li [:a {:href "//news.ycombinator.org" :target "_blank"} "Hacker News"]]]]]] [:div.accordion-group [:div.accordion-heading [:a.accordion-toggle {:data-toggle "collapse" :data-parent "#links" :href "#links3"} "Programming"]] [:div#links3.accordion-body.collapse [:div.accordion-inner [:ul [:li [:a {:href "//bitbucket.org" :target "_blank"} "Bitbucket"]] [:li [:a {:href "//webnoir.org" :target "_blank"} "Noir"]] [:li [:a {:href "//twitter.github.com" :target "_blank"} "Twitter Bootstrap"]]]]]]])) (defpage "/partials/pipes" [] (html [:h2 "Yahoo Pipes Example"] [:div#pipe] [:p [:a.btn {:href "http://pipes.yahoo.com/pipes/pipe.info?_id=0857e00eb73ac6bc8c974b60f6c30e96"} "View Pipe on Yahoo &raquo;"]])) (defpage "/partials/videos" [] (html [:h2 "My Videos"] [:hr] [:h3 "Goalcharge"] [:p "An app I created for the Mobile App contest last semester"] [:iframe.visible-desktop {:width "640" :height "480" :src "//www.youtube.com/embed/v3RTXbi7g4o?rel=0" :frameborder "0" :allowfullscreen ""}] [:iframe.visible-tablet {:width "480" :height "360" :src "//www.youtube.com/embed/v3RTXbi7g4o?rel=0" :frameborder "0" :allowfullscreen ""}] [:a.btn.visible-phone {:href "http://youtu.be/v3RTXbi7g4o"} "View Video On Youtube"])) (defpage "/partials/places" [] (html [:h2 "Places"] [:ul#places_tabs.nav.nav-tabs [:li.active [:a {:href "#" :ng-click "showNormal()"} "Normal"]] [:li [:a {:href "#" :ng-click "showChicago()"} "Chicago"]]] [:div#map_canvas])) (defpage "/partials/places/normal" [] (html [:div.info-window [:h4 "Normal, IL"] [:p "I was born here, most of my family is here, and I don't get out of here often. I do love this town though."]])) (defpage "/partials/places/chicago" [] (html [:div.info-window [:h4 "Chicago, IL"] [:p "I haven't spent too much time here, but I do go on occasion for conferences and professional gatherings. I'll probably work downtown some day."]])) (defpage "/partials/restaurants" [] (html [:h2 "Restaurants"] [:div.tabbable [:ul#restaurant_tabs.nav.nav-tabs [:li.active [:a {:href "#restaurant_tab_1" :data-toggle "tab"} "Restaurant List"]] [:li [:a {:href "#restaurant_tab_2" :data-gtoggle "tab"} "{{{true:'Edit',false:'Add'}[edit]}} Restaurant"]]] [:div.tab-content [:div#restaurant_tab_1.tab-pane.active [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th [:a {:ng-click "column='restaurant_name';reverse=false" :ng-show "column!='restaurant_name'"} "Name"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='restaurant_name'"} "Name"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='restaurant_name'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th [:a {:ng-click "column='address';reverse=false" :ng-show "column!='address'"} "Address"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='address'"} "Address"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='address'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th [:a {:ng-click "column='city';reverse=false" :ng-show "column!='city'"} "City"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='city'"} "City"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='city'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th [:a {:ng-click "column='state';reverse=false" :ng-show "column!='state'"} "St"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='state'"} "St"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='state'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th [:a {:ng-click "column='zip';reverse=false" :ng-show "column!='zip'"} "Zip"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='zip'"} "Zip"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='zip'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th "Edit"] [:th "Delete"]] [:colgroup [:col.span2] [:col.span2] [:col.span2] [:col.span1] [:col.span1] [:col.span1] [:col.span1]]] [:tbody {:ng-repeat "restaurant in restaurantList | orderBy:column:reverse"} [:tr [:td "{{restaurant.restaurant_name}}"] [:td "{{restaurant.address}}"] [:td "{{restaurant.city}}"] [:td "{{restaurant.state}}"] [:td "{{restaurant.zip}}"] [:td.action-icon [:a {:ng-click (str "update(restaurant.restaurant_name," "restaurant.address," "restaurant.city," "restaurant.state," "restaurant.zip)")} [:i.icon-edit]]] [:td.action-icon [:a {:ng-click "$parent.confirm=$index" :ng-show "$parent.confirm!=$index"} [:i.icon-trash]] [:a {:ng-click "$parent.confirm=-1" :ng-show "$parent.confirm==$index"} [:i.icon-ban-circle]]]] [:tr {:ng-show "$parent.confirm==$index"} [:td.confirm-delete {:colspan "7"} [:a.btn.btn-danger {:ng-click "remove(restaurant.restaurant_name);$parent.confirm=-1"} "Confirm Delete"]]]]]] [:div#restaurant_tab_2.tab-pane [:div#add_restaurant_placeholder] [:form#add_restaurant.form-horizontal {:name "add_restaurant" :ng-submit "save()"} [:fieldset [:div.control-group {:ng-class "{error: add_restaurant.restaurant_name.$invalid}"} [:label.control-label {:for "add_restaurant_name"} "Name: "] [:div.controls [:input#add_restaurant_name.input-xlarge {:ng-model "restaurant_name" :type "text" :name "restaurant_name" :maxlength "35" :required ""}] [:span.help-inline {:ng-show "add_restaurant.restaurant_name.$invalid"} "Name must be non-empty"] [:p "Enter the restaurant name"]]] [:div.control-group {:ng-class "{error: add_restaurant.address.$invalid}"} [:label.control-label {:for "add_restaurant_address"} "Address: "] [:div.controls [:input#add_restaurant_address.input-xlarge {:ng-model "address" :type "text" :name "address" :maxlength "40" :required ""}] [:span.help-inline {:ng-show "add_restaurant.address.$invalid"} "Address must be non-empty"] [:p "Enter the restaurant's street address"]]] [:div.control-group {:ng-class "{error: add_restaurant.city.$invalid}"} [:label.control-label {:for "add_restaurant_city"} "City: "] [:div.controls [:input#add_restaurant_city.input-xlarge {:ng-model "city" :type "text" :name "city" :maxlength "30" :required ""}] [:span.help-inline {:ng-show "add_restaurant.city.$invalid"} "City must be non-empty"] [:p "Enter the restaurant's city"]]] [:div.control-group {:ng-class "{error: add_restaurant.state.$invalid}"} [:label.control-label {:for "add_restaurant_state"} "State: "] [:div.controls [:select#add_restaurant_state {:ng-model "state" :name "state" :required ""} [:option {:value ""} "-- Select a State --"] [:option {:value "AL"} "Alabama"] [:option {:value "AK"} "Alaska"] [:option {:value "AZ"} "Arizona"] [:option {:value "AR"} "Arkansas"] [:option {:value "CA"} "California"] [:option {:value "CO"} "Colorado"] [:option {:value "CT"} "Connecticut"] [:option {:value "DE"} "Delaware"] [:option {:value "DC"} "District Of Columbia"] [:option {:value "FL"} "Florida"] [:option {:value "GA"} "Georgia"] [:option {:value "HI"} "Hawaii"] [:option {:value "ID"} "Idaho"] [:option {:value "IL"} "Illinois"] [:option {:value "IN"} "Indiana"] [:option {:value "IA"} "Iowa"] [:option {:value "KS"} "Kansas"] [:option {:value "KY"} "Kentucky"] [:option {:value "LA"} "Louisiana"] [:option {:value "ME"} "Maine"] [:option {:value "MD"} "Maryland"] [:option {:value "MA"} "Massachusetts"] [:option {:value "MI"} "Michigan"] [:option {:value "MN"} "Minnesota"] [:option {:value "MS"} "Mississippi"] [:option {:value "MO"} "Missouri"] [:option {:value "MT"} "Montana"] [:option {:value "NE"} "Nebraska"] [:option {:value "NV"} "Nevada"] [:option {:value "NH"} "New Hampshire"] [:option {:value "NJ"} "New Jersey"] [:option {:value "NM"} "New Mexico"] [:option {:value "NY"} "New York"] [:option {:value "NC"} "North Carolina"] [:option {:value "ND"} "North Dakota"] [:option {:value "OH"} "Ohio"] [:option {:value "OK"} "Oklahoma"] [:option {:value "OR"} "Oregon"] [:option {:value "PA"} "Pennsylvania"] [:option {:value "RI"} "Rhode Island"] [:option {:value "SC"} "South Carolina"] [:option {:value "SD"} "South Dakota"] [:option {:value "TN"} "Tennessee"] [:option {:value "TX"} "Texas"] [:option {:value "UT"} "Utah"] [:option {:value "VT"} "Vermont"] [:option {:value "VA"} "Virginia"] [:option {:value "WA"} "Washington"] [:option {:value "WV"} "West Virginia"] [:option {:value "WI"} "Wisconsin"] [:option {:value "WY"} "Wyoming"]] [:span.help-inline {:ng-show "add_restaurant.state.$invalid"} "You must choose a state."] [:p "Enter the restaurant's state"]]] [:div.control-group {:ng-class "{error: add_restaurant.zip.$invalid}"} [:label.control-label {:for "add_restaurant_zip"} "Zip: "] [:div.controls [:input#add_restaurant_zip.input-xlarge {:ng-model "zip" :type "text" :name "zip" :maxlength "5" :required "" :ng-pattern "/^\\d{5}$/"}] [:span.help-inline {:ng-show "add_restaurant.zip.$invalid"} "Zip must be non-empty and 5 digits"] [:p "Enter the restaurant's zip"]]] [:div.form-actions [:button.btn.btn-primary {:type "submit" :ng-disabled "isClean() || add_restaurant.$invalid"} "Save"] [:button#add_restaurant_reset.btn {:ng-click "reset()"} "Cancel"]]]]]]])) (defpage "/db/restaurants" [] (response/json (db/get-restaurants))) (defpage [:post "/db/restaurants"] {:keys [restaurant_name address city state zip]} (if-let [new-list (db/update-restaurant restaurant_name address city state zip)] (response/json new-list) (response/empty))) (defpage [:delete "/db/restaurants"] {:keys [restaurant_name]} (if-let [new-list (db/rem-restaurant restaurant_name)] (response/json new-list) (response/empty))) (defpage "/partials/examples" [] (html [:div.row [:div.span9 [:div#carousel.carousel.slide [:div.carousel-inner [:div.item [:img {:alt "PitchIt" :src (utils/add-context "/img/pitchit.png")}] [:div.carousel-caption [:h4 [:a {:href "http://brian-jesse.com/pitchit"} "PitchIt"]] [:p "An application developed for Illinois State University. PitchIt is an application that helps a class of future entrepreneurs develop their business plan."]]] [:div.item [:img {:alt "GoalCharge" :src (utils/add-context "/img/goalcharge.png")}] [:div.carousel-caption [:h4 [:a {:href "http://goalcharge.com"}"GoalCharge"]] [:p "GoalCharge was first concieved during a mobile application development competion. It has since been ported for use on desktop and mobile devices."]]] [:div.item [:img {:alt "Leah Walk" :src (utils/add-context "/img/leahwalk.png")}] [:div.carousel-caption [:h4 [:a {:href "http://leahwalk.com"} "Leah Walk"]] [:p "The Leah Memorial Walk site is an example of simple elegant design"]]]] [:a.carousel-control.left {:href "#carousel" :data-slide "prev"} "&lsaquo;"] [:a.carousel-control.right {:href "#carousel" :data-slide "next"} "&rsaquo;"] ]]] [:div.row [:div.span4 [:h4 "Front End Framework Knowledge"] [:ul [:li "Angular JS"] [:li "Twitter Bootstrap"] [:li "jQuery"]]] [:div.span4 [:h4 "Back End Development Platforms"] [:ul [:li "PHP - Codeigniter"] [:li "Java EE6 - Glassfish"] [:li "Clojure - Noir"] [:li "Python - Flask"]]] [:div.row [:div#bootstraplove.span8 [:hr] [:h3 "Twitter Bootstrap"] [:p "Bootstrap gives you the ability to rapidly develop nice looking websites in a shorter amount of time. With the default styles from Bootstrap you have sensible margins and padding on useful elements, nice layout for standard ui items, and decent typography. Utilizing the grid system makes laying out your page simple. Bootstrap's responsive template is simple to use and radically changes the way mobile sites are constructed."] [:p "Bootstrap also enforces standard practices when creating forms and laying out your page. Bootstrap is compatible with older and modern browsers, so you aren't at a disadvantage when offering backwards compatibility."]]]])) (defonce pic-order (atom [1 2 3 4])) (defpage [:post "/ws/picorder"] {:keys [order]} (response/json (reset! pic-order order))) (defpage "/ws/picorder" [] (response/json @pic-order)) (defpage "/partials/gallery" [] (html [:div.tabbable [:ul#gallery_tabs.nav.nav-tabs [:li.active [:a {:href "#gallery_tab_1" :data-toggle "tab"} "Gallery"]] [:li [:a {:href "#gallery_tab_2" :data-gtoggle "tab"} "Reorder"]]] [:div.tab-content [:div#gallery_tab_1.tab-pane.active [:div.row {} [:div.span2 {:ng-repeat "image in pics" :fancy-box-directive ""} [:a {:rel "group" :href (utils/add-context "/img/gallery/{{image}}.jpg")} [:img.img-rounded {:alt "" :ng-src (utils/add-context "/img/gallery/{{image}}_sm.jpg")}]]]]] [:div#gallery_tab_2.tab-pane [:ul.row {:sortable-directive ""} [:li.span2 {:ng-repeat "image in pics" :id "{{image}}"} [:img.img-rounded {:ng-src (utils/add-context "/img/gallery/{{image}}_sm.jpg")}]]] [:div.row [:div.span3] [:div.span3 [:a.btn {:ng-click "saveOrder()"} "Save Order"]]]]]]))
109944
(ns it354.views.index (:use [noir.core :only [defpage defpartial]] [hiccup.core :only [html]]) (:require [it354.views.layout :as layout] [it354.views.utils :as utils] [it354.models.db :as db] [noir.response :as response])) (defpage "/" [] (layout/layout "<NAME>" [:div.wrapper [:div.title.hidden-phone [:div.container [:div.row [:div.span2.hidden-phone [:img.img-polaroid {:src (utils/add-context "/img/me.jpg")}]] [:div.span10 [:div.row [:h1 "<NAME>"]] [:div.row [:a.btn.btn-primary.btn-large {:href "https://www.facebook.com/BJesse90"} [:i.icon-facebook-sign.icon-large] "View Facebook Profile"] [:a.btn.btn-primary.btn-large {:href "http://www.linkedin.com/pub/brian-jesse/57/769/136"} [:i.icon-linkedin-sign.icon-large] "View Linkedin Profile"]]]]]] [:div#main_content.content [:div.navbar.navbar-fixed-top.visible-phone [:div.navbar-inner [:div.container [:a.btn.btn-navbar {:data-toggle "collapse" :data-target ".nav-collapse"} [:span.icon-reorder]] [:a.brand {:href "#"} "<NAME>"] [:div.nav-collapse [:ul.nav [:li [:a {:href "http://www.linkedin.com/pub/brian-jesse/57/769/136"} [:i.icon-linkedin-sign.pull-right] "LinkedIn"]] [:li [:a {:href "https://www.facebook.com/BJesse90"} [:i.icon-facebook-sign.pull-right] "Facebook"]] [:li [:a {:href "#/home"} [:i.icon-chevron-right.pull-right] "Home"]] [:li [:a {:href "#/resume"} [:i.icon-chevron-right.pull-right] "Resume"]] [:li [:a {:href "#/links"} [:i.icon-chevron-right.pull-right] "Links"]] [:li [:a {:href "#/pipes"} [:i.icon-chevron-right.pull-right] "Pipes"]] [:li [:a {:href "#/restaurants"} [:i.icon-chevron-right.pull-right] "Restaurants"]] [:li [:a {:href "#/places"} [:i.icon-chevron-right.pull-right] "Places"]] [:li [:a {:href "#/examples"} [:i.icon-chevron-right.pull-right] "Examples"]] [:li [:a {:href "#/gallery"} [:i.icon-chevron-right.pull-right] "Gallery"]] [:li [:a {:href "#/videos"} [:i.icon-chevron-right.pull-right] "Videos"]]]]]]] [:div.container [:div.row [:div.span3.hidden-phone [:ul.nav.nav-list [:li [:a {:href "#/home" :class "{{homeLink}}"} [:i.icon-chevron-right] "Home"]] [:li [:a {:href "#/resume" :class "{{resumeLink}}"} [:i.icon-chevron-right] "Resume"]] [:li [:a {:href "#/links" :class "{{linksLink}}"} [:i.icon-chevron-right] "Links"]] [:li [:a {:href "#/pipes" :class "{{pipesLink}}"} [:i.icon-chevron-right] "Pipes"]] [:li [:a {:href "#/restaurants" :class "{{restaurantsLink}}"} [:i.icon-chevron-right] "Restaurants"]] [:li [:a {:href "#/places" :class "{{placesLink}}"} [:i.icon-chevron-right] "Places"]] [:li [:a {:href "#/examples" :class "{{examplesLink}}"} [:i.icon-chevron-right] "Examples"]] [:li [:a {:href "#/gallery" :class "{{galleryLink}}"} [:i.icon-chevron-right] "Gallery"]] [:li [:a {:href "#/videos" :class "{{videosLink}}"} [:i.icon-chevron-right] "Videos"]]]] [:div.span9 [:div.well {:ng-view ""}]]]]] [:div.push]] [:footer [:div.container [:h4 "&copy; <NAME> 2012"]]])) (defpage "/partials/home" [] (html (utils/comment-html "Facebook Badge START") [:a.fb-badge {:href "https://www.facebook.com/BJesse90" :target "_TOP" :title "<NAME>"} [:img.img-rounded {:src "https://www.facebook.com/badge.php?id=1463500045&bid=2846&key=<KEY>&format=png&z=1373594599" :style "border: 0px;"}]] (utils/comment-html "Facebook Badge END") [:h2 "About Me"] [:p "I am currently pursuing a bachelor's degreen in Computer Science at Illinois State University. I work for the department of Business Intelligence and Technology Solutions at ISU as a Java web programmer. I have experience working in tech support in a small business and an enterprise environment. Last spring I was selected as a finalist in the State Farm Mobile App Development competition for my social goal tracking app Goalcharge"] [:p [:a.btn {:href "#/videos"} "Check out the Goalcharge video &raquo;"]])) (defpage "/partials/resume" [] (html [:h2 "Resume"] [:hr] [:h3 "Objective"] [:table.table.table-bordered.table-striped [:tr [:td "To enhance my web development expertise, further my programming skills, and improve my general computer knowledge in a challenging, fast paced, and team-oriented environment."]]] [:h3 "Education"] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Illinois State University, "] "Normal IL (2010-Present)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Major:"]] [:td "Computer Science"]] [:tr [:td [:u "Curriculum:"]] [:td "Mathematics, technical and group skills, programming, and web development"]] [:tr [:td [:u "Involvement:"]] [:td "IT club; performed as webmaster for various clubs"]]]] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Illinois Valley Community College, "] "Oglesby IL (2008-2010)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Curriculum:"]] [:td "Programming, Electronic Theory, Chemistry, Calculus"]] [:tr [:td [:u "Involvement:"]] [:td "Association of Information Technology Professionals (AITP), Psychology Club, theater, political activism, and civic organizations"]]]] [:h3 "Qualifications"] [:table.table.table-bordered.table-striped.table-hover [:tr [:td "Two years of Java experience including use of JPA, JSF, and restful web services"]] [:tr [:td "Finalist in a mobile app development contest"]] [:tr [:td "Website design skills using HTML 5 and CSS 3 for desktops and mobile devices"]] [:tr [:td "Apache, Glassfish, PHP, and JavaScript development skills"]] [:tr [:td "Unix server administration on Debian and Red Hat installations"]] [:tr [:td "C++ proficiency and extensive knowledge of data structures and algorithms"]] [:tr [:td "Experience working with collaborative build tools such as Maven, Subversion, and Git"]] [:tr [:td "Talents with graphic arts and video editing utilizing Adobe suites"]]] [:h3 "Experience"] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Business Intelligence and Technology Solutions - Illinois State University, "] "Normal IL"]] [:tr [:th {:colspan "2"} "Web Team Intern (Aug 2011-Present)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Duties:"]] [:td "Java web app programming and rewriting, CMS integration with website"]] [:tr [:td [:u "Skills Gained:"]] [:td "Project management and development in a highly skilled environment, multiple development environments"]]]] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Enterprise Systems Support - Illinois State University, "] "Normal IL"]] [:tr [:th {:colspan "2"} "Senior Technician (Mar 2011 - Aug 2011)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Duties:"]] [:td "IT support, secure computer deployment, mobile development, and supervising techs"]] [:tr [:td [:u "Skills Gained:"]] [:td "Managing multiple open tickets, and solving customer’s issues"]]]] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Computer Spa, "] "Ottawa IL"]] [:tr [:th {:colspan "2"} "(Jun 2009 - May 2010)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Duties:"]] [:td "Computer repair and maintenance, maintaining Windows and Novell networks"]] [:tr [:td [:u "Skills Gained:"]] [:td "Personal interaction with business clients"]]]] [:a.btn.btn-primary.btn-large {:href "http://www.linkedin.com/pub/brian-jesse/57/769/136"} [:i.icon-linkedin-sign.icon-large] "View Linkedin Profile"])) (defpage "/partials/links" [] (html [:h2 "My Favorite Links"] [:div#links.accordion [:div.accordion-group [:div.accordion-heading [:a.accordion-toggle {:data-toggle "collapse" :data-parent "#links" :href "#links1"} "Blogs"]] [:div#links1.accordion-body.collapse.in [:div.accordion-inner [:ul [:li [:a {:href "//theverge.com" :target "_blank"} "The Verge"]] [:li [:a {:href "//xkcd.com/" :target "_blank"} "XKCD"]] [:li [:a {:href "//blog.hash-of-codes.com" :target "_blank"} "Hash of Codes"]]]]]] [:div.accordion-group [:div.accordion-heading [:a.accordion-toggle {:data-toggle "collapse" :data-parent "#links" :href "#links2"} "Social Media"]] [:div#links2.accordion-body.collapse [:div.accordion-inner [:ul [:li [:a {:href "//reddit.com" :target "_blank"} "Reddit"]] [:li [:a {:href "//coderwall.com" :target "_blank"} "Coderwall"]] [:li [:a {:href "//news.ycombinator.org" :target "_blank"} "Hacker News"]]]]]] [:div.accordion-group [:div.accordion-heading [:a.accordion-toggle {:data-toggle "collapse" :data-parent "#links" :href "#links3"} "Programming"]] [:div#links3.accordion-body.collapse [:div.accordion-inner [:ul [:li [:a {:href "//bitbucket.org" :target "_blank"} "Bitbucket"]] [:li [:a {:href "//webnoir.org" :target "_blank"} "Noir"]] [:li [:a {:href "//twitter.github.com" :target "_blank"} "Twitter Bootstrap"]]]]]]])) (defpage "/partials/pipes" [] (html [:h2 "Yahoo Pipes Example"] [:div#pipe] [:p [:a.btn {:href "http://pipes.yahoo.com/pipes/pipe.info?_id=0857e00eb73ac6bc8c974b60f6c30e96"} "View Pipe on Yahoo &raquo;"]])) (defpage "/partials/videos" [] (html [:h2 "My Videos"] [:hr] [:h3 "Goalcharge"] [:p "An app I created for the Mobile App contest last semester"] [:iframe.visible-desktop {:width "640" :height "480" :src "//www.youtube.com/embed/v3RTXbi7g4o?rel=0" :frameborder "0" :allowfullscreen ""}] [:iframe.visible-tablet {:width "480" :height "360" :src "//www.youtube.com/embed/v3RTXbi7g4o?rel=0" :frameborder "0" :allowfullscreen ""}] [:a.btn.visible-phone {:href "http://youtu.be/v3RTXbi7g4o"} "View Video On Youtube"])) (defpage "/partials/places" [] (html [:h2 "Places"] [:ul#places_tabs.nav.nav-tabs [:li.active [:a {:href "#" :ng-click "showNormal()"} "Normal"]] [:li [:a {:href "#" :ng-click "showChicago()"} "Chicago"]]] [:div#map_canvas])) (defpage "/partials/places/normal" [] (html [:div.info-window [:h4 "Normal, IL"] [:p "I was born here, most of my family is here, and I don't get out of here often. I do love this town though."]])) (defpage "/partials/places/chicago" [] (html [:div.info-window [:h4 "Chicago, IL"] [:p "I haven't spent too much time here, but I do go on occasion for conferences and professional gatherings. I'll probably work downtown some day."]])) (defpage "/partials/restaurants" [] (html [:h2 "Restaurants"] [:div.tabbable [:ul#restaurant_tabs.nav.nav-tabs [:li.active [:a {:href "#restaurant_tab_1" :data-toggle "tab"} "Restaurant List"]] [:li [:a {:href "#restaurant_tab_2" :data-gtoggle "tab"} "{{{true:'Edit',false:'Add'}[edit]}} Restaurant"]]] [:div.tab-content [:div#restaurant_tab_1.tab-pane.active [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th [:a {:ng-click "column='restaurant_name';reverse=false" :ng-show "column!='restaurant_name'"} "Name"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='restaurant_name'"} "Name"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='restaurant_name'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th [:a {:ng-click "column='address';reverse=false" :ng-show "column!='address'"} "Address"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='address'"} "Address"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='address'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th [:a {:ng-click "column='city';reverse=false" :ng-show "column!='city'"} "City"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='city'"} "City"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='city'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th [:a {:ng-click "column='state';reverse=false" :ng-show "column!='state'"} "St"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='state'"} "St"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='state'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th [:a {:ng-click "column='zip';reverse=false" :ng-show "column!='zip'"} "Zip"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='zip'"} "Zip"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='zip'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th "Edit"] [:th "Delete"]] [:colgroup [:col.span2] [:col.span2] [:col.span2] [:col.span1] [:col.span1] [:col.span1] [:col.span1]]] [:tbody {:ng-repeat "restaurant in restaurantList | orderBy:column:reverse"} [:tr [:td "{{restaurant.restaurant_name}}"] [:td "{{restaurant.address}}"] [:td "{{restaurant.city}}"] [:td "{{restaurant.state}}"] [:td "{{restaurant.zip}}"] [:td.action-icon [:a {:ng-click (str "update(restaurant.restaurant_name," "restaurant.address," "restaurant.city," "restaurant.state," "restaurant.zip)")} [:i.icon-edit]]] [:td.action-icon [:a {:ng-click "$parent.confirm=$index" :ng-show "$parent.confirm!=$index"} [:i.icon-trash]] [:a {:ng-click "$parent.confirm=-1" :ng-show "$parent.confirm==$index"} [:i.icon-ban-circle]]]] [:tr {:ng-show "$parent.confirm==$index"} [:td.confirm-delete {:colspan "7"} [:a.btn.btn-danger {:ng-click "remove(restaurant.restaurant_name);$parent.confirm=-1"} "Confirm Delete"]]]]]] [:div#restaurant_tab_2.tab-pane [:div#add_restaurant_placeholder] [:form#add_restaurant.form-horizontal {:name "add_restaurant" :ng-submit "save()"} [:fieldset [:div.control-group {:ng-class "{error: add_restaurant.restaurant_name.$invalid}"} [:label.control-label {:for "add_restaurant_name"} "Name: "] [:div.controls [:input#add_restaurant_name.input-xlarge {:ng-model "restaurant_name" :type "text" :name "restaurant_name" :maxlength "35" :required ""}] [:span.help-inline {:ng-show "add_restaurant.restaurant_name.$invalid"} "Name must be non-empty"] [:p "Enter the restaurant name"]]] [:div.control-group {:ng-class "{error: add_restaurant.address.$invalid}"} [:label.control-label {:for "add_restaurant_address"} "Address: "] [:div.controls [:input#add_restaurant_address.input-xlarge {:ng-model "address" :type "text" :name "address" :maxlength "40" :required ""}] [:span.help-inline {:ng-show "add_restaurant.address.$invalid"} "Address must be non-empty"] [:p "Enter the restaurant's street address"]]] [:div.control-group {:ng-class "{error: add_restaurant.city.$invalid}"} [:label.control-label {:for "add_restaurant_city"} "City: "] [:div.controls [:input#add_restaurant_city.input-xlarge {:ng-model "city" :type "text" :name "city" :maxlength "30" :required ""}] [:span.help-inline {:ng-show "add_restaurant.city.$invalid"} "City must be non-empty"] [:p "Enter the restaurant's city"]]] [:div.control-group {:ng-class "{error: add_restaurant.state.$invalid}"} [:label.control-label {:for "add_restaurant_state"} "State: "] [:div.controls [:select#add_restaurant_state {:ng-model "state" :name "state" :required ""} [:option {:value ""} "-- Select a State --"] [:option {:value "AL"} "Alabama"] [:option {:value "AK"} "Alaska"] [:option {:value "AZ"} "Arizona"] [:option {:value "AR"} "Arkansas"] [:option {:value "CA"} "California"] [:option {:value "CO"} "Colorado"] [:option {:value "CT"} "Connecticut"] [:option {:value "DE"} "Delaware"] [:option {:value "DC"} "District Of Columbia"] [:option {:value "FL"} "Florida"] [:option {:value "GA"} "Georgia"] [:option {:value "HI"} "Hawaii"] [:option {:value "ID"} "Idaho"] [:option {:value "IL"} "Illinois"] [:option {:value "IN"} "Indiana"] [:option {:value "IA"} "Iowa"] [:option {:value "KS"} "Kansas"] [:option {:value "KY"} "Kentucky"] [:option {:value "LA"} "Louisiana"] [:option {:value "ME"} "Maine"] [:option {:value "MD"} "Maryland"] [:option {:value "MA"} "Massachusetts"] [:option {:value "MI"} "Michigan"] [:option {:value "MN"} "Minnesota"] [:option {:value "MS"} "Mississippi"] [:option {:value "MO"} "Missouri"] [:option {:value "MT"} "Montana"] [:option {:value "NE"} "Nebraska"] [:option {:value "NV"} "Nevada"] [:option {:value "NH"} "New Hampshire"] [:option {:value "NJ"} "New Jersey"] [:option {:value "NM"} "New Mexico"] [:option {:value "NY"} "New York"] [:option {:value "NC"} "North Carolina"] [:option {:value "ND"} "North Dakota"] [:option {:value "OH"} "Ohio"] [:option {:value "OK"} "Oklahoma"] [:option {:value "OR"} "Oregon"] [:option {:value "PA"} "Pennsylvania"] [:option {:value "RI"} "Rhode Island"] [:option {:value "SC"} "South Carolina"] [:option {:value "SD"} "South Dakota"] [:option {:value "TN"} "Tennessee"] [:option {:value "TX"} "Texas"] [:option {:value "UT"} "Utah"] [:option {:value "VT"} "Vermont"] [:option {:value "VA"} "Virginia"] [:option {:value "WA"} "Washington"] [:option {:value "WV"} "West Virginia"] [:option {:value "WI"} "Wisconsin"] [:option {:value "WY"} "Wyoming"]] [:span.help-inline {:ng-show "add_restaurant.state.$invalid"} "You must choose a state."] [:p "Enter the restaurant's state"]]] [:div.control-group {:ng-class "{error: add_restaurant.zip.$invalid}"} [:label.control-label {:for "add_restaurant_zip"} "Zip: "] [:div.controls [:input#add_restaurant_zip.input-xlarge {:ng-model "zip" :type "text" :name "zip" :maxlength "5" :required "" :ng-pattern "/^\\d{5}$/"}] [:span.help-inline {:ng-show "add_restaurant.zip.$invalid"} "Zip must be non-empty and 5 digits"] [:p "Enter the restaurant's zip"]]] [:div.form-actions [:button.btn.btn-primary {:type "submit" :ng-disabled "isClean() || add_restaurant.$invalid"} "Save"] [:button#add_restaurant_reset.btn {:ng-click "reset()"} "Cancel"]]]]]]])) (defpage "/db/restaurants" [] (response/json (db/get-restaurants))) (defpage [:post "/db/restaurants"] {:keys [restaurant_name address city state zip]} (if-let [new-list (db/update-restaurant restaurant_name address city state zip)] (response/json new-list) (response/empty))) (defpage [:delete "/db/restaurants"] {:keys [restaurant_name]} (if-let [new-list (db/rem-restaurant restaurant_name)] (response/json new-list) (response/empty))) (defpage "/partials/examples" [] (html [:div.row [:div.span9 [:div#carousel.carousel.slide [:div.carousel-inner [:div.item [:img {:alt "PitchIt" :src (utils/add-context "/img/pitchit.png")}] [:div.carousel-caption [:h4 [:a {:href "http://brian-jesse.com/pitchit"} "PitchIt"]] [:p "An application developed for Illinois State University. PitchIt is an application that helps a class of future entrepreneurs develop their business plan."]]] [:div.item [:img {:alt "GoalCharge" :src (utils/add-context "/img/goalcharge.png")}] [:div.carousel-caption [:h4 [:a {:href "http://goalcharge.com"}"GoalCharge"]] [:p "GoalCharge was first concieved during a mobile application development competion. It has since been ported for use on desktop and mobile devices."]]] [:div.item [:img {:alt "Leah Walk" :src (utils/add-context "/img/leahwalk.png")}] [:div.carousel-caption [:h4 [:a {:href "http://leahwalk.com"} "Leah Walk"]] [:p "The Leah Memorial Walk site is an example of simple elegant design"]]]] [:a.carousel-control.left {:href "#carousel" :data-slide "prev"} "&lsaquo;"] [:a.carousel-control.right {:href "#carousel" :data-slide "next"} "&rsaquo;"] ]]] [:div.row [:div.span4 [:h4 "Front End Framework Knowledge"] [:ul [:li "Angular JS"] [:li "Twitter Bootstrap"] [:li "jQuery"]]] [:div.span4 [:h4 "Back End Development Platforms"] [:ul [:li "PHP - Codeigniter"] [:li "Java EE6 - Glassfish"] [:li "Clojure - Noir"] [:li "Python - Flask"]]] [:div.row [:div#bootstraplove.span8 [:hr] [:h3 "Twitter Bootstrap"] [:p "Bootstrap gives you the ability to rapidly develop nice looking websites in a shorter amount of time. With the default styles from Bootstrap you have sensible margins and padding on useful elements, nice layout for standard ui items, and decent typography. Utilizing the grid system makes laying out your page simple. Bootstrap's responsive template is simple to use and radically changes the way mobile sites are constructed."] [:p "Bootstrap also enforces standard practices when creating forms and laying out your page. Bootstrap is compatible with older and modern browsers, so you aren't at a disadvantage when offering backwards compatibility."]]]])) (defonce pic-order (atom [1 2 3 4])) (defpage [:post "/ws/picorder"] {:keys [order]} (response/json (reset! pic-order order))) (defpage "/ws/picorder" [] (response/json @pic-order)) (defpage "/partials/gallery" [] (html [:div.tabbable [:ul#gallery_tabs.nav.nav-tabs [:li.active [:a {:href "#gallery_tab_1" :data-toggle "tab"} "Gallery"]] [:li [:a {:href "#gallery_tab_2" :data-gtoggle "tab"} "Reorder"]]] [:div.tab-content [:div#gallery_tab_1.tab-pane.active [:div.row {} [:div.span2 {:ng-repeat "image in pics" :fancy-box-directive ""} [:a {:rel "group" :href (utils/add-context "/img/gallery/{{image}}.jpg")} [:img.img-rounded {:alt "" :ng-src (utils/add-context "/img/gallery/{{image}}_sm.jpg")}]]]]] [:div#gallery_tab_2.tab-pane [:ul.row {:sortable-directive ""} [:li.span2 {:ng-repeat "image in pics" :id "{{image}}"} [:img.img-rounded {:ng-src (utils/add-context "/img/gallery/{{image}}_sm.jpg")}]]] [:div.row [:div.span3] [:div.span3 [:a.btn {:ng-click "saveOrder()"} "Save Order"]]]]]]))
true
(ns it354.views.index (:use [noir.core :only [defpage defpartial]] [hiccup.core :only [html]]) (:require [it354.views.layout :as layout] [it354.views.utils :as utils] [it354.models.db :as db] [noir.response :as response])) (defpage "/" [] (layout/layout "PI:NAME:<NAME>END_PI" [:div.wrapper [:div.title.hidden-phone [:div.container [:div.row [:div.span2.hidden-phone [:img.img-polaroid {:src (utils/add-context "/img/me.jpg")}]] [:div.span10 [:div.row [:h1 "PI:NAME:<NAME>END_PI"]] [:div.row [:a.btn.btn-primary.btn-large {:href "https://www.facebook.com/BJesse90"} [:i.icon-facebook-sign.icon-large] "View Facebook Profile"] [:a.btn.btn-primary.btn-large {:href "http://www.linkedin.com/pub/brian-jesse/57/769/136"} [:i.icon-linkedin-sign.icon-large] "View Linkedin Profile"]]]]]] [:div#main_content.content [:div.navbar.navbar-fixed-top.visible-phone [:div.navbar-inner [:div.container [:a.btn.btn-navbar {:data-toggle "collapse" :data-target ".nav-collapse"} [:span.icon-reorder]] [:a.brand {:href "#"} "PI:NAME:<NAME>END_PI"] [:div.nav-collapse [:ul.nav [:li [:a {:href "http://www.linkedin.com/pub/brian-jesse/57/769/136"} [:i.icon-linkedin-sign.pull-right] "LinkedIn"]] [:li [:a {:href "https://www.facebook.com/BJesse90"} [:i.icon-facebook-sign.pull-right] "Facebook"]] [:li [:a {:href "#/home"} [:i.icon-chevron-right.pull-right] "Home"]] [:li [:a {:href "#/resume"} [:i.icon-chevron-right.pull-right] "Resume"]] [:li [:a {:href "#/links"} [:i.icon-chevron-right.pull-right] "Links"]] [:li [:a {:href "#/pipes"} [:i.icon-chevron-right.pull-right] "Pipes"]] [:li [:a {:href "#/restaurants"} [:i.icon-chevron-right.pull-right] "Restaurants"]] [:li [:a {:href "#/places"} [:i.icon-chevron-right.pull-right] "Places"]] [:li [:a {:href "#/examples"} [:i.icon-chevron-right.pull-right] "Examples"]] [:li [:a {:href "#/gallery"} [:i.icon-chevron-right.pull-right] "Gallery"]] [:li [:a {:href "#/videos"} [:i.icon-chevron-right.pull-right] "Videos"]]]]]]] [:div.container [:div.row [:div.span3.hidden-phone [:ul.nav.nav-list [:li [:a {:href "#/home" :class "{{homeLink}}"} [:i.icon-chevron-right] "Home"]] [:li [:a {:href "#/resume" :class "{{resumeLink}}"} [:i.icon-chevron-right] "Resume"]] [:li [:a {:href "#/links" :class "{{linksLink}}"} [:i.icon-chevron-right] "Links"]] [:li [:a {:href "#/pipes" :class "{{pipesLink}}"} [:i.icon-chevron-right] "Pipes"]] [:li [:a {:href "#/restaurants" :class "{{restaurantsLink}}"} [:i.icon-chevron-right] "Restaurants"]] [:li [:a {:href "#/places" :class "{{placesLink}}"} [:i.icon-chevron-right] "Places"]] [:li [:a {:href "#/examples" :class "{{examplesLink}}"} [:i.icon-chevron-right] "Examples"]] [:li [:a {:href "#/gallery" :class "{{galleryLink}}"} [:i.icon-chevron-right] "Gallery"]] [:li [:a {:href "#/videos" :class "{{videosLink}}"} [:i.icon-chevron-right] "Videos"]]]] [:div.span9 [:div.well {:ng-view ""}]]]]] [:div.push]] [:footer [:div.container [:h4 "&copy; PI:NAME:<NAME>END_PI 2012"]]])) (defpage "/partials/home" [] (html (utils/comment-html "Facebook Badge START") [:a.fb-badge {:href "https://www.facebook.com/BJesse90" :target "_TOP" :title "PI:NAME:<NAME>END_PI"} [:img.img-rounded {:src "https://www.facebook.com/badge.php?id=1463500045&bid=2846&key=PI:KEY:<KEY>END_PI&format=png&z=1373594599" :style "border: 0px;"}]] (utils/comment-html "Facebook Badge END") [:h2 "About Me"] [:p "I am currently pursuing a bachelor's degreen in Computer Science at Illinois State University. I work for the department of Business Intelligence and Technology Solutions at ISU as a Java web programmer. I have experience working in tech support in a small business and an enterprise environment. Last spring I was selected as a finalist in the State Farm Mobile App Development competition for my social goal tracking app Goalcharge"] [:p [:a.btn {:href "#/videos"} "Check out the Goalcharge video &raquo;"]])) (defpage "/partials/resume" [] (html [:h2 "Resume"] [:hr] [:h3 "Objective"] [:table.table.table-bordered.table-striped [:tr [:td "To enhance my web development expertise, further my programming skills, and improve my general computer knowledge in a challenging, fast paced, and team-oriented environment."]]] [:h3 "Education"] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Illinois State University, "] "Normal IL (2010-Present)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Major:"]] [:td "Computer Science"]] [:tr [:td [:u "Curriculum:"]] [:td "Mathematics, technical and group skills, programming, and web development"]] [:tr [:td [:u "Involvement:"]] [:td "IT club; performed as webmaster for various clubs"]]]] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Illinois Valley Community College, "] "Oglesby IL (2008-2010)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Curriculum:"]] [:td "Programming, Electronic Theory, Chemistry, Calculus"]] [:tr [:td [:u "Involvement:"]] [:td "Association of Information Technology Professionals (AITP), Psychology Club, theater, political activism, and civic organizations"]]]] [:h3 "Qualifications"] [:table.table.table-bordered.table-striped.table-hover [:tr [:td "Two years of Java experience including use of JPA, JSF, and restful web services"]] [:tr [:td "Finalist in a mobile app development contest"]] [:tr [:td "Website design skills using HTML 5 and CSS 3 for desktops and mobile devices"]] [:tr [:td "Apache, Glassfish, PHP, and JavaScript development skills"]] [:tr [:td "Unix server administration on Debian and Red Hat installations"]] [:tr [:td "C++ proficiency and extensive knowledge of data structures and algorithms"]] [:tr [:td "Experience working with collaborative build tools such as Maven, Subversion, and Git"]] [:tr [:td "Talents with graphic arts and video editing utilizing Adobe suites"]]] [:h3 "Experience"] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Business Intelligence and Technology Solutions - Illinois State University, "] "Normal IL"]] [:tr [:th {:colspan "2"} "Web Team Intern (Aug 2011-Present)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Duties:"]] [:td "Java web app programming and rewriting, CMS integration with website"]] [:tr [:td [:u "Skills Gained:"]] [:td "Project management and development in a highly skilled environment, multiple development environments"]]]] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Enterprise Systems Support - Illinois State University, "] "Normal IL"]] [:tr [:th {:colspan "2"} "Senior Technician (Mar 2011 - Aug 2011)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Duties:"]] [:td "IT support, secure computer deployment, mobile development, and supervising techs"]] [:tr [:td [:u "Skills Gained:"]] [:td "Managing multiple open tickets, and solving customer’s issues"]]]] [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th {:colspan "2"} [:strong "Computer Spa, "] "Ottawa IL"]] [:tr [:th {:colspan "2"} "(Jun 2009 - May 2010)"]]] [:colgroup [:col.span2] [:col.span8]] [:tbody [:tr [:td [:u "Duties:"]] [:td "Computer repair and maintenance, maintaining Windows and Novell networks"]] [:tr [:td [:u "Skills Gained:"]] [:td "Personal interaction with business clients"]]]] [:a.btn.btn-primary.btn-large {:href "http://www.linkedin.com/pub/brian-jesse/57/769/136"} [:i.icon-linkedin-sign.icon-large] "View Linkedin Profile"])) (defpage "/partials/links" [] (html [:h2 "My Favorite Links"] [:div#links.accordion [:div.accordion-group [:div.accordion-heading [:a.accordion-toggle {:data-toggle "collapse" :data-parent "#links" :href "#links1"} "Blogs"]] [:div#links1.accordion-body.collapse.in [:div.accordion-inner [:ul [:li [:a {:href "//theverge.com" :target "_blank"} "The Verge"]] [:li [:a {:href "//xkcd.com/" :target "_blank"} "XKCD"]] [:li [:a {:href "//blog.hash-of-codes.com" :target "_blank"} "Hash of Codes"]]]]]] [:div.accordion-group [:div.accordion-heading [:a.accordion-toggle {:data-toggle "collapse" :data-parent "#links" :href "#links2"} "Social Media"]] [:div#links2.accordion-body.collapse [:div.accordion-inner [:ul [:li [:a {:href "//reddit.com" :target "_blank"} "Reddit"]] [:li [:a {:href "//coderwall.com" :target "_blank"} "Coderwall"]] [:li [:a {:href "//news.ycombinator.org" :target "_blank"} "Hacker News"]]]]]] [:div.accordion-group [:div.accordion-heading [:a.accordion-toggle {:data-toggle "collapse" :data-parent "#links" :href "#links3"} "Programming"]] [:div#links3.accordion-body.collapse [:div.accordion-inner [:ul [:li [:a {:href "//bitbucket.org" :target "_blank"} "Bitbucket"]] [:li [:a {:href "//webnoir.org" :target "_blank"} "Noir"]] [:li [:a {:href "//twitter.github.com" :target "_blank"} "Twitter Bootstrap"]]]]]]])) (defpage "/partials/pipes" [] (html [:h2 "Yahoo Pipes Example"] [:div#pipe] [:p [:a.btn {:href "http://pipes.yahoo.com/pipes/pipe.info?_id=0857e00eb73ac6bc8c974b60f6c30e96"} "View Pipe on Yahoo &raquo;"]])) (defpage "/partials/videos" [] (html [:h2 "My Videos"] [:hr] [:h3 "Goalcharge"] [:p "An app I created for the Mobile App contest last semester"] [:iframe.visible-desktop {:width "640" :height "480" :src "//www.youtube.com/embed/v3RTXbi7g4o?rel=0" :frameborder "0" :allowfullscreen ""}] [:iframe.visible-tablet {:width "480" :height "360" :src "//www.youtube.com/embed/v3RTXbi7g4o?rel=0" :frameborder "0" :allowfullscreen ""}] [:a.btn.visible-phone {:href "http://youtu.be/v3RTXbi7g4o"} "View Video On Youtube"])) (defpage "/partials/places" [] (html [:h2 "Places"] [:ul#places_tabs.nav.nav-tabs [:li.active [:a {:href "#" :ng-click "showNormal()"} "Normal"]] [:li [:a {:href "#" :ng-click "showChicago()"} "Chicago"]]] [:div#map_canvas])) (defpage "/partials/places/normal" [] (html [:div.info-window [:h4 "Normal, IL"] [:p "I was born here, most of my family is here, and I don't get out of here often. I do love this town though."]])) (defpage "/partials/places/chicago" [] (html [:div.info-window [:h4 "Chicago, IL"] [:p "I haven't spent too much time here, but I do go on occasion for conferences and professional gatherings. I'll probably work downtown some day."]])) (defpage "/partials/restaurants" [] (html [:h2 "Restaurants"] [:div.tabbable [:ul#restaurant_tabs.nav.nav-tabs [:li.active [:a {:href "#restaurant_tab_1" :data-toggle "tab"} "Restaurant List"]] [:li [:a {:href "#restaurant_tab_2" :data-gtoggle "tab"} "{{{true:'Edit',false:'Add'}[edit]}} Restaurant"]]] [:div.tab-content [:div#restaurant_tab_1.tab-pane.active [:table.table.table-bordered.table-striped.table-hover [:thead [:tr [:th [:a {:ng-click "column='restaurant_name';reverse=false" :ng-show "column!='restaurant_name'"} "Name"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='restaurant_name'"} "Name"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='restaurant_name'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th [:a {:ng-click "column='address';reverse=false" :ng-show "column!='address'"} "Address"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='address'"} "Address"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='address'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th [:a {:ng-click "column='city';reverse=false" :ng-show "column!='city'"} "City"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='city'"} "City"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='city'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th [:a {:ng-click "column='state';reverse=false" :ng-show "column!='state'"} "St"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='state'"} "St"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='state'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th [:a {:ng-click "column='zip';reverse=false" :ng-show "column!='zip'"} "Zip"] [:a {:ng-click "reverse=!reverse" :ng-show "column=='zip'"} "Zip"] [:a.reverse-icon {:ng-click "reverse=!reverse"} [:i {:ng-show "column=='zip'" :ng-class "{true:'icon-sort-up',false:'icon-sort-down'}[reverse]"}]]] [:th "Edit"] [:th "Delete"]] [:colgroup [:col.span2] [:col.span2] [:col.span2] [:col.span1] [:col.span1] [:col.span1] [:col.span1]]] [:tbody {:ng-repeat "restaurant in restaurantList | orderBy:column:reverse"} [:tr [:td "{{restaurant.restaurant_name}}"] [:td "{{restaurant.address}}"] [:td "{{restaurant.city}}"] [:td "{{restaurant.state}}"] [:td "{{restaurant.zip}}"] [:td.action-icon [:a {:ng-click (str "update(restaurant.restaurant_name," "restaurant.address," "restaurant.city," "restaurant.state," "restaurant.zip)")} [:i.icon-edit]]] [:td.action-icon [:a {:ng-click "$parent.confirm=$index" :ng-show "$parent.confirm!=$index"} [:i.icon-trash]] [:a {:ng-click "$parent.confirm=-1" :ng-show "$parent.confirm==$index"} [:i.icon-ban-circle]]]] [:tr {:ng-show "$parent.confirm==$index"} [:td.confirm-delete {:colspan "7"} [:a.btn.btn-danger {:ng-click "remove(restaurant.restaurant_name);$parent.confirm=-1"} "Confirm Delete"]]]]]] [:div#restaurant_tab_2.tab-pane [:div#add_restaurant_placeholder] [:form#add_restaurant.form-horizontal {:name "add_restaurant" :ng-submit "save()"} [:fieldset [:div.control-group {:ng-class "{error: add_restaurant.restaurant_name.$invalid}"} [:label.control-label {:for "add_restaurant_name"} "Name: "] [:div.controls [:input#add_restaurant_name.input-xlarge {:ng-model "restaurant_name" :type "text" :name "restaurant_name" :maxlength "35" :required ""}] [:span.help-inline {:ng-show "add_restaurant.restaurant_name.$invalid"} "Name must be non-empty"] [:p "Enter the restaurant name"]]] [:div.control-group {:ng-class "{error: add_restaurant.address.$invalid}"} [:label.control-label {:for "add_restaurant_address"} "Address: "] [:div.controls [:input#add_restaurant_address.input-xlarge {:ng-model "address" :type "text" :name "address" :maxlength "40" :required ""}] [:span.help-inline {:ng-show "add_restaurant.address.$invalid"} "Address must be non-empty"] [:p "Enter the restaurant's street address"]]] [:div.control-group {:ng-class "{error: add_restaurant.city.$invalid}"} [:label.control-label {:for "add_restaurant_city"} "City: "] [:div.controls [:input#add_restaurant_city.input-xlarge {:ng-model "city" :type "text" :name "city" :maxlength "30" :required ""}] [:span.help-inline {:ng-show "add_restaurant.city.$invalid"} "City must be non-empty"] [:p "Enter the restaurant's city"]]] [:div.control-group {:ng-class "{error: add_restaurant.state.$invalid}"} [:label.control-label {:for "add_restaurant_state"} "State: "] [:div.controls [:select#add_restaurant_state {:ng-model "state" :name "state" :required ""} [:option {:value ""} "-- Select a State --"] [:option {:value "AL"} "Alabama"] [:option {:value "AK"} "Alaska"] [:option {:value "AZ"} "Arizona"] [:option {:value "AR"} "Arkansas"] [:option {:value "CA"} "California"] [:option {:value "CO"} "Colorado"] [:option {:value "CT"} "Connecticut"] [:option {:value "DE"} "Delaware"] [:option {:value "DC"} "District Of Columbia"] [:option {:value "FL"} "Florida"] [:option {:value "GA"} "Georgia"] [:option {:value "HI"} "Hawaii"] [:option {:value "ID"} "Idaho"] [:option {:value "IL"} "Illinois"] [:option {:value "IN"} "Indiana"] [:option {:value "IA"} "Iowa"] [:option {:value "KS"} "Kansas"] [:option {:value "KY"} "Kentucky"] [:option {:value "LA"} "Louisiana"] [:option {:value "ME"} "Maine"] [:option {:value "MD"} "Maryland"] [:option {:value "MA"} "Massachusetts"] [:option {:value "MI"} "Michigan"] [:option {:value "MN"} "Minnesota"] [:option {:value "MS"} "Mississippi"] [:option {:value "MO"} "Missouri"] [:option {:value "MT"} "Montana"] [:option {:value "NE"} "Nebraska"] [:option {:value "NV"} "Nevada"] [:option {:value "NH"} "New Hampshire"] [:option {:value "NJ"} "New Jersey"] [:option {:value "NM"} "New Mexico"] [:option {:value "NY"} "New York"] [:option {:value "NC"} "North Carolina"] [:option {:value "ND"} "North Dakota"] [:option {:value "OH"} "Ohio"] [:option {:value "OK"} "Oklahoma"] [:option {:value "OR"} "Oregon"] [:option {:value "PA"} "Pennsylvania"] [:option {:value "RI"} "Rhode Island"] [:option {:value "SC"} "South Carolina"] [:option {:value "SD"} "South Dakota"] [:option {:value "TN"} "Tennessee"] [:option {:value "TX"} "Texas"] [:option {:value "UT"} "Utah"] [:option {:value "VT"} "Vermont"] [:option {:value "VA"} "Virginia"] [:option {:value "WA"} "Washington"] [:option {:value "WV"} "West Virginia"] [:option {:value "WI"} "Wisconsin"] [:option {:value "WY"} "Wyoming"]] [:span.help-inline {:ng-show "add_restaurant.state.$invalid"} "You must choose a state."] [:p "Enter the restaurant's state"]]] [:div.control-group {:ng-class "{error: add_restaurant.zip.$invalid}"} [:label.control-label {:for "add_restaurant_zip"} "Zip: "] [:div.controls [:input#add_restaurant_zip.input-xlarge {:ng-model "zip" :type "text" :name "zip" :maxlength "5" :required "" :ng-pattern "/^\\d{5}$/"}] [:span.help-inline {:ng-show "add_restaurant.zip.$invalid"} "Zip must be non-empty and 5 digits"] [:p "Enter the restaurant's zip"]]] [:div.form-actions [:button.btn.btn-primary {:type "submit" :ng-disabled "isClean() || add_restaurant.$invalid"} "Save"] [:button#add_restaurant_reset.btn {:ng-click "reset()"} "Cancel"]]]]]]])) (defpage "/db/restaurants" [] (response/json (db/get-restaurants))) (defpage [:post "/db/restaurants"] {:keys [restaurant_name address city state zip]} (if-let [new-list (db/update-restaurant restaurant_name address city state zip)] (response/json new-list) (response/empty))) (defpage [:delete "/db/restaurants"] {:keys [restaurant_name]} (if-let [new-list (db/rem-restaurant restaurant_name)] (response/json new-list) (response/empty))) (defpage "/partials/examples" [] (html [:div.row [:div.span9 [:div#carousel.carousel.slide [:div.carousel-inner [:div.item [:img {:alt "PitchIt" :src (utils/add-context "/img/pitchit.png")}] [:div.carousel-caption [:h4 [:a {:href "http://brian-jesse.com/pitchit"} "PitchIt"]] [:p "An application developed for Illinois State University. PitchIt is an application that helps a class of future entrepreneurs develop their business plan."]]] [:div.item [:img {:alt "GoalCharge" :src (utils/add-context "/img/goalcharge.png")}] [:div.carousel-caption [:h4 [:a {:href "http://goalcharge.com"}"GoalCharge"]] [:p "GoalCharge was first concieved during a mobile application development competion. It has since been ported for use on desktop and mobile devices."]]] [:div.item [:img {:alt "Leah Walk" :src (utils/add-context "/img/leahwalk.png")}] [:div.carousel-caption [:h4 [:a {:href "http://leahwalk.com"} "Leah Walk"]] [:p "The Leah Memorial Walk site is an example of simple elegant design"]]]] [:a.carousel-control.left {:href "#carousel" :data-slide "prev"} "&lsaquo;"] [:a.carousel-control.right {:href "#carousel" :data-slide "next"} "&rsaquo;"] ]]] [:div.row [:div.span4 [:h4 "Front End Framework Knowledge"] [:ul [:li "Angular JS"] [:li "Twitter Bootstrap"] [:li "jQuery"]]] [:div.span4 [:h4 "Back End Development Platforms"] [:ul [:li "PHP - Codeigniter"] [:li "Java EE6 - Glassfish"] [:li "Clojure - Noir"] [:li "Python - Flask"]]] [:div.row [:div#bootstraplove.span8 [:hr] [:h3 "Twitter Bootstrap"] [:p "Bootstrap gives you the ability to rapidly develop nice looking websites in a shorter amount of time. With the default styles from Bootstrap you have sensible margins and padding on useful elements, nice layout for standard ui items, and decent typography. Utilizing the grid system makes laying out your page simple. Bootstrap's responsive template is simple to use and radically changes the way mobile sites are constructed."] [:p "Bootstrap also enforces standard practices when creating forms and laying out your page. Bootstrap is compatible with older and modern browsers, so you aren't at a disadvantage when offering backwards compatibility."]]]])) (defonce pic-order (atom [1 2 3 4])) (defpage [:post "/ws/picorder"] {:keys [order]} (response/json (reset! pic-order order))) (defpage "/ws/picorder" [] (response/json @pic-order)) (defpage "/partials/gallery" [] (html [:div.tabbable [:ul#gallery_tabs.nav.nav-tabs [:li.active [:a {:href "#gallery_tab_1" :data-toggle "tab"} "Gallery"]] [:li [:a {:href "#gallery_tab_2" :data-gtoggle "tab"} "Reorder"]]] [:div.tab-content [:div#gallery_tab_1.tab-pane.active [:div.row {} [:div.span2 {:ng-repeat "image in pics" :fancy-box-directive ""} [:a {:rel "group" :href (utils/add-context "/img/gallery/{{image}}.jpg")} [:img.img-rounded {:alt "" :ng-src (utils/add-context "/img/gallery/{{image}}_sm.jpg")}]]]]] [:div#gallery_tab_2.tab-pane [:ul.row {:sortable-directive ""} [:li.span2 {:ng-repeat "image in pics" :id "{{image}}"} [:img.img-rounded {:ng-src (utils/add-context "/img/gallery/{{image}}_sm.jpg")}]]] [:div.row [:div.span3] [:div.span3 [:a.btn {:ng-click "saveOrder()"} "Save Order"]]]]]]))
[ { "context": "ir REGISTRATION\n \"sip:rkd@example.com\"))))))\n\n(deftest no-authtype-avp-test\n (testing ", "end": 1250, "score": 0.999873697757721, "start": 1235, "tag": "EMAIL", "value": "rkd@example.com" }, { "context": "te-mock-lir nil\n \"sip:rkd@example.com\"))))))\n\n\n\n(deftest unreg-test\n (testing \"Test th", "end": 1522, "score": 0.9998192191123962, "start": 1507, "tag": "EMAIL", "value": "rkd@example.com" }, { "context": "ir REGISTRATION\n \"sip:rkd@example.com\"))))))\n\n(deftest restoration-test\n (testing \"Tes", "end": 1877, "score": 0.9999038577079773, "start": 1862, "tag": "EMAIL", "value": "rkd@example.com" }, { "context": "ND_CAPABILITIES\n \"sip:rkd@example.com\"))))))\n\n(deftest unknown-test\n (testing \"Test th", "end": 2219, "score": 0.9999060034751892, "start": 2204, "tag": "EMAIL", "value": "rkd@example.com" }, { "context": "ir REGISTRATION\n \"sip:rkd@example.com\"))))))\n\n", "end": 2524, "score": 0.9998567700386047, "start": 2509, "tag": "EMAIL", "value": "rkd@example.com" } ]
test/org/leafhss/hss/cx_lir_test.clj
rkday/leafhss
1
(ns org.leafhss.hss.cx-lir-test (:require [clojure.test :refer :all] [org.leafhss.hss.cx :refer :all] [org.leafhss.hss.data :as data] [org.leafhss.hss.testdata :refer :all] [org.leafhss.hss.common-test :refer :all] [org.leafhss.hss.constants :refer :all] [cljito.core :refer :all]) (:import org.jdiameter.api.AvpSet org.jdiameter.api.Avp)) (defn create-mock-lir [auth-type pub] (let [auth-type-avp (when (not (nil? auth-type)) (when-> (mock Avp) (.getInteger32) (.thenReturn (int auth-type)))) public-identity-avp (when-> (mock Avp) (.getUTF8String) (.thenReturn pub)) mock-avpset (mock AvpSet) mocked (when-> (make-mock 302) (.getAvps) (.thenReturn mock-avpset))] (when-> mock-avpset (.getAvp 601 10415) (.thenReturn public-identity-avp)) (when-> mock-avpset (.getAvp 623 10415) (.thenReturn auth-type-avp)) mocked)) (deftest success-test (testing "Test that a LIR for auth-type REGISTRATION succeeds" (is (= mock-ok-answer (.processRequest cx-listener (create-mock-lir REGISTRATION "sip:rkd@example.com")))))) (deftest no-authtype-avp-test (testing "Test that a LIR without an auth-type AVP defaults correctly" (is (= mock-ok-answer (.processRequest cx-listener (create-mock-lir nil "sip:rkd@example.com")))))) (deftest unreg-test (testing "Test that a LIR for auth-type REGISTRATION succeeds when the user is not registered with an S-CSCF" (is (= mock-unregistered-service-answer (.processRequest unregistered-cx-listener (create-mock-lir REGISTRATION "sip:rkd@example.com")))))) (deftest restoration-test (testing "Test that a LIR for auth-type REGISTRATION_AND_CAPABILITIES (used in SIP Restoration) succeeds" (is (= mock-ok-answer (.processRequest unregistered-cx-listener (create-mock-lir REGISTRATION_AND_CAPABILITIES "sip:rkd@example.com")))))) (deftest unknown-test (testing "Test that a LIR fails when the public ID it references does not exist" (is (= mock-unknown-answer (.processRequest public-not-found-cx-listener (create-mock-lir REGISTRATION "sip:rkd@example.com"))))))
32349
(ns org.leafhss.hss.cx-lir-test (:require [clojure.test :refer :all] [org.leafhss.hss.cx :refer :all] [org.leafhss.hss.data :as data] [org.leafhss.hss.testdata :refer :all] [org.leafhss.hss.common-test :refer :all] [org.leafhss.hss.constants :refer :all] [cljito.core :refer :all]) (:import org.jdiameter.api.AvpSet org.jdiameter.api.Avp)) (defn create-mock-lir [auth-type pub] (let [auth-type-avp (when (not (nil? auth-type)) (when-> (mock Avp) (.getInteger32) (.thenReturn (int auth-type)))) public-identity-avp (when-> (mock Avp) (.getUTF8String) (.thenReturn pub)) mock-avpset (mock AvpSet) mocked (when-> (make-mock 302) (.getAvps) (.thenReturn mock-avpset))] (when-> mock-avpset (.getAvp 601 10415) (.thenReturn public-identity-avp)) (when-> mock-avpset (.getAvp 623 10415) (.thenReturn auth-type-avp)) mocked)) (deftest success-test (testing "Test that a LIR for auth-type REGISTRATION succeeds" (is (= mock-ok-answer (.processRequest cx-listener (create-mock-lir REGISTRATION "sip:<EMAIL>")))))) (deftest no-authtype-avp-test (testing "Test that a LIR without an auth-type AVP defaults correctly" (is (= mock-ok-answer (.processRequest cx-listener (create-mock-lir nil "sip:<EMAIL>")))))) (deftest unreg-test (testing "Test that a LIR for auth-type REGISTRATION succeeds when the user is not registered with an S-CSCF" (is (= mock-unregistered-service-answer (.processRequest unregistered-cx-listener (create-mock-lir REGISTRATION "sip:<EMAIL>")))))) (deftest restoration-test (testing "Test that a LIR for auth-type REGISTRATION_AND_CAPABILITIES (used in SIP Restoration) succeeds" (is (= mock-ok-answer (.processRequest unregistered-cx-listener (create-mock-lir REGISTRATION_AND_CAPABILITIES "sip:<EMAIL>")))))) (deftest unknown-test (testing "Test that a LIR fails when the public ID it references does not exist" (is (= mock-unknown-answer (.processRequest public-not-found-cx-listener (create-mock-lir REGISTRATION "sip:<EMAIL>"))))))
true
(ns org.leafhss.hss.cx-lir-test (:require [clojure.test :refer :all] [org.leafhss.hss.cx :refer :all] [org.leafhss.hss.data :as data] [org.leafhss.hss.testdata :refer :all] [org.leafhss.hss.common-test :refer :all] [org.leafhss.hss.constants :refer :all] [cljito.core :refer :all]) (:import org.jdiameter.api.AvpSet org.jdiameter.api.Avp)) (defn create-mock-lir [auth-type pub] (let [auth-type-avp (when (not (nil? auth-type)) (when-> (mock Avp) (.getInteger32) (.thenReturn (int auth-type)))) public-identity-avp (when-> (mock Avp) (.getUTF8String) (.thenReturn pub)) mock-avpset (mock AvpSet) mocked (when-> (make-mock 302) (.getAvps) (.thenReturn mock-avpset))] (when-> mock-avpset (.getAvp 601 10415) (.thenReturn public-identity-avp)) (when-> mock-avpset (.getAvp 623 10415) (.thenReturn auth-type-avp)) mocked)) (deftest success-test (testing "Test that a LIR for auth-type REGISTRATION succeeds" (is (= mock-ok-answer (.processRequest cx-listener (create-mock-lir REGISTRATION "sip:PI:EMAIL:<EMAIL>END_PI")))))) (deftest no-authtype-avp-test (testing "Test that a LIR without an auth-type AVP defaults correctly" (is (= mock-ok-answer (.processRequest cx-listener (create-mock-lir nil "sip:PI:EMAIL:<EMAIL>END_PI")))))) (deftest unreg-test (testing "Test that a LIR for auth-type REGISTRATION succeeds when the user is not registered with an S-CSCF" (is (= mock-unregistered-service-answer (.processRequest unregistered-cx-listener (create-mock-lir REGISTRATION "sip:PI:EMAIL:<EMAIL>END_PI")))))) (deftest restoration-test (testing "Test that a LIR for auth-type REGISTRATION_AND_CAPABILITIES (used in SIP Restoration) succeeds" (is (= mock-ok-answer (.processRequest unregistered-cx-listener (create-mock-lir REGISTRATION_AND_CAPABILITIES "sip:PI:EMAIL:<EMAIL>END_PI")))))) (deftest unknown-test (testing "Test that a LIR fails when the public ID it references does not exist" (is (= mock-unknown-answer (.processRequest public-not-found-cx-listener (create-mock-lir REGISTRATION "sip:PI:EMAIL:<EMAIL>END_PI"))))))
[ { "context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.basal.io\n\n \"Use", "end": 597, "score": 0.9998567700386047, "start": 584, "tag": "NAME", "value": "Kenneth Leung" }, { "context": ";;;;;;;;;;\n#_\n(def sample\n {:q1 {:question \"hello ken\"\n :choices \"q|b|c\"\n :default \"c\"\n ", "end": 36255, "score": 0.9990758895874023, "start": 36252, "tag": "NAME", "value": "ken" }, { "context": "lt :a1\n :next :q2}\n :q2 {:question \"hello paul\"\n :result :a2\n :next :q3}\n :q3 {:", "end": 36391, "score": 0.9983828067779541, "start": 36387, "tag": "NAME", "value": "paul" }, { "context": "lt :a2\n :next :q3}\n :q3 {:question \"hello joe\"\n :choices \"2\"\n :result (fn [answer", "end": 36460, "score": 0.9993624687194824, "start": 36457, "tag": "NAME", "value": "joe" } ]
src/main/clojure/czlab/basal/io.clj
llnek/xlib
0
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, Kenneth Leung. All rights reserved. (ns czlab.basal.io "Useful additions to clojure io." (:require [clojure.edn :as edn] [clojure.pprint :as pp] [clojure.string :as cs] [czlab.basal.util :as u] [czlab.basal.core :as c] [clojure.java.io :as io] [clojure.data.json :as js] [czlab.basal.indent :as in]) (:import [java.nio.file CopyOption Files Path Paths FileVisitResult SimpleFileVisitor StandardCopyOption] [java.util.zip GZIPInputStream GZIPOutputStream] [java.nio ByteBuffer CharBuffer] [czlab.basal XData] [java.util Arrays Base64 Base64$Decoder Base64$Encoder] [java.util.zip ZipFile ZipEntry] [java.util Stack] [java.net URI URL] [org.xml.sax InputSource] [java.io DataInputStream DataOutputStream FileInputStream FileOutputStream CharArrayWriter StringWriter FileFilter File InputStream Closeable OutputStream Reader Writer IOException InputStreamReader OutputStreamWriter BufferedOutputStream ByteArrayInputStream ByteArrayOutputStream] [java.nio.file.attribute BasicFileAttributes])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) (def ^:dynamic *membuf-limit* (* 4 c/MegaBytes)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- os* [x] `(clojure.java.io/output-stream ~x)) (c/defmacro- is* [x] `(clojure.java.io/input-stream ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro istream "Same as clojure.java.io's input-stream." {:arglists '([x])} [x] `(clojure.java.io/input-stream ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro ostream "Same as clojure.java.io's output-stream." {:arglists '([x])} [x] `(clojure.java.io/output-stream ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro file? "Is this a file?" {:arglists '([in])} [in] `(instance? java.io.File ~in)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro slurp-utf8 "Read f with utf8 encoding." {:arglists '([f])} [f] `(slurp ~f :encoding "utf-8")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro spit-utf8 "Write f with utf8 encoding." {:arglists '([f c])} [f c] `(spit ~f (str ~c) :encoding "utf-8")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn file-repo "Java's system temporary folder." {:arglists '([])} [] (io/file (u/sys-tmp-dir))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn baos<> "Make a byte array output stream." {:arglists '([][size]) :tag ByteArrayOutputStream} ([] (baos<> nil)) ([size] (ByteArrayOutputStream. (int (c/num?? size c/BUF-SZ))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fsize "Get length of file." {:arglists '([in])} [in] (some-> in io/file .length)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fname "Get name of file." {:tag String :arglists '([in])} [in] (some-> in io/file .getName)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn klose "Close object (quietly)." {:arglists '([obj])} [obj] (c/try! (some-> (c/cast? Closeable obj) .close))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn copy "Copy certain number of bytes to output." {:arglists '([in out] [in out count])} ([in out] (copy in out -1)) ([in out kount] {:pre [(number? kount)]} (if (neg? kount) (io/copy in out) (let [[di? ^InputStream is] (if (c/is? InputStream in) [false in] [true (is* in)]) [do? ^OutputStream os] (if (c/is? OutputStream out) [false out] [true (os* out)])] (try (loop [remain kount total 0 buf (byte-array c/BUF-SZ)] (let [len (if (< remain c/BUF-SZ) remain c/BUF-SZ) n (if-not (pos? len) -1 (.read is buf 0 len))] (if (neg? n) nil ;to be consistent with io/copy (do (if (pos? n) (.write os buf 0 n)) (recur (long (- remain n)) (long (+ total n)) buf))))) (finally (if di? (klose is)) (if do? (klose os)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->bytes "Convert almost anything to byte[]." {:tag "[B" :arglists '([in][in enc])} ([in] (x->bytes in "utf-8")) ([in enc] (cond (c/is? u/CSCZ in) (let [^ByteBuffer bb (.encode (u/charset?? enc) (CharBuffer/wrap ^chars in))] (Arrays/copyOfRange (.array bb) (.position bb) (.limit bb))) (c/is? StringBuilder in) (x->bytes (.toString ^Object in) enc) (string? in) (.getBytes ^String in (u/encoding?? enc)) (or (nil? in) (bytes? in)) in (c/is? XData in) (.getBytes ^XData in) (c/is? ByteArrayOutputStream in) (.toByteArray ^ByteArrayOutputStream in) :else (let [os (baos<>)] (io/copy in os) (.toByteArray os))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->chars "Convert almost anything to char[]." {:tag "[C" :arglists '([in][in enc])} ([in] (x->chars in "utf-8")) ([in enc] (cond (c/is? CharArrayWriter in) (.toCharArray ^CharArrayWriter in) (or (nil? in) (c/is? u/CSCZ in)) in (c/is? StringBuilder in) (x->chars (.toString ^Object in)) (string? in) (.toCharArray ^String in) (c/is? XData in) (x->chars (.getBytes ^XData in)) (bytes? in) (->> (u/encoding?? enc) (String. ^bytes in) .toCharArray) (c/is? ByteArrayOutputStream in) (x->chars (.toByteArray ^ByteArrayOutputStream in) enc) :else (let [os (baos<>)] (io/copy in os) (x->chars (.toByteArray os) enc))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->str "Convert almost anything to String." {:tag String :arglists '([in][in enc])} ([in] (x->str in "utf-8")) ([in enc] (cond (or (nil? in) (string? in)) in (bytes? in) (String. ^bytes in ^String enc) (c/is? InputStream in) (x->str (let [os (baos<>)] (io/copy in os) os)) (c/is? File in) (slurp in :encoding enc) (c/is? XData in) (.strit ^XData in) (c/is? StringBuilder in) (.toString ^Object in) (c/is? ByteArrayOutputStream in) (String. (.toByteArray ^ByteArrayOutputStream in) ^String enc) :else (String. (x->chars in enc))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn read-number "Deserialize a number." {:tag Number :arglists '([in numType])} [in numType] {:pre [(class? numType)]} (c/wo* [dis (DataInputStream. (is* in))] (cond (or (= numType Double) (= numType Double/TYPE)) (.readDouble dis) (or (= numType Float) (= numType Float/TYPE)) (.readFloat dis) (or (= numType Integer) (= numType Integer/TYPE)) (.readInt dis) (or (= numType Long) (= numType Long/TYPE)) (.readLong dis) :else (u/throw-BadData "Unsupported number type %s." numType)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn write-number "Serialize a number." {:tag "[B" :arglists '([nnum])} [nnum] {:pre [(number? nnum)]} (c/wo* [baos (baos<>) dos (DataOutputStream. baos)] (let [numType (class nnum)] (cond (or (= numType Double) (= numType Double/TYPE)) (.writeDouble dos (double nnum)) (or (= numType Float) (= numType Float/TYPE)) (.writeFloat dos (float nnum)) (or (= numType Integer) (= numType Integer/TYPE)) (.writeInt dos (int nnum)) (or (= numType Long) (= numType Long/TYPE)) (.writeLong dos (long nnum)) :else (u/throw-BadData "Unsupported number type %s." numType)) (.flush dos) (.toByteArray baos)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fdelete "Delete file (quietly)." {:arglists '([f])} [f] (c/try! (if (c/is? File f) (io/delete-file f true)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn bytes->hex "Bytes into hex-chars." {:tag "[C" :arglists '([in])} [in] (let [b' (x->bytes in) len (if (nil? b') 0 (* 2 (alength b')))] (loop [k 0 pos 0 out (char-array len)] (if (>= pos len) (if (nil? in) nil out) (let [n (bit-and (aget b' k) 0xff)] (aset-char out ;; high 4 bits pos (aget ^chars c/hex-chars (unsigned-bit-shift-right n 4))) (aset-char out ;; low 4 bits (+ pos 1) (aget ^chars c/hex-chars (bit-and n 0xf))) (recur (+ 1 k) (+ 2 pos) out)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hexify "Turn bytes into hex string." {:tag String :arglists '([in])} [in] (some-> in bytes->hex x->str)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gzip "Gzip input." {:tag "[B" :arglists '([in])} [in] (if-some [b (x->bytes in)] (with-open [baos (baos<>) g (GZIPOutputStream. baos)] (.write g b 0 (alength b)) (.finish g) (.toByteArray baos)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gunzip "Gunzip input." {:tag "[B" :arglists '([in])} [in] (if-some [b (x->bytes in)] (with-open [inp (GZIPInputStream. (io/input-stream b))] (x->bytes inp)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn reset-stream! "Reset stream (safely)." {:arglists '([in])} [in] (if-some [inp (c/cast? InputStream in)] (c/try! (.reset inp))) in) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn input-stream?? "Returns a tuple [you-close? stream]." {:arglists '([arg] [arg enc])} ([arg] (input-stream?? arg "utf-8")) ([arg enc] (cond (or (bytes? arg) (c/is? URL arg) (c/is? File arg)) [true (io/input-stream arg)] (c/is? ByteArrayOutputStream arg) (input-stream?? (x->bytes arg)) (c/is? u/CSCZ arg) (input-stream?? (x->bytes arg enc)) (or (nil? arg) (c/is? InputStream arg)) [false arg] (string? arg) (if (cs/starts-with? arg "file:") (input-stream?? (io/as-url arg)) (input-stream?? (x->bytes arg enc)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gzb64->bytes "Unzip content which is base64 encoded + gziped." {:tag "[B" :arglists '([in])} [in] (some->> in x->str (.decode (Base64/getDecoder)) gunzip)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn bytes->gzb64 "Zip content and then base64 encode it." {:tag String :arglists '([in])} [in] (some->> (some-> in x->bytes gzip) (.encodeToString (Base64/getEncoder)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn readable-bytes "Get the available bytes in this stream." {:tag Integer :arglists '([in][in enc])} ([in] (readable-bytes in "utf-8")) ([in enc] (cond (c/is? InputStream in) (.available ^InputStream in) (c/is? File in) (.length (c/cast? File in)) (c/is? URL in) (c/wo* [i (is* in)] (readable-bytes i enc)) (string? in) (readable-bytes (x->bytes in enc) enc) (bytes? in) (alength ^bytes in) (c/is? u/CSCZ in) (readable-bytes (x->bytes in enc) enc) :else 0))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn tmpfile "Create f in temp dir." {:tag File :arglists '([f])} [f] (->> (if-not (c/is? File f) (str f) (.getName ^File f)) (io/file (file-repo)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn temp-file "Create a temporary file." {:tag File :arglists '([] [pfx sux] [pfx sux dir])} ([] (temp-file nil nil)) ([pfx sux] (temp-file pfx sux (file-repo))) ([pfx sux dir] (c/do-with [f (File/createTempFile (c/stror pfx "czlab") (c/stror sux ".tmp") (io/file dir))] (fdelete f)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn open-temp-file "A Tuple(2) [File, OutputStream?]." {:arglists '([] [pfx sux] [pfx sux dir])} ([] (open-temp-file nil nil)) ([pfx sux] (open-temp-file pfx sux (file-repo))) ([pfx sux dir] (let [fp (temp-file pfx sux dir)] [fp (os* fp)]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->file "Copy content to a temp file." {:tag File :arglists '([in][in fout])} ([in] (x->file in nil)) ([in fout] (let [fp (or fout (temp-file))] (c/pre (c/is? File fp)) (try (io/copy in fp) fp (catch Throwable _ (if (nil? fout) (fdelete fp)) nil))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn reset-source! "Reset an input source." {:arglists '([in])} [in] (if-some [src (c/cast? InputSource in)] (let [ism (.getByteStream src) rdr (.getCharacterStream src)] (c/try! (some-> ism .reset)) (c/try! (some-> rdr .reset)))) in) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- swap-bytes "Swap bytes in buffer to file." [baos enc] (let [[f ^OutputStream os :as rc] (open-temp-file)] (doto os (.write (x->bytes baos enc)) .flush) (klose baos) rc)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- swap-chars "Swap chars in writer to file." [wtr enc] (let [[fp ^OutputStream out] (open-temp-file) w (OutputStreamWriter. out (u/encoding?? enc))] (doto w (.write (x->chars wtr enc)) .flush) (klose wtr) [fp w])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- slurp-inp [^InputStream inp limit enc] (loop [bits (byte-array c/BUF-SZ) os (baos<>) fo nil cnt 0 c (.read inp bits)] (if (neg? c) (try (if fo fo (x->bytes os enc)) (finally (klose os))) (do (if (pos? c) (.write ^OutputStream os bits 0 c)) (let [[f o'] (if-not (and (nil? fo) (> (+ c cnt) limit)) [fo os] (swap-bytes os enc))] (recur bits o' f (+ c cnt) (.read inp bits))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- slurp-rdr [^Reader rdr limit enc] (loop [cw (CharArrayWriter. (int c/BUF-SZ)) carr (char-array c/BUF-SZ) fo nil cnt 0 c (.read rdr carr)] (if (neg? c) (try (if fo fo (x->chars cw enc)) (finally (klose cw))) (do (if (pos? c) (.write ^Writer cw carr 0 c)) (let [[f w] (if-not (and (nil? fo) (> (+ c cnt) limit)) [fo cw] (swap-chars cw enc))] (recur w carr f (+ c cnt) (.read rdr carr))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn slurpb "Like slurp but reads in bytes." {:arglists '([in] [in enc] [in enc useFile?])} ([in enc] (slurpb in enc false)) ([in] (slurpb in "utf-8")) ([in enc usefile?] (let [[c? i] (input-stream?? in)] (try (slurp-inp i (if usefile? 1 *membuf-limit*) enc) (finally (if c? (klose i))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn slurpc "Like slurp but reads in chars." {:arglists '([in] [in enc] [in enc useFile?])} ([in enc] (slurpc in enc false)) ([in] (slurpc in "utf-8")) ([in enc usefile?] (let [[c? i] (input-stream?? in) _ (assert (c/is? InputStream i) "Expected input-stream!") rdr (InputStreamReader. i)] (try (slurp-rdr rdr (if usefile? 1 *membuf-limit*) enc) (finally (if c? (klose rdr))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn file-read-write? "Is file readable & writable?" {:arglists '([in])} [in] (if-some [^File fp (some-> in (io/file))] (and (.exists fp) (.isFile fp) (.canRead fp) (.canWrite fp)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn file-ok? "If file exists?" {:arglists '([in])} [in] (if-some [^File fp (some-> in (io/file))] (.exists fp))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn file-read? "Is file readable?" {:arglists '([in])} [in] (if-some [^File fp (some-> in (io/file))] (and (.exists fp) (.isFile fp) (.canRead fp)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn dir-read-write? "Is dir readable and writable?" {:arglists '([in])} [in] (if-some [^File dir (some-> in (io/file))] (and (.exists dir) (.isDirectory dir) (.canRead dir) (.canWrite dir)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn dir-read? "Is dir readable?" {:arglists '([in])} [in] (if-some [^File dir (some-> in (io/file))] (and (.exists dir) (.isDirectory dir) (.canRead dir)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn can-exec? "Is file executable?" {:arglists '([in])} [in] (if-some [^File fp (some-> in (io/file))] (and (.exists fp) (.canExecute fp)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn parent-file "Parent file." {:tag File :arglists '([in])} [in] (if-some [^File f (some-> in (io/file))] (.getParentFile f))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn parent-path "Path to parent." {:tag String :arglists '([path])} [path] (if (c/nichts? path) "" (.getParent (io/file path)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-file "Get a file from a directory." {:arglists '([dir fname])} [dir fname] (let [fp (io/file dir fname)] (if (file-read? fp) (XData. fp false)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn spit-file "Save a file to a directory." {:tag File :arglists '([file stuff] [file stuff del?])} ([file stuff] (spit-file file stuff false)) ([file stuff del?] (let [fp (io/file file) ^XData in (if (c/is? XData stuff) stuff (XData. stuff false))] (if del? (fdelete fp) (if (.exists fp) (u/throw-IOE "File %s exists." fp))) (if-not (.isFile in) (io/copy (.getBytes in) fp) (let [opts (c/marray CopyOption 1)] (aset #^"[Ljava.nio.file.CopyOption;" opts 0 StandardCopyOption/REPLACE_EXISTING) (Files/move (.. in fileRef toPath) (.toPath fp) opts) ;;since file has moved, update stuff (.setDeleteFlag in false) (.reset in nil))) fp))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn save-file "Save a file to a directory." {:tag File :arglists '([dir fname stuff] [dir fname stuff del?])} ([dir fname stuff] (save-file dir fname stuff false)) ([dir fname stuff del?] (spit-file (io/file dir fname) stuff del?))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn change-content "Pass file content - as string to the work function, returning new content." {:tag String :arglists '([file work] [file work enc])} ([file work] (change-content file work "utf-8")) ([file work enc] {:pre [(fn? work)]} (if (file-read? file) (work (slurp file :encoding (u/encoding?? enc)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn replace-file! "Update file with new content." {:tag File :arglists '([file work] [file work enc])} ([file work] (replace-file! file work "utf-8")) ([file work enc] {:pre [(fn? work)]} (spit file (change-content file work enc) :encoding (u/encoding?? enc)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn unzip->dir "Unzip zip file to a target folder." {:arglists '([srcZip desDir])} [^File srcZip ^File desDir] (let [z (ZipFile. srcZip) es (.entries z)] (.mkdirs desDir) (while (.hasMoreElements es) (let [^ZipEntry en (.nextElement es) f (io/file desDir (-> (.getName en) (.replaceAll "^[\\/]+" "")))] (if (.isDirectory en) (.mkdirs f) (do (.. f getParentFile mkdirs) (c/wo* [inp (.getInputStream z en)] (io/copy inp f)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mkdirs "Make directories." {:tag File :arglists '([arg])} [arg] (cond (string? arg) (mkdirs (io/file arg)) (c/is? File arg) (doto ^File arg .mkdirs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn list-files "List files with certain extension." {:arglists '([dir ext])} [dir ext] (c/vec-> (.listFiles (io/file dir) (reify FileFilter (accept [_ f] (cs/ends-with? (.getName f) ext)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn list-dirs "List sub-directories." {:arglists '([dir])} [dir] (c/vec-> (.listFiles (io/file dir) (reify FileFilter (accept [_ f] (.isDirectory f)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn list-any-files "List files with certain extension recursively." {:arglists '([dir ext])} [dir ext] (c/do-with-atom [res (atom [])] (let [dir (io/file dir) dig (fn [^File root ext bin func] (doseq [^File f (.listFiles root) :let [fn (.getName f) d? (.isDirectory f)]] (cond d? (func f ext bin func) (cs/ends-with? fn ext) (swap! bin conj f))))] (if (dir-read? dir) (dig dir ext res dig))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn grep-folder-paths "Recurse a dir, pick out dirs that have files of this extension." {:arglists '([rootDir ext])} [rootDir ext] (c/do-with-atom [bin (atom #{})] (let [rootDir (io/file rootDir) rlen (+ 1 (c/n# (u/fpath rootDir))) dig (fn [^File top func] (doseq [^File f (.listFiles top) :let [fn (.getName f) d? (.isDirectory f)]] (cond d? (func f func) (cs/ends-with? fn ext) (let [p (.getParentFile f)] (if-not (c/in? @bin p) (swap! bin conj p))))))] (dig rootDir dig)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- scan-tree "Walk down folder hierarchies." [^Stack stk ext out seed] (if-let [^File top (or seed (.peek stk))] (doseq [^File f (.listFiles top)] (let [p (map #(.getName ^File %) (if-not (.empty stk) (.toArray stk))) fid (.getName f) paths (conj (c/vec-> p) fid)] (if (.isDirectory f) (do (.push stk f) (scan-tree stk ext out nil)) (if (cs/ends-with? fid ext) (swap! out conj (cs/join "/" paths))))))) (when-not (.empty stk) (.pop stk)) out) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn grep-file-paths "Recurse a folder, picking out files with the given extension." {:arglists '([rootDir ext])} [rootDir ext] ;; the stack is used to store the folder hierarchy @(scan-tree (Stack.) ext (atom []) (io/file rootDir))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn basename "Get the name of file without extension." {:arglists '([file])} [file] (let [n (.getName (io/file file)) p (cs/last-index-of n ".")] (if p (subs n 0 p) n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn touch! "Touch a file." {:arglists '([file])} [file] (if-some [f (io/file file)] (if-not (.exists f) (do (.. f getParentFile mkdirs) (c/wo* [o (os* f)])) (when-not (.setLastModified f (u/system-time)) (u/throw-IOE "Unable to set the lastmodtime: %s." f))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn chunk-read-stream "Reads through this data, and for each chunk calls the function." {:arglists '([data cb])} [data cb] (let [b (byte-array c/FourK) [z? ^InputStream inp] (input-stream?? data)] (try (loop [c (if inp (.read inp b) 0) t 0] (if (pos? c) (do (cb b 0 c false) (recur (.read inp b) (long (+ t c)))) (cb b 0 0 true))) (finally (if z? (klose inp)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fmt->edn "Format to EDN." {:tag String :arglists '([obj])} [obj] (let [w (StringWriter.)] (if obj (pp/with-pprint-dispatch in/indent-dispatch (pp/pprint obj w))) (str w))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn read-edn "Parse EDN formatted text." {:arglists '([arg] [arg enc])} ([arg] (read-edn arg "utf-8")) ([arg enc] (if-some [s (x->str arg enc)] (edn/read-string s)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fmt->json "Format to JSON." {:tag String :arglists '([data])} [data] (some-> data js/write-str)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn read-json "Parses JSON." {:arglists '([data] [data enc] [data enc keyfn])} ([data enc] (read-json data enc nil)) ([data] (read-json data "utf-8")) ([data enc keyfn] (if-some [s (x->str data enc)] (if keyfn (js/read-str s :key-fn keyfn) (js/read-str s))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->stream "Load the resource as stream." {:tag InputStream :arglists '([path] [path ldr])} ([path] (res->stream path nil)) ([path ldr] {:pre [(string? path)]} (when-not (empty? path) (-> (u/get-cldr ldr) (.getResourceAsStream ^String path))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->url "Load the resource as URL." {:tag URL :arglists '([path] [path ldr])} ([path] (res->url path nil)) ([path ldr] {:pre [(string? path)]} (when-not (empty? path) (-> (u/get-cldr ldr) (.getResource ^String path))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->str "Load the resource as string." {:tag String :arglists '([path] [path enc] [path enc ldr])} ([path enc] (res->str path enc nil)) ([path] (res->str path "utf-8" nil)) ([path enc ldr] (if-some [r (res->stream path ldr)] (c/wo* [inp r out (baos<> c/BUF-SZ)] (io/copy inp out :buffer-size c/BUF-SZ) (x->str out enc))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->bytes "Load the resource as bytes." {:tag "[B" :arglists '([path][path ldr])} ([path] (res->bytes path nil)) ([path ldr] (if-some [r (res->stream path ldr)] (c/wo* [inp r out (baos<> c/BUF-SZ)] (io/copy inp out :buffer-size c/BUF-SZ) (x->bytes out))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->file "Load the resource and write it to a temp file." {:tag File :arglists '([path] [path ldr])} ([path] (res->file path nil)) ([path ldr] (if-some [r (res->stream path ldr)] (c/do-with [out (temp-file)] (c/wo* [inp r] (io/copy inp out :buffer-size c/BUF-SZ)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn delete-dir "Deleting recursively a directory with native Java. https://docs.oracle.com/javase/tutorial/essential/io/walk.html" {:arglists '([dir])} [dir] (if-some [root (Paths/get (-> dir io/file .toURI))] (Files/walkFileTree root (proxy [SimpleFileVisitor][] (visitFile [^Path file ^BasicFileAttributes attrs] (Files/delete file) FileVisitResult/CONTINUE) (postVisitDirectory [^Path dir ^IOException ex] (Files/delete dir) FileVisitResult/CONTINUE))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn clean-dir "Clean out recursively a directory with native Java. https://docs.oracle.com/javase/tutorial/essential/io/walk.html" {:arglists '([dir])} [dir] (if-some [root (Paths/get (-> dir io/file .toURI))] (Files/walkFileTree root (proxy [SimpleFileVisitor][] (visitFile [^Path file ^BasicFileAttributes attrs] (Files/delete file) FileVisitResult/CONTINUE) (postVisitDirectory [^Path dir ^IOException ex] (if (not= dir root) (Files/delete dir)) FileVisitResult/CONTINUE))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn cmenu "A console menu, prompting a sequence of questions via console." {:arglists '([cmdQs q1])} [cmdQs q1] {:pre [(map? cmdQs)]} (letfn [(read-data [^Reader in] (let [[ms bf] (loop [c (.read in) bf (c/sbf<>)] (let [m (cond (or (== c 4) (== c -1)) #{:quit :break} (== c (int \newline)) #{:break} (c/or?? [== c] 27 (int \return) (int \backspace)) nil :else (c/do->nil (c/sbf+ bf (char c))))] (if (c/in? m :break) [m bf] (recur (.read in) bf))))] (if-not (c/in? ms :quit) (c/strim (str bf))))) (on-answer [^Writer cout answer props {:keys [result id must? default next]}] (if (nil? answer) (c/do->nil (.write cout "\n")) (let [rc (c/stror answer default)] (cond (and must? (c/nichts? rc)) id ;no answer, loop try again (keyword? result) (do (swap! props assoc result rc) next) (fn? result) (let [[nxt p] (result rc @props)] (reset! props p) (or nxt ::caio!!)) :else ::caio!!)))) (popQ [^Writer cout ^Reader cin props {:as Q :keys [must? choices default question]}] (if (nil? Q) ::caio!! (do (.write cout (str question (if must? "*") "? ")) (if (c/hgl? choices) (.write cout (str "[" choices "]"))) (if (c/hgl? default) (.write cout (str "(" default ")"))) (doto cout (.write " ") .flush) ;; get the input from user, return the next question (-> (read-data cin) (on-answer cout props Q))))) (cycleQ [cout cin cmdQs start props] (loop [rc (popQ cout cin props (cmdQs start))] (cond (nil? rc) {} (= ::caio!! rc) @props :else (recur (popQ cout cin props (cmdQs rc))))))] (let [cout (-> System/out BufferedOutputStream. OutputStreamWriter.) func (->> System/in InputStreamReader. (partial cycleQ cout))] (.write cout (str ">>> Press " "<ctrl-c> or <ctrl-d>" "<Enter> to cancel...\n")) (-> #(update-in %1 [%2] assoc :id %2) (reduce cmdQs (keys cmdQs)) (func q1 (atom {})))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #_ (def sample {:q1 {:question "hello ken" :choices "q|b|c" :default "c" :must? true :result :a1 :next :q2} :q2 {:question "hello paul" :result :a2 :next :q3} :q3 {:question "hello joe" :choices "2" :result (fn [answer result] [nil (assoc result :zzz answer)])}}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
87599
;; 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. ;; ;; Copyright © 2013-2022, <NAME>. All rights reserved. (ns czlab.basal.io "Useful additions to clojure io." (:require [clojure.edn :as edn] [clojure.pprint :as pp] [clojure.string :as cs] [czlab.basal.util :as u] [czlab.basal.core :as c] [clojure.java.io :as io] [clojure.data.json :as js] [czlab.basal.indent :as in]) (:import [java.nio.file CopyOption Files Path Paths FileVisitResult SimpleFileVisitor StandardCopyOption] [java.util.zip GZIPInputStream GZIPOutputStream] [java.nio ByteBuffer CharBuffer] [czlab.basal XData] [java.util Arrays Base64 Base64$Decoder Base64$Encoder] [java.util.zip ZipFile ZipEntry] [java.util Stack] [java.net URI URL] [org.xml.sax InputSource] [java.io DataInputStream DataOutputStream FileInputStream FileOutputStream CharArrayWriter StringWriter FileFilter File InputStream Closeable OutputStream Reader Writer IOException InputStreamReader OutputStreamWriter BufferedOutputStream ByteArrayInputStream ByteArrayOutputStream] [java.nio.file.attribute BasicFileAttributes])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) (def ^:dynamic *membuf-limit* (* 4 c/MegaBytes)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- os* [x] `(clojure.java.io/output-stream ~x)) (c/defmacro- is* [x] `(clojure.java.io/input-stream ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro istream "Same as clojure.java.io's input-stream." {:arglists '([x])} [x] `(clojure.java.io/input-stream ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro ostream "Same as clojure.java.io's output-stream." {:arglists '([x])} [x] `(clojure.java.io/output-stream ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro file? "Is this a file?" {:arglists '([in])} [in] `(instance? java.io.File ~in)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro slurp-utf8 "Read f with utf8 encoding." {:arglists '([f])} [f] `(slurp ~f :encoding "utf-8")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro spit-utf8 "Write f with utf8 encoding." {:arglists '([f c])} [f c] `(spit ~f (str ~c) :encoding "utf-8")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn file-repo "Java's system temporary folder." {:arglists '([])} [] (io/file (u/sys-tmp-dir))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn baos<> "Make a byte array output stream." {:arglists '([][size]) :tag ByteArrayOutputStream} ([] (baos<> nil)) ([size] (ByteArrayOutputStream. (int (c/num?? size c/BUF-SZ))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fsize "Get length of file." {:arglists '([in])} [in] (some-> in io/file .length)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fname "Get name of file." {:tag String :arglists '([in])} [in] (some-> in io/file .getName)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn klose "Close object (quietly)." {:arglists '([obj])} [obj] (c/try! (some-> (c/cast? Closeable obj) .close))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn copy "Copy certain number of bytes to output." {:arglists '([in out] [in out count])} ([in out] (copy in out -1)) ([in out kount] {:pre [(number? kount)]} (if (neg? kount) (io/copy in out) (let [[di? ^InputStream is] (if (c/is? InputStream in) [false in] [true (is* in)]) [do? ^OutputStream os] (if (c/is? OutputStream out) [false out] [true (os* out)])] (try (loop [remain kount total 0 buf (byte-array c/BUF-SZ)] (let [len (if (< remain c/BUF-SZ) remain c/BUF-SZ) n (if-not (pos? len) -1 (.read is buf 0 len))] (if (neg? n) nil ;to be consistent with io/copy (do (if (pos? n) (.write os buf 0 n)) (recur (long (- remain n)) (long (+ total n)) buf))))) (finally (if di? (klose is)) (if do? (klose os)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->bytes "Convert almost anything to byte[]." {:tag "[B" :arglists '([in][in enc])} ([in] (x->bytes in "utf-8")) ([in enc] (cond (c/is? u/CSCZ in) (let [^ByteBuffer bb (.encode (u/charset?? enc) (CharBuffer/wrap ^chars in))] (Arrays/copyOfRange (.array bb) (.position bb) (.limit bb))) (c/is? StringBuilder in) (x->bytes (.toString ^Object in) enc) (string? in) (.getBytes ^String in (u/encoding?? enc)) (or (nil? in) (bytes? in)) in (c/is? XData in) (.getBytes ^XData in) (c/is? ByteArrayOutputStream in) (.toByteArray ^ByteArrayOutputStream in) :else (let [os (baos<>)] (io/copy in os) (.toByteArray os))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->chars "Convert almost anything to char[]." {:tag "[C" :arglists '([in][in enc])} ([in] (x->chars in "utf-8")) ([in enc] (cond (c/is? CharArrayWriter in) (.toCharArray ^CharArrayWriter in) (or (nil? in) (c/is? u/CSCZ in)) in (c/is? StringBuilder in) (x->chars (.toString ^Object in)) (string? in) (.toCharArray ^String in) (c/is? XData in) (x->chars (.getBytes ^XData in)) (bytes? in) (->> (u/encoding?? enc) (String. ^bytes in) .toCharArray) (c/is? ByteArrayOutputStream in) (x->chars (.toByteArray ^ByteArrayOutputStream in) enc) :else (let [os (baos<>)] (io/copy in os) (x->chars (.toByteArray os) enc))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->str "Convert almost anything to String." {:tag String :arglists '([in][in enc])} ([in] (x->str in "utf-8")) ([in enc] (cond (or (nil? in) (string? in)) in (bytes? in) (String. ^bytes in ^String enc) (c/is? InputStream in) (x->str (let [os (baos<>)] (io/copy in os) os)) (c/is? File in) (slurp in :encoding enc) (c/is? XData in) (.strit ^XData in) (c/is? StringBuilder in) (.toString ^Object in) (c/is? ByteArrayOutputStream in) (String. (.toByteArray ^ByteArrayOutputStream in) ^String enc) :else (String. (x->chars in enc))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn read-number "Deserialize a number." {:tag Number :arglists '([in numType])} [in numType] {:pre [(class? numType)]} (c/wo* [dis (DataInputStream. (is* in))] (cond (or (= numType Double) (= numType Double/TYPE)) (.readDouble dis) (or (= numType Float) (= numType Float/TYPE)) (.readFloat dis) (or (= numType Integer) (= numType Integer/TYPE)) (.readInt dis) (or (= numType Long) (= numType Long/TYPE)) (.readLong dis) :else (u/throw-BadData "Unsupported number type %s." numType)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn write-number "Serialize a number." {:tag "[B" :arglists '([nnum])} [nnum] {:pre [(number? nnum)]} (c/wo* [baos (baos<>) dos (DataOutputStream. baos)] (let [numType (class nnum)] (cond (or (= numType Double) (= numType Double/TYPE)) (.writeDouble dos (double nnum)) (or (= numType Float) (= numType Float/TYPE)) (.writeFloat dos (float nnum)) (or (= numType Integer) (= numType Integer/TYPE)) (.writeInt dos (int nnum)) (or (= numType Long) (= numType Long/TYPE)) (.writeLong dos (long nnum)) :else (u/throw-BadData "Unsupported number type %s." numType)) (.flush dos) (.toByteArray baos)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fdelete "Delete file (quietly)." {:arglists '([f])} [f] (c/try! (if (c/is? File f) (io/delete-file f true)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn bytes->hex "Bytes into hex-chars." {:tag "[C" :arglists '([in])} [in] (let [b' (x->bytes in) len (if (nil? b') 0 (* 2 (alength b')))] (loop [k 0 pos 0 out (char-array len)] (if (>= pos len) (if (nil? in) nil out) (let [n (bit-and (aget b' k) 0xff)] (aset-char out ;; high 4 bits pos (aget ^chars c/hex-chars (unsigned-bit-shift-right n 4))) (aset-char out ;; low 4 bits (+ pos 1) (aget ^chars c/hex-chars (bit-and n 0xf))) (recur (+ 1 k) (+ 2 pos) out)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hexify "Turn bytes into hex string." {:tag String :arglists '([in])} [in] (some-> in bytes->hex x->str)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gzip "Gzip input." {:tag "[B" :arglists '([in])} [in] (if-some [b (x->bytes in)] (with-open [baos (baos<>) g (GZIPOutputStream. baos)] (.write g b 0 (alength b)) (.finish g) (.toByteArray baos)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gunzip "Gunzip input." {:tag "[B" :arglists '([in])} [in] (if-some [b (x->bytes in)] (with-open [inp (GZIPInputStream. (io/input-stream b))] (x->bytes inp)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn reset-stream! "Reset stream (safely)." {:arglists '([in])} [in] (if-some [inp (c/cast? InputStream in)] (c/try! (.reset inp))) in) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn input-stream?? "Returns a tuple [you-close? stream]." {:arglists '([arg] [arg enc])} ([arg] (input-stream?? arg "utf-8")) ([arg enc] (cond (or (bytes? arg) (c/is? URL arg) (c/is? File arg)) [true (io/input-stream arg)] (c/is? ByteArrayOutputStream arg) (input-stream?? (x->bytes arg)) (c/is? u/CSCZ arg) (input-stream?? (x->bytes arg enc)) (or (nil? arg) (c/is? InputStream arg)) [false arg] (string? arg) (if (cs/starts-with? arg "file:") (input-stream?? (io/as-url arg)) (input-stream?? (x->bytes arg enc)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gzb64->bytes "Unzip content which is base64 encoded + gziped." {:tag "[B" :arglists '([in])} [in] (some->> in x->str (.decode (Base64/getDecoder)) gunzip)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn bytes->gzb64 "Zip content and then base64 encode it." {:tag String :arglists '([in])} [in] (some->> (some-> in x->bytes gzip) (.encodeToString (Base64/getEncoder)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn readable-bytes "Get the available bytes in this stream." {:tag Integer :arglists '([in][in enc])} ([in] (readable-bytes in "utf-8")) ([in enc] (cond (c/is? InputStream in) (.available ^InputStream in) (c/is? File in) (.length (c/cast? File in)) (c/is? URL in) (c/wo* [i (is* in)] (readable-bytes i enc)) (string? in) (readable-bytes (x->bytes in enc) enc) (bytes? in) (alength ^bytes in) (c/is? u/CSCZ in) (readable-bytes (x->bytes in enc) enc) :else 0))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn tmpfile "Create f in temp dir." {:tag File :arglists '([f])} [f] (->> (if-not (c/is? File f) (str f) (.getName ^File f)) (io/file (file-repo)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn temp-file "Create a temporary file." {:tag File :arglists '([] [pfx sux] [pfx sux dir])} ([] (temp-file nil nil)) ([pfx sux] (temp-file pfx sux (file-repo))) ([pfx sux dir] (c/do-with [f (File/createTempFile (c/stror pfx "czlab") (c/stror sux ".tmp") (io/file dir))] (fdelete f)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn open-temp-file "A Tuple(2) [File, OutputStream?]." {:arglists '([] [pfx sux] [pfx sux dir])} ([] (open-temp-file nil nil)) ([pfx sux] (open-temp-file pfx sux (file-repo))) ([pfx sux dir] (let [fp (temp-file pfx sux dir)] [fp (os* fp)]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->file "Copy content to a temp file." {:tag File :arglists '([in][in fout])} ([in] (x->file in nil)) ([in fout] (let [fp (or fout (temp-file))] (c/pre (c/is? File fp)) (try (io/copy in fp) fp (catch Throwable _ (if (nil? fout) (fdelete fp)) nil))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn reset-source! "Reset an input source." {:arglists '([in])} [in] (if-some [src (c/cast? InputSource in)] (let [ism (.getByteStream src) rdr (.getCharacterStream src)] (c/try! (some-> ism .reset)) (c/try! (some-> rdr .reset)))) in) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- swap-bytes "Swap bytes in buffer to file." [baos enc] (let [[f ^OutputStream os :as rc] (open-temp-file)] (doto os (.write (x->bytes baos enc)) .flush) (klose baos) rc)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- swap-chars "Swap chars in writer to file." [wtr enc] (let [[fp ^OutputStream out] (open-temp-file) w (OutputStreamWriter. out (u/encoding?? enc))] (doto w (.write (x->chars wtr enc)) .flush) (klose wtr) [fp w])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- slurp-inp [^InputStream inp limit enc] (loop [bits (byte-array c/BUF-SZ) os (baos<>) fo nil cnt 0 c (.read inp bits)] (if (neg? c) (try (if fo fo (x->bytes os enc)) (finally (klose os))) (do (if (pos? c) (.write ^OutputStream os bits 0 c)) (let [[f o'] (if-not (and (nil? fo) (> (+ c cnt) limit)) [fo os] (swap-bytes os enc))] (recur bits o' f (+ c cnt) (.read inp bits))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- slurp-rdr [^Reader rdr limit enc] (loop [cw (CharArrayWriter. (int c/BUF-SZ)) carr (char-array c/BUF-SZ) fo nil cnt 0 c (.read rdr carr)] (if (neg? c) (try (if fo fo (x->chars cw enc)) (finally (klose cw))) (do (if (pos? c) (.write ^Writer cw carr 0 c)) (let [[f w] (if-not (and (nil? fo) (> (+ c cnt) limit)) [fo cw] (swap-chars cw enc))] (recur w carr f (+ c cnt) (.read rdr carr))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn slurpb "Like slurp but reads in bytes." {:arglists '([in] [in enc] [in enc useFile?])} ([in enc] (slurpb in enc false)) ([in] (slurpb in "utf-8")) ([in enc usefile?] (let [[c? i] (input-stream?? in)] (try (slurp-inp i (if usefile? 1 *membuf-limit*) enc) (finally (if c? (klose i))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn slurpc "Like slurp but reads in chars." {:arglists '([in] [in enc] [in enc useFile?])} ([in enc] (slurpc in enc false)) ([in] (slurpc in "utf-8")) ([in enc usefile?] (let [[c? i] (input-stream?? in) _ (assert (c/is? InputStream i) "Expected input-stream!") rdr (InputStreamReader. i)] (try (slurp-rdr rdr (if usefile? 1 *membuf-limit*) enc) (finally (if c? (klose rdr))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn file-read-write? "Is file readable & writable?" {:arglists '([in])} [in] (if-some [^File fp (some-> in (io/file))] (and (.exists fp) (.isFile fp) (.canRead fp) (.canWrite fp)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn file-ok? "If file exists?" {:arglists '([in])} [in] (if-some [^File fp (some-> in (io/file))] (.exists fp))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn file-read? "Is file readable?" {:arglists '([in])} [in] (if-some [^File fp (some-> in (io/file))] (and (.exists fp) (.isFile fp) (.canRead fp)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn dir-read-write? "Is dir readable and writable?" {:arglists '([in])} [in] (if-some [^File dir (some-> in (io/file))] (and (.exists dir) (.isDirectory dir) (.canRead dir) (.canWrite dir)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn dir-read? "Is dir readable?" {:arglists '([in])} [in] (if-some [^File dir (some-> in (io/file))] (and (.exists dir) (.isDirectory dir) (.canRead dir)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn can-exec? "Is file executable?" {:arglists '([in])} [in] (if-some [^File fp (some-> in (io/file))] (and (.exists fp) (.canExecute fp)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn parent-file "Parent file." {:tag File :arglists '([in])} [in] (if-some [^File f (some-> in (io/file))] (.getParentFile f))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn parent-path "Path to parent." {:tag String :arglists '([path])} [path] (if (c/nichts? path) "" (.getParent (io/file path)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-file "Get a file from a directory." {:arglists '([dir fname])} [dir fname] (let [fp (io/file dir fname)] (if (file-read? fp) (XData. fp false)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn spit-file "Save a file to a directory." {:tag File :arglists '([file stuff] [file stuff del?])} ([file stuff] (spit-file file stuff false)) ([file stuff del?] (let [fp (io/file file) ^XData in (if (c/is? XData stuff) stuff (XData. stuff false))] (if del? (fdelete fp) (if (.exists fp) (u/throw-IOE "File %s exists." fp))) (if-not (.isFile in) (io/copy (.getBytes in) fp) (let [opts (c/marray CopyOption 1)] (aset #^"[Ljava.nio.file.CopyOption;" opts 0 StandardCopyOption/REPLACE_EXISTING) (Files/move (.. in fileRef toPath) (.toPath fp) opts) ;;since file has moved, update stuff (.setDeleteFlag in false) (.reset in nil))) fp))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn save-file "Save a file to a directory." {:tag File :arglists '([dir fname stuff] [dir fname stuff del?])} ([dir fname stuff] (save-file dir fname stuff false)) ([dir fname stuff del?] (spit-file (io/file dir fname) stuff del?))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn change-content "Pass file content - as string to the work function, returning new content." {:tag String :arglists '([file work] [file work enc])} ([file work] (change-content file work "utf-8")) ([file work enc] {:pre [(fn? work)]} (if (file-read? file) (work (slurp file :encoding (u/encoding?? enc)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn replace-file! "Update file with new content." {:tag File :arglists '([file work] [file work enc])} ([file work] (replace-file! file work "utf-8")) ([file work enc] {:pre [(fn? work)]} (spit file (change-content file work enc) :encoding (u/encoding?? enc)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn unzip->dir "Unzip zip file to a target folder." {:arglists '([srcZip desDir])} [^File srcZip ^File desDir] (let [z (ZipFile. srcZip) es (.entries z)] (.mkdirs desDir) (while (.hasMoreElements es) (let [^ZipEntry en (.nextElement es) f (io/file desDir (-> (.getName en) (.replaceAll "^[\\/]+" "")))] (if (.isDirectory en) (.mkdirs f) (do (.. f getParentFile mkdirs) (c/wo* [inp (.getInputStream z en)] (io/copy inp f)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mkdirs "Make directories." {:tag File :arglists '([arg])} [arg] (cond (string? arg) (mkdirs (io/file arg)) (c/is? File arg) (doto ^File arg .mkdirs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn list-files "List files with certain extension." {:arglists '([dir ext])} [dir ext] (c/vec-> (.listFiles (io/file dir) (reify FileFilter (accept [_ f] (cs/ends-with? (.getName f) ext)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn list-dirs "List sub-directories." {:arglists '([dir])} [dir] (c/vec-> (.listFiles (io/file dir) (reify FileFilter (accept [_ f] (.isDirectory f)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn list-any-files "List files with certain extension recursively." {:arglists '([dir ext])} [dir ext] (c/do-with-atom [res (atom [])] (let [dir (io/file dir) dig (fn [^File root ext bin func] (doseq [^File f (.listFiles root) :let [fn (.getName f) d? (.isDirectory f)]] (cond d? (func f ext bin func) (cs/ends-with? fn ext) (swap! bin conj f))))] (if (dir-read? dir) (dig dir ext res dig))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn grep-folder-paths "Recurse a dir, pick out dirs that have files of this extension." {:arglists '([rootDir ext])} [rootDir ext] (c/do-with-atom [bin (atom #{})] (let [rootDir (io/file rootDir) rlen (+ 1 (c/n# (u/fpath rootDir))) dig (fn [^File top func] (doseq [^File f (.listFiles top) :let [fn (.getName f) d? (.isDirectory f)]] (cond d? (func f func) (cs/ends-with? fn ext) (let [p (.getParentFile f)] (if-not (c/in? @bin p) (swap! bin conj p))))))] (dig rootDir dig)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- scan-tree "Walk down folder hierarchies." [^Stack stk ext out seed] (if-let [^File top (or seed (.peek stk))] (doseq [^File f (.listFiles top)] (let [p (map #(.getName ^File %) (if-not (.empty stk) (.toArray stk))) fid (.getName f) paths (conj (c/vec-> p) fid)] (if (.isDirectory f) (do (.push stk f) (scan-tree stk ext out nil)) (if (cs/ends-with? fid ext) (swap! out conj (cs/join "/" paths))))))) (when-not (.empty stk) (.pop stk)) out) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn grep-file-paths "Recurse a folder, picking out files with the given extension." {:arglists '([rootDir ext])} [rootDir ext] ;; the stack is used to store the folder hierarchy @(scan-tree (Stack.) ext (atom []) (io/file rootDir))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn basename "Get the name of file without extension." {:arglists '([file])} [file] (let [n (.getName (io/file file)) p (cs/last-index-of n ".")] (if p (subs n 0 p) n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn touch! "Touch a file." {:arglists '([file])} [file] (if-some [f (io/file file)] (if-not (.exists f) (do (.. f getParentFile mkdirs) (c/wo* [o (os* f)])) (when-not (.setLastModified f (u/system-time)) (u/throw-IOE "Unable to set the lastmodtime: %s." f))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn chunk-read-stream "Reads through this data, and for each chunk calls the function." {:arglists '([data cb])} [data cb] (let [b (byte-array c/FourK) [z? ^InputStream inp] (input-stream?? data)] (try (loop [c (if inp (.read inp b) 0) t 0] (if (pos? c) (do (cb b 0 c false) (recur (.read inp b) (long (+ t c)))) (cb b 0 0 true))) (finally (if z? (klose inp)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fmt->edn "Format to EDN." {:tag String :arglists '([obj])} [obj] (let [w (StringWriter.)] (if obj (pp/with-pprint-dispatch in/indent-dispatch (pp/pprint obj w))) (str w))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn read-edn "Parse EDN formatted text." {:arglists '([arg] [arg enc])} ([arg] (read-edn arg "utf-8")) ([arg enc] (if-some [s (x->str arg enc)] (edn/read-string s)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fmt->json "Format to JSON." {:tag String :arglists '([data])} [data] (some-> data js/write-str)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn read-json "Parses JSON." {:arglists '([data] [data enc] [data enc keyfn])} ([data enc] (read-json data enc nil)) ([data] (read-json data "utf-8")) ([data enc keyfn] (if-some [s (x->str data enc)] (if keyfn (js/read-str s :key-fn keyfn) (js/read-str s))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->stream "Load the resource as stream." {:tag InputStream :arglists '([path] [path ldr])} ([path] (res->stream path nil)) ([path ldr] {:pre [(string? path)]} (when-not (empty? path) (-> (u/get-cldr ldr) (.getResourceAsStream ^String path))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->url "Load the resource as URL." {:tag URL :arglists '([path] [path ldr])} ([path] (res->url path nil)) ([path ldr] {:pre [(string? path)]} (when-not (empty? path) (-> (u/get-cldr ldr) (.getResource ^String path))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->str "Load the resource as string." {:tag String :arglists '([path] [path enc] [path enc ldr])} ([path enc] (res->str path enc nil)) ([path] (res->str path "utf-8" nil)) ([path enc ldr] (if-some [r (res->stream path ldr)] (c/wo* [inp r out (baos<> c/BUF-SZ)] (io/copy inp out :buffer-size c/BUF-SZ) (x->str out enc))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->bytes "Load the resource as bytes." {:tag "[B" :arglists '([path][path ldr])} ([path] (res->bytes path nil)) ([path ldr] (if-some [r (res->stream path ldr)] (c/wo* [inp r out (baos<> c/BUF-SZ)] (io/copy inp out :buffer-size c/BUF-SZ) (x->bytes out))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->file "Load the resource and write it to a temp file." {:tag File :arglists '([path] [path ldr])} ([path] (res->file path nil)) ([path ldr] (if-some [r (res->stream path ldr)] (c/do-with [out (temp-file)] (c/wo* [inp r] (io/copy inp out :buffer-size c/BUF-SZ)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn delete-dir "Deleting recursively a directory with native Java. https://docs.oracle.com/javase/tutorial/essential/io/walk.html" {:arglists '([dir])} [dir] (if-some [root (Paths/get (-> dir io/file .toURI))] (Files/walkFileTree root (proxy [SimpleFileVisitor][] (visitFile [^Path file ^BasicFileAttributes attrs] (Files/delete file) FileVisitResult/CONTINUE) (postVisitDirectory [^Path dir ^IOException ex] (Files/delete dir) FileVisitResult/CONTINUE))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn clean-dir "Clean out recursively a directory with native Java. https://docs.oracle.com/javase/tutorial/essential/io/walk.html" {:arglists '([dir])} [dir] (if-some [root (Paths/get (-> dir io/file .toURI))] (Files/walkFileTree root (proxy [SimpleFileVisitor][] (visitFile [^Path file ^BasicFileAttributes attrs] (Files/delete file) FileVisitResult/CONTINUE) (postVisitDirectory [^Path dir ^IOException ex] (if (not= dir root) (Files/delete dir)) FileVisitResult/CONTINUE))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn cmenu "A console menu, prompting a sequence of questions via console." {:arglists '([cmdQs q1])} [cmdQs q1] {:pre [(map? cmdQs)]} (letfn [(read-data [^Reader in] (let [[ms bf] (loop [c (.read in) bf (c/sbf<>)] (let [m (cond (or (== c 4) (== c -1)) #{:quit :break} (== c (int \newline)) #{:break} (c/or?? [== c] 27 (int \return) (int \backspace)) nil :else (c/do->nil (c/sbf+ bf (char c))))] (if (c/in? m :break) [m bf] (recur (.read in) bf))))] (if-not (c/in? ms :quit) (c/strim (str bf))))) (on-answer [^Writer cout answer props {:keys [result id must? default next]}] (if (nil? answer) (c/do->nil (.write cout "\n")) (let [rc (c/stror answer default)] (cond (and must? (c/nichts? rc)) id ;no answer, loop try again (keyword? result) (do (swap! props assoc result rc) next) (fn? result) (let [[nxt p] (result rc @props)] (reset! props p) (or nxt ::caio!!)) :else ::caio!!)))) (popQ [^Writer cout ^Reader cin props {:as Q :keys [must? choices default question]}] (if (nil? Q) ::caio!! (do (.write cout (str question (if must? "*") "? ")) (if (c/hgl? choices) (.write cout (str "[" choices "]"))) (if (c/hgl? default) (.write cout (str "(" default ")"))) (doto cout (.write " ") .flush) ;; get the input from user, return the next question (-> (read-data cin) (on-answer cout props Q))))) (cycleQ [cout cin cmdQs start props] (loop [rc (popQ cout cin props (cmdQs start))] (cond (nil? rc) {} (= ::caio!! rc) @props :else (recur (popQ cout cin props (cmdQs rc))))))] (let [cout (-> System/out BufferedOutputStream. OutputStreamWriter.) func (->> System/in InputStreamReader. (partial cycleQ cout))] (.write cout (str ">>> Press " "<ctrl-c> or <ctrl-d>" "<Enter> to cancel...\n")) (-> #(update-in %1 [%2] assoc :id %2) (reduce cmdQs (keys cmdQs)) (func q1 (atom {})))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #_ (def sample {:q1 {:question "hello <NAME>" :choices "q|b|c" :default "c" :must? true :result :a1 :next :q2} :q2 {:question "hello <NAME>" :result :a2 :next :q3} :q3 {:question "hello <NAME>" :choices "2" :result (fn [answer result] [nil (assoc result :zzz answer)])}}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
true
;; 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. ;; ;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved. (ns czlab.basal.io "Useful additions to clojure io." (:require [clojure.edn :as edn] [clojure.pprint :as pp] [clojure.string :as cs] [czlab.basal.util :as u] [czlab.basal.core :as c] [clojure.java.io :as io] [clojure.data.json :as js] [czlab.basal.indent :as in]) (:import [java.nio.file CopyOption Files Path Paths FileVisitResult SimpleFileVisitor StandardCopyOption] [java.util.zip GZIPInputStream GZIPOutputStream] [java.nio ByteBuffer CharBuffer] [czlab.basal XData] [java.util Arrays Base64 Base64$Decoder Base64$Encoder] [java.util.zip ZipFile ZipEntry] [java.util Stack] [java.net URI URL] [org.xml.sax InputSource] [java.io DataInputStream DataOutputStream FileInputStream FileOutputStream CharArrayWriter StringWriter FileFilter File InputStream Closeable OutputStream Reader Writer IOException InputStreamReader OutputStreamWriter BufferedOutputStream ByteArrayInputStream ByteArrayOutputStream] [java.nio.file.attribute BasicFileAttributes])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) (def ^:dynamic *membuf-limit* (* 4 c/MegaBytes)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/defmacro- os* [x] `(clojure.java.io/output-stream ~x)) (c/defmacro- is* [x] `(clojure.java.io/input-stream ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro istream "Same as clojure.java.io's input-stream." {:arglists '([x])} [x] `(clojure.java.io/input-stream ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro ostream "Same as clojure.java.io's output-stream." {:arglists '([x])} [x] `(clojure.java.io/output-stream ~x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro file? "Is this a file?" {:arglists '([in])} [in] `(instance? java.io.File ~in)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro slurp-utf8 "Read f with utf8 encoding." {:arglists '([f])} [f] `(slurp ~f :encoding "utf-8")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro spit-utf8 "Write f with utf8 encoding." {:arglists '([f c])} [f c] `(spit ~f (str ~c) :encoding "utf-8")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn file-repo "Java's system temporary folder." {:arglists '([])} [] (io/file (u/sys-tmp-dir))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn baos<> "Make a byte array output stream." {:arglists '([][size]) :tag ByteArrayOutputStream} ([] (baos<> nil)) ([size] (ByteArrayOutputStream. (int (c/num?? size c/BUF-SZ))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fsize "Get length of file." {:arglists '([in])} [in] (some-> in io/file .length)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fname "Get name of file." {:tag String :arglists '([in])} [in] (some-> in io/file .getName)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn klose "Close object (quietly)." {:arglists '([obj])} [obj] (c/try! (some-> (c/cast? Closeable obj) .close))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn copy "Copy certain number of bytes to output." {:arglists '([in out] [in out count])} ([in out] (copy in out -1)) ([in out kount] {:pre [(number? kount)]} (if (neg? kount) (io/copy in out) (let [[di? ^InputStream is] (if (c/is? InputStream in) [false in] [true (is* in)]) [do? ^OutputStream os] (if (c/is? OutputStream out) [false out] [true (os* out)])] (try (loop [remain kount total 0 buf (byte-array c/BUF-SZ)] (let [len (if (< remain c/BUF-SZ) remain c/BUF-SZ) n (if-not (pos? len) -1 (.read is buf 0 len))] (if (neg? n) nil ;to be consistent with io/copy (do (if (pos? n) (.write os buf 0 n)) (recur (long (- remain n)) (long (+ total n)) buf))))) (finally (if di? (klose is)) (if do? (klose os)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->bytes "Convert almost anything to byte[]." {:tag "[B" :arglists '([in][in enc])} ([in] (x->bytes in "utf-8")) ([in enc] (cond (c/is? u/CSCZ in) (let [^ByteBuffer bb (.encode (u/charset?? enc) (CharBuffer/wrap ^chars in))] (Arrays/copyOfRange (.array bb) (.position bb) (.limit bb))) (c/is? StringBuilder in) (x->bytes (.toString ^Object in) enc) (string? in) (.getBytes ^String in (u/encoding?? enc)) (or (nil? in) (bytes? in)) in (c/is? XData in) (.getBytes ^XData in) (c/is? ByteArrayOutputStream in) (.toByteArray ^ByteArrayOutputStream in) :else (let [os (baos<>)] (io/copy in os) (.toByteArray os))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->chars "Convert almost anything to char[]." {:tag "[C" :arglists '([in][in enc])} ([in] (x->chars in "utf-8")) ([in enc] (cond (c/is? CharArrayWriter in) (.toCharArray ^CharArrayWriter in) (or (nil? in) (c/is? u/CSCZ in)) in (c/is? StringBuilder in) (x->chars (.toString ^Object in)) (string? in) (.toCharArray ^String in) (c/is? XData in) (x->chars (.getBytes ^XData in)) (bytes? in) (->> (u/encoding?? enc) (String. ^bytes in) .toCharArray) (c/is? ByteArrayOutputStream in) (x->chars (.toByteArray ^ByteArrayOutputStream in) enc) :else (let [os (baos<>)] (io/copy in os) (x->chars (.toByteArray os) enc))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->str "Convert almost anything to String." {:tag String :arglists '([in][in enc])} ([in] (x->str in "utf-8")) ([in enc] (cond (or (nil? in) (string? in)) in (bytes? in) (String. ^bytes in ^String enc) (c/is? InputStream in) (x->str (let [os (baos<>)] (io/copy in os) os)) (c/is? File in) (slurp in :encoding enc) (c/is? XData in) (.strit ^XData in) (c/is? StringBuilder in) (.toString ^Object in) (c/is? ByteArrayOutputStream in) (String. (.toByteArray ^ByteArrayOutputStream in) ^String enc) :else (String. (x->chars in enc))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn read-number "Deserialize a number." {:tag Number :arglists '([in numType])} [in numType] {:pre [(class? numType)]} (c/wo* [dis (DataInputStream. (is* in))] (cond (or (= numType Double) (= numType Double/TYPE)) (.readDouble dis) (or (= numType Float) (= numType Float/TYPE)) (.readFloat dis) (or (= numType Integer) (= numType Integer/TYPE)) (.readInt dis) (or (= numType Long) (= numType Long/TYPE)) (.readLong dis) :else (u/throw-BadData "Unsupported number type %s." numType)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn write-number "Serialize a number." {:tag "[B" :arglists '([nnum])} [nnum] {:pre [(number? nnum)]} (c/wo* [baos (baos<>) dos (DataOutputStream. baos)] (let [numType (class nnum)] (cond (or (= numType Double) (= numType Double/TYPE)) (.writeDouble dos (double nnum)) (or (= numType Float) (= numType Float/TYPE)) (.writeFloat dos (float nnum)) (or (= numType Integer) (= numType Integer/TYPE)) (.writeInt dos (int nnum)) (or (= numType Long) (= numType Long/TYPE)) (.writeLong dos (long nnum)) :else (u/throw-BadData "Unsupported number type %s." numType)) (.flush dos) (.toByteArray baos)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fdelete "Delete file (quietly)." {:arglists '([f])} [f] (c/try! (if (c/is? File f) (io/delete-file f true)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn bytes->hex "Bytes into hex-chars." {:tag "[C" :arglists '([in])} [in] (let [b' (x->bytes in) len (if (nil? b') 0 (* 2 (alength b')))] (loop [k 0 pos 0 out (char-array len)] (if (>= pos len) (if (nil? in) nil out) (let [n (bit-and (aget b' k) 0xff)] (aset-char out ;; high 4 bits pos (aget ^chars c/hex-chars (unsigned-bit-shift-right n 4))) (aset-char out ;; low 4 bits (+ pos 1) (aget ^chars c/hex-chars (bit-and n 0xf))) (recur (+ 1 k) (+ 2 pos) out)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hexify "Turn bytes into hex string." {:tag String :arglists '([in])} [in] (some-> in bytes->hex x->str)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gzip "Gzip input." {:tag "[B" :arglists '([in])} [in] (if-some [b (x->bytes in)] (with-open [baos (baos<>) g (GZIPOutputStream. baos)] (.write g b 0 (alength b)) (.finish g) (.toByteArray baos)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gunzip "Gunzip input." {:tag "[B" :arglists '([in])} [in] (if-some [b (x->bytes in)] (with-open [inp (GZIPInputStream. (io/input-stream b))] (x->bytes inp)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn reset-stream! "Reset stream (safely)." {:arglists '([in])} [in] (if-some [inp (c/cast? InputStream in)] (c/try! (.reset inp))) in) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn input-stream?? "Returns a tuple [you-close? stream]." {:arglists '([arg] [arg enc])} ([arg] (input-stream?? arg "utf-8")) ([arg enc] (cond (or (bytes? arg) (c/is? URL arg) (c/is? File arg)) [true (io/input-stream arg)] (c/is? ByteArrayOutputStream arg) (input-stream?? (x->bytes arg)) (c/is? u/CSCZ arg) (input-stream?? (x->bytes arg enc)) (or (nil? arg) (c/is? InputStream arg)) [false arg] (string? arg) (if (cs/starts-with? arg "file:") (input-stream?? (io/as-url arg)) (input-stream?? (x->bytes arg enc)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn gzb64->bytes "Unzip content which is base64 encoded + gziped." {:tag "[B" :arglists '([in])} [in] (some->> in x->str (.decode (Base64/getDecoder)) gunzip)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn bytes->gzb64 "Zip content and then base64 encode it." {:tag String :arglists '([in])} [in] (some->> (some-> in x->bytes gzip) (.encodeToString (Base64/getEncoder)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn readable-bytes "Get the available bytes in this stream." {:tag Integer :arglists '([in][in enc])} ([in] (readable-bytes in "utf-8")) ([in enc] (cond (c/is? InputStream in) (.available ^InputStream in) (c/is? File in) (.length (c/cast? File in)) (c/is? URL in) (c/wo* [i (is* in)] (readable-bytes i enc)) (string? in) (readable-bytes (x->bytes in enc) enc) (bytes? in) (alength ^bytes in) (c/is? u/CSCZ in) (readable-bytes (x->bytes in enc) enc) :else 0))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn tmpfile "Create f in temp dir." {:tag File :arglists '([f])} [f] (->> (if-not (c/is? File f) (str f) (.getName ^File f)) (io/file (file-repo)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn temp-file "Create a temporary file." {:tag File :arglists '([] [pfx sux] [pfx sux dir])} ([] (temp-file nil nil)) ([pfx sux] (temp-file pfx sux (file-repo))) ([pfx sux dir] (c/do-with [f (File/createTempFile (c/stror pfx "czlab") (c/stror sux ".tmp") (io/file dir))] (fdelete f)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn open-temp-file "A Tuple(2) [File, OutputStream?]." {:arglists '([] [pfx sux] [pfx sux dir])} ([] (open-temp-file nil nil)) ([pfx sux] (open-temp-file pfx sux (file-repo))) ([pfx sux dir] (let [fp (temp-file pfx sux dir)] [fp (os* fp)]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn x->file "Copy content to a temp file." {:tag File :arglists '([in][in fout])} ([in] (x->file in nil)) ([in fout] (let [fp (or fout (temp-file))] (c/pre (c/is? File fp)) (try (io/copy in fp) fp (catch Throwable _ (if (nil? fout) (fdelete fp)) nil))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn reset-source! "Reset an input source." {:arglists '([in])} [in] (if-some [src (c/cast? InputSource in)] (let [ism (.getByteStream src) rdr (.getCharacterStream src)] (c/try! (some-> ism .reset)) (c/try! (some-> rdr .reset)))) in) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- swap-bytes "Swap bytes in buffer to file." [baos enc] (let [[f ^OutputStream os :as rc] (open-temp-file)] (doto os (.write (x->bytes baos enc)) .flush) (klose baos) rc)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- swap-chars "Swap chars in writer to file." [wtr enc] (let [[fp ^OutputStream out] (open-temp-file) w (OutputStreamWriter. out (u/encoding?? enc))] (doto w (.write (x->chars wtr enc)) .flush) (klose wtr) [fp w])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- slurp-inp [^InputStream inp limit enc] (loop [bits (byte-array c/BUF-SZ) os (baos<>) fo nil cnt 0 c (.read inp bits)] (if (neg? c) (try (if fo fo (x->bytes os enc)) (finally (klose os))) (do (if (pos? c) (.write ^OutputStream os bits 0 c)) (let [[f o'] (if-not (and (nil? fo) (> (+ c cnt) limit)) [fo os] (swap-bytes os enc))] (recur bits o' f (+ c cnt) (.read inp bits))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- slurp-rdr [^Reader rdr limit enc] (loop [cw (CharArrayWriter. (int c/BUF-SZ)) carr (char-array c/BUF-SZ) fo nil cnt 0 c (.read rdr carr)] (if (neg? c) (try (if fo fo (x->chars cw enc)) (finally (klose cw))) (do (if (pos? c) (.write ^Writer cw carr 0 c)) (let [[f w] (if-not (and (nil? fo) (> (+ c cnt) limit)) [fo cw] (swap-chars cw enc))] (recur w carr f (+ c cnt) (.read rdr carr))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn slurpb "Like slurp but reads in bytes." {:arglists '([in] [in enc] [in enc useFile?])} ([in enc] (slurpb in enc false)) ([in] (slurpb in "utf-8")) ([in enc usefile?] (let [[c? i] (input-stream?? in)] (try (slurp-inp i (if usefile? 1 *membuf-limit*) enc) (finally (if c? (klose i))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn slurpc "Like slurp but reads in chars." {:arglists '([in] [in enc] [in enc useFile?])} ([in enc] (slurpc in enc false)) ([in] (slurpc in "utf-8")) ([in enc usefile?] (let [[c? i] (input-stream?? in) _ (assert (c/is? InputStream i) "Expected input-stream!") rdr (InputStreamReader. i)] (try (slurp-rdr rdr (if usefile? 1 *membuf-limit*) enc) (finally (if c? (klose rdr))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn file-read-write? "Is file readable & writable?" {:arglists '([in])} [in] (if-some [^File fp (some-> in (io/file))] (and (.exists fp) (.isFile fp) (.canRead fp) (.canWrite fp)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn file-ok? "If file exists?" {:arglists '([in])} [in] (if-some [^File fp (some-> in (io/file))] (.exists fp))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn file-read? "Is file readable?" {:arglists '([in])} [in] (if-some [^File fp (some-> in (io/file))] (and (.exists fp) (.isFile fp) (.canRead fp)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn dir-read-write? "Is dir readable and writable?" {:arglists '([in])} [in] (if-some [^File dir (some-> in (io/file))] (and (.exists dir) (.isDirectory dir) (.canRead dir) (.canWrite dir)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn dir-read? "Is dir readable?" {:arglists '([in])} [in] (if-some [^File dir (some-> in (io/file))] (and (.exists dir) (.isDirectory dir) (.canRead dir)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn can-exec? "Is file executable?" {:arglists '([in])} [in] (if-some [^File fp (some-> in (io/file))] (and (.exists fp) (.canExecute fp)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn parent-file "Parent file." {:tag File :arglists '([in])} [in] (if-some [^File f (some-> in (io/file))] (.getParentFile f))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn parent-path "Path to parent." {:tag String :arglists '([path])} [path] (if (c/nichts? path) "" (.getParent (io/file path)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn get-file "Get a file from a directory." {:arglists '([dir fname])} [dir fname] (let [fp (io/file dir fname)] (if (file-read? fp) (XData. fp false)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn spit-file "Save a file to a directory." {:tag File :arglists '([file stuff] [file stuff del?])} ([file stuff] (spit-file file stuff false)) ([file stuff del?] (let [fp (io/file file) ^XData in (if (c/is? XData stuff) stuff (XData. stuff false))] (if del? (fdelete fp) (if (.exists fp) (u/throw-IOE "File %s exists." fp))) (if-not (.isFile in) (io/copy (.getBytes in) fp) (let [opts (c/marray CopyOption 1)] (aset #^"[Ljava.nio.file.CopyOption;" opts 0 StandardCopyOption/REPLACE_EXISTING) (Files/move (.. in fileRef toPath) (.toPath fp) opts) ;;since file has moved, update stuff (.setDeleteFlag in false) (.reset in nil))) fp))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn save-file "Save a file to a directory." {:tag File :arglists '([dir fname stuff] [dir fname stuff del?])} ([dir fname stuff] (save-file dir fname stuff false)) ([dir fname stuff del?] (spit-file (io/file dir fname) stuff del?))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn change-content "Pass file content - as string to the work function, returning new content." {:tag String :arglists '([file work] [file work enc])} ([file work] (change-content file work "utf-8")) ([file work enc] {:pre [(fn? work)]} (if (file-read? file) (work (slurp file :encoding (u/encoding?? enc)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn replace-file! "Update file with new content." {:tag File :arglists '([file work] [file work enc])} ([file work] (replace-file! file work "utf-8")) ([file work enc] {:pre [(fn? work)]} (spit file (change-content file work enc) :encoding (u/encoding?? enc)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn unzip->dir "Unzip zip file to a target folder." {:arglists '([srcZip desDir])} [^File srcZip ^File desDir] (let [z (ZipFile. srcZip) es (.entries z)] (.mkdirs desDir) (while (.hasMoreElements es) (let [^ZipEntry en (.nextElement es) f (io/file desDir (-> (.getName en) (.replaceAll "^[\\/]+" "")))] (if (.isDirectory en) (.mkdirs f) (do (.. f getParentFile mkdirs) (c/wo* [inp (.getInputStream z en)] (io/copy inp f)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mkdirs "Make directories." {:tag File :arglists '([arg])} [arg] (cond (string? arg) (mkdirs (io/file arg)) (c/is? File arg) (doto ^File arg .mkdirs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn list-files "List files with certain extension." {:arglists '([dir ext])} [dir ext] (c/vec-> (.listFiles (io/file dir) (reify FileFilter (accept [_ f] (cs/ends-with? (.getName f) ext)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn list-dirs "List sub-directories." {:arglists '([dir])} [dir] (c/vec-> (.listFiles (io/file dir) (reify FileFilter (accept [_ f] (.isDirectory f)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn list-any-files "List files with certain extension recursively." {:arglists '([dir ext])} [dir ext] (c/do-with-atom [res (atom [])] (let [dir (io/file dir) dig (fn [^File root ext bin func] (doseq [^File f (.listFiles root) :let [fn (.getName f) d? (.isDirectory f)]] (cond d? (func f ext bin func) (cs/ends-with? fn ext) (swap! bin conj f))))] (if (dir-read? dir) (dig dir ext res dig))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn grep-folder-paths "Recurse a dir, pick out dirs that have files of this extension." {:arglists '([rootDir ext])} [rootDir ext] (c/do-with-atom [bin (atom #{})] (let [rootDir (io/file rootDir) rlen (+ 1 (c/n# (u/fpath rootDir))) dig (fn [^File top func] (doseq [^File f (.listFiles top) :let [fn (.getName f) d? (.isDirectory f)]] (cond d? (func f func) (cs/ends-with? fn ext) (let [p (.getParentFile f)] (if-not (c/in? @bin p) (swap! bin conj p))))))] (dig rootDir dig)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- scan-tree "Walk down folder hierarchies." [^Stack stk ext out seed] (if-let [^File top (or seed (.peek stk))] (doseq [^File f (.listFiles top)] (let [p (map #(.getName ^File %) (if-not (.empty stk) (.toArray stk))) fid (.getName f) paths (conj (c/vec-> p) fid)] (if (.isDirectory f) (do (.push stk f) (scan-tree stk ext out nil)) (if (cs/ends-with? fid ext) (swap! out conj (cs/join "/" paths))))))) (when-not (.empty stk) (.pop stk)) out) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn grep-file-paths "Recurse a folder, picking out files with the given extension." {:arglists '([rootDir ext])} [rootDir ext] ;; the stack is used to store the folder hierarchy @(scan-tree (Stack.) ext (atom []) (io/file rootDir))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn basename "Get the name of file without extension." {:arglists '([file])} [file] (let [n (.getName (io/file file)) p (cs/last-index-of n ".")] (if p (subs n 0 p) n))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn touch! "Touch a file." {:arglists '([file])} [file] (if-some [f (io/file file)] (if-not (.exists f) (do (.. f getParentFile mkdirs) (c/wo* [o (os* f)])) (when-not (.setLastModified f (u/system-time)) (u/throw-IOE "Unable to set the lastmodtime: %s." f))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn chunk-read-stream "Reads through this data, and for each chunk calls the function." {:arglists '([data cb])} [data cb] (let [b (byte-array c/FourK) [z? ^InputStream inp] (input-stream?? data)] (try (loop [c (if inp (.read inp b) 0) t 0] (if (pos? c) (do (cb b 0 c false) (recur (.read inp b) (long (+ t c)))) (cb b 0 0 true))) (finally (if z? (klose inp)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fmt->edn "Format to EDN." {:tag String :arglists '([obj])} [obj] (let [w (StringWriter.)] (if obj (pp/with-pprint-dispatch in/indent-dispatch (pp/pprint obj w))) (str w))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn read-edn "Parse EDN formatted text." {:arglists '([arg] [arg enc])} ([arg] (read-edn arg "utf-8")) ([arg enc] (if-some [s (x->str arg enc)] (edn/read-string s)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fmt->json "Format to JSON." {:tag String :arglists '([data])} [data] (some-> data js/write-str)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn read-json "Parses JSON." {:arglists '([data] [data enc] [data enc keyfn])} ([data enc] (read-json data enc nil)) ([data] (read-json data "utf-8")) ([data enc keyfn] (if-some [s (x->str data enc)] (if keyfn (js/read-str s :key-fn keyfn) (js/read-str s))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->stream "Load the resource as stream." {:tag InputStream :arglists '([path] [path ldr])} ([path] (res->stream path nil)) ([path ldr] {:pre [(string? path)]} (when-not (empty? path) (-> (u/get-cldr ldr) (.getResourceAsStream ^String path))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->url "Load the resource as URL." {:tag URL :arglists '([path] [path ldr])} ([path] (res->url path nil)) ([path ldr] {:pre [(string? path)]} (when-not (empty? path) (-> (u/get-cldr ldr) (.getResource ^String path))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->str "Load the resource as string." {:tag String :arglists '([path] [path enc] [path enc ldr])} ([path enc] (res->str path enc nil)) ([path] (res->str path "utf-8" nil)) ([path enc ldr] (if-some [r (res->stream path ldr)] (c/wo* [inp r out (baos<> c/BUF-SZ)] (io/copy inp out :buffer-size c/BUF-SZ) (x->str out enc))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->bytes "Load the resource as bytes." {:tag "[B" :arglists '([path][path ldr])} ([path] (res->bytes path nil)) ([path ldr] (if-some [r (res->stream path ldr)] (c/wo* [inp r out (baos<> c/BUF-SZ)] (io/copy inp out :buffer-size c/BUF-SZ) (x->bytes out))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn res->file "Load the resource and write it to a temp file." {:tag File :arglists '([path] [path ldr])} ([path] (res->file path nil)) ([path ldr] (if-some [r (res->stream path ldr)] (c/do-with [out (temp-file)] (c/wo* [inp r] (io/copy inp out :buffer-size c/BUF-SZ)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn delete-dir "Deleting recursively a directory with native Java. https://docs.oracle.com/javase/tutorial/essential/io/walk.html" {:arglists '([dir])} [dir] (if-some [root (Paths/get (-> dir io/file .toURI))] (Files/walkFileTree root (proxy [SimpleFileVisitor][] (visitFile [^Path file ^BasicFileAttributes attrs] (Files/delete file) FileVisitResult/CONTINUE) (postVisitDirectory [^Path dir ^IOException ex] (Files/delete dir) FileVisitResult/CONTINUE))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn clean-dir "Clean out recursively a directory with native Java. https://docs.oracle.com/javase/tutorial/essential/io/walk.html" {:arglists '([dir])} [dir] (if-some [root (Paths/get (-> dir io/file .toURI))] (Files/walkFileTree root (proxy [SimpleFileVisitor][] (visitFile [^Path file ^BasicFileAttributes attrs] (Files/delete file) FileVisitResult/CONTINUE) (postVisitDirectory [^Path dir ^IOException ex] (if (not= dir root) (Files/delete dir)) FileVisitResult/CONTINUE))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn cmenu "A console menu, prompting a sequence of questions via console." {:arglists '([cmdQs q1])} [cmdQs q1] {:pre [(map? cmdQs)]} (letfn [(read-data [^Reader in] (let [[ms bf] (loop [c (.read in) bf (c/sbf<>)] (let [m (cond (or (== c 4) (== c -1)) #{:quit :break} (== c (int \newline)) #{:break} (c/or?? [== c] 27 (int \return) (int \backspace)) nil :else (c/do->nil (c/sbf+ bf (char c))))] (if (c/in? m :break) [m bf] (recur (.read in) bf))))] (if-not (c/in? ms :quit) (c/strim (str bf))))) (on-answer [^Writer cout answer props {:keys [result id must? default next]}] (if (nil? answer) (c/do->nil (.write cout "\n")) (let [rc (c/stror answer default)] (cond (and must? (c/nichts? rc)) id ;no answer, loop try again (keyword? result) (do (swap! props assoc result rc) next) (fn? result) (let [[nxt p] (result rc @props)] (reset! props p) (or nxt ::caio!!)) :else ::caio!!)))) (popQ [^Writer cout ^Reader cin props {:as Q :keys [must? choices default question]}] (if (nil? Q) ::caio!! (do (.write cout (str question (if must? "*") "? ")) (if (c/hgl? choices) (.write cout (str "[" choices "]"))) (if (c/hgl? default) (.write cout (str "(" default ")"))) (doto cout (.write " ") .flush) ;; get the input from user, return the next question (-> (read-data cin) (on-answer cout props Q))))) (cycleQ [cout cin cmdQs start props] (loop [rc (popQ cout cin props (cmdQs start))] (cond (nil? rc) {} (= ::caio!! rc) @props :else (recur (popQ cout cin props (cmdQs rc))))))] (let [cout (-> System/out BufferedOutputStream. OutputStreamWriter.) func (->> System/in InputStreamReader. (partial cycleQ cout))] (.write cout (str ">>> Press " "<ctrl-c> or <ctrl-d>" "<Enter> to cancel...\n")) (-> #(update-in %1 [%2] assoc :id %2) (reduce cmdQs (keys cmdQs)) (func q1 (atom {})))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #_ (def sample {:q1 {:question "hello PI:NAME:<NAME>END_PI" :choices "q|b|c" :default "c" :must? true :result :a1 :next :q2} :q2 {:question "hello PI:NAME:<NAME>END_PI" :result :a2 :next :q3} :q3 {:question "hello PI:NAME:<NAME>END_PI" :choices "2" :result (fn [answer result] [nil (assoc result :zzz answer)])}}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": "ameters\n\n id 1\n source-key \"claronte:test:source\"\n backup-key \"claronte:test:backup\"\n ", "end": 477, "score": 0.9985193014144897, "start": 457, "tag": "KEY", "value": "claronte:test:source" }, { "context": "ey \"claronte:test:source\"\n backup-key \"claronte:test:backup\"\n message \"foo\"\n\n _ (car/wc", "end": 523, "score": 0.9984801411628723, "start": 503, "tag": "KEY", "value": "claronte:test:backup" }, { "context": "ameters\n\n id 1\n source-key \"claronte:test:source\"\n backup-key \"claronte:test:backup\"\n ", "end": 1534, "score": 0.9984211325645447, "start": 1514, "tag": "KEY", "value": "claronte:test:source" }, { "context": "ey \"claronte:test:source\"\n backup-key \"claronte:test:backup\"\n message \"bar\"\n\n _ (car/wc", "end": 1580, "score": 0.9986414909362793, "start": 1560, "tag": "KEY", "value": "claronte:test:backup" } ]
test/claronte/transport/fetcher/redis/fetcher_test.clj
jordillonch/claronte
1
(ns claronte.transport.fetcher.redis.fetcher-test (:require [clojure.test :refer :all] [taoensso.carmine :as car :refer (wcar)] [claronte.config.claronte-config :refer :all] [claronte.transport.fetcher.redis.fetcher :refer :all])) (deftest fetch-and-confirm-one-message-test (testing (let [redis-server-connection-parameters fetcher-redis-server-connection-parameters id 1 source-key "claronte:test:source" backup-key "claronte:test:backup" message "foo" _ (car/wcar redis-server-connection-parameters (car/rpush source-key message)) redis-fetcher (->RedisFetcher id redis-server-connection-parameters source-key backup-key) ; fetch message message-fetched (.fetch-one-message redis-fetcher) message-backed-up (car/wcar redis-server-connection-parameters (car/lrange backup-key 0 0)) ; confirm message _ (.confirm-message redis-fetcher) backup-message-list-len-after-confirm (car/wcar redis-server-connection-parameters (car/llen backup-key)) ] (is (= message message-fetched)) (is (= message (first message-backed-up))) (is (zero? backup-message-list-len-after-confirm)) ) )) (deftest fetch-and-rollback-one-message-test (testing (let [redis-server-connection-parameters fetcher-redis-server-connection-parameters id 1 source-key "claronte:test:source" backup-key "claronte:test:backup" message "bar" _ (car/wcar redis-server-connection-parameters (car/rpush source-key message)) redis-fetcher (->RedisFetcher id redis-server-connection-parameters source-key backup-key) ; fetch message message-fetched (.fetch-one-message redis-fetcher) ; rollback message message-rolledback (.rollback-message redis-fetcher) message-in-the-source-key-after-rollback (car/wcar redis-server-connection-parameters (car/lrange source-key 0 0)) backup-message-list-len-after-rollback (car/wcar redis-server-connection-parameters (car/llen backup-key)) ; cleanup _ (car/wcar redis-server-connection-parameters (car/del source-key)) ] (is (= message message-fetched)) (is (= message message-rolledback)) (is (= message (first message-in-the-source-key-after-rollback))) (is (zero? backup-message-list-len-after-rollback)) ) ))
56035
(ns claronte.transport.fetcher.redis.fetcher-test (:require [clojure.test :refer :all] [taoensso.carmine :as car :refer (wcar)] [claronte.config.claronte-config :refer :all] [claronte.transport.fetcher.redis.fetcher :refer :all])) (deftest fetch-and-confirm-one-message-test (testing (let [redis-server-connection-parameters fetcher-redis-server-connection-parameters id 1 source-key "<KEY>" backup-key "<KEY>" message "foo" _ (car/wcar redis-server-connection-parameters (car/rpush source-key message)) redis-fetcher (->RedisFetcher id redis-server-connection-parameters source-key backup-key) ; fetch message message-fetched (.fetch-one-message redis-fetcher) message-backed-up (car/wcar redis-server-connection-parameters (car/lrange backup-key 0 0)) ; confirm message _ (.confirm-message redis-fetcher) backup-message-list-len-after-confirm (car/wcar redis-server-connection-parameters (car/llen backup-key)) ] (is (= message message-fetched)) (is (= message (first message-backed-up))) (is (zero? backup-message-list-len-after-confirm)) ) )) (deftest fetch-and-rollback-one-message-test (testing (let [redis-server-connection-parameters fetcher-redis-server-connection-parameters id 1 source-key "<KEY>" backup-key "<KEY>" message "bar" _ (car/wcar redis-server-connection-parameters (car/rpush source-key message)) redis-fetcher (->RedisFetcher id redis-server-connection-parameters source-key backup-key) ; fetch message message-fetched (.fetch-one-message redis-fetcher) ; rollback message message-rolledback (.rollback-message redis-fetcher) message-in-the-source-key-after-rollback (car/wcar redis-server-connection-parameters (car/lrange source-key 0 0)) backup-message-list-len-after-rollback (car/wcar redis-server-connection-parameters (car/llen backup-key)) ; cleanup _ (car/wcar redis-server-connection-parameters (car/del source-key)) ] (is (= message message-fetched)) (is (= message message-rolledback)) (is (= message (first message-in-the-source-key-after-rollback))) (is (zero? backup-message-list-len-after-rollback)) ) ))
true
(ns claronte.transport.fetcher.redis.fetcher-test (:require [clojure.test :refer :all] [taoensso.carmine :as car :refer (wcar)] [claronte.config.claronte-config :refer :all] [claronte.transport.fetcher.redis.fetcher :refer :all])) (deftest fetch-and-confirm-one-message-test (testing (let [redis-server-connection-parameters fetcher-redis-server-connection-parameters id 1 source-key "PI:KEY:<KEY>END_PI" backup-key "PI:KEY:<KEY>END_PI" message "foo" _ (car/wcar redis-server-connection-parameters (car/rpush source-key message)) redis-fetcher (->RedisFetcher id redis-server-connection-parameters source-key backup-key) ; fetch message message-fetched (.fetch-one-message redis-fetcher) message-backed-up (car/wcar redis-server-connection-parameters (car/lrange backup-key 0 0)) ; confirm message _ (.confirm-message redis-fetcher) backup-message-list-len-after-confirm (car/wcar redis-server-connection-parameters (car/llen backup-key)) ] (is (= message message-fetched)) (is (= message (first message-backed-up))) (is (zero? backup-message-list-len-after-confirm)) ) )) (deftest fetch-and-rollback-one-message-test (testing (let [redis-server-connection-parameters fetcher-redis-server-connection-parameters id 1 source-key "PI:KEY:<KEY>END_PI" backup-key "PI:KEY:<KEY>END_PI" message "bar" _ (car/wcar redis-server-connection-parameters (car/rpush source-key message)) redis-fetcher (->RedisFetcher id redis-server-connection-parameters source-key backup-key) ; fetch message message-fetched (.fetch-one-message redis-fetcher) ; rollback message message-rolledback (.rollback-message redis-fetcher) message-in-the-source-key-after-rollback (car/wcar redis-server-connection-parameters (car/lrange source-key 0 0)) backup-message-list-len-after-rollback (car/wcar redis-server-connection-parameters (car/llen backup-key)) ; cleanup _ (car/wcar redis-server-connection-parameters (car/del source-key)) ] (is (= message message-fetched)) (is (= message message-rolledback)) (is (= message (first message-in-the-source-key-after-rollback))) (is (zero? backup-message-list-len-after-rollback)) ) ))
[ { "context": "ns 'Transfer from xx2181 NetBank'\"\n (is (= [\"stuart\" [\"contribution\"]] (jja/classify \"savings\" \"Trans", "end": 664, "score": 0.5846269130706787, "start": 660, "tag": "NAME", "value": "uart" }, { "context": "and the description mentions Alanna\"\n (is (= [\"alanna\" [\"contribution\"]] (jja/classify \"savings\" \"Direc", "end": 881, "score": 0.6922881603240967, "start": 875, "tag": "NAME", "value": "alanna" }, { "context": "sitive-amount))))\n (testing \"Given the account is viridian, the amount is positive, and the description star", "end": 3626, "score": 0.9641881585121155, "start": 3618, "tag": "NAME", "value": "viridian" } ]
test/jjAgglomerator/classifier_test.clj
s5b/jjAgglomerator
0
(ns jjAgglomerator.classifier-test (:require [clojure.test :refer :all] [jjAgglomerator.classifier :refer :all :as jja])) (def negative-amount (BigDecimal. "-67.23")) (def positive-amount (BigDecimal. "+413.87")) (deftest classify-transactions-from-savings (testing "Given the account is savings, the amount is negative, and the description mentions transfer and interest" (is (= ["admin" ["repayment"]] (jja/classify "savings" "Transfer to xx0721 NetBank Viridian interest" negative-amount)))) (testing "Given the account is savings, the amount is positive, and the description mentions 'Transfer from xx2181 NetBank'" (is (= ["stuart" ["contribution"]] (jja/classify "savings" "Transfer from xx2181 NetBank" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description mentions Alanna" (is (= ["alanna" ["contribution"]] (jja/classify "savings" "Direct Credit 165074 BENDIGO BANK ALANNA" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description mentions Rob, RJB, or robert" (is (= ["robert" ["contribution"]] (jja/classify "savings" "Transfer from ROBERT BEGG NetBank RJB" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description contains a partion rob" (is (= ["-unknown-" []] (jja/classify "savings" "Transfer from ROBBERY" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description contains the word 'belmont'" (is (= ["mark" ["contribution"]] (jja/classify "savings" "Cash Dep Branch Belmont" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description contains the word 'mark'" (is (= ["mark" ["contribution"]] (jja/classify "savings" "Cash Dep Branch Torquay CLASIC - MARK" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description is exactly 'Credit Interest'" (is (= ["bank" ["interest"]] (jja/classify "savings" "Credit Interest" positive-amount)))) ) (deftest classify-transactions-from-viridian (testing "Given the account is viridian, the amount is negative, and the description matches 'DEBIT INT TO nn MONTH'" (is (= ["bank" ["interest"]] (jja/classify "viridian" "DEBIT INT TO 30 JAN" negative-amount)))) (testing "Given the account is viridian, the amount is negative, and the description matches 'Debit Interest'" (is (= ["bank" ["interest"]] (jja/classify "viridian" "Debit Interest" negative-amount)))) (testing "Given the account is viridian, the amount is negative, and the description matches 'BL BCR MANAGEMEN CRM MANAGEM'" (is (= ["classic" ["bodycorp"]] (jja/classify "viridian" "BL BCR MANAGEMEN BL BCR MAANGEMENT" negative-amount)))) (testing "Given the account is viridian, the amount is negative, and the description contains 'BL BCR MANAGEMEN CRM MANAGEM'" (is (= ["classic" ["bodycorp"]] (jja/classify "viridian" "Direct Debit 126817 BL BCR MANAGEMEN BL BCR MAANGEMENT" negative-amount)))) (testing "Given the account is viridian, the amount is negative, and the description contains 'BRIGHTON CLASSIC'" (is (= ["classic" ["bodycorp"]] (jja/classify "viridian" "Direct Debit 479537 BRIGHTON CLASSIC RL0020179" negative-amount)))) (testing "Given the account is viridian, the amount is positive, and the description starts with 'NETBANK TFR' and contains 'interest'" (is (= ["admin" ["repayment"]] (jja/classify "viridian" "NETBANK TFR Viridian interest" positive-amount)))) (testing "Given the account is viridian, the amount is positive, and the description starts with 'Transfer from xx1826' and contains 'interest'" (is (= ["admin" ["repayment"]] (jja/classify "viridian" "Transfer from xx1826 NetBank Interest Payment" positive-amount)))) )
101656
(ns jjAgglomerator.classifier-test (:require [clojure.test :refer :all] [jjAgglomerator.classifier :refer :all :as jja])) (def negative-amount (BigDecimal. "-67.23")) (def positive-amount (BigDecimal. "+413.87")) (deftest classify-transactions-from-savings (testing "Given the account is savings, the amount is negative, and the description mentions transfer and interest" (is (= ["admin" ["repayment"]] (jja/classify "savings" "Transfer to xx0721 NetBank Viridian interest" negative-amount)))) (testing "Given the account is savings, the amount is positive, and the description mentions 'Transfer from xx2181 NetBank'" (is (= ["st<NAME>" ["contribution"]] (jja/classify "savings" "Transfer from xx2181 NetBank" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description mentions Alanna" (is (= ["<NAME>" ["contribution"]] (jja/classify "savings" "Direct Credit 165074 BENDIGO BANK ALANNA" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description mentions Rob, RJB, or robert" (is (= ["robert" ["contribution"]] (jja/classify "savings" "Transfer from ROBERT BEGG NetBank RJB" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description contains a partion rob" (is (= ["-unknown-" []] (jja/classify "savings" "Transfer from ROBBERY" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description contains the word 'belmont'" (is (= ["mark" ["contribution"]] (jja/classify "savings" "Cash Dep Branch Belmont" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description contains the word 'mark'" (is (= ["mark" ["contribution"]] (jja/classify "savings" "Cash Dep Branch Torquay CLASIC - MARK" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description is exactly 'Credit Interest'" (is (= ["bank" ["interest"]] (jja/classify "savings" "Credit Interest" positive-amount)))) ) (deftest classify-transactions-from-viridian (testing "Given the account is viridian, the amount is negative, and the description matches 'DEBIT INT TO nn MONTH'" (is (= ["bank" ["interest"]] (jja/classify "viridian" "DEBIT INT TO 30 JAN" negative-amount)))) (testing "Given the account is viridian, the amount is negative, and the description matches 'Debit Interest'" (is (= ["bank" ["interest"]] (jja/classify "viridian" "Debit Interest" negative-amount)))) (testing "Given the account is viridian, the amount is negative, and the description matches 'BL BCR MANAGEMEN CRM MANAGEM'" (is (= ["classic" ["bodycorp"]] (jja/classify "viridian" "BL BCR MANAGEMEN BL BCR MAANGEMENT" negative-amount)))) (testing "Given the account is viridian, the amount is negative, and the description contains 'BL BCR MANAGEMEN CRM MANAGEM'" (is (= ["classic" ["bodycorp"]] (jja/classify "viridian" "Direct Debit 126817 BL BCR MANAGEMEN BL BCR MAANGEMENT" negative-amount)))) (testing "Given the account is viridian, the amount is negative, and the description contains 'BRIGHTON CLASSIC'" (is (= ["classic" ["bodycorp"]] (jja/classify "viridian" "Direct Debit 479537 BRIGHTON CLASSIC RL0020179" negative-amount)))) (testing "Given the account is viridian, the amount is positive, and the description starts with 'NETBANK TFR' and contains 'interest'" (is (= ["admin" ["repayment"]] (jja/classify "viridian" "NETBANK TFR Viridian interest" positive-amount)))) (testing "Given the account is <NAME>, the amount is positive, and the description starts with 'Transfer from xx1826' and contains 'interest'" (is (= ["admin" ["repayment"]] (jja/classify "viridian" "Transfer from xx1826 NetBank Interest Payment" positive-amount)))) )
true
(ns jjAgglomerator.classifier-test (:require [clojure.test :refer :all] [jjAgglomerator.classifier :refer :all :as jja])) (def negative-amount (BigDecimal. "-67.23")) (def positive-amount (BigDecimal. "+413.87")) (deftest classify-transactions-from-savings (testing "Given the account is savings, the amount is negative, and the description mentions transfer and interest" (is (= ["admin" ["repayment"]] (jja/classify "savings" "Transfer to xx0721 NetBank Viridian interest" negative-amount)))) (testing "Given the account is savings, the amount is positive, and the description mentions 'Transfer from xx2181 NetBank'" (is (= ["stPI:NAME:<NAME>END_PI" ["contribution"]] (jja/classify "savings" "Transfer from xx2181 NetBank" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description mentions Alanna" (is (= ["PI:NAME:<NAME>END_PI" ["contribution"]] (jja/classify "savings" "Direct Credit 165074 BENDIGO BANK ALANNA" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description mentions Rob, RJB, or robert" (is (= ["robert" ["contribution"]] (jja/classify "savings" "Transfer from ROBERT BEGG NetBank RJB" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description contains a partion rob" (is (= ["-unknown-" []] (jja/classify "savings" "Transfer from ROBBERY" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description contains the word 'belmont'" (is (= ["mark" ["contribution"]] (jja/classify "savings" "Cash Dep Branch Belmont" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description contains the word 'mark'" (is (= ["mark" ["contribution"]] (jja/classify "savings" "Cash Dep Branch Torquay CLASIC - MARK" positive-amount)))) (testing "Given the account is savings, the amount is positive, and the description is exactly 'Credit Interest'" (is (= ["bank" ["interest"]] (jja/classify "savings" "Credit Interest" positive-amount)))) ) (deftest classify-transactions-from-viridian (testing "Given the account is viridian, the amount is negative, and the description matches 'DEBIT INT TO nn MONTH'" (is (= ["bank" ["interest"]] (jja/classify "viridian" "DEBIT INT TO 30 JAN" negative-amount)))) (testing "Given the account is viridian, the amount is negative, and the description matches 'Debit Interest'" (is (= ["bank" ["interest"]] (jja/classify "viridian" "Debit Interest" negative-amount)))) (testing "Given the account is viridian, the amount is negative, and the description matches 'BL BCR MANAGEMEN CRM MANAGEM'" (is (= ["classic" ["bodycorp"]] (jja/classify "viridian" "BL BCR MANAGEMEN BL BCR MAANGEMENT" negative-amount)))) (testing "Given the account is viridian, the amount is negative, and the description contains 'BL BCR MANAGEMEN CRM MANAGEM'" (is (= ["classic" ["bodycorp"]] (jja/classify "viridian" "Direct Debit 126817 BL BCR MANAGEMEN BL BCR MAANGEMENT" negative-amount)))) (testing "Given the account is viridian, the amount is negative, and the description contains 'BRIGHTON CLASSIC'" (is (= ["classic" ["bodycorp"]] (jja/classify "viridian" "Direct Debit 479537 BRIGHTON CLASSIC RL0020179" negative-amount)))) (testing "Given the account is viridian, the amount is positive, and the description starts with 'NETBANK TFR' and contains 'interest'" (is (= ["admin" ["repayment"]] (jja/classify "viridian" "NETBANK TFR Viridian interest" positive-amount)))) (testing "Given the account is PI:NAME:<NAME>END_PI, the amount is positive, and the description starts with 'Transfer from xx1826' and contains 'interest'" (is (= ["admin" ["repayment"]] (jja/classify "viridian" "Transfer from xx1826 NetBank Interest Payment" positive-amount)))) )
[ { "context": " (tags/make-tag {:tag-key \"gov.nasa.eosdis\"})\n tag-colls)]\n (index/w", "end": 6778, "score": 0.5212878584861755, "start": 6778, "tag": "KEY", "value": "" } ]
system-int-test/test/cmr/system_int_test/search/collection_directory_pages_test.clj
mschmele/Common-Metadata-Repository
0
(ns cmr.system-int-test.search.collection-directory-pages-test "This tests a running CMR site's directory links at all levels: top-most, eosdis, and provider." (:require [clj-http.client :as client] [clojure.string :as string] [clojure.test :refer :all] [cmr.mock-echo.client.echo-util :as e] [cmr.search.site.data :as site-data] [cmr.search.site.routes :as r] [cmr.system-int-test.data2.core :as d] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.tag-util :as tags] [cmr.transmit.config :as transmit-config] [cmr.umm-spec.models.umm-common-models :as cm] [cmr.umm-spec.test.expected-conversion :as exp-conv])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Constants and general utility functions for the tests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private base-url "We don't call to `(transmit-config/application-public-root-url)` due to the fact that it requires a context and we're not creating contexts for these integration tests, we're simply using an HTTP client." (format "%s://%s:%s/" (transmit-config/search-protocol) (transmit-config/search-host) (transmit-config/search-port))) (defn- get-response [url-path] (->> url-path (str base-url) (client/get))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Exepcted results check functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn expected-header-link? [body] (string/includes? body (str base-url "site/collections/directory"))) (defn expected-top-level-links? [body] (string/includes? body (str base-url "site/collections/directory/eosdis"))) (defn expected-eosdis-level-links? [body] (let [url (str base-url "site/collections/directory") tag "gov.nasa.eosdis"] (and (string/includes? body (format "%s/%s/%s" url "PROV1" tag)) (string/includes? body (format "%s/%s/%s" url "PROV2" tag)) (string/includes? body (format "%s/%s/%s" url "PROV3" tag)) (not (string/includes? body "NOCOLLS")) (not (string/includes? body "NONEOSDIS"))))) (defn expected-provider1-level-links? [body] (let [url (format "%sconcepts" base-url)] (and (string/includes? body (format "%s/%s" url "C2-PROV1.html")) (string/includes? body "Collection Item 2") (string/includes? body (format "%s/%s" url "C3-PROV1.html")) (string/includes? body "Collection Item 3")))) (defn expected-provider2-level-links? [body] (let [url (format "%sconcepts" base-url)] (and (string/includes? body (format "%s/%s" url "C2-PROV2.html")) (string/includes? body "Collection Item 2") (string/includes? body (format "%s/%s" url "C3-PROV2.html")) (string/includes? body "Collection Item 3")))) (defn expected-provider3-level-links? [body] (let [url "http://dx.doi.org"] (and (string/includes? body (format "%s/%s" url "doi5")) (string/includes? body "Collection Item 5") (string/includes? body (format "%s/%s" url "doi6")) (string/includes? body "Collection Item 6")))) (defn expected-provider1-col1-link? [body] (let [url (format "%sconcepts" base-url)] (and (string/includes? body (format "%s/%s" url "C1-PROV1.html")) (string/includes? body "Collection Item 1")))) (def expected-over-ten-count "<td class=\"align-r\">\n 14\n </td>") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Functions for creating testing data ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- setup-collections "A utility function that generates testing collections data with the bits we need to test." [] (let [[c1-p1 c2-p1 c3-p1 c1-p2 c2-p2 c3-p2 c1-p4 c2-p4 c3-p4] (for [p ["PROV1" "PROV2" "NONEOSDIS"] n (range 1 4)] (d/ingest-umm-spec-collection p (assoc exp-conv/example-collection-record :ShortName (str "s" n) :EntryTitle (str "Collection Item " n) :concept-id (format "C%d-%s" n p)) {:format :umm-json :accept-format :json})) [c1-p3 c2-p3 c3-p3] (for [n (range 4 7)] (d/ingest-umm-spec-collection "PROV3" (assoc exp-conv/example-collection-record :ShortName (str "s" n) :EntryTitle (str "Collection Item " n) :DOI (cm/map->DoiType {:DOI (str "doi" n) :Authority (str "auth" n)}) :concept-id (format "C%d-PROV3" n)) {:format :umm-json :accept-format :json})) ;; Let's create another collection that will put the total over the ;; default of 10 values so that we can ensure the :unlimited option ;; is being used in the directory page data. over-ten-colls (for [n (range 20 41)] (d/ingest-umm-spec-collection "PROV2" (assoc exp-conv/example-collection-record :ShortName (str "s" n) :EntryTitle (str "Collection Item " n) :concept-id (format "C%d-PROV2" n)) {:format :umm-json :accept-format :json}))] ;; Wait until collections are indexed so tags can be associated with them (index/wait-until-indexed) ;; Use the following to generate html links that will be matched in tests (let [user-token (e/login (s/context) "user") notag-colls [c1-p1 c1-p2 c1-p3] nodoi-colls [c1-p1 c2-p1 c3-p1 c1-p2 c2-p2 c3-p2] doi-colls [c1-p3 c2-p3 c3-p3] non-eosdis-provider-colls [c1-p4 c2-p4 c3-p4] all-colls (flatten [over-ten-colls nodoi-colls doi-colls non-eosdis-provider-colls]) tag-colls (into over-ten-colls [c2-p1 c2-p2 c2-p3 c3-p1 c3-p2 c3-p3]) tag (tags/save-tag user-token (tags/make-tag {:tag-key "gov.nasa.eosdis"}) tag-colls)] (index/wait-until-indexed) ;; Sanity checks (is (= (count notag-colls) 3)) (is (= (count nodoi-colls) 6)) (is (= (count doi-colls) 3)) (is (= (count tag-colls) 27)) (is (= (count all-colls) 33))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Fixtures ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def collections-fixture (fn [f] (setup-collections) (f))) ;; Note tha the fixtures are created out of order such that sorting can be ;; checked. (use-fixtures :once (join-fixtures [(ingest/reset-fixture {"provguid5" "NOCOLLS" "provguid4" "NONEOSDIS" "provguid3" "PROV3" "provguid1" "PROV1" "provguid2" "PROV2"}) tags/grant-all-tag-fixture collections-fixture])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Tests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftest header-link (testing "check the link for landing pages in the header" (let [response (get-response "")] (is (= 200 (:status response))) (is (expected-header-link? (:body response)))))) (deftest top-level-links (let [response (get-response "site/collections/directory") body (:body response)] (testing "check top level status and links" (is (= 200 (:status response))) (is (expected-top-level-links? body))) (testing "top level directory page should have header links" (is (expected-header-link? body))))) (deftest eosdis-level-links (Thread/sleep 1000) (let [response (get-response "site/collections/directory/eosdis") body (:body response)] (testing "check eosdis level status and links" (is (= 200 (:status response))) (is (expected-eosdis-level-links? body))) (testing "providers should be sorted by name" (is (and (< (string/index-of body "PROV1") (string/index-of body "PROV2")) (< (string/index-of body "PROV2") (string/index-of body "PROV3"))))) (testing "eosdis-level directory page should have header links" (is (expected-header-link? body))) (testing "provider page should have header links" (is (expected-header-link? body))) ;; XXX Can't get a consistent count on the page ... ; (testing "collection count is greater than the default 10-limit" ; (is (string/includes? body expected-over-ten-count))) )) (deftest provider1-level-links (let [provider "PROV1" tag "gov.nasa.eosdis" url-path (format "site/collections/directory/%s/%s" provider tag) response (get-response url-path) body (:body response)] (testing "check the status and links for PROV1" (is (= 200 (:status response))) (is (expected-provider1-level-links? body))) (testing "the collections not tagged with eosdis shouldn't show up" (is (not (expected-provider1-col1-link? body)))) (testing "provider page should have header links" (is (expected-header-link? body))))) (deftest provider2-level-links (let [provider "PROV2" tag "gov.nasa.eosdis" url-path (format "site/collections/directory/%s/%s" provider tag) response (get-response url-path) body (:body response)] (testing "check the status and links for PROV2" (is (= 200 (:status response))) (is (expected-provider2-level-links? body))) (testing "the collections not tagged with eosdis shouldn't show up" (is (not (expected-provider1-col1-link? body)))) (testing "provider page should have header links" (is (expected-header-link? body))))) (deftest provider3-level-links (let [provider "PROV3" tag "gov.nasa.eosdis" url-path (format "site/collections/directory/%s/%s" provider tag) response (get-response url-path) body (:body response)] (testing "check the status and links for PROV3" (is (= 200 (:status response))) (is (expected-provider3-level-links? body))) (testing "the collections not tagged with eosdis shouldn't show up" (is (not (expected-provider1-col1-link? body)))) (testing "provider page should have header links" (is (expected-header-link? body))))) ;; Note that the following test was originally in the unit tests for ;; cmr-search (thus its similarity to those tests) but had to be moved into ;; the integration tests due to the introduction of `base-url` support in the ;; templates (which the following text exercises). The base URL is obtained ;; (ulimately) by calling c.t.config/application-public-root-url which needs ;; `public-conf` data set in both the route-creation as well as the request. ;; It was thus just easier and more natural to perform the required checks as ;; part the integration tests, since the running system already has that data ;; set up. (deftest eosdis-collections-directory-page (testing "eosdis collections collections directory page returns content" (let [response (get-response "site/collections/directory/eosdis")] (is (= (:status response) 200)) (is (string/includes? (:body response) "Provider Holdings Directory")) (is (string/includes? (:body response) "EOSDIS")))))
40897
(ns cmr.system-int-test.search.collection-directory-pages-test "This tests a running CMR site's directory links at all levels: top-most, eosdis, and provider." (:require [clj-http.client :as client] [clojure.string :as string] [clojure.test :refer :all] [cmr.mock-echo.client.echo-util :as e] [cmr.search.site.data :as site-data] [cmr.search.site.routes :as r] [cmr.system-int-test.data2.core :as d] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.tag-util :as tags] [cmr.transmit.config :as transmit-config] [cmr.umm-spec.models.umm-common-models :as cm] [cmr.umm-spec.test.expected-conversion :as exp-conv])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Constants and general utility functions for the tests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private base-url "We don't call to `(transmit-config/application-public-root-url)` due to the fact that it requires a context and we're not creating contexts for these integration tests, we're simply using an HTTP client." (format "%s://%s:%s/" (transmit-config/search-protocol) (transmit-config/search-host) (transmit-config/search-port))) (defn- get-response [url-path] (->> url-path (str base-url) (client/get))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Exepcted results check functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn expected-header-link? [body] (string/includes? body (str base-url "site/collections/directory"))) (defn expected-top-level-links? [body] (string/includes? body (str base-url "site/collections/directory/eosdis"))) (defn expected-eosdis-level-links? [body] (let [url (str base-url "site/collections/directory") tag "gov.nasa.eosdis"] (and (string/includes? body (format "%s/%s/%s" url "PROV1" tag)) (string/includes? body (format "%s/%s/%s" url "PROV2" tag)) (string/includes? body (format "%s/%s/%s" url "PROV3" tag)) (not (string/includes? body "NOCOLLS")) (not (string/includes? body "NONEOSDIS"))))) (defn expected-provider1-level-links? [body] (let [url (format "%sconcepts" base-url)] (and (string/includes? body (format "%s/%s" url "C2-PROV1.html")) (string/includes? body "Collection Item 2") (string/includes? body (format "%s/%s" url "C3-PROV1.html")) (string/includes? body "Collection Item 3")))) (defn expected-provider2-level-links? [body] (let [url (format "%sconcepts" base-url)] (and (string/includes? body (format "%s/%s" url "C2-PROV2.html")) (string/includes? body "Collection Item 2") (string/includes? body (format "%s/%s" url "C3-PROV2.html")) (string/includes? body "Collection Item 3")))) (defn expected-provider3-level-links? [body] (let [url "http://dx.doi.org"] (and (string/includes? body (format "%s/%s" url "doi5")) (string/includes? body "Collection Item 5") (string/includes? body (format "%s/%s" url "doi6")) (string/includes? body "Collection Item 6")))) (defn expected-provider1-col1-link? [body] (let [url (format "%sconcepts" base-url)] (and (string/includes? body (format "%s/%s" url "C1-PROV1.html")) (string/includes? body "Collection Item 1")))) (def expected-over-ten-count "<td class=\"align-r\">\n 14\n </td>") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Functions for creating testing data ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- setup-collections "A utility function that generates testing collections data with the bits we need to test." [] (let [[c1-p1 c2-p1 c3-p1 c1-p2 c2-p2 c3-p2 c1-p4 c2-p4 c3-p4] (for [p ["PROV1" "PROV2" "NONEOSDIS"] n (range 1 4)] (d/ingest-umm-spec-collection p (assoc exp-conv/example-collection-record :ShortName (str "s" n) :EntryTitle (str "Collection Item " n) :concept-id (format "C%d-%s" n p)) {:format :umm-json :accept-format :json})) [c1-p3 c2-p3 c3-p3] (for [n (range 4 7)] (d/ingest-umm-spec-collection "PROV3" (assoc exp-conv/example-collection-record :ShortName (str "s" n) :EntryTitle (str "Collection Item " n) :DOI (cm/map->DoiType {:DOI (str "doi" n) :Authority (str "auth" n)}) :concept-id (format "C%d-PROV3" n)) {:format :umm-json :accept-format :json})) ;; Let's create another collection that will put the total over the ;; default of 10 values so that we can ensure the :unlimited option ;; is being used in the directory page data. over-ten-colls (for [n (range 20 41)] (d/ingest-umm-spec-collection "PROV2" (assoc exp-conv/example-collection-record :ShortName (str "s" n) :EntryTitle (str "Collection Item " n) :concept-id (format "C%d-PROV2" n)) {:format :umm-json :accept-format :json}))] ;; Wait until collections are indexed so tags can be associated with them (index/wait-until-indexed) ;; Use the following to generate html links that will be matched in tests (let [user-token (e/login (s/context) "user") notag-colls [c1-p1 c1-p2 c1-p3] nodoi-colls [c1-p1 c2-p1 c3-p1 c1-p2 c2-p2 c3-p2] doi-colls [c1-p3 c2-p3 c3-p3] non-eosdis-provider-colls [c1-p4 c2-p4 c3-p4] all-colls (flatten [over-ten-colls nodoi-colls doi-colls non-eosdis-provider-colls]) tag-colls (into over-ten-colls [c2-p1 c2-p2 c2-p3 c3-p1 c3-p2 c3-p3]) tag (tags/save-tag user-token (tags/make-tag {:tag-key "gov.nasa<KEY>.eosdis"}) tag-colls)] (index/wait-until-indexed) ;; Sanity checks (is (= (count notag-colls) 3)) (is (= (count nodoi-colls) 6)) (is (= (count doi-colls) 3)) (is (= (count tag-colls) 27)) (is (= (count all-colls) 33))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Fixtures ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def collections-fixture (fn [f] (setup-collections) (f))) ;; Note tha the fixtures are created out of order such that sorting can be ;; checked. (use-fixtures :once (join-fixtures [(ingest/reset-fixture {"provguid5" "NOCOLLS" "provguid4" "NONEOSDIS" "provguid3" "PROV3" "provguid1" "PROV1" "provguid2" "PROV2"}) tags/grant-all-tag-fixture collections-fixture])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Tests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftest header-link (testing "check the link for landing pages in the header" (let [response (get-response "")] (is (= 200 (:status response))) (is (expected-header-link? (:body response)))))) (deftest top-level-links (let [response (get-response "site/collections/directory") body (:body response)] (testing "check top level status and links" (is (= 200 (:status response))) (is (expected-top-level-links? body))) (testing "top level directory page should have header links" (is (expected-header-link? body))))) (deftest eosdis-level-links (Thread/sleep 1000) (let [response (get-response "site/collections/directory/eosdis") body (:body response)] (testing "check eosdis level status and links" (is (= 200 (:status response))) (is (expected-eosdis-level-links? body))) (testing "providers should be sorted by name" (is (and (< (string/index-of body "PROV1") (string/index-of body "PROV2")) (< (string/index-of body "PROV2") (string/index-of body "PROV3"))))) (testing "eosdis-level directory page should have header links" (is (expected-header-link? body))) (testing "provider page should have header links" (is (expected-header-link? body))) ;; XXX Can't get a consistent count on the page ... ; (testing "collection count is greater than the default 10-limit" ; (is (string/includes? body expected-over-ten-count))) )) (deftest provider1-level-links (let [provider "PROV1" tag "gov.nasa.eosdis" url-path (format "site/collections/directory/%s/%s" provider tag) response (get-response url-path) body (:body response)] (testing "check the status and links for PROV1" (is (= 200 (:status response))) (is (expected-provider1-level-links? body))) (testing "the collections not tagged with eosdis shouldn't show up" (is (not (expected-provider1-col1-link? body)))) (testing "provider page should have header links" (is (expected-header-link? body))))) (deftest provider2-level-links (let [provider "PROV2" tag "gov.nasa.eosdis" url-path (format "site/collections/directory/%s/%s" provider tag) response (get-response url-path) body (:body response)] (testing "check the status and links for PROV2" (is (= 200 (:status response))) (is (expected-provider2-level-links? body))) (testing "the collections not tagged with eosdis shouldn't show up" (is (not (expected-provider1-col1-link? body)))) (testing "provider page should have header links" (is (expected-header-link? body))))) (deftest provider3-level-links (let [provider "PROV3" tag "gov.nasa.eosdis" url-path (format "site/collections/directory/%s/%s" provider tag) response (get-response url-path) body (:body response)] (testing "check the status and links for PROV3" (is (= 200 (:status response))) (is (expected-provider3-level-links? body))) (testing "the collections not tagged with eosdis shouldn't show up" (is (not (expected-provider1-col1-link? body)))) (testing "provider page should have header links" (is (expected-header-link? body))))) ;; Note that the following test was originally in the unit tests for ;; cmr-search (thus its similarity to those tests) but had to be moved into ;; the integration tests due to the introduction of `base-url` support in the ;; templates (which the following text exercises). The base URL is obtained ;; (ulimately) by calling c.t.config/application-public-root-url which needs ;; `public-conf` data set in both the route-creation as well as the request. ;; It was thus just easier and more natural to perform the required checks as ;; part the integration tests, since the running system already has that data ;; set up. (deftest eosdis-collections-directory-page (testing "eosdis collections collections directory page returns content" (let [response (get-response "site/collections/directory/eosdis")] (is (= (:status response) 200)) (is (string/includes? (:body response) "Provider Holdings Directory")) (is (string/includes? (:body response) "EOSDIS")))))
true
(ns cmr.system-int-test.search.collection-directory-pages-test "This tests a running CMR site's directory links at all levels: top-most, eosdis, and provider." (:require [clj-http.client :as client] [clojure.string :as string] [clojure.test :refer :all] [cmr.mock-echo.client.echo-util :as e] [cmr.search.site.data :as site-data] [cmr.search.site.routes :as r] [cmr.system-int-test.data2.core :as d] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.tag-util :as tags] [cmr.transmit.config :as transmit-config] [cmr.umm-spec.models.umm-common-models :as cm] [cmr.umm-spec.test.expected-conversion :as exp-conv])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Constants and general utility functions for the tests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private base-url "We don't call to `(transmit-config/application-public-root-url)` due to the fact that it requires a context and we're not creating contexts for these integration tests, we're simply using an HTTP client." (format "%s://%s:%s/" (transmit-config/search-protocol) (transmit-config/search-host) (transmit-config/search-port))) (defn- get-response [url-path] (->> url-path (str base-url) (client/get))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Exepcted results check functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn expected-header-link? [body] (string/includes? body (str base-url "site/collections/directory"))) (defn expected-top-level-links? [body] (string/includes? body (str base-url "site/collections/directory/eosdis"))) (defn expected-eosdis-level-links? [body] (let [url (str base-url "site/collections/directory") tag "gov.nasa.eosdis"] (and (string/includes? body (format "%s/%s/%s" url "PROV1" tag)) (string/includes? body (format "%s/%s/%s" url "PROV2" tag)) (string/includes? body (format "%s/%s/%s" url "PROV3" tag)) (not (string/includes? body "NOCOLLS")) (not (string/includes? body "NONEOSDIS"))))) (defn expected-provider1-level-links? [body] (let [url (format "%sconcepts" base-url)] (and (string/includes? body (format "%s/%s" url "C2-PROV1.html")) (string/includes? body "Collection Item 2") (string/includes? body (format "%s/%s" url "C3-PROV1.html")) (string/includes? body "Collection Item 3")))) (defn expected-provider2-level-links? [body] (let [url (format "%sconcepts" base-url)] (and (string/includes? body (format "%s/%s" url "C2-PROV2.html")) (string/includes? body "Collection Item 2") (string/includes? body (format "%s/%s" url "C3-PROV2.html")) (string/includes? body "Collection Item 3")))) (defn expected-provider3-level-links? [body] (let [url "http://dx.doi.org"] (and (string/includes? body (format "%s/%s" url "doi5")) (string/includes? body "Collection Item 5") (string/includes? body (format "%s/%s" url "doi6")) (string/includes? body "Collection Item 6")))) (defn expected-provider1-col1-link? [body] (let [url (format "%sconcepts" base-url)] (and (string/includes? body (format "%s/%s" url "C1-PROV1.html")) (string/includes? body "Collection Item 1")))) (def expected-over-ten-count "<td class=\"align-r\">\n 14\n </td>") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Functions for creating testing data ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- setup-collections "A utility function that generates testing collections data with the bits we need to test." [] (let [[c1-p1 c2-p1 c3-p1 c1-p2 c2-p2 c3-p2 c1-p4 c2-p4 c3-p4] (for [p ["PROV1" "PROV2" "NONEOSDIS"] n (range 1 4)] (d/ingest-umm-spec-collection p (assoc exp-conv/example-collection-record :ShortName (str "s" n) :EntryTitle (str "Collection Item " n) :concept-id (format "C%d-%s" n p)) {:format :umm-json :accept-format :json})) [c1-p3 c2-p3 c3-p3] (for [n (range 4 7)] (d/ingest-umm-spec-collection "PROV3" (assoc exp-conv/example-collection-record :ShortName (str "s" n) :EntryTitle (str "Collection Item " n) :DOI (cm/map->DoiType {:DOI (str "doi" n) :Authority (str "auth" n)}) :concept-id (format "C%d-PROV3" n)) {:format :umm-json :accept-format :json})) ;; Let's create another collection that will put the total over the ;; default of 10 values so that we can ensure the :unlimited option ;; is being used in the directory page data. over-ten-colls (for [n (range 20 41)] (d/ingest-umm-spec-collection "PROV2" (assoc exp-conv/example-collection-record :ShortName (str "s" n) :EntryTitle (str "Collection Item " n) :concept-id (format "C%d-PROV2" n)) {:format :umm-json :accept-format :json}))] ;; Wait until collections are indexed so tags can be associated with them (index/wait-until-indexed) ;; Use the following to generate html links that will be matched in tests (let [user-token (e/login (s/context) "user") notag-colls [c1-p1 c1-p2 c1-p3] nodoi-colls [c1-p1 c2-p1 c3-p1 c1-p2 c2-p2 c3-p2] doi-colls [c1-p3 c2-p3 c3-p3] non-eosdis-provider-colls [c1-p4 c2-p4 c3-p4] all-colls (flatten [over-ten-colls nodoi-colls doi-colls non-eosdis-provider-colls]) tag-colls (into over-ten-colls [c2-p1 c2-p2 c2-p3 c3-p1 c3-p2 c3-p3]) tag (tags/save-tag user-token (tags/make-tag {:tag-key "gov.nasaPI:KEY:<KEY>END_PI.eosdis"}) tag-colls)] (index/wait-until-indexed) ;; Sanity checks (is (= (count notag-colls) 3)) (is (= (count nodoi-colls) 6)) (is (= (count doi-colls) 3)) (is (= (count tag-colls) 27)) (is (= (count all-colls) 33))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Fixtures ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def collections-fixture (fn [f] (setup-collections) (f))) ;; Note tha the fixtures are created out of order such that sorting can be ;; checked. (use-fixtures :once (join-fixtures [(ingest/reset-fixture {"provguid5" "NOCOLLS" "provguid4" "NONEOSDIS" "provguid3" "PROV3" "provguid1" "PROV1" "provguid2" "PROV2"}) tags/grant-all-tag-fixture collections-fixture])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Tests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftest header-link (testing "check the link for landing pages in the header" (let [response (get-response "")] (is (= 200 (:status response))) (is (expected-header-link? (:body response)))))) (deftest top-level-links (let [response (get-response "site/collections/directory") body (:body response)] (testing "check top level status and links" (is (= 200 (:status response))) (is (expected-top-level-links? body))) (testing "top level directory page should have header links" (is (expected-header-link? body))))) (deftest eosdis-level-links (Thread/sleep 1000) (let [response (get-response "site/collections/directory/eosdis") body (:body response)] (testing "check eosdis level status and links" (is (= 200 (:status response))) (is (expected-eosdis-level-links? body))) (testing "providers should be sorted by name" (is (and (< (string/index-of body "PROV1") (string/index-of body "PROV2")) (< (string/index-of body "PROV2") (string/index-of body "PROV3"))))) (testing "eosdis-level directory page should have header links" (is (expected-header-link? body))) (testing "provider page should have header links" (is (expected-header-link? body))) ;; XXX Can't get a consistent count on the page ... ; (testing "collection count is greater than the default 10-limit" ; (is (string/includes? body expected-over-ten-count))) )) (deftest provider1-level-links (let [provider "PROV1" tag "gov.nasa.eosdis" url-path (format "site/collections/directory/%s/%s" provider tag) response (get-response url-path) body (:body response)] (testing "check the status and links for PROV1" (is (= 200 (:status response))) (is (expected-provider1-level-links? body))) (testing "the collections not tagged with eosdis shouldn't show up" (is (not (expected-provider1-col1-link? body)))) (testing "provider page should have header links" (is (expected-header-link? body))))) (deftest provider2-level-links (let [provider "PROV2" tag "gov.nasa.eosdis" url-path (format "site/collections/directory/%s/%s" provider tag) response (get-response url-path) body (:body response)] (testing "check the status and links for PROV2" (is (= 200 (:status response))) (is (expected-provider2-level-links? body))) (testing "the collections not tagged with eosdis shouldn't show up" (is (not (expected-provider1-col1-link? body)))) (testing "provider page should have header links" (is (expected-header-link? body))))) (deftest provider3-level-links (let [provider "PROV3" tag "gov.nasa.eosdis" url-path (format "site/collections/directory/%s/%s" provider tag) response (get-response url-path) body (:body response)] (testing "check the status and links for PROV3" (is (= 200 (:status response))) (is (expected-provider3-level-links? body))) (testing "the collections not tagged with eosdis shouldn't show up" (is (not (expected-provider1-col1-link? body)))) (testing "provider page should have header links" (is (expected-header-link? body))))) ;; Note that the following test was originally in the unit tests for ;; cmr-search (thus its similarity to those tests) but had to be moved into ;; the integration tests due to the introduction of `base-url` support in the ;; templates (which the following text exercises). The base URL is obtained ;; (ulimately) by calling c.t.config/application-public-root-url which needs ;; `public-conf` data set in both the route-creation as well as the request. ;; It was thus just easier and more natural to perform the required checks as ;; part the integration tests, since the running system already has that data ;; set up. (deftest eosdis-collections-directory-page (testing "eosdis collections collections directory page returns content" (let [response (get-response "site/collections/directory/eosdis")] (is (= (:status response) 200)) (is (string/includes? (:body response) "Provider Holdings Directory")) (is (string/includes? (:body response) "EOSDIS")))))
[ { "context": "nge\"\n [state side kw new-val delta]\n (let [key (name kw)]\n (system-msg state side\n (str", "end": 2508, "score": 0.993195116519928, "start": 2501, "tag": "KEY", "value": "name kw" } ]
src/clj/game/core/actions.clj
nathanj/netrunner
0
(in-ns 'game.core) ;; These functions are called by main.clj in response to commands sent by users. (declare available-mu card-str can-rez? can-advance? corp-install effect-as-handler enforce-msg gain-agenda-point get-remote-names get-run-ices jack-out move name-zone play-instant purge resolve-select run runner-install trash update-breaker-strength update-ice-in-server update-run-ice win can-run? can-run-server? can-score? say play-sfx base-mod-size free-mu) ;;; Neutral actions (defn play "Called when the player clicks a card from hand." [state side {:keys [card server]}] (when-let [card (get-card state card)] (case (:type card) ("Event" "Operation") (play-instant state side card {:extra-cost [:click 1]}) ("Hardware" "Resource" "Program") (runner-install state side (make-eid state) card {:extra-cost [:click 1]}) ("ICE" "Upgrade" "Asset" "Agenda") (corp-install state side card server {:extra-cost [:click 1] :action :corp-click-install})) (trigger-event state side :play card))) (defn shuffle-deck "Shuffle R&D/Stack." [state side {:keys [close] :as args}] (swap! state update-in [side :deck] shuffle) (if close (do (swap! state update-in [side] dissoc :view-deck) (system-msg state side "stops looking at their deck and shuffles it")) (system-msg state side "shuffles their deck"))) (defn click-draw "Click to draw." [state side args] (when (and (not (get-in @state [side :register :cannot-draw])) (pay state side nil :click 1 {:action :corp-click-draw})) (system-msg state side "spends [Click] to draw a card") (trigger-event state side (if (= side :corp) :corp-click-draw :runner-click-draw) (->> @state side :deck (take 1))) (draw state side) (swap! state update-in [:stats side :click :draw] (fnil inc 0)) (play-sfx state side "click-card"))) (defn click-credit "Click to gain 1 credit." [state side args] (when (pay state side nil :click 1 {:action :corp-click-credit}) (system-msg state side "spends [Click] to gain 1 [Credits]") (gain-credits state side 1 (keyword (str (name side) "-click-credit"))) (swap! state update-in [:stats side :click :credit] (fnil inc 0)) (trigger-event state side (if (= side :corp) :corp-click-credit :runner-click-credit)) (play-sfx state side "click-credit"))) (defn- change-msg "Send a system message indicating the property change" [state side kw new-val delta] (let [key (name kw)] (system-msg state side (str "sets " (.replace key "-" " ") " to " new-val " (" (if (pos? delta) (str "+" delta) delta) ")")))) (defn- change-map "Change a player's property using the :mod system" [state side key delta] (gain state side key {:mod delta}) (change-msg state side key (base-mod-size state side key) delta)) (defn- change-mu "Send a system message indicating how mu was changed" [state side delta] (free-mu state delta) (system-msg state side (str "sets unused MU to " (available-mu state) " (" (if (pos? delta) (str "+" delta) delta) ")"))) (defn- change-tags "Change a player's base tag count" [state delta] (if (neg? delta) (deduct state :runner [:tag (Math/abs delta)]) (gain state :runner :tag delta)) (system-msg state :runner (str "sets Tags to " (get-in @state [:runner :tag :base]) " (" (if (pos? delta) (str "+" delta) delta) ")"))) (defn change "Increase/decrease a player's property (clicks, credits, MU, etc.) by delta." [state side {:keys [key delta]}] (cond ;; Memory needs special treatment and message (= :memory key) (change-mu state side delta) ;; Hand size needs special treatment as it expects a map (= :hand-size key) (change-map state side key delta) ;; Tags need special treatment since they are a more complex map (= :tag key) (change-tags state delta) :else (do (if (neg? delta) (deduct state side [key (- delta)]) (swap! state update-in [side key] (partial + delta))) (change-msg state side key (get-in @state [side key]) delta)))) (defn move-card "Called when the user drags a card from one zone to another." [state side {:keys [card server]}] (let [c (get-card state card) ;; hack: if dragging opponent's card from play-area (Indexing), the previous line will fail ;; to find the card. the next line will search in the other player's play-area. c (or c (get-card state (assoc card :side (other-side (to-keyword (:side card)))))) last-zone (last (:zone c)) src (name-zone (:side c) (:zone c)) from-str (when-not (nil? src) (if (= :content last-zone) (str " in " src) ; this string matches the message when a card is trashed via (trash) (str " from their " src))) label (if (and (not= last-zone :play-area) (not (and (= (:side c) "Runner") (= last-zone :hand) (= server "Grip"))) (or (and (= (:side c) "Runner") (not (:facedown c))) (rezzed? c) (:seen c) (= last-zone :deck))) (:title c) "a card") s (if (#{"HQ" "R&D" "Archives"} server) :corp :runner)] ;; allow moving from play-area always, otherwise only when same side, and to valid zone (when (and (not= src server) (same-side? s (:side card)) (or (= last-zone :play-area) (same-side? side (:side card)))) (let [move-card-to (partial move state s (dissoc c :seen :rezzed)) log-move (fn [verb & text] (system-msg state side (str verb " " label from-str (when (seq text) (apply str " " text)))))] (case server ("Heap" "Archives") (if (= :hand (first (:zone c))) ;; Discard from hand, do not trigger trash (do (move-card-to :discard {:force true}) (log-move "discards")) (do (trash state s c {:unpreventable true}) (log-move "trashes"))) ("Grip" "HQ") (do (move-card-to :hand {:force true}) (log-move "moves" "to " server)) ("Stack" "R&D") (do (move-card-to :deck {:front true :force true}) (log-move "moves" "to the top of " server)) ;; default nil))))) (defn concede "Trigger game concede by specified side. Takes a third argument for use with user commands." ([state side _] (concede state side)) ([state side] (system-msg state side "concedes") (win state (if (= side :corp) :runner :corp) "Concede"))) (defn- finish-prompt [state side prompt card] (when-let [end-effect (:end-effect prompt)] (end-effect state side (make-eid state) card nil)) ;; remove the prompt from the queue (swap! state update-in [side :prompt] (fn [pr] (filter #(not= % prompt) pr))) ;; This is a dirty hack to end the run when the last access prompt is resolved. (when (empty? (get-in @state [:runner :prompt])) (when-let [run (:run @state)] (when (:ended run) (handle-end-run state :runner))) (swap! state dissoc :access)) true) (defn resolve-prompt "Resolves a prompt by invoking its effect function with the selected target of the prompt. Triggered by a selection of a prompt choice button in the UI." [state side {:keys [choice card] :as args}] (let [servercard (get-card state card) card (if (not= (:title card) (:title servercard)) (@all-cards (:title card)) servercard) prompt (first (get-in @state [side :prompt])) choices (:choices prompt)] (cond ;; Shortcut (= choice "Cancel") (do (if-let [cancel-effect (:cancel-effect prompt)] ;; trigger the cancel effect (cancel-effect choice) (effect-completed state side (:eid prompt))) (finish-prompt state side prompt card)) ;; Integer prompts (or (= choices :credit) (:counter choices) (:number choices)) (if (number? choice) (do (when (= choices :credit) ; :credit prompts require payment (pay state side card :credit (min choice (get-in @state [side :credit])))) (when (:counter choices) ;; :Counter prompts deduct counters from the card (add-counter state side (:card prompt) (:counter choices) (- choice))) ;; trigger the prompt's effect function (when-let [effect-prompt (:effect prompt)] (effect-prompt (or choice card))) (finish-prompt state side prompt card)) (.println *err* "Error in an integer prompt")) ;; List of card titles for auto-completion (:card-title choices) (if (string? choice) (let [title-fn (:card-title choices) found (some #(when (= (lower-case choice) (lower-case (:title % ""))) %) (vals @all-cards))] (if found (if (title-fn state side (make-eid state) (:card prompt) [found]) (do (when-let [effect-prompt (:effect prompt)] (effect-prompt (or choice card))) (finish-prompt state side prompt card)) (toast state side (str "You cannot choose " choice " for this effect.") "warning")) (toast state side (str "Could not find a card named " choice ".") "warning"))) (.println *err* "Error in a card-title prompt")) ;; Default text prompt :else (let [buttons (filter #(or (= choice %) (= card %) (let [choice-str (if (string? choice) (lower-case choice) (lower-case (:title choice "do-not-match")))] (or (= choice-str (lower-case %)) (= choice-str (lower-case (:title % "")))))) choices) button (first buttons)] (if button (do (when-let [effect-prompt (:effect prompt)] (effect-prompt button)) (finish-prompt state side prompt card)) (.println *err* "Error in a text prompt")))))) (defn select "Attempt to select the given card to satisfy the current select prompt. Calls resolve-select if the max number of cards has been selected." [state side {:keys [card] :as args}] (let [card (get-card state card) r (get-in @state [side :selected 0 :req]) cid (get-in @state [side :selected 0 :not-self])] (when (and (not= (:cid card) cid) (or (not r) (r card))) (let [c (update-in card [:selected] not)] (update! state side c) (if (:selected c) (swap! state update-in [side :selected 0 :cards] #(conj % c)) (swap! state update-in [side :selected 0 :cards] (fn [coll] (remove-once #(= (:cid %) (:cid card)) coll)))) (let [selected (get-in @state [side :selected 0])] (when (= (count (:cards selected)) (or (:max selected) 1)) (resolve-select state side))))))) (defn- do-play-ability [state side card ability targets] (let [cost (:cost ability)] (when (or (nil? cost) (if (has-subtype? card "Run") (apply can-pay? state side (:title card) cost (get-in @state [:bonus :run-cost])) (apply can-pay? state side (:title card) cost))) (when-let [activatemsg (:activatemsg ability)] (system-msg state side activatemsg)) (resolve-ability state side ability card targets)))) (defn play-ability "Triggers a card's ability using its zero-based index into the card's card-def :abilities vector." [state side {:keys [card ability targets] :as args}] (let [card (get-card state card) cdef (card-def card) abilities (:abilities cdef) ab (if (= ability (count abilities)) ;; recurring credit abilities are not in the :abilities map and are implicit {:msg "take 1 [Recurring Credits]" :req (req (pos? (get-counters card :recurring))) :effect (req (add-prop state side card :rec-counter -1) (gain state side :credit 1) (when (has-subtype? card "Stealth") (trigger-event state side :spent-stealth-credit card)))} (get-in cdef [:abilities ability]))] (when-not (:disabled card) (do-play-ability state side card ab targets)))) (defn play-auto-pump "Use the 'match strength with ice' function of icebreakers." [state side args] (let [run (:run @state) card (get-card state (:card args)) run-ice (get-run-ices state) ice-cnt (count run-ice) ice-idx (dec (:position run 0)) in-range (and (pos? ice-cnt) (< -1 ice-idx ice-cnt)) current-ice (when (and run in-range) (get-card state (run-ice ice-idx))) pumpabi (some #(when (:pump %) %) (:abilities (card-def card))) pumpcst (when pumpabi (second (drop-while #(and (not= % :credit) (not= % "credit")) (:cost pumpabi)))) strdif (when current-ice (max 0 (- (or (:current-strength current-ice) (:strength current-ice)) (or (:current-strength card) (:strength card))))) pumpnum (when strdif (int (Math/ceil (/ strdif (:pump pumpabi 1)))))] (when (and pumpnum pumpcst (>= (get-in @state [:runner :credit]) (* pumpnum pumpcst))) (dotimes [n pumpnum] (resolve-ability state side (dissoc pumpabi :msg) (get-card state card) nil)) (system-msg state side (str "spends " (* pumpnum pumpcst) " [Credits] to increase the strength of " (:title card) " to " (:current-strength (get-card state card))))))) (defn play-copy-ability "Play an ability from another card's definition." [state side {:keys [card source index] :as args}] (let [card (get-card state card) source-abis (:abilities (cards (.replace source "'" ""))) abi (when (< -1 index (count source-abis)) (nth source-abis index))] (when abi (do-play-ability state side card abi nil)))) (def dynamic-abilities {"auto-pump" play-auto-pump "copy" play-copy-ability}) (defn play-dynamic-ability "Triggers an ability that was dynamically added to a card's data but is not necessarily present in its :abilities vector." [state side args] ((dynamic-abilities (:dynamic args)) state (keyword side) args)) (defn play-corp-ability "Triggers a runner card's corp-ability using its zero-based index into the card's card-def :corp-abilities vector." [state side {:keys [card ability targets] :as args}] (let [card (get-card state card) cdef (card-def card) ab (get-in cdef [:corp-abilities ability])] (do-play-ability state side card ab targets))) (defn play-runner-ability "Triggers a corp card's runner-ability using its zero-based index into the card's card-def :runner-abilities vector." [state side {:keys [card ability targets] :as args}] (let [card (get-card state card) cdef (card-def card) ab (get-in cdef [:runner-abilities ability])] (do-play-ability state side card ab targets))) (defn play-subroutine "Triggers a card's subroutine using its zero-based index into the card's :subroutines vector." ([state side args] (let [eid (make-eid state {:source (-> args :card :title) :source-type :subroutine})] (play-subroutine state side eid args))) ([state side eid {:keys [card subroutine targets] :as args}] (let [card (get-card state card) sub (nth (:subroutines card) subroutine nil)] (if (or (nil? sub) (nil? (:from-cid sub))) (let [cdef-idx (if (nil? sub) subroutine (-> sub :data :cdef-idx)) cdef (card-def card) cdef-sub (get-in cdef [:subroutines cdef-idx]) cost (:cost cdef-sub)] (when (or (nil? cost) (apply can-pay? state side (:title card) cost)) (when-let [activatemsg (:activatemsg cdef-sub)] (system-msg state side activatemsg)) (resolve-ability state side eid cdef-sub card targets))) (when-let [sub-card (find-latest state {:cid (:from-cid sub) :side side})] (when-let [sub-effect (:sub-effect (card-def sub-card))] (resolve-ability state side eid sub-effect card (assoc (:data sub) :targets targets)))))))) ;;; Corp actions (defn trash-resource "Click to trash a resource." [state side args] (let [trash-cost (max 0 (- 2 (get-in @state [:corp :trash-cost-bonus] 0)))] (when-let [cost-str (pay state side nil :click 1 :credit trash-cost {:action :corp-trash-resource})] (resolve-ability state side {:prompt "Choose a resource to trash" :choices {:req (fn [card] (if (and (seq (filter (fn [c] (untrashable-while-resources? c)) (all-active-installed state :runner))) (> (count (filter #(is-type? % "Resource") (all-active-installed state :runner))) 1)) (and (is-type? card "Resource") (not (untrashable-while-resources? card))) (is-type? card "Resource")))} :cancel-effect (effect (gain :credit trash-cost :click 1)) :effect (effect (trash target) (system-msg (str (build-spend-msg cost-str "trash") (:title target))))} nil nil)))) (defn do-purge "Purge viruses." [state side args] (when-let [cost (pay state side nil :click 3 {:action :corp-click-purge})] (purge state side) (let [spent (build-spend-msg cost "purge") message (str spent "all virus counters")] (system-msg state side message)) (play-sfx state side "virus-purge"))) (defn rez "Rez a corp card." ([state side card] (rez state side (make-eid state) card nil)) ([state side card args] (rez state side (make-eid state) card args)) ([state side eid {:keys [disabled] :as card} {:keys [ignore-cost no-warning force no-get-card paid-alt cached-bonus] :as args}] (let [card (if no-get-card card (get-card state card)) altcost (when-not no-get-card (:alternative-cost (card-def card)))] (when cached-bonus (rez-cost-bonus state side cached-bonus)) (if (or force (can-rez? state side card)) (do (trigger-event state side :pre-rez card) (if (or (#{"Asset" "ICE" "Upgrade"} (:type card)) (:install-rezzed (card-def card))) (do (trigger-event state side :pre-rez-cost card) (if (and altcost (can-pay? state side nil altcost)(not ignore-cost)) (let [curr-bonus (get-rez-cost-bonus state side)] (prompt! state side card (str "Pay the alternative Rez cost?") ["Yes" "No"] {:async true :effect (req (if (and (= target "Yes") (can-pay? state side (:title card) altcost)) (do (pay state side card altcost) (rez state side eid (-> card (dissoc :alternative-cost)) (merge args {:ignore-cost true :no-get-card true :paid-alt true}))) (do (rez state side eid (-> card (dissoc :alternative-cost)) (merge args {:no-get-card true :cached-bonus curr-bonus})))))})) (let [cdef (card-def card) cost (rez-cost state side card) costs (concat (when-not ignore-cost [:credit cost]) (when (and (not= ignore-cost :all-costs) (not (:disabled card))) (:additional-cost cdef)))] (when-let [cost-str (apply pay state side card costs)] ;; Deregister the derezzed-events before rezzing card (when (:derezzed-events cdef) (unregister-events state side card)) (if-not disabled (card-init state side (assoc card :rezzed :this-turn)) (update! state side (assoc card :rezzed :this-turn))) (doseq [h (:hosted card)] (update! state side (-> h (update-in [:zone] #(map to-keyword %)) (update-in [:host :zone] #(map to-keyword %))))) (system-msg state side (str (build-spend-msg cost-str "rez" "rezzes") (:title card) (cond paid-alt " by paying its alternative cost" ignore-cost " at no cost"))) (when (and (not no-warning) (:corp-phase-12 @state)) (toast state :corp "You are not allowed to rez cards between Start of Turn and Mandatory Draw. Please rez prior to clicking Start Turn in the future." "warning" {:time-out 0 :close-button true})) (if (ice? card) (do (update-ice-strength state side card) (play-sfx state side "rez-ice")) (play-sfx state side "rez-other")) (swap! state update-in [:stats :corp :cards :rezzed] (fnil inc 0)) (trigger-event-sync state side eid :rez card))))) (effect-completed state side eid)) (swap! state update-in [:bonus] dissoc :cost)) (effect-completed state side eid))))) (defn derez "Derez a corp card." [state side card] (let [card (get-card state card)] (system-msg state side (str "derezzes " (:title card))) (update! state :corp (deactivate state :corp card true)) (let [cdef (card-def card)] (when-let [derez-effect (:derez-effect cdef)] (resolve-ability state side derez-effect (get-card state card) nil)) (when-let [dre (:derezzed-events cdef)] (register-events state side dre card))) (trigger-event state side :derez card side))) (defn advance "Advance a corp card that can be advanced. If you pass in a truthy value as the 4th parameter, it will advance at no cost (for the card Success)." ([state side {:keys [card]}] (advance state side card nil)) ([state side card no-cost] (let [card (get-card state card)] (when (can-advance? state side card) (when-let [cost (pay state side card :click (if-not no-cost 1 0) :credit (if-not no-cost 1 0) {:action :corp-advance})] (let [spent (build-spend-msg cost "advance") card (card-str state card) message (str spent card)] (system-msg state side message)) (update-advancement-cost state side card) (add-prop state side (get-card state card) :advance-counter 1) (play-sfx state side "click-advance")))))) (defn score "Score an agenda. It trusts the card data passed to it." ([state side args] (score state side (make-eid state) args)) ([state side eid args] (let [card (or (:card args) args)] (when (and (can-score? state side card) (empty? (filter #(= (:cid card) (:cid %)) (get-in @state [:corp :register :cannot-score]))) (>= (get-counters card :advancement) (or (:current-cost card) (:advancementcost card)))) ;; do not card-init necessarily. if card-def has :effect, wrap a fake event (let [moved-card (move state :corp card :scored) c (card-init state :corp moved-card {:resolve-effect false :init-data true}) points (get-agenda-points state :corp c)] (trigger-event-simult state :corp eid :agenda-scored {:first-ability {:effect (req (when-let [current (first (get-in @state [:runner :current]))] ;; TODO: Make this use remove-old-current (system-say state side (str (:title current) " is trashed.")) ; This is to handle Employee Strike with damage IDs #2688 (when (:disable-id (card-def current)) (swap! state assoc-in [:corp :disable-id] true)) (trash state side current)))} :card-ability (card-as-handler c) :after-active-player {:effect (req (let [c (get-card state c) points (or (get-agenda-points state :corp c) points)] (set-prop state :corp (get-card state moved-card) :advance-counter 0) (system-msg state :corp (str "scores " (:title c) " and gains " (quantify points "agenda point"))) (swap! state update-in [:corp :register :scored-agenda] #(+ (or % 0) points)) (swap! state dissoc-in [:corp :disable-id]) (gain-agenda-point state :corp points) (play-sfx state side "agenda-score")))}} c)))))) (defn no-action "The corp indicates they have no more actions for the encounter." [state side args] (swap! state assoc-in [:run :no-action] true) (system-msg state side "has no further action") (trigger-event state side :no-action) (let [run-ice (get-run-ices state) pos (get-in @state [:run :position]) ice (when (and pos (pos? pos) (<= pos (count run-ice))) (get-card state (nth run-ice (dec pos))))] (when (rezzed? ice) (trigger-event state side :encounter-ice ice) (update-ice-strength state side ice)))) ;;; Runner actions (defn click-run "Click to start a run." [state side {:keys [server] :as args}] (let [cost-bonus (get-in @state [:bonus :run-cost]) click-cost-bonus (get-in @state [:bonus :click-run-cost])] (when (and (can-run? state side) (can-run-server? state server) (can-pay? state :runner "a run" :click 1 cost-bonus click-cost-bonus)) (swap! state assoc-in [:runner :register :made-click-run] true) (when-let [cost-str (pay state :runner nil :click 1 cost-bonus click-cost-bonus)] (run state side server) (system-msg state :runner (str (build-spend-msg cost-str "make a run on") server)) (play-sfx state side "click-run"))))) (defn remove-tag "Click to remove a tag." [state side args] (let [remove-cost (max 0 (- 2 (get-in @state [:runner :tag-remove-bonus] 0)))] (when-let [cost-str (pay state side nil :click 1 :credit remove-cost)] (lose-tags state :runner 1) (system-msg state side (build-spend-msg cost-str "remove 1 tag")) (play-sfx state side "click-remove-tag")))) (defn continue "The runner decides to approach the next ice, or the server itself." [state side args] (when (get-in @state [:run :no-action]) (let [run-ice (get-run-ices state) pos (get-in @state [:run :position]) cur-ice (when (and pos (pos? pos) (<= pos (count run-ice))) (get-card state (nth run-ice (dec pos)))) next-ice (when (and pos (< 1 pos) (<= (dec pos) (count run-ice))) (get-card state (nth run-ice (- pos 2))))] (wait-for (trigger-event-sync state side :pass-ice cur-ice) (do (update-ice-in-server state side (get-in @state (concat [:corp :servers] (get-in @state [:run :server])))) (swap! state update-in [:run :position] (fnil dec 1)) (swap! state assoc-in [:run :no-action] false) (system-msg state side "continues the run") (when cur-ice (update-ice-strength state side cur-ice)) (if next-ice (trigger-event-sync state side (make-eid state) :approach-ice next-ice) (trigger-event-sync state side (make-eid state) :approach-server)) (doseq [p (filter #(has-subtype? % "Icebreaker") (all-active-installed state :runner))] (update! state side (update-in (get-card state p) [:pump] dissoc :encounter)) (update-breaker-strength state side p))))))) (defn view-deck "Allows the player to view their deck by making the cards in the deck public." [state side args] (system-msg state side "looks at their deck") (swap! state assoc-in [side :view-deck] true)) (defn close-deck "Closes the deck view and makes cards in deck private again." [state side args] (system-msg state side "stops looking at their deck") (swap! state update-in [side] dissoc :view-deck))
39996
(in-ns 'game.core) ;; These functions are called by main.clj in response to commands sent by users. (declare available-mu card-str can-rez? can-advance? corp-install effect-as-handler enforce-msg gain-agenda-point get-remote-names get-run-ices jack-out move name-zone play-instant purge resolve-select run runner-install trash update-breaker-strength update-ice-in-server update-run-ice win can-run? can-run-server? can-score? say play-sfx base-mod-size free-mu) ;;; Neutral actions (defn play "Called when the player clicks a card from hand." [state side {:keys [card server]}] (when-let [card (get-card state card)] (case (:type card) ("Event" "Operation") (play-instant state side card {:extra-cost [:click 1]}) ("Hardware" "Resource" "Program") (runner-install state side (make-eid state) card {:extra-cost [:click 1]}) ("ICE" "Upgrade" "Asset" "Agenda") (corp-install state side card server {:extra-cost [:click 1] :action :corp-click-install})) (trigger-event state side :play card))) (defn shuffle-deck "Shuffle R&D/Stack." [state side {:keys [close] :as args}] (swap! state update-in [side :deck] shuffle) (if close (do (swap! state update-in [side] dissoc :view-deck) (system-msg state side "stops looking at their deck and shuffles it")) (system-msg state side "shuffles their deck"))) (defn click-draw "Click to draw." [state side args] (when (and (not (get-in @state [side :register :cannot-draw])) (pay state side nil :click 1 {:action :corp-click-draw})) (system-msg state side "spends [Click] to draw a card") (trigger-event state side (if (= side :corp) :corp-click-draw :runner-click-draw) (->> @state side :deck (take 1))) (draw state side) (swap! state update-in [:stats side :click :draw] (fnil inc 0)) (play-sfx state side "click-card"))) (defn click-credit "Click to gain 1 credit." [state side args] (when (pay state side nil :click 1 {:action :corp-click-credit}) (system-msg state side "spends [Click] to gain 1 [Credits]") (gain-credits state side 1 (keyword (str (name side) "-click-credit"))) (swap! state update-in [:stats side :click :credit] (fnil inc 0)) (trigger-event state side (if (= side :corp) :corp-click-credit :runner-click-credit)) (play-sfx state side "click-credit"))) (defn- change-msg "Send a system message indicating the property change" [state side kw new-val delta] (let [key (<KEY>)] (system-msg state side (str "sets " (.replace key "-" " ") " to " new-val " (" (if (pos? delta) (str "+" delta) delta) ")")))) (defn- change-map "Change a player's property using the :mod system" [state side key delta] (gain state side key {:mod delta}) (change-msg state side key (base-mod-size state side key) delta)) (defn- change-mu "Send a system message indicating how mu was changed" [state side delta] (free-mu state delta) (system-msg state side (str "sets unused MU to " (available-mu state) " (" (if (pos? delta) (str "+" delta) delta) ")"))) (defn- change-tags "Change a player's base tag count" [state delta] (if (neg? delta) (deduct state :runner [:tag (Math/abs delta)]) (gain state :runner :tag delta)) (system-msg state :runner (str "sets Tags to " (get-in @state [:runner :tag :base]) " (" (if (pos? delta) (str "+" delta) delta) ")"))) (defn change "Increase/decrease a player's property (clicks, credits, MU, etc.) by delta." [state side {:keys [key delta]}] (cond ;; Memory needs special treatment and message (= :memory key) (change-mu state side delta) ;; Hand size needs special treatment as it expects a map (= :hand-size key) (change-map state side key delta) ;; Tags need special treatment since they are a more complex map (= :tag key) (change-tags state delta) :else (do (if (neg? delta) (deduct state side [key (- delta)]) (swap! state update-in [side key] (partial + delta))) (change-msg state side key (get-in @state [side key]) delta)))) (defn move-card "Called when the user drags a card from one zone to another." [state side {:keys [card server]}] (let [c (get-card state card) ;; hack: if dragging opponent's card from play-area (Indexing), the previous line will fail ;; to find the card. the next line will search in the other player's play-area. c (or c (get-card state (assoc card :side (other-side (to-keyword (:side card)))))) last-zone (last (:zone c)) src (name-zone (:side c) (:zone c)) from-str (when-not (nil? src) (if (= :content last-zone) (str " in " src) ; this string matches the message when a card is trashed via (trash) (str " from their " src))) label (if (and (not= last-zone :play-area) (not (and (= (:side c) "Runner") (= last-zone :hand) (= server "Grip"))) (or (and (= (:side c) "Runner") (not (:facedown c))) (rezzed? c) (:seen c) (= last-zone :deck))) (:title c) "a card") s (if (#{"HQ" "R&D" "Archives"} server) :corp :runner)] ;; allow moving from play-area always, otherwise only when same side, and to valid zone (when (and (not= src server) (same-side? s (:side card)) (or (= last-zone :play-area) (same-side? side (:side card)))) (let [move-card-to (partial move state s (dissoc c :seen :rezzed)) log-move (fn [verb & text] (system-msg state side (str verb " " label from-str (when (seq text) (apply str " " text)))))] (case server ("Heap" "Archives") (if (= :hand (first (:zone c))) ;; Discard from hand, do not trigger trash (do (move-card-to :discard {:force true}) (log-move "discards")) (do (trash state s c {:unpreventable true}) (log-move "trashes"))) ("Grip" "HQ") (do (move-card-to :hand {:force true}) (log-move "moves" "to " server)) ("Stack" "R&D") (do (move-card-to :deck {:front true :force true}) (log-move "moves" "to the top of " server)) ;; default nil))))) (defn concede "Trigger game concede by specified side. Takes a third argument for use with user commands." ([state side _] (concede state side)) ([state side] (system-msg state side "concedes") (win state (if (= side :corp) :runner :corp) "Concede"))) (defn- finish-prompt [state side prompt card] (when-let [end-effect (:end-effect prompt)] (end-effect state side (make-eid state) card nil)) ;; remove the prompt from the queue (swap! state update-in [side :prompt] (fn [pr] (filter #(not= % prompt) pr))) ;; This is a dirty hack to end the run when the last access prompt is resolved. (when (empty? (get-in @state [:runner :prompt])) (when-let [run (:run @state)] (when (:ended run) (handle-end-run state :runner))) (swap! state dissoc :access)) true) (defn resolve-prompt "Resolves a prompt by invoking its effect function with the selected target of the prompt. Triggered by a selection of a prompt choice button in the UI." [state side {:keys [choice card] :as args}] (let [servercard (get-card state card) card (if (not= (:title card) (:title servercard)) (@all-cards (:title card)) servercard) prompt (first (get-in @state [side :prompt])) choices (:choices prompt)] (cond ;; Shortcut (= choice "Cancel") (do (if-let [cancel-effect (:cancel-effect prompt)] ;; trigger the cancel effect (cancel-effect choice) (effect-completed state side (:eid prompt))) (finish-prompt state side prompt card)) ;; Integer prompts (or (= choices :credit) (:counter choices) (:number choices)) (if (number? choice) (do (when (= choices :credit) ; :credit prompts require payment (pay state side card :credit (min choice (get-in @state [side :credit])))) (when (:counter choices) ;; :Counter prompts deduct counters from the card (add-counter state side (:card prompt) (:counter choices) (- choice))) ;; trigger the prompt's effect function (when-let [effect-prompt (:effect prompt)] (effect-prompt (or choice card))) (finish-prompt state side prompt card)) (.println *err* "Error in an integer prompt")) ;; List of card titles for auto-completion (:card-title choices) (if (string? choice) (let [title-fn (:card-title choices) found (some #(when (= (lower-case choice) (lower-case (:title % ""))) %) (vals @all-cards))] (if found (if (title-fn state side (make-eid state) (:card prompt) [found]) (do (when-let [effect-prompt (:effect prompt)] (effect-prompt (or choice card))) (finish-prompt state side prompt card)) (toast state side (str "You cannot choose " choice " for this effect.") "warning")) (toast state side (str "Could not find a card named " choice ".") "warning"))) (.println *err* "Error in a card-title prompt")) ;; Default text prompt :else (let [buttons (filter #(or (= choice %) (= card %) (let [choice-str (if (string? choice) (lower-case choice) (lower-case (:title choice "do-not-match")))] (or (= choice-str (lower-case %)) (= choice-str (lower-case (:title % "")))))) choices) button (first buttons)] (if button (do (when-let [effect-prompt (:effect prompt)] (effect-prompt button)) (finish-prompt state side prompt card)) (.println *err* "Error in a text prompt")))))) (defn select "Attempt to select the given card to satisfy the current select prompt. Calls resolve-select if the max number of cards has been selected." [state side {:keys [card] :as args}] (let [card (get-card state card) r (get-in @state [side :selected 0 :req]) cid (get-in @state [side :selected 0 :not-self])] (when (and (not= (:cid card) cid) (or (not r) (r card))) (let [c (update-in card [:selected] not)] (update! state side c) (if (:selected c) (swap! state update-in [side :selected 0 :cards] #(conj % c)) (swap! state update-in [side :selected 0 :cards] (fn [coll] (remove-once #(= (:cid %) (:cid card)) coll)))) (let [selected (get-in @state [side :selected 0])] (when (= (count (:cards selected)) (or (:max selected) 1)) (resolve-select state side))))))) (defn- do-play-ability [state side card ability targets] (let [cost (:cost ability)] (when (or (nil? cost) (if (has-subtype? card "Run") (apply can-pay? state side (:title card) cost (get-in @state [:bonus :run-cost])) (apply can-pay? state side (:title card) cost))) (when-let [activatemsg (:activatemsg ability)] (system-msg state side activatemsg)) (resolve-ability state side ability card targets)))) (defn play-ability "Triggers a card's ability using its zero-based index into the card's card-def :abilities vector." [state side {:keys [card ability targets] :as args}] (let [card (get-card state card) cdef (card-def card) abilities (:abilities cdef) ab (if (= ability (count abilities)) ;; recurring credit abilities are not in the :abilities map and are implicit {:msg "take 1 [Recurring Credits]" :req (req (pos? (get-counters card :recurring))) :effect (req (add-prop state side card :rec-counter -1) (gain state side :credit 1) (when (has-subtype? card "Stealth") (trigger-event state side :spent-stealth-credit card)))} (get-in cdef [:abilities ability]))] (when-not (:disabled card) (do-play-ability state side card ab targets)))) (defn play-auto-pump "Use the 'match strength with ice' function of icebreakers." [state side args] (let [run (:run @state) card (get-card state (:card args)) run-ice (get-run-ices state) ice-cnt (count run-ice) ice-idx (dec (:position run 0)) in-range (and (pos? ice-cnt) (< -1 ice-idx ice-cnt)) current-ice (when (and run in-range) (get-card state (run-ice ice-idx))) pumpabi (some #(when (:pump %) %) (:abilities (card-def card))) pumpcst (when pumpabi (second (drop-while #(and (not= % :credit) (not= % "credit")) (:cost pumpabi)))) strdif (when current-ice (max 0 (- (or (:current-strength current-ice) (:strength current-ice)) (or (:current-strength card) (:strength card))))) pumpnum (when strdif (int (Math/ceil (/ strdif (:pump pumpabi 1)))))] (when (and pumpnum pumpcst (>= (get-in @state [:runner :credit]) (* pumpnum pumpcst))) (dotimes [n pumpnum] (resolve-ability state side (dissoc pumpabi :msg) (get-card state card) nil)) (system-msg state side (str "spends " (* pumpnum pumpcst) " [Credits] to increase the strength of " (:title card) " to " (:current-strength (get-card state card))))))) (defn play-copy-ability "Play an ability from another card's definition." [state side {:keys [card source index] :as args}] (let [card (get-card state card) source-abis (:abilities (cards (.replace source "'" ""))) abi (when (< -1 index (count source-abis)) (nth source-abis index))] (when abi (do-play-ability state side card abi nil)))) (def dynamic-abilities {"auto-pump" play-auto-pump "copy" play-copy-ability}) (defn play-dynamic-ability "Triggers an ability that was dynamically added to a card's data but is not necessarily present in its :abilities vector." [state side args] ((dynamic-abilities (:dynamic args)) state (keyword side) args)) (defn play-corp-ability "Triggers a runner card's corp-ability using its zero-based index into the card's card-def :corp-abilities vector." [state side {:keys [card ability targets] :as args}] (let [card (get-card state card) cdef (card-def card) ab (get-in cdef [:corp-abilities ability])] (do-play-ability state side card ab targets))) (defn play-runner-ability "Triggers a corp card's runner-ability using its zero-based index into the card's card-def :runner-abilities vector." [state side {:keys [card ability targets] :as args}] (let [card (get-card state card) cdef (card-def card) ab (get-in cdef [:runner-abilities ability])] (do-play-ability state side card ab targets))) (defn play-subroutine "Triggers a card's subroutine using its zero-based index into the card's :subroutines vector." ([state side args] (let [eid (make-eid state {:source (-> args :card :title) :source-type :subroutine})] (play-subroutine state side eid args))) ([state side eid {:keys [card subroutine targets] :as args}] (let [card (get-card state card) sub (nth (:subroutines card) subroutine nil)] (if (or (nil? sub) (nil? (:from-cid sub))) (let [cdef-idx (if (nil? sub) subroutine (-> sub :data :cdef-idx)) cdef (card-def card) cdef-sub (get-in cdef [:subroutines cdef-idx]) cost (:cost cdef-sub)] (when (or (nil? cost) (apply can-pay? state side (:title card) cost)) (when-let [activatemsg (:activatemsg cdef-sub)] (system-msg state side activatemsg)) (resolve-ability state side eid cdef-sub card targets))) (when-let [sub-card (find-latest state {:cid (:from-cid sub) :side side})] (when-let [sub-effect (:sub-effect (card-def sub-card))] (resolve-ability state side eid sub-effect card (assoc (:data sub) :targets targets)))))))) ;;; Corp actions (defn trash-resource "Click to trash a resource." [state side args] (let [trash-cost (max 0 (- 2 (get-in @state [:corp :trash-cost-bonus] 0)))] (when-let [cost-str (pay state side nil :click 1 :credit trash-cost {:action :corp-trash-resource})] (resolve-ability state side {:prompt "Choose a resource to trash" :choices {:req (fn [card] (if (and (seq (filter (fn [c] (untrashable-while-resources? c)) (all-active-installed state :runner))) (> (count (filter #(is-type? % "Resource") (all-active-installed state :runner))) 1)) (and (is-type? card "Resource") (not (untrashable-while-resources? card))) (is-type? card "Resource")))} :cancel-effect (effect (gain :credit trash-cost :click 1)) :effect (effect (trash target) (system-msg (str (build-spend-msg cost-str "trash") (:title target))))} nil nil)))) (defn do-purge "Purge viruses." [state side args] (when-let [cost (pay state side nil :click 3 {:action :corp-click-purge})] (purge state side) (let [spent (build-spend-msg cost "purge") message (str spent "all virus counters")] (system-msg state side message)) (play-sfx state side "virus-purge"))) (defn rez "Rez a corp card." ([state side card] (rez state side (make-eid state) card nil)) ([state side card args] (rez state side (make-eid state) card args)) ([state side eid {:keys [disabled] :as card} {:keys [ignore-cost no-warning force no-get-card paid-alt cached-bonus] :as args}] (let [card (if no-get-card card (get-card state card)) altcost (when-not no-get-card (:alternative-cost (card-def card)))] (when cached-bonus (rez-cost-bonus state side cached-bonus)) (if (or force (can-rez? state side card)) (do (trigger-event state side :pre-rez card) (if (or (#{"Asset" "ICE" "Upgrade"} (:type card)) (:install-rezzed (card-def card))) (do (trigger-event state side :pre-rez-cost card) (if (and altcost (can-pay? state side nil altcost)(not ignore-cost)) (let [curr-bonus (get-rez-cost-bonus state side)] (prompt! state side card (str "Pay the alternative Rez cost?") ["Yes" "No"] {:async true :effect (req (if (and (= target "Yes") (can-pay? state side (:title card) altcost)) (do (pay state side card altcost) (rez state side eid (-> card (dissoc :alternative-cost)) (merge args {:ignore-cost true :no-get-card true :paid-alt true}))) (do (rez state side eid (-> card (dissoc :alternative-cost)) (merge args {:no-get-card true :cached-bonus curr-bonus})))))})) (let [cdef (card-def card) cost (rez-cost state side card) costs (concat (when-not ignore-cost [:credit cost]) (when (and (not= ignore-cost :all-costs) (not (:disabled card))) (:additional-cost cdef)))] (when-let [cost-str (apply pay state side card costs)] ;; Deregister the derezzed-events before rezzing card (when (:derezzed-events cdef) (unregister-events state side card)) (if-not disabled (card-init state side (assoc card :rezzed :this-turn)) (update! state side (assoc card :rezzed :this-turn))) (doseq [h (:hosted card)] (update! state side (-> h (update-in [:zone] #(map to-keyword %)) (update-in [:host :zone] #(map to-keyword %))))) (system-msg state side (str (build-spend-msg cost-str "rez" "rezzes") (:title card) (cond paid-alt " by paying its alternative cost" ignore-cost " at no cost"))) (when (and (not no-warning) (:corp-phase-12 @state)) (toast state :corp "You are not allowed to rez cards between Start of Turn and Mandatory Draw. Please rez prior to clicking Start Turn in the future." "warning" {:time-out 0 :close-button true})) (if (ice? card) (do (update-ice-strength state side card) (play-sfx state side "rez-ice")) (play-sfx state side "rez-other")) (swap! state update-in [:stats :corp :cards :rezzed] (fnil inc 0)) (trigger-event-sync state side eid :rez card))))) (effect-completed state side eid)) (swap! state update-in [:bonus] dissoc :cost)) (effect-completed state side eid))))) (defn derez "Derez a corp card." [state side card] (let [card (get-card state card)] (system-msg state side (str "derezzes " (:title card))) (update! state :corp (deactivate state :corp card true)) (let [cdef (card-def card)] (when-let [derez-effect (:derez-effect cdef)] (resolve-ability state side derez-effect (get-card state card) nil)) (when-let [dre (:derezzed-events cdef)] (register-events state side dre card))) (trigger-event state side :derez card side))) (defn advance "Advance a corp card that can be advanced. If you pass in a truthy value as the 4th parameter, it will advance at no cost (for the card Success)." ([state side {:keys [card]}] (advance state side card nil)) ([state side card no-cost] (let [card (get-card state card)] (when (can-advance? state side card) (when-let [cost (pay state side card :click (if-not no-cost 1 0) :credit (if-not no-cost 1 0) {:action :corp-advance})] (let [spent (build-spend-msg cost "advance") card (card-str state card) message (str spent card)] (system-msg state side message)) (update-advancement-cost state side card) (add-prop state side (get-card state card) :advance-counter 1) (play-sfx state side "click-advance")))))) (defn score "Score an agenda. It trusts the card data passed to it." ([state side args] (score state side (make-eid state) args)) ([state side eid args] (let [card (or (:card args) args)] (when (and (can-score? state side card) (empty? (filter #(= (:cid card) (:cid %)) (get-in @state [:corp :register :cannot-score]))) (>= (get-counters card :advancement) (or (:current-cost card) (:advancementcost card)))) ;; do not card-init necessarily. if card-def has :effect, wrap a fake event (let [moved-card (move state :corp card :scored) c (card-init state :corp moved-card {:resolve-effect false :init-data true}) points (get-agenda-points state :corp c)] (trigger-event-simult state :corp eid :agenda-scored {:first-ability {:effect (req (when-let [current (first (get-in @state [:runner :current]))] ;; TODO: Make this use remove-old-current (system-say state side (str (:title current) " is trashed.")) ; This is to handle Employee Strike with damage IDs #2688 (when (:disable-id (card-def current)) (swap! state assoc-in [:corp :disable-id] true)) (trash state side current)))} :card-ability (card-as-handler c) :after-active-player {:effect (req (let [c (get-card state c) points (or (get-agenda-points state :corp c) points)] (set-prop state :corp (get-card state moved-card) :advance-counter 0) (system-msg state :corp (str "scores " (:title c) " and gains " (quantify points "agenda point"))) (swap! state update-in [:corp :register :scored-agenda] #(+ (or % 0) points)) (swap! state dissoc-in [:corp :disable-id]) (gain-agenda-point state :corp points) (play-sfx state side "agenda-score")))}} c)))))) (defn no-action "The corp indicates they have no more actions for the encounter." [state side args] (swap! state assoc-in [:run :no-action] true) (system-msg state side "has no further action") (trigger-event state side :no-action) (let [run-ice (get-run-ices state) pos (get-in @state [:run :position]) ice (when (and pos (pos? pos) (<= pos (count run-ice))) (get-card state (nth run-ice (dec pos))))] (when (rezzed? ice) (trigger-event state side :encounter-ice ice) (update-ice-strength state side ice)))) ;;; Runner actions (defn click-run "Click to start a run." [state side {:keys [server] :as args}] (let [cost-bonus (get-in @state [:bonus :run-cost]) click-cost-bonus (get-in @state [:bonus :click-run-cost])] (when (and (can-run? state side) (can-run-server? state server) (can-pay? state :runner "a run" :click 1 cost-bonus click-cost-bonus)) (swap! state assoc-in [:runner :register :made-click-run] true) (when-let [cost-str (pay state :runner nil :click 1 cost-bonus click-cost-bonus)] (run state side server) (system-msg state :runner (str (build-spend-msg cost-str "make a run on") server)) (play-sfx state side "click-run"))))) (defn remove-tag "Click to remove a tag." [state side args] (let [remove-cost (max 0 (- 2 (get-in @state [:runner :tag-remove-bonus] 0)))] (when-let [cost-str (pay state side nil :click 1 :credit remove-cost)] (lose-tags state :runner 1) (system-msg state side (build-spend-msg cost-str "remove 1 tag")) (play-sfx state side "click-remove-tag")))) (defn continue "The runner decides to approach the next ice, or the server itself." [state side args] (when (get-in @state [:run :no-action]) (let [run-ice (get-run-ices state) pos (get-in @state [:run :position]) cur-ice (when (and pos (pos? pos) (<= pos (count run-ice))) (get-card state (nth run-ice (dec pos)))) next-ice (when (and pos (< 1 pos) (<= (dec pos) (count run-ice))) (get-card state (nth run-ice (- pos 2))))] (wait-for (trigger-event-sync state side :pass-ice cur-ice) (do (update-ice-in-server state side (get-in @state (concat [:corp :servers] (get-in @state [:run :server])))) (swap! state update-in [:run :position] (fnil dec 1)) (swap! state assoc-in [:run :no-action] false) (system-msg state side "continues the run") (when cur-ice (update-ice-strength state side cur-ice)) (if next-ice (trigger-event-sync state side (make-eid state) :approach-ice next-ice) (trigger-event-sync state side (make-eid state) :approach-server)) (doseq [p (filter #(has-subtype? % "Icebreaker") (all-active-installed state :runner))] (update! state side (update-in (get-card state p) [:pump] dissoc :encounter)) (update-breaker-strength state side p))))))) (defn view-deck "Allows the player to view their deck by making the cards in the deck public." [state side args] (system-msg state side "looks at their deck") (swap! state assoc-in [side :view-deck] true)) (defn close-deck "Closes the deck view and makes cards in deck private again." [state side args] (system-msg state side "stops looking at their deck") (swap! state update-in [side] dissoc :view-deck))
true
(in-ns 'game.core) ;; These functions are called by main.clj in response to commands sent by users. (declare available-mu card-str can-rez? can-advance? corp-install effect-as-handler enforce-msg gain-agenda-point get-remote-names get-run-ices jack-out move name-zone play-instant purge resolve-select run runner-install trash update-breaker-strength update-ice-in-server update-run-ice win can-run? can-run-server? can-score? say play-sfx base-mod-size free-mu) ;;; Neutral actions (defn play "Called when the player clicks a card from hand." [state side {:keys [card server]}] (when-let [card (get-card state card)] (case (:type card) ("Event" "Operation") (play-instant state side card {:extra-cost [:click 1]}) ("Hardware" "Resource" "Program") (runner-install state side (make-eid state) card {:extra-cost [:click 1]}) ("ICE" "Upgrade" "Asset" "Agenda") (corp-install state side card server {:extra-cost [:click 1] :action :corp-click-install})) (trigger-event state side :play card))) (defn shuffle-deck "Shuffle R&D/Stack." [state side {:keys [close] :as args}] (swap! state update-in [side :deck] shuffle) (if close (do (swap! state update-in [side] dissoc :view-deck) (system-msg state side "stops looking at their deck and shuffles it")) (system-msg state side "shuffles their deck"))) (defn click-draw "Click to draw." [state side args] (when (and (not (get-in @state [side :register :cannot-draw])) (pay state side nil :click 1 {:action :corp-click-draw})) (system-msg state side "spends [Click] to draw a card") (trigger-event state side (if (= side :corp) :corp-click-draw :runner-click-draw) (->> @state side :deck (take 1))) (draw state side) (swap! state update-in [:stats side :click :draw] (fnil inc 0)) (play-sfx state side "click-card"))) (defn click-credit "Click to gain 1 credit." [state side args] (when (pay state side nil :click 1 {:action :corp-click-credit}) (system-msg state side "spends [Click] to gain 1 [Credits]") (gain-credits state side 1 (keyword (str (name side) "-click-credit"))) (swap! state update-in [:stats side :click :credit] (fnil inc 0)) (trigger-event state side (if (= side :corp) :corp-click-credit :runner-click-credit)) (play-sfx state side "click-credit"))) (defn- change-msg "Send a system message indicating the property change" [state side kw new-val delta] (let [key (PI:KEY:<KEY>END_PI)] (system-msg state side (str "sets " (.replace key "-" " ") " to " new-val " (" (if (pos? delta) (str "+" delta) delta) ")")))) (defn- change-map "Change a player's property using the :mod system" [state side key delta] (gain state side key {:mod delta}) (change-msg state side key (base-mod-size state side key) delta)) (defn- change-mu "Send a system message indicating how mu was changed" [state side delta] (free-mu state delta) (system-msg state side (str "sets unused MU to " (available-mu state) " (" (if (pos? delta) (str "+" delta) delta) ")"))) (defn- change-tags "Change a player's base tag count" [state delta] (if (neg? delta) (deduct state :runner [:tag (Math/abs delta)]) (gain state :runner :tag delta)) (system-msg state :runner (str "sets Tags to " (get-in @state [:runner :tag :base]) " (" (if (pos? delta) (str "+" delta) delta) ")"))) (defn change "Increase/decrease a player's property (clicks, credits, MU, etc.) by delta." [state side {:keys [key delta]}] (cond ;; Memory needs special treatment and message (= :memory key) (change-mu state side delta) ;; Hand size needs special treatment as it expects a map (= :hand-size key) (change-map state side key delta) ;; Tags need special treatment since they are a more complex map (= :tag key) (change-tags state delta) :else (do (if (neg? delta) (deduct state side [key (- delta)]) (swap! state update-in [side key] (partial + delta))) (change-msg state side key (get-in @state [side key]) delta)))) (defn move-card "Called when the user drags a card from one zone to another." [state side {:keys [card server]}] (let [c (get-card state card) ;; hack: if dragging opponent's card from play-area (Indexing), the previous line will fail ;; to find the card. the next line will search in the other player's play-area. c (or c (get-card state (assoc card :side (other-side (to-keyword (:side card)))))) last-zone (last (:zone c)) src (name-zone (:side c) (:zone c)) from-str (when-not (nil? src) (if (= :content last-zone) (str " in " src) ; this string matches the message when a card is trashed via (trash) (str " from their " src))) label (if (and (not= last-zone :play-area) (not (and (= (:side c) "Runner") (= last-zone :hand) (= server "Grip"))) (or (and (= (:side c) "Runner") (not (:facedown c))) (rezzed? c) (:seen c) (= last-zone :deck))) (:title c) "a card") s (if (#{"HQ" "R&D" "Archives"} server) :corp :runner)] ;; allow moving from play-area always, otherwise only when same side, and to valid zone (when (and (not= src server) (same-side? s (:side card)) (or (= last-zone :play-area) (same-side? side (:side card)))) (let [move-card-to (partial move state s (dissoc c :seen :rezzed)) log-move (fn [verb & text] (system-msg state side (str verb " " label from-str (when (seq text) (apply str " " text)))))] (case server ("Heap" "Archives") (if (= :hand (first (:zone c))) ;; Discard from hand, do not trigger trash (do (move-card-to :discard {:force true}) (log-move "discards")) (do (trash state s c {:unpreventable true}) (log-move "trashes"))) ("Grip" "HQ") (do (move-card-to :hand {:force true}) (log-move "moves" "to " server)) ("Stack" "R&D") (do (move-card-to :deck {:front true :force true}) (log-move "moves" "to the top of " server)) ;; default nil))))) (defn concede "Trigger game concede by specified side. Takes a third argument for use with user commands." ([state side _] (concede state side)) ([state side] (system-msg state side "concedes") (win state (if (= side :corp) :runner :corp) "Concede"))) (defn- finish-prompt [state side prompt card] (when-let [end-effect (:end-effect prompt)] (end-effect state side (make-eid state) card nil)) ;; remove the prompt from the queue (swap! state update-in [side :prompt] (fn [pr] (filter #(not= % prompt) pr))) ;; This is a dirty hack to end the run when the last access prompt is resolved. (when (empty? (get-in @state [:runner :prompt])) (when-let [run (:run @state)] (when (:ended run) (handle-end-run state :runner))) (swap! state dissoc :access)) true) (defn resolve-prompt "Resolves a prompt by invoking its effect function with the selected target of the prompt. Triggered by a selection of a prompt choice button in the UI." [state side {:keys [choice card] :as args}] (let [servercard (get-card state card) card (if (not= (:title card) (:title servercard)) (@all-cards (:title card)) servercard) prompt (first (get-in @state [side :prompt])) choices (:choices prompt)] (cond ;; Shortcut (= choice "Cancel") (do (if-let [cancel-effect (:cancel-effect prompt)] ;; trigger the cancel effect (cancel-effect choice) (effect-completed state side (:eid prompt))) (finish-prompt state side prompt card)) ;; Integer prompts (or (= choices :credit) (:counter choices) (:number choices)) (if (number? choice) (do (when (= choices :credit) ; :credit prompts require payment (pay state side card :credit (min choice (get-in @state [side :credit])))) (when (:counter choices) ;; :Counter prompts deduct counters from the card (add-counter state side (:card prompt) (:counter choices) (- choice))) ;; trigger the prompt's effect function (when-let [effect-prompt (:effect prompt)] (effect-prompt (or choice card))) (finish-prompt state side prompt card)) (.println *err* "Error in an integer prompt")) ;; List of card titles for auto-completion (:card-title choices) (if (string? choice) (let [title-fn (:card-title choices) found (some #(when (= (lower-case choice) (lower-case (:title % ""))) %) (vals @all-cards))] (if found (if (title-fn state side (make-eid state) (:card prompt) [found]) (do (when-let [effect-prompt (:effect prompt)] (effect-prompt (or choice card))) (finish-prompt state side prompt card)) (toast state side (str "You cannot choose " choice " for this effect.") "warning")) (toast state side (str "Could not find a card named " choice ".") "warning"))) (.println *err* "Error in a card-title prompt")) ;; Default text prompt :else (let [buttons (filter #(or (= choice %) (= card %) (let [choice-str (if (string? choice) (lower-case choice) (lower-case (:title choice "do-not-match")))] (or (= choice-str (lower-case %)) (= choice-str (lower-case (:title % "")))))) choices) button (first buttons)] (if button (do (when-let [effect-prompt (:effect prompt)] (effect-prompt button)) (finish-prompt state side prompt card)) (.println *err* "Error in a text prompt")))))) (defn select "Attempt to select the given card to satisfy the current select prompt. Calls resolve-select if the max number of cards has been selected." [state side {:keys [card] :as args}] (let [card (get-card state card) r (get-in @state [side :selected 0 :req]) cid (get-in @state [side :selected 0 :not-self])] (when (and (not= (:cid card) cid) (or (not r) (r card))) (let [c (update-in card [:selected] not)] (update! state side c) (if (:selected c) (swap! state update-in [side :selected 0 :cards] #(conj % c)) (swap! state update-in [side :selected 0 :cards] (fn [coll] (remove-once #(= (:cid %) (:cid card)) coll)))) (let [selected (get-in @state [side :selected 0])] (when (= (count (:cards selected)) (or (:max selected) 1)) (resolve-select state side))))))) (defn- do-play-ability [state side card ability targets] (let [cost (:cost ability)] (when (or (nil? cost) (if (has-subtype? card "Run") (apply can-pay? state side (:title card) cost (get-in @state [:bonus :run-cost])) (apply can-pay? state side (:title card) cost))) (when-let [activatemsg (:activatemsg ability)] (system-msg state side activatemsg)) (resolve-ability state side ability card targets)))) (defn play-ability "Triggers a card's ability using its zero-based index into the card's card-def :abilities vector." [state side {:keys [card ability targets] :as args}] (let [card (get-card state card) cdef (card-def card) abilities (:abilities cdef) ab (if (= ability (count abilities)) ;; recurring credit abilities are not in the :abilities map and are implicit {:msg "take 1 [Recurring Credits]" :req (req (pos? (get-counters card :recurring))) :effect (req (add-prop state side card :rec-counter -1) (gain state side :credit 1) (when (has-subtype? card "Stealth") (trigger-event state side :spent-stealth-credit card)))} (get-in cdef [:abilities ability]))] (when-not (:disabled card) (do-play-ability state side card ab targets)))) (defn play-auto-pump "Use the 'match strength with ice' function of icebreakers." [state side args] (let [run (:run @state) card (get-card state (:card args)) run-ice (get-run-ices state) ice-cnt (count run-ice) ice-idx (dec (:position run 0)) in-range (and (pos? ice-cnt) (< -1 ice-idx ice-cnt)) current-ice (when (and run in-range) (get-card state (run-ice ice-idx))) pumpabi (some #(when (:pump %) %) (:abilities (card-def card))) pumpcst (when pumpabi (second (drop-while #(and (not= % :credit) (not= % "credit")) (:cost pumpabi)))) strdif (when current-ice (max 0 (- (or (:current-strength current-ice) (:strength current-ice)) (or (:current-strength card) (:strength card))))) pumpnum (when strdif (int (Math/ceil (/ strdif (:pump pumpabi 1)))))] (when (and pumpnum pumpcst (>= (get-in @state [:runner :credit]) (* pumpnum pumpcst))) (dotimes [n pumpnum] (resolve-ability state side (dissoc pumpabi :msg) (get-card state card) nil)) (system-msg state side (str "spends " (* pumpnum pumpcst) " [Credits] to increase the strength of " (:title card) " to " (:current-strength (get-card state card))))))) (defn play-copy-ability "Play an ability from another card's definition." [state side {:keys [card source index] :as args}] (let [card (get-card state card) source-abis (:abilities (cards (.replace source "'" ""))) abi (when (< -1 index (count source-abis)) (nth source-abis index))] (when abi (do-play-ability state side card abi nil)))) (def dynamic-abilities {"auto-pump" play-auto-pump "copy" play-copy-ability}) (defn play-dynamic-ability "Triggers an ability that was dynamically added to a card's data but is not necessarily present in its :abilities vector." [state side args] ((dynamic-abilities (:dynamic args)) state (keyword side) args)) (defn play-corp-ability "Triggers a runner card's corp-ability using its zero-based index into the card's card-def :corp-abilities vector." [state side {:keys [card ability targets] :as args}] (let [card (get-card state card) cdef (card-def card) ab (get-in cdef [:corp-abilities ability])] (do-play-ability state side card ab targets))) (defn play-runner-ability "Triggers a corp card's runner-ability using its zero-based index into the card's card-def :runner-abilities vector." [state side {:keys [card ability targets] :as args}] (let [card (get-card state card) cdef (card-def card) ab (get-in cdef [:runner-abilities ability])] (do-play-ability state side card ab targets))) (defn play-subroutine "Triggers a card's subroutine using its zero-based index into the card's :subroutines vector." ([state side args] (let [eid (make-eid state {:source (-> args :card :title) :source-type :subroutine})] (play-subroutine state side eid args))) ([state side eid {:keys [card subroutine targets] :as args}] (let [card (get-card state card) sub (nth (:subroutines card) subroutine nil)] (if (or (nil? sub) (nil? (:from-cid sub))) (let [cdef-idx (if (nil? sub) subroutine (-> sub :data :cdef-idx)) cdef (card-def card) cdef-sub (get-in cdef [:subroutines cdef-idx]) cost (:cost cdef-sub)] (when (or (nil? cost) (apply can-pay? state side (:title card) cost)) (when-let [activatemsg (:activatemsg cdef-sub)] (system-msg state side activatemsg)) (resolve-ability state side eid cdef-sub card targets))) (when-let [sub-card (find-latest state {:cid (:from-cid sub) :side side})] (when-let [sub-effect (:sub-effect (card-def sub-card))] (resolve-ability state side eid sub-effect card (assoc (:data sub) :targets targets)))))))) ;;; Corp actions (defn trash-resource "Click to trash a resource." [state side args] (let [trash-cost (max 0 (- 2 (get-in @state [:corp :trash-cost-bonus] 0)))] (when-let [cost-str (pay state side nil :click 1 :credit trash-cost {:action :corp-trash-resource})] (resolve-ability state side {:prompt "Choose a resource to trash" :choices {:req (fn [card] (if (and (seq (filter (fn [c] (untrashable-while-resources? c)) (all-active-installed state :runner))) (> (count (filter #(is-type? % "Resource") (all-active-installed state :runner))) 1)) (and (is-type? card "Resource") (not (untrashable-while-resources? card))) (is-type? card "Resource")))} :cancel-effect (effect (gain :credit trash-cost :click 1)) :effect (effect (trash target) (system-msg (str (build-spend-msg cost-str "trash") (:title target))))} nil nil)))) (defn do-purge "Purge viruses." [state side args] (when-let [cost (pay state side nil :click 3 {:action :corp-click-purge})] (purge state side) (let [spent (build-spend-msg cost "purge") message (str spent "all virus counters")] (system-msg state side message)) (play-sfx state side "virus-purge"))) (defn rez "Rez a corp card." ([state side card] (rez state side (make-eid state) card nil)) ([state side card args] (rez state side (make-eid state) card args)) ([state side eid {:keys [disabled] :as card} {:keys [ignore-cost no-warning force no-get-card paid-alt cached-bonus] :as args}] (let [card (if no-get-card card (get-card state card)) altcost (when-not no-get-card (:alternative-cost (card-def card)))] (when cached-bonus (rez-cost-bonus state side cached-bonus)) (if (or force (can-rez? state side card)) (do (trigger-event state side :pre-rez card) (if (or (#{"Asset" "ICE" "Upgrade"} (:type card)) (:install-rezzed (card-def card))) (do (trigger-event state side :pre-rez-cost card) (if (and altcost (can-pay? state side nil altcost)(not ignore-cost)) (let [curr-bonus (get-rez-cost-bonus state side)] (prompt! state side card (str "Pay the alternative Rez cost?") ["Yes" "No"] {:async true :effect (req (if (and (= target "Yes") (can-pay? state side (:title card) altcost)) (do (pay state side card altcost) (rez state side eid (-> card (dissoc :alternative-cost)) (merge args {:ignore-cost true :no-get-card true :paid-alt true}))) (do (rez state side eid (-> card (dissoc :alternative-cost)) (merge args {:no-get-card true :cached-bonus curr-bonus})))))})) (let [cdef (card-def card) cost (rez-cost state side card) costs (concat (when-not ignore-cost [:credit cost]) (when (and (not= ignore-cost :all-costs) (not (:disabled card))) (:additional-cost cdef)))] (when-let [cost-str (apply pay state side card costs)] ;; Deregister the derezzed-events before rezzing card (when (:derezzed-events cdef) (unregister-events state side card)) (if-not disabled (card-init state side (assoc card :rezzed :this-turn)) (update! state side (assoc card :rezzed :this-turn))) (doseq [h (:hosted card)] (update! state side (-> h (update-in [:zone] #(map to-keyword %)) (update-in [:host :zone] #(map to-keyword %))))) (system-msg state side (str (build-spend-msg cost-str "rez" "rezzes") (:title card) (cond paid-alt " by paying its alternative cost" ignore-cost " at no cost"))) (when (and (not no-warning) (:corp-phase-12 @state)) (toast state :corp "You are not allowed to rez cards between Start of Turn and Mandatory Draw. Please rez prior to clicking Start Turn in the future." "warning" {:time-out 0 :close-button true})) (if (ice? card) (do (update-ice-strength state side card) (play-sfx state side "rez-ice")) (play-sfx state side "rez-other")) (swap! state update-in [:stats :corp :cards :rezzed] (fnil inc 0)) (trigger-event-sync state side eid :rez card))))) (effect-completed state side eid)) (swap! state update-in [:bonus] dissoc :cost)) (effect-completed state side eid))))) (defn derez "Derez a corp card." [state side card] (let [card (get-card state card)] (system-msg state side (str "derezzes " (:title card))) (update! state :corp (deactivate state :corp card true)) (let [cdef (card-def card)] (when-let [derez-effect (:derez-effect cdef)] (resolve-ability state side derez-effect (get-card state card) nil)) (when-let [dre (:derezzed-events cdef)] (register-events state side dre card))) (trigger-event state side :derez card side))) (defn advance "Advance a corp card that can be advanced. If you pass in a truthy value as the 4th parameter, it will advance at no cost (for the card Success)." ([state side {:keys [card]}] (advance state side card nil)) ([state side card no-cost] (let [card (get-card state card)] (when (can-advance? state side card) (when-let [cost (pay state side card :click (if-not no-cost 1 0) :credit (if-not no-cost 1 0) {:action :corp-advance})] (let [spent (build-spend-msg cost "advance") card (card-str state card) message (str spent card)] (system-msg state side message)) (update-advancement-cost state side card) (add-prop state side (get-card state card) :advance-counter 1) (play-sfx state side "click-advance")))))) (defn score "Score an agenda. It trusts the card data passed to it." ([state side args] (score state side (make-eid state) args)) ([state side eid args] (let [card (or (:card args) args)] (when (and (can-score? state side card) (empty? (filter #(= (:cid card) (:cid %)) (get-in @state [:corp :register :cannot-score]))) (>= (get-counters card :advancement) (or (:current-cost card) (:advancementcost card)))) ;; do not card-init necessarily. if card-def has :effect, wrap a fake event (let [moved-card (move state :corp card :scored) c (card-init state :corp moved-card {:resolve-effect false :init-data true}) points (get-agenda-points state :corp c)] (trigger-event-simult state :corp eid :agenda-scored {:first-ability {:effect (req (when-let [current (first (get-in @state [:runner :current]))] ;; TODO: Make this use remove-old-current (system-say state side (str (:title current) " is trashed.")) ; This is to handle Employee Strike with damage IDs #2688 (when (:disable-id (card-def current)) (swap! state assoc-in [:corp :disable-id] true)) (trash state side current)))} :card-ability (card-as-handler c) :after-active-player {:effect (req (let [c (get-card state c) points (or (get-agenda-points state :corp c) points)] (set-prop state :corp (get-card state moved-card) :advance-counter 0) (system-msg state :corp (str "scores " (:title c) " and gains " (quantify points "agenda point"))) (swap! state update-in [:corp :register :scored-agenda] #(+ (or % 0) points)) (swap! state dissoc-in [:corp :disable-id]) (gain-agenda-point state :corp points) (play-sfx state side "agenda-score")))}} c)))))) (defn no-action "The corp indicates they have no more actions for the encounter." [state side args] (swap! state assoc-in [:run :no-action] true) (system-msg state side "has no further action") (trigger-event state side :no-action) (let [run-ice (get-run-ices state) pos (get-in @state [:run :position]) ice (when (and pos (pos? pos) (<= pos (count run-ice))) (get-card state (nth run-ice (dec pos))))] (when (rezzed? ice) (trigger-event state side :encounter-ice ice) (update-ice-strength state side ice)))) ;;; Runner actions (defn click-run "Click to start a run." [state side {:keys [server] :as args}] (let [cost-bonus (get-in @state [:bonus :run-cost]) click-cost-bonus (get-in @state [:bonus :click-run-cost])] (when (and (can-run? state side) (can-run-server? state server) (can-pay? state :runner "a run" :click 1 cost-bonus click-cost-bonus)) (swap! state assoc-in [:runner :register :made-click-run] true) (when-let [cost-str (pay state :runner nil :click 1 cost-bonus click-cost-bonus)] (run state side server) (system-msg state :runner (str (build-spend-msg cost-str "make a run on") server)) (play-sfx state side "click-run"))))) (defn remove-tag "Click to remove a tag." [state side args] (let [remove-cost (max 0 (- 2 (get-in @state [:runner :tag-remove-bonus] 0)))] (when-let [cost-str (pay state side nil :click 1 :credit remove-cost)] (lose-tags state :runner 1) (system-msg state side (build-spend-msg cost-str "remove 1 tag")) (play-sfx state side "click-remove-tag")))) (defn continue "The runner decides to approach the next ice, or the server itself." [state side args] (when (get-in @state [:run :no-action]) (let [run-ice (get-run-ices state) pos (get-in @state [:run :position]) cur-ice (when (and pos (pos? pos) (<= pos (count run-ice))) (get-card state (nth run-ice (dec pos)))) next-ice (when (and pos (< 1 pos) (<= (dec pos) (count run-ice))) (get-card state (nth run-ice (- pos 2))))] (wait-for (trigger-event-sync state side :pass-ice cur-ice) (do (update-ice-in-server state side (get-in @state (concat [:corp :servers] (get-in @state [:run :server])))) (swap! state update-in [:run :position] (fnil dec 1)) (swap! state assoc-in [:run :no-action] false) (system-msg state side "continues the run") (when cur-ice (update-ice-strength state side cur-ice)) (if next-ice (trigger-event-sync state side (make-eid state) :approach-ice next-ice) (trigger-event-sync state side (make-eid state) :approach-server)) (doseq [p (filter #(has-subtype? % "Icebreaker") (all-active-installed state :runner))] (update! state side (update-in (get-card state p) [:pump] dissoc :encounter)) (update-breaker-strength state side p))))))) (defn view-deck "Allows the player to view their deck by making the cards in the deck public." [state side args] (system-msg state side "looks at their deck") (swap! state assoc-in [side :view-deck] true)) (defn close-deck "Closes the deck view and makes cards in deck private again." [state side args] (system-msg state side "stops looking at their deck") (swap! state update-in [side] dissoc :view-deck))
[ { "context": "ozilla.org/MPL/2.0/.\n;;\n;; Copyright (c) 2016-2022 Andrey Antukh <niwi@niwi.nz>\n\n(ns user\n (:require\n [clojure.", "end": 245, "score": 0.9998846054077148, "start": 232, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ".0/.\n;;\n;; Copyright (c) 2016-2022 Andrey Antukh <niwi@niwi.nz>\n\n(ns user\n (:require\n [clojure.spec.alpha :as", "end": 259, "score": 0.9999316334724426, "start": 247, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
test/user.clj
updcon/buddy-core
0
;; This Source Code Form is subject to the terms of the Mozilla Public ;; License, v. 2.0. If a copy of the MPL was not distributed with this ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. ;; ;; Copyright (c) 2016-2022 Andrey Antukh <niwi@niwi.nz> (ns user (:require [clojure.spec.alpha :as s] [clojure.tools.namespace.repl :as repl] [clojure.walk :refer [macroexpand-all]] [clojure.pprint :refer [pprint]] [clojure.test :as test] [clojure.java.io :as io] [clojure.repl :refer :all] [criterium.core :refer [quick-bench bench with-progress-reporting]])) (defmacro run-quick-bench [& exprs] `(with-progress-reporting (quick-bench (do ~@exprs) :verbose))) (defmacro run-quick-bench' [& exprs] `(quick-bench (do ~@exprs))) (defmacro run-bench [& exprs] `(with-progress-reporting (bench (do ~@exprs) :verbose))) (defmacro run-bench' [& exprs] `(bench (do ~@exprs))) (defn run-tests ([] (run-tests #".*-tests$")) ([o] (repl/refresh) (cond (instance? java.util.regex.Pattern o) (test/run-all-tests o) (symbol? o) (if-let [sns (namespace o)] (do (require (symbol sns)) (test/test-vars [(resolve o)])) (test/test-ns o)))))
47508
;; This Source Code Form is subject to the terms of the Mozilla Public ;; License, v. 2.0. If a copy of the MPL was not distributed with this ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. ;; ;; Copyright (c) 2016-2022 <NAME> <<EMAIL>> (ns user (:require [clojure.spec.alpha :as s] [clojure.tools.namespace.repl :as repl] [clojure.walk :refer [macroexpand-all]] [clojure.pprint :refer [pprint]] [clojure.test :as test] [clojure.java.io :as io] [clojure.repl :refer :all] [criterium.core :refer [quick-bench bench with-progress-reporting]])) (defmacro run-quick-bench [& exprs] `(with-progress-reporting (quick-bench (do ~@exprs) :verbose))) (defmacro run-quick-bench' [& exprs] `(quick-bench (do ~@exprs))) (defmacro run-bench [& exprs] `(with-progress-reporting (bench (do ~@exprs) :verbose))) (defmacro run-bench' [& exprs] `(bench (do ~@exprs))) (defn run-tests ([] (run-tests #".*-tests$")) ([o] (repl/refresh) (cond (instance? java.util.regex.Pattern o) (test/run-all-tests o) (symbol? o) (if-let [sns (namespace o)] (do (require (symbol sns)) (test/test-vars [(resolve o)])) (test/test-ns o)))))
true
;; This Source Code Form is subject to the terms of the Mozilla Public ;; License, v. 2.0. If a copy of the MPL was not distributed with this ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. ;; ;; Copyright (c) 2016-2022 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (ns user (:require [clojure.spec.alpha :as s] [clojure.tools.namespace.repl :as repl] [clojure.walk :refer [macroexpand-all]] [clojure.pprint :refer [pprint]] [clojure.test :as test] [clojure.java.io :as io] [clojure.repl :refer :all] [criterium.core :refer [quick-bench bench with-progress-reporting]])) (defmacro run-quick-bench [& exprs] `(with-progress-reporting (quick-bench (do ~@exprs) :verbose))) (defmacro run-quick-bench' [& exprs] `(quick-bench (do ~@exprs))) (defmacro run-bench [& exprs] `(with-progress-reporting (bench (do ~@exprs) :verbose))) (defmacro run-bench' [& exprs] `(bench (do ~@exprs))) (defn run-tests ([] (run-tests #".*-tests$")) ([o] (repl/refresh) (cond (instance? java.util.regex.Pattern o) (test/run-all-tests o) (symbol? o) (if-let [sns (namespace o)] (do (require (symbol sns)) (test/test-vars [(resolve o)])) (test/test-ns o)))))
[ { "context": "ector 1 2 3 4))\n(defn mapify [] (hash-map \"name\" \"Alexander\" \"class\" \"Intro to Clojure\"))\n(defn setify [] (ha", "end": 479, "score": 0.9994388818740845, "start": 470, "tag": "NAME", "value": "Alexander" }, { "context": "contains? m :name) (= (str/lower-case (:name m)) \"alex\")\n :default false))\n\n(defn guess-number\n [a b", "end": 1121, "score": 0.6064196825027466, "start": 1117, "tag": "NAME", "value": "alex" } ]
src/clojure_intro_examples/simple_functions.clj
leftofnull/clojure_intro_examples
0
(ns clojure-intro-examples.simple-functions (:require [clojure.string :as str] [clojure.core.async :as a :refer [>! <! >!! <!! go chan buffer close! thread alts! alts!! timeout]])) (defn string-concat [data] (str "Hello " data " from " "the " "string " "concatenator" ".")) (defn listify [] (list 1 2 3 4)) (defn vectorize [] (vector 1 2 3 4)) (defn mapify [] (hash-map "name" "Alexander" "class" "Intro to Clojure")) (defn setify [] (hash-set 1 2 3 1 2 3 1 2 3)) (defn list->vec [l] (vec l)) (defn vec->set [v] (set v)) (defn multiply-100 [n] (* n 100)) (defn square [n] (* n n)) (defn cube [n] (* n n n)) (defn add-10 [n] (+ n 10)) (defn divide-by-2 [n] (/ n 2)) (defn name-from-map-by-key [m] (:name m)) (defn name-from-map-by-key-get [m] (get m :name)) (defn name-from-nested-map-by-key [m] (get-in m [:person :name])) (defn name-from-nested-map-by-key-composed [m] ((comp :name :person) m)) (defn even-number? [n] (= (mod n 2) 0)) (defn named-alex? [m] (cond (contains? m :name) (= (str/lower-case (:name m)) "alex") :default false)) (defn guess-number [a b] (->> a (* 2) (* b) (/ 2) (double) (- a) (Math/ceil) (int)))
28400
(ns clojure-intro-examples.simple-functions (:require [clojure.string :as str] [clojure.core.async :as a :refer [>! <! >!! <!! go chan buffer close! thread alts! alts!! timeout]])) (defn string-concat [data] (str "Hello " data " from " "the " "string " "concatenator" ".")) (defn listify [] (list 1 2 3 4)) (defn vectorize [] (vector 1 2 3 4)) (defn mapify [] (hash-map "name" "<NAME>" "class" "Intro to Clojure")) (defn setify [] (hash-set 1 2 3 1 2 3 1 2 3)) (defn list->vec [l] (vec l)) (defn vec->set [v] (set v)) (defn multiply-100 [n] (* n 100)) (defn square [n] (* n n)) (defn cube [n] (* n n n)) (defn add-10 [n] (+ n 10)) (defn divide-by-2 [n] (/ n 2)) (defn name-from-map-by-key [m] (:name m)) (defn name-from-map-by-key-get [m] (get m :name)) (defn name-from-nested-map-by-key [m] (get-in m [:person :name])) (defn name-from-nested-map-by-key-composed [m] ((comp :name :person) m)) (defn even-number? [n] (= (mod n 2) 0)) (defn named-alex? [m] (cond (contains? m :name) (= (str/lower-case (:name m)) "<NAME>") :default false)) (defn guess-number [a b] (->> a (* 2) (* b) (/ 2) (double) (- a) (Math/ceil) (int)))
true
(ns clojure-intro-examples.simple-functions (:require [clojure.string :as str] [clojure.core.async :as a :refer [>! <! >!! <!! go chan buffer close! thread alts! alts!! timeout]])) (defn string-concat [data] (str "Hello " data " from " "the " "string " "concatenator" ".")) (defn listify [] (list 1 2 3 4)) (defn vectorize [] (vector 1 2 3 4)) (defn mapify [] (hash-map "name" "PI:NAME:<NAME>END_PI" "class" "Intro to Clojure")) (defn setify [] (hash-set 1 2 3 1 2 3 1 2 3)) (defn list->vec [l] (vec l)) (defn vec->set [v] (set v)) (defn multiply-100 [n] (* n 100)) (defn square [n] (* n n)) (defn cube [n] (* n n n)) (defn add-10 [n] (+ n 10)) (defn divide-by-2 [n] (/ n 2)) (defn name-from-map-by-key [m] (:name m)) (defn name-from-map-by-key-get [m] (get m :name)) (defn name-from-nested-map-by-key [m] (get-in m [:person :name])) (defn name-from-nested-map-by-key-composed [m] ((comp :name :person) m)) (defn even-number? [n] (= (mod n 2) 0)) (defn named-alex? [m] (cond (contains? m :name) (= (str/lower-case (:name m)) "PI:NAME:<NAME>END_PI") :default false)) (defn guess-number [a b] (->> a (* 2) (* b) (/ 2) (double) (- a) (Math/ceil) (int)))
[ { "context": ";-\n; Copyright 2014-2015 © Meikel Brandmeyer.\n; All rights reserved.\n;\n; Licensed under the EU", "end": 44, "score": 0.999875545501709, "start": 27, "tag": "NAME", "value": "Meikel Brandmeyer" } ]
src/main/clojure/hay/stack.clj
pinky-editor/hay
2
;- ; Copyright 2014-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.stack (:require [hay.compiler :as compiler] [hay.engine :as engine] [hay.grammar :as grammar])) (def core-signatures {#'+ '[x y -- z] #'conj '[coll x -- coll] #'count '[coll -- n]}) (doseq [[v sig] core-signatures] (alter-meta! v assoc :hay/signature sig) (compiler/expose-var v)) (defn ^:private sig>args [sig] (if (= sig :thread) '[thread] (vec (take-while #(not= % '--) sig)))) (defn setword! [nspace wname value] (swap! engine/runtime assoc-in [:namespaces nspace :words wname] value)) (defmacro defword [fname & {:keys [namespace signature body] :or {namespace (ns-name *ns*)}}] `(setword! ~(name namespace) ~(name fname) (-> (fn ~(sig>args signature) ~body) (vary-meta assoc :hay/signature '~signature) compiler/compile))) (defword :map :signature [f s -- s] :body (map (engine/hay-call f) s)) (defword :. :signature :thread :body (let [[stack [block word]] (engine/pop-n (:stack thread) 2)] (setword! (get-in thread [:locals "*ns*"]) (name word) block) (assoc thread :stack stack))) (defn repl [] (loop [t (assoc-in (engine/>hay-thread nil) [:locals "*ns*"] "user")] (print (str (get-in t [:locals "*ns*"]) "⇒ ")) (flush) (let [words (map compiler/compile (grammar/read-string (read-line))) ins (mapcat :instructions words) t (engine/run (assoc t :instructions ins :state :running)) stack (:stack t)] (when-not (= (peek stack) :hay/exit) (doseq [v stack] (print " → ") (prn v)) (recur t)))))
98681
;- ; Copyright 2014-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.stack (:require [hay.compiler :as compiler] [hay.engine :as engine] [hay.grammar :as grammar])) (def core-signatures {#'+ '[x y -- z] #'conj '[coll x -- coll] #'count '[coll -- n]}) (doseq [[v sig] core-signatures] (alter-meta! v assoc :hay/signature sig) (compiler/expose-var v)) (defn ^:private sig>args [sig] (if (= sig :thread) '[thread] (vec (take-while #(not= % '--) sig)))) (defn setword! [nspace wname value] (swap! engine/runtime assoc-in [:namespaces nspace :words wname] value)) (defmacro defword [fname & {:keys [namespace signature body] :or {namespace (ns-name *ns*)}}] `(setword! ~(name namespace) ~(name fname) (-> (fn ~(sig>args signature) ~body) (vary-meta assoc :hay/signature '~signature) compiler/compile))) (defword :map :signature [f s -- s] :body (map (engine/hay-call f) s)) (defword :. :signature :thread :body (let [[stack [block word]] (engine/pop-n (:stack thread) 2)] (setword! (get-in thread [:locals "*ns*"]) (name word) block) (assoc thread :stack stack))) (defn repl [] (loop [t (assoc-in (engine/>hay-thread nil) [:locals "*ns*"] "user")] (print (str (get-in t [:locals "*ns*"]) "⇒ ")) (flush) (let [words (map compiler/compile (grammar/read-string (read-line))) ins (mapcat :instructions words) t (engine/run (assoc t :instructions ins :state :running)) stack (:stack t)] (when-not (= (peek stack) :hay/exit) (doseq [v stack] (print " → ") (prn v)) (recur t)))))
true
;- ; Copyright 2014-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.stack (:require [hay.compiler :as compiler] [hay.engine :as engine] [hay.grammar :as grammar])) (def core-signatures {#'+ '[x y -- z] #'conj '[coll x -- coll] #'count '[coll -- n]}) (doseq [[v sig] core-signatures] (alter-meta! v assoc :hay/signature sig) (compiler/expose-var v)) (defn ^:private sig>args [sig] (if (= sig :thread) '[thread] (vec (take-while #(not= % '--) sig)))) (defn setword! [nspace wname value] (swap! engine/runtime assoc-in [:namespaces nspace :words wname] value)) (defmacro defword [fname & {:keys [namespace signature body] :or {namespace (ns-name *ns*)}}] `(setword! ~(name namespace) ~(name fname) (-> (fn ~(sig>args signature) ~body) (vary-meta assoc :hay/signature '~signature) compiler/compile))) (defword :map :signature [f s -- s] :body (map (engine/hay-call f) s)) (defword :. :signature :thread :body (let [[stack [block word]] (engine/pop-n (:stack thread) 2)] (setword! (get-in thread [:locals "*ns*"]) (name word) block) (assoc thread :stack stack))) (defn repl [] (loop [t (assoc-in (engine/>hay-thread nil) [:locals "*ns*"] "user")] (print (str (get-in t [:locals "*ns*"]) "⇒ ")) (flush) (let [words (map compiler/compile (grammar/read-string (read-line))) ins (mapcat :instructions words) t (engine/run (assoc t :instructions ins :state :running)) stack (:stack t)] (when-not (= (peek stack) :hay/exit) (doseq [v stack] (print " → ") (prn v)) (recur t)))))
[ { "context": "short mail-address\n (is (pattern/valid-email? \"a@abc.jp\"))\n ;; valid mail-address\n (is (pattern/val", "end": 563, "score": 0.9991899728775024, "start": 555, "tag": "EMAIL", "value": "a@abc.jp" }, { "context": "valid mail-address\n (is (pattern/valid-email? \"test@example.com\"))\n ;; @ not found\n (is (not (pattern/valid", "end": 640, "score": 0.9995887875556946, "start": 624, "tag": "EMAIL", "value": "test@example.com" }, { "context": " mail-address\n (is (not (pattern/valid-email? \"test@example.com \")))\n ;; valid mail-address include symbol cha", "end": 805, "score": 0.9995473027229309, "start": 789, "tag": "EMAIL", "value": "test@example.com" }, { "context": " for japanese moby\n (is (pattern/valid-email? \"test..@example.com\"))\n ;; It's valid value of \"From:\" header, but", "end": 1041, "score": 0.8811428546905518, "start": 1023, "tag": "EMAIL", "value": "test..@example.com" }, { "context": "mail-address\n (is (not (pattern/valid-email? \"<test@example.com>\")))\n ;; It's valid, but it disturb consistenc", "end": 1168, "score": 0.9994251132011414, "start": 1152, "tag": "EMAIL", "value": "test@example.com" }, { "context": "this\n (is (not (pattern/valid-email? \"\\\"test\\\"@example.com\")))\n ;; It's valid, but should not allow this!", "end": 1305, "score": 0.8869244456291199, "start": 1294, "tag": "EMAIL", "value": "example.com" }, { "context": ".com\")))\n (is (not (pattern/valid-email? \"test%example.org@example.com\"))))\n\n (testing \"valid-password?\"\n (is (not (", "end": 1505, "score": 0.8089281916618347, "start": 1482, "tag": "EMAIL", "value": "example.org@example.com" }, { "context": "password? \"\")))\n (is (pattern/valid-password? \"1234abcd\"))\n (is (pattern/valid-password? \"ABCD!@#$\"))\n", "end": 1672, "score": 0.9994173049926758, "start": 1664, "tag": "PASSWORD", "value": "1234abcd" }, { "context": "ord? \"ABCD!@#$\"))\n (is (pattern/valid-password? \"%^&*()_+\"))\n (is (pattern/valid-password? \"<>\\\\\\\"'\"))\n ", "end": 1763, "score": 0.9419831037521362, "start": 1755, "tag": "PASSWORD", "value": "\"%^&*()_" }, { "context": "&*()_+\"))\n (is (pattern/valid-password? \"<>\\\\\\\"'\"))\n (is (not (pattern/valid-password? \"passwor", "end": 1808, "score": 0.6138191223144531, "start": 1808, "tag": "PASSWORD", "value": "" }, { "context": "sword \")))\n (is (not (pattern/valid-password? \"password\\n\")))\n (is (not (pattern/valid-password? \"passwo", "end": 1915, "score": 0.9973276257514954, "start": 1905, "tag": "PASSWORD", "value": "password\\n" }, { "context": "word\\n\")))\n (is (not (pattern/valid-password? \"password\\t\"))))\n\n (testing \"valid-uuid?\"\n (is (not (patt", "end": 1969, "score": 0.9957674145698547, "start": 1959, "tag": "PASSWORD", "value": "password\\t" } ]
test/proton/pattern_test.cljc
iku000888/proton
0
(ns proton.pattern-test (:require #?(:clj [clojure.test :refer [deftest is testing]] :cljs [cljs.test :refer-macros [deftest is testing]]) [proton.pattern :as pattern])) (deftest pattern-test (testing "valid-email?" (is (not (pattern/valid-email? nil))) ;; empty (is (not (pattern/valid-email? ""))) ;; only local-part (is (not (pattern/valid-email? "example"))) ;; only domain-part (is (not (pattern/valid-email? "example.com"))) ;; valid short mail-address (is (pattern/valid-email? "a@abc.jp")) ;; valid mail-address (is (pattern/valid-email? "test@example.com")) ;; @ not found (is (not (pattern/valid-email? "test_example.com"))) ;; extra spaced mail-address (is (not (pattern/valid-email? "test@example.com "))) ;; valid mail-address include symbol chars (is (pattern/valid-email? "test+!&-_=?@example.com")) ;; It's not valid(violation rfc), but it should allow for japanese moby (is (pattern/valid-email? "test..@example.com")) ;; It's valid value of "From:" header, but not valid mail-address (is (not (pattern/valid-email? "<test@example.com>"))) ;; It's valid, but it disturb consistency check, so may not allow this (is (not (pattern/valid-email? "\"test\"@example.com"))) ;; It's valid, but should not allow this! These are "source routing". (is (not (pattern/valid-email? "test%example.com"))) (is (not (pattern/valid-email? "test%example.org@example.com")))) (testing "valid-password?" (is (not (pattern/valid-password? nil))) (is (not (pattern/valid-password? ""))) (is (pattern/valid-password? "1234abcd")) (is (pattern/valid-password? "ABCD!@#$")) (is (pattern/valid-password? "%^&*()_+")) (is (pattern/valid-password? "<>\\\"'")) (is (not (pattern/valid-password? "password "))) (is (not (pattern/valid-password? "password\n"))) (is (not (pattern/valid-password? "password\t")))) (testing "valid-uuid?" (is (not (pattern/valid-uuid? nil))) (is (not (pattern/valid-uuid? ""))) (is (pattern/valid-uuid? "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"))))
79177
(ns proton.pattern-test (:require #?(:clj [clojure.test :refer [deftest is testing]] :cljs [cljs.test :refer-macros [deftest is testing]]) [proton.pattern :as pattern])) (deftest pattern-test (testing "valid-email?" (is (not (pattern/valid-email? nil))) ;; empty (is (not (pattern/valid-email? ""))) ;; only local-part (is (not (pattern/valid-email? "example"))) ;; only domain-part (is (not (pattern/valid-email? "example.com"))) ;; valid short mail-address (is (pattern/valid-email? "<EMAIL>")) ;; valid mail-address (is (pattern/valid-email? "<EMAIL>")) ;; @ not found (is (not (pattern/valid-email? "test_example.com"))) ;; extra spaced mail-address (is (not (pattern/valid-email? "<EMAIL> "))) ;; valid mail-address include symbol chars (is (pattern/valid-email? "test+!&-_=?@example.com")) ;; It's not valid(violation rfc), but it should allow for japanese moby (is (pattern/valid-email? "<EMAIL>")) ;; It's valid value of "From:" header, but not valid mail-address (is (not (pattern/valid-email? "<<EMAIL>>"))) ;; It's valid, but it disturb consistency check, so may not allow this (is (not (pattern/valid-email? "\"test\"@<EMAIL>"))) ;; It's valid, but should not allow this! These are "source routing". (is (not (pattern/valid-email? "test%example.com"))) (is (not (pattern/valid-email? "test%<EMAIL>")))) (testing "valid-password?" (is (not (pattern/valid-password? nil))) (is (not (pattern/valid-password? ""))) (is (pattern/valid-password? "<PASSWORD>")) (is (pattern/valid-password? "ABCD!@#$")) (is (pattern/valid-password? <PASSWORD>+")) (is (pattern/valid-password? "<>\\\"<PASSWORD>'")) (is (not (pattern/valid-password? "password "))) (is (not (pattern/valid-password? "<PASSWORD>"))) (is (not (pattern/valid-password? "<PASSWORD>")))) (testing "valid-uuid?" (is (not (pattern/valid-uuid? nil))) (is (not (pattern/valid-uuid? ""))) (is (pattern/valid-uuid? "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"))))
true
(ns proton.pattern-test (:require #?(:clj [clojure.test :refer [deftest is testing]] :cljs [cljs.test :refer-macros [deftest is testing]]) [proton.pattern :as pattern])) (deftest pattern-test (testing "valid-email?" (is (not (pattern/valid-email? nil))) ;; empty (is (not (pattern/valid-email? ""))) ;; only local-part (is (not (pattern/valid-email? "example"))) ;; only domain-part (is (not (pattern/valid-email? "example.com"))) ;; valid short mail-address (is (pattern/valid-email? "PI:EMAIL:<EMAIL>END_PI")) ;; valid mail-address (is (pattern/valid-email? "PI:EMAIL:<EMAIL>END_PI")) ;; @ not found (is (not (pattern/valid-email? "test_example.com"))) ;; extra spaced mail-address (is (not (pattern/valid-email? "PI:EMAIL:<EMAIL>END_PI "))) ;; valid mail-address include symbol chars (is (pattern/valid-email? "test+!&-_=?@example.com")) ;; It's not valid(violation rfc), but it should allow for japanese moby (is (pattern/valid-email? "PI:EMAIL:<EMAIL>END_PI")) ;; It's valid value of "From:" header, but not valid mail-address (is (not (pattern/valid-email? "<PI:EMAIL:<EMAIL>END_PI>"))) ;; It's valid, but it disturb consistency check, so may not allow this (is (not (pattern/valid-email? "\"test\"@PI:EMAIL:<EMAIL>END_PI"))) ;; It's valid, but should not allow this! These are "source routing". (is (not (pattern/valid-email? "test%example.com"))) (is (not (pattern/valid-email? "test%PI:EMAIL:<EMAIL>END_PI")))) (testing "valid-password?" (is (not (pattern/valid-password? nil))) (is (not (pattern/valid-password? ""))) (is (pattern/valid-password? "PI:PASSWORD:<PASSWORD>END_PI")) (is (pattern/valid-password? "ABCD!@#$")) (is (pattern/valid-password? PI:PASSWORD:<PASSWORD>END_PI+")) (is (pattern/valid-password? "<>\\\"PI:PASSWORD:<PASSWORD>END_PI'")) (is (not (pattern/valid-password? "password "))) (is (not (pattern/valid-password? "PI:PASSWORD:<PASSWORD>END_PI"))) (is (not (pattern/valid-password? "PI:PASSWORD:<PASSWORD>END_PI")))) (testing "valid-uuid?" (is (not (pattern/valid-uuid? nil))) (is (not (pattern/valid-uuid? ""))) (is (pattern/valid-uuid? "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"))))
[ { "context": "e) (hour 4 false) false)) :form :part-of-day)\n\n \"domattina\"\n [#\"(?i)domattina\"]\n (assoc (intersect (cycle-", "end": 12401, "score": 0.9769982695579529, "start": 12392, "tag": "NAME", "value": "domattina" }, { "context": "lse)) :form :part-of-day)\n\n \"domattina\"\n [#\"(?i)domattina\"]\n (assoc (intersect (cycle-nth :day 1) (interva", "end": 12421, "score": 0.7842332720756531, "start": 12412, "tag": "NAME", "value": "domattina" } ]
resources/languages/it/rules/time.clj
sebastianmika/duckling
0
( ;; generic "two time tokens in a row" [(dim :time #(not (:latent %))) (dim :time #(not (:latent %)))] ; sequence of two tokens with a time dimension (intersect %1 %2) ; same thing, with "de" in between like "domingo de la semana pasada" "two time tokens separated by `di`" [(dim :time #(not (:latent %))) #"(?i)de" (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn (intersect %1 %3) "in <named-month>" ; in September [#"(?i)in|del mese( di)?" {:form :month}] %2 ; does NOT dissoc latent ;; "named-day" #"(?i)luned[ìi]|lun?\.?" (day-of-week 1) "named-day" #"(?i)marted[iì]|mar?\.?" (day-of-week 2) "named-day" #"(?i)mercoled[iì]|mer?\.?" (day-of-week 3) "named-day" #"(?i)gioved[iì]|gio?\.?" (day-of-week 4) "named-day" #"(?i)venerd[iì]|ven?\.?" (day-of-week 5) "named-day" #"(?i)sabato|sab?\.?" (day-of-week 6) "named-day" #"(?i)domenica|dom?\.?" (day-of-week 7) "named-month" #"(?i)gennaio|genn?\.?" (month 1) "named-month" #"(?i)febbraio|febb?\.?" (month 2) "named-month" #"(?i)marzo|mar\.?" (month 3) "named-month" #"(?i)aprile|apr\.?" (month 4) "named-month" #"(?i)maggio|magg?\.?" (month 5) "named-month" #"(?i)giugno|giu\.?" (month 6) "named-month" #"(?i)luglio|lug\.?" (month 7) "named-month" #"(?i)agosto|ago\.?" (month 8) "named-month" #"(?i)settembre|sett?\.?" (month 9) "named-month" #"(?i)ottobre|ott\.?" (month 10) "named-month" #"(?i)novembre|nov\.?" (month 11) "named-month" #"(?i)dicembre|dic\.?" (month 12) ; Holiday TODO: check online holidays ; or define dynamyc rule (last thursday of october..) "christmas" #"(?i)((il )?giorno di )?natale" (month-day 12 25) "christmas eve" #"(?i)((al)?la )?vigig?lia( di natale)?" (month-day 12 24) "new year's eve" #"(?i)((la )?vigig?lia di capodanno|san silvestro)" (month-day 12 31) "new year's day" #"(?i)(capodanno|primo dell' ?anno)" (month-day 1 1) "epifania" #"(?i)(epifania|befana)" (month-day 1 6) "valentine's day" #"(?i)s(an|\.) valentino|festa degli innamorati" (month-day 2 14) "festa del papà" #"(?i)festa del pap[aà]|(festa di )?s(an|\.) giuseppe" (month-day 3 19) "festa della liberazione" #"(?i)((festa|anniversario) della|(al)?la) liberazione" (month-day 4 25) "festa del lavoro" #"(?i)festa del lavoro|(festa|giorno) dei lavoratori" (month-day 5 1) "festa della repubblica" #"(?i)((festa del)?la )?repubblica" (month-day 6 2) "ferragosto" #"(?i)ferragosto|assunzione" (month-day 8 15) "halloween day" #"(?i)hall?owe?en" (month-day 10 31) "ognissanti" #"(?i)(tutti i |ognis|festa dei |([ia]l )?giorno dei )santi" (month-day 11 1) "commemorazione dei defunti" #"(?i)((giorno dei|commemorazione dei|ai) )?(morti|defunti)" (month-day 11 2) "immacolata concezione" #"(?i)(all')?immacolata( concezione)?" (month-day 12 8) "santo stefano" #"(?i)s(anto|\.) stefano" (month-day 12 26) "Mother's Day";second Sunday in May. #"(?i)festa della mamma" (intersect (day-of-week 7) (month 5) (cycle-nth-after :week 1 (month-day 5 1))) "right now" #"(subito|immediatamente|proprio adesso|in questo momento)" (cycle-nth :second 0) "now" #"(?i)(ora|al momento|attualmente|adesso|(di )?oggi|in giornata)" (cycle-nth :day 0) "tomorrow" #"(?i)domani" (cycle-nth :day 1) "yesterday" #"(?i)ieri" (cycle-nth :day -1) "EOM|End of month" #"(?i)fine del mese" (cycle-nth :month 1) "EOY|End of year" #"(?i)fine dell' ?anno" (cycle-nth :year 1) "the day after tomorrow" #"(?i)(il giorno )?dopo\s?domani" (cycle-nth :day 2) "the day before yesterday" #"(?i)(l')?altro\s?ieri" (cycle-nth :day -2) ;; ;; This, Next, Last ;; assumed to be strictly in the future: ;; "this Monday" => next week if today in Monday "this <day-of-week>" ; assumed to be in the future [#"(?i)quest[oaie]" {:form :day-of-week}] (pred-nth-not-immediate %2 0) ;; for other preds, it can be immediate: ;; "this month" => now is part of it ; See also: cycles in en.cycles.clj "this <time>" [#"(?i)quest[oaie']" (dim :time)] (pred-nth %2 0) "next <time>" [#"(?i)prossim[ao]" (dim :time)] (pred-nth %2 1) "next <time>" [(dim :time) #"(?i)dopo|prossim[ao]"] (pred-nth %1 1) "prossimi <unit-of-duration>" [#"(?i)((ne)?i|(nel)?le) prossim[ie]" (dim :unit-of-duration)] (interval (cycle-nth (:grain %2) 1) (cycle-nth (:grain %2) 3) true) "<time> last" [(dim :time) #"(?i)(ultim|scors|passat)[oaie]"] (pred-nth %1 -1) "last <time> " [#"(?i)(ultim|scors|passat)[oaie]" (dim :time)] (pred-nth %2 -1) "last <day-of-week> of <time>" [#"(?i)(l')ultim[oa]" {:form :day-of-week} #"(?i)di" (dim :time)] (pred-last-of %2 %4) "last <cycle> of <time>" [#"(?i)(l')ultim[oa]" (dim :cycle) #"(?i)di|del(l[oa'])" (dim :time)] (cycle-last-of %2 %4) ; Ordinals "nth <time> of <time>" [(dim :ordinal) (dim :time) #"(?i)di|del(l[oa'])|in" (dim :time)] (pred-nth (intersect %4 %2) (dec (:value %1))) "nth <time> of <time>" [#"(?i)il|l'" (dim :ordinal) (dim :time) #"(?i)di|del(l[oa'])|in" (dim :time)] (pred-nth (intersect %5 %3) (dec (:value %2))) "nth <time> after <time>" [(dim :ordinal) (dim :time) #"(?i)dopo" (dim :time)] (pred-nth-after %2 %4 (dec (:value %1))) "nth <time> after <time>" [#"(?i)il|l'" (dim :ordinal) (dim :time) #"(?i)dopo" (dim :time)] (pred-nth-after %3 %5 (dec (:value %2))) ; Years ; Between 1000 and 2100 we assume it's a year ; Outside of this, it's safer to consider it's latent "year (1000-2100 not latent)" (integer 1000 2100) (year (:value %1)) "year (latent)" (integer -10000 -1) (assoc (year (:value %1)) :latent true) "year (latent)" (integer 2101 10000) (assoc (year (:value %1)) :latent true) ; Day of month appears in the following context: ; - the nth ; - March nth ; - nth of March ; - mm/dd (and other numerical formats like yyyy-mm-dd etc.) ; In general we are flexible and accept both ordinals (3rd) and numbers (3) "day of month (1st)" [#"(?i)(primo|1o|1º|1°)( di)?"]; (day-of-month 1) "the <day-of-month>" ; this one is not latent [#"(?i)il" (integer 1 31)] (assoc (day-of-month (:value %2)) :latent true) "<day-of-month> <named-month>" ; dodici luglio 2010 (this rule removes latency) [(integer 1 31) {:form :month}] (intersect %2 (day-of-month (:value %1))) "<named-day> <day-of-month>" ; Friday 18 [{:form :day-of-week} (integer 1 31)] (intersect %1 (day-of-month (:value %2))) "il <day-of-month> de <named-month>" ; il dodici luglio 2010 [#"(?i)il" (integer 1 31) {:form :month}] (intersect %3 (day-of-month (:value %2))) ;; hours and minutes (absolute time) "<integer> (latent time-of-day)" (integer 0 24) (assoc (hour (:value %1) false) :latent true) "le idi di <named-month>" ; the ides of march 13th for most months, but on the 15th for March, May, July, and October [#"(?i)(le )?idi di" {:form :month}] (intersect %2 (day-of-month (if (#{3 5 7 10} (:month %2)) 15 13))) "noon" #"(?i)mezz?ogiorno" (hour 12 false) "midnight" #"(?i)mez?zanott?e" (hour 0 false) "<time-of-day> ora" [#"(?i)or[ea]" #(:full-hour %)] (dissoc %2 :latent) "at <time-of-day>" ; alle due [#"(?i)all[e']|le|a" {:form :time-of-day}] (dissoc %2 :latent) "hh(:|h)mm (time-of-day)" #"((?:[01]?\d)|(?:2[0-3]))[:h]([0-5]\d)" (hour-minute (Integer/parseInt (first (:groups %1))) (Integer/parseInt (second (:groups %1))) false) "hh(:|h)mm (time-of-day)" #"(?i)((?:0?\d)|(?:1[0-2]))[:h]([0-5]\d) d(i|el(la)?) (pomeriggio|(sta)?(sera|notte))" (hour-minute (+ 12 (Integer/parseInt (first (:groups %1)))) (Integer/parseInt (second (:groups %1))) false) ; specific rule to address "3 in the afternoon", "9 in the evening" "<integer 0 12> del <part of day>" [(integer 0 12) #"(?i)d(i|el(la)?) (pomeriggio|(sta)?(sera|notte))"] (hour (+ 12 (:value %1)) false) "hh <relative-minutes> del pomeriggio(time-of-day)" [(dim :time :full-hour) #(:relative-minutes %) #"(?i)d(i|el(la)?) (pomeriggio|(sta)?(sera|notte))"] (if (< 12 (:full-hour %1)) (dissoc %1 :latent) (hour-relativemin (+ 12 (:full-hour %1)) (:relative-minutes %2) false)) "hh <relative-minutes> del pomeriggio(time-of-day)" [(dim :time :full-hour) #"e" #(:relative-minutes %) #"(?i)d(i|el(la)?)" #"(pomeriggio|(sta)?(sera|notte))"] (if (< 12 (:full-hour %1)) (dissoc %1 :latent) (hour-relativemin (+ 12 (:full-hour %1)) (:relative-minutes %3) false)) "hhmm (military time-of-day)" #"(?i)((?:[01]?\d)|(?:2[0-3]))([0-5]\d)" (-> (hour-minute (Integer/parseInt (first (:groups %1))) (Integer/parseInt (second (:groups %1))) false) ; not a 12-hour clock (assoc :latent true)) "una" #"(?i)una" (hour 1 true) "quarter (relative minutes)" #"(?i)un quarto" {:relative-minutes 15} "trois quarts (relative minutes)" #"(?i)(3|tre) quarti?" {:relative-minutes 45} "half (relative minutes)" #"mezzo" {:relative-minutes 30} "number (as relative minutes)" (integer 1 59) {:relative-minutes (:value %1)} "<integer> minutes (as relative minutes)" [(integer 1 59) #"(?i)min\.?(ut[oi])?"] {:relative-minutes (:val %1)} "<hour-of-day> <integer> (as relative minutes)" [(dim :time :full-hour) #(:relative-minutes %)] ;before [{:for-relative-minutes true} #(:relative-minutes %)] (hour-relativemin (:full-hour %1) (:relative-minutes %2) (:twelve-hour-clock? %1)) "<hour-of-day> minus <integer> (as relative minutes)" [(dim :time :full-hour) #"meno" #(:relative-minutes %)] (hour-relativemin (:full-hour %1) (- (:relative-minutes %3)) (:twelve-hour-clock? %1)) "relative minutes to <integer> (as hour-of-day)" [#(:relative-minutes %) #"(?i)a" (dim :time :full-hour)] (hour-relativemin (:full-hour %3) (- (:relative-minutes %1)) true) "<hour-of-day> and <relative minutes>" [(dim :time :full-hour) #"e" #(:relative-minutes %)] (hour-relativemin (:full-hour %1) (:relative-minutes %3) (:twelve-hour-clock? %1)) ;; Formatted dates and times "dd[/-]mm[/-]yyyy" #"(3[01]|[12]\d|0?[1-9])[/-](0?[1-9]|1[0-2])[/-](\d{2,4})" (parse-dmy (first (:groups %1)) (second (:groups %1)) (nth (:groups %1) 2) true) "yyyy-mm-dd" #"(\d{2,4})-(0?[1-9]|1[0-2])-(3[01]|[12]\d|0?[1-9])" (parse-dmy (nth (:groups %1) 2) (second (:groups %1)) (first (:groups %1)) true) "dd[/-]mm" #"(3[01]|[12]\d|0?[1-9])[/-](0?[1-9]|1[0-2])" (parse-dmy (first (:groups %1)) (second (:groups %1)) nil true) ; Part of day (morning, evening...). They are intervals. "morning" #"(?i)mattin(ata|[aoe])" (assoc (interval (hour 4 false) (hour 12 false) false) :form :part-of-day :latent true) "lunch" #"(?i)(a )?pranzo" (assoc (interval (hour 12 false) (hour 14 false) false) :form :part-of-day :latent true) "afternoon" #"(?i)pomeriggio?" (assoc (interval (hour 12 false) (hour 19 false) false) :form :part-of-day :latent true) "evening" #"(?i)ser(ata|[ae])" (assoc (interval (hour 18 false) (hour 0 false) false) :form :part-of-day :latent true) "night" #"(?i)nott(e|ata)" (assoc (intersect (cycle-nth :day 1) (interval (hour 0 false) (hour 4 false) false)) :form :part-of-day :latent true) "this <part-of-day>" [#"(?i)quest[oa]|sta|in|nel(la)?" {:form :part-of-day}] (assoc (intersect (cycle-nth :day 0) %2) :form :part-of-day) ;; removes :latent "<time> notte" [(dim :time) #"(?i)((in|nella|alla) )?nott(e|ata)"] (intersect (cycle-nth-after :day 1 %1) (interval (hour 0 false) (hour 4 false) false)) "<time> notte" [#"(?i)((nella|alla) )?nott(e|ata)( d(i|el))" (dim :time)] (intersect (cycle-nth-after :day 1 %2) (interval (hour 0 false) (hour 4 false) false)) "stamattina" [#"(?i)stamattina"] (assoc (intersect (cycle-nth :day 0) (interval (hour 4 false) (hour 12 false) false)) :form :part-of-day) "stasera" [#"(?i)stasera"] (assoc (intersect (cycle-nth :day 0) (interval (hour 18 false) (hour 0 false) false)) :form :part-of-day) "stanotte" [#"(?i)stanotte"] (assoc (intersect (cycle-nth :day 1) (interval (hour 0 false) (hour 4 false) false)) :form :part-of-day) "domattina" [#"(?i)domattina"] (assoc (intersect (cycle-nth :day 1) (interval (hour 4 false) (hour 12 false) false)) :form :part-of-day) "<dim time> <part-of-day>" ; since "morning" "evening" etc. are latent, general time+time is blocked [(dim :time) {:form :part-of-day}] (intersect %1 %2) "<part-of-day> of <dim time>" ; since "morning" "evening" etc. are latent, general time+time is blocked [{:form :part-of-day} #"(?i)d(i|el)" (dim :time)] (intersect %1 %3) "in the <part-of-day> of <dim time>" ; since "morning" "evening" etc. are latent, general time+time is blocked [#"(?i)nel(la)?" {:form :part-of-day} #"(?i)d(i|el)" (dim :time)] (intersect %2 %4) "<dim time> al <part-of-day>" ; since "morning" "evening" etc. are latent, general time+time is blocked [(dim :time) #"(?i)al|nel(la)?|in|d(i|el(la)?)" {:form :part-of-day}] (intersect %1 %3) ;specific rule to address "3 in the morning","3h du matin" and extend morning span from 0 to 12 "<dim time> del mattino" [{:form :time-of-day} #"del mattino"] (intersect %1 (assoc (interval (hour 0 false) (hour 12 false) false) :form :part-of-day :latent true)) ; Other intervals: week-end, seasons "week-end" #"(?i)week[ -]?end|fine ?settimana|we" (interval (intersect (day-of-week 5) (hour 18 false)) (intersect (day-of-week 1) (hour 0 false)) false) "season" #"(?i)(in )?estate" ;could be smarter and take the exact hour into account... also some years the day can change (interval (month-day 6 21) (month-day 9 23) false) "season" #"(?i)(in )?autunno" (interval (month-day 9 23) (month-day 12 21) false) "season" #"(?i)(in )?inverno" (interval (month-day 12 21) (month-day 3 20) false) "season" #"(?i)(in )?primavera" (interval (month-day 3 20) (month-day 6 21) false) ; Absorptions ; a specific version of "il", above, removes :latent for integer as day of month ; this one is more general but does not remove latency "il <time>" [#"(?i)il" (dim :time #(not (:latent %)))] %2 ;; Time zones "timezone" #"(?i)(YEKT|YEKST|YAPT|YAKT|YAKST|WT|WST|WITA|WIT|WIB|WGT|WGST|WFT|WEZ|WET|WESZ|WEST|WAT|WAST|VUT|VLAT|VLAST|VET|UZT|UYT|UYST|UTC|ULAT|TVT|TMT|TLT|TKT|TJT|TFT|TAHT|SST|SRT|SGT|SCT|SBT|SAST|SAMT|RET|PYT|PYST|PWT|PT|PST|PONT|PMST|PMDT|PKT|PHT|PHOT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|NCT|MYT|MVT|MUT|MST|MSK|MSD|MMT|MHT|MEZ|MESZ|MDT|MAWT|MART|MAGT|MAGST|LINT|LHST|LHDT|KUYT|KST|KRAT|KRAST|KGT|JST|IST|IRST|IRKT|IRKST|IRDT|IOT|IDT|ICT|HOVT|HNY|HNT|HNR|HNP|HNE|HNC|HNA|HLV|HKT|HAY|HAT|HAST|HAR|HAP|HAE|HADT|HAC|HAA|GYT|GST|GMT|GILT|GFT|GET|GAMT|GALT|FNT|FKT|FKST|FJT|FJST|ET|EST|EGT|EGST|EET|EEST|EDT|ECT|EAT|EAST|EASST|DAVT|ChST|CXT|CVT|CST|COT|CLT|CLST|CKT|CHAST|CHADT|CET|CEST|CDT|CCT|CAT|CAST|BTT|BST|BRT|BRST|BOT|BNT|AZT|AZST|AZOT|AZOST|AWST|AWDT|AST|ART|AQTT|ANAT|ANAST|AMT|AMST|ALMT|AKST|AKDT|AFT|AEST|AEDT|ADT|ACST|ACDT)" {:dim :timezone :value (-> %1 :groups first clojure.string/upper-case)} "<time> timezone" [(dim :time) (dim :timezone)] (assoc %1 :timezone (:value %2)) ; Precision ; FIXME ; - should be applied to all dims not just time-of-day ;- shouldn't remove latency, except maybe -ish "<time-of-day> circa" ; 7ish [{:form :time-of-day} #"(?i)circa"] (-> %1 (dissoc :latent) (merge {:precision "approximate"})) "<time-of-day> precise" ; sharp [{:form :time-of-day} #"(?i)precise"] (-> %1 (dissoc :latent) (merge {:precision "exact"})) "circa per le <time-of-day>" ; about [#"(?i)(circa )?per( le)?|circa( alle)?|verso( le)?" {:form :time-of-day}] (-> %2 (dissoc :latent) (merge {:precision "approximate"})) "verso <part-of-day>" ; about [#"(?i)verso( la| il)?" {:form :part-of-day}] (merge %2 {:precision "approximate"}) ; Intervals "dd-dd <month> (interval)" [#"(?i)(?:dal(?: |l'))?(3[01]|[12]\d|0?[1-9])" #"(?i)\-|([fs]ino )?al(l')?" #"(3[01]|[12]\d|0?[1-9])" {:form :month}] (interval (intersect %4 (day-of-month (Integer/parseInt (-> %1 :groups first)))) (intersect %4 (day-of-month (Integer/parseInt (-> %3 :groups first)))) true) "dd-dd <month> (interval)" [#"(?i)tra( il|l')?" #"(3[01]|[12]\d|0?[1-9])" #"(?i)e( il|l')?" #"(3[01]|[12]\d|0?[1-9])" {:form :month}] (interval (intersect %5 (day-of-month (Integer/parseInt (-> %2 :groups first)))) (intersect %5 (day-of-month (Integer/parseInt (-> %4 :groups first)))) true) ; Blocked for :latent time. May need to accept certain latents only, like hours "<datetime> - <datetime> (interval)" [(dim :time #(not (:latent %))) #"\-|[fs]ino a(l(l[e'])?)?" (dim :time #(not (:latent %)))] (interval %1 %3 true) "fino al <datetime> (interval)" [#"\-|[fs]ino a(l(l[ae'])?)?" (dim :time #(not (:latent %)))] (interval (cycle-nth :second 0) %2 false) "dal <datetime> al <datetime> (interval)" [#"(?i)da(l(l')?)?" (dim :time) #"\-|([fs]ino )?al(l')?" (dim :time)] (interval %2 %4 true) "tra il <datetime> e il <datetime> (interval)" [#"(?i)tra( il| l')?" (dim :time) #"e( il| l')?" (dim :time)] (interval %2 %4 true) "<time-of-day> - <time-of-day> <day-of-month> (interval)" [{:form :time-of-day} #"\-" {:form :time-of-day} (dim :time #(not (:latent %)))] (interval (intersect %1 %4) (intersect %3 %4) true) ; Specific for time-of-day, to help resolve ambiguities "dalle <time-of-day> alle <time-of-day> (interval)" [#"(?i)da(l(le|l')?)?" {:form :time-of-day} #"\-|([fs]ino )?a(l(l[e'])?)?" {:form :time-of-day}] (interval %2 %4 true) ; Specific for within duration... Would need to be reworked "in <duration>" [#"(?i)in|per|entro" (dim :duration)] (interval (cycle-nth :second 0) (in-duration (:value %2)) false) "entro il <duration>" [#"(?i)entro (il|l')|per (il|l[a'])|in|nel(l[a'])?" (dim :unit-of-duration)] (interval (cycle-nth :second 0) (cycle-nth (:grain %2) 1) false) ; One-sided Intervals "entro le <time-of-day>" [#"(?i)entro( l[ea'])?|prima d(i|ell['e])" (dim :time)] (merge %2 {:direction :before}) "dopo le <time-of-day>" [#"(?i)dopo l[e']|da(l(l['e])?)?" (dim :time)] (merge %2 {:direction :after}) "<time> dopo le <time-of-day>" [(dim :time) #"(?i)dopo l[e']|dall['e]" {:form :time-of-day}] (merge (intersect %1 %3) {:direction :after}) "<time> dopo le <time-of-day>" [(dim :time) #"(?i)dopo l[e']|dall['e]" {:form :time-of-day}] (merge (intersect %1 %3) {:direction :after}) "<time> entro le <time-of-day>" [(dim :time) #"(?i)entro( l[e'])?|prima d(i|ell['e])" (dim :time)] (merge (intersect %1 %3) {:direction :before}) )
43803
( ;; generic "two time tokens in a row" [(dim :time #(not (:latent %))) (dim :time #(not (:latent %)))] ; sequence of two tokens with a time dimension (intersect %1 %2) ; same thing, with "de" in between like "domingo de la semana pasada" "two time tokens separated by `di`" [(dim :time #(not (:latent %))) #"(?i)de" (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn (intersect %1 %3) "in <named-month>" ; in September [#"(?i)in|del mese( di)?" {:form :month}] %2 ; does NOT dissoc latent ;; "named-day" #"(?i)luned[ìi]|lun?\.?" (day-of-week 1) "named-day" #"(?i)marted[iì]|mar?\.?" (day-of-week 2) "named-day" #"(?i)mercoled[iì]|mer?\.?" (day-of-week 3) "named-day" #"(?i)gioved[iì]|gio?\.?" (day-of-week 4) "named-day" #"(?i)venerd[iì]|ven?\.?" (day-of-week 5) "named-day" #"(?i)sabato|sab?\.?" (day-of-week 6) "named-day" #"(?i)domenica|dom?\.?" (day-of-week 7) "named-month" #"(?i)gennaio|genn?\.?" (month 1) "named-month" #"(?i)febbraio|febb?\.?" (month 2) "named-month" #"(?i)marzo|mar\.?" (month 3) "named-month" #"(?i)aprile|apr\.?" (month 4) "named-month" #"(?i)maggio|magg?\.?" (month 5) "named-month" #"(?i)giugno|giu\.?" (month 6) "named-month" #"(?i)luglio|lug\.?" (month 7) "named-month" #"(?i)agosto|ago\.?" (month 8) "named-month" #"(?i)settembre|sett?\.?" (month 9) "named-month" #"(?i)ottobre|ott\.?" (month 10) "named-month" #"(?i)novembre|nov\.?" (month 11) "named-month" #"(?i)dicembre|dic\.?" (month 12) ; Holiday TODO: check online holidays ; or define dynamyc rule (last thursday of october..) "christmas" #"(?i)((il )?giorno di )?natale" (month-day 12 25) "christmas eve" #"(?i)((al)?la )?vigig?lia( di natale)?" (month-day 12 24) "new year's eve" #"(?i)((la )?vigig?lia di capodanno|san silvestro)" (month-day 12 31) "new year's day" #"(?i)(capodanno|primo dell' ?anno)" (month-day 1 1) "epifania" #"(?i)(epifania|befana)" (month-day 1 6) "valentine's day" #"(?i)s(an|\.) valentino|festa degli innamorati" (month-day 2 14) "festa del papà" #"(?i)festa del pap[aà]|(festa di )?s(an|\.) giuseppe" (month-day 3 19) "festa della liberazione" #"(?i)((festa|anniversario) della|(al)?la) liberazione" (month-day 4 25) "festa del lavoro" #"(?i)festa del lavoro|(festa|giorno) dei lavoratori" (month-day 5 1) "festa della repubblica" #"(?i)((festa del)?la )?repubblica" (month-day 6 2) "ferragosto" #"(?i)ferragosto|assunzione" (month-day 8 15) "halloween day" #"(?i)hall?owe?en" (month-day 10 31) "ognissanti" #"(?i)(tutti i |ognis|festa dei |([ia]l )?giorno dei )santi" (month-day 11 1) "commemorazione dei defunti" #"(?i)((giorno dei|commemorazione dei|ai) )?(morti|defunti)" (month-day 11 2) "immacolata concezione" #"(?i)(all')?immacolata( concezione)?" (month-day 12 8) "santo stefano" #"(?i)s(anto|\.) stefano" (month-day 12 26) "Mother's Day";second Sunday in May. #"(?i)festa della mamma" (intersect (day-of-week 7) (month 5) (cycle-nth-after :week 1 (month-day 5 1))) "right now" #"(subito|immediatamente|proprio adesso|in questo momento)" (cycle-nth :second 0) "now" #"(?i)(ora|al momento|attualmente|adesso|(di )?oggi|in giornata)" (cycle-nth :day 0) "tomorrow" #"(?i)domani" (cycle-nth :day 1) "yesterday" #"(?i)ieri" (cycle-nth :day -1) "EOM|End of month" #"(?i)fine del mese" (cycle-nth :month 1) "EOY|End of year" #"(?i)fine dell' ?anno" (cycle-nth :year 1) "the day after tomorrow" #"(?i)(il giorno )?dopo\s?domani" (cycle-nth :day 2) "the day before yesterday" #"(?i)(l')?altro\s?ieri" (cycle-nth :day -2) ;; ;; This, Next, Last ;; assumed to be strictly in the future: ;; "this Monday" => next week if today in Monday "this <day-of-week>" ; assumed to be in the future [#"(?i)quest[oaie]" {:form :day-of-week}] (pred-nth-not-immediate %2 0) ;; for other preds, it can be immediate: ;; "this month" => now is part of it ; See also: cycles in en.cycles.clj "this <time>" [#"(?i)quest[oaie']" (dim :time)] (pred-nth %2 0) "next <time>" [#"(?i)prossim[ao]" (dim :time)] (pred-nth %2 1) "next <time>" [(dim :time) #"(?i)dopo|prossim[ao]"] (pred-nth %1 1) "prossimi <unit-of-duration>" [#"(?i)((ne)?i|(nel)?le) prossim[ie]" (dim :unit-of-duration)] (interval (cycle-nth (:grain %2) 1) (cycle-nth (:grain %2) 3) true) "<time> last" [(dim :time) #"(?i)(ultim|scors|passat)[oaie]"] (pred-nth %1 -1) "last <time> " [#"(?i)(ultim|scors|passat)[oaie]" (dim :time)] (pred-nth %2 -1) "last <day-of-week> of <time>" [#"(?i)(l')ultim[oa]" {:form :day-of-week} #"(?i)di" (dim :time)] (pred-last-of %2 %4) "last <cycle> of <time>" [#"(?i)(l')ultim[oa]" (dim :cycle) #"(?i)di|del(l[oa'])" (dim :time)] (cycle-last-of %2 %4) ; Ordinals "nth <time> of <time>" [(dim :ordinal) (dim :time) #"(?i)di|del(l[oa'])|in" (dim :time)] (pred-nth (intersect %4 %2) (dec (:value %1))) "nth <time> of <time>" [#"(?i)il|l'" (dim :ordinal) (dim :time) #"(?i)di|del(l[oa'])|in" (dim :time)] (pred-nth (intersect %5 %3) (dec (:value %2))) "nth <time> after <time>" [(dim :ordinal) (dim :time) #"(?i)dopo" (dim :time)] (pred-nth-after %2 %4 (dec (:value %1))) "nth <time> after <time>" [#"(?i)il|l'" (dim :ordinal) (dim :time) #"(?i)dopo" (dim :time)] (pred-nth-after %3 %5 (dec (:value %2))) ; Years ; Between 1000 and 2100 we assume it's a year ; Outside of this, it's safer to consider it's latent "year (1000-2100 not latent)" (integer 1000 2100) (year (:value %1)) "year (latent)" (integer -10000 -1) (assoc (year (:value %1)) :latent true) "year (latent)" (integer 2101 10000) (assoc (year (:value %1)) :latent true) ; Day of month appears in the following context: ; - the nth ; - March nth ; - nth of March ; - mm/dd (and other numerical formats like yyyy-mm-dd etc.) ; In general we are flexible and accept both ordinals (3rd) and numbers (3) "day of month (1st)" [#"(?i)(primo|1o|1º|1°)( di)?"]; (day-of-month 1) "the <day-of-month>" ; this one is not latent [#"(?i)il" (integer 1 31)] (assoc (day-of-month (:value %2)) :latent true) "<day-of-month> <named-month>" ; dodici luglio 2010 (this rule removes latency) [(integer 1 31) {:form :month}] (intersect %2 (day-of-month (:value %1))) "<named-day> <day-of-month>" ; Friday 18 [{:form :day-of-week} (integer 1 31)] (intersect %1 (day-of-month (:value %2))) "il <day-of-month> de <named-month>" ; il dodici luglio 2010 [#"(?i)il" (integer 1 31) {:form :month}] (intersect %3 (day-of-month (:value %2))) ;; hours and minutes (absolute time) "<integer> (latent time-of-day)" (integer 0 24) (assoc (hour (:value %1) false) :latent true) "le idi di <named-month>" ; the ides of march 13th for most months, but on the 15th for March, May, July, and October [#"(?i)(le )?idi di" {:form :month}] (intersect %2 (day-of-month (if (#{3 5 7 10} (:month %2)) 15 13))) "noon" #"(?i)mezz?ogiorno" (hour 12 false) "midnight" #"(?i)mez?zanott?e" (hour 0 false) "<time-of-day> ora" [#"(?i)or[ea]" #(:full-hour %)] (dissoc %2 :latent) "at <time-of-day>" ; alle due [#"(?i)all[e']|le|a" {:form :time-of-day}] (dissoc %2 :latent) "hh(:|h)mm (time-of-day)" #"((?:[01]?\d)|(?:2[0-3]))[:h]([0-5]\d)" (hour-minute (Integer/parseInt (first (:groups %1))) (Integer/parseInt (second (:groups %1))) false) "hh(:|h)mm (time-of-day)" #"(?i)((?:0?\d)|(?:1[0-2]))[:h]([0-5]\d) d(i|el(la)?) (pomeriggio|(sta)?(sera|notte))" (hour-minute (+ 12 (Integer/parseInt (first (:groups %1)))) (Integer/parseInt (second (:groups %1))) false) ; specific rule to address "3 in the afternoon", "9 in the evening" "<integer 0 12> del <part of day>" [(integer 0 12) #"(?i)d(i|el(la)?) (pomeriggio|(sta)?(sera|notte))"] (hour (+ 12 (:value %1)) false) "hh <relative-minutes> del pomeriggio(time-of-day)" [(dim :time :full-hour) #(:relative-minutes %) #"(?i)d(i|el(la)?) (pomeriggio|(sta)?(sera|notte))"] (if (< 12 (:full-hour %1)) (dissoc %1 :latent) (hour-relativemin (+ 12 (:full-hour %1)) (:relative-minutes %2) false)) "hh <relative-minutes> del pomeriggio(time-of-day)" [(dim :time :full-hour) #"e" #(:relative-minutes %) #"(?i)d(i|el(la)?)" #"(pomeriggio|(sta)?(sera|notte))"] (if (< 12 (:full-hour %1)) (dissoc %1 :latent) (hour-relativemin (+ 12 (:full-hour %1)) (:relative-minutes %3) false)) "hhmm (military time-of-day)" #"(?i)((?:[01]?\d)|(?:2[0-3]))([0-5]\d)" (-> (hour-minute (Integer/parseInt (first (:groups %1))) (Integer/parseInt (second (:groups %1))) false) ; not a 12-hour clock (assoc :latent true)) "una" #"(?i)una" (hour 1 true) "quarter (relative minutes)" #"(?i)un quarto" {:relative-minutes 15} "trois quarts (relative minutes)" #"(?i)(3|tre) quarti?" {:relative-minutes 45} "half (relative minutes)" #"mezzo" {:relative-minutes 30} "number (as relative minutes)" (integer 1 59) {:relative-minutes (:value %1)} "<integer> minutes (as relative minutes)" [(integer 1 59) #"(?i)min\.?(ut[oi])?"] {:relative-minutes (:val %1)} "<hour-of-day> <integer> (as relative minutes)" [(dim :time :full-hour) #(:relative-minutes %)] ;before [{:for-relative-minutes true} #(:relative-minutes %)] (hour-relativemin (:full-hour %1) (:relative-minutes %2) (:twelve-hour-clock? %1)) "<hour-of-day> minus <integer> (as relative minutes)" [(dim :time :full-hour) #"meno" #(:relative-minutes %)] (hour-relativemin (:full-hour %1) (- (:relative-minutes %3)) (:twelve-hour-clock? %1)) "relative minutes to <integer> (as hour-of-day)" [#(:relative-minutes %) #"(?i)a" (dim :time :full-hour)] (hour-relativemin (:full-hour %3) (- (:relative-minutes %1)) true) "<hour-of-day> and <relative minutes>" [(dim :time :full-hour) #"e" #(:relative-minutes %)] (hour-relativemin (:full-hour %1) (:relative-minutes %3) (:twelve-hour-clock? %1)) ;; Formatted dates and times "dd[/-]mm[/-]yyyy" #"(3[01]|[12]\d|0?[1-9])[/-](0?[1-9]|1[0-2])[/-](\d{2,4})" (parse-dmy (first (:groups %1)) (second (:groups %1)) (nth (:groups %1) 2) true) "yyyy-mm-dd" #"(\d{2,4})-(0?[1-9]|1[0-2])-(3[01]|[12]\d|0?[1-9])" (parse-dmy (nth (:groups %1) 2) (second (:groups %1)) (first (:groups %1)) true) "dd[/-]mm" #"(3[01]|[12]\d|0?[1-9])[/-](0?[1-9]|1[0-2])" (parse-dmy (first (:groups %1)) (second (:groups %1)) nil true) ; Part of day (morning, evening...). They are intervals. "morning" #"(?i)mattin(ata|[aoe])" (assoc (interval (hour 4 false) (hour 12 false) false) :form :part-of-day :latent true) "lunch" #"(?i)(a )?pranzo" (assoc (interval (hour 12 false) (hour 14 false) false) :form :part-of-day :latent true) "afternoon" #"(?i)pomeriggio?" (assoc (interval (hour 12 false) (hour 19 false) false) :form :part-of-day :latent true) "evening" #"(?i)ser(ata|[ae])" (assoc (interval (hour 18 false) (hour 0 false) false) :form :part-of-day :latent true) "night" #"(?i)nott(e|ata)" (assoc (intersect (cycle-nth :day 1) (interval (hour 0 false) (hour 4 false) false)) :form :part-of-day :latent true) "this <part-of-day>" [#"(?i)quest[oa]|sta|in|nel(la)?" {:form :part-of-day}] (assoc (intersect (cycle-nth :day 0) %2) :form :part-of-day) ;; removes :latent "<time> notte" [(dim :time) #"(?i)((in|nella|alla) )?nott(e|ata)"] (intersect (cycle-nth-after :day 1 %1) (interval (hour 0 false) (hour 4 false) false)) "<time> notte" [#"(?i)((nella|alla) )?nott(e|ata)( d(i|el))" (dim :time)] (intersect (cycle-nth-after :day 1 %2) (interval (hour 0 false) (hour 4 false) false)) "stamattina" [#"(?i)stamattina"] (assoc (intersect (cycle-nth :day 0) (interval (hour 4 false) (hour 12 false) false)) :form :part-of-day) "stasera" [#"(?i)stasera"] (assoc (intersect (cycle-nth :day 0) (interval (hour 18 false) (hour 0 false) false)) :form :part-of-day) "stanotte" [#"(?i)stanotte"] (assoc (intersect (cycle-nth :day 1) (interval (hour 0 false) (hour 4 false) false)) :form :part-of-day) "<NAME>" [#"(?i)<NAME>"] (assoc (intersect (cycle-nth :day 1) (interval (hour 4 false) (hour 12 false) false)) :form :part-of-day) "<dim time> <part-of-day>" ; since "morning" "evening" etc. are latent, general time+time is blocked [(dim :time) {:form :part-of-day}] (intersect %1 %2) "<part-of-day> of <dim time>" ; since "morning" "evening" etc. are latent, general time+time is blocked [{:form :part-of-day} #"(?i)d(i|el)" (dim :time)] (intersect %1 %3) "in the <part-of-day> of <dim time>" ; since "morning" "evening" etc. are latent, general time+time is blocked [#"(?i)nel(la)?" {:form :part-of-day} #"(?i)d(i|el)" (dim :time)] (intersect %2 %4) "<dim time> al <part-of-day>" ; since "morning" "evening" etc. are latent, general time+time is blocked [(dim :time) #"(?i)al|nel(la)?|in|d(i|el(la)?)" {:form :part-of-day}] (intersect %1 %3) ;specific rule to address "3 in the morning","3h du matin" and extend morning span from 0 to 12 "<dim time> del mattino" [{:form :time-of-day} #"del mattino"] (intersect %1 (assoc (interval (hour 0 false) (hour 12 false) false) :form :part-of-day :latent true)) ; Other intervals: week-end, seasons "week-end" #"(?i)week[ -]?end|fine ?settimana|we" (interval (intersect (day-of-week 5) (hour 18 false)) (intersect (day-of-week 1) (hour 0 false)) false) "season" #"(?i)(in )?estate" ;could be smarter and take the exact hour into account... also some years the day can change (interval (month-day 6 21) (month-day 9 23) false) "season" #"(?i)(in )?autunno" (interval (month-day 9 23) (month-day 12 21) false) "season" #"(?i)(in )?inverno" (interval (month-day 12 21) (month-day 3 20) false) "season" #"(?i)(in )?primavera" (interval (month-day 3 20) (month-day 6 21) false) ; Absorptions ; a specific version of "il", above, removes :latent for integer as day of month ; this one is more general but does not remove latency "il <time>" [#"(?i)il" (dim :time #(not (:latent %)))] %2 ;; Time zones "timezone" #"(?i)(YEKT|YEKST|YAPT|YAKT|YAKST|WT|WST|WITA|WIT|WIB|WGT|WGST|WFT|WEZ|WET|WESZ|WEST|WAT|WAST|VUT|VLAT|VLAST|VET|UZT|UYT|UYST|UTC|ULAT|TVT|TMT|TLT|TKT|TJT|TFT|TAHT|SST|SRT|SGT|SCT|SBT|SAST|SAMT|RET|PYT|PYST|PWT|PT|PST|PONT|PMST|PMDT|PKT|PHT|PHOT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|NCT|MYT|MVT|MUT|MST|MSK|MSD|MMT|MHT|MEZ|MESZ|MDT|MAWT|MART|MAGT|MAGST|LINT|LHST|LHDT|KUYT|KST|KRAT|KRAST|KGT|JST|IST|IRST|IRKT|IRKST|IRDT|IOT|IDT|ICT|HOVT|HNY|HNT|HNR|HNP|HNE|HNC|HNA|HLV|HKT|HAY|HAT|HAST|HAR|HAP|HAE|HADT|HAC|HAA|GYT|GST|GMT|GILT|GFT|GET|GAMT|GALT|FNT|FKT|FKST|FJT|FJST|ET|EST|EGT|EGST|EET|EEST|EDT|ECT|EAT|EAST|EASST|DAVT|ChST|CXT|CVT|CST|COT|CLT|CLST|CKT|CHAST|CHADT|CET|CEST|CDT|CCT|CAT|CAST|BTT|BST|BRT|BRST|BOT|BNT|AZT|AZST|AZOT|AZOST|AWST|AWDT|AST|ART|AQTT|ANAT|ANAST|AMT|AMST|ALMT|AKST|AKDT|AFT|AEST|AEDT|ADT|ACST|ACDT)" {:dim :timezone :value (-> %1 :groups first clojure.string/upper-case)} "<time> timezone" [(dim :time) (dim :timezone)] (assoc %1 :timezone (:value %2)) ; Precision ; FIXME ; - should be applied to all dims not just time-of-day ;- shouldn't remove latency, except maybe -ish "<time-of-day> circa" ; 7ish [{:form :time-of-day} #"(?i)circa"] (-> %1 (dissoc :latent) (merge {:precision "approximate"})) "<time-of-day> precise" ; sharp [{:form :time-of-day} #"(?i)precise"] (-> %1 (dissoc :latent) (merge {:precision "exact"})) "circa per le <time-of-day>" ; about [#"(?i)(circa )?per( le)?|circa( alle)?|verso( le)?" {:form :time-of-day}] (-> %2 (dissoc :latent) (merge {:precision "approximate"})) "verso <part-of-day>" ; about [#"(?i)verso( la| il)?" {:form :part-of-day}] (merge %2 {:precision "approximate"}) ; Intervals "dd-dd <month> (interval)" [#"(?i)(?:dal(?: |l'))?(3[01]|[12]\d|0?[1-9])" #"(?i)\-|([fs]ino )?al(l')?" #"(3[01]|[12]\d|0?[1-9])" {:form :month}] (interval (intersect %4 (day-of-month (Integer/parseInt (-> %1 :groups first)))) (intersect %4 (day-of-month (Integer/parseInt (-> %3 :groups first)))) true) "dd-dd <month> (interval)" [#"(?i)tra( il|l')?" #"(3[01]|[12]\d|0?[1-9])" #"(?i)e( il|l')?" #"(3[01]|[12]\d|0?[1-9])" {:form :month}] (interval (intersect %5 (day-of-month (Integer/parseInt (-> %2 :groups first)))) (intersect %5 (day-of-month (Integer/parseInt (-> %4 :groups first)))) true) ; Blocked for :latent time. May need to accept certain latents only, like hours "<datetime> - <datetime> (interval)" [(dim :time #(not (:latent %))) #"\-|[fs]ino a(l(l[e'])?)?" (dim :time #(not (:latent %)))] (interval %1 %3 true) "fino al <datetime> (interval)" [#"\-|[fs]ino a(l(l[ae'])?)?" (dim :time #(not (:latent %)))] (interval (cycle-nth :second 0) %2 false) "dal <datetime> al <datetime> (interval)" [#"(?i)da(l(l')?)?" (dim :time) #"\-|([fs]ino )?al(l')?" (dim :time)] (interval %2 %4 true) "tra il <datetime> e il <datetime> (interval)" [#"(?i)tra( il| l')?" (dim :time) #"e( il| l')?" (dim :time)] (interval %2 %4 true) "<time-of-day> - <time-of-day> <day-of-month> (interval)" [{:form :time-of-day} #"\-" {:form :time-of-day} (dim :time #(not (:latent %)))] (interval (intersect %1 %4) (intersect %3 %4) true) ; Specific for time-of-day, to help resolve ambiguities "dalle <time-of-day> alle <time-of-day> (interval)" [#"(?i)da(l(le|l')?)?" {:form :time-of-day} #"\-|([fs]ino )?a(l(l[e'])?)?" {:form :time-of-day}] (interval %2 %4 true) ; Specific for within duration... Would need to be reworked "in <duration>" [#"(?i)in|per|entro" (dim :duration)] (interval (cycle-nth :second 0) (in-duration (:value %2)) false) "entro il <duration>" [#"(?i)entro (il|l')|per (il|l[a'])|in|nel(l[a'])?" (dim :unit-of-duration)] (interval (cycle-nth :second 0) (cycle-nth (:grain %2) 1) false) ; One-sided Intervals "entro le <time-of-day>" [#"(?i)entro( l[ea'])?|prima d(i|ell['e])" (dim :time)] (merge %2 {:direction :before}) "dopo le <time-of-day>" [#"(?i)dopo l[e']|da(l(l['e])?)?" (dim :time)] (merge %2 {:direction :after}) "<time> dopo le <time-of-day>" [(dim :time) #"(?i)dopo l[e']|dall['e]" {:form :time-of-day}] (merge (intersect %1 %3) {:direction :after}) "<time> dopo le <time-of-day>" [(dim :time) #"(?i)dopo l[e']|dall['e]" {:form :time-of-day}] (merge (intersect %1 %3) {:direction :after}) "<time> entro le <time-of-day>" [(dim :time) #"(?i)entro( l[e'])?|prima d(i|ell['e])" (dim :time)] (merge (intersect %1 %3) {:direction :before}) )
true
( ;; generic "two time tokens in a row" [(dim :time #(not (:latent %))) (dim :time #(not (:latent %)))] ; sequence of two tokens with a time dimension (intersect %1 %2) ; same thing, with "de" in between like "domingo de la semana pasada" "two time tokens separated by `di`" [(dim :time #(not (:latent %))) #"(?i)de" (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn (intersect %1 %3) "in <named-month>" ; in September [#"(?i)in|del mese( di)?" {:form :month}] %2 ; does NOT dissoc latent ;; "named-day" #"(?i)luned[ìi]|lun?\.?" (day-of-week 1) "named-day" #"(?i)marted[iì]|mar?\.?" (day-of-week 2) "named-day" #"(?i)mercoled[iì]|mer?\.?" (day-of-week 3) "named-day" #"(?i)gioved[iì]|gio?\.?" (day-of-week 4) "named-day" #"(?i)venerd[iì]|ven?\.?" (day-of-week 5) "named-day" #"(?i)sabato|sab?\.?" (day-of-week 6) "named-day" #"(?i)domenica|dom?\.?" (day-of-week 7) "named-month" #"(?i)gennaio|genn?\.?" (month 1) "named-month" #"(?i)febbraio|febb?\.?" (month 2) "named-month" #"(?i)marzo|mar\.?" (month 3) "named-month" #"(?i)aprile|apr\.?" (month 4) "named-month" #"(?i)maggio|magg?\.?" (month 5) "named-month" #"(?i)giugno|giu\.?" (month 6) "named-month" #"(?i)luglio|lug\.?" (month 7) "named-month" #"(?i)agosto|ago\.?" (month 8) "named-month" #"(?i)settembre|sett?\.?" (month 9) "named-month" #"(?i)ottobre|ott\.?" (month 10) "named-month" #"(?i)novembre|nov\.?" (month 11) "named-month" #"(?i)dicembre|dic\.?" (month 12) ; Holiday TODO: check online holidays ; or define dynamyc rule (last thursday of october..) "christmas" #"(?i)((il )?giorno di )?natale" (month-day 12 25) "christmas eve" #"(?i)((al)?la )?vigig?lia( di natale)?" (month-day 12 24) "new year's eve" #"(?i)((la )?vigig?lia di capodanno|san silvestro)" (month-day 12 31) "new year's day" #"(?i)(capodanno|primo dell' ?anno)" (month-day 1 1) "epifania" #"(?i)(epifania|befana)" (month-day 1 6) "valentine's day" #"(?i)s(an|\.) valentino|festa degli innamorati" (month-day 2 14) "festa del papà" #"(?i)festa del pap[aà]|(festa di )?s(an|\.) giuseppe" (month-day 3 19) "festa della liberazione" #"(?i)((festa|anniversario) della|(al)?la) liberazione" (month-day 4 25) "festa del lavoro" #"(?i)festa del lavoro|(festa|giorno) dei lavoratori" (month-day 5 1) "festa della repubblica" #"(?i)((festa del)?la )?repubblica" (month-day 6 2) "ferragosto" #"(?i)ferragosto|assunzione" (month-day 8 15) "halloween day" #"(?i)hall?owe?en" (month-day 10 31) "ognissanti" #"(?i)(tutti i |ognis|festa dei |([ia]l )?giorno dei )santi" (month-day 11 1) "commemorazione dei defunti" #"(?i)((giorno dei|commemorazione dei|ai) )?(morti|defunti)" (month-day 11 2) "immacolata concezione" #"(?i)(all')?immacolata( concezione)?" (month-day 12 8) "santo stefano" #"(?i)s(anto|\.) stefano" (month-day 12 26) "Mother's Day";second Sunday in May. #"(?i)festa della mamma" (intersect (day-of-week 7) (month 5) (cycle-nth-after :week 1 (month-day 5 1))) "right now" #"(subito|immediatamente|proprio adesso|in questo momento)" (cycle-nth :second 0) "now" #"(?i)(ora|al momento|attualmente|adesso|(di )?oggi|in giornata)" (cycle-nth :day 0) "tomorrow" #"(?i)domani" (cycle-nth :day 1) "yesterday" #"(?i)ieri" (cycle-nth :day -1) "EOM|End of month" #"(?i)fine del mese" (cycle-nth :month 1) "EOY|End of year" #"(?i)fine dell' ?anno" (cycle-nth :year 1) "the day after tomorrow" #"(?i)(il giorno )?dopo\s?domani" (cycle-nth :day 2) "the day before yesterday" #"(?i)(l')?altro\s?ieri" (cycle-nth :day -2) ;; ;; This, Next, Last ;; assumed to be strictly in the future: ;; "this Monday" => next week if today in Monday "this <day-of-week>" ; assumed to be in the future [#"(?i)quest[oaie]" {:form :day-of-week}] (pred-nth-not-immediate %2 0) ;; for other preds, it can be immediate: ;; "this month" => now is part of it ; See also: cycles in en.cycles.clj "this <time>" [#"(?i)quest[oaie']" (dim :time)] (pred-nth %2 0) "next <time>" [#"(?i)prossim[ao]" (dim :time)] (pred-nth %2 1) "next <time>" [(dim :time) #"(?i)dopo|prossim[ao]"] (pred-nth %1 1) "prossimi <unit-of-duration>" [#"(?i)((ne)?i|(nel)?le) prossim[ie]" (dim :unit-of-duration)] (interval (cycle-nth (:grain %2) 1) (cycle-nth (:grain %2) 3) true) "<time> last" [(dim :time) #"(?i)(ultim|scors|passat)[oaie]"] (pred-nth %1 -1) "last <time> " [#"(?i)(ultim|scors|passat)[oaie]" (dim :time)] (pred-nth %2 -1) "last <day-of-week> of <time>" [#"(?i)(l')ultim[oa]" {:form :day-of-week} #"(?i)di" (dim :time)] (pred-last-of %2 %4) "last <cycle> of <time>" [#"(?i)(l')ultim[oa]" (dim :cycle) #"(?i)di|del(l[oa'])" (dim :time)] (cycle-last-of %2 %4) ; Ordinals "nth <time> of <time>" [(dim :ordinal) (dim :time) #"(?i)di|del(l[oa'])|in" (dim :time)] (pred-nth (intersect %4 %2) (dec (:value %1))) "nth <time> of <time>" [#"(?i)il|l'" (dim :ordinal) (dim :time) #"(?i)di|del(l[oa'])|in" (dim :time)] (pred-nth (intersect %5 %3) (dec (:value %2))) "nth <time> after <time>" [(dim :ordinal) (dim :time) #"(?i)dopo" (dim :time)] (pred-nth-after %2 %4 (dec (:value %1))) "nth <time> after <time>" [#"(?i)il|l'" (dim :ordinal) (dim :time) #"(?i)dopo" (dim :time)] (pred-nth-after %3 %5 (dec (:value %2))) ; Years ; Between 1000 and 2100 we assume it's a year ; Outside of this, it's safer to consider it's latent "year (1000-2100 not latent)" (integer 1000 2100) (year (:value %1)) "year (latent)" (integer -10000 -1) (assoc (year (:value %1)) :latent true) "year (latent)" (integer 2101 10000) (assoc (year (:value %1)) :latent true) ; Day of month appears in the following context: ; - the nth ; - March nth ; - nth of March ; - mm/dd (and other numerical formats like yyyy-mm-dd etc.) ; In general we are flexible and accept both ordinals (3rd) and numbers (3) "day of month (1st)" [#"(?i)(primo|1o|1º|1°)( di)?"]; (day-of-month 1) "the <day-of-month>" ; this one is not latent [#"(?i)il" (integer 1 31)] (assoc (day-of-month (:value %2)) :latent true) "<day-of-month> <named-month>" ; dodici luglio 2010 (this rule removes latency) [(integer 1 31) {:form :month}] (intersect %2 (day-of-month (:value %1))) "<named-day> <day-of-month>" ; Friday 18 [{:form :day-of-week} (integer 1 31)] (intersect %1 (day-of-month (:value %2))) "il <day-of-month> de <named-month>" ; il dodici luglio 2010 [#"(?i)il" (integer 1 31) {:form :month}] (intersect %3 (day-of-month (:value %2))) ;; hours and minutes (absolute time) "<integer> (latent time-of-day)" (integer 0 24) (assoc (hour (:value %1) false) :latent true) "le idi di <named-month>" ; the ides of march 13th for most months, but on the 15th for March, May, July, and October [#"(?i)(le )?idi di" {:form :month}] (intersect %2 (day-of-month (if (#{3 5 7 10} (:month %2)) 15 13))) "noon" #"(?i)mezz?ogiorno" (hour 12 false) "midnight" #"(?i)mez?zanott?e" (hour 0 false) "<time-of-day> ora" [#"(?i)or[ea]" #(:full-hour %)] (dissoc %2 :latent) "at <time-of-day>" ; alle due [#"(?i)all[e']|le|a" {:form :time-of-day}] (dissoc %2 :latent) "hh(:|h)mm (time-of-day)" #"((?:[01]?\d)|(?:2[0-3]))[:h]([0-5]\d)" (hour-minute (Integer/parseInt (first (:groups %1))) (Integer/parseInt (second (:groups %1))) false) "hh(:|h)mm (time-of-day)" #"(?i)((?:0?\d)|(?:1[0-2]))[:h]([0-5]\d) d(i|el(la)?) (pomeriggio|(sta)?(sera|notte))" (hour-minute (+ 12 (Integer/parseInt (first (:groups %1)))) (Integer/parseInt (second (:groups %1))) false) ; specific rule to address "3 in the afternoon", "9 in the evening" "<integer 0 12> del <part of day>" [(integer 0 12) #"(?i)d(i|el(la)?) (pomeriggio|(sta)?(sera|notte))"] (hour (+ 12 (:value %1)) false) "hh <relative-minutes> del pomeriggio(time-of-day)" [(dim :time :full-hour) #(:relative-minutes %) #"(?i)d(i|el(la)?) (pomeriggio|(sta)?(sera|notte))"] (if (< 12 (:full-hour %1)) (dissoc %1 :latent) (hour-relativemin (+ 12 (:full-hour %1)) (:relative-minutes %2) false)) "hh <relative-minutes> del pomeriggio(time-of-day)" [(dim :time :full-hour) #"e" #(:relative-minutes %) #"(?i)d(i|el(la)?)" #"(pomeriggio|(sta)?(sera|notte))"] (if (< 12 (:full-hour %1)) (dissoc %1 :latent) (hour-relativemin (+ 12 (:full-hour %1)) (:relative-minutes %3) false)) "hhmm (military time-of-day)" #"(?i)((?:[01]?\d)|(?:2[0-3]))([0-5]\d)" (-> (hour-minute (Integer/parseInt (first (:groups %1))) (Integer/parseInt (second (:groups %1))) false) ; not a 12-hour clock (assoc :latent true)) "una" #"(?i)una" (hour 1 true) "quarter (relative minutes)" #"(?i)un quarto" {:relative-minutes 15} "trois quarts (relative minutes)" #"(?i)(3|tre) quarti?" {:relative-minutes 45} "half (relative minutes)" #"mezzo" {:relative-minutes 30} "number (as relative minutes)" (integer 1 59) {:relative-minutes (:value %1)} "<integer> minutes (as relative minutes)" [(integer 1 59) #"(?i)min\.?(ut[oi])?"] {:relative-minutes (:val %1)} "<hour-of-day> <integer> (as relative minutes)" [(dim :time :full-hour) #(:relative-minutes %)] ;before [{:for-relative-minutes true} #(:relative-minutes %)] (hour-relativemin (:full-hour %1) (:relative-minutes %2) (:twelve-hour-clock? %1)) "<hour-of-day> minus <integer> (as relative minutes)" [(dim :time :full-hour) #"meno" #(:relative-minutes %)] (hour-relativemin (:full-hour %1) (- (:relative-minutes %3)) (:twelve-hour-clock? %1)) "relative minutes to <integer> (as hour-of-day)" [#(:relative-minutes %) #"(?i)a" (dim :time :full-hour)] (hour-relativemin (:full-hour %3) (- (:relative-minutes %1)) true) "<hour-of-day> and <relative minutes>" [(dim :time :full-hour) #"e" #(:relative-minutes %)] (hour-relativemin (:full-hour %1) (:relative-minutes %3) (:twelve-hour-clock? %1)) ;; Formatted dates and times "dd[/-]mm[/-]yyyy" #"(3[01]|[12]\d|0?[1-9])[/-](0?[1-9]|1[0-2])[/-](\d{2,4})" (parse-dmy (first (:groups %1)) (second (:groups %1)) (nth (:groups %1) 2) true) "yyyy-mm-dd" #"(\d{2,4})-(0?[1-9]|1[0-2])-(3[01]|[12]\d|0?[1-9])" (parse-dmy (nth (:groups %1) 2) (second (:groups %1)) (first (:groups %1)) true) "dd[/-]mm" #"(3[01]|[12]\d|0?[1-9])[/-](0?[1-9]|1[0-2])" (parse-dmy (first (:groups %1)) (second (:groups %1)) nil true) ; Part of day (morning, evening...). They are intervals. "morning" #"(?i)mattin(ata|[aoe])" (assoc (interval (hour 4 false) (hour 12 false) false) :form :part-of-day :latent true) "lunch" #"(?i)(a )?pranzo" (assoc (interval (hour 12 false) (hour 14 false) false) :form :part-of-day :latent true) "afternoon" #"(?i)pomeriggio?" (assoc (interval (hour 12 false) (hour 19 false) false) :form :part-of-day :latent true) "evening" #"(?i)ser(ata|[ae])" (assoc (interval (hour 18 false) (hour 0 false) false) :form :part-of-day :latent true) "night" #"(?i)nott(e|ata)" (assoc (intersect (cycle-nth :day 1) (interval (hour 0 false) (hour 4 false) false)) :form :part-of-day :latent true) "this <part-of-day>" [#"(?i)quest[oa]|sta|in|nel(la)?" {:form :part-of-day}] (assoc (intersect (cycle-nth :day 0) %2) :form :part-of-day) ;; removes :latent "<time> notte" [(dim :time) #"(?i)((in|nella|alla) )?nott(e|ata)"] (intersect (cycle-nth-after :day 1 %1) (interval (hour 0 false) (hour 4 false) false)) "<time> notte" [#"(?i)((nella|alla) )?nott(e|ata)( d(i|el))" (dim :time)] (intersect (cycle-nth-after :day 1 %2) (interval (hour 0 false) (hour 4 false) false)) "stamattina" [#"(?i)stamattina"] (assoc (intersect (cycle-nth :day 0) (interval (hour 4 false) (hour 12 false) false)) :form :part-of-day) "stasera" [#"(?i)stasera"] (assoc (intersect (cycle-nth :day 0) (interval (hour 18 false) (hour 0 false) false)) :form :part-of-day) "stanotte" [#"(?i)stanotte"] (assoc (intersect (cycle-nth :day 1) (interval (hour 0 false) (hour 4 false) false)) :form :part-of-day) "PI:NAME:<NAME>END_PI" [#"(?i)PI:NAME:<NAME>END_PI"] (assoc (intersect (cycle-nth :day 1) (interval (hour 4 false) (hour 12 false) false)) :form :part-of-day) "<dim time> <part-of-day>" ; since "morning" "evening" etc. are latent, general time+time is blocked [(dim :time) {:form :part-of-day}] (intersect %1 %2) "<part-of-day> of <dim time>" ; since "morning" "evening" etc. are latent, general time+time is blocked [{:form :part-of-day} #"(?i)d(i|el)" (dim :time)] (intersect %1 %3) "in the <part-of-day> of <dim time>" ; since "morning" "evening" etc. are latent, general time+time is blocked [#"(?i)nel(la)?" {:form :part-of-day} #"(?i)d(i|el)" (dim :time)] (intersect %2 %4) "<dim time> al <part-of-day>" ; since "morning" "evening" etc. are latent, general time+time is blocked [(dim :time) #"(?i)al|nel(la)?|in|d(i|el(la)?)" {:form :part-of-day}] (intersect %1 %3) ;specific rule to address "3 in the morning","3h du matin" and extend morning span from 0 to 12 "<dim time> del mattino" [{:form :time-of-day} #"del mattino"] (intersect %1 (assoc (interval (hour 0 false) (hour 12 false) false) :form :part-of-day :latent true)) ; Other intervals: week-end, seasons "week-end" #"(?i)week[ -]?end|fine ?settimana|we" (interval (intersect (day-of-week 5) (hour 18 false)) (intersect (day-of-week 1) (hour 0 false)) false) "season" #"(?i)(in )?estate" ;could be smarter and take the exact hour into account... also some years the day can change (interval (month-day 6 21) (month-day 9 23) false) "season" #"(?i)(in )?autunno" (interval (month-day 9 23) (month-day 12 21) false) "season" #"(?i)(in )?inverno" (interval (month-day 12 21) (month-day 3 20) false) "season" #"(?i)(in )?primavera" (interval (month-day 3 20) (month-day 6 21) false) ; Absorptions ; a specific version of "il", above, removes :latent for integer as day of month ; this one is more general but does not remove latency "il <time>" [#"(?i)il" (dim :time #(not (:latent %)))] %2 ;; Time zones "timezone" #"(?i)(YEKT|YEKST|YAPT|YAKT|YAKST|WT|WST|WITA|WIT|WIB|WGT|WGST|WFT|WEZ|WET|WESZ|WEST|WAT|WAST|VUT|VLAT|VLAST|VET|UZT|UYT|UYST|UTC|ULAT|TVT|TMT|TLT|TKT|TJT|TFT|TAHT|SST|SRT|SGT|SCT|SBT|SAST|SAMT|RET|PYT|PYST|PWT|PT|PST|PONT|PMST|PMDT|PKT|PHT|PHOT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|NCT|MYT|MVT|MUT|MST|MSK|MSD|MMT|MHT|MEZ|MESZ|MDT|MAWT|MART|MAGT|MAGST|LINT|LHST|LHDT|KUYT|KST|KRAT|KRAST|KGT|JST|IST|IRST|IRKT|IRKST|IRDT|IOT|IDT|ICT|HOVT|HNY|HNT|HNR|HNP|HNE|HNC|HNA|HLV|HKT|HAY|HAT|HAST|HAR|HAP|HAE|HADT|HAC|HAA|GYT|GST|GMT|GILT|GFT|GET|GAMT|GALT|FNT|FKT|FKST|FJT|FJST|ET|EST|EGT|EGST|EET|EEST|EDT|ECT|EAT|EAST|EASST|DAVT|ChST|CXT|CVT|CST|COT|CLT|CLST|CKT|CHAST|CHADT|CET|CEST|CDT|CCT|CAT|CAST|BTT|BST|BRT|BRST|BOT|BNT|AZT|AZST|AZOT|AZOST|AWST|AWDT|AST|ART|AQTT|ANAT|ANAST|AMT|AMST|ALMT|AKST|AKDT|AFT|AEST|AEDT|ADT|ACST|ACDT)" {:dim :timezone :value (-> %1 :groups first clojure.string/upper-case)} "<time> timezone" [(dim :time) (dim :timezone)] (assoc %1 :timezone (:value %2)) ; Precision ; FIXME ; - should be applied to all dims not just time-of-day ;- shouldn't remove latency, except maybe -ish "<time-of-day> circa" ; 7ish [{:form :time-of-day} #"(?i)circa"] (-> %1 (dissoc :latent) (merge {:precision "approximate"})) "<time-of-day> precise" ; sharp [{:form :time-of-day} #"(?i)precise"] (-> %1 (dissoc :latent) (merge {:precision "exact"})) "circa per le <time-of-day>" ; about [#"(?i)(circa )?per( le)?|circa( alle)?|verso( le)?" {:form :time-of-day}] (-> %2 (dissoc :latent) (merge {:precision "approximate"})) "verso <part-of-day>" ; about [#"(?i)verso( la| il)?" {:form :part-of-day}] (merge %2 {:precision "approximate"}) ; Intervals "dd-dd <month> (interval)" [#"(?i)(?:dal(?: |l'))?(3[01]|[12]\d|0?[1-9])" #"(?i)\-|([fs]ino )?al(l')?" #"(3[01]|[12]\d|0?[1-9])" {:form :month}] (interval (intersect %4 (day-of-month (Integer/parseInt (-> %1 :groups first)))) (intersect %4 (day-of-month (Integer/parseInt (-> %3 :groups first)))) true) "dd-dd <month> (interval)" [#"(?i)tra( il|l')?" #"(3[01]|[12]\d|0?[1-9])" #"(?i)e( il|l')?" #"(3[01]|[12]\d|0?[1-9])" {:form :month}] (interval (intersect %5 (day-of-month (Integer/parseInt (-> %2 :groups first)))) (intersect %5 (day-of-month (Integer/parseInt (-> %4 :groups first)))) true) ; Blocked for :latent time. May need to accept certain latents only, like hours "<datetime> - <datetime> (interval)" [(dim :time #(not (:latent %))) #"\-|[fs]ino a(l(l[e'])?)?" (dim :time #(not (:latent %)))] (interval %1 %3 true) "fino al <datetime> (interval)" [#"\-|[fs]ino a(l(l[ae'])?)?" (dim :time #(not (:latent %)))] (interval (cycle-nth :second 0) %2 false) "dal <datetime> al <datetime> (interval)" [#"(?i)da(l(l')?)?" (dim :time) #"\-|([fs]ino )?al(l')?" (dim :time)] (interval %2 %4 true) "tra il <datetime> e il <datetime> (interval)" [#"(?i)tra( il| l')?" (dim :time) #"e( il| l')?" (dim :time)] (interval %2 %4 true) "<time-of-day> - <time-of-day> <day-of-month> (interval)" [{:form :time-of-day} #"\-" {:form :time-of-day} (dim :time #(not (:latent %)))] (interval (intersect %1 %4) (intersect %3 %4) true) ; Specific for time-of-day, to help resolve ambiguities "dalle <time-of-day> alle <time-of-day> (interval)" [#"(?i)da(l(le|l')?)?" {:form :time-of-day} #"\-|([fs]ino )?a(l(l[e'])?)?" {:form :time-of-day}] (interval %2 %4 true) ; Specific for within duration... Would need to be reworked "in <duration>" [#"(?i)in|per|entro" (dim :duration)] (interval (cycle-nth :second 0) (in-duration (:value %2)) false) "entro il <duration>" [#"(?i)entro (il|l')|per (il|l[a'])|in|nel(l[a'])?" (dim :unit-of-duration)] (interval (cycle-nth :second 0) (cycle-nth (:grain %2) 1) false) ; One-sided Intervals "entro le <time-of-day>" [#"(?i)entro( l[ea'])?|prima d(i|ell['e])" (dim :time)] (merge %2 {:direction :before}) "dopo le <time-of-day>" [#"(?i)dopo l[e']|da(l(l['e])?)?" (dim :time)] (merge %2 {:direction :after}) "<time> dopo le <time-of-day>" [(dim :time) #"(?i)dopo l[e']|dall['e]" {:form :time-of-day}] (merge (intersect %1 %3) {:direction :after}) "<time> dopo le <time-of-day>" [(dim :time) #"(?i)dopo l[e']|dall['e]" {:form :time-of-day}] (merge (intersect %1 %3) {:direction :after}) "<time> entro le <time-of-day>" [(dim :time) #"(?i)entro( l[e'])?|prima d(i|ell['e])" (dim :time)] (merge (intersect %1 %3) {:direction :before}) )
[ { "context": "tString config \"user\" nil \"email\") \"\")]\n {:name name\n :email email}))\n\n(defn set-user-info! [git-o", "end": 4369, "score": 0.9359599351882935, "start": 4365, "tag": "NAME", "value": "name" } ]
editor/src/clj/editor/git.clj
Krzlfx/defold
2
;; 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.git (:require [camel-snake-kebab :as camel] [clojure.java.io :as io] [clojure.set :as set] [clojure.string :as str] [editor.git-credentials :as git-credentials] [editor.fs :as fs] [editor.ui :as ui] [util.text-util :as text-util] [service.log :as log]) (:import [java.io File IOException] [java.net URI] [java.nio.file Files FileVisitResult Path SimpleFileVisitor] [java.util Collection] [javafx.scene.control ProgressBar] [org.eclipse.jgit.api Git PushCommand ResetCommand$ResetType TransportCommand TransportConfigCallback] [org.eclipse.jgit.api.errors StashApplyFailureException] [org.eclipse.jgit.diff DiffEntry RenameDetector] [org.eclipse.jgit.errors MissingObjectException] [org.eclipse.jgit.lib BatchingProgressMonitor BranchConfig ObjectId ProgressMonitor Repository] [org.eclipse.jgit.revwalk RevCommit RevWalk] [org.eclipse.jgit.transport CredentialsProvider JschConfigSessionFactory RemoteConfig SshTransport URIish UsernamePasswordCredentialsProvider] [org.eclipse.jgit.treewalk FileTreeIterator TreeWalk] [org.eclipse.jgit.treewalk.filter PathFilter PathFilterGroup] [com.jcraft.jsch Session])) (set! *warn-on-reflection* true) ;; When opening a project, we ensure the .gitignore file contains every entry on this list. (defonce required-gitignore-entries ["/.internal" "/build"]) ;; Based on the contents of the .gitignore file we include in template projects. (defonce default-gitignore-entries (vec (concat required-gitignore-entries [".externalToolBuilders" ".DS_Store" "Thumbs.db" ".lock-wscript" "*.pyc" ".project" ".cproject" "builtins"]))) (defn try-open ^Git [^File repo-path] (try (Git/open repo-path) (catch Exception _ nil))) (defn get-commit ^RevCommit [^Repository repository revision] (when-some [object-id (.resolve repository revision)] (let [walk (RevWalk. repository)] (.setRetainBody walk true) (.parseCommit walk object-id)))) (defn- diff-entry->map [^DiffEntry de] ; NOTE: We convert /dev/null paths to nil, and convert copies into adds. (let [f (fn [p] (when-not (= p "/dev/null") p)) change-type (-> (.getChangeType de) str .toLowerCase keyword)] (if (= :copy change-type) {:score 0 :change-type :add :old-path nil :new-path (f (.getNewPath de))} {:score (.getScore de) :change-type change-type :old-path (f (.getOldPath de)) :new-path (f (.getNewPath de))}))) (defn- find-original-for-renamed [ustatus file] (->> ustatus (filter (fn [e] (= file (:new-path e)))) (map :old-path) (first))) ;; ================================================================================= (defn- as-repository ^Repository [git-or-repository] (if (instance? Repository git-or-repository) git-or-repository (.getRepository ^Git git-or-repository))) (defn user-info [git-or-repository] (let [repository (as-repository git-or-repository) config (.getConfig repository) name (or (.getString config "user" nil "name") "") email (or (.getString config "user" nil "email") "")] {:name name :email email})) (defn set-user-info! [git-or-repository {new-name :name new-email :email :as user-info}] (assert (string? new-name)) (assert (string? new-email)) (when (not= user-info (user-info git-or-repository)) ;; The new user info differs from the stored info. ;; Update user info in the repository config. (let [repository (as-repository git-or-repository) config (.getConfig repository)] (.setString config "user" nil "name" new-name) (.setString config "user" nil "email" new-email) ;; Attempt to save the updated repository config. ;; The in-memory config retains the modifications even if this fails. (try (.save config) (catch IOException error (log/warn :msg "Failed to save updated user info to Git repository config." :exception error)))))) (defn- remote-name ^String [^Repository repository] (let [config (.getConfig repository) branch (.getBranch repository) branch-config (BranchConfig. config branch) remote-names (map #(.getName ^RemoteConfig %) (RemoteConfig/getAllRemoteConfigs config))] (or (.getRemote branch-config) (some (fn [remote-name] (when (.equalsIgnoreCase "origin" remote-name) remote-name)) remote-names) (first remote-names)))) (defn remote-info ([git-or-repository purpose] (let [repository (as-repository git-or-repository) remote-name (or (remote-name repository) "origin")] (remote-info repository purpose remote-name))) ([git-or-repository purpose ^String remote-name] (let [repository (as-repository git-or-repository) config (.getConfig repository) remote (RemoteConfig. config remote-name)] (when-some [^URIish uri-ish (first (case purpose :fetch (.getURIs remote) :push (concat (.getPushURIs remote) (.getURIs remote))))] {:name remote-name :scheme (if-some [scheme (.getScheme uri-ish)] (keyword scheme) :ssh) :host (.getHost uri-ish) :port (.getPort uri-ish) :path (.getPath uri-ish) :user (.getUser uri-ish) :pass (.getPass uri-ish)})))) (defn remote-uri ^URI [{:keys [scheme ^String host ^int port ^String path] :or {port -1} :as remote-info}] (let [^String user-info (if-some [user (not-empty (:user remote-info))] (if-some [pass (not-empty (:pass remote-info))] (str user ":" pass) user))] (URI. (name scheme) user-info host port path nil nil))) ;; Does the equivalent *config-wise* of: ;; > git config remote.origin.url url ;; > git push -u origin ;; Which is: ;; > git config remote.origin.url url ;; > git config remote.origin.fetch +refs/heads/*:refs/remotes/origin/* ;; > git config branch.master.remote origin ;; > git config branch.master.merge refs/heads/master ;; according to https://stackoverflow.com/questions/27823940/jgit-pushing-a-branch-and-add-upstream-u-option (defn config-remote! [^Git git url] (let [config (.. git getRepository getConfig)] (doto config (.setString "remote" "origin" "url" url) (.setString "remote" "origin" "fetch" "+refs/heads/*:refs/remotes/origin/*") (.setString "branch" "master" "remote" "origin") (.setString "branch" "master" "merge" "refs/heads/master") (.save)))) (defn worktree [^Git git] (.getWorkTree (.getRepository git))) (defn get-current-commit-ref [^Git git] (get-commit (.getRepository git) "HEAD")) (defn status [^Git git] (let [s (-> git (.status) (.call))] {:added (set (.getAdded s)) :changed (set (.getChanged s)) :conflicting (set (.getConflicting s)) :ignored-not-in-index (set (.getIgnoredNotInIndex s)) :missing (set (.getMissing s)) :modified (set (.getModified s)) :removed (set (.getRemoved s)) :uncommitted-changes (set (.getUncommittedChanges s)) :untracked (set (.getUntracked s)) :untracked-folders (set (.getUntrackedFolders s)) :conflicting-stage-state (apply hash-map (mapcat (fn [[k v]] [k (-> v str camel/->kebab-case keyword)]) (.getConflictingStageState s)))})) (defn- make-add-diff-entry [file-path] {:score 0 :change-type :add :old-path nil :new-path file-path}) (defn- make-delete-diff-entry [file-path] {:score 0 :change-type :delete :old-path file-path :new-path nil}) (defn- make-modify-diff-entry [file-path] {:score 0 :change-type :modify :old-path file-path :new-path file-path}) (defn- diff-entry-path ^String [{:keys [old-path new-path]}] (or new-path old-path)) (defn unified-status "Get the actual status by comparing contents on disk and HEAD. The state of the index (i.e. whether or not a file is staged) does not matter." ([^Git git] (unified-status git (status git))) ([^Git git git-status] (let [changed-paths (into #{} (mapcat git-status) [:added :changed :missing :modified :removed :untracked])] (if (empty? changed-paths) [] (let [repository (.getRepository git) rename-detector (doto (RenameDetector. repository) (.addAll (with-open [tree-walk (doto (TreeWalk. repository) (.addTree (.getTree ^RevCommit (get-commit repository "HEAD"))) (.addTree (FileTreeIterator. repository)) (.setFilter (PathFilterGroup/createFromStrings ^Collection changed-paths)) (.setRecursive true))] (DiffEntry/scan tree-walk))))] (try (let [diff-entries (.compute rename-detector nil)] (mapv diff-entry->map diff-entries)) (catch MissingObjectException _ ;; TODO: Workaround for what appears to be a bug inside JGit. ;; The rename detector failed for some reason. Report the status ;; without considering renames. This results in separate :added and ;; :deleted entries for unstaged renames, but will resolve into a ;; single :renamed entry once staged. (sort-by diff-entry-path (concat (map make-add-diff-entry (concat (:added git-status) (:untracked git-status))) (map make-modify-diff-entry (concat (:changed git-status) (:modified git-status))) (map make-delete-diff-entry (concat (:missing git-status) (:removed git-status)))))))))))) (defn file ^java.io.File [^Git git file-path] (io/file (str (worktree git) "/" file-path))) (defn show-file (^bytes [^Git git name] (show-file git name "HEAD")) (^bytes [^Git git name ref] (let [repo (.getRepository git)] (with-open [rw (RevWalk. repo)] (let [last-commit-id (.resolve repo ref) commit (.parseCommit rw last-commit-id) tree (.getTree commit)] (with-open [tw (TreeWalk. repo)] (.addTree tw tree) (.setRecursive tw true) (.setFilter tw (PathFilter/create name)) (.next tw) (let [id (.getObjectId tw 0)] (when (not= (ObjectId/zeroId) id) (let [loader (.open repo id)] (.getBytes loader)))))))))) (defn locked-files "Returns a set of all files in the repository that could cause major operations on the work tree to fail due to permissions issues or file locks from external processes. Does not include ignored files or files below the .git directory." [^Git git] (let [locked-files (volatile! (transient #{})) repository (.getRepository git) work-directory-path (.toPath (.getWorkTree repository)) dot-git-directory-path (.toPath (.getDirectory repository)) {dirs true files false} (->> (.. git status call getIgnoredNotInIndex) (map #(.resolve work-directory-path ^String %)) (group-by #(.isDirectory (.toFile ^Path %)))) ignored-directory-paths (set dirs) ignored-file-paths (set files)] (Files/walkFileTree work-directory-path (proxy [SimpleFileVisitor] [] (preVisitDirectory [^Path directory-path _attrs] (if (contains? ignored-directory-paths directory-path) FileVisitResult/SKIP_SUBTREE FileVisitResult/CONTINUE)) (visitFile [^Path file-path _attrs] (when (and (not (.startsWith file-path dot-git-directory-path)) (not (contains? ignored-file-paths file-path))) (let [file (.toFile file-path)] (when (fs/locked-file? file) (vswap! locked-files conj! file)))) FileVisitResult/CONTINUE) (visitFileFailed [^Path file-path _attrs] (vswap! locked-files conj! (.toFile file-path)) FileVisitResult/CONTINUE))) (persistent! (deref locked-files)))) (defn locked-files-error-message [locked-files] (str/join "\n" (concat ["The following project files are locked or in use by another process:"] (map #(str "\u00A0\u00A0\u2022\u00A0" %) ; " * " (NO-BREAK SPACE, NO-BREAK SPACE, BULLET, NO-BREAK SPACE) (sort locked-files)) ["" "Please ensure they are writable and quit other applications that reference files in the project before trying again."]))) (defn ensure-gitignore-configured! "When supplied a non-nil Git instance, ensures the repository has a .gitignore file that ignores our .internal and build output directories. Returns true if a change was made to the .gitignore file or a new .gitignore was created." [^Git git] (if (nil? git) false (let [gitignore-file (file git ".gitignore") ^String old-gitignore-text (when (.exists gitignore-file) (slurp gitignore-file :encoding "UTF-8")) old-gitignore-entries (some-> old-gitignore-text str/split-lines) old-gitignore-entries-set (into #{} (remove str/blank?) old-gitignore-entries) line-separator (text-util/guess-line-separator old-gitignore-text)] (if (empty? old-gitignore-entries-set) (do (spit gitignore-file (str/join line-separator default-gitignore-entries) :encoding "UTF-8") true) (let [new-gitignore-entries (into old-gitignore-entries (remove (fn [required-entry] (or (contains? old-gitignore-entries-set required-entry) (contains? old-gitignore-entries-set (fs/without-leading-slash required-entry))))) required-gitignore-entries)] (if (= old-gitignore-entries new-gitignore-entries) false (do (spit gitignore-file (str/join line-separator new-gitignore-entries) :encoding "UTF-8") true))))))) (defn internal-files-are-tracked? "Returns true if the supplied Git instance is non-nil and we detect any tracked files under the .internal or build directories. This means a commit was made with an improperly configured .gitignore, and will likely cause issues during sync with collaborators." [^Git git] (if (nil? git) false (let [repo (.getRepository git)] (with-open [rw (RevWalk. repo)] (let [commit-id (.resolve repo "HEAD") commit (.parseCommit rw commit-id) tree (.getTree commit) ^Collection path-prefixes [".internal/" "build/"]] (with-open [tw (TreeWalk. repo)] (.addTree tw tree) (.setRecursive tw true) (.setFilter tw (PathFilterGroup/createFromStrings path-prefixes)) (.next tw))))))) (defn clone! "Clone a repository into the specified directory." [^CredentialsProvider creds ^String remote-url ^File directory ^ProgressMonitor progress-monitor] (try (with-open [_ (.call (doto (Git/cloneRepository) (.setCredentialsProvider creds) (.setProgressMonitor progress-monitor) (.setURI remote-url) (.setDirectory directory)))] nil) (catch Exception e ;; The .call method throws an exception if the operation was cancelled. ;; Sadly it appears there is not a specific exception type for that, so ;; we silence any exceptions if the operation was cancelled. (when-not (.isCancelled progress-monitor) (throw e))))) (defn- make-transport-config-callback ^TransportConfigCallback [^String ssh-session-password] {:pre [(and (string? ssh-session-password) (not (empty? ssh-session-password)))]} (let [ssh-session-factory (proxy [JschConfigSessionFactory] [] (configure [_host session] (.setPassword ^Session session ssh-session-password)))] (reify TransportConfigCallback (configure [_this transport] (.setSshSessionFactory ^SshTransport transport ssh-session-factory))))) (defn make-credentials-provider ^CredentialsProvider [credentials] (let [^String username (or (:username credentials) "") ^String password (or (:password credentials) "")] (UsernamePasswordCredentialsProvider. username password))) (defn- configure-transport-command! ^TransportCommand [^TransportCommand command purpose {:keys [encrypted-credentials ^int timeout-seconds] :as _opts :or {timeout-seconds -1}}] ;; Taking GitHub as an example, clones made over the https:// protocol ;; authenticate with a username & password in order to push changes. You can ;; also make a Personal Access Token on GitHub to use in place of a password. ;; ;; Clones made over the git:// protocol can only pull, not push. The files are ;; transferred unencrypted. ;; ;; Clones made over the ssh:// protocol use public key authentication. You ;; must generate a public / private key pair and upload the public key to your ;; GitHub account. The private key is loaded from the `.ssh` directory in the ;; HOME folder. It will look for files named `identity`, `id_rsa` and `id_dsa` ;; and it should "just work". However, if a passphrase was used to create the ;; keys, we need to override createDefaultJSch in a subclassed instance of the ;; JschConfigSessionFactory class in order to associate the passphrase with a ;; key file. We do not currently do this here. ;; ;; Most of this information was gathered from here: ;; https://www.codeaffine.com/2014/12/09/jgit-authentication/ (case (:scheme (remote-info (.getRepository command) purpose)) :https (let [credentials (git-credentials/decrypt-credentials encrypted-credentials) credentials-provider (make-credentials-provider credentials)] (.setCredentialsProvider command credentials-provider)) :ssh (let [credentials (git-credentials/decrypt-credentials encrypted-credentials)] (when-some [ssh-session-password (not-empty (:ssh-session-password credentials))] (let [transport-config-callback (make-transport-config-callback ssh-session-password)] (.setTransportConfigCallback command transport-config-callback)))) nil) (cond-> command (pos? timeout-seconds) (.setTimeout timeout-seconds))) (defn pull! [^Git git opts] (-> (.pull git) (configure-transport-command! :fetch opts) (.call))) (defn- make-batching-progress-monitor ^BatchingProgressMonitor [weights-by-task cancelled-atom on-progress!] (let [^double sum-weight (reduce + 0.0 (vals weights-by-task)) normalized-weights-by-task (into {} (map (fn [[task ^double weight]] [task (/ weight sum-weight)])) weights-by-task) progress-by-task (atom (into {} (map #(vector % 0)) (keys weights-by-task))) set-progress (fn [task percent] (swap! progress-by-task assoc task percent)) current-progress (fn [] (reduce + 0.0 (keep (fn [[task ^long percent]] (when-some [^double weight (normalized-weights-by-task task)] (* percent weight 0.01))) @progress-by-task)))] (proxy [BatchingProgressMonitor] [] (onUpdate ([taskName workCurr]) ([taskName workCurr workTotal percentDone] (set-progress taskName percentDone) (on-progress! (current-progress)))) (onEndTask ([taskName workCurr]) ([taskName workCurr workTotal percentDone])) (isCancelled [] (boolean (some-> cancelled-atom deref)))))) (def ^:private ^:const push-tasks ;; TODO: Tweak these weights. {"Finding sources" 1 "Writing objects" 1 "remote: Updating references" 1}) (defn- configure-push-command! ^PushCommand [^PushCommand command {:keys [dry-run on-progress] :as _opts}] (cond-> command dry-run (.setDryRun true) (some? on-progress) (.setProgressMonitor (make-batching-progress-monitor push-tasks nil on-progress)))) (defn push! [^Git git opts] (-> (.push git) (configure-push-command! opts) (configure-transport-command! :push opts) (.call))) (defn make-add-change [file-path] {:change-type :add :old-path nil :new-path file-path}) (defn make-delete-change [file-path] {:change-type :delete :old-path file-path :new-path nil}) (defn make-modify-change [file-path] {:change-type :modify :old-path file-path :new-path file-path}) (defn make-rename-change [old-path new-path] {:change-type :rename :old-path old-path :new-path new-path}) (defn change-path [{:keys [old-path new-path]}] (or new-path old-path)) (defn stage-change! [^Git git {:keys [change-type old-path new-path]}] (case change-type (:add :modify) (-> git .add (.addFilepattern new-path) .call) :delete (-> git .rm (.addFilepattern old-path) (.setCached true) .call) :rename (do (-> git .rm (.addFilepattern old-path) (.setCached true) .call) (-> git .add (.addFilepattern new-path) .call)))) (defn unstage-change! [^Git git {:keys [change-type old-path new-path]}] (case change-type (:add :modify) (-> git .reset (.addPath new-path) .call) :delete (-> git .reset (.addPath old-path) .call) :rename (-> git .reset (.addPath old-path) (.addPath new-path) .call))) (defn- find-case-changes [added-paths removed-paths] (into {} (keep (fn [^String added-path] (some (fn [^String removed-path] (when (.equalsIgnoreCase added-path removed-path) [added-path removed-path])) removed-paths))) added-paths)) (defn- perform-case-changes! [^Git git case-changes] ;; In case we fail to perform a case change, attempt to undo the successfully ;; performed case changes before throwing. (let [performed-case-changes-atom (atom [])] (try (doseq [[new-path old-path] case-changes] (let [new-file (file git new-path) old-file (file git old-path)] (fs/move-file! old-file new-file) (swap! performed-case-changes-atom conj [new-file old-file]))) (catch Throwable error ;; Attempt to undo the performed case changes before throwing. (doseq [[new-file old-file] (rseq @performed-case-changes-atom)] (fs/move-file! new-file old-file {:fail :silently})) (throw error))))) (defn- undo-case-changes! [^Git git case-changes] (perform-case-changes! git (map reverse case-changes))) (defn revert-to-revision! "High-level revert. Resets the working directory to the state it would have after a clean checkout of the specified start-ref. Performs the equivalent of git reset --hard git clean --force -d" [^Git git ^RevCommit start-ref] ;; On case-insensitive file systems, we must manually revert case changes. ;; Otherwise the new-cased files will be removed during the clean call. (when-not fs/case-sensitive? (let [{:keys [missing untracked]} (status git) case-changes (find-case-changes untracked missing)] (undo-case-changes! git case-changes))) (-> (.reset git) (.setMode ResetCommand$ResetType/HARD) (.setRef (.name start-ref)) (.call)) (-> (.clean git) (.setCleanDirectories true) (.call))) (defn- revert-case-changes! "Finds and reverts any case changes in the supplied git status. Returns a map of the case changes that were reverted." [^Git git {:keys [added changed missing removed untracked] :as _status}] ;; If we're on a case-insensitive file system, we revert case-changes before ;; stashing. The case-changes will be restored when we apply the stash. (let [case-changes (find-case-changes (set/union added untracked) (set/union removed missing))] (when (seq case-changes) ;; Unstage everything so that we can safely undo the case changes. ;; This is fine, because we will stage everything before stashing. (when-some [staged-paths (not-empty (set/union added changed removed))] (let [reset-command (.reset git)] (doseq [path staged-paths] (.addPath reset-command path)) (.call reset-command))) ;; Undo case-changes. (undo-case-changes! git case-changes)) case-changes)) (defn- stage-removals! [^Git git status pred] (when-some [removed-paths (not-empty (into #{} (filter pred) (:missing status)))] (let [rm-command (.rm git)] (.setCached rm-command true) (doseq [path removed-paths] (.addFilepattern rm-command path)) (.call rm-command) nil))) (defn- stage-additions! [^Git git status pred] (when-some [changed-paths (not-empty (into #{} (filter pred) (concat (:modified status) (:untracked status))))] (let [add-command (.add git)] (doseq [path changed-paths] (.addFilepattern add-command path)) (.call add-command) nil))) (defn stage-all! "Stage all unstaged changes in the specified Git repo." [^Git git] (let [status (status git) include? (constantly true)] (stage-removals! git status include?) (stage-additions! git status include?))) (defn stash! "High-level stash. Before stashing, stages all changes. We do this because stashes internally treat untracked files differently from tracked files. Normally untracked files are not stashed at all, but even when using the setIncludeUntracked flag, untracked files are dealt with separately from tracked files. When later applied, a conflict among the tracked files will abort the stash apply command before the untracked files are restored. For our purposes, we want a unified set of conflicts among all the tracked and untracked files. Before stashing, we also revert any case-changes if we're running on a case-insensitive file system. We will reapply the case-changes when the stash is applied. If we do not do this, we will lose any remote changes to case- changed files when applying the stash. Returns nil if there was nothing to stash, or a map with the stash ref and the set of file paths that were staged at the time the stash was made." [^Git git] (let [pre-stash-status (status git) reverted-case-changes (when-not fs/case-sensitive? (revert-case-changes! git pre-stash-status))] (stage-all! git) (when-some [stash-ref (-> git .stashCreate .call)] {:ref stash-ref :case-changes reverted-case-changes :staged (set/union (:added pre-stash-status) (:changed pre-stash-status) (:removed pre-stash-status))}))) (defn stash-apply! [^Git git stash-info] (when (some? stash-info) ;; Apply the stash. The apply-result will be either an ObjectId returned ;; from (.call StashApplyCommand) or a StashApplyFailureException if thrown. (let [apply-result (try (-> (.stashApply git) (.setStashRef (.name ^RevCommit (:ref stash-info))) (.call)) (catch StashApplyFailureException error error)) status-after-apply (status git) paths-with-conflicts (set (keys (:conflicting-stage-state status-after-apply))) paths-to-unstage (set/difference (set/union (:added status-after-apply) (:changed status-after-apply) (:removed status-after-apply)) paths-with-conflicts)] ;; Unstage everything that is without conflict. Later we will stage ;; everything that was staged at the time the stash was made. (when-some [staged-paths (not-empty paths-to-unstage)] (let [reset-command (.reset git)] (doseq [path staged-paths] (.addPath reset-command path)) (.call reset-command))) ;; Restore any reverted case changes. Skip over case changes that involve ;; conflicting paths just in case. (let [case-changes (remove (partial some paths-with-conflicts) (:case-changes stash-info))] (perform-case-changes! git case-changes)) ;; Restore staged files state from before the stash. (when (empty? paths-with-conflicts) (let [status (status git) was-staged? (:staged stash-info)] (stage-removals! git status was-staged?) (stage-additions! git status was-staged?))) (if (instance? Throwable apply-result) (throw apply-result) apply-result)))) (defn stash-drop! [^Git git stash-info] (let [stash-ref ^RevCommit (:ref stash-info) stashes (map-indexed vector (.call (.stashList git))) matching-stash (first (filter #(= stash-ref (second %)) stashes))] (when matching-stash (-> (.stashDrop git) (.setStashRef (first matching-stash)) (.call))))) (defn commit [^Git git ^String message] (-> (.commit git) (.setMessage message) (.call))) ;; "High level" revert ;; * Changed files are checked out ;; * New files are removed ;; * Deleted files are checked out ;; NOTE: Not to be confused with "git revert" (defn revert [^Git git files] (let [us (unified-status git) renames (into {} (keep (fn [new-path] (when-some [old-path (find-original-for-renamed us new-path)] [new-path old-path]))) files) others (into [] (remove renames) files)] ;; Revert renames first. (doseq [[new-path old-path] renames] (-> git .rm (.addFilepattern new-path) (.setCached true) .call) (fs/delete-file! (file git new-path)) (-> git .reset (.addPath old-path) .call) (-> git .checkout (.addPath old-path) .call)) ;; Revert others. (when (seq others) (let [co (-> git (.checkout)) reset (-> git (.reset) (.setRef "HEAD"))] (doseq [path others] (.addPath co path) (.addPath reset path)) (.call reset) (.call co)) ;; Delete all untracked files in "others" as a last step ;; JGit doesn't support this operation with RmCommand (let [s (status git)] (doseq [path others] (when (contains? (:untracked s) path) (fs/delete-file! (file git path) {:missing :fail}))))))) (def ^:private ^:const clone-tasks {"remote: Finding sources" 1 "Receiving objects" 88 "Resolving deltas" 10 "Updating references" 1}) (defn make-clone-monitor ^ProgressMonitor [^ProgressBar progress-bar cancelled-atom] (make-batching-progress-monitor clone-tasks cancelled-atom (fn [progress] (ui/run-later (.setProgress progress-bar progress))))) ;; ================================================================================= (defn selection-diffable? [selection] (and (= 1 (count selection)) (let [change-type (:change-type (first selection))] (and (keyword? change-type) (not= :add change-type) (not= :delete change-type))))) (defn selection-diff-data [git selection] (let [change (first selection) old-path (or (:old-path change) (:new-path change) ) new-path (or (:new-path change) (:old-path change) ) old (String. ^bytes (show-file git old-path)) new (slurp (file git new-path)) binary? (not-every? text-util/text-char? new)] {:binary? binary? :new new :new-path new-path :old old :old-path old-path})) (defn init [^String path] (-> (Git/init) (.setDirectory (File. path)) (.call)))
1360
;; 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.git (:require [camel-snake-kebab :as camel] [clojure.java.io :as io] [clojure.set :as set] [clojure.string :as str] [editor.git-credentials :as git-credentials] [editor.fs :as fs] [editor.ui :as ui] [util.text-util :as text-util] [service.log :as log]) (:import [java.io File IOException] [java.net URI] [java.nio.file Files FileVisitResult Path SimpleFileVisitor] [java.util Collection] [javafx.scene.control ProgressBar] [org.eclipse.jgit.api Git PushCommand ResetCommand$ResetType TransportCommand TransportConfigCallback] [org.eclipse.jgit.api.errors StashApplyFailureException] [org.eclipse.jgit.diff DiffEntry RenameDetector] [org.eclipse.jgit.errors MissingObjectException] [org.eclipse.jgit.lib BatchingProgressMonitor BranchConfig ObjectId ProgressMonitor Repository] [org.eclipse.jgit.revwalk RevCommit RevWalk] [org.eclipse.jgit.transport CredentialsProvider JschConfigSessionFactory RemoteConfig SshTransport URIish UsernamePasswordCredentialsProvider] [org.eclipse.jgit.treewalk FileTreeIterator TreeWalk] [org.eclipse.jgit.treewalk.filter PathFilter PathFilterGroup] [com.jcraft.jsch Session])) (set! *warn-on-reflection* true) ;; When opening a project, we ensure the .gitignore file contains every entry on this list. (defonce required-gitignore-entries ["/.internal" "/build"]) ;; Based on the contents of the .gitignore file we include in template projects. (defonce default-gitignore-entries (vec (concat required-gitignore-entries [".externalToolBuilders" ".DS_Store" "Thumbs.db" ".lock-wscript" "*.pyc" ".project" ".cproject" "builtins"]))) (defn try-open ^Git [^File repo-path] (try (Git/open repo-path) (catch Exception _ nil))) (defn get-commit ^RevCommit [^Repository repository revision] (when-some [object-id (.resolve repository revision)] (let [walk (RevWalk. repository)] (.setRetainBody walk true) (.parseCommit walk object-id)))) (defn- diff-entry->map [^DiffEntry de] ; NOTE: We convert /dev/null paths to nil, and convert copies into adds. (let [f (fn [p] (when-not (= p "/dev/null") p)) change-type (-> (.getChangeType de) str .toLowerCase keyword)] (if (= :copy change-type) {:score 0 :change-type :add :old-path nil :new-path (f (.getNewPath de))} {:score (.getScore de) :change-type change-type :old-path (f (.getOldPath de)) :new-path (f (.getNewPath de))}))) (defn- find-original-for-renamed [ustatus file] (->> ustatus (filter (fn [e] (= file (:new-path e)))) (map :old-path) (first))) ;; ================================================================================= (defn- as-repository ^Repository [git-or-repository] (if (instance? Repository git-or-repository) git-or-repository (.getRepository ^Git git-or-repository))) (defn user-info [git-or-repository] (let [repository (as-repository git-or-repository) config (.getConfig repository) name (or (.getString config "user" nil "name") "") email (or (.getString config "user" nil "email") "")] {:name <NAME> :email email})) (defn set-user-info! [git-or-repository {new-name :name new-email :email :as user-info}] (assert (string? new-name)) (assert (string? new-email)) (when (not= user-info (user-info git-or-repository)) ;; The new user info differs from the stored info. ;; Update user info in the repository config. (let [repository (as-repository git-or-repository) config (.getConfig repository)] (.setString config "user" nil "name" new-name) (.setString config "user" nil "email" new-email) ;; Attempt to save the updated repository config. ;; The in-memory config retains the modifications even if this fails. (try (.save config) (catch IOException error (log/warn :msg "Failed to save updated user info to Git repository config." :exception error)))))) (defn- remote-name ^String [^Repository repository] (let [config (.getConfig repository) branch (.getBranch repository) branch-config (BranchConfig. config branch) remote-names (map #(.getName ^RemoteConfig %) (RemoteConfig/getAllRemoteConfigs config))] (or (.getRemote branch-config) (some (fn [remote-name] (when (.equalsIgnoreCase "origin" remote-name) remote-name)) remote-names) (first remote-names)))) (defn remote-info ([git-or-repository purpose] (let [repository (as-repository git-or-repository) remote-name (or (remote-name repository) "origin")] (remote-info repository purpose remote-name))) ([git-or-repository purpose ^String remote-name] (let [repository (as-repository git-or-repository) config (.getConfig repository) remote (RemoteConfig. config remote-name)] (when-some [^URIish uri-ish (first (case purpose :fetch (.getURIs remote) :push (concat (.getPushURIs remote) (.getURIs remote))))] {:name remote-name :scheme (if-some [scheme (.getScheme uri-ish)] (keyword scheme) :ssh) :host (.getHost uri-ish) :port (.getPort uri-ish) :path (.getPath uri-ish) :user (.getUser uri-ish) :pass (.getPass uri-ish)})))) (defn remote-uri ^URI [{:keys [scheme ^String host ^int port ^String path] :or {port -1} :as remote-info}] (let [^String user-info (if-some [user (not-empty (:user remote-info))] (if-some [pass (not-empty (:pass remote-info))] (str user ":" pass) user))] (URI. (name scheme) user-info host port path nil nil))) ;; Does the equivalent *config-wise* of: ;; > git config remote.origin.url url ;; > git push -u origin ;; Which is: ;; > git config remote.origin.url url ;; > git config remote.origin.fetch +refs/heads/*:refs/remotes/origin/* ;; > git config branch.master.remote origin ;; > git config branch.master.merge refs/heads/master ;; according to https://stackoverflow.com/questions/27823940/jgit-pushing-a-branch-and-add-upstream-u-option (defn config-remote! [^Git git url] (let [config (.. git getRepository getConfig)] (doto config (.setString "remote" "origin" "url" url) (.setString "remote" "origin" "fetch" "+refs/heads/*:refs/remotes/origin/*") (.setString "branch" "master" "remote" "origin") (.setString "branch" "master" "merge" "refs/heads/master") (.save)))) (defn worktree [^Git git] (.getWorkTree (.getRepository git))) (defn get-current-commit-ref [^Git git] (get-commit (.getRepository git) "HEAD")) (defn status [^Git git] (let [s (-> git (.status) (.call))] {:added (set (.getAdded s)) :changed (set (.getChanged s)) :conflicting (set (.getConflicting s)) :ignored-not-in-index (set (.getIgnoredNotInIndex s)) :missing (set (.getMissing s)) :modified (set (.getModified s)) :removed (set (.getRemoved s)) :uncommitted-changes (set (.getUncommittedChanges s)) :untracked (set (.getUntracked s)) :untracked-folders (set (.getUntrackedFolders s)) :conflicting-stage-state (apply hash-map (mapcat (fn [[k v]] [k (-> v str camel/->kebab-case keyword)]) (.getConflictingStageState s)))})) (defn- make-add-diff-entry [file-path] {:score 0 :change-type :add :old-path nil :new-path file-path}) (defn- make-delete-diff-entry [file-path] {:score 0 :change-type :delete :old-path file-path :new-path nil}) (defn- make-modify-diff-entry [file-path] {:score 0 :change-type :modify :old-path file-path :new-path file-path}) (defn- diff-entry-path ^String [{:keys [old-path new-path]}] (or new-path old-path)) (defn unified-status "Get the actual status by comparing contents on disk and HEAD. The state of the index (i.e. whether or not a file is staged) does not matter." ([^Git git] (unified-status git (status git))) ([^Git git git-status] (let [changed-paths (into #{} (mapcat git-status) [:added :changed :missing :modified :removed :untracked])] (if (empty? changed-paths) [] (let [repository (.getRepository git) rename-detector (doto (RenameDetector. repository) (.addAll (with-open [tree-walk (doto (TreeWalk. repository) (.addTree (.getTree ^RevCommit (get-commit repository "HEAD"))) (.addTree (FileTreeIterator. repository)) (.setFilter (PathFilterGroup/createFromStrings ^Collection changed-paths)) (.setRecursive true))] (DiffEntry/scan tree-walk))))] (try (let [diff-entries (.compute rename-detector nil)] (mapv diff-entry->map diff-entries)) (catch MissingObjectException _ ;; TODO: Workaround for what appears to be a bug inside JGit. ;; The rename detector failed for some reason. Report the status ;; without considering renames. This results in separate :added and ;; :deleted entries for unstaged renames, but will resolve into a ;; single :renamed entry once staged. (sort-by diff-entry-path (concat (map make-add-diff-entry (concat (:added git-status) (:untracked git-status))) (map make-modify-diff-entry (concat (:changed git-status) (:modified git-status))) (map make-delete-diff-entry (concat (:missing git-status) (:removed git-status)))))))))))) (defn file ^java.io.File [^Git git file-path] (io/file (str (worktree git) "/" file-path))) (defn show-file (^bytes [^Git git name] (show-file git name "HEAD")) (^bytes [^Git git name ref] (let [repo (.getRepository git)] (with-open [rw (RevWalk. repo)] (let [last-commit-id (.resolve repo ref) commit (.parseCommit rw last-commit-id) tree (.getTree commit)] (with-open [tw (TreeWalk. repo)] (.addTree tw tree) (.setRecursive tw true) (.setFilter tw (PathFilter/create name)) (.next tw) (let [id (.getObjectId tw 0)] (when (not= (ObjectId/zeroId) id) (let [loader (.open repo id)] (.getBytes loader)))))))))) (defn locked-files "Returns a set of all files in the repository that could cause major operations on the work tree to fail due to permissions issues or file locks from external processes. Does not include ignored files or files below the .git directory." [^Git git] (let [locked-files (volatile! (transient #{})) repository (.getRepository git) work-directory-path (.toPath (.getWorkTree repository)) dot-git-directory-path (.toPath (.getDirectory repository)) {dirs true files false} (->> (.. git status call getIgnoredNotInIndex) (map #(.resolve work-directory-path ^String %)) (group-by #(.isDirectory (.toFile ^Path %)))) ignored-directory-paths (set dirs) ignored-file-paths (set files)] (Files/walkFileTree work-directory-path (proxy [SimpleFileVisitor] [] (preVisitDirectory [^Path directory-path _attrs] (if (contains? ignored-directory-paths directory-path) FileVisitResult/SKIP_SUBTREE FileVisitResult/CONTINUE)) (visitFile [^Path file-path _attrs] (when (and (not (.startsWith file-path dot-git-directory-path)) (not (contains? ignored-file-paths file-path))) (let [file (.toFile file-path)] (when (fs/locked-file? file) (vswap! locked-files conj! file)))) FileVisitResult/CONTINUE) (visitFileFailed [^Path file-path _attrs] (vswap! locked-files conj! (.toFile file-path)) FileVisitResult/CONTINUE))) (persistent! (deref locked-files)))) (defn locked-files-error-message [locked-files] (str/join "\n" (concat ["The following project files are locked or in use by another process:"] (map #(str "\u00A0\u00A0\u2022\u00A0" %) ; " * " (NO-BREAK SPACE, NO-BREAK SPACE, BULLET, NO-BREAK SPACE) (sort locked-files)) ["" "Please ensure they are writable and quit other applications that reference files in the project before trying again."]))) (defn ensure-gitignore-configured! "When supplied a non-nil Git instance, ensures the repository has a .gitignore file that ignores our .internal and build output directories. Returns true if a change was made to the .gitignore file or a new .gitignore was created." [^Git git] (if (nil? git) false (let [gitignore-file (file git ".gitignore") ^String old-gitignore-text (when (.exists gitignore-file) (slurp gitignore-file :encoding "UTF-8")) old-gitignore-entries (some-> old-gitignore-text str/split-lines) old-gitignore-entries-set (into #{} (remove str/blank?) old-gitignore-entries) line-separator (text-util/guess-line-separator old-gitignore-text)] (if (empty? old-gitignore-entries-set) (do (spit gitignore-file (str/join line-separator default-gitignore-entries) :encoding "UTF-8") true) (let [new-gitignore-entries (into old-gitignore-entries (remove (fn [required-entry] (or (contains? old-gitignore-entries-set required-entry) (contains? old-gitignore-entries-set (fs/without-leading-slash required-entry))))) required-gitignore-entries)] (if (= old-gitignore-entries new-gitignore-entries) false (do (spit gitignore-file (str/join line-separator new-gitignore-entries) :encoding "UTF-8") true))))))) (defn internal-files-are-tracked? "Returns true if the supplied Git instance is non-nil and we detect any tracked files under the .internal or build directories. This means a commit was made with an improperly configured .gitignore, and will likely cause issues during sync with collaborators." [^Git git] (if (nil? git) false (let [repo (.getRepository git)] (with-open [rw (RevWalk. repo)] (let [commit-id (.resolve repo "HEAD") commit (.parseCommit rw commit-id) tree (.getTree commit) ^Collection path-prefixes [".internal/" "build/"]] (with-open [tw (TreeWalk. repo)] (.addTree tw tree) (.setRecursive tw true) (.setFilter tw (PathFilterGroup/createFromStrings path-prefixes)) (.next tw))))))) (defn clone! "Clone a repository into the specified directory." [^CredentialsProvider creds ^String remote-url ^File directory ^ProgressMonitor progress-monitor] (try (with-open [_ (.call (doto (Git/cloneRepository) (.setCredentialsProvider creds) (.setProgressMonitor progress-monitor) (.setURI remote-url) (.setDirectory directory)))] nil) (catch Exception e ;; The .call method throws an exception if the operation was cancelled. ;; Sadly it appears there is not a specific exception type for that, so ;; we silence any exceptions if the operation was cancelled. (when-not (.isCancelled progress-monitor) (throw e))))) (defn- make-transport-config-callback ^TransportConfigCallback [^String ssh-session-password] {:pre [(and (string? ssh-session-password) (not (empty? ssh-session-password)))]} (let [ssh-session-factory (proxy [JschConfigSessionFactory] [] (configure [_host session] (.setPassword ^Session session ssh-session-password)))] (reify TransportConfigCallback (configure [_this transport] (.setSshSessionFactory ^SshTransport transport ssh-session-factory))))) (defn make-credentials-provider ^CredentialsProvider [credentials] (let [^String username (or (:username credentials) "") ^String password (or (:password credentials) "")] (UsernamePasswordCredentialsProvider. username password))) (defn- configure-transport-command! ^TransportCommand [^TransportCommand command purpose {:keys [encrypted-credentials ^int timeout-seconds] :as _opts :or {timeout-seconds -1}}] ;; Taking GitHub as an example, clones made over the https:// protocol ;; authenticate with a username & password in order to push changes. You can ;; also make a Personal Access Token on GitHub to use in place of a password. ;; ;; Clones made over the git:// protocol can only pull, not push. The files are ;; transferred unencrypted. ;; ;; Clones made over the ssh:// protocol use public key authentication. You ;; must generate a public / private key pair and upload the public key to your ;; GitHub account. The private key is loaded from the `.ssh` directory in the ;; HOME folder. It will look for files named `identity`, `id_rsa` and `id_dsa` ;; and it should "just work". However, if a passphrase was used to create the ;; keys, we need to override createDefaultJSch in a subclassed instance of the ;; JschConfigSessionFactory class in order to associate the passphrase with a ;; key file. We do not currently do this here. ;; ;; Most of this information was gathered from here: ;; https://www.codeaffine.com/2014/12/09/jgit-authentication/ (case (:scheme (remote-info (.getRepository command) purpose)) :https (let [credentials (git-credentials/decrypt-credentials encrypted-credentials) credentials-provider (make-credentials-provider credentials)] (.setCredentialsProvider command credentials-provider)) :ssh (let [credentials (git-credentials/decrypt-credentials encrypted-credentials)] (when-some [ssh-session-password (not-empty (:ssh-session-password credentials))] (let [transport-config-callback (make-transport-config-callback ssh-session-password)] (.setTransportConfigCallback command transport-config-callback)))) nil) (cond-> command (pos? timeout-seconds) (.setTimeout timeout-seconds))) (defn pull! [^Git git opts] (-> (.pull git) (configure-transport-command! :fetch opts) (.call))) (defn- make-batching-progress-monitor ^BatchingProgressMonitor [weights-by-task cancelled-atom on-progress!] (let [^double sum-weight (reduce + 0.0 (vals weights-by-task)) normalized-weights-by-task (into {} (map (fn [[task ^double weight]] [task (/ weight sum-weight)])) weights-by-task) progress-by-task (atom (into {} (map #(vector % 0)) (keys weights-by-task))) set-progress (fn [task percent] (swap! progress-by-task assoc task percent)) current-progress (fn [] (reduce + 0.0 (keep (fn [[task ^long percent]] (when-some [^double weight (normalized-weights-by-task task)] (* percent weight 0.01))) @progress-by-task)))] (proxy [BatchingProgressMonitor] [] (onUpdate ([taskName workCurr]) ([taskName workCurr workTotal percentDone] (set-progress taskName percentDone) (on-progress! (current-progress)))) (onEndTask ([taskName workCurr]) ([taskName workCurr workTotal percentDone])) (isCancelled [] (boolean (some-> cancelled-atom deref)))))) (def ^:private ^:const push-tasks ;; TODO: Tweak these weights. {"Finding sources" 1 "Writing objects" 1 "remote: Updating references" 1}) (defn- configure-push-command! ^PushCommand [^PushCommand command {:keys [dry-run on-progress] :as _opts}] (cond-> command dry-run (.setDryRun true) (some? on-progress) (.setProgressMonitor (make-batching-progress-monitor push-tasks nil on-progress)))) (defn push! [^Git git opts] (-> (.push git) (configure-push-command! opts) (configure-transport-command! :push opts) (.call))) (defn make-add-change [file-path] {:change-type :add :old-path nil :new-path file-path}) (defn make-delete-change [file-path] {:change-type :delete :old-path file-path :new-path nil}) (defn make-modify-change [file-path] {:change-type :modify :old-path file-path :new-path file-path}) (defn make-rename-change [old-path new-path] {:change-type :rename :old-path old-path :new-path new-path}) (defn change-path [{:keys [old-path new-path]}] (or new-path old-path)) (defn stage-change! [^Git git {:keys [change-type old-path new-path]}] (case change-type (:add :modify) (-> git .add (.addFilepattern new-path) .call) :delete (-> git .rm (.addFilepattern old-path) (.setCached true) .call) :rename (do (-> git .rm (.addFilepattern old-path) (.setCached true) .call) (-> git .add (.addFilepattern new-path) .call)))) (defn unstage-change! [^Git git {:keys [change-type old-path new-path]}] (case change-type (:add :modify) (-> git .reset (.addPath new-path) .call) :delete (-> git .reset (.addPath old-path) .call) :rename (-> git .reset (.addPath old-path) (.addPath new-path) .call))) (defn- find-case-changes [added-paths removed-paths] (into {} (keep (fn [^String added-path] (some (fn [^String removed-path] (when (.equalsIgnoreCase added-path removed-path) [added-path removed-path])) removed-paths))) added-paths)) (defn- perform-case-changes! [^Git git case-changes] ;; In case we fail to perform a case change, attempt to undo the successfully ;; performed case changes before throwing. (let [performed-case-changes-atom (atom [])] (try (doseq [[new-path old-path] case-changes] (let [new-file (file git new-path) old-file (file git old-path)] (fs/move-file! old-file new-file) (swap! performed-case-changes-atom conj [new-file old-file]))) (catch Throwable error ;; Attempt to undo the performed case changes before throwing. (doseq [[new-file old-file] (rseq @performed-case-changes-atom)] (fs/move-file! new-file old-file {:fail :silently})) (throw error))))) (defn- undo-case-changes! [^Git git case-changes] (perform-case-changes! git (map reverse case-changes))) (defn revert-to-revision! "High-level revert. Resets the working directory to the state it would have after a clean checkout of the specified start-ref. Performs the equivalent of git reset --hard git clean --force -d" [^Git git ^RevCommit start-ref] ;; On case-insensitive file systems, we must manually revert case changes. ;; Otherwise the new-cased files will be removed during the clean call. (when-not fs/case-sensitive? (let [{:keys [missing untracked]} (status git) case-changes (find-case-changes untracked missing)] (undo-case-changes! git case-changes))) (-> (.reset git) (.setMode ResetCommand$ResetType/HARD) (.setRef (.name start-ref)) (.call)) (-> (.clean git) (.setCleanDirectories true) (.call))) (defn- revert-case-changes! "Finds and reverts any case changes in the supplied git status. Returns a map of the case changes that were reverted." [^Git git {:keys [added changed missing removed untracked] :as _status}] ;; If we're on a case-insensitive file system, we revert case-changes before ;; stashing. The case-changes will be restored when we apply the stash. (let [case-changes (find-case-changes (set/union added untracked) (set/union removed missing))] (when (seq case-changes) ;; Unstage everything so that we can safely undo the case changes. ;; This is fine, because we will stage everything before stashing. (when-some [staged-paths (not-empty (set/union added changed removed))] (let [reset-command (.reset git)] (doseq [path staged-paths] (.addPath reset-command path)) (.call reset-command))) ;; Undo case-changes. (undo-case-changes! git case-changes)) case-changes)) (defn- stage-removals! [^Git git status pred] (when-some [removed-paths (not-empty (into #{} (filter pred) (:missing status)))] (let [rm-command (.rm git)] (.setCached rm-command true) (doseq [path removed-paths] (.addFilepattern rm-command path)) (.call rm-command) nil))) (defn- stage-additions! [^Git git status pred] (when-some [changed-paths (not-empty (into #{} (filter pred) (concat (:modified status) (:untracked status))))] (let [add-command (.add git)] (doseq [path changed-paths] (.addFilepattern add-command path)) (.call add-command) nil))) (defn stage-all! "Stage all unstaged changes in the specified Git repo." [^Git git] (let [status (status git) include? (constantly true)] (stage-removals! git status include?) (stage-additions! git status include?))) (defn stash! "High-level stash. Before stashing, stages all changes. We do this because stashes internally treat untracked files differently from tracked files. Normally untracked files are not stashed at all, but even when using the setIncludeUntracked flag, untracked files are dealt with separately from tracked files. When later applied, a conflict among the tracked files will abort the stash apply command before the untracked files are restored. For our purposes, we want a unified set of conflicts among all the tracked and untracked files. Before stashing, we also revert any case-changes if we're running on a case-insensitive file system. We will reapply the case-changes when the stash is applied. If we do not do this, we will lose any remote changes to case- changed files when applying the stash. Returns nil if there was nothing to stash, or a map with the stash ref and the set of file paths that were staged at the time the stash was made." [^Git git] (let [pre-stash-status (status git) reverted-case-changes (when-not fs/case-sensitive? (revert-case-changes! git pre-stash-status))] (stage-all! git) (when-some [stash-ref (-> git .stashCreate .call)] {:ref stash-ref :case-changes reverted-case-changes :staged (set/union (:added pre-stash-status) (:changed pre-stash-status) (:removed pre-stash-status))}))) (defn stash-apply! [^Git git stash-info] (when (some? stash-info) ;; Apply the stash. The apply-result will be either an ObjectId returned ;; from (.call StashApplyCommand) or a StashApplyFailureException if thrown. (let [apply-result (try (-> (.stashApply git) (.setStashRef (.name ^RevCommit (:ref stash-info))) (.call)) (catch StashApplyFailureException error error)) status-after-apply (status git) paths-with-conflicts (set (keys (:conflicting-stage-state status-after-apply))) paths-to-unstage (set/difference (set/union (:added status-after-apply) (:changed status-after-apply) (:removed status-after-apply)) paths-with-conflicts)] ;; Unstage everything that is without conflict. Later we will stage ;; everything that was staged at the time the stash was made. (when-some [staged-paths (not-empty paths-to-unstage)] (let [reset-command (.reset git)] (doseq [path staged-paths] (.addPath reset-command path)) (.call reset-command))) ;; Restore any reverted case changes. Skip over case changes that involve ;; conflicting paths just in case. (let [case-changes (remove (partial some paths-with-conflicts) (:case-changes stash-info))] (perform-case-changes! git case-changes)) ;; Restore staged files state from before the stash. (when (empty? paths-with-conflicts) (let [status (status git) was-staged? (:staged stash-info)] (stage-removals! git status was-staged?) (stage-additions! git status was-staged?))) (if (instance? Throwable apply-result) (throw apply-result) apply-result)))) (defn stash-drop! [^Git git stash-info] (let [stash-ref ^RevCommit (:ref stash-info) stashes (map-indexed vector (.call (.stashList git))) matching-stash (first (filter #(= stash-ref (second %)) stashes))] (when matching-stash (-> (.stashDrop git) (.setStashRef (first matching-stash)) (.call))))) (defn commit [^Git git ^String message] (-> (.commit git) (.setMessage message) (.call))) ;; "High level" revert ;; * Changed files are checked out ;; * New files are removed ;; * Deleted files are checked out ;; NOTE: Not to be confused with "git revert" (defn revert [^Git git files] (let [us (unified-status git) renames (into {} (keep (fn [new-path] (when-some [old-path (find-original-for-renamed us new-path)] [new-path old-path]))) files) others (into [] (remove renames) files)] ;; Revert renames first. (doseq [[new-path old-path] renames] (-> git .rm (.addFilepattern new-path) (.setCached true) .call) (fs/delete-file! (file git new-path)) (-> git .reset (.addPath old-path) .call) (-> git .checkout (.addPath old-path) .call)) ;; Revert others. (when (seq others) (let [co (-> git (.checkout)) reset (-> git (.reset) (.setRef "HEAD"))] (doseq [path others] (.addPath co path) (.addPath reset path)) (.call reset) (.call co)) ;; Delete all untracked files in "others" as a last step ;; JGit doesn't support this operation with RmCommand (let [s (status git)] (doseq [path others] (when (contains? (:untracked s) path) (fs/delete-file! (file git path) {:missing :fail}))))))) (def ^:private ^:const clone-tasks {"remote: Finding sources" 1 "Receiving objects" 88 "Resolving deltas" 10 "Updating references" 1}) (defn make-clone-monitor ^ProgressMonitor [^ProgressBar progress-bar cancelled-atom] (make-batching-progress-monitor clone-tasks cancelled-atom (fn [progress] (ui/run-later (.setProgress progress-bar progress))))) ;; ================================================================================= (defn selection-diffable? [selection] (and (= 1 (count selection)) (let [change-type (:change-type (first selection))] (and (keyword? change-type) (not= :add change-type) (not= :delete change-type))))) (defn selection-diff-data [git selection] (let [change (first selection) old-path (or (:old-path change) (:new-path change) ) new-path (or (:new-path change) (:old-path change) ) old (String. ^bytes (show-file git old-path)) new (slurp (file git new-path)) binary? (not-every? text-util/text-char? new)] {:binary? binary? :new new :new-path new-path :old old :old-path old-path})) (defn init [^String path] (-> (Git/init) (.setDirectory (File. path)) (.call)))
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.git (:require [camel-snake-kebab :as camel] [clojure.java.io :as io] [clojure.set :as set] [clojure.string :as str] [editor.git-credentials :as git-credentials] [editor.fs :as fs] [editor.ui :as ui] [util.text-util :as text-util] [service.log :as log]) (:import [java.io File IOException] [java.net URI] [java.nio.file Files FileVisitResult Path SimpleFileVisitor] [java.util Collection] [javafx.scene.control ProgressBar] [org.eclipse.jgit.api Git PushCommand ResetCommand$ResetType TransportCommand TransportConfigCallback] [org.eclipse.jgit.api.errors StashApplyFailureException] [org.eclipse.jgit.diff DiffEntry RenameDetector] [org.eclipse.jgit.errors MissingObjectException] [org.eclipse.jgit.lib BatchingProgressMonitor BranchConfig ObjectId ProgressMonitor Repository] [org.eclipse.jgit.revwalk RevCommit RevWalk] [org.eclipse.jgit.transport CredentialsProvider JschConfigSessionFactory RemoteConfig SshTransport URIish UsernamePasswordCredentialsProvider] [org.eclipse.jgit.treewalk FileTreeIterator TreeWalk] [org.eclipse.jgit.treewalk.filter PathFilter PathFilterGroup] [com.jcraft.jsch Session])) (set! *warn-on-reflection* true) ;; When opening a project, we ensure the .gitignore file contains every entry on this list. (defonce required-gitignore-entries ["/.internal" "/build"]) ;; Based on the contents of the .gitignore file we include in template projects. (defonce default-gitignore-entries (vec (concat required-gitignore-entries [".externalToolBuilders" ".DS_Store" "Thumbs.db" ".lock-wscript" "*.pyc" ".project" ".cproject" "builtins"]))) (defn try-open ^Git [^File repo-path] (try (Git/open repo-path) (catch Exception _ nil))) (defn get-commit ^RevCommit [^Repository repository revision] (when-some [object-id (.resolve repository revision)] (let [walk (RevWalk. repository)] (.setRetainBody walk true) (.parseCommit walk object-id)))) (defn- diff-entry->map [^DiffEntry de] ; NOTE: We convert /dev/null paths to nil, and convert copies into adds. (let [f (fn [p] (when-not (= p "/dev/null") p)) change-type (-> (.getChangeType de) str .toLowerCase keyword)] (if (= :copy change-type) {:score 0 :change-type :add :old-path nil :new-path (f (.getNewPath de))} {:score (.getScore de) :change-type change-type :old-path (f (.getOldPath de)) :new-path (f (.getNewPath de))}))) (defn- find-original-for-renamed [ustatus file] (->> ustatus (filter (fn [e] (= file (:new-path e)))) (map :old-path) (first))) ;; ================================================================================= (defn- as-repository ^Repository [git-or-repository] (if (instance? Repository git-or-repository) git-or-repository (.getRepository ^Git git-or-repository))) (defn user-info [git-or-repository] (let [repository (as-repository git-or-repository) config (.getConfig repository) name (or (.getString config "user" nil "name") "") email (or (.getString config "user" nil "email") "")] {:name PI:NAME:<NAME>END_PI :email email})) (defn set-user-info! [git-or-repository {new-name :name new-email :email :as user-info}] (assert (string? new-name)) (assert (string? new-email)) (when (not= user-info (user-info git-or-repository)) ;; The new user info differs from the stored info. ;; Update user info in the repository config. (let [repository (as-repository git-or-repository) config (.getConfig repository)] (.setString config "user" nil "name" new-name) (.setString config "user" nil "email" new-email) ;; Attempt to save the updated repository config. ;; The in-memory config retains the modifications even if this fails. (try (.save config) (catch IOException error (log/warn :msg "Failed to save updated user info to Git repository config." :exception error)))))) (defn- remote-name ^String [^Repository repository] (let [config (.getConfig repository) branch (.getBranch repository) branch-config (BranchConfig. config branch) remote-names (map #(.getName ^RemoteConfig %) (RemoteConfig/getAllRemoteConfigs config))] (or (.getRemote branch-config) (some (fn [remote-name] (when (.equalsIgnoreCase "origin" remote-name) remote-name)) remote-names) (first remote-names)))) (defn remote-info ([git-or-repository purpose] (let [repository (as-repository git-or-repository) remote-name (or (remote-name repository) "origin")] (remote-info repository purpose remote-name))) ([git-or-repository purpose ^String remote-name] (let [repository (as-repository git-or-repository) config (.getConfig repository) remote (RemoteConfig. config remote-name)] (when-some [^URIish uri-ish (first (case purpose :fetch (.getURIs remote) :push (concat (.getPushURIs remote) (.getURIs remote))))] {:name remote-name :scheme (if-some [scheme (.getScheme uri-ish)] (keyword scheme) :ssh) :host (.getHost uri-ish) :port (.getPort uri-ish) :path (.getPath uri-ish) :user (.getUser uri-ish) :pass (.getPass uri-ish)})))) (defn remote-uri ^URI [{:keys [scheme ^String host ^int port ^String path] :or {port -1} :as remote-info}] (let [^String user-info (if-some [user (not-empty (:user remote-info))] (if-some [pass (not-empty (:pass remote-info))] (str user ":" pass) user))] (URI. (name scheme) user-info host port path nil nil))) ;; Does the equivalent *config-wise* of: ;; > git config remote.origin.url url ;; > git push -u origin ;; Which is: ;; > git config remote.origin.url url ;; > git config remote.origin.fetch +refs/heads/*:refs/remotes/origin/* ;; > git config branch.master.remote origin ;; > git config branch.master.merge refs/heads/master ;; according to https://stackoverflow.com/questions/27823940/jgit-pushing-a-branch-and-add-upstream-u-option (defn config-remote! [^Git git url] (let [config (.. git getRepository getConfig)] (doto config (.setString "remote" "origin" "url" url) (.setString "remote" "origin" "fetch" "+refs/heads/*:refs/remotes/origin/*") (.setString "branch" "master" "remote" "origin") (.setString "branch" "master" "merge" "refs/heads/master") (.save)))) (defn worktree [^Git git] (.getWorkTree (.getRepository git))) (defn get-current-commit-ref [^Git git] (get-commit (.getRepository git) "HEAD")) (defn status [^Git git] (let [s (-> git (.status) (.call))] {:added (set (.getAdded s)) :changed (set (.getChanged s)) :conflicting (set (.getConflicting s)) :ignored-not-in-index (set (.getIgnoredNotInIndex s)) :missing (set (.getMissing s)) :modified (set (.getModified s)) :removed (set (.getRemoved s)) :uncommitted-changes (set (.getUncommittedChanges s)) :untracked (set (.getUntracked s)) :untracked-folders (set (.getUntrackedFolders s)) :conflicting-stage-state (apply hash-map (mapcat (fn [[k v]] [k (-> v str camel/->kebab-case keyword)]) (.getConflictingStageState s)))})) (defn- make-add-diff-entry [file-path] {:score 0 :change-type :add :old-path nil :new-path file-path}) (defn- make-delete-diff-entry [file-path] {:score 0 :change-type :delete :old-path file-path :new-path nil}) (defn- make-modify-diff-entry [file-path] {:score 0 :change-type :modify :old-path file-path :new-path file-path}) (defn- diff-entry-path ^String [{:keys [old-path new-path]}] (or new-path old-path)) (defn unified-status "Get the actual status by comparing contents on disk and HEAD. The state of the index (i.e. whether or not a file is staged) does not matter." ([^Git git] (unified-status git (status git))) ([^Git git git-status] (let [changed-paths (into #{} (mapcat git-status) [:added :changed :missing :modified :removed :untracked])] (if (empty? changed-paths) [] (let [repository (.getRepository git) rename-detector (doto (RenameDetector. repository) (.addAll (with-open [tree-walk (doto (TreeWalk. repository) (.addTree (.getTree ^RevCommit (get-commit repository "HEAD"))) (.addTree (FileTreeIterator. repository)) (.setFilter (PathFilterGroup/createFromStrings ^Collection changed-paths)) (.setRecursive true))] (DiffEntry/scan tree-walk))))] (try (let [diff-entries (.compute rename-detector nil)] (mapv diff-entry->map diff-entries)) (catch MissingObjectException _ ;; TODO: Workaround for what appears to be a bug inside JGit. ;; The rename detector failed for some reason. Report the status ;; without considering renames. This results in separate :added and ;; :deleted entries for unstaged renames, but will resolve into a ;; single :renamed entry once staged. (sort-by diff-entry-path (concat (map make-add-diff-entry (concat (:added git-status) (:untracked git-status))) (map make-modify-diff-entry (concat (:changed git-status) (:modified git-status))) (map make-delete-diff-entry (concat (:missing git-status) (:removed git-status)))))))))))) (defn file ^java.io.File [^Git git file-path] (io/file (str (worktree git) "/" file-path))) (defn show-file (^bytes [^Git git name] (show-file git name "HEAD")) (^bytes [^Git git name ref] (let [repo (.getRepository git)] (with-open [rw (RevWalk. repo)] (let [last-commit-id (.resolve repo ref) commit (.parseCommit rw last-commit-id) tree (.getTree commit)] (with-open [tw (TreeWalk. repo)] (.addTree tw tree) (.setRecursive tw true) (.setFilter tw (PathFilter/create name)) (.next tw) (let [id (.getObjectId tw 0)] (when (not= (ObjectId/zeroId) id) (let [loader (.open repo id)] (.getBytes loader)))))))))) (defn locked-files "Returns a set of all files in the repository that could cause major operations on the work tree to fail due to permissions issues or file locks from external processes. Does not include ignored files or files below the .git directory." [^Git git] (let [locked-files (volatile! (transient #{})) repository (.getRepository git) work-directory-path (.toPath (.getWorkTree repository)) dot-git-directory-path (.toPath (.getDirectory repository)) {dirs true files false} (->> (.. git status call getIgnoredNotInIndex) (map #(.resolve work-directory-path ^String %)) (group-by #(.isDirectory (.toFile ^Path %)))) ignored-directory-paths (set dirs) ignored-file-paths (set files)] (Files/walkFileTree work-directory-path (proxy [SimpleFileVisitor] [] (preVisitDirectory [^Path directory-path _attrs] (if (contains? ignored-directory-paths directory-path) FileVisitResult/SKIP_SUBTREE FileVisitResult/CONTINUE)) (visitFile [^Path file-path _attrs] (when (and (not (.startsWith file-path dot-git-directory-path)) (not (contains? ignored-file-paths file-path))) (let [file (.toFile file-path)] (when (fs/locked-file? file) (vswap! locked-files conj! file)))) FileVisitResult/CONTINUE) (visitFileFailed [^Path file-path _attrs] (vswap! locked-files conj! (.toFile file-path)) FileVisitResult/CONTINUE))) (persistent! (deref locked-files)))) (defn locked-files-error-message [locked-files] (str/join "\n" (concat ["The following project files are locked or in use by another process:"] (map #(str "\u00A0\u00A0\u2022\u00A0" %) ; " * " (NO-BREAK SPACE, NO-BREAK SPACE, BULLET, NO-BREAK SPACE) (sort locked-files)) ["" "Please ensure they are writable and quit other applications that reference files in the project before trying again."]))) (defn ensure-gitignore-configured! "When supplied a non-nil Git instance, ensures the repository has a .gitignore file that ignores our .internal and build output directories. Returns true if a change was made to the .gitignore file or a new .gitignore was created." [^Git git] (if (nil? git) false (let [gitignore-file (file git ".gitignore") ^String old-gitignore-text (when (.exists gitignore-file) (slurp gitignore-file :encoding "UTF-8")) old-gitignore-entries (some-> old-gitignore-text str/split-lines) old-gitignore-entries-set (into #{} (remove str/blank?) old-gitignore-entries) line-separator (text-util/guess-line-separator old-gitignore-text)] (if (empty? old-gitignore-entries-set) (do (spit gitignore-file (str/join line-separator default-gitignore-entries) :encoding "UTF-8") true) (let [new-gitignore-entries (into old-gitignore-entries (remove (fn [required-entry] (or (contains? old-gitignore-entries-set required-entry) (contains? old-gitignore-entries-set (fs/without-leading-slash required-entry))))) required-gitignore-entries)] (if (= old-gitignore-entries new-gitignore-entries) false (do (spit gitignore-file (str/join line-separator new-gitignore-entries) :encoding "UTF-8") true))))))) (defn internal-files-are-tracked? "Returns true if the supplied Git instance is non-nil and we detect any tracked files under the .internal or build directories. This means a commit was made with an improperly configured .gitignore, and will likely cause issues during sync with collaborators." [^Git git] (if (nil? git) false (let [repo (.getRepository git)] (with-open [rw (RevWalk. repo)] (let [commit-id (.resolve repo "HEAD") commit (.parseCommit rw commit-id) tree (.getTree commit) ^Collection path-prefixes [".internal/" "build/"]] (with-open [tw (TreeWalk. repo)] (.addTree tw tree) (.setRecursive tw true) (.setFilter tw (PathFilterGroup/createFromStrings path-prefixes)) (.next tw))))))) (defn clone! "Clone a repository into the specified directory." [^CredentialsProvider creds ^String remote-url ^File directory ^ProgressMonitor progress-monitor] (try (with-open [_ (.call (doto (Git/cloneRepository) (.setCredentialsProvider creds) (.setProgressMonitor progress-monitor) (.setURI remote-url) (.setDirectory directory)))] nil) (catch Exception e ;; The .call method throws an exception if the operation was cancelled. ;; Sadly it appears there is not a specific exception type for that, so ;; we silence any exceptions if the operation was cancelled. (when-not (.isCancelled progress-monitor) (throw e))))) (defn- make-transport-config-callback ^TransportConfigCallback [^String ssh-session-password] {:pre [(and (string? ssh-session-password) (not (empty? ssh-session-password)))]} (let [ssh-session-factory (proxy [JschConfigSessionFactory] [] (configure [_host session] (.setPassword ^Session session ssh-session-password)))] (reify TransportConfigCallback (configure [_this transport] (.setSshSessionFactory ^SshTransport transport ssh-session-factory))))) (defn make-credentials-provider ^CredentialsProvider [credentials] (let [^String username (or (:username credentials) "") ^String password (or (:password credentials) "")] (UsernamePasswordCredentialsProvider. username password))) (defn- configure-transport-command! ^TransportCommand [^TransportCommand command purpose {:keys [encrypted-credentials ^int timeout-seconds] :as _opts :or {timeout-seconds -1}}] ;; Taking GitHub as an example, clones made over the https:// protocol ;; authenticate with a username & password in order to push changes. You can ;; also make a Personal Access Token on GitHub to use in place of a password. ;; ;; Clones made over the git:// protocol can only pull, not push. The files are ;; transferred unencrypted. ;; ;; Clones made over the ssh:// protocol use public key authentication. You ;; must generate a public / private key pair and upload the public key to your ;; GitHub account. The private key is loaded from the `.ssh` directory in the ;; HOME folder. It will look for files named `identity`, `id_rsa` and `id_dsa` ;; and it should "just work". However, if a passphrase was used to create the ;; keys, we need to override createDefaultJSch in a subclassed instance of the ;; JschConfigSessionFactory class in order to associate the passphrase with a ;; key file. We do not currently do this here. ;; ;; Most of this information was gathered from here: ;; https://www.codeaffine.com/2014/12/09/jgit-authentication/ (case (:scheme (remote-info (.getRepository command) purpose)) :https (let [credentials (git-credentials/decrypt-credentials encrypted-credentials) credentials-provider (make-credentials-provider credentials)] (.setCredentialsProvider command credentials-provider)) :ssh (let [credentials (git-credentials/decrypt-credentials encrypted-credentials)] (when-some [ssh-session-password (not-empty (:ssh-session-password credentials))] (let [transport-config-callback (make-transport-config-callback ssh-session-password)] (.setTransportConfigCallback command transport-config-callback)))) nil) (cond-> command (pos? timeout-seconds) (.setTimeout timeout-seconds))) (defn pull! [^Git git opts] (-> (.pull git) (configure-transport-command! :fetch opts) (.call))) (defn- make-batching-progress-monitor ^BatchingProgressMonitor [weights-by-task cancelled-atom on-progress!] (let [^double sum-weight (reduce + 0.0 (vals weights-by-task)) normalized-weights-by-task (into {} (map (fn [[task ^double weight]] [task (/ weight sum-weight)])) weights-by-task) progress-by-task (atom (into {} (map #(vector % 0)) (keys weights-by-task))) set-progress (fn [task percent] (swap! progress-by-task assoc task percent)) current-progress (fn [] (reduce + 0.0 (keep (fn [[task ^long percent]] (when-some [^double weight (normalized-weights-by-task task)] (* percent weight 0.01))) @progress-by-task)))] (proxy [BatchingProgressMonitor] [] (onUpdate ([taskName workCurr]) ([taskName workCurr workTotal percentDone] (set-progress taskName percentDone) (on-progress! (current-progress)))) (onEndTask ([taskName workCurr]) ([taskName workCurr workTotal percentDone])) (isCancelled [] (boolean (some-> cancelled-atom deref)))))) (def ^:private ^:const push-tasks ;; TODO: Tweak these weights. {"Finding sources" 1 "Writing objects" 1 "remote: Updating references" 1}) (defn- configure-push-command! ^PushCommand [^PushCommand command {:keys [dry-run on-progress] :as _opts}] (cond-> command dry-run (.setDryRun true) (some? on-progress) (.setProgressMonitor (make-batching-progress-monitor push-tasks nil on-progress)))) (defn push! [^Git git opts] (-> (.push git) (configure-push-command! opts) (configure-transport-command! :push opts) (.call))) (defn make-add-change [file-path] {:change-type :add :old-path nil :new-path file-path}) (defn make-delete-change [file-path] {:change-type :delete :old-path file-path :new-path nil}) (defn make-modify-change [file-path] {:change-type :modify :old-path file-path :new-path file-path}) (defn make-rename-change [old-path new-path] {:change-type :rename :old-path old-path :new-path new-path}) (defn change-path [{:keys [old-path new-path]}] (or new-path old-path)) (defn stage-change! [^Git git {:keys [change-type old-path new-path]}] (case change-type (:add :modify) (-> git .add (.addFilepattern new-path) .call) :delete (-> git .rm (.addFilepattern old-path) (.setCached true) .call) :rename (do (-> git .rm (.addFilepattern old-path) (.setCached true) .call) (-> git .add (.addFilepattern new-path) .call)))) (defn unstage-change! [^Git git {:keys [change-type old-path new-path]}] (case change-type (:add :modify) (-> git .reset (.addPath new-path) .call) :delete (-> git .reset (.addPath old-path) .call) :rename (-> git .reset (.addPath old-path) (.addPath new-path) .call))) (defn- find-case-changes [added-paths removed-paths] (into {} (keep (fn [^String added-path] (some (fn [^String removed-path] (when (.equalsIgnoreCase added-path removed-path) [added-path removed-path])) removed-paths))) added-paths)) (defn- perform-case-changes! [^Git git case-changes] ;; In case we fail to perform a case change, attempt to undo the successfully ;; performed case changes before throwing. (let [performed-case-changes-atom (atom [])] (try (doseq [[new-path old-path] case-changes] (let [new-file (file git new-path) old-file (file git old-path)] (fs/move-file! old-file new-file) (swap! performed-case-changes-atom conj [new-file old-file]))) (catch Throwable error ;; Attempt to undo the performed case changes before throwing. (doseq [[new-file old-file] (rseq @performed-case-changes-atom)] (fs/move-file! new-file old-file {:fail :silently})) (throw error))))) (defn- undo-case-changes! [^Git git case-changes] (perform-case-changes! git (map reverse case-changes))) (defn revert-to-revision! "High-level revert. Resets the working directory to the state it would have after a clean checkout of the specified start-ref. Performs the equivalent of git reset --hard git clean --force -d" [^Git git ^RevCommit start-ref] ;; On case-insensitive file systems, we must manually revert case changes. ;; Otherwise the new-cased files will be removed during the clean call. (when-not fs/case-sensitive? (let [{:keys [missing untracked]} (status git) case-changes (find-case-changes untracked missing)] (undo-case-changes! git case-changes))) (-> (.reset git) (.setMode ResetCommand$ResetType/HARD) (.setRef (.name start-ref)) (.call)) (-> (.clean git) (.setCleanDirectories true) (.call))) (defn- revert-case-changes! "Finds and reverts any case changes in the supplied git status. Returns a map of the case changes that were reverted." [^Git git {:keys [added changed missing removed untracked] :as _status}] ;; If we're on a case-insensitive file system, we revert case-changes before ;; stashing. The case-changes will be restored when we apply the stash. (let [case-changes (find-case-changes (set/union added untracked) (set/union removed missing))] (when (seq case-changes) ;; Unstage everything so that we can safely undo the case changes. ;; This is fine, because we will stage everything before stashing. (when-some [staged-paths (not-empty (set/union added changed removed))] (let [reset-command (.reset git)] (doseq [path staged-paths] (.addPath reset-command path)) (.call reset-command))) ;; Undo case-changes. (undo-case-changes! git case-changes)) case-changes)) (defn- stage-removals! [^Git git status pred] (when-some [removed-paths (not-empty (into #{} (filter pred) (:missing status)))] (let [rm-command (.rm git)] (.setCached rm-command true) (doseq [path removed-paths] (.addFilepattern rm-command path)) (.call rm-command) nil))) (defn- stage-additions! [^Git git status pred] (when-some [changed-paths (not-empty (into #{} (filter pred) (concat (:modified status) (:untracked status))))] (let [add-command (.add git)] (doseq [path changed-paths] (.addFilepattern add-command path)) (.call add-command) nil))) (defn stage-all! "Stage all unstaged changes in the specified Git repo." [^Git git] (let [status (status git) include? (constantly true)] (stage-removals! git status include?) (stage-additions! git status include?))) (defn stash! "High-level stash. Before stashing, stages all changes. We do this because stashes internally treat untracked files differently from tracked files. Normally untracked files are not stashed at all, but even when using the setIncludeUntracked flag, untracked files are dealt with separately from tracked files. When later applied, a conflict among the tracked files will abort the stash apply command before the untracked files are restored. For our purposes, we want a unified set of conflicts among all the tracked and untracked files. Before stashing, we also revert any case-changes if we're running on a case-insensitive file system. We will reapply the case-changes when the stash is applied. If we do not do this, we will lose any remote changes to case- changed files when applying the stash. Returns nil if there was nothing to stash, or a map with the stash ref and the set of file paths that were staged at the time the stash was made." [^Git git] (let [pre-stash-status (status git) reverted-case-changes (when-not fs/case-sensitive? (revert-case-changes! git pre-stash-status))] (stage-all! git) (when-some [stash-ref (-> git .stashCreate .call)] {:ref stash-ref :case-changes reverted-case-changes :staged (set/union (:added pre-stash-status) (:changed pre-stash-status) (:removed pre-stash-status))}))) (defn stash-apply! [^Git git stash-info] (when (some? stash-info) ;; Apply the stash. The apply-result will be either an ObjectId returned ;; from (.call StashApplyCommand) or a StashApplyFailureException if thrown. (let [apply-result (try (-> (.stashApply git) (.setStashRef (.name ^RevCommit (:ref stash-info))) (.call)) (catch StashApplyFailureException error error)) status-after-apply (status git) paths-with-conflicts (set (keys (:conflicting-stage-state status-after-apply))) paths-to-unstage (set/difference (set/union (:added status-after-apply) (:changed status-after-apply) (:removed status-after-apply)) paths-with-conflicts)] ;; Unstage everything that is without conflict. Later we will stage ;; everything that was staged at the time the stash was made. (when-some [staged-paths (not-empty paths-to-unstage)] (let [reset-command (.reset git)] (doseq [path staged-paths] (.addPath reset-command path)) (.call reset-command))) ;; Restore any reverted case changes. Skip over case changes that involve ;; conflicting paths just in case. (let [case-changes (remove (partial some paths-with-conflicts) (:case-changes stash-info))] (perform-case-changes! git case-changes)) ;; Restore staged files state from before the stash. (when (empty? paths-with-conflicts) (let [status (status git) was-staged? (:staged stash-info)] (stage-removals! git status was-staged?) (stage-additions! git status was-staged?))) (if (instance? Throwable apply-result) (throw apply-result) apply-result)))) (defn stash-drop! [^Git git stash-info] (let [stash-ref ^RevCommit (:ref stash-info) stashes (map-indexed vector (.call (.stashList git))) matching-stash (first (filter #(= stash-ref (second %)) stashes))] (when matching-stash (-> (.stashDrop git) (.setStashRef (first matching-stash)) (.call))))) (defn commit [^Git git ^String message] (-> (.commit git) (.setMessage message) (.call))) ;; "High level" revert ;; * Changed files are checked out ;; * New files are removed ;; * Deleted files are checked out ;; NOTE: Not to be confused with "git revert" (defn revert [^Git git files] (let [us (unified-status git) renames (into {} (keep (fn [new-path] (when-some [old-path (find-original-for-renamed us new-path)] [new-path old-path]))) files) others (into [] (remove renames) files)] ;; Revert renames first. (doseq [[new-path old-path] renames] (-> git .rm (.addFilepattern new-path) (.setCached true) .call) (fs/delete-file! (file git new-path)) (-> git .reset (.addPath old-path) .call) (-> git .checkout (.addPath old-path) .call)) ;; Revert others. (when (seq others) (let [co (-> git (.checkout)) reset (-> git (.reset) (.setRef "HEAD"))] (doseq [path others] (.addPath co path) (.addPath reset path)) (.call reset) (.call co)) ;; Delete all untracked files in "others" as a last step ;; JGit doesn't support this operation with RmCommand (let [s (status git)] (doseq [path others] (when (contains? (:untracked s) path) (fs/delete-file! (file git path) {:missing :fail}))))))) (def ^:private ^:const clone-tasks {"remote: Finding sources" 1 "Receiving objects" 88 "Resolving deltas" 10 "Updating references" 1}) (defn make-clone-monitor ^ProgressMonitor [^ProgressBar progress-bar cancelled-atom] (make-batching-progress-monitor clone-tasks cancelled-atom (fn [progress] (ui/run-later (.setProgress progress-bar progress))))) ;; ================================================================================= (defn selection-diffable? [selection] (and (= 1 (count selection)) (let [change-type (:change-type (first selection))] (and (keyword? change-type) (not= :add change-type) (not= :delete change-type))))) (defn selection-diff-data [git selection] (let [change (first selection) old-path (or (:old-path change) (:new-path change) ) new-path (or (:new-path change) (:old-path change) ) old (String. ^bytes (show-file git old-path)) new (slurp (file git new-path)) binary? (not-every? text-util/text-char? new)] {:binary? binary? :new new :new-path new-path :old old :old-path old-path})) (defn init [^String path] (-> (Git/init) (.setDirectory (File. path)) (.call)))
[ { "context": "sitions.auto-dubstep\n (:use [overtone.live]))\n\n;; Dan Stowells' Dubstep Synth:\n;; SClang version:\n;;\n;;s.waitFor", "end": 90, "score": 0.9982900619506836, "start": 78, "tag": "NAME", "value": "Dan Stowells" } ]
src/overtone/examples/compositions/auto_dubstep.clj
ABaldwinHunter/overtone
3,870
(ns overtone.examples.compositions.auto-dubstep (:use [overtone.live])) ;; Dan Stowells' Dubstep Synth: ;; SClang version: ;; ;;s.waitForBoot{Ndef(\a).play;Ndef(\a, ;;{ ;;var trig, freq, notes, wob, sweep, kickenv, kick, snare, swr, syn, bpm, x; ;;x = MouseX.kr(1, 4); ;; ;; ;;// START HERE: ;; ;;bpm = 120; ;; ;;notes = [40, 41, 28, 28, 28, 28, 27, 25, 35, 78]; ;; ;;trig = Impulse.kr(bpm/120); ;;freq = Demand.kr(trig, 0, Dxrand(notes, inf)).lag(0.25).midicps; ;;swr = Demand.kr(trig, 0, Dseq([1, 6, 6, 2, 1, 2, 4, 8, 3, 3], inf)); ;;sweep = LFTri.ar(swr).exprange(40, 3000); ;; ;; ;;// Here we make the wobble bass: ;;wob = Saw.ar(freq * [0.99, 1.01]).sum; ;;wob = LPF.ar(wob, sweep); ;;wob = Normalizer.ar(wob) * 0.8; ;;wob = wob + BPF.ar(wob, 1500, 2); ;;wob = wob + GVerb.ar(wob, 9, 0.7, 0.7, mul: 0.2); ;; ;; ;;// Here we add some drums: ;;kickenv = Decay.ar(T2A.ar(Demand.kr(Impulse.kr(bpm / 30),0,Dseq([1,0,0,0,0,0,1,0, 1,0,0,1,0,0,0,0],inf))),0.7); ;;kick = SinOsc.ar(40+(kickenv*kickenv*kickenv*200),0,7*kickenv).clip2; ;;snare = 3*PinkNoise.ar(1!2)*Decay.ar(Impulse.ar(bpm / 240, 0.5),[0.4,2],[1,0.05]).sum; ;;snare = (snare + BPF.ar(4*snare,2000)).clip2; ;; ;;// This line actually outputs the sound: ;;(wob + kick + snare).clip2; ;; ;;})} ;; ;; Directly translated to Overtone: (demo 60 (let [bpm 120 ;; create pool of notes as seed for random base line sequence notes [40 41 28 28 28 27 25 35 78] ;; create an impulse trigger firing once per bar trig (impulse:kr (/ bpm 120)) ;; create frequency generator for a randomly picked note freq (midicps (lag (demand trig 0 (dxrand notes INF)) 0.25)) ;; switch note durations swr (demand trig 0 (dseq [1 6 6 2 1 2 4 8 3 3] INF)) ;; create a sweep curve for filter below sweep (lin-exp (lf-tri swr) -1 1 40 3000) ;; create a slightly detuned stereo sawtooth oscillator wob (mix (saw (* freq [0.99 1.01]))) ;; apply low pass filter using sweep curve to control cutoff freq wob (lpf wob sweep) ;; normalize to 80% volume wob (* 0.8 (normalizer wob)) ;; apply band pass filter with resonance at 5kHz wob (+ wob (bpf wob 1500 2)) ;; mix in 20% reverb wob (+ wob (* 0.2 (g-verb wob 9 0.7 0.7))) ;; create impulse generator from given drum pattern kickenv (decay (t2a (demand (impulse:kr (/ bpm 30)) 0 (dseq [1 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0] INF))) 0.7) ;; use modulated sine wave oscillator kick (* (* kickenv 7) (sin-osc (+ 40 (* kickenv kickenv kickenv 200)))) ;; clip at max volume to create distortion kick (clip2 kick 1) ;; snare is just using gated & over-amplified pink noise snare (* 3 (pink-noise) (apply + (* (decay (impulse (/ bpm 240) 0.5) [0.4 2]) [1 0.05]))) ;; send through band pass filter with peak @ 2kHz snare (+ snare (bpf (* 4 snare) 2000)) ;; also clip at max vol to distort snare (clip2 snare 1)] ;; mixdown & clip (clip2 (+ wob kick snare) 1))) ;;(stop)
118266
(ns overtone.examples.compositions.auto-dubstep (:use [overtone.live])) ;; <NAME>' Dubstep Synth: ;; SClang version: ;; ;;s.waitForBoot{Ndef(\a).play;Ndef(\a, ;;{ ;;var trig, freq, notes, wob, sweep, kickenv, kick, snare, swr, syn, bpm, x; ;;x = MouseX.kr(1, 4); ;; ;; ;;// START HERE: ;; ;;bpm = 120; ;; ;;notes = [40, 41, 28, 28, 28, 28, 27, 25, 35, 78]; ;; ;;trig = Impulse.kr(bpm/120); ;;freq = Demand.kr(trig, 0, Dxrand(notes, inf)).lag(0.25).midicps; ;;swr = Demand.kr(trig, 0, Dseq([1, 6, 6, 2, 1, 2, 4, 8, 3, 3], inf)); ;;sweep = LFTri.ar(swr).exprange(40, 3000); ;; ;; ;;// Here we make the wobble bass: ;;wob = Saw.ar(freq * [0.99, 1.01]).sum; ;;wob = LPF.ar(wob, sweep); ;;wob = Normalizer.ar(wob) * 0.8; ;;wob = wob + BPF.ar(wob, 1500, 2); ;;wob = wob + GVerb.ar(wob, 9, 0.7, 0.7, mul: 0.2); ;; ;; ;;// Here we add some drums: ;;kickenv = Decay.ar(T2A.ar(Demand.kr(Impulse.kr(bpm / 30),0,Dseq([1,0,0,0,0,0,1,0, 1,0,0,1,0,0,0,0],inf))),0.7); ;;kick = SinOsc.ar(40+(kickenv*kickenv*kickenv*200),0,7*kickenv).clip2; ;;snare = 3*PinkNoise.ar(1!2)*Decay.ar(Impulse.ar(bpm / 240, 0.5),[0.4,2],[1,0.05]).sum; ;;snare = (snare + BPF.ar(4*snare,2000)).clip2; ;; ;;// This line actually outputs the sound: ;;(wob + kick + snare).clip2; ;; ;;})} ;; ;; Directly translated to Overtone: (demo 60 (let [bpm 120 ;; create pool of notes as seed for random base line sequence notes [40 41 28 28 28 27 25 35 78] ;; create an impulse trigger firing once per bar trig (impulse:kr (/ bpm 120)) ;; create frequency generator for a randomly picked note freq (midicps (lag (demand trig 0 (dxrand notes INF)) 0.25)) ;; switch note durations swr (demand trig 0 (dseq [1 6 6 2 1 2 4 8 3 3] INF)) ;; create a sweep curve for filter below sweep (lin-exp (lf-tri swr) -1 1 40 3000) ;; create a slightly detuned stereo sawtooth oscillator wob (mix (saw (* freq [0.99 1.01]))) ;; apply low pass filter using sweep curve to control cutoff freq wob (lpf wob sweep) ;; normalize to 80% volume wob (* 0.8 (normalizer wob)) ;; apply band pass filter with resonance at 5kHz wob (+ wob (bpf wob 1500 2)) ;; mix in 20% reverb wob (+ wob (* 0.2 (g-verb wob 9 0.7 0.7))) ;; create impulse generator from given drum pattern kickenv (decay (t2a (demand (impulse:kr (/ bpm 30)) 0 (dseq [1 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0] INF))) 0.7) ;; use modulated sine wave oscillator kick (* (* kickenv 7) (sin-osc (+ 40 (* kickenv kickenv kickenv 200)))) ;; clip at max volume to create distortion kick (clip2 kick 1) ;; snare is just using gated & over-amplified pink noise snare (* 3 (pink-noise) (apply + (* (decay (impulse (/ bpm 240) 0.5) [0.4 2]) [1 0.05]))) ;; send through band pass filter with peak @ 2kHz snare (+ snare (bpf (* 4 snare) 2000)) ;; also clip at max vol to distort snare (clip2 snare 1)] ;; mixdown & clip (clip2 (+ wob kick snare) 1))) ;;(stop)
true
(ns overtone.examples.compositions.auto-dubstep (:use [overtone.live])) ;; PI:NAME:<NAME>END_PI' Dubstep Synth: ;; SClang version: ;; ;;s.waitForBoot{Ndef(\a).play;Ndef(\a, ;;{ ;;var trig, freq, notes, wob, sweep, kickenv, kick, snare, swr, syn, bpm, x; ;;x = MouseX.kr(1, 4); ;; ;; ;;// START HERE: ;; ;;bpm = 120; ;; ;;notes = [40, 41, 28, 28, 28, 28, 27, 25, 35, 78]; ;; ;;trig = Impulse.kr(bpm/120); ;;freq = Demand.kr(trig, 0, Dxrand(notes, inf)).lag(0.25).midicps; ;;swr = Demand.kr(trig, 0, Dseq([1, 6, 6, 2, 1, 2, 4, 8, 3, 3], inf)); ;;sweep = LFTri.ar(swr).exprange(40, 3000); ;; ;; ;;// Here we make the wobble bass: ;;wob = Saw.ar(freq * [0.99, 1.01]).sum; ;;wob = LPF.ar(wob, sweep); ;;wob = Normalizer.ar(wob) * 0.8; ;;wob = wob + BPF.ar(wob, 1500, 2); ;;wob = wob + GVerb.ar(wob, 9, 0.7, 0.7, mul: 0.2); ;; ;; ;;// Here we add some drums: ;;kickenv = Decay.ar(T2A.ar(Demand.kr(Impulse.kr(bpm / 30),0,Dseq([1,0,0,0,0,0,1,0, 1,0,0,1,0,0,0,0],inf))),0.7); ;;kick = SinOsc.ar(40+(kickenv*kickenv*kickenv*200),0,7*kickenv).clip2; ;;snare = 3*PinkNoise.ar(1!2)*Decay.ar(Impulse.ar(bpm / 240, 0.5),[0.4,2],[1,0.05]).sum; ;;snare = (snare + BPF.ar(4*snare,2000)).clip2; ;; ;;// This line actually outputs the sound: ;;(wob + kick + snare).clip2; ;; ;;})} ;; ;; Directly translated to Overtone: (demo 60 (let [bpm 120 ;; create pool of notes as seed for random base line sequence notes [40 41 28 28 28 27 25 35 78] ;; create an impulse trigger firing once per bar trig (impulse:kr (/ bpm 120)) ;; create frequency generator for a randomly picked note freq (midicps (lag (demand trig 0 (dxrand notes INF)) 0.25)) ;; switch note durations swr (demand trig 0 (dseq [1 6 6 2 1 2 4 8 3 3] INF)) ;; create a sweep curve for filter below sweep (lin-exp (lf-tri swr) -1 1 40 3000) ;; create a slightly detuned stereo sawtooth oscillator wob (mix (saw (* freq [0.99 1.01]))) ;; apply low pass filter using sweep curve to control cutoff freq wob (lpf wob sweep) ;; normalize to 80% volume wob (* 0.8 (normalizer wob)) ;; apply band pass filter with resonance at 5kHz wob (+ wob (bpf wob 1500 2)) ;; mix in 20% reverb wob (+ wob (* 0.2 (g-verb wob 9 0.7 0.7))) ;; create impulse generator from given drum pattern kickenv (decay (t2a (demand (impulse:kr (/ bpm 30)) 0 (dseq [1 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0] INF))) 0.7) ;; use modulated sine wave oscillator kick (* (* kickenv 7) (sin-osc (+ 40 (* kickenv kickenv kickenv 200)))) ;; clip at max volume to create distortion kick (clip2 kick 1) ;; snare is just using gated & over-amplified pink noise snare (* 3 (pink-noise) (apply + (* (decay (impulse (/ bpm 240) 0.5) [0.4 2]) [1 0.05]))) ;; send through band pass filter with peak @ 2kHz snare (+ snare (bpf (* 4 snare) 2000)) ;; also clip at max vol to distort snare (clip2 snare 1)] ;; mixdown & clip (clip2 (+ wob kick snare) 1))) ;;(stop)
[ { "context": "om/foaf/0.1/\"}\n {:foaf/firstName \"Pablo\"\n :foaf/surname \"Picasso\"})\n ", "end": 2458, "score": 0.9985531568527222, "start": 2453, "tag": "NAME", "value": "Pablo" }, { "context": "irstName \"Pablo\"\n :foaf/surname \"Picasso\"})\n (select-keys (first docs)\n ", "end": 2500, "score": 0.965019941329956, "start": 2493, "tag": "NAME", "value": "Picasso" }, { "context": " :where [[e :foaf/firstName \"Pablo\"]]})))))\n\n (t/testing \"can read tx log\"\n ", "end": 4748, "score": 0.9791853427886963, "start": 4743, "tag": "NAME", "value": "Pablo" } ]
crux-test/test/crux/kafka_test.clj
Antonelli712/crux
0
(ns crux.kafka-test (:require [clojure.test :as t] [clojure.java.io :as io] [crux.io :as cio] [clojure.tools.logging :as log] [crux.db :as db] [crux.index :as idx] [crux.fixtures.kafka :as fk] [crux.object-store :as os] [crux.lru :as lru] [crux.fixtures.kv-only :as fkv :refer [*kv*]] [crux.kafka :as k] [crux.query :as q] [crux.rdf :as rdf] [crux.sparql :as sparql] [crux.api :as api] [crux.tx :as tx]) (:import java.time.Duration java.util.List org.apache.kafka.clients.producer.ProducerRecord org.apache.kafka.clients.consumer.ConsumerRecord org.apache.kafka.common.TopicPartition java.io.Closeable)) (t/use-fixtures :once fk/with-embedded-kafka-cluster) (t/use-fixtures :each fk/with-kafka-client fkv/with-memdb fkv/with-kv-store) (defn- consumer-record->value [^ConsumerRecord record] (.value record)) (t/deftest test-can-produce-and-consume-message-using-embedded-kafka (let [topic "test-can-produce-and-consume-message-using-embedded-kafka-topic" person {:crux.db/id "foo"} partitions [(TopicPartition. topic 0)]] (k/create-topic fk/*admin-client* topic 1 1 {}) @(.send fk/*producer* (ProducerRecord. topic person)) (.assign fk/*consumer* partitions) (let [records (.poll fk/*consumer* (Duration/ofMillis 10000))] (t/is (= 1 (count (seq records)))) (t/is (= person (first (map consumer-record->value records))))))) (t/deftest test-can-transact-entities (let [tx-topic "test-can-transact-entities-tx" doc-topic "test-can-transact-entities-doc" tx-ops (rdf/->tx-ops (rdf/ntriples "crux/example-data-artists.nt")) tx-log (k/->KafkaTxLog fk/*producer* tx-topic doc-topic {}) indexer (tx/->KvIndexer *kv* tx-log (os/->KvObjectStore *kv*) nil)] (k/create-topic fk/*admin-client* tx-topic 1 1 k/tx-topic-config) (k/create-topic fk/*admin-client* doc-topic 1 1 k/doc-topic-config) (k/subscribe-from-stored-offsets indexer fk/*consumer* [doc-topic]) (db/submit-tx tx-log tx-ops) (let [docs (map consumer-record->value (.poll fk/*consumer* (Duration/ofMillis 10000)))] (t/is (= 7 (count docs))) (t/is (= (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/"} {:foaf/firstName "Pablo" :foaf/surname "Picasso"}) (select-keys (first docs) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/"} [:foaf/firstName :foaf/surname]))))))) (t/deftest test-can-transact-and-query-entities (let [tx-topic "test-can-transact-and-query-entities-tx" doc-topic "test-can-transact-and-query-entities-doc" tx-ops (rdf/->tx-ops (rdf/ntriples "crux/picasso.nt")) tx-log (k/->KafkaTxLog fk/*producer* tx-topic doc-topic {"bootstrap.servers" fk/*kafka-bootstrap-servers*}) indexer (tx/->KvIndexer *kv* tx-log (os/->KvObjectStore *kv*) nil) object-store (os/->CachedObjectStore (lru/new-cache os/default-doc-cache-size) (os/->KvObjectStore *kv*)) node (reify crux.api.ICruxAPI (db [this] (q/db *kv* object-store (cio/next-monotonic-date) (cio/next-monotonic-date))))] (k/create-topic fk/*admin-client* tx-topic 1 1 k/tx-topic-config) (k/create-topic fk/*admin-client* doc-topic 1 1 k/doc-topic-config) (k/subscribe-from-stored-offsets indexer fk/*consumer* [tx-topic doc-topic]) (t/testing "transacting and indexing" (let [{:crux.tx/keys [tx-id tx-time]} @(db/submit-tx tx-log tx-ops) consume-opts {:indexer indexer :consumer fk/*consumer* :pending-txs-state (atom []) :tx-topic tx-topic :doc-topic doc-topic}] (t/is (= {:txs 1 :docs 3} (k/consume-and-index-entities consume-opts))) (t/is (empty? (.poll fk/*consumer* (Duration/ofMillis 1000)))) (t/testing "restoring to stored offsets" (.seekToBeginning fk/*consumer* (.assignment fk/*consumer*)) (k/seek-to-stored-offsets indexer fk/*consumer* (.assignment fk/*consumer*)) (t/is (empty? (.poll fk/*consumer* (Duration/ofMillis 1000))))) (t/testing "querying transacted data" (t/is (= #{[:http://example.org/Picasso]} (q/q (api/db node) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/"} '{:find [e] :where [[e :foaf/firstName "Pablo"]]}))))) (t/testing "can read tx log" (with-open [consumer (db/new-tx-log-context tx-log)] (let [log (db/tx-log tx-log consumer nil)] (t/is (not (realized? log))) ;; Cannot compare the tx-ops as they contain blank nodes ;; with random ids. (t/is (= {:crux.tx/tx-time tx-time :crux.tx/tx-id tx-id} (dissoc (first log) :crux.tx.event/tx-events))) (t/is (= 1 (count log))) (t/is (= 3 (count (:crux.tx.event/tx-events (first log)))))))))))) (t/deftest test-can-process-compacted-documents ;; when doing a evict a tombstone document will be written to ;; replace the original document. The original document will be then ;; removed once kafka compacts it away. (let [tx-topic "test-can-process-compacted-documents-tx" doc-topic "test-can-process-compacted-documents-doc" tx-ops (rdf/->tx-ops (rdf/ntriples "crux/picasso.nt")) tx-log (k/->KafkaTxLog fk/*producer* tx-topic doc-topic {"bootstrap.servers" fk/*kafka-bootstrap-servers*}) object-store (os/->CachedObjectStore (lru/new-cache os/default-doc-cache-size) (os/->KvObjectStore *kv*)) indexer (tx/->KvIndexer *kv* tx-log (os/->KvObjectStore *kv*) nil) node (reify crux.api.ICruxAPI (db [this] (q/db *kv* object-store (cio/next-monotonic-date) (cio/next-monotonic-date))))] (k/create-topic fk/*admin-client* tx-topic 1 1 k/tx-topic-config) (k/create-topic fk/*admin-client* doc-topic 1 1 k/doc-topic-config) (k/subscribe-from-stored-offsets indexer fk/*consumer* [tx-topic doc-topic]) (t/testing "transacting and indexing" (let [consume-opts {:indexer indexer :consumer fk/*consumer* :pending-txs-state (atom []) :tx-topic tx-topic :doc-topic doc-topic} evicted-doc {:crux.db/id :to-be-eviceted :personal "private"} non-evicted-doc {:crux.db/id :not-evicted :personal "private"} evicted-doc-hash (do @(db/submit-tx tx-log [[:crux.tx/put evicted-doc] [:crux.tx/put non-evicted-doc]]) (k/consume-and-index-entities consume-opts) (while (not= {:txs 0 :docs 0} (k/consume-and-index-entities consume-opts))) (:crux.db/content-hash (q/entity-tx (api/db node) (:crux.db/id evicted-doc)))) after-evict-doc {:crux.db/id :after-evict :personal "private"} {:crux.tx/keys [tx-id tx-time]} (do @(db/submit-tx tx-log [[:crux.tx/evict (:crux.db/id evicted-doc)]]) @(db/submit-tx tx-log [[:crux.tx/put after-evict-doc]]))] (while (not= {:txs 0 :docs 0} (k/consume-and-index-entities consume-opts))) (t/testing "querying transacted data" (t/is (= non-evicted-doc (q/entity (api/db node) (:crux.db/id non-evicted-doc)))) (t/is (nil? (q/entity (api/db node) (:crux.db/id evicted-doc)))) (t/is (= after-evict-doc (q/entity (api/db node) (:crux.db/id after-evict-doc))))) (t/testing "re-indexing the same transactions after doc compaction" (binding [fk/*consumer-options* {"max.poll.records" "1"}] (fk/with-kafka-client (fn [] (fkv/with-kv-store (fn [] (let [object-store (os/->KvObjectStore *kv*) indexer (tx/->KvIndexer *kv* tx-log object-store nil) consume-opts {:indexer indexer :consumer fk/*consumer* :pending-txs-state (atom []) :tx-topic tx-topic :doc-topic doc-topic}] (k/subscribe-from-stored-offsets indexer fk/*consumer* [tx-topic doc-topic]) (k/consume-and-index-entities consume-opts) (t/is (= {:txs 0, :docs 1} (k/consume-and-index-entities consume-opts))) ;; delete the object that would have been compacted away (db/delete-objects object-store [evicted-doc-hash]) (while (not= {:txs 0 :docs 0} (k/consume-and-index-entities consume-opts))) (t/is (empty? (.poll fk/*consumer* (Duration/ofMillis 1000)))) (t/testing "querying transacted data" (t/is (= non-evicted-doc (q/entity (api/db node) (:crux.db/id non-evicted-doc)))) (t/is (nil? (q/entity (api/db node) (:crux.db/id evicted-doc)))) (t/is (= after-evict-doc (q/entity (api/db node) (:crux.db/id after-evict-doc))))))))))))))))
107490
(ns crux.kafka-test (:require [clojure.test :as t] [clojure.java.io :as io] [crux.io :as cio] [clojure.tools.logging :as log] [crux.db :as db] [crux.index :as idx] [crux.fixtures.kafka :as fk] [crux.object-store :as os] [crux.lru :as lru] [crux.fixtures.kv-only :as fkv :refer [*kv*]] [crux.kafka :as k] [crux.query :as q] [crux.rdf :as rdf] [crux.sparql :as sparql] [crux.api :as api] [crux.tx :as tx]) (:import java.time.Duration java.util.List org.apache.kafka.clients.producer.ProducerRecord org.apache.kafka.clients.consumer.ConsumerRecord org.apache.kafka.common.TopicPartition java.io.Closeable)) (t/use-fixtures :once fk/with-embedded-kafka-cluster) (t/use-fixtures :each fk/with-kafka-client fkv/with-memdb fkv/with-kv-store) (defn- consumer-record->value [^ConsumerRecord record] (.value record)) (t/deftest test-can-produce-and-consume-message-using-embedded-kafka (let [topic "test-can-produce-and-consume-message-using-embedded-kafka-topic" person {:crux.db/id "foo"} partitions [(TopicPartition. topic 0)]] (k/create-topic fk/*admin-client* topic 1 1 {}) @(.send fk/*producer* (ProducerRecord. topic person)) (.assign fk/*consumer* partitions) (let [records (.poll fk/*consumer* (Duration/ofMillis 10000))] (t/is (= 1 (count (seq records)))) (t/is (= person (first (map consumer-record->value records))))))) (t/deftest test-can-transact-entities (let [tx-topic "test-can-transact-entities-tx" doc-topic "test-can-transact-entities-doc" tx-ops (rdf/->tx-ops (rdf/ntriples "crux/example-data-artists.nt")) tx-log (k/->KafkaTxLog fk/*producer* tx-topic doc-topic {}) indexer (tx/->KvIndexer *kv* tx-log (os/->KvObjectStore *kv*) nil)] (k/create-topic fk/*admin-client* tx-topic 1 1 k/tx-topic-config) (k/create-topic fk/*admin-client* doc-topic 1 1 k/doc-topic-config) (k/subscribe-from-stored-offsets indexer fk/*consumer* [doc-topic]) (db/submit-tx tx-log tx-ops) (let [docs (map consumer-record->value (.poll fk/*consumer* (Duration/ofMillis 10000)))] (t/is (= 7 (count docs))) (t/is (= (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/"} {:foaf/firstName "<NAME>" :foaf/surname "<NAME>"}) (select-keys (first docs) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/"} [:foaf/firstName :foaf/surname]))))))) (t/deftest test-can-transact-and-query-entities (let [tx-topic "test-can-transact-and-query-entities-tx" doc-topic "test-can-transact-and-query-entities-doc" tx-ops (rdf/->tx-ops (rdf/ntriples "crux/picasso.nt")) tx-log (k/->KafkaTxLog fk/*producer* tx-topic doc-topic {"bootstrap.servers" fk/*kafka-bootstrap-servers*}) indexer (tx/->KvIndexer *kv* tx-log (os/->KvObjectStore *kv*) nil) object-store (os/->CachedObjectStore (lru/new-cache os/default-doc-cache-size) (os/->KvObjectStore *kv*)) node (reify crux.api.ICruxAPI (db [this] (q/db *kv* object-store (cio/next-monotonic-date) (cio/next-monotonic-date))))] (k/create-topic fk/*admin-client* tx-topic 1 1 k/tx-topic-config) (k/create-topic fk/*admin-client* doc-topic 1 1 k/doc-topic-config) (k/subscribe-from-stored-offsets indexer fk/*consumer* [tx-topic doc-topic]) (t/testing "transacting and indexing" (let [{:crux.tx/keys [tx-id tx-time]} @(db/submit-tx tx-log tx-ops) consume-opts {:indexer indexer :consumer fk/*consumer* :pending-txs-state (atom []) :tx-topic tx-topic :doc-topic doc-topic}] (t/is (= {:txs 1 :docs 3} (k/consume-and-index-entities consume-opts))) (t/is (empty? (.poll fk/*consumer* (Duration/ofMillis 1000)))) (t/testing "restoring to stored offsets" (.seekToBeginning fk/*consumer* (.assignment fk/*consumer*)) (k/seek-to-stored-offsets indexer fk/*consumer* (.assignment fk/*consumer*)) (t/is (empty? (.poll fk/*consumer* (Duration/ofMillis 1000))))) (t/testing "querying transacted data" (t/is (= #{[:http://example.org/Picasso]} (q/q (api/db node) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/"} '{:find [e] :where [[e :foaf/firstName "<NAME>"]]}))))) (t/testing "can read tx log" (with-open [consumer (db/new-tx-log-context tx-log)] (let [log (db/tx-log tx-log consumer nil)] (t/is (not (realized? log))) ;; Cannot compare the tx-ops as they contain blank nodes ;; with random ids. (t/is (= {:crux.tx/tx-time tx-time :crux.tx/tx-id tx-id} (dissoc (first log) :crux.tx.event/tx-events))) (t/is (= 1 (count log))) (t/is (= 3 (count (:crux.tx.event/tx-events (first log)))))))))))) (t/deftest test-can-process-compacted-documents ;; when doing a evict a tombstone document will be written to ;; replace the original document. The original document will be then ;; removed once kafka compacts it away. (let [tx-topic "test-can-process-compacted-documents-tx" doc-topic "test-can-process-compacted-documents-doc" tx-ops (rdf/->tx-ops (rdf/ntriples "crux/picasso.nt")) tx-log (k/->KafkaTxLog fk/*producer* tx-topic doc-topic {"bootstrap.servers" fk/*kafka-bootstrap-servers*}) object-store (os/->CachedObjectStore (lru/new-cache os/default-doc-cache-size) (os/->KvObjectStore *kv*)) indexer (tx/->KvIndexer *kv* tx-log (os/->KvObjectStore *kv*) nil) node (reify crux.api.ICruxAPI (db [this] (q/db *kv* object-store (cio/next-monotonic-date) (cio/next-monotonic-date))))] (k/create-topic fk/*admin-client* tx-topic 1 1 k/tx-topic-config) (k/create-topic fk/*admin-client* doc-topic 1 1 k/doc-topic-config) (k/subscribe-from-stored-offsets indexer fk/*consumer* [tx-topic doc-topic]) (t/testing "transacting and indexing" (let [consume-opts {:indexer indexer :consumer fk/*consumer* :pending-txs-state (atom []) :tx-topic tx-topic :doc-topic doc-topic} evicted-doc {:crux.db/id :to-be-eviceted :personal "private"} non-evicted-doc {:crux.db/id :not-evicted :personal "private"} evicted-doc-hash (do @(db/submit-tx tx-log [[:crux.tx/put evicted-doc] [:crux.tx/put non-evicted-doc]]) (k/consume-and-index-entities consume-opts) (while (not= {:txs 0 :docs 0} (k/consume-and-index-entities consume-opts))) (:crux.db/content-hash (q/entity-tx (api/db node) (:crux.db/id evicted-doc)))) after-evict-doc {:crux.db/id :after-evict :personal "private"} {:crux.tx/keys [tx-id tx-time]} (do @(db/submit-tx tx-log [[:crux.tx/evict (:crux.db/id evicted-doc)]]) @(db/submit-tx tx-log [[:crux.tx/put after-evict-doc]]))] (while (not= {:txs 0 :docs 0} (k/consume-and-index-entities consume-opts))) (t/testing "querying transacted data" (t/is (= non-evicted-doc (q/entity (api/db node) (:crux.db/id non-evicted-doc)))) (t/is (nil? (q/entity (api/db node) (:crux.db/id evicted-doc)))) (t/is (= after-evict-doc (q/entity (api/db node) (:crux.db/id after-evict-doc))))) (t/testing "re-indexing the same transactions after doc compaction" (binding [fk/*consumer-options* {"max.poll.records" "1"}] (fk/with-kafka-client (fn [] (fkv/with-kv-store (fn [] (let [object-store (os/->KvObjectStore *kv*) indexer (tx/->KvIndexer *kv* tx-log object-store nil) consume-opts {:indexer indexer :consumer fk/*consumer* :pending-txs-state (atom []) :tx-topic tx-topic :doc-topic doc-topic}] (k/subscribe-from-stored-offsets indexer fk/*consumer* [tx-topic doc-topic]) (k/consume-and-index-entities consume-opts) (t/is (= {:txs 0, :docs 1} (k/consume-and-index-entities consume-opts))) ;; delete the object that would have been compacted away (db/delete-objects object-store [evicted-doc-hash]) (while (not= {:txs 0 :docs 0} (k/consume-and-index-entities consume-opts))) (t/is (empty? (.poll fk/*consumer* (Duration/ofMillis 1000)))) (t/testing "querying transacted data" (t/is (= non-evicted-doc (q/entity (api/db node) (:crux.db/id non-evicted-doc)))) (t/is (nil? (q/entity (api/db node) (:crux.db/id evicted-doc)))) (t/is (= after-evict-doc (q/entity (api/db node) (:crux.db/id after-evict-doc))))))))))))))))
true
(ns crux.kafka-test (:require [clojure.test :as t] [clojure.java.io :as io] [crux.io :as cio] [clojure.tools.logging :as log] [crux.db :as db] [crux.index :as idx] [crux.fixtures.kafka :as fk] [crux.object-store :as os] [crux.lru :as lru] [crux.fixtures.kv-only :as fkv :refer [*kv*]] [crux.kafka :as k] [crux.query :as q] [crux.rdf :as rdf] [crux.sparql :as sparql] [crux.api :as api] [crux.tx :as tx]) (:import java.time.Duration java.util.List org.apache.kafka.clients.producer.ProducerRecord org.apache.kafka.clients.consumer.ConsumerRecord org.apache.kafka.common.TopicPartition java.io.Closeable)) (t/use-fixtures :once fk/with-embedded-kafka-cluster) (t/use-fixtures :each fk/with-kafka-client fkv/with-memdb fkv/with-kv-store) (defn- consumer-record->value [^ConsumerRecord record] (.value record)) (t/deftest test-can-produce-and-consume-message-using-embedded-kafka (let [topic "test-can-produce-and-consume-message-using-embedded-kafka-topic" person {:crux.db/id "foo"} partitions [(TopicPartition. topic 0)]] (k/create-topic fk/*admin-client* topic 1 1 {}) @(.send fk/*producer* (ProducerRecord. topic person)) (.assign fk/*consumer* partitions) (let [records (.poll fk/*consumer* (Duration/ofMillis 10000))] (t/is (= 1 (count (seq records)))) (t/is (= person (first (map consumer-record->value records))))))) (t/deftest test-can-transact-entities (let [tx-topic "test-can-transact-entities-tx" doc-topic "test-can-transact-entities-doc" tx-ops (rdf/->tx-ops (rdf/ntriples "crux/example-data-artists.nt")) tx-log (k/->KafkaTxLog fk/*producer* tx-topic doc-topic {}) indexer (tx/->KvIndexer *kv* tx-log (os/->KvObjectStore *kv*) nil)] (k/create-topic fk/*admin-client* tx-topic 1 1 k/tx-topic-config) (k/create-topic fk/*admin-client* doc-topic 1 1 k/doc-topic-config) (k/subscribe-from-stored-offsets indexer fk/*consumer* [doc-topic]) (db/submit-tx tx-log tx-ops) (let [docs (map consumer-record->value (.poll fk/*consumer* (Duration/ofMillis 10000)))] (t/is (= 7 (count docs))) (t/is (= (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/"} {:foaf/firstName "PI:NAME:<NAME>END_PI" :foaf/surname "PI:NAME:<NAME>END_PI"}) (select-keys (first docs) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/"} [:foaf/firstName :foaf/surname]))))))) (t/deftest test-can-transact-and-query-entities (let [tx-topic "test-can-transact-and-query-entities-tx" doc-topic "test-can-transact-and-query-entities-doc" tx-ops (rdf/->tx-ops (rdf/ntriples "crux/picasso.nt")) tx-log (k/->KafkaTxLog fk/*producer* tx-topic doc-topic {"bootstrap.servers" fk/*kafka-bootstrap-servers*}) indexer (tx/->KvIndexer *kv* tx-log (os/->KvObjectStore *kv*) nil) object-store (os/->CachedObjectStore (lru/new-cache os/default-doc-cache-size) (os/->KvObjectStore *kv*)) node (reify crux.api.ICruxAPI (db [this] (q/db *kv* object-store (cio/next-monotonic-date) (cio/next-monotonic-date))))] (k/create-topic fk/*admin-client* tx-topic 1 1 k/tx-topic-config) (k/create-topic fk/*admin-client* doc-topic 1 1 k/doc-topic-config) (k/subscribe-from-stored-offsets indexer fk/*consumer* [tx-topic doc-topic]) (t/testing "transacting and indexing" (let [{:crux.tx/keys [tx-id tx-time]} @(db/submit-tx tx-log tx-ops) consume-opts {:indexer indexer :consumer fk/*consumer* :pending-txs-state (atom []) :tx-topic tx-topic :doc-topic doc-topic}] (t/is (= {:txs 1 :docs 3} (k/consume-and-index-entities consume-opts))) (t/is (empty? (.poll fk/*consumer* (Duration/ofMillis 1000)))) (t/testing "restoring to stored offsets" (.seekToBeginning fk/*consumer* (.assignment fk/*consumer*)) (k/seek-to-stored-offsets indexer fk/*consumer* (.assignment fk/*consumer*)) (t/is (empty? (.poll fk/*consumer* (Duration/ofMillis 1000))))) (t/testing "querying transacted data" (t/is (= #{[:http://example.org/Picasso]} (q/q (api/db node) (rdf/with-prefix {:foaf "http://xmlns.com/foaf/0.1/"} '{:find [e] :where [[e :foaf/firstName "PI:NAME:<NAME>END_PI"]]}))))) (t/testing "can read tx log" (with-open [consumer (db/new-tx-log-context tx-log)] (let [log (db/tx-log tx-log consumer nil)] (t/is (not (realized? log))) ;; Cannot compare the tx-ops as they contain blank nodes ;; with random ids. (t/is (= {:crux.tx/tx-time tx-time :crux.tx/tx-id tx-id} (dissoc (first log) :crux.tx.event/tx-events))) (t/is (= 1 (count log))) (t/is (= 3 (count (:crux.tx.event/tx-events (first log)))))))))))) (t/deftest test-can-process-compacted-documents ;; when doing a evict a tombstone document will be written to ;; replace the original document. The original document will be then ;; removed once kafka compacts it away. (let [tx-topic "test-can-process-compacted-documents-tx" doc-topic "test-can-process-compacted-documents-doc" tx-ops (rdf/->tx-ops (rdf/ntriples "crux/picasso.nt")) tx-log (k/->KafkaTxLog fk/*producer* tx-topic doc-topic {"bootstrap.servers" fk/*kafka-bootstrap-servers*}) object-store (os/->CachedObjectStore (lru/new-cache os/default-doc-cache-size) (os/->KvObjectStore *kv*)) indexer (tx/->KvIndexer *kv* tx-log (os/->KvObjectStore *kv*) nil) node (reify crux.api.ICruxAPI (db [this] (q/db *kv* object-store (cio/next-monotonic-date) (cio/next-monotonic-date))))] (k/create-topic fk/*admin-client* tx-topic 1 1 k/tx-topic-config) (k/create-topic fk/*admin-client* doc-topic 1 1 k/doc-topic-config) (k/subscribe-from-stored-offsets indexer fk/*consumer* [tx-topic doc-topic]) (t/testing "transacting and indexing" (let [consume-opts {:indexer indexer :consumer fk/*consumer* :pending-txs-state (atom []) :tx-topic tx-topic :doc-topic doc-topic} evicted-doc {:crux.db/id :to-be-eviceted :personal "private"} non-evicted-doc {:crux.db/id :not-evicted :personal "private"} evicted-doc-hash (do @(db/submit-tx tx-log [[:crux.tx/put evicted-doc] [:crux.tx/put non-evicted-doc]]) (k/consume-and-index-entities consume-opts) (while (not= {:txs 0 :docs 0} (k/consume-and-index-entities consume-opts))) (:crux.db/content-hash (q/entity-tx (api/db node) (:crux.db/id evicted-doc)))) after-evict-doc {:crux.db/id :after-evict :personal "private"} {:crux.tx/keys [tx-id tx-time]} (do @(db/submit-tx tx-log [[:crux.tx/evict (:crux.db/id evicted-doc)]]) @(db/submit-tx tx-log [[:crux.tx/put after-evict-doc]]))] (while (not= {:txs 0 :docs 0} (k/consume-and-index-entities consume-opts))) (t/testing "querying transacted data" (t/is (= non-evicted-doc (q/entity (api/db node) (:crux.db/id non-evicted-doc)))) (t/is (nil? (q/entity (api/db node) (:crux.db/id evicted-doc)))) (t/is (= after-evict-doc (q/entity (api/db node) (:crux.db/id after-evict-doc))))) (t/testing "re-indexing the same transactions after doc compaction" (binding [fk/*consumer-options* {"max.poll.records" "1"}] (fk/with-kafka-client (fn [] (fkv/with-kv-store (fn [] (let [object-store (os/->KvObjectStore *kv*) indexer (tx/->KvIndexer *kv* tx-log object-store nil) consume-opts {:indexer indexer :consumer fk/*consumer* :pending-txs-state (atom []) :tx-topic tx-topic :doc-topic doc-topic}] (k/subscribe-from-stored-offsets indexer fk/*consumer* [tx-topic doc-topic]) (k/consume-and-index-entities consume-opts) (t/is (= {:txs 0, :docs 1} (k/consume-and-index-entities consume-opts))) ;; delete the object that would have been compacted away (db/delete-objects object-store [evicted-doc-hash]) (while (not= {:txs 0 :docs 0} (k/consume-and-index-entities consume-opts))) (t/is (empty? (.poll fk/*consumer* (Duration/ofMillis 1000)))) (t/testing "querying transacted data" (t/is (= non-evicted-doc (q/entity (api/db node) (:crux.db/id non-evicted-doc)))) (t/is (nil? (q/entity (api/db node) (:crux.db/id evicted-doc)))) (t/is (= after-evict-doc (q/entity (api/db node) (:crux.db/id after-evict-doc))))))))))))))))
[ { "context": "nterface to TweeboParser\n;;;;\n;;;; @copyright 2020 Dennis Drown et l'Université du Québec à Montréal\n;;;; -------", "end": 390, "score": 0.9998774528503418, "start": 378, "tag": "NAME", "value": "Dennis Drown" } ]
apps/say_sila/priv/fnode/say/src/say/tweebo.clj
dendrown/say_sila
0
;;;; ------------------------------------------------------------------------- ;;;; ;;;; _/_/_/ _/_/_/ _/ _/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/ _/ _/ _/_/_/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/ ;;;; ;;;; Say-Sila interface to TweeboParser ;;;; ;;;; @copyright 2020 Dennis Drown et l'Université du Québec à Montréal ;;;; ------------------------------------------------------------------------- (ns say.tweebo (:require [say.genie :refer :all] [say.resources] [say.config :as cfg] [say.label :as lbl] [say.log :as log] [say.resources :as rsc] [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.java.shell :as sh] [clojure.pprint :refer [pp]] [clojure.string :as str] [me.raynes.fs :as fs])) ;;; -------------------------------------------------------------------------- (set! *warn-on-reflection* true) (def ^:const Subdir-Tweet-Cut 3) ; (Final) digits from tweet ID (def ^:const Subdir-User-Cut 2) ; Letters from user ID (def ^:const Subdir-Unknown-Cut 4) ; Characters from unrecognized ID (def ^:const Tweebo-Exec "/usr/local/bin/tweebo") (defonce Runner (agent 0)) (defonce Tweebo-Dir (rsc/get-dir (cfg/?? :tweebo :dir) "tweebo")) ;;; -------------------------------------------------------------------------- (defn get-subdir "Returns the subdirectory (under the tweebo resource directory) where a user's tweet or profile analysis should go." [fname] ;; The text ID is the simple filename; remove any extension. (let [id (first (str/split fname #"\." 2)) cnt (count id)] (cond ;; Use the last digits of a tweet ID. (The initial digits don't vary enough.) (str/starts-with? id lbl/Tweet-Tag) (subs id (- cnt Subdir-Tweet-Cut)) ;; Use the first part of the account name for user profiles (str/starts-with? id lbl/Profile-Tag) (let [skip (count lbl/Profile-Tag) cut (min cnt (+ skip Subdir-User-Cut))] (str/upper-case (subs id skip cut))) :else (str "_" (subs id 0 Subdir-Unknown-Cut))))) ;;; -------------------------------------------------------------------------- (defn get-fpath "Returns the filepath associated with a endency tree for later use." ([tid] (get-fpath tid nil)) ([tid kind] (rsc/get-fpath Tweebo-Dir (get-subdir tid) (if kind (str tid "." (name kind)) tid)))) ;;; -------------------------------------------------------------------------- (defn- go-prepare "Prepares a TweeboParser (predicted) dependency tree for later use." [runs tid text] (let [ipath (get-fpath tid) opath (get-fpath tid :predict) ofile (io/file opath)] (if (.exists ofile) (do ;(log/debug "Tweebo parse exists:" opath) runs) (do (log/fmt-debug "Parsing dependencies: cnt[~a] fp[~a]" runs ipath) (.mkdirs (.getParentFile ofile)) (spit ipath text) (let [{:keys [err exit out]} (sh/sh Tweebo-Exec ipath)] (if (zero? exit) ;; TweeboParser seems to be writing normal output to stderr (do (log/fmt-debug "Tweebo on ~a: ~a" tid (last (str/split err #"\n"))) (inc runs)) ;; Errors are also going to stderr (do (log/fmt-error "Tweebo failure on ~a: ~a: rc[~a]" tid err exit) runs))))))) ;;; -------------------------------------------------------------------------- (defn prepare "Prepares a TweeboParser (predicted) dependency tree for later use." [tid text] (send-off Runner go-prepare tid text)) ;;; -------------------------------------------------------------------------- (defn predict "Prepares a TweeboParser (predicted) dependency tree for later use." [tid] (when-let [lines (try (with-open [rdr (io/reader (get-fpath tid :predict))] (doall (csv/read-csv rdr :separator \tab))) (catch Exception ex ;(log/error "Cannot read predicted dependencies:" tid) nil))] ;; There's a pesky empty line at the end of the Tweebo output (remove #(= % [""]) lines))) ;;; -------------------------------------------------------------------------- (defn get-terms "Returns a lazy sequence of tbe terms, as parsed by Tweebo, for a given tweet ID. If the tweet has not previously been parsed by Tweebo, the function returns an empty list." [tid] ;; Filter out the nil from the final empty line in the the tweebo output (map second (predict tid))) ;;; -------------------------------------------------------------------------- (defn get-pos "Returns a lazy sequence of part of speech tags, as parsed by Tweebo, for a given tweet ID. If the tweet has not previously been parsed by Tweebo, the function returns an empty list." [tid] ;; Filter out the nil from the final empty line in the the tweebo output (map #(nth % 3) (predict tid))) ;;; -------------------------------------------------------------------------- (defn get-pos-terms "For a given tweet ID, returns a lazy sequence of vectors, each containing the part of speech tag of a term and the term itself. If the tweet has not previously been parsed by Tweebo, the function returns an empty list." [tid & opts] ;; Filter out the nil from the final empty line in the the tweebo output (when-let [parse (predict tid)] (let [pairs (map (fn [[_ term _ pos]] [pos term]) parse)] (if (some #{:side-by-side} opts) (reduce (fn [[poss terms] [p t]] [(conj poss p) (conj terms t)]) [[] []] pairs) pairs)))) ;;; -------------------------------------------------------------------------- (defn wait "Blocks execution until all pernding Tweebo Parser requests have completed." [] (log/fmt-debug "Syncing Tweebo requests: cnt[~a]" @Runner) (when-not (await-for 30000 Runner) (recur))) ;;; -------------------------------------------------------------------------- (defn print-tree "Prints a tree structure to show dependencies." [{:keys [etokens pos-tags tid] :or {etokens (repeat nil)}}] (letfn [; ----------------------------------------------------------------- (combine [[etok pos [ndx tok _ _ _ _ dep]]] ;; Take just the elements we need [ndx dep pos (if etok etok tok)]) ; ----------------------------------------------------------------- (child? [[_ dep _ _] pix] ;; Is the dependency the parent index (pix)? (= dep pix)) ; ----------------------------------------------------------------- (omit? [i] (or (nil? i) (child? i "-1"))) ; ----------------------------------------------------------------- (root? [i] (child? i "0")) ; ----------------------------------------------------------------- (proc [lvl finals? [pix _ pos parent] children] ;; With the short token lists, we always check all the children (let [[fins?-a fin?-z] (butlast-last finals?) branch (if fin?-z "└" "├") indent (if (zero? lvl) "" (apply str (map #(if % " " "│ ") fins?-a))) kids (filter #(child? % pix) children)] ;; Print the current node and recursively process its children (log/fmt! "~a~a── ~a (~a)\n" indent branch parent pos) (process (inc lvl) finals? kids children))) ; ----------------------------------------------------------------- (process [lvl finals? parents-az children] (let [[parents-a parent-z] (butlast-last parents-az)] ;; If there's only one parent, it'll be the last parent (when parent-z (run! #(proc lvl (conj finals? false) % children) parents-a) (proc lvl (conj finals? true) parent-z children))))] ;; Process the Tweebo parser output (let [parsed (map combine (zip etokens pos-tags (predict tid))) {roots true children false} (group-by root? (remove omit? parsed))] (println "•") (process 0 [] roots children) (println)))) ;;; -------------------------------------------------------------------------- (defn migrate! "Development function that copies Tweebo files from the legacy directory structure to the new one as defined in the configuration." [] (let [old-dir (rsc/get-dir "tweebo") old-fpath #(str old-dir "/" %) ignore #{".keep" "working_dir" "requote" "requote.l"}] (println "Migrating Tweebo files:") (println "* SRC:" old-dir) (println "* DST:" Tweebo-Dir) (println "Please press <ENTER>") (read-line) (doseq [o (.list (io/file old-dir))] (when-not (ignore o) (log/debug "Copying" o) (fs/copy+ (old-fpath o) (get-fpath o))))))
91178
;;;; ------------------------------------------------------------------------- ;;;; ;;;; _/_/_/ _/_/_/ _/ _/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/ _/ _/ _/_/_/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/ ;;;; ;;;; Say-Sila interface to TweeboParser ;;;; ;;;; @copyright 2020 <NAME> et l'Université du Québec à Montréal ;;;; ------------------------------------------------------------------------- (ns say.tweebo (:require [say.genie :refer :all] [say.resources] [say.config :as cfg] [say.label :as lbl] [say.log :as log] [say.resources :as rsc] [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.java.shell :as sh] [clojure.pprint :refer [pp]] [clojure.string :as str] [me.raynes.fs :as fs])) ;;; -------------------------------------------------------------------------- (set! *warn-on-reflection* true) (def ^:const Subdir-Tweet-Cut 3) ; (Final) digits from tweet ID (def ^:const Subdir-User-Cut 2) ; Letters from user ID (def ^:const Subdir-Unknown-Cut 4) ; Characters from unrecognized ID (def ^:const Tweebo-Exec "/usr/local/bin/tweebo") (defonce Runner (agent 0)) (defonce Tweebo-Dir (rsc/get-dir (cfg/?? :tweebo :dir) "tweebo")) ;;; -------------------------------------------------------------------------- (defn get-subdir "Returns the subdirectory (under the tweebo resource directory) where a user's tweet or profile analysis should go." [fname] ;; The text ID is the simple filename; remove any extension. (let [id (first (str/split fname #"\." 2)) cnt (count id)] (cond ;; Use the last digits of a tweet ID. (The initial digits don't vary enough.) (str/starts-with? id lbl/Tweet-Tag) (subs id (- cnt Subdir-Tweet-Cut)) ;; Use the first part of the account name for user profiles (str/starts-with? id lbl/Profile-Tag) (let [skip (count lbl/Profile-Tag) cut (min cnt (+ skip Subdir-User-Cut))] (str/upper-case (subs id skip cut))) :else (str "_" (subs id 0 Subdir-Unknown-Cut))))) ;;; -------------------------------------------------------------------------- (defn get-fpath "Returns the filepath associated with a endency tree for later use." ([tid] (get-fpath tid nil)) ([tid kind] (rsc/get-fpath Tweebo-Dir (get-subdir tid) (if kind (str tid "." (name kind)) tid)))) ;;; -------------------------------------------------------------------------- (defn- go-prepare "Prepares a TweeboParser (predicted) dependency tree for later use." [runs tid text] (let [ipath (get-fpath tid) opath (get-fpath tid :predict) ofile (io/file opath)] (if (.exists ofile) (do ;(log/debug "Tweebo parse exists:" opath) runs) (do (log/fmt-debug "Parsing dependencies: cnt[~a] fp[~a]" runs ipath) (.mkdirs (.getParentFile ofile)) (spit ipath text) (let [{:keys [err exit out]} (sh/sh Tweebo-Exec ipath)] (if (zero? exit) ;; TweeboParser seems to be writing normal output to stderr (do (log/fmt-debug "Tweebo on ~a: ~a" tid (last (str/split err #"\n"))) (inc runs)) ;; Errors are also going to stderr (do (log/fmt-error "Tweebo failure on ~a: ~a: rc[~a]" tid err exit) runs))))))) ;;; -------------------------------------------------------------------------- (defn prepare "Prepares a TweeboParser (predicted) dependency tree for later use." [tid text] (send-off Runner go-prepare tid text)) ;;; -------------------------------------------------------------------------- (defn predict "Prepares a TweeboParser (predicted) dependency tree for later use." [tid] (when-let [lines (try (with-open [rdr (io/reader (get-fpath tid :predict))] (doall (csv/read-csv rdr :separator \tab))) (catch Exception ex ;(log/error "Cannot read predicted dependencies:" tid) nil))] ;; There's a pesky empty line at the end of the Tweebo output (remove #(= % [""]) lines))) ;;; -------------------------------------------------------------------------- (defn get-terms "Returns a lazy sequence of tbe terms, as parsed by Tweebo, for a given tweet ID. If the tweet has not previously been parsed by Tweebo, the function returns an empty list." [tid] ;; Filter out the nil from the final empty line in the the tweebo output (map second (predict tid))) ;;; -------------------------------------------------------------------------- (defn get-pos "Returns a lazy sequence of part of speech tags, as parsed by Tweebo, for a given tweet ID. If the tweet has not previously been parsed by Tweebo, the function returns an empty list." [tid] ;; Filter out the nil from the final empty line in the the tweebo output (map #(nth % 3) (predict tid))) ;;; -------------------------------------------------------------------------- (defn get-pos-terms "For a given tweet ID, returns a lazy sequence of vectors, each containing the part of speech tag of a term and the term itself. If the tweet has not previously been parsed by Tweebo, the function returns an empty list." [tid & opts] ;; Filter out the nil from the final empty line in the the tweebo output (when-let [parse (predict tid)] (let [pairs (map (fn [[_ term _ pos]] [pos term]) parse)] (if (some #{:side-by-side} opts) (reduce (fn [[poss terms] [p t]] [(conj poss p) (conj terms t)]) [[] []] pairs) pairs)))) ;;; -------------------------------------------------------------------------- (defn wait "Blocks execution until all pernding Tweebo Parser requests have completed." [] (log/fmt-debug "Syncing Tweebo requests: cnt[~a]" @Runner) (when-not (await-for 30000 Runner) (recur))) ;;; -------------------------------------------------------------------------- (defn print-tree "Prints a tree structure to show dependencies." [{:keys [etokens pos-tags tid] :or {etokens (repeat nil)}}] (letfn [; ----------------------------------------------------------------- (combine [[etok pos [ndx tok _ _ _ _ dep]]] ;; Take just the elements we need [ndx dep pos (if etok etok tok)]) ; ----------------------------------------------------------------- (child? [[_ dep _ _] pix] ;; Is the dependency the parent index (pix)? (= dep pix)) ; ----------------------------------------------------------------- (omit? [i] (or (nil? i) (child? i "-1"))) ; ----------------------------------------------------------------- (root? [i] (child? i "0")) ; ----------------------------------------------------------------- (proc [lvl finals? [pix _ pos parent] children] ;; With the short token lists, we always check all the children (let [[fins?-a fin?-z] (butlast-last finals?) branch (if fin?-z "└" "├") indent (if (zero? lvl) "" (apply str (map #(if % " " "│ ") fins?-a))) kids (filter #(child? % pix) children)] ;; Print the current node and recursively process its children (log/fmt! "~a~a── ~a (~a)\n" indent branch parent pos) (process (inc lvl) finals? kids children))) ; ----------------------------------------------------------------- (process [lvl finals? parents-az children] (let [[parents-a parent-z] (butlast-last parents-az)] ;; If there's only one parent, it'll be the last parent (when parent-z (run! #(proc lvl (conj finals? false) % children) parents-a) (proc lvl (conj finals? true) parent-z children))))] ;; Process the Tweebo parser output (let [parsed (map combine (zip etokens pos-tags (predict tid))) {roots true children false} (group-by root? (remove omit? parsed))] (println "•") (process 0 [] roots children) (println)))) ;;; -------------------------------------------------------------------------- (defn migrate! "Development function that copies Tweebo files from the legacy directory structure to the new one as defined in the configuration." [] (let [old-dir (rsc/get-dir "tweebo") old-fpath #(str old-dir "/" %) ignore #{".keep" "working_dir" "requote" "requote.l"}] (println "Migrating Tweebo files:") (println "* SRC:" old-dir) (println "* DST:" Tweebo-Dir) (println "Please press <ENTER>") (read-line) (doseq [o (.list (io/file old-dir))] (when-not (ignore o) (log/debug "Copying" o) (fs/copy+ (old-fpath o) (get-fpath o))))))
true
;;;; ------------------------------------------------------------------------- ;;;; ;;;; _/_/_/ _/_/_/ _/ _/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/ _/ _/ _/_/_/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/ ;;;; ;;;; Say-Sila interface to TweeboParser ;;;; ;;;; @copyright 2020 PI:NAME:<NAME>END_PI et l'Université du Québec à Montréal ;;;; ------------------------------------------------------------------------- (ns say.tweebo (:require [say.genie :refer :all] [say.resources] [say.config :as cfg] [say.label :as lbl] [say.log :as log] [say.resources :as rsc] [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.java.shell :as sh] [clojure.pprint :refer [pp]] [clojure.string :as str] [me.raynes.fs :as fs])) ;;; -------------------------------------------------------------------------- (set! *warn-on-reflection* true) (def ^:const Subdir-Tweet-Cut 3) ; (Final) digits from tweet ID (def ^:const Subdir-User-Cut 2) ; Letters from user ID (def ^:const Subdir-Unknown-Cut 4) ; Characters from unrecognized ID (def ^:const Tweebo-Exec "/usr/local/bin/tweebo") (defonce Runner (agent 0)) (defonce Tweebo-Dir (rsc/get-dir (cfg/?? :tweebo :dir) "tweebo")) ;;; -------------------------------------------------------------------------- (defn get-subdir "Returns the subdirectory (under the tweebo resource directory) where a user's tweet or profile analysis should go." [fname] ;; The text ID is the simple filename; remove any extension. (let [id (first (str/split fname #"\." 2)) cnt (count id)] (cond ;; Use the last digits of a tweet ID. (The initial digits don't vary enough.) (str/starts-with? id lbl/Tweet-Tag) (subs id (- cnt Subdir-Tweet-Cut)) ;; Use the first part of the account name for user profiles (str/starts-with? id lbl/Profile-Tag) (let [skip (count lbl/Profile-Tag) cut (min cnt (+ skip Subdir-User-Cut))] (str/upper-case (subs id skip cut))) :else (str "_" (subs id 0 Subdir-Unknown-Cut))))) ;;; -------------------------------------------------------------------------- (defn get-fpath "Returns the filepath associated with a endency tree for later use." ([tid] (get-fpath tid nil)) ([tid kind] (rsc/get-fpath Tweebo-Dir (get-subdir tid) (if kind (str tid "." (name kind)) tid)))) ;;; -------------------------------------------------------------------------- (defn- go-prepare "Prepares a TweeboParser (predicted) dependency tree for later use." [runs tid text] (let [ipath (get-fpath tid) opath (get-fpath tid :predict) ofile (io/file opath)] (if (.exists ofile) (do ;(log/debug "Tweebo parse exists:" opath) runs) (do (log/fmt-debug "Parsing dependencies: cnt[~a] fp[~a]" runs ipath) (.mkdirs (.getParentFile ofile)) (spit ipath text) (let [{:keys [err exit out]} (sh/sh Tweebo-Exec ipath)] (if (zero? exit) ;; TweeboParser seems to be writing normal output to stderr (do (log/fmt-debug "Tweebo on ~a: ~a" tid (last (str/split err #"\n"))) (inc runs)) ;; Errors are also going to stderr (do (log/fmt-error "Tweebo failure on ~a: ~a: rc[~a]" tid err exit) runs))))))) ;;; -------------------------------------------------------------------------- (defn prepare "Prepares a TweeboParser (predicted) dependency tree for later use." [tid text] (send-off Runner go-prepare tid text)) ;;; -------------------------------------------------------------------------- (defn predict "Prepares a TweeboParser (predicted) dependency tree for later use." [tid] (when-let [lines (try (with-open [rdr (io/reader (get-fpath tid :predict))] (doall (csv/read-csv rdr :separator \tab))) (catch Exception ex ;(log/error "Cannot read predicted dependencies:" tid) nil))] ;; There's a pesky empty line at the end of the Tweebo output (remove #(= % [""]) lines))) ;;; -------------------------------------------------------------------------- (defn get-terms "Returns a lazy sequence of tbe terms, as parsed by Tweebo, for a given tweet ID. If the tweet has not previously been parsed by Tweebo, the function returns an empty list." [tid] ;; Filter out the nil from the final empty line in the the tweebo output (map second (predict tid))) ;;; -------------------------------------------------------------------------- (defn get-pos "Returns a lazy sequence of part of speech tags, as parsed by Tweebo, for a given tweet ID. If the tweet has not previously been parsed by Tweebo, the function returns an empty list." [tid] ;; Filter out the nil from the final empty line in the the tweebo output (map #(nth % 3) (predict tid))) ;;; -------------------------------------------------------------------------- (defn get-pos-terms "For a given tweet ID, returns a lazy sequence of vectors, each containing the part of speech tag of a term and the term itself. If the tweet has not previously been parsed by Tweebo, the function returns an empty list." [tid & opts] ;; Filter out the nil from the final empty line in the the tweebo output (when-let [parse (predict tid)] (let [pairs (map (fn [[_ term _ pos]] [pos term]) parse)] (if (some #{:side-by-side} opts) (reduce (fn [[poss terms] [p t]] [(conj poss p) (conj terms t)]) [[] []] pairs) pairs)))) ;;; -------------------------------------------------------------------------- (defn wait "Blocks execution until all pernding Tweebo Parser requests have completed." [] (log/fmt-debug "Syncing Tweebo requests: cnt[~a]" @Runner) (when-not (await-for 30000 Runner) (recur))) ;;; -------------------------------------------------------------------------- (defn print-tree "Prints a tree structure to show dependencies." [{:keys [etokens pos-tags tid] :or {etokens (repeat nil)}}] (letfn [; ----------------------------------------------------------------- (combine [[etok pos [ndx tok _ _ _ _ dep]]] ;; Take just the elements we need [ndx dep pos (if etok etok tok)]) ; ----------------------------------------------------------------- (child? [[_ dep _ _] pix] ;; Is the dependency the parent index (pix)? (= dep pix)) ; ----------------------------------------------------------------- (omit? [i] (or (nil? i) (child? i "-1"))) ; ----------------------------------------------------------------- (root? [i] (child? i "0")) ; ----------------------------------------------------------------- (proc [lvl finals? [pix _ pos parent] children] ;; With the short token lists, we always check all the children (let [[fins?-a fin?-z] (butlast-last finals?) branch (if fin?-z "└" "├") indent (if (zero? lvl) "" (apply str (map #(if % " " "│ ") fins?-a))) kids (filter #(child? % pix) children)] ;; Print the current node and recursively process its children (log/fmt! "~a~a── ~a (~a)\n" indent branch parent pos) (process (inc lvl) finals? kids children))) ; ----------------------------------------------------------------- (process [lvl finals? parents-az children] (let [[parents-a parent-z] (butlast-last parents-az)] ;; If there's only one parent, it'll be the last parent (when parent-z (run! #(proc lvl (conj finals? false) % children) parents-a) (proc lvl (conj finals? true) parent-z children))))] ;; Process the Tweebo parser output (let [parsed (map combine (zip etokens pos-tags (predict tid))) {roots true children false} (group-by root? (remove omit? parsed))] (println "•") (process 0 [] roots children) (println)))) ;;; -------------------------------------------------------------------------- (defn migrate! "Development function that copies Tweebo files from the legacy directory structure to the new one as defined in the configuration." [] (let [old-dir (rsc/get-dir "tweebo") old-fpath #(str old-dir "/" %) ignore #{".keep" "working_dir" "requote" "requote.l"}] (println "Migrating Tweebo files:") (println "* SRC:" old-dir) (println "* DST:" Tweebo-Dir) (println "Please press <ENTER>") (read-line) (doseq [o (.list (io/file old-dir))] (when-not (ignore o) (log/debug "Copying" o) (fs/copy+ (old-fpath o) (get-fpath o))))))
[ { "context": "put-wrapper\"}\n [:input {:type \"text\" :name \"username\"\n :placeholder \"Write your usernam", "end": 1963, "score": 0.9059932827949524, "start": 1955, "tag": "USERNAME", "value": "username" }, { "context": "\n [username, password]\n (when (and (= username \"admin\")\n (= password \"123123\"))\n {:usern", "end": 2716, "score": 0.9990608096122742, "start": 2711, "tag": "USERNAME", "value": "admin" }, { "context": "nd (= username \"admin\")\n (= password \"123123\"))\n {:username \"Admin\"}))\n\n;; A hanlder that s", "end": 2751, "score": 0.9993438720703125, "start": 2745, "tag": "PASSWORD", "value": "123123" }, { "context": " (= password \"123123\"))\n {:username \"Admin\"}))\n\n;; A hanlder that simply render the login pa", "end": 2776, "score": 0.9980384707450867, "start": 2771, "tag": "USERNAME", "value": "Admin" } ]
examples/website-ssl/src/website/handlers.clj
source-c/catacumba
212
(ns website.handlers (:require [clojure.java.io :as io] [hiccup.page :as hc] [catacumba.core :as ct] [catacumba.handlers :as hs] [catacumba.handlers.auth :as auth] [catacumba.http :as http])) ;; A function that renders the basic html layout ;; for all pages used in that application. (defn layout [content] (hc/html5 [:head [:meta {:charset "utf-8"}] [:title "Sample dummy website"] [:link {:href "/assets/styles.css" :type "text/css" :rel "stylesheet" :media "screen"}]] [:body content])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Home Page ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Shows a simple html page. It has different content for anonynmous ;; and logged users. (defn home-page [context] (-> (layout [:section {:class "home-page"} (if-let [user (:identity context)] [:div [:p (format "Welcome %s" (:username user))] [:p [:a {:href "/logout"} "logout"]]] [:div [:p "Welcome to the dummy website application."] [:p [:a {:href "/login"} "Login"]]])]) (http/ok {:content-type "text/html"}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Login page ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; A helper function for render login page, it used also for initial ;; rendering and render login page with errors on post requests. (defn- render-login-page ([] (render-login-page [])) ([errors] (layout [:section {:class "login-page"} [:p "Login"] (when (seq errors) [:div {:class "errors"} (for [e errors] [:div e])]) [:form {:action "" :method "post"} [:div {:class "input-wrapper"} [:input {:type "text" :name "username" :placeholder "Write your username here..."}]] [:div {:class "input-wrapper"} [:input {:type "password" :name "password" :placeholder "Write your password here..."}]] [:div {:class "input-wrapper"} [:input {:type "submit" :value "Submit"}]]]]))) ;; A simple function that has the responsability of authenticate the incomoning ;; credentials on login post request. In the current implementation it just ;; checks if a user and password matches to the builtin "user" representation, ;; but in your implementation this function may access to the database or any ;; other source for authenticate. This is just a example. (defn- authenticate [username, password] (when (and (= username "admin") (= password "123123")) {:username "Admin"})) ;; A hanlder that simply render the login page for GET requests. (defn login-page [context] (-> (render-login-page) (http/ok {:content-type "text/html"}))) ;; A handler that clears the session and redirect to the home page. (defn logout-page [context] (let [session (:session context)] (swap! session dissoc :identity) (http/found "/"))) ;; A handler that handles the POST requests for login page. (defn login-submit [context] (let [form-params (ct/get-formdata context) query-params (:query-params context) username (get form-params "username" "") password (get form-params "password" "")] (if (or (empty? username) (empty? password)) ;; Firstly validates the input, if required fields ;; are empty, render the login page html with ;; convenient error mesasage and return it. (http/ok (render-login-page ["The two fields are mandatory."]) {:content-type "text/html"}) ;; In case contrary, try validate the incoming ;; credentials, and in case of them validates ;; successful, update the session `:identity` key ;; with the authenticated user object. ;; In case contrary, return a login page ;; rendered with approapiate error message (if-let [user (authenticate username password)] (let [nexturl (get query-params "next" "/") session (:session context)] (swap! session assoc :identity user) (http/found nexturl)) (http/ok (render-login-page ["User or password are incorrect"]) {:content-type "text/html"})))))
20526
(ns website.handlers (:require [clojure.java.io :as io] [hiccup.page :as hc] [catacumba.core :as ct] [catacumba.handlers :as hs] [catacumba.handlers.auth :as auth] [catacumba.http :as http])) ;; A function that renders the basic html layout ;; for all pages used in that application. (defn layout [content] (hc/html5 [:head [:meta {:charset "utf-8"}] [:title "Sample dummy website"] [:link {:href "/assets/styles.css" :type "text/css" :rel "stylesheet" :media "screen"}]] [:body content])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Home Page ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Shows a simple html page. It has different content for anonynmous ;; and logged users. (defn home-page [context] (-> (layout [:section {:class "home-page"} (if-let [user (:identity context)] [:div [:p (format "Welcome %s" (:username user))] [:p [:a {:href "/logout"} "logout"]]] [:div [:p "Welcome to the dummy website application."] [:p [:a {:href "/login"} "Login"]]])]) (http/ok {:content-type "text/html"}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Login page ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; A helper function for render login page, it used also for initial ;; rendering and render login page with errors on post requests. (defn- render-login-page ([] (render-login-page [])) ([errors] (layout [:section {:class "login-page"} [:p "Login"] (when (seq errors) [:div {:class "errors"} (for [e errors] [:div e])]) [:form {:action "" :method "post"} [:div {:class "input-wrapper"} [:input {:type "text" :name "username" :placeholder "Write your username here..."}]] [:div {:class "input-wrapper"} [:input {:type "password" :name "password" :placeholder "Write your password here..."}]] [:div {:class "input-wrapper"} [:input {:type "submit" :value "Submit"}]]]]))) ;; A simple function that has the responsability of authenticate the incomoning ;; credentials on login post request. In the current implementation it just ;; checks if a user and password matches to the builtin "user" representation, ;; but in your implementation this function may access to the database or any ;; other source for authenticate. This is just a example. (defn- authenticate [username, password] (when (and (= username "admin") (= password "<PASSWORD>")) {:username "Admin"})) ;; A hanlder that simply render the login page for GET requests. (defn login-page [context] (-> (render-login-page) (http/ok {:content-type "text/html"}))) ;; A handler that clears the session and redirect to the home page. (defn logout-page [context] (let [session (:session context)] (swap! session dissoc :identity) (http/found "/"))) ;; A handler that handles the POST requests for login page. (defn login-submit [context] (let [form-params (ct/get-formdata context) query-params (:query-params context) username (get form-params "username" "") password (get form-params "password" "")] (if (or (empty? username) (empty? password)) ;; Firstly validates the input, if required fields ;; are empty, render the login page html with ;; convenient error mesasage and return it. (http/ok (render-login-page ["The two fields are mandatory."]) {:content-type "text/html"}) ;; In case contrary, try validate the incoming ;; credentials, and in case of them validates ;; successful, update the session `:identity` key ;; with the authenticated user object. ;; In case contrary, return a login page ;; rendered with approapiate error message (if-let [user (authenticate username password)] (let [nexturl (get query-params "next" "/") session (:session context)] (swap! session assoc :identity user) (http/found nexturl)) (http/ok (render-login-page ["User or password are incorrect"]) {:content-type "text/html"})))))
true
(ns website.handlers (:require [clojure.java.io :as io] [hiccup.page :as hc] [catacumba.core :as ct] [catacumba.handlers :as hs] [catacumba.handlers.auth :as auth] [catacumba.http :as http])) ;; A function that renders the basic html layout ;; for all pages used in that application. (defn layout [content] (hc/html5 [:head [:meta {:charset "utf-8"}] [:title "Sample dummy website"] [:link {:href "/assets/styles.css" :type "text/css" :rel "stylesheet" :media "screen"}]] [:body content])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Home Page ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Shows a simple html page. It has different content for anonynmous ;; and logged users. (defn home-page [context] (-> (layout [:section {:class "home-page"} (if-let [user (:identity context)] [:div [:p (format "Welcome %s" (:username user))] [:p [:a {:href "/logout"} "logout"]]] [:div [:p "Welcome to the dummy website application."] [:p [:a {:href "/login"} "Login"]]])]) (http/ok {:content-type "text/html"}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Login page ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; A helper function for render login page, it used also for initial ;; rendering and render login page with errors on post requests. (defn- render-login-page ([] (render-login-page [])) ([errors] (layout [:section {:class "login-page"} [:p "Login"] (when (seq errors) [:div {:class "errors"} (for [e errors] [:div e])]) [:form {:action "" :method "post"} [:div {:class "input-wrapper"} [:input {:type "text" :name "username" :placeholder "Write your username here..."}]] [:div {:class "input-wrapper"} [:input {:type "password" :name "password" :placeholder "Write your password here..."}]] [:div {:class "input-wrapper"} [:input {:type "submit" :value "Submit"}]]]]))) ;; A simple function that has the responsability of authenticate the incomoning ;; credentials on login post request. In the current implementation it just ;; checks if a user and password matches to the builtin "user" representation, ;; but in your implementation this function may access to the database or any ;; other source for authenticate. This is just a example. (defn- authenticate [username, password] (when (and (= username "admin") (= password "PI:PASSWORD:<PASSWORD>END_PI")) {:username "Admin"})) ;; A hanlder that simply render the login page for GET requests. (defn login-page [context] (-> (render-login-page) (http/ok {:content-type "text/html"}))) ;; A handler that clears the session and redirect to the home page. (defn logout-page [context] (let [session (:session context)] (swap! session dissoc :identity) (http/found "/"))) ;; A handler that handles the POST requests for login page. (defn login-submit [context] (let [form-params (ct/get-formdata context) query-params (:query-params context) username (get form-params "username" "") password (get form-params "password" "")] (if (or (empty? username) (empty? password)) ;; Firstly validates the input, if required fields ;; are empty, render the login page html with ;; convenient error mesasage and return it. (http/ok (render-login-page ["The two fields are mandatory."]) {:content-type "text/html"}) ;; In case contrary, try validate the incoming ;; credentials, and in case of them validates ;; successful, update the session `:identity` key ;; with the authenticated user object. ;; In case contrary, return a login page ;; rendered with approapiate error message (if-let [user (authenticate username password)] (let [nexturl (get query-params "next" "/") session (:session context)] (swap! session assoc :identity user) (http/found nexturl)) (http/ok (render-login-page ["User or password are incorrect"]) {:content-type "text/html"})))))
[ { "context": ";; Copyright (C) 2011, Jozef Wagner. All rights reserved. \n\n(ns dredd.app\n \"App mana", "end": 35, "score": 0.999862015247345, "start": 23, "tag": "NAME", "value": "Jozef Wagner" } ]
data/train/clojure/11eb9fd0737e0121ee7a3bbb36990555aca366e8app.clj
harshp8l/deep-learning-lang-detection
84
;; Copyright (C) 2011, Jozef Wagner. All rights reserved. (ns dredd.app "App management" (:use compojure.core ring.util.response [hiccup core page-helpers form-helpers] [incanter core excel]) (:require [compojure.route :as route] [compojure.handler :as handler] [dredd.local-settings :as settings] [dredd.db-adapter.neo4j :as neo] [dredd.server :as server] [dredd.data :as data] [dredd.data.tests :as tests] [dredd.data.itest :as itest] [dredd.data.iquestion :as iquestion] [dredd.data.user :as user])) ;; Implementation details ;; Main (defn- choose-group [] (form-to [:post "set-group"] [:p "Vyberte si skupinu, do ktorej patrite: " (drop-down :group ["Pondelok 7:30" "Pondelok 13:30" "Streda 15:10"])] (submit-button "Pokracovat"))) (defn- login-form [] (form-to [:post "login"] [:p "Username: " (text-field :username "")] [:p "Password: " (password-field :password "")] (submit-button "Log in"))) (defn- user-menu [user-id] (let [user (user/get user-id)] [:p (:cn user) " | " [:a {:href "choose"} "Vybrat cvicenie"] " | " ;; NOTE: localization [:a {:href "logout"} "Log out"]])) (defn- main-page [user-id message] (html (html5 [:head [:meta {:charset "UTF-8"}]] [:body [:h1 "Zistovanie pripravenosti studentov na cvicenia z predmetu Programovanie"] ;; NOTE: localization (when message [:p [:b message]]) (if user-id (let [user (user/get user-id)] (if (or (user/admin? user-id) (:group user)) (user-menu user-id) (choose-group))) (login-form))]))) ;; Login (defn- login-page! [username password] (io!) (let [user-id (user/login! username password)] (-> (redirect "main") (assoc :session (if user-id {:user-id user-id} {:message "Wrong username or password"}))))) ;; Logout (defn- logout-page [] (-> (redirect "main") (assoc :session nil))) (defn- set-group! [user-id group] (user/set-group! user-id group) (redirect "main")) ;; Choosing test (defn- can-take-test [user-id test-id] (let [itest (itest/get user-id test-id)] (or (nil? itest) (not (:finished itest))))) (defn- show-controls [user-id test-id] (if (users/admin? user-id) [:p [:a {:href (str "admin/" test-id)} "Administracia"] " " [:a {:href "export.xls"} "Export"] ] (if (can-take-test user-id test-id) [:a {:href (str "test/" test-id)} "Otvor"] [:a {:href (str "view/" test-id)} "Pozri vysledky"]))) (defn- choose-page [user-id] (html (html5 [:body [:h1 "Vyber si cvicenie"] ;; NOTE: Localization (map (fn [t] [:p (:name t) " | " (show-controls user-id (:id t))]) tests/tests)]))) ;; Taking test (defn- print-iquestion [& ids] (let [q (apply iquestion/get ids)] [:div [:p [:b "Question " (:id q) ": "] (:name q)] [:p [:i (:text q)]] [:textarea {:rows "15" :cols "80" :name (:id q)} ""]])) (defn- take-test-page [user-id test-id] (if-not (can-take-test user-id test-id) ;; user has already finished the test {:status 403 :headers {} :body "You have already finished this test"} ;; ready to take a test (let [itest (or (itest/get user-id test-id) (data/add-itest! user-id (tests/get test-id))) user (user/get user-id)] (html (html5 [:body [:h1 (:name itest)] (form-to [:post "../submit-test"] (hidden-field :test-id test-id) [:hr] (map (partial print-iquestion user-id test-id) (:questions itest)) [:hr] (submit-button "Odoslat a Ukoncit"))]))))) ;; NOTE: Localization ;; Viewing test (defn- view-iquestion [& ids] (let [q (apply iquestion/get ids)] [:div [:p [:b "Question " (:id q) ": "] (:name q)] [:p [:i (:text q)]] [:p [:i "Your answer: "]] [:p [:pre (h (:answer q))]] [:p [:i "Znamka: "] (:result q)] [:p [:i "Poznamka: "] (:comment q)]])) (defn- view-test-page [user-id test-id] (let [itest (itest/get user-id test-id) user (user/get user-id)] (html (html5 [:body [:h1 (:name itest)] [:hr] (map (partial view-iquestion user-id test-id) (:questions itest)) [:hr]])))) ;; Submitting test (defn- submit-test! [user-id test-id params] (io!) ;; TODO: only if not finished yet (data/submit-itest! user-id test-id params) (-> (redirect "main") (assoc :session {:user-id user-id :message "Uspesne odoslane!"}))) ;; Rank test (defn- rank-test! [{:keys [student-id test-id question-id result comment]}] (io!) (iquestion/rank! student-id test-id question-id result comment) (redirect (str "admin/" test-id))) ;; Manage users (defn- print-user [user-id] (let [user (user/get user-id)] [:div [:hr] [:p "Id: " [:b (:uid user)]] [:p "Name: " [:b (:givenName user)]] [:p "Surname: " [:b (:sn user)]]])) (defn- manage-users [] (html (html5 [:body [:h1 "User management"] (map print-user (user/get-all))]))) ;; Administrator interface (defn- rank-iquestion [user-id test-id question-id] (let [q (iquestion/get user-id test-id question-id)] (when-not (:result q) [:div (form-to [:post "../rank-question"] (hidden-field :test-id test-id) (hidden-field :student-id user-id) (hidden-field :question-id question-id) [:p [:b "Question " (:id q) ": "] (:name q)] [:p [:i (:text q)]] [:p [:i "Your answer: "]] [:p [:pre (h (:answer q))]] [:p [:i "Znamka: "] (text-field :result (:result q))] [:p [:i "Poznamka: "] (text-field :comment (:comment q))] [:p (submit-button "Rank")] )]))) (defn- has-unranked-questions [user-id test-id] true (let [questions (:questions (itest/get user-id test-id))] (some #(not ( :result (iquestion/get user-id test-id %))) questions))) (defn- admin-user-test [user-id test-id] (let [user (user/get user-id) itest (itest/get user-id test-id)] (when (has-unranked-questions user-id test-id) [:div [:hr] [:p (:cn user) " (" user-id ")"] (if (:finished itest) [:p "Test finished at " (:finished itest)] [:p "Test NOT finished"]) (map (partial rank-iquestion user-id test-id) (:questions itest))]))) (defn- admin-test-page [test-id] (let [user-ids (user/get-all)] (html (html5 [:body [:h1 "Administracia"] (map #(admin-user-test % test-id) user-ids)])))) ;; Export (defn- question-header [test-id question-id] (let [h (str test-id "-" question-id "-")] [(str h "question") (str h "answer") (str h "result")])) (defn- question-body [user-id test-id question-id] (let [q (iquestions/get-iquestion user-id test-id question-id)] [(:text q) (:answer q) (str (if (empty? (str (:result q) (comment "(" (:comment q) ")"))) "" (str(:result q))))])) (defn- test-header [{test-id :id}] (let [qs (:questions (tests/get test-id))] (mapcat (partial question-header test-id) qs))) (defn- create-sheet-header [] (cons "Name:" (cons "Group:" (mapcat test-header tests/tests)))) (defn user-test-body [user-id {test-id :id}] (let [qs (:questions (tests/get test-id))] (mapcat (partial question-body user-id test-id) qs))) (defn user-row [user-id] (let [u (users/get-user user-id)] (cons (users/get-user-name u) (cons (:group u) (mapcat (partial user-test-body user-id) tests/tests))))) (defn- create-sheet-body [] ;; each user has one row (map user-row (user/get-all)) ) (defn- admin-export-page [] (let [fname "temp.xls" sheet-header (create-sheet-header) sheet-body (create-sheet-body)] (save-xls (dataset sheet-header sheet-body) fname) (file-response fname))) ;; Middleware ;; TODO: authorization (defmacro with-user [user-id & body] `(if (and ~user-id (not (data/maintenance?))) (do ~@body) {:status 403 :headers {} :body "You must be logged in to view this page!"})) (defmacro with-admin [user-id & body] `(if (user/admin? ~user-id) (do ~@body) {:status 403 :headers {} :body "You must be administrator to view this page"})) (defmacro with-test [test-id & body] `(if (tests/get ~test-id) (do ~@body) {:status 403 :headers {} :body "There is no such test!"})) ;; Page layout ;; TODO zaradenie do skupiny (defroutes main-routes (GET "/" [] (redirect (str (:base-url settings/server) "/main"))) (GET "/main" {{:keys [user-id message]} :session} (main-page user-id message)) (GET "/choose" {{user-id :user-id} :session} (with-user user-id (choose-page user-id))) (GET "/test/:test-id" {{user-id :user-id} :session {test-id :test-id} :route-params} (with-user user-id (with-test test-id (take-test-page user-id test-id)))) (GET "/admin/:test-id" {{user-id :user-id} :session {test-id :test-id} :route-params} (with-admin user-id (with-test test-id (admin-test-page test-id)))) (GET "/admin-users" {{user-id :user-id} :session} (with-admin user-id (manage-users))) (GET "/view/:test-id" {{user-id :user-id} :session {test-id :test-id} :route-params} (with-user user-id (with-test test-id (view-test-page user-id test-id)))) (GET "/export.xls" {{user-id :user-id} :session} (with-admin user-id (admin-export-page))) (POST "/submit-test" {{user-id :user-id} :session {test-id :test-id :as params} :params} (with-user user-id (with-test test-id (submit-test! user-id test-id params)))) (POST "/rank-question" {{user-id :user-id} :session {test-id :test-id :as params} :params} (with-admin user-id (rank-test! params))) ;; TODO hodnotenie (GET "/logout" [] (logout-page)) (GET "/shutdown" {{user-id :user-id} :session} (with-admin user-id (server/shutdown!) "you may now stop the server")) (POST "/login" [username password] (login-page! username password)) (POST "/set-group" {{user-id :user-id} :session {group :group :as params} :params} (with-user user-id (set-group! user-id group))) (POST "/user-do" []) (route/resources "/") (route/not-found "Page not found")) ;; TODO logging (defn wrap-utf8 [handler] (fn [request] (-> (handler request) (content-type "text/html; charset=utf-8")))) ;; Main App handler (def handler (-> (handler/site main-routes) (wrap-utf8)))
123793
;; Copyright (C) 2011, <NAME>. All rights reserved. (ns dredd.app "App management" (:use compojure.core ring.util.response [hiccup core page-helpers form-helpers] [incanter core excel]) (:require [compojure.route :as route] [compojure.handler :as handler] [dredd.local-settings :as settings] [dredd.db-adapter.neo4j :as neo] [dredd.server :as server] [dredd.data :as data] [dredd.data.tests :as tests] [dredd.data.itest :as itest] [dredd.data.iquestion :as iquestion] [dredd.data.user :as user])) ;; Implementation details ;; Main (defn- choose-group [] (form-to [:post "set-group"] [:p "Vyberte si skupinu, do ktorej patrite: " (drop-down :group ["Pondelok 7:30" "Pondelok 13:30" "Streda 15:10"])] (submit-button "Pokracovat"))) (defn- login-form [] (form-to [:post "login"] [:p "Username: " (text-field :username "")] [:p "Password: " (password-field :password "")] (submit-button "Log in"))) (defn- user-menu [user-id] (let [user (user/get user-id)] [:p (:cn user) " | " [:a {:href "choose"} "Vybrat cvicenie"] " | " ;; NOTE: localization [:a {:href "logout"} "Log out"]])) (defn- main-page [user-id message] (html (html5 [:head [:meta {:charset "UTF-8"}]] [:body [:h1 "Zistovanie pripravenosti studentov na cvicenia z predmetu Programovanie"] ;; NOTE: localization (when message [:p [:b message]]) (if user-id (let [user (user/get user-id)] (if (or (user/admin? user-id) (:group user)) (user-menu user-id) (choose-group))) (login-form))]))) ;; Login (defn- login-page! [username password] (io!) (let [user-id (user/login! username password)] (-> (redirect "main") (assoc :session (if user-id {:user-id user-id} {:message "Wrong username or password"}))))) ;; Logout (defn- logout-page [] (-> (redirect "main") (assoc :session nil))) (defn- set-group! [user-id group] (user/set-group! user-id group) (redirect "main")) ;; Choosing test (defn- can-take-test [user-id test-id] (let [itest (itest/get user-id test-id)] (or (nil? itest) (not (:finished itest))))) (defn- show-controls [user-id test-id] (if (users/admin? user-id) [:p [:a {:href (str "admin/" test-id)} "Administracia"] " " [:a {:href "export.xls"} "Export"] ] (if (can-take-test user-id test-id) [:a {:href (str "test/" test-id)} "Otvor"] [:a {:href (str "view/" test-id)} "Pozri vysledky"]))) (defn- choose-page [user-id] (html (html5 [:body [:h1 "Vyber si cvicenie"] ;; NOTE: Localization (map (fn [t] [:p (:name t) " | " (show-controls user-id (:id t))]) tests/tests)]))) ;; Taking test (defn- print-iquestion [& ids] (let [q (apply iquestion/get ids)] [:div [:p [:b "Question " (:id q) ": "] (:name q)] [:p [:i (:text q)]] [:textarea {:rows "15" :cols "80" :name (:id q)} ""]])) (defn- take-test-page [user-id test-id] (if-not (can-take-test user-id test-id) ;; user has already finished the test {:status 403 :headers {} :body "You have already finished this test"} ;; ready to take a test (let [itest (or (itest/get user-id test-id) (data/add-itest! user-id (tests/get test-id))) user (user/get user-id)] (html (html5 [:body [:h1 (:name itest)] (form-to [:post "../submit-test"] (hidden-field :test-id test-id) [:hr] (map (partial print-iquestion user-id test-id) (:questions itest)) [:hr] (submit-button "Odoslat a Ukoncit"))]))))) ;; NOTE: Localization ;; Viewing test (defn- view-iquestion [& ids] (let [q (apply iquestion/get ids)] [:div [:p [:b "Question " (:id q) ": "] (:name q)] [:p [:i (:text q)]] [:p [:i "Your answer: "]] [:p [:pre (h (:answer q))]] [:p [:i "Znamka: "] (:result q)] [:p [:i "Poznamka: "] (:comment q)]])) (defn- view-test-page [user-id test-id] (let [itest (itest/get user-id test-id) user (user/get user-id)] (html (html5 [:body [:h1 (:name itest)] [:hr] (map (partial view-iquestion user-id test-id) (:questions itest)) [:hr]])))) ;; Submitting test (defn- submit-test! [user-id test-id params] (io!) ;; TODO: only if not finished yet (data/submit-itest! user-id test-id params) (-> (redirect "main") (assoc :session {:user-id user-id :message "Uspesne odoslane!"}))) ;; Rank test (defn- rank-test! [{:keys [student-id test-id question-id result comment]}] (io!) (iquestion/rank! student-id test-id question-id result comment) (redirect (str "admin/" test-id))) ;; Manage users (defn- print-user [user-id] (let [user (user/get user-id)] [:div [:hr] [:p "Id: " [:b (:uid user)]] [:p "Name: " [:b (:givenName user)]] [:p "Surname: " [:b (:sn user)]]])) (defn- manage-users [] (html (html5 [:body [:h1 "User management"] (map print-user (user/get-all))]))) ;; Administrator interface (defn- rank-iquestion [user-id test-id question-id] (let [q (iquestion/get user-id test-id question-id)] (when-not (:result q) [:div (form-to [:post "../rank-question"] (hidden-field :test-id test-id) (hidden-field :student-id user-id) (hidden-field :question-id question-id) [:p [:b "Question " (:id q) ": "] (:name q)] [:p [:i (:text q)]] [:p [:i "Your answer: "]] [:p [:pre (h (:answer q))]] [:p [:i "Znamka: "] (text-field :result (:result q))] [:p [:i "Poznamka: "] (text-field :comment (:comment q))] [:p (submit-button "Rank")] )]))) (defn- has-unranked-questions [user-id test-id] true (let [questions (:questions (itest/get user-id test-id))] (some #(not ( :result (iquestion/get user-id test-id %))) questions))) (defn- admin-user-test [user-id test-id] (let [user (user/get user-id) itest (itest/get user-id test-id)] (when (has-unranked-questions user-id test-id) [:div [:hr] [:p (:cn user) " (" user-id ")"] (if (:finished itest) [:p "Test finished at " (:finished itest)] [:p "Test NOT finished"]) (map (partial rank-iquestion user-id test-id) (:questions itest))]))) (defn- admin-test-page [test-id] (let [user-ids (user/get-all)] (html (html5 [:body [:h1 "Administracia"] (map #(admin-user-test % test-id) user-ids)])))) ;; Export (defn- question-header [test-id question-id] (let [h (str test-id "-" question-id "-")] [(str h "question") (str h "answer") (str h "result")])) (defn- question-body [user-id test-id question-id] (let [q (iquestions/get-iquestion user-id test-id question-id)] [(:text q) (:answer q) (str (if (empty? (str (:result q) (comment "(" (:comment q) ")"))) "" (str(:result q))))])) (defn- test-header [{test-id :id}] (let [qs (:questions (tests/get test-id))] (mapcat (partial question-header test-id) qs))) (defn- create-sheet-header [] (cons "Name:" (cons "Group:" (mapcat test-header tests/tests)))) (defn user-test-body [user-id {test-id :id}] (let [qs (:questions (tests/get test-id))] (mapcat (partial question-body user-id test-id) qs))) (defn user-row [user-id] (let [u (users/get-user user-id)] (cons (users/get-user-name u) (cons (:group u) (mapcat (partial user-test-body user-id) tests/tests))))) (defn- create-sheet-body [] ;; each user has one row (map user-row (user/get-all)) ) (defn- admin-export-page [] (let [fname "temp.xls" sheet-header (create-sheet-header) sheet-body (create-sheet-body)] (save-xls (dataset sheet-header sheet-body) fname) (file-response fname))) ;; Middleware ;; TODO: authorization (defmacro with-user [user-id & body] `(if (and ~user-id (not (data/maintenance?))) (do ~@body) {:status 403 :headers {} :body "You must be logged in to view this page!"})) (defmacro with-admin [user-id & body] `(if (user/admin? ~user-id) (do ~@body) {:status 403 :headers {} :body "You must be administrator to view this page"})) (defmacro with-test [test-id & body] `(if (tests/get ~test-id) (do ~@body) {:status 403 :headers {} :body "There is no such test!"})) ;; Page layout ;; TODO zaradenie do skupiny (defroutes main-routes (GET "/" [] (redirect (str (:base-url settings/server) "/main"))) (GET "/main" {{:keys [user-id message]} :session} (main-page user-id message)) (GET "/choose" {{user-id :user-id} :session} (with-user user-id (choose-page user-id))) (GET "/test/:test-id" {{user-id :user-id} :session {test-id :test-id} :route-params} (with-user user-id (with-test test-id (take-test-page user-id test-id)))) (GET "/admin/:test-id" {{user-id :user-id} :session {test-id :test-id} :route-params} (with-admin user-id (with-test test-id (admin-test-page test-id)))) (GET "/admin-users" {{user-id :user-id} :session} (with-admin user-id (manage-users))) (GET "/view/:test-id" {{user-id :user-id} :session {test-id :test-id} :route-params} (with-user user-id (with-test test-id (view-test-page user-id test-id)))) (GET "/export.xls" {{user-id :user-id} :session} (with-admin user-id (admin-export-page))) (POST "/submit-test" {{user-id :user-id} :session {test-id :test-id :as params} :params} (with-user user-id (with-test test-id (submit-test! user-id test-id params)))) (POST "/rank-question" {{user-id :user-id} :session {test-id :test-id :as params} :params} (with-admin user-id (rank-test! params))) ;; TODO hodnotenie (GET "/logout" [] (logout-page)) (GET "/shutdown" {{user-id :user-id} :session} (with-admin user-id (server/shutdown!) "you may now stop the server")) (POST "/login" [username password] (login-page! username password)) (POST "/set-group" {{user-id :user-id} :session {group :group :as params} :params} (with-user user-id (set-group! user-id group))) (POST "/user-do" []) (route/resources "/") (route/not-found "Page not found")) ;; TODO logging (defn wrap-utf8 [handler] (fn [request] (-> (handler request) (content-type "text/html; charset=utf-8")))) ;; Main App handler (def handler (-> (handler/site main-routes) (wrap-utf8)))
true
;; Copyright (C) 2011, PI:NAME:<NAME>END_PI. All rights reserved. (ns dredd.app "App management" (:use compojure.core ring.util.response [hiccup core page-helpers form-helpers] [incanter core excel]) (:require [compojure.route :as route] [compojure.handler :as handler] [dredd.local-settings :as settings] [dredd.db-adapter.neo4j :as neo] [dredd.server :as server] [dredd.data :as data] [dredd.data.tests :as tests] [dredd.data.itest :as itest] [dredd.data.iquestion :as iquestion] [dredd.data.user :as user])) ;; Implementation details ;; Main (defn- choose-group [] (form-to [:post "set-group"] [:p "Vyberte si skupinu, do ktorej patrite: " (drop-down :group ["Pondelok 7:30" "Pondelok 13:30" "Streda 15:10"])] (submit-button "Pokracovat"))) (defn- login-form [] (form-to [:post "login"] [:p "Username: " (text-field :username "")] [:p "Password: " (password-field :password "")] (submit-button "Log in"))) (defn- user-menu [user-id] (let [user (user/get user-id)] [:p (:cn user) " | " [:a {:href "choose"} "Vybrat cvicenie"] " | " ;; NOTE: localization [:a {:href "logout"} "Log out"]])) (defn- main-page [user-id message] (html (html5 [:head [:meta {:charset "UTF-8"}]] [:body [:h1 "Zistovanie pripravenosti studentov na cvicenia z predmetu Programovanie"] ;; NOTE: localization (when message [:p [:b message]]) (if user-id (let [user (user/get user-id)] (if (or (user/admin? user-id) (:group user)) (user-menu user-id) (choose-group))) (login-form))]))) ;; Login (defn- login-page! [username password] (io!) (let [user-id (user/login! username password)] (-> (redirect "main") (assoc :session (if user-id {:user-id user-id} {:message "Wrong username or password"}))))) ;; Logout (defn- logout-page [] (-> (redirect "main") (assoc :session nil))) (defn- set-group! [user-id group] (user/set-group! user-id group) (redirect "main")) ;; Choosing test (defn- can-take-test [user-id test-id] (let [itest (itest/get user-id test-id)] (or (nil? itest) (not (:finished itest))))) (defn- show-controls [user-id test-id] (if (users/admin? user-id) [:p [:a {:href (str "admin/" test-id)} "Administracia"] " " [:a {:href "export.xls"} "Export"] ] (if (can-take-test user-id test-id) [:a {:href (str "test/" test-id)} "Otvor"] [:a {:href (str "view/" test-id)} "Pozri vysledky"]))) (defn- choose-page [user-id] (html (html5 [:body [:h1 "Vyber si cvicenie"] ;; NOTE: Localization (map (fn [t] [:p (:name t) " | " (show-controls user-id (:id t))]) tests/tests)]))) ;; Taking test (defn- print-iquestion [& ids] (let [q (apply iquestion/get ids)] [:div [:p [:b "Question " (:id q) ": "] (:name q)] [:p [:i (:text q)]] [:textarea {:rows "15" :cols "80" :name (:id q)} ""]])) (defn- take-test-page [user-id test-id] (if-not (can-take-test user-id test-id) ;; user has already finished the test {:status 403 :headers {} :body "You have already finished this test"} ;; ready to take a test (let [itest (or (itest/get user-id test-id) (data/add-itest! user-id (tests/get test-id))) user (user/get user-id)] (html (html5 [:body [:h1 (:name itest)] (form-to [:post "../submit-test"] (hidden-field :test-id test-id) [:hr] (map (partial print-iquestion user-id test-id) (:questions itest)) [:hr] (submit-button "Odoslat a Ukoncit"))]))))) ;; NOTE: Localization ;; Viewing test (defn- view-iquestion [& ids] (let [q (apply iquestion/get ids)] [:div [:p [:b "Question " (:id q) ": "] (:name q)] [:p [:i (:text q)]] [:p [:i "Your answer: "]] [:p [:pre (h (:answer q))]] [:p [:i "Znamka: "] (:result q)] [:p [:i "Poznamka: "] (:comment q)]])) (defn- view-test-page [user-id test-id] (let [itest (itest/get user-id test-id) user (user/get user-id)] (html (html5 [:body [:h1 (:name itest)] [:hr] (map (partial view-iquestion user-id test-id) (:questions itest)) [:hr]])))) ;; Submitting test (defn- submit-test! [user-id test-id params] (io!) ;; TODO: only if not finished yet (data/submit-itest! user-id test-id params) (-> (redirect "main") (assoc :session {:user-id user-id :message "Uspesne odoslane!"}))) ;; Rank test (defn- rank-test! [{:keys [student-id test-id question-id result comment]}] (io!) (iquestion/rank! student-id test-id question-id result comment) (redirect (str "admin/" test-id))) ;; Manage users (defn- print-user [user-id] (let [user (user/get user-id)] [:div [:hr] [:p "Id: " [:b (:uid user)]] [:p "Name: " [:b (:givenName user)]] [:p "Surname: " [:b (:sn user)]]])) (defn- manage-users [] (html (html5 [:body [:h1 "User management"] (map print-user (user/get-all))]))) ;; Administrator interface (defn- rank-iquestion [user-id test-id question-id] (let [q (iquestion/get user-id test-id question-id)] (when-not (:result q) [:div (form-to [:post "../rank-question"] (hidden-field :test-id test-id) (hidden-field :student-id user-id) (hidden-field :question-id question-id) [:p [:b "Question " (:id q) ": "] (:name q)] [:p [:i (:text q)]] [:p [:i "Your answer: "]] [:p [:pre (h (:answer q))]] [:p [:i "Znamka: "] (text-field :result (:result q))] [:p [:i "Poznamka: "] (text-field :comment (:comment q))] [:p (submit-button "Rank")] )]))) (defn- has-unranked-questions [user-id test-id] true (let [questions (:questions (itest/get user-id test-id))] (some #(not ( :result (iquestion/get user-id test-id %))) questions))) (defn- admin-user-test [user-id test-id] (let [user (user/get user-id) itest (itest/get user-id test-id)] (when (has-unranked-questions user-id test-id) [:div [:hr] [:p (:cn user) " (" user-id ")"] (if (:finished itest) [:p "Test finished at " (:finished itest)] [:p "Test NOT finished"]) (map (partial rank-iquestion user-id test-id) (:questions itest))]))) (defn- admin-test-page [test-id] (let [user-ids (user/get-all)] (html (html5 [:body [:h1 "Administracia"] (map #(admin-user-test % test-id) user-ids)])))) ;; Export (defn- question-header [test-id question-id] (let [h (str test-id "-" question-id "-")] [(str h "question") (str h "answer") (str h "result")])) (defn- question-body [user-id test-id question-id] (let [q (iquestions/get-iquestion user-id test-id question-id)] [(:text q) (:answer q) (str (if (empty? (str (:result q) (comment "(" (:comment q) ")"))) "" (str(:result q))))])) (defn- test-header [{test-id :id}] (let [qs (:questions (tests/get test-id))] (mapcat (partial question-header test-id) qs))) (defn- create-sheet-header [] (cons "Name:" (cons "Group:" (mapcat test-header tests/tests)))) (defn user-test-body [user-id {test-id :id}] (let [qs (:questions (tests/get test-id))] (mapcat (partial question-body user-id test-id) qs))) (defn user-row [user-id] (let [u (users/get-user user-id)] (cons (users/get-user-name u) (cons (:group u) (mapcat (partial user-test-body user-id) tests/tests))))) (defn- create-sheet-body [] ;; each user has one row (map user-row (user/get-all)) ) (defn- admin-export-page [] (let [fname "temp.xls" sheet-header (create-sheet-header) sheet-body (create-sheet-body)] (save-xls (dataset sheet-header sheet-body) fname) (file-response fname))) ;; Middleware ;; TODO: authorization (defmacro with-user [user-id & body] `(if (and ~user-id (not (data/maintenance?))) (do ~@body) {:status 403 :headers {} :body "You must be logged in to view this page!"})) (defmacro with-admin [user-id & body] `(if (user/admin? ~user-id) (do ~@body) {:status 403 :headers {} :body "You must be administrator to view this page"})) (defmacro with-test [test-id & body] `(if (tests/get ~test-id) (do ~@body) {:status 403 :headers {} :body "There is no such test!"})) ;; Page layout ;; TODO zaradenie do skupiny (defroutes main-routes (GET "/" [] (redirect (str (:base-url settings/server) "/main"))) (GET "/main" {{:keys [user-id message]} :session} (main-page user-id message)) (GET "/choose" {{user-id :user-id} :session} (with-user user-id (choose-page user-id))) (GET "/test/:test-id" {{user-id :user-id} :session {test-id :test-id} :route-params} (with-user user-id (with-test test-id (take-test-page user-id test-id)))) (GET "/admin/:test-id" {{user-id :user-id} :session {test-id :test-id} :route-params} (with-admin user-id (with-test test-id (admin-test-page test-id)))) (GET "/admin-users" {{user-id :user-id} :session} (with-admin user-id (manage-users))) (GET "/view/:test-id" {{user-id :user-id} :session {test-id :test-id} :route-params} (with-user user-id (with-test test-id (view-test-page user-id test-id)))) (GET "/export.xls" {{user-id :user-id} :session} (with-admin user-id (admin-export-page))) (POST "/submit-test" {{user-id :user-id} :session {test-id :test-id :as params} :params} (with-user user-id (with-test test-id (submit-test! user-id test-id params)))) (POST "/rank-question" {{user-id :user-id} :session {test-id :test-id :as params} :params} (with-admin user-id (rank-test! params))) ;; TODO hodnotenie (GET "/logout" [] (logout-page)) (GET "/shutdown" {{user-id :user-id} :session} (with-admin user-id (server/shutdown!) "you may now stop the server")) (POST "/login" [username password] (login-page! username password)) (POST "/set-group" {{user-id :user-id} :session {group :group :as params} :params} (with-user user-id (set-group! user-id group))) (POST "/user-do" []) (route/resources "/") (route/not-found "Page not found")) ;; TODO logging (defn wrap-utf8 [handler] (fn [request] (-> (handler request) (content-type "text/html; charset=utf-8")))) ;; Main App handler (def handler (-> (handler/site main-routes) (wrap-utf8)))
[ { "context": "========================\n; Copyright (C) 2021-2022 Radislav (Radicchio) Golubtsov\n;\n; (See the LICENSE file at the top o", "end": 547, "score": 0.9645174741744995, "start": 528, "tag": "NAME", "value": "Radislav (Radicchio" }, { "context": "===\n; Copyright (C) 2021-2022 Radislav (Radicchio) Golubtsov\n;\n; (See the LICENSE file at the top of the sourc", "end": 558, "score": 0.9996860027313232, "start": 549, "tag": "NAME", "value": "Golubtsov" }, { "context": "daemon overall termination status.\n \" {:added \"0.0.1\"} [args]\n\n (let [server-port (nth args 0", "end": 8040, "score": 0.9305008053779602, "start": 8035, "tag": "IP_ADDRESS", "value": "0.0.1" } ]
src/com/transroutownish/proto/bus/controller.clj
rgolubtsov/transroutownish-proto-bus-clojure
0
; ; src/com/transroutownish/proto/bus/controller.clj ; ============================================================================= ; Urban bus routing microservice prototype (Clojure port). Version 0.15.1 ; ============================================================================= ; A daemon written in Clojure, designed and intended to be run ; as a microservice, implementing a simple urban bus routing prototype. ; ============================================================================= ; Copyright (C) 2021-2022 Radislav (Radicchio) Golubtsov ; ; (See the LICENSE file at the top of the source tree.) ; (ns com.transroutownish.proto.bus.controller "The controller module of the daemon." (:require [clojure.tools.logging :as log] [clojure.edn :as edn] [clojure.walk :refer [ keywordize-keys ]] [clojure.string :refer [ split index-of ]] [clojure.data.json :refer [ write-str ]] [clojure.repl :refer [ set-break-handler! ]] [org.httpkit.server :refer [ run-server as-channel send! ]] ) (:import [org.graylog2.syslog4j.impl.unix UnixSyslogConfig] [org.graylog2.syslog4j.impl.unix UnixSyslog ] [org.graylog2.syslog4j SyslogIF ] ) (:require [com.transroutownish.proto.bus.helper :as AUX]) ) ; Helper constants. (defmacro REST-PREFIX [] "route" ) (defmacro REST-DIRECT [] "direct") (defmacro FROM [] "from") (defmacro TO [] "to" ) (defmacro HTTP-200-OK [] 200 ) (defmacro HTTP-400-BAD-REQ [] 400 ) (defmacro HDR-CONTENT-TYPE-N [] "content-type" ) (defmacro HDR-CONTENT-TYPE-V [] "application/json") ; Extra helper constants. (defmacro ZERO [] "0") (defmacro PARAMS-SEP [] #"=|&") (defmacro TRUE [] "true") (defmacro SEQ1-REGEX "The regex pattern for the leading part of a bus stops sequence, before the matching element." [] ".*\\s" ) (defmacro SEQ2-REGEX "The regex pattern for the trailing part of a bus stops sequence, after the matching element." [] "\\s.*" ) (def debug-log-enabled-ref "The Ref to the debug logging enabler." (ref []) ) (def routes-vector-ref "The Ref to a vector containing all available routes." (ref []) ) (def s-ref "The Ref to the Unix system logger." (ref []) ) (defn -send-response "Helper function. Used to send the HTTP response back to the client. Args: req: The incoming HTTP request object. status: The HTTP status code. body: The body of the response. Returns: A hash map containing the asynchronous HTTP `AsyncChannel`. " {:added "0.0.5"} [req status body] (as-channel req {:on-open (fn [channel] (send! channel { :headers {(HDR-CONTENT-TYPE-N) (HDR-CONTENT-TYPE-V)} :status status :body body }))}) ) (defn find-direct-route "Performs the routes processing (onto bus stops sequences) to identify and return whether a particular interval between two bus stop points given is direct (i.e. contains in any of the routes), or not. Args: routes: A vector containing all available routes. from: The starting bus stop point. to: The ending bus stop point. Returns: `true` if the direct route is found, `false` otherwise. " {:added "0.0.1"} [routes from to] (let [debug-log-enabled (nth @debug-log-enabled-ref 0)] (let [routes-count (count routes)] (try (loop [-routes routes i 0] (when (< i routes-count) (let [route (first -routes)] (if debug-log-enabled (log/debug (+ i 1) (AUX/EQUALS) route) ) (if (.matches route (str (SEQ1-REGEX) from (SEQ2-REGEX))) ; Pinning in the starting bus stop point, if it's found. ; Next, searching for the ending bus stop point ; on the current route, beginning at the pinned point. (let [route-from (subs route (index-of route (str from)))] (if debug-log-enabled (log/debug from (AUX/V-BAR) route-from) ) (if (.matches route-from (str (SEQ1-REGEX) to (SEQ2-REGEX))) (throw (Exception. (TRUE))) )) )) (recur (rest -routes) (inc i))) ) false (catch Exception e (read-string (.getMessage e)) ; <== Like direct = true; break; )))) ) (defn reqhandler "The request handler callback. Gets called when a new incoming HTTP request is received. Args: req: The incoming HTTP request object. Returns: The HTTP status code, response headers, and a body of the response. " {:added "0.0.1"} [req] (let [debug-log-enabled (nth @debug-log-enabled-ref 0)] (let [s (nth @s-ref 0)] ; <== The Unix system logger. (let [method (get req :request-method)] (let [uri (get req :uri )] ; GET /route/direct (if (= method :get) (if (= uri (str (AUX/SLASH) (REST-PREFIX) (AUX/SLASH) (REST-DIRECT))) ; ----------------------------------------------------------------- ; --- Parsing and validating request params - Begin --------------- ; ----------------------------------------------------------------- (let [params0 (get req :query-string)] (let [params (if (nil? params0) {:from (ZERO) :to (ZERO)} (keywordize-keys (try (apply hash-map (split params0 (PARAMS-SEP))) (catch IllegalArgumentException e {:from (ZERO) :to (ZERO)} ))) )] (let [from (get params :from)] (let [to (get params :to )] (if debug-log-enabled (do (log/debug (FROM) (AUX/EQUALS) from (AUX/V-BAR) (TO ) (AUX/EQUALS) to) (.debug s (str (FROM) (AUX/SPACE) (AUX/EQUALS) (AUX/SPACE) from (AUX/SPACE) (AUX/V-BAR ) (AUX/SPACE) (TO ) (AUX/SPACE) (AUX/EQUALS) (AUX/SPACE) to)) )) (let [-from (try (edn/read-string from) (catch NumberFormatException e (ZERO) ))] (let [-to (try (edn/read-string to ) (catch NumberFormatException e (ZERO) ))] (let [is-request-malformed (try (or (< -from 1) (< -to 1)) (catch ClassCastException e true ))] ; ----------------------------------------------------------------- ; --- Parsing and validating request params - End ----------------- ; ----------------------------------------------------------------- (if is-request-malformed (-send-response req (HTTP-400-BAD-REQ) (write-str (hash-map :error (AUX/ERR-REQ-PARAMS-MUST-BE-POSITIVE-INTS)))) ;Performing the routes processing to find out the direct route. (let [direct (if (= -from -to) false (find-direct-route (nth @routes-vector-ref 0) -from -to))] (-send-response req (HTTP-200-OK ) (write-str (hash-map :from -from :to -to :direct direct)))) )))))))) ) ))))) ) (defn startup "Starts up the daemon. Args: args: A list containing the server port number to listen on, as the first element. Returns: The exit code indicating the daemon overall termination status. " {:added "0.0.1"} [args] (let [server-port (nth args 0)] (let [debug-log-enabled (nth args 1)] (let [routes-vector (nth args 2)] ; Starting an STM transaction to alter Refs: ; routes vector and debug log enabler. (dosync (alter debug-log-enabled-ref conj debug-log-enabled) (alter routes-vector-ref conj routes-vector ) ) ; Opening the system logger. ; Calling <syslog.h> openlog(NULL, LOG_CONS | LOG_PID, LOG_DAEMON); (let [cfg (UnixSyslogConfig.)] (.setIdent cfg nil) (.setFacility cfg SyslogIF/FACILITY_DAEMON) (let [s (UnixSyslog.)] (.initialize s SyslogIF/UNIX_SYSLOG cfg) (dosync (alter s-ref conj s)) (let [stop-server (run-server reqhandler {:port server-port})] (log/info (AUX/MSG-SERVER-STARTED) server-port) (.info s (str (AUX/MSG-SERVER-STARTED) (AUX/SPACE) server-port)) (set-break-handler! (fn [_] (log/info (AUX/MSG-SERVER-STOPPED)) (.info s (AUX/MSG-SERVER-STOPPED)) ; Closing the system logger. ; Calling <syslog.h> closelog(); (.shutdown s) (stop-server) ; (System/exit (AUX/EXIT-SUCCESS)) )))))))) ) ; vim:set nu et ts=4 sw=4:
42410
; ; src/com/transroutownish/proto/bus/controller.clj ; ============================================================================= ; Urban bus routing microservice prototype (Clojure port). Version 0.15.1 ; ============================================================================= ; A daemon written in Clojure, designed and intended to be run ; as a microservice, implementing a simple urban bus routing prototype. ; ============================================================================= ; Copyright (C) 2021-2022 <NAME>) <NAME> ; ; (See the LICENSE file at the top of the source tree.) ; (ns com.transroutownish.proto.bus.controller "The controller module of the daemon." (:require [clojure.tools.logging :as log] [clojure.edn :as edn] [clojure.walk :refer [ keywordize-keys ]] [clojure.string :refer [ split index-of ]] [clojure.data.json :refer [ write-str ]] [clojure.repl :refer [ set-break-handler! ]] [org.httpkit.server :refer [ run-server as-channel send! ]] ) (:import [org.graylog2.syslog4j.impl.unix UnixSyslogConfig] [org.graylog2.syslog4j.impl.unix UnixSyslog ] [org.graylog2.syslog4j SyslogIF ] ) (:require [com.transroutownish.proto.bus.helper :as AUX]) ) ; Helper constants. (defmacro REST-PREFIX [] "route" ) (defmacro REST-DIRECT [] "direct") (defmacro FROM [] "from") (defmacro TO [] "to" ) (defmacro HTTP-200-OK [] 200 ) (defmacro HTTP-400-BAD-REQ [] 400 ) (defmacro HDR-CONTENT-TYPE-N [] "content-type" ) (defmacro HDR-CONTENT-TYPE-V [] "application/json") ; Extra helper constants. (defmacro ZERO [] "0") (defmacro PARAMS-SEP [] #"=|&") (defmacro TRUE [] "true") (defmacro SEQ1-REGEX "The regex pattern for the leading part of a bus stops sequence, before the matching element." [] ".*\\s" ) (defmacro SEQ2-REGEX "The regex pattern for the trailing part of a bus stops sequence, after the matching element." [] "\\s.*" ) (def debug-log-enabled-ref "The Ref to the debug logging enabler." (ref []) ) (def routes-vector-ref "The Ref to a vector containing all available routes." (ref []) ) (def s-ref "The Ref to the Unix system logger." (ref []) ) (defn -send-response "Helper function. Used to send the HTTP response back to the client. Args: req: The incoming HTTP request object. status: The HTTP status code. body: The body of the response. Returns: A hash map containing the asynchronous HTTP `AsyncChannel`. " {:added "0.0.5"} [req status body] (as-channel req {:on-open (fn [channel] (send! channel { :headers {(HDR-CONTENT-TYPE-N) (HDR-CONTENT-TYPE-V)} :status status :body body }))}) ) (defn find-direct-route "Performs the routes processing (onto bus stops sequences) to identify and return whether a particular interval between two bus stop points given is direct (i.e. contains in any of the routes), or not. Args: routes: A vector containing all available routes. from: The starting bus stop point. to: The ending bus stop point. Returns: `true` if the direct route is found, `false` otherwise. " {:added "0.0.1"} [routes from to] (let [debug-log-enabled (nth @debug-log-enabled-ref 0)] (let [routes-count (count routes)] (try (loop [-routes routes i 0] (when (< i routes-count) (let [route (first -routes)] (if debug-log-enabled (log/debug (+ i 1) (AUX/EQUALS) route) ) (if (.matches route (str (SEQ1-REGEX) from (SEQ2-REGEX))) ; Pinning in the starting bus stop point, if it's found. ; Next, searching for the ending bus stop point ; on the current route, beginning at the pinned point. (let [route-from (subs route (index-of route (str from)))] (if debug-log-enabled (log/debug from (AUX/V-BAR) route-from) ) (if (.matches route-from (str (SEQ1-REGEX) to (SEQ2-REGEX))) (throw (Exception. (TRUE))) )) )) (recur (rest -routes) (inc i))) ) false (catch Exception e (read-string (.getMessage e)) ; <== Like direct = true; break; )))) ) (defn reqhandler "The request handler callback. Gets called when a new incoming HTTP request is received. Args: req: The incoming HTTP request object. Returns: The HTTP status code, response headers, and a body of the response. " {:added "0.0.1"} [req] (let [debug-log-enabled (nth @debug-log-enabled-ref 0)] (let [s (nth @s-ref 0)] ; <== The Unix system logger. (let [method (get req :request-method)] (let [uri (get req :uri )] ; GET /route/direct (if (= method :get) (if (= uri (str (AUX/SLASH) (REST-PREFIX) (AUX/SLASH) (REST-DIRECT))) ; ----------------------------------------------------------------- ; --- Parsing and validating request params - Begin --------------- ; ----------------------------------------------------------------- (let [params0 (get req :query-string)] (let [params (if (nil? params0) {:from (ZERO) :to (ZERO)} (keywordize-keys (try (apply hash-map (split params0 (PARAMS-SEP))) (catch IllegalArgumentException e {:from (ZERO) :to (ZERO)} ))) )] (let [from (get params :from)] (let [to (get params :to )] (if debug-log-enabled (do (log/debug (FROM) (AUX/EQUALS) from (AUX/V-BAR) (TO ) (AUX/EQUALS) to) (.debug s (str (FROM) (AUX/SPACE) (AUX/EQUALS) (AUX/SPACE) from (AUX/SPACE) (AUX/V-BAR ) (AUX/SPACE) (TO ) (AUX/SPACE) (AUX/EQUALS) (AUX/SPACE) to)) )) (let [-from (try (edn/read-string from) (catch NumberFormatException e (ZERO) ))] (let [-to (try (edn/read-string to ) (catch NumberFormatException e (ZERO) ))] (let [is-request-malformed (try (or (< -from 1) (< -to 1)) (catch ClassCastException e true ))] ; ----------------------------------------------------------------- ; --- Parsing and validating request params - End ----------------- ; ----------------------------------------------------------------- (if is-request-malformed (-send-response req (HTTP-400-BAD-REQ) (write-str (hash-map :error (AUX/ERR-REQ-PARAMS-MUST-BE-POSITIVE-INTS)))) ;Performing the routes processing to find out the direct route. (let [direct (if (= -from -to) false (find-direct-route (nth @routes-vector-ref 0) -from -to))] (-send-response req (HTTP-200-OK ) (write-str (hash-map :from -from :to -to :direct direct)))) )))))))) ) ))))) ) (defn startup "Starts up the daemon. Args: args: A list containing the server port number to listen on, as the first element. Returns: The exit code indicating the daemon overall termination status. " {:added "0.0.1"} [args] (let [server-port (nth args 0)] (let [debug-log-enabled (nth args 1)] (let [routes-vector (nth args 2)] ; Starting an STM transaction to alter Refs: ; routes vector and debug log enabler. (dosync (alter debug-log-enabled-ref conj debug-log-enabled) (alter routes-vector-ref conj routes-vector ) ) ; Opening the system logger. ; Calling <syslog.h> openlog(NULL, LOG_CONS | LOG_PID, LOG_DAEMON); (let [cfg (UnixSyslogConfig.)] (.setIdent cfg nil) (.setFacility cfg SyslogIF/FACILITY_DAEMON) (let [s (UnixSyslog.)] (.initialize s SyslogIF/UNIX_SYSLOG cfg) (dosync (alter s-ref conj s)) (let [stop-server (run-server reqhandler {:port server-port})] (log/info (AUX/MSG-SERVER-STARTED) server-port) (.info s (str (AUX/MSG-SERVER-STARTED) (AUX/SPACE) server-port)) (set-break-handler! (fn [_] (log/info (AUX/MSG-SERVER-STOPPED)) (.info s (AUX/MSG-SERVER-STOPPED)) ; Closing the system logger. ; Calling <syslog.h> closelog(); (.shutdown s) (stop-server) ; (System/exit (AUX/EXIT-SUCCESS)) )))))))) ) ; vim:set nu et ts=4 sw=4:
true
; ; src/com/transroutownish/proto/bus/controller.clj ; ============================================================================= ; Urban bus routing microservice prototype (Clojure port). Version 0.15.1 ; ============================================================================= ; A daemon written in Clojure, designed and intended to be run ; as a microservice, implementing a simple urban bus routing prototype. ; ============================================================================= ; Copyright (C) 2021-2022 PI:NAME:<NAME>END_PI) PI:NAME:<NAME>END_PI ; ; (See the LICENSE file at the top of the source tree.) ; (ns com.transroutownish.proto.bus.controller "The controller module of the daemon." (:require [clojure.tools.logging :as log] [clojure.edn :as edn] [clojure.walk :refer [ keywordize-keys ]] [clojure.string :refer [ split index-of ]] [clojure.data.json :refer [ write-str ]] [clojure.repl :refer [ set-break-handler! ]] [org.httpkit.server :refer [ run-server as-channel send! ]] ) (:import [org.graylog2.syslog4j.impl.unix UnixSyslogConfig] [org.graylog2.syslog4j.impl.unix UnixSyslog ] [org.graylog2.syslog4j SyslogIF ] ) (:require [com.transroutownish.proto.bus.helper :as AUX]) ) ; Helper constants. (defmacro REST-PREFIX [] "route" ) (defmacro REST-DIRECT [] "direct") (defmacro FROM [] "from") (defmacro TO [] "to" ) (defmacro HTTP-200-OK [] 200 ) (defmacro HTTP-400-BAD-REQ [] 400 ) (defmacro HDR-CONTENT-TYPE-N [] "content-type" ) (defmacro HDR-CONTENT-TYPE-V [] "application/json") ; Extra helper constants. (defmacro ZERO [] "0") (defmacro PARAMS-SEP [] #"=|&") (defmacro TRUE [] "true") (defmacro SEQ1-REGEX "The regex pattern for the leading part of a bus stops sequence, before the matching element." [] ".*\\s" ) (defmacro SEQ2-REGEX "The regex pattern for the trailing part of a bus stops sequence, after the matching element." [] "\\s.*" ) (def debug-log-enabled-ref "The Ref to the debug logging enabler." (ref []) ) (def routes-vector-ref "The Ref to a vector containing all available routes." (ref []) ) (def s-ref "The Ref to the Unix system logger." (ref []) ) (defn -send-response "Helper function. Used to send the HTTP response back to the client. Args: req: The incoming HTTP request object. status: The HTTP status code. body: The body of the response. Returns: A hash map containing the asynchronous HTTP `AsyncChannel`. " {:added "0.0.5"} [req status body] (as-channel req {:on-open (fn [channel] (send! channel { :headers {(HDR-CONTENT-TYPE-N) (HDR-CONTENT-TYPE-V)} :status status :body body }))}) ) (defn find-direct-route "Performs the routes processing (onto bus stops sequences) to identify and return whether a particular interval between two bus stop points given is direct (i.e. contains in any of the routes), or not. Args: routes: A vector containing all available routes. from: The starting bus stop point. to: The ending bus stop point. Returns: `true` if the direct route is found, `false` otherwise. " {:added "0.0.1"} [routes from to] (let [debug-log-enabled (nth @debug-log-enabled-ref 0)] (let [routes-count (count routes)] (try (loop [-routes routes i 0] (when (< i routes-count) (let [route (first -routes)] (if debug-log-enabled (log/debug (+ i 1) (AUX/EQUALS) route) ) (if (.matches route (str (SEQ1-REGEX) from (SEQ2-REGEX))) ; Pinning in the starting bus stop point, if it's found. ; Next, searching for the ending bus stop point ; on the current route, beginning at the pinned point. (let [route-from (subs route (index-of route (str from)))] (if debug-log-enabled (log/debug from (AUX/V-BAR) route-from) ) (if (.matches route-from (str (SEQ1-REGEX) to (SEQ2-REGEX))) (throw (Exception. (TRUE))) )) )) (recur (rest -routes) (inc i))) ) false (catch Exception e (read-string (.getMessage e)) ; <== Like direct = true; break; )))) ) (defn reqhandler "The request handler callback. Gets called when a new incoming HTTP request is received. Args: req: The incoming HTTP request object. Returns: The HTTP status code, response headers, and a body of the response. " {:added "0.0.1"} [req] (let [debug-log-enabled (nth @debug-log-enabled-ref 0)] (let [s (nth @s-ref 0)] ; <== The Unix system logger. (let [method (get req :request-method)] (let [uri (get req :uri )] ; GET /route/direct (if (= method :get) (if (= uri (str (AUX/SLASH) (REST-PREFIX) (AUX/SLASH) (REST-DIRECT))) ; ----------------------------------------------------------------- ; --- Parsing and validating request params - Begin --------------- ; ----------------------------------------------------------------- (let [params0 (get req :query-string)] (let [params (if (nil? params0) {:from (ZERO) :to (ZERO)} (keywordize-keys (try (apply hash-map (split params0 (PARAMS-SEP))) (catch IllegalArgumentException e {:from (ZERO) :to (ZERO)} ))) )] (let [from (get params :from)] (let [to (get params :to )] (if debug-log-enabled (do (log/debug (FROM) (AUX/EQUALS) from (AUX/V-BAR) (TO ) (AUX/EQUALS) to) (.debug s (str (FROM) (AUX/SPACE) (AUX/EQUALS) (AUX/SPACE) from (AUX/SPACE) (AUX/V-BAR ) (AUX/SPACE) (TO ) (AUX/SPACE) (AUX/EQUALS) (AUX/SPACE) to)) )) (let [-from (try (edn/read-string from) (catch NumberFormatException e (ZERO) ))] (let [-to (try (edn/read-string to ) (catch NumberFormatException e (ZERO) ))] (let [is-request-malformed (try (or (< -from 1) (< -to 1)) (catch ClassCastException e true ))] ; ----------------------------------------------------------------- ; --- Parsing and validating request params - End ----------------- ; ----------------------------------------------------------------- (if is-request-malformed (-send-response req (HTTP-400-BAD-REQ) (write-str (hash-map :error (AUX/ERR-REQ-PARAMS-MUST-BE-POSITIVE-INTS)))) ;Performing the routes processing to find out the direct route. (let [direct (if (= -from -to) false (find-direct-route (nth @routes-vector-ref 0) -from -to))] (-send-response req (HTTP-200-OK ) (write-str (hash-map :from -from :to -to :direct direct)))) )))))))) ) ))))) ) (defn startup "Starts up the daemon. Args: args: A list containing the server port number to listen on, as the first element. Returns: The exit code indicating the daemon overall termination status. " {:added "0.0.1"} [args] (let [server-port (nth args 0)] (let [debug-log-enabled (nth args 1)] (let [routes-vector (nth args 2)] ; Starting an STM transaction to alter Refs: ; routes vector and debug log enabler. (dosync (alter debug-log-enabled-ref conj debug-log-enabled) (alter routes-vector-ref conj routes-vector ) ) ; Opening the system logger. ; Calling <syslog.h> openlog(NULL, LOG_CONS | LOG_PID, LOG_DAEMON); (let [cfg (UnixSyslogConfig.)] (.setIdent cfg nil) (.setFacility cfg SyslogIF/FACILITY_DAEMON) (let [s (UnixSyslog.)] (.initialize s SyslogIF/UNIX_SYSLOG cfg) (dosync (alter s-ref conj s)) (let [stop-server (run-server reqhandler {:port server-port})] (log/info (AUX/MSG-SERVER-STARTED) server-port) (.info s (str (AUX/MSG-SERVER-STARTED) (AUX/SPACE) server-port)) (set-break-handler! (fn [_] (log/info (AUX/MSG-SERVER-STOPPED)) (.info s (AUX/MSG-SERVER-STOPPED)) ; Closing the system logger. ; Calling <syslog.h> closelog(); (.shutdown s) (stop-server) ; (System/exit (AUX/EXIT-SUCCESS)) )))))))) ) ; vim:set nu et ts=4 sw=4:
[ { "context": "st \":\" port \"/\" db)\n :user user\n :password password}))\n\n(defn spec\n []\n (parse-config (cfg/database", "end": 722, "score": 0.9986326098442078, "start": 714, "tag": "PASSWORD", "value": "password" } ]
src/kulu_backend/db.clj
vkrmis/kulu-backend
3
(ns kulu-backend.db (:require [clj-time.coerce :as time-convert] [clj-time.core :as time] [clojure.java.jdbc :as j] [kulu-backend.config :as cfg] [kulu-backend.utils.api :as api-utils] [clojure.tools.logging :as log]) (:import [com.jolbox.bonecp BoneCPDataSource])) (defn parse-config "Parses username/pwd etc. from a DB URL like postgresql://username:password@localhost:5432/kulu_backend_dev" [url] (let [[_ user password host port db] (re-find #"^.*://(.*):(.*)@(.*):(.*)/(.*)$" url)] {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname (str "//" host ":" port "/" db) :user user :password password})) (defn spec [] (parse-config (cfg/database-url))) (def min-pool 3) (def max-pool 6) (defn pool [spec] (let [partitions 3 cpds (doto (BoneCPDataSource.) (.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec))) (.setUsername (:user spec)) (.setPassword (:password spec)) (.setMinConnectionsPerPartition (inc (int (/ min-pool partitions)))) (.setMaxConnectionsPerPartition (inc (int (/ max-pool partitions)))) (.setPartitionCount partitions) (.setStatisticsEnabled true) ;; test connections every 25 mins (default is 240): (.setIdleConnectionTestPeriodInMinutes 25) ;; allow connections to be idle for 3 hours (default is 60 minutes): (.setIdleMaxAgeInMinutes (* 3 60)) (.setConnectionTestStatement "/* ping *\\/ SELECT 1"))] {:datasource cpds})) (def pooled-db (delay (do (log/info "connecting to postgresql with " (spec)) (pool (spec))))) (defn connection [] @pooled-db) (defn exec-transaction [jdbc-fn args] (j/with-db-transaction [conn (connection)] (api-utils/dasherize (api-utils/idiomatize-keys-for-sql #(apply (partial jdbc-fn conn) %1) args)))) (defn query [& args] (exec-transaction j/query args)) ;; TODO: ;; jdbc methods already run in a transaction by default ;; see how we can separate exec-transaction v j/<method> out (defn insert! [table-name & [args & _]] (let [now (time-convert/to-sql-time (time/now))] (exec-transaction j/insert! [table-name (merge {:created_at now :updated_at now} args)]))) (defn exec-nested-transactions [fns] (j/with-db-transaction [conn (connection)] ((apply comp (reverse fns))))) (defn insert-without-timestamps! [table-name & [args]] (exec-transaction j/insert! [table-name args])) (defn update! [table-name set-map where-clause] (let [now (time-convert/to-sql-time (time/now))] (exec-transaction j/update! [table-name (merge {:updated_at now} set-map) where-clause]))) (defn delete! "deletes all records matching the where-clause" [table-name where-clause] (assert (sequential? where-clause) "the where clause must be a sequence") (assert (not (empty? where-clause)) "no clause; attempting to delete the whole table permitted") (try (exec-transaction j/delete! [table-name where-clause]) (catch Exception e (.printStackTrace (.getNextException e)))))
45983
(ns kulu-backend.db (:require [clj-time.coerce :as time-convert] [clj-time.core :as time] [clojure.java.jdbc :as j] [kulu-backend.config :as cfg] [kulu-backend.utils.api :as api-utils] [clojure.tools.logging :as log]) (:import [com.jolbox.bonecp BoneCPDataSource])) (defn parse-config "Parses username/pwd etc. from a DB URL like postgresql://username:password@localhost:5432/kulu_backend_dev" [url] (let [[_ user password host port db] (re-find #"^.*://(.*):(.*)@(.*):(.*)/(.*)$" url)] {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname (str "//" host ":" port "/" db) :user user :password <PASSWORD>})) (defn spec [] (parse-config (cfg/database-url))) (def min-pool 3) (def max-pool 6) (defn pool [spec] (let [partitions 3 cpds (doto (BoneCPDataSource.) (.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec))) (.setUsername (:user spec)) (.setPassword (:password spec)) (.setMinConnectionsPerPartition (inc (int (/ min-pool partitions)))) (.setMaxConnectionsPerPartition (inc (int (/ max-pool partitions)))) (.setPartitionCount partitions) (.setStatisticsEnabled true) ;; test connections every 25 mins (default is 240): (.setIdleConnectionTestPeriodInMinutes 25) ;; allow connections to be idle for 3 hours (default is 60 minutes): (.setIdleMaxAgeInMinutes (* 3 60)) (.setConnectionTestStatement "/* ping *\\/ SELECT 1"))] {:datasource cpds})) (def pooled-db (delay (do (log/info "connecting to postgresql with " (spec)) (pool (spec))))) (defn connection [] @pooled-db) (defn exec-transaction [jdbc-fn args] (j/with-db-transaction [conn (connection)] (api-utils/dasherize (api-utils/idiomatize-keys-for-sql #(apply (partial jdbc-fn conn) %1) args)))) (defn query [& args] (exec-transaction j/query args)) ;; TODO: ;; jdbc methods already run in a transaction by default ;; see how we can separate exec-transaction v j/<method> out (defn insert! [table-name & [args & _]] (let [now (time-convert/to-sql-time (time/now))] (exec-transaction j/insert! [table-name (merge {:created_at now :updated_at now} args)]))) (defn exec-nested-transactions [fns] (j/with-db-transaction [conn (connection)] ((apply comp (reverse fns))))) (defn insert-without-timestamps! [table-name & [args]] (exec-transaction j/insert! [table-name args])) (defn update! [table-name set-map where-clause] (let [now (time-convert/to-sql-time (time/now))] (exec-transaction j/update! [table-name (merge {:updated_at now} set-map) where-clause]))) (defn delete! "deletes all records matching the where-clause" [table-name where-clause] (assert (sequential? where-clause) "the where clause must be a sequence") (assert (not (empty? where-clause)) "no clause; attempting to delete the whole table permitted") (try (exec-transaction j/delete! [table-name where-clause]) (catch Exception e (.printStackTrace (.getNextException e)))))
true
(ns kulu-backend.db (:require [clj-time.coerce :as time-convert] [clj-time.core :as time] [clojure.java.jdbc :as j] [kulu-backend.config :as cfg] [kulu-backend.utils.api :as api-utils] [clojure.tools.logging :as log]) (:import [com.jolbox.bonecp BoneCPDataSource])) (defn parse-config "Parses username/pwd etc. from a DB URL like postgresql://username:password@localhost:5432/kulu_backend_dev" [url] (let [[_ user password host port db] (re-find #"^.*://(.*):(.*)@(.*):(.*)/(.*)$" url)] {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname (str "//" host ":" port "/" db) :user user :password PI:PASSWORD:<PASSWORD>END_PI})) (defn spec [] (parse-config (cfg/database-url))) (def min-pool 3) (def max-pool 6) (defn pool [spec] (let [partitions 3 cpds (doto (BoneCPDataSource.) (.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec))) (.setUsername (:user spec)) (.setPassword (:password spec)) (.setMinConnectionsPerPartition (inc (int (/ min-pool partitions)))) (.setMaxConnectionsPerPartition (inc (int (/ max-pool partitions)))) (.setPartitionCount partitions) (.setStatisticsEnabled true) ;; test connections every 25 mins (default is 240): (.setIdleConnectionTestPeriodInMinutes 25) ;; allow connections to be idle for 3 hours (default is 60 minutes): (.setIdleMaxAgeInMinutes (* 3 60)) (.setConnectionTestStatement "/* ping *\\/ SELECT 1"))] {:datasource cpds})) (def pooled-db (delay (do (log/info "connecting to postgresql with " (spec)) (pool (spec))))) (defn connection [] @pooled-db) (defn exec-transaction [jdbc-fn args] (j/with-db-transaction [conn (connection)] (api-utils/dasherize (api-utils/idiomatize-keys-for-sql #(apply (partial jdbc-fn conn) %1) args)))) (defn query [& args] (exec-transaction j/query args)) ;; TODO: ;; jdbc methods already run in a transaction by default ;; see how we can separate exec-transaction v j/<method> out (defn insert! [table-name & [args & _]] (let [now (time-convert/to-sql-time (time/now))] (exec-transaction j/insert! [table-name (merge {:created_at now :updated_at now} args)]))) (defn exec-nested-transactions [fns] (j/with-db-transaction [conn (connection)] ((apply comp (reverse fns))))) (defn insert-without-timestamps! [table-name & [args]] (exec-transaction j/insert! [table-name args])) (defn update! [table-name set-map where-clause] (let [now (time-convert/to-sql-time (time/now))] (exec-transaction j/update! [table-name (merge {:updated_at now} set-map) where-clause]))) (defn delete! "deletes all records matching the where-clause" [table-name where-clause] (assert (sequential? where-clause) "the where clause must be a sequence") (assert (not (empty? where-clause)) "no clause; attempting to delete the whole table permitted") (try (exec-transaction j/delete! [table-name where-clause]) (catch Exception e (.printStackTrace (.getNextException e)))))
[ { "context": "s causal.core\n \"The core Cause API.\"\n {:author \"Chris Smothers\"}\n (:refer-clojure :exclude [list map merge])\n ", "end": 66, "score": 0.9998811483383179, "start": 52, "tag": "NAME", "value": "Chris Smothers" } ]
src/causal/core.cljc
smothers/causal-tree
114
(ns causal.core "The core Cause API." {:author "Chris Smothers"} (:refer-clojure :exclude [list map merge]) (:require [causal.collections.shared :as s] [causal.util :refer [redef] :refer-macros [redef]] [causal.protocols :as proto] [causal.collections.list :as c.list] [causal.collections.map :as c.map] [causal.base.core :as c.base])) ; Special values have special effects on causal collections. ; NOTE: Special values do not compose with one another. ; E.g. applying hide to a hide will not equal show. (def ^{:doc "Insert this value to hide a cause."} hide :causal/hide) (def ^{:doc "The id of the first node in every causal-list. To insert a node at the front, set root-id as the cause."} root-id s/root-id) ; Causal base. This is what you want 99% of the time. (redef base c.base/new-causal-base) (redef transact proto/transact) (redef undo proto/undo) (redef redo proto/redo) (redef ref? c.base/ref?) (redef uuid->ref c.base/uuid->ref) (redef get-collection proto/get-collection) (redef set-site-id proto/set-site-id) (redef set-uuid proto/set-uuid) ;;;;;;;;;;;; Other Stuff ;;;;;;;;;;;; ; Causal meta attributes (redef get-uuid proto/get-uuid) (redef get-ts proto/get-ts) (redef get-site-id proto/get-site-id) ; Nodes are the building blocks of causal data types. (redef node s/new-node) ; Causal collection types are convergent and EDN-like. (redef list c.list/new-causal-list) (redef map c.map/new-causal-map) ; Causal collection functions (redef insert proto/insert) (redef append proto/append) (redef weft proto/weft) (redef merge proto/causal-merge) (redef get-weave proto/get-weave) (redef get-nodes proto/get-nodes) ; Causal conversion (redef causal->edn s/causal->edn)
33957
(ns causal.core "The core Cause API." {:author "<NAME>"} (:refer-clojure :exclude [list map merge]) (:require [causal.collections.shared :as s] [causal.util :refer [redef] :refer-macros [redef]] [causal.protocols :as proto] [causal.collections.list :as c.list] [causal.collections.map :as c.map] [causal.base.core :as c.base])) ; Special values have special effects on causal collections. ; NOTE: Special values do not compose with one another. ; E.g. applying hide to a hide will not equal show. (def ^{:doc "Insert this value to hide a cause."} hide :causal/hide) (def ^{:doc "The id of the first node in every causal-list. To insert a node at the front, set root-id as the cause."} root-id s/root-id) ; Causal base. This is what you want 99% of the time. (redef base c.base/new-causal-base) (redef transact proto/transact) (redef undo proto/undo) (redef redo proto/redo) (redef ref? c.base/ref?) (redef uuid->ref c.base/uuid->ref) (redef get-collection proto/get-collection) (redef set-site-id proto/set-site-id) (redef set-uuid proto/set-uuid) ;;;;;;;;;;;; Other Stuff ;;;;;;;;;;;; ; Causal meta attributes (redef get-uuid proto/get-uuid) (redef get-ts proto/get-ts) (redef get-site-id proto/get-site-id) ; Nodes are the building blocks of causal data types. (redef node s/new-node) ; Causal collection types are convergent and EDN-like. (redef list c.list/new-causal-list) (redef map c.map/new-causal-map) ; Causal collection functions (redef insert proto/insert) (redef append proto/append) (redef weft proto/weft) (redef merge proto/causal-merge) (redef get-weave proto/get-weave) (redef get-nodes proto/get-nodes) ; Causal conversion (redef causal->edn s/causal->edn)
true
(ns causal.core "The core Cause API." {:author "PI:NAME:<NAME>END_PI"} (:refer-clojure :exclude [list map merge]) (:require [causal.collections.shared :as s] [causal.util :refer [redef] :refer-macros [redef]] [causal.protocols :as proto] [causal.collections.list :as c.list] [causal.collections.map :as c.map] [causal.base.core :as c.base])) ; Special values have special effects on causal collections. ; NOTE: Special values do not compose with one another. ; E.g. applying hide to a hide will not equal show. (def ^{:doc "Insert this value to hide a cause."} hide :causal/hide) (def ^{:doc "The id of the first node in every causal-list. To insert a node at the front, set root-id as the cause."} root-id s/root-id) ; Causal base. This is what you want 99% of the time. (redef base c.base/new-causal-base) (redef transact proto/transact) (redef undo proto/undo) (redef redo proto/redo) (redef ref? c.base/ref?) (redef uuid->ref c.base/uuid->ref) (redef get-collection proto/get-collection) (redef set-site-id proto/set-site-id) (redef set-uuid proto/set-uuid) ;;;;;;;;;;;; Other Stuff ;;;;;;;;;;;; ; Causal meta attributes (redef get-uuid proto/get-uuid) (redef get-ts proto/get-ts) (redef get-site-id proto/get-site-id) ; Nodes are the building blocks of causal data types. (redef node s/new-node) ; Causal collection types are convergent and EDN-like. (redef list c.list/new-causal-list) (redef map c.map/new-causal-map) ; Causal collection functions (redef insert proto/insert) (redef append proto/append) (redef weft proto/weft) (redef merge proto/causal-merge) (redef get-weave proto/get-weave) (redef get-nodes proto/get-nodes) ; Causal conversion (redef causal->edn s/causal->edn)
[ { "context": " for clojure projects.\"\n :url \"http://github.com/iotemplates/clojure-web-ring\"\n :license {:name \"Apache Licen", "end": 139, "score": 0.999549150466919, "start": 128, "tag": "USERNAME", "value": "iotemplates" }, { "context": "0\"\n :year 2020\n :key \"apache-2.0\"}\n :dependencies [[org.clojure/clojure \"1.10.1\"]", "end": 311, "score": 0.6425117254257202, "start": 308, "tag": "KEY", "value": "2.0" } ]
project.clj
iotemplates/clojure-web-ring
0
(defproject clojure-web-ring "0.1.0-SNAPSHOT" :description "A basic template for clojure projects." :url "http://github.com/iotemplates/clojure-web-ring" :license {:name "Apache License 2.0" :url "https://www.apache.org/licenses/LICENSE-2.0" :year 2020 :key "apache-2.0"} :dependencies [[org.clojure/clojure "1.10.1"] [ring/ring-core "1.7.1"] [ring/ring-jetty-adapter "1.7.1"] ] :main ^:skip-aot clojure-web-ring.core :target-path "target/%s" :profiles {:test {:dependencies [[clj-http "3.12.3"]]} :uberjar {:aot :all :jvm-opts ["-Dclojure.compiler.direct-linking=true"]}})
119252
(defproject clojure-web-ring "0.1.0-SNAPSHOT" :description "A basic template for clojure projects." :url "http://github.com/iotemplates/clojure-web-ring" :license {:name "Apache License 2.0" :url "https://www.apache.org/licenses/LICENSE-2.0" :year 2020 :key "apache-<KEY>"} :dependencies [[org.clojure/clojure "1.10.1"] [ring/ring-core "1.7.1"] [ring/ring-jetty-adapter "1.7.1"] ] :main ^:skip-aot clojure-web-ring.core :target-path "target/%s" :profiles {:test {:dependencies [[clj-http "3.12.3"]]} :uberjar {:aot :all :jvm-opts ["-Dclojure.compiler.direct-linking=true"]}})
true
(defproject clojure-web-ring "0.1.0-SNAPSHOT" :description "A basic template for clojure projects." :url "http://github.com/iotemplates/clojure-web-ring" :license {:name "Apache License 2.0" :url "https://www.apache.org/licenses/LICENSE-2.0" :year 2020 :key "apache-PI:KEY:<KEY>END_PI"} :dependencies [[org.clojure/clojure "1.10.1"] [ring/ring-core "1.7.1"] [ring/ring-jetty-adapter "1.7.1"] ] :main ^:skip-aot clojure-web-ring.core :target-path "target/%s" :profiles {:test {:dependencies [[clj-http "3.12.3"]]} :uberjar {:aot :all :jvm-opts ["-Dclojure.compiler.direct-linking=true"]}})
[ { "context": "***********\n\n(def BC_Fiume_Flumendosa\n {:bacino \"Fiume Flumendosa\"\n :name nil\n :monte [{:name :F09\n ", "end": 8622, "score": 0.9934422969818115, "start": 8606, "tag": "NAME", "value": "Fiume Flumendosa" } ]
src/bacidro/core.clj
laingit/bacidro
0
(ns bacidro.core (:require [clojure.pprint :as pp] [bacidro.db-access :as my-db-access] [bacidro.db-access :as my-db-file])) (defn- find-loop [table-obj] (let [find-parent (fn [id] (let [parent (get-in table-obj [id :valle])] parent)) run (fn trova-idrometri-a-valle [acc id] (let [{:keys [up loop]} acc parent (find-parent id) new-acc (if (nil? id) {:up up :loop loop} {:up (conj up id) :loop loop})] (if (= parent nil) new-acc (let [gia-trovati (set up)] (if (gia-trovati id) {:up up :loop id} (trova-idrometri-a-valle new-acc parent))) ))) results (map (fn [[k {:keys [tipo]}]] (let [{:keys [up loop]} (run {:up [] :loop nil} k)] {:id k :tipo tipo :up up :loop loop})) table-obj) errori (filter (fn [{:keys [id loop]}] (= id loop)) results) errori-monte (filter (fn [{:keys [tipo]}] (= tipo :monte)) errori) errori-1 (map (fn [{:keys [up] :as all}] (assoc all :set (set up))) errori) gruppo-errori (group-by :set errori-1) ] {:all results :errori-1 errori-1 :errori-monte errori-monte :gruppo-errori gruppo-errori} )) (defn main [table settore] (let [table-new (letfn [(trasforma-new [{:keys [id tipo valle]}] {:id id :tipo tipo :valle valle})] (map trasforma-new table)) table-obj (letfn [(seq-to-obj [{:keys [id tipo valle]}] {id {:tipo tipo :valle valle}})] (->> table-new (map seq-to-obj) (into {}))) group-by-children (group-by :valle table-new) idrometri-a-monte (letfn [(estrai-da-children [[idrometro children]] (let [valori (map (fn [{:keys [id]}] {:a-monte id}) children)] {idrometro (into [] valori)}))] (->> group-by-children (map estrai-da-children) (into {}))) report-nodi (letfn [(conta-nodi [[k v]] {k (count v)})] (->> idrometri-a-monte (map conta-nodi) (into {}))) ] {:settore settore :table-new table-new :table-obj table-obj :group-by-chidren group-by-children :rootName nil :idrometri-a-monte idrometri-a-monte :report-nodi report-nodi})) (def idro-data (my-db-access/get-idro-data)) idro-data (group-by :settore idro-data) (def GLOBAL-ELABORATI (->> idro-data (group-by :settore) (map (fn [[settore table]] {settore (main table settore)})) (into {}))) (def GLOBAL-TEST-ERRORI (->> GLOBAL-ELABORATI (map (fn [[settore table]] {settore (find-loop (:table-obj table))})) (into {}))) (def GLOBAL-ISOLA-ERRORI (->> GLOBAL-TEST-ERRORI (map (fn [[settore errori]] (let [errori-settore (:gruppo-errori errori)] {settore (keys errori-settore)}))) (into {}))) (def GLOBAL-REPORT {:errori (filter (fn [[settore err]] (not (nil? err))) GLOBAL-ISOLA-ERRORI) :settori (count GLOBAL-ISOLA-ERRORI) :lista-ok (->> GLOBAL-ISOLA-ERRORI (filter (fn [[settore err]] (nil? err))) (map first)) }) (pp/pprint GLOBAL-ELABORATI) (pp/pprint GLOBAL-TEST-ERRORI) (pp/pprint GLOBAL-REPORT) (find GLOBAL-ELABORATI "CEDRINO") (find GLOBAL-TEST-ERRORI "TEMO") GLOBAL-ELABORATI GLOBAL-TEST-ERRORI GLOBAL-REPORT #_(defn build-tree [idrometri-a-monte id-root acc valore] (let [children (get idrometri-a-monte id-root) monte (if (nil? children) [] (->> (map (fn [{:keys [a-monte]}] (let [child {:name a-monte :valore valore :monte []} new-acc (conj acc child)] (build-tree idrometri-a-monte a-monte new-acc (+ valore 1)))) children) (into []))) ] {:name id-root :valore valore :monte monte})) (defn build-tree-bis [{:keys [idrometri-a-monte contribuisce-a id-root acc livello tree-name sub-val]}] (let [children (get idrometri-a-monte id-root) n-child (count children) monte (if (nil? children) acc (->> (map (fn [{:keys [a-monte]} sub-val-children] (build-tree-bis {:idrometri-a-monte idrometri-a-monte :contribuisce-a (conj contribuisce-a id-root) :id-root a-monte :acc acc :livello (+ livello 1) :tree-name (str tree-name "." sub-val-children) :sub-val sub-val-children})) children (range 1 1000000)) (into []))) ] {:name id-root :contribuisce-a (->> (conj contribuisce-a id-root) (into [])) :livello livello :tree-name tree-name :sub-val sub-val :n-child n-child :monte monte})) ;; String -> ;; input GLOBALE : GLOBAL-ELABORATI ;; input parametro : settore (defn sx [nome-settore] (let [dati-settore (GLOBAL-ELABORATI nome-settore) {:keys [idrometri-a-monte]} dati-settore root (idrometri-a-monte nil) errore (if (= (count root) 1) false true) ;solo un elemento root consentito id-root (-> root first :a-monte)] {:settore nome-settore :errore errore :look-in-root-if-error-true root :id-root id-root :idrometri-a-monte idrometri-a-monte})) (sx "CHIA") (defn- my-tree [nome-settore] (let [elabora-settore (sx nome-settore) {:keys [settore errore look-in-root-if-error-true id-root idrometri-a-monte]} elabora-settore] (if errore (print settore look-in-root-if-error-true) (build-tree-bis {:idrometri-a-monte idrometri-a-monte :id-root id-root :contribuisce-a () :acc [] :livello 1 :tree-name "1" :sub-val 1})))) (my-tree "COGHINAS") (defn- trova-tutti [t-obj id acc] (let [children (get t-obj id) monte (if (nil? children) acc (->> (mapcat (fn [{:keys [a-monte]}] (trova-tutti t-obj a-monte acc)) children) (into []))) ] (conj monte id))) (defn- elabora-settore [[nome-settore {:keys [table-obj idrometri-a-monte]}]] (let [mappa-parti (->> table-obj (map (fn [[key-idro _]] {key-idro (trova-tutti idrometri-a-monte key-idro [])})) (into {}))] {:settore nome-settore :mappa-parti mappa-parti})) (defn crea-record-tabella-parti-idro [{:keys [settore mappa-parti]}] (mapcat (fn [[k v]] (for [vx v] {:settore settore :link_id_geo vx :to_dissolve k})) mappa-parti)) ;; test singolo (-> GLOBAL-ELABORATI (find "FLUMENDOSA") elabora-settore crea-record-tabella-parti-idro) (def new-records-TABELLA-PARTI-IDRO (->> GLOBAL-ELABORATI (map elabora-settore) (mapcat crea-record-tabella-parti-idro))) (my-db-access/write-new-records new-records-TABELLA-PARTI-IDRO) ;; SCRIVE NELLA TABELLA ACCESS ******************* (def BC_Fiume_Flumendosa {:bacino "Fiume Flumendosa" :name nil :monte [{:name :F09 :tipo :base :monte [{:name :F21 :tipo :mezzo :monte [{:name :F42 :monte [{:name :F10 :monte [{:name :L6 :monte []}]} {:name :F34 :monte [{:name :L23 :monte []} {:name :L19 :monte [{:nome :F70 :monte [{:name :L11 :monte []} {:name :L10 :monte []}] }] }] }] }] }] } {:name :F36, :tipo :monte, :monte []} ]})
112374
(ns bacidro.core (:require [clojure.pprint :as pp] [bacidro.db-access :as my-db-access] [bacidro.db-access :as my-db-file])) (defn- find-loop [table-obj] (let [find-parent (fn [id] (let [parent (get-in table-obj [id :valle])] parent)) run (fn trova-idrometri-a-valle [acc id] (let [{:keys [up loop]} acc parent (find-parent id) new-acc (if (nil? id) {:up up :loop loop} {:up (conj up id) :loop loop})] (if (= parent nil) new-acc (let [gia-trovati (set up)] (if (gia-trovati id) {:up up :loop id} (trova-idrometri-a-valle new-acc parent))) ))) results (map (fn [[k {:keys [tipo]}]] (let [{:keys [up loop]} (run {:up [] :loop nil} k)] {:id k :tipo tipo :up up :loop loop})) table-obj) errori (filter (fn [{:keys [id loop]}] (= id loop)) results) errori-monte (filter (fn [{:keys [tipo]}] (= tipo :monte)) errori) errori-1 (map (fn [{:keys [up] :as all}] (assoc all :set (set up))) errori) gruppo-errori (group-by :set errori-1) ] {:all results :errori-1 errori-1 :errori-monte errori-monte :gruppo-errori gruppo-errori} )) (defn main [table settore] (let [table-new (letfn [(trasforma-new [{:keys [id tipo valle]}] {:id id :tipo tipo :valle valle})] (map trasforma-new table)) table-obj (letfn [(seq-to-obj [{:keys [id tipo valle]}] {id {:tipo tipo :valle valle}})] (->> table-new (map seq-to-obj) (into {}))) group-by-children (group-by :valle table-new) idrometri-a-monte (letfn [(estrai-da-children [[idrometro children]] (let [valori (map (fn [{:keys [id]}] {:a-monte id}) children)] {idrometro (into [] valori)}))] (->> group-by-children (map estrai-da-children) (into {}))) report-nodi (letfn [(conta-nodi [[k v]] {k (count v)})] (->> idrometri-a-monte (map conta-nodi) (into {}))) ] {:settore settore :table-new table-new :table-obj table-obj :group-by-chidren group-by-children :rootName nil :idrometri-a-monte idrometri-a-monte :report-nodi report-nodi})) (def idro-data (my-db-access/get-idro-data)) idro-data (group-by :settore idro-data) (def GLOBAL-ELABORATI (->> idro-data (group-by :settore) (map (fn [[settore table]] {settore (main table settore)})) (into {}))) (def GLOBAL-TEST-ERRORI (->> GLOBAL-ELABORATI (map (fn [[settore table]] {settore (find-loop (:table-obj table))})) (into {}))) (def GLOBAL-ISOLA-ERRORI (->> GLOBAL-TEST-ERRORI (map (fn [[settore errori]] (let [errori-settore (:gruppo-errori errori)] {settore (keys errori-settore)}))) (into {}))) (def GLOBAL-REPORT {:errori (filter (fn [[settore err]] (not (nil? err))) GLOBAL-ISOLA-ERRORI) :settori (count GLOBAL-ISOLA-ERRORI) :lista-ok (->> GLOBAL-ISOLA-ERRORI (filter (fn [[settore err]] (nil? err))) (map first)) }) (pp/pprint GLOBAL-ELABORATI) (pp/pprint GLOBAL-TEST-ERRORI) (pp/pprint GLOBAL-REPORT) (find GLOBAL-ELABORATI "CEDRINO") (find GLOBAL-TEST-ERRORI "TEMO") GLOBAL-ELABORATI GLOBAL-TEST-ERRORI GLOBAL-REPORT #_(defn build-tree [idrometri-a-monte id-root acc valore] (let [children (get idrometri-a-monte id-root) monte (if (nil? children) [] (->> (map (fn [{:keys [a-monte]}] (let [child {:name a-monte :valore valore :monte []} new-acc (conj acc child)] (build-tree idrometri-a-monte a-monte new-acc (+ valore 1)))) children) (into []))) ] {:name id-root :valore valore :monte monte})) (defn build-tree-bis [{:keys [idrometri-a-monte contribuisce-a id-root acc livello tree-name sub-val]}] (let [children (get idrometri-a-monte id-root) n-child (count children) monte (if (nil? children) acc (->> (map (fn [{:keys [a-monte]} sub-val-children] (build-tree-bis {:idrometri-a-monte idrometri-a-monte :contribuisce-a (conj contribuisce-a id-root) :id-root a-monte :acc acc :livello (+ livello 1) :tree-name (str tree-name "." sub-val-children) :sub-val sub-val-children})) children (range 1 1000000)) (into []))) ] {:name id-root :contribuisce-a (->> (conj contribuisce-a id-root) (into [])) :livello livello :tree-name tree-name :sub-val sub-val :n-child n-child :monte monte})) ;; String -> ;; input GLOBALE : GLOBAL-ELABORATI ;; input parametro : settore (defn sx [nome-settore] (let [dati-settore (GLOBAL-ELABORATI nome-settore) {:keys [idrometri-a-monte]} dati-settore root (idrometri-a-monte nil) errore (if (= (count root) 1) false true) ;solo un elemento root consentito id-root (-> root first :a-monte)] {:settore nome-settore :errore errore :look-in-root-if-error-true root :id-root id-root :idrometri-a-monte idrometri-a-monte})) (sx "CHIA") (defn- my-tree [nome-settore] (let [elabora-settore (sx nome-settore) {:keys [settore errore look-in-root-if-error-true id-root idrometri-a-monte]} elabora-settore] (if errore (print settore look-in-root-if-error-true) (build-tree-bis {:idrometri-a-monte idrometri-a-monte :id-root id-root :contribuisce-a () :acc [] :livello 1 :tree-name "1" :sub-val 1})))) (my-tree "COGHINAS") (defn- trova-tutti [t-obj id acc] (let [children (get t-obj id) monte (if (nil? children) acc (->> (mapcat (fn [{:keys [a-monte]}] (trova-tutti t-obj a-monte acc)) children) (into []))) ] (conj monte id))) (defn- elabora-settore [[nome-settore {:keys [table-obj idrometri-a-monte]}]] (let [mappa-parti (->> table-obj (map (fn [[key-idro _]] {key-idro (trova-tutti idrometri-a-monte key-idro [])})) (into {}))] {:settore nome-settore :mappa-parti mappa-parti})) (defn crea-record-tabella-parti-idro [{:keys [settore mappa-parti]}] (mapcat (fn [[k v]] (for [vx v] {:settore settore :link_id_geo vx :to_dissolve k})) mappa-parti)) ;; test singolo (-> GLOBAL-ELABORATI (find "FLUMENDOSA") elabora-settore crea-record-tabella-parti-idro) (def new-records-TABELLA-PARTI-IDRO (->> GLOBAL-ELABORATI (map elabora-settore) (mapcat crea-record-tabella-parti-idro))) (my-db-access/write-new-records new-records-TABELLA-PARTI-IDRO) ;; SCRIVE NELLA TABELLA ACCESS ******************* (def BC_Fiume_Flumendosa {:bacino "<NAME>" :name nil :monte [{:name :F09 :tipo :base :monte [{:name :F21 :tipo :mezzo :monte [{:name :F42 :monte [{:name :F10 :monte [{:name :L6 :monte []}]} {:name :F34 :monte [{:name :L23 :monte []} {:name :L19 :monte [{:nome :F70 :monte [{:name :L11 :monte []} {:name :L10 :monte []}] }] }] }] }] }] } {:name :F36, :tipo :monte, :monte []} ]})
true
(ns bacidro.core (:require [clojure.pprint :as pp] [bacidro.db-access :as my-db-access] [bacidro.db-access :as my-db-file])) (defn- find-loop [table-obj] (let [find-parent (fn [id] (let [parent (get-in table-obj [id :valle])] parent)) run (fn trova-idrometri-a-valle [acc id] (let [{:keys [up loop]} acc parent (find-parent id) new-acc (if (nil? id) {:up up :loop loop} {:up (conj up id) :loop loop})] (if (= parent nil) new-acc (let [gia-trovati (set up)] (if (gia-trovati id) {:up up :loop id} (trova-idrometri-a-valle new-acc parent))) ))) results (map (fn [[k {:keys [tipo]}]] (let [{:keys [up loop]} (run {:up [] :loop nil} k)] {:id k :tipo tipo :up up :loop loop})) table-obj) errori (filter (fn [{:keys [id loop]}] (= id loop)) results) errori-monte (filter (fn [{:keys [tipo]}] (= tipo :monte)) errori) errori-1 (map (fn [{:keys [up] :as all}] (assoc all :set (set up))) errori) gruppo-errori (group-by :set errori-1) ] {:all results :errori-1 errori-1 :errori-monte errori-monte :gruppo-errori gruppo-errori} )) (defn main [table settore] (let [table-new (letfn [(trasforma-new [{:keys [id tipo valle]}] {:id id :tipo tipo :valle valle})] (map trasforma-new table)) table-obj (letfn [(seq-to-obj [{:keys [id tipo valle]}] {id {:tipo tipo :valle valle}})] (->> table-new (map seq-to-obj) (into {}))) group-by-children (group-by :valle table-new) idrometri-a-monte (letfn [(estrai-da-children [[idrometro children]] (let [valori (map (fn [{:keys [id]}] {:a-monte id}) children)] {idrometro (into [] valori)}))] (->> group-by-children (map estrai-da-children) (into {}))) report-nodi (letfn [(conta-nodi [[k v]] {k (count v)})] (->> idrometri-a-monte (map conta-nodi) (into {}))) ] {:settore settore :table-new table-new :table-obj table-obj :group-by-chidren group-by-children :rootName nil :idrometri-a-monte idrometri-a-monte :report-nodi report-nodi})) (def idro-data (my-db-access/get-idro-data)) idro-data (group-by :settore idro-data) (def GLOBAL-ELABORATI (->> idro-data (group-by :settore) (map (fn [[settore table]] {settore (main table settore)})) (into {}))) (def GLOBAL-TEST-ERRORI (->> GLOBAL-ELABORATI (map (fn [[settore table]] {settore (find-loop (:table-obj table))})) (into {}))) (def GLOBAL-ISOLA-ERRORI (->> GLOBAL-TEST-ERRORI (map (fn [[settore errori]] (let [errori-settore (:gruppo-errori errori)] {settore (keys errori-settore)}))) (into {}))) (def GLOBAL-REPORT {:errori (filter (fn [[settore err]] (not (nil? err))) GLOBAL-ISOLA-ERRORI) :settori (count GLOBAL-ISOLA-ERRORI) :lista-ok (->> GLOBAL-ISOLA-ERRORI (filter (fn [[settore err]] (nil? err))) (map first)) }) (pp/pprint GLOBAL-ELABORATI) (pp/pprint GLOBAL-TEST-ERRORI) (pp/pprint GLOBAL-REPORT) (find GLOBAL-ELABORATI "CEDRINO") (find GLOBAL-TEST-ERRORI "TEMO") GLOBAL-ELABORATI GLOBAL-TEST-ERRORI GLOBAL-REPORT #_(defn build-tree [idrometri-a-monte id-root acc valore] (let [children (get idrometri-a-monte id-root) monte (if (nil? children) [] (->> (map (fn [{:keys [a-monte]}] (let [child {:name a-monte :valore valore :monte []} new-acc (conj acc child)] (build-tree idrometri-a-monte a-monte new-acc (+ valore 1)))) children) (into []))) ] {:name id-root :valore valore :monte monte})) (defn build-tree-bis [{:keys [idrometri-a-monte contribuisce-a id-root acc livello tree-name sub-val]}] (let [children (get idrometri-a-monte id-root) n-child (count children) monte (if (nil? children) acc (->> (map (fn [{:keys [a-monte]} sub-val-children] (build-tree-bis {:idrometri-a-monte idrometri-a-monte :contribuisce-a (conj contribuisce-a id-root) :id-root a-monte :acc acc :livello (+ livello 1) :tree-name (str tree-name "." sub-val-children) :sub-val sub-val-children})) children (range 1 1000000)) (into []))) ] {:name id-root :contribuisce-a (->> (conj contribuisce-a id-root) (into [])) :livello livello :tree-name tree-name :sub-val sub-val :n-child n-child :monte monte})) ;; String -> ;; input GLOBALE : GLOBAL-ELABORATI ;; input parametro : settore (defn sx [nome-settore] (let [dati-settore (GLOBAL-ELABORATI nome-settore) {:keys [idrometri-a-monte]} dati-settore root (idrometri-a-monte nil) errore (if (= (count root) 1) false true) ;solo un elemento root consentito id-root (-> root first :a-monte)] {:settore nome-settore :errore errore :look-in-root-if-error-true root :id-root id-root :idrometri-a-monte idrometri-a-monte})) (sx "CHIA") (defn- my-tree [nome-settore] (let [elabora-settore (sx nome-settore) {:keys [settore errore look-in-root-if-error-true id-root idrometri-a-monte]} elabora-settore] (if errore (print settore look-in-root-if-error-true) (build-tree-bis {:idrometri-a-monte idrometri-a-monte :id-root id-root :contribuisce-a () :acc [] :livello 1 :tree-name "1" :sub-val 1})))) (my-tree "COGHINAS") (defn- trova-tutti [t-obj id acc] (let [children (get t-obj id) monte (if (nil? children) acc (->> (mapcat (fn [{:keys [a-monte]}] (trova-tutti t-obj a-monte acc)) children) (into []))) ] (conj monte id))) (defn- elabora-settore [[nome-settore {:keys [table-obj idrometri-a-monte]}]] (let [mappa-parti (->> table-obj (map (fn [[key-idro _]] {key-idro (trova-tutti idrometri-a-monte key-idro [])})) (into {}))] {:settore nome-settore :mappa-parti mappa-parti})) (defn crea-record-tabella-parti-idro [{:keys [settore mappa-parti]}] (mapcat (fn [[k v]] (for [vx v] {:settore settore :link_id_geo vx :to_dissolve k})) mappa-parti)) ;; test singolo (-> GLOBAL-ELABORATI (find "FLUMENDOSA") elabora-settore crea-record-tabella-parti-idro) (def new-records-TABELLA-PARTI-IDRO (->> GLOBAL-ELABORATI (map elabora-settore) (mapcat crea-record-tabella-parti-idro))) (my-db-access/write-new-records new-records-TABELLA-PARTI-IDRO) ;; SCRIVE NELLA TABELLA ACCESS ******************* (def BC_Fiume_Flumendosa {:bacino "PI:NAME:<NAME>END_PI" :name nil :monte [{:name :F09 :tipo :base :monte [{:name :F21 :tipo :mezzo :monte [{:name :F42 :monte [{:name :F10 :monte [{:name :L6 :monte []}]} {:name :F34 :monte [{:name :L23 :monte []} {:name :L19 :monte [{:nome :F70 :monte [{:name :L11 :monte []} {:name :L10 :monte []}] }] }] }] }] }] } {:name :F36, :tipo :monte, :monte []} ]})
[ { "context": "rends for a single name > (view-births-by-name [\"Harry\"]) ;\n;; To view trends for multiple names > (vi", "end": 5665, "score": 0.9998371601104736, "start": 5660, "tag": "NAME", "value": "Harry" }, { "context": "rends for multiple names > (view-births-by-name [\"Harry\" \"Mary\"]) ;\n;;\n(defn view-births-by-name [cnames ", "end": 5740, "score": 0.9998383522033691, "start": 5735, "tag": "NAME", "value": "Harry" }, { "context": "r multiple names > (view-births-by-name [\"Harry\" \"Mary\"]) ;\n;;\n(defn view-births-by-name [cnames namedat", "end": 5747, "score": 0.9998053908348083, "start": 5743, "tag": "NAME", "value": "Mary" }, { "context": "o be saved.\n;;\n;; Example: (save-births-by-name [\"Harry\" \"John\"] \"harry-john.png\")\n;;\n(defn save-births-b", "end": 6068, "score": 0.9998403787612915, "start": 6063, "tag": "NAME", "value": "Harry" }, { "context": "ed.\n;;\n;; Example: (save-births-by-name [\"Harry\" \"John\"] \"harry-john.png\")\n;;\n(defn save-births-by-name\n", "end": 6075, "score": 0.9998458027839661, "start": 6071, "tag": "NAME", "value": "John" } ]
src/hello_bitly/baby_names.clj
phoenix2082/punter
2
(ns hello-bitly.baby_names (:gen-class) (:import (java.lang.Double) (java.text.DecimalFormat) (org.jfree.chart StandardChartTheme) (org.jfree.chart.plot DefaultDrawingSupplier) (java.awt Color) (java.io ByteArrayOutputStream ByteArrayInputStream) (java.nio.file.Files)) (:require [clojure.walk] [clojure.pprint :as pp] [clojure.string :as cstr] [criterium.core :refer :all] [hello-bitly.util :as hbu])) (use '(incanter core charts datasets)) (def babynamefilepath "./datasets/names") (def bheader [:name :sex :births]) (defn filter-out-files [filelist] (filter (fn [fitem] (and (.isFile fitem) (cstr/ends-with? (.getName fitem) ".txt"))) filelist)) (defn file-abs-path [filelist] (map #(.getAbsolutePath %) filelist)) (defn read-table [path seperator names] (as-> (hbu/read-file path) records (-> (map (fn [rec] (cstr/split rec (re-pattern seperator))) records) (into names)))) (defn read-directory "This method read all the files from a directory and returns list of files. arg - folderpath - the path of directory" [folderpath] (-> (new java.io.File folderpath) (.listFiles) (filter-out-files) (file-abs-path))) ;; (#(.getPath %)) ;; (read-file))) (defn read-records [records seperator] ;(prn "reading records") (map (fn [rec] (cstr/split rec (re-pattern seperator))) records)) (defn prep-records [records] ;(prn "prep-records") (pmap (fn [rec] [(first rec) (second rec) (Integer/parseInt (last rec))]) records)) (defn add-extra-value [records val] ;(prn "adding year") (pmap (fn [rec] (conj rec val)) records)) (defn get-year-from-filename [filename] ;(prn filename) (-> (re-pattern "\\d+") (re-find filename) (Integer/parseInt))) (defn get-yearly-records [filepath] (-> (hbu/read-file filepath) (read-records ",") (prep-records) (add-extra-value (get-year-from-filename filepath)))) (defn get-all-year-record [dirpath] (doseq [filepath (read-directory dirpath)] (if (cstr/ends-with? filepath ".txt") (get-yearly-records filepath)))) (defn all-year-records [dirpath] (let [filepaths (vec (read-directory dirpath)) filecount (count filepaths)] (loop [i 0 v ()] (if (< i filecount) (recur (inc i) (into v (get-yearly-records (get filepaths i)))) v)))) ;; (def allrec (all-year-records babynamefilepath)) ;; (def namedata (incanter.core/dataset [:name :sex :births] records)) ;; (incanter.core/$rollup :sum :births :sex babynames) ;; (incanter.core/$rollup :sum :births [:year :sex] namedata) ;; years - (1880 1900 1920 1940 1960 1980 2000 2020) ;; (query-dataset cars {:speed {:$in #{17 14 19}}}) ;; (query-dataset cars {:year {:$in #{ 1880 1900 1920 1940 1960 1980 2000 2020}}}) (defn get-years [] #{1880 1900 1920 1940 1960 1980 2000 2017}) ;; Uncomment this to test (defonce allrec (all-year-records babynamefilepath)) (defonce namedata (incanter.core/dataset [:name :sex :births :year] allrec)) (defn get-line-chart [namedata] (with-data (->> (incanter.core/query-dataset namedata {:year {:$in (get-years)}}) (incanter.core/$rollup :sum :births [:year :sex]) (incanter.core/$order :year :asc)) (incanter.charts/line-chart :year :births :group-by :sex :legend true :y-label "Births" :x-label "Year" :title "Trends"))) (defn view-test-chart-2 [namedata] (with-data (->> (incanter.core/query-dataset namedata {:year {:$in (get-years)}}) (incanter.core/$rollup :sum :births [:year :sex]) (incanter.core/$order :year :asc)) (view (incanter.charts/line-chart :year :births :group-by :sex :legend true :y-label "Births" :x-label "Year" :title "Trends")))) (defn save-test-chart-2 [namedata] (with-data (->> (incanter.core/query-dataset namedata {:year {:$in (get-years)}}) (incanter.core/$rollup :sum :births [:year :sex]) (incanter.core/$order :year :asc)) (save (incanter.charts/line-chart :year :births :group-by :sex :legend true :y-label "Count by Gender" :x-label "Year" :title "Trends") "birth-trends.png"))) ;; Use this method to create chart object. ;; Input : cnames > Vector of names. ;; Output : returen a chart object. ;; Used by view-births-by-name/save-births-by-name methods. (defn chart-by-birth-name [cnames namedata] (with-data (->> (incanter.core/query-dataset namedata {:name {:$in (set cnames)}}) (incanter.core/$rollup :sum :births [:year :name]) (incanter.core/$order :year :asc)) (incanter.charts/line-chart :year :births :group-by :name :legend true :y-label "Births" :x-label "Year" :title "Trends"))) ;; Use this to method to view child naming trends. ;; Will create a chart on desktop ;; ;; Input : cnames > Vector of names. ;; filename > Name of file in which result need to be saved. ;; ;; Example: ;; To view trends for a single name > (view-births-by-name ["Harry"]) ; ;; To view trends for multiple names > (view-births-by-name ["Harry" "Mary"]) ; ;; (defn view-births-by-name [cnames namedata] (incanter.core/view (chart-by-birth-name cnames))) ;; Use this method to save child naming trends as png file. ;; ;; Input : cnames > Vector of names. ;; filename > Name of file in which result need to be saved. ;; ;; Example: (save-births-by-name ["Harry" "John"] "harry-john.png") ;; (defn save-births-by-name [cnames filename namedata] (incanter.core/save (chart-by-birth-name cnames namedata) filename)) ;; Most Popular names in last 10 years (defn most-popular-name [namedata] (with-data (->> (incanter.core/query-dataset namedata {:year {:$in (set (range 2008 2018 1))}}) (incanter.core/$rollup :sum :births [:year :name]) (incanter.core/$order [:year :name] :asc) (#(incanter.core/sel % :rows (range 10)))) (incanter.charts/line-chart :year :births :group-by :name :legend true :y-label "Births" :x-label "Year" :title "Trends"))) (defn view-most-popular-name [] (incanter.core/view (most-popular-name))) ;; (def f10data (incanter.core/query-dataset namedata {:year {:$in (set (range 2008 2018 1))}})) ;; (def f10grouped (incanter.core/$rollup :sum :births [:year :name]) f10data) ;; ;; (def f10sorted (incanter.core/$order [:year :name] :asc f10grouped)) (defn check-and-update [resultmap year bname bncount] (let [kbname (keyword bname)] ;; (prn kyear) (assoc-in resultmap [year kbname] bncount))) (defn process-record [cnames cyear ccount] (let [totalrec (count cyear)] (loop [i 0 v {}] (if (< i totalrec) (recur (inc i) (check-and-update v (get cyear i) (get cnames i) (get ccount i))) v)))) (defn get-gender-trends [] (let [mlchart (get-line-chart namedata) out-stream (ByteArrayOutputStream.) in-stream (do (save mlchart out-stream) (ByteArrayInputStream. (.toByteArray out-stream)))] in-stream))
3828
(ns hello-bitly.baby_names (:gen-class) (:import (java.lang.Double) (java.text.DecimalFormat) (org.jfree.chart StandardChartTheme) (org.jfree.chart.plot DefaultDrawingSupplier) (java.awt Color) (java.io ByteArrayOutputStream ByteArrayInputStream) (java.nio.file.Files)) (:require [clojure.walk] [clojure.pprint :as pp] [clojure.string :as cstr] [criterium.core :refer :all] [hello-bitly.util :as hbu])) (use '(incanter core charts datasets)) (def babynamefilepath "./datasets/names") (def bheader [:name :sex :births]) (defn filter-out-files [filelist] (filter (fn [fitem] (and (.isFile fitem) (cstr/ends-with? (.getName fitem) ".txt"))) filelist)) (defn file-abs-path [filelist] (map #(.getAbsolutePath %) filelist)) (defn read-table [path seperator names] (as-> (hbu/read-file path) records (-> (map (fn [rec] (cstr/split rec (re-pattern seperator))) records) (into names)))) (defn read-directory "This method read all the files from a directory and returns list of files. arg - folderpath - the path of directory" [folderpath] (-> (new java.io.File folderpath) (.listFiles) (filter-out-files) (file-abs-path))) ;; (#(.getPath %)) ;; (read-file))) (defn read-records [records seperator] ;(prn "reading records") (map (fn [rec] (cstr/split rec (re-pattern seperator))) records)) (defn prep-records [records] ;(prn "prep-records") (pmap (fn [rec] [(first rec) (second rec) (Integer/parseInt (last rec))]) records)) (defn add-extra-value [records val] ;(prn "adding year") (pmap (fn [rec] (conj rec val)) records)) (defn get-year-from-filename [filename] ;(prn filename) (-> (re-pattern "\\d+") (re-find filename) (Integer/parseInt))) (defn get-yearly-records [filepath] (-> (hbu/read-file filepath) (read-records ",") (prep-records) (add-extra-value (get-year-from-filename filepath)))) (defn get-all-year-record [dirpath] (doseq [filepath (read-directory dirpath)] (if (cstr/ends-with? filepath ".txt") (get-yearly-records filepath)))) (defn all-year-records [dirpath] (let [filepaths (vec (read-directory dirpath)) filecount (count filepaths)] (loop [i 0 v ()] (if (< i filecount) (recur (inc i) (into v (get-yearly-records (get filepaths i)))) v)))) ;; (def allrec (all-year-records babynamefilepath)) ;; (def namedata (incanter.core/dataset [:name :sex :births] records)) ;; (incanter.core/$rollup :sum :births :sex babynames) ;; (incanter.core/$rollup :sum :births [:year :sex] namedata) ;; years - (1880 1900 1920 1940 1960 1980 2000 2020) ;; (query-dataset cars {:speed {:$in #{17 14 19}}}) ;; (query-dataset cars {:year {:$in #{ 1880 1900 1920 1940 1960 1980 2000 2020}}}) (defn get-years [] #{1880 1900 1920 1940 1960 1980 2000 2017}) ;; Uncomment this to test (defonce allrec (all-year-records babynamefilepath)) (defonce namedata (incanter.core/dataset [:name :sex :births :year] allrec)) (defn get-line-chart [namedata] (with-data (->> (incanter.core/query-dataset namedata {:year {:$in (get-years)}}) (incanter.core/$rollup :sum :births [:year :sex]) (incanter.core/$order :year :asc)) (incanter.charts/line-chart :year :births :group-by :sex :legend true :y-label "Births" :x-label "Year" :title "Trends"))) (defn view-test-chart-2 [namedata] (with-data (->> (incanter.core/query-dataset namedata {:year {:$in (get-years)}}) (incanter.core/$rollup :sum :births [:year :sex]) (incanter.core/$order :year :asc)) (view (incanter.charts/line-chart :year :births :group-by :sex :legend true :y-label "Births" :x-label "Year" :title "Trends")))) (defn save-test-chart-2 [namedata] (with-data (->> (incanter.core/query-dataset namedata {:year {:$in (get-years)}}) (incanter.core/$rollup :sum :births [:year :sex]) (incanter.core/$order :year :asc)) (save (incanter.charts/line-chart :year :births :group-by :sex :legend true :y-label "Count by Gender" :x-label "Year" :title "Trends") "birth-trends.png"))) ;; Use this method to create chart object. ;; Input : cnames > Vector of names. ;; Output : returen a chart object. ;; Used by view-births-by-name/save-births-by-name methods. (defn chart-by-birth-name [cnames namedata] (with-data (->> (incanter.core/query-dataset namedata {:name {:$in (set cnames)}}) (incanter.core/$rollup :sum :births [:year :name]) (incanter.core/$order :year :asc)) (incanter.charts/line-chart :year :births :group-by :name :legend true :y-label "Births" :x-label "Year" :title "Trends"))) ;; Use this to method to view child naming trends. ;; Will create a chart on desktop ;; ;; Input : cnames > Vector of names. ;; filename > Name of file in which result need to be saved. ;; ;; Example: ;; To view trends for a single name > (view-births-by-name ["<NAME>"]) ; ;; To view trends for multiple names > (view-births-by-name ["<NAME>" "<NAME>"]) ; ;; (defn view-births-by-name [cnames namedata] (incanter.core/view (chart-by-birth-name cnames))) ;; Use this method to save child naming trends as png file. ;; ;; Input : cnames > Vector of names. ;; filename > Name of file in which result need to be saved. ;; ;; Example: (save-births-by-name ["<NAME>" "<NAME>"] "harry-john.png") ;; (defn save-births-by-name [cnames filename namedata] (incanter.core/save (chart-by-birth-name cnames namedata) filename)) ;; Most Popular names in last 10 years (defn most-popular-name [namedata] (with-data (->> (incanter.core/query-dataset namedata {:year {:$in (set (range 2008 2018 1))}}) (incanter.core/$rollup :sum :births [:year :name]) (incanter.core/$order [:year :name] :asc) (#(incanter.core/sel % :rows (range 10)))) (incanter.charts/line-chart :year :births :group-by :name :legend true :y-label "Births" :x-label "Year" :title "Trends"))) (defn view-most-popular-name [] (incanter.core/view (most-popular-name))) ;; (def f10data (incanter.core/query-dataset namedata {:year {:$in (set (range 2008 2018 1))}})) ;; (def f10grouped (incanter.core/$rollup :sum :births [:year :name]) f10data) ;; ;; (def f10sorted (incanter.core/$order [:year :name] :asc f10grouped)) (defn check-and-update [resultmap year bname bncount] (let [kbname (keyword bname)] ;; (prn kyear) (assoc-in resultmap [year kbname] bncount))) (defn process-record [cnames cyear ccount] (let [totalrec (count cyear)] (loop [i 0 v {}] (if (< i totalrec) (recur (inc i) (check-and-update v (get cyear i) (get cnames i) (get ccount i))) v)))) (defn get-gender-trends [] (let [mlchart (get-line-chart namedata) out-stream (ByteArrayOutputStream.) in-stream (do (save mlchart out-stream) (ByteArrayInputStream. (.toByteArray out-stream)))] in-stream))
true
(ns hello-bitly.baby_names (:gen-class) (:import (java.lang.Double) (java.text.DecimalFormat) (org.jfree.chart StandardChartTheme) (org.jfree.chart.plot DefaultDrawingSupplier) (java.awt Color) (java.io ByteArrayOutputStream ByteArrayInputStream) (java.nio.file.Files)) (:require [clojure.walk] [clojure.pprint :as pp] [clojure.string :as cstr] [criterium.core :refer :all] [hello-bitly.util :as hbu])) (use '(incanter core charts datasets)) (def babynamefilepath "./datasets/names") (def bheader [:name :sex :births]) (defn filter-out-files [filelist] (filter (fn [fitem] (and (.isFile fitem) (cstr/ends-with? (.getName fitem) ".txt"))) filelist)) (defn file-abs-path [filelist] (map #(.getAbsolutePath %) filelist)) (defn read-table [path seperator names] (as-> (hbu/read-file path) records (-> (map (fn [rec] (cstr/split rec (re-pattern seperator))) records) (into names)))) (defn read-directory "This method read all the files from a directory and returns list of files. arg - folderpath - the path of directory" [folderpath] (-> (new java.io.File folderpath) (.listFiles) (filter-out-files) (file-abs-path))) ;; (#(.getPath %)) ;; (read-file))) (defn read-records [records seperator] ;(prn "reading records") (map (fn [rec] (cstr/split rec (re-pattern seperator))) records)) (defn prep-records [records] ;(prn "prep-records") (pmap (fn [rec] [(first rec) (second rec) (Integer/parseInt (last rec))]) records)) (defn add-extra-value [records val] ;(prn "adding year") (pmap (fn [rec] (conj rec val)) records)) (defn get-year-from-filename [filename] ;(prn filename) (-> (re-pattern "\\d+") (re-find filename) (Integer/parseInt))) (defn get-yearly-records [filepath] (-> (hbu/read-file filepath) (read-records ",") (prep-records) (add-extra-value (get-year-from-filename filepath)))) (defn get-all-year-record [dirpath] (doseq [filepath (read-directory dirpath)] (if (cstr/ends-with? filepath ".txt") (get-yearly-records filepath)))) (defn all-year-records [dirpath] (let [filepaths (vec (read-directory dirpath)) filecount (count filepaths)] (loop [i 0 v ()] (if (< i filecount) (recur (inc i) (into v (get-yearly-records (get filepaths i)))) v)))) ;; (def allrec (all-year-records babynamefilepath)) ;; (def namedata (incanter.core/dataset [:name :sex :births] records)) ;; (incanter.core/$rollup :sum :births :sex babynames) ;; (incanter.core/$rollup :sum :births [:year :sex] namedata) ;; years - (1880 1900 1920 1940 1960 1980 2000 2020) ;; (query-dataset cars {:speed {:$in #{17 14 19}}}) ;; (query-dataset cars {:year {:$in #{ 1880 1900 1920 1940 1960 1980 2000 2020}}}) (defn get-years [] #{1880 1900 1920 1940 1960 1980 2000 2017}) ;; Uncomment this to test (defonce allrec (all-year-records babynamefilepath)) (defonce namedata (incanter.core/dataset [:name :sex :births :year] allrec)) (defn get-line-chart [namedata] (with-data (->> (incanter.core/query-dataset namedata {:year {:$in (get-years)}}) (incanter.core/$rollup :sum :births [:year :sex]) (incanter.core/$order :year :asc)) (incanter.charts/line-chart :year :births :group-by :sex :legend true :y-label "Births" :x-label "Year" :title "Trends"))) (defn view-test-chart-2 [namedata] (with-data (->> (incanter.core/query-dataset namedata {:year {:$in (get-years)}}) (incanter.core/$rollup :sum :births [:year :sex]) (incanter.core/$order :year :asc)) (view (incanter.charts/line-chart :year :births :group-by :sex :legend true :y-label "Births" :x-label "Year" :title "Trends")))) (defn save-test-chart-2 [namedata] (with-data (->> (incanter.core/query-dataset namedata {:year {:$in (get-years)}}) (incanter.core/$rollup :sum :births [:year :sex]) (incanter.core/$order :year :asc)) (save (incanter.charts/line-chart :year :births :group-by :sex :legend true :y-label "Count by Gender" :x-label "Year" :title "Trends") "birth-trends.png"))) ;; Use this method to create chart object. ;; Input : cnames > Vector of names. ;; Output : returen a chart object. ;; Used by view-births-by-name/save-births-by-name methods. (defn chart-by-birth-name [cnames namedata] (with-data (->> (incanter.core/query-dataset namedata {:name {:$in (set cnames)}}) (incanter.core/$rollup :sum :births [:year :name]) (incanter.core/$order :year :asc)) (incanter.charts/line-chart :year :births :group-by :name :legend true :y-label "Births" :x-label "Year" :title "Trends"))) ;; Use this to method to view child naming trends. ;; Will create a chart on desktop ;; ;; Input : cnames > Vector of names. ;; filename > Name of file in which result need to be saved. ;; ;; Example: ;; To view trends for a single name > (view-births-by-name ["PI:NAME:<NAME>END_PI"]) ; ;; To view trends for multiple names > (view-births-by-name ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) ; ;; (defn view-births-by-name [cnames namedata] (incanter.core/view (chart-by-birth-name cnames))) ;; Use this method to save child naming trends as png file. ;; ;; Input : cnames > Vector of names. ;; filename > Name of file in which result need to be saved. ;; ;; Example: (save-births-by-name ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] "harry-john.png") ;; (defn save-births-by-name [cnames filename namedata] (incanter.core/save (chart-by-birth-name cnames namedata) filename)) ;; Most Popular names in last 10 years (defn most-popular-name [namedata] (with-data (->> (incanter.core/query-dataset namedata {:year {:$in (set (range 2008 2018 1))}}) (incanter.core/$rollup :sum :births [:year :name]) (incanter.core/$order [:year :name] :asc) (#(incanter.core/sel % :rows (range 10)))) (incanter.charts/line-chart :year :births :group-by :name :legend true :y-label "Births" :x-label "Year" :title "Trends"))) (defn view-most-popular-name [] (incanter.core/view (most-popular-name))) ;; (def f10data (incanter.core/query-dataset namedata {:year {:$in (set (range 2008 2018 1))}})) ;; (def f10grouped (incanter.core/$rollup :sum :births [:year :name]) f10data) ;; ;; (def f10sorted (incanter.core/$order [:year :name] :asc f10grouped)) (defn check-and-update [resultmap year bname bncount] (let [kbname (keyword bname)] ;; (prn kyear) (assoc-in resultmap [year kbname] bncount))) (defn process-record [cnames cyear ccount] (let [totalrec (count cyear)] (loop [i 0 v {}] (if (< i totalrec) (recur (inc i) (check-and-update v (get cyear i) (get cnames i) (get ccount i))) v)))) (defn get-gender-trends [] (let [mlchart (get-line-chart namedata) out-stream (ByteArrayOutputStream.) in-stream (do (save mlchart out-stream) (ByteArrayInputStream. (.toByteArray out-stream)))] in-stream))
[ { "context": "an instance of record\n(def terminator (Customer. \"Arny\" \"T2\" \"AT2@skynet.com\" 111110011 :CORP\n ", "end": 451, "score": 0.9980975389480591, "start": 447, "tag": "NAME", "value": "Arny" }, { "context": "of record\n(def terminator (Customer. \"Arny\" \"T2\" \"AT2@skynet.com\" 111110011 :CORP\n (Address. \"Has", "end": 473, "score": 0.9999021291732788, "start": 459, "tag": "EMAIL", "value": "AT2@skynet.com" } ]
src/clojuretryout/domainmodelling/defrecordExmple.clj
mshiray/clojuretryout
0
;define namespace (ns com.clojuretryout.domainmodelling) ;define enum type with keyword {:RETAIL 0 , :CORP 1} ;defining composite data types as records ;TODO: Move it to separate file (defrecord Address [street city state zip]) ;; => com.clojuretryout.domainmodelling.Address (defrecord Customer [fname lname email phone type address]) ;; => com.clojuretryout.domainmodelling.Customer ;create an instance of record (def terminator (Customer. "Arny" "T2" "AT2@skynet.com" 111110011 :CORP (Address. "Hasta La Vista Road" "LA" "CA" 345612))) ;Define fucntion accepting the defined type record (defn printCustomer [customer] (println (:fname customer) "" (:lname customer) "#" (:phone customer) "#" (:type customer) (-> customer :address :zip)) ; note the -> & placement of dto ref ) ;invoke function with isntance of record type (printCustomer terminator)
69986
;define namespace (ns com.clojuretryout.domainmodelling) ;define enum type with keyword {:RETAIL 0 , :CORP 1} ;defining composite data types as records ;TODO: Move it to separate file (defrecord Address [street city state zip]) ;; => com.clojuretryout.domainmodelling.Address (defrecord Customer [fname lname email phone type address]) ;; => com.clojuretryout.domainmodelling.Customer ;create an instance of record (def terminator (Customer. "<NAME>" "T2" "<EMAIL>" 111110011 :CORP (Address. "Hasta La Vista Road" "LA" "CA" 345612))) ;Define fucntion accepting the defined type record (defn printCustomer [customer] (println (:fname customer) "" (:lname customer) "#" (:phone customer) "#" (:type customer) (-> customer :address :zip)) ; note the -> & placement of dto ref ) ;invoke function with isntance of record type (printCustomer terminator)
true
;define namespace (ns com.clojuretryout.domainmodelling) ;define enum type with keyword {:RETAIL 0 , :CORP 1} ;defining composite data types as records ;TODO: Move it to separate file (defrecord Address [street city state zip]) ;; => com.clojuretryout.domainmodelling.Address (defrecord Customer [fname lname email phone type address]) ;; => com.clojuretryout.domainmodelling.Customer ;create an instance of record (def terminator (Customer. "PI:NAME:<NAME>END_PI" "T2" "PI:EMAIL:<EMAIL>END_PI" 111110011 :CORP (Address. "Hasta La Vista Road" "LA" "CA" 345612))) ;Define fucntion accepting the defined type record (defn printCustomer [customer] (println (:fname customer) "" (:lname customer) "#" (:phone customer) "#" (:type customer) (-> customer :address :zip)) ; note the -> & placement of dto ref ) ;invoke function with isntance of record type (printCustomer terminator)
[ { "context": "; Copyright (C) 2014, 2015 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch)\n; Re", "end": 44, "score": 0.9998025298118591, "start": 31, "tag": "NAME", "value": "Thomas Schank" }, { "context": "; Copyright (C) 2014, 2015 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch)\n; Released under the M", "end": 62, "score": 0.9999231696128845, "start": 47, "tag": "EMAIL", "value": "DrTom@schank.ch" }, { "context": "C) 2014, 2015 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.9999234676361084, "start": 64, "tag": "EMAIL", "value": "Thomas.Schank@algocon.ch" } ]
test/json_roa/ring_middleware/request_test.clj
json-roa/json-roa_clj-utils
0
; Copyright (C) 2014, 2015 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch) ; Released under the MIT license. (ns json-roa.ring-middleware.request-test (:require [cheshire.core :as cheshire] [clj-logging-config.log4j :as logging-config] [clojure.data.json :as json] [clojure.tools.logging :as logging] [json-roa.ring-middleware.request] [ring.mock.request :as mock] ) (:use clojure.test) ) (def base-request (-> (mock/request :post "/test") (mock/header "accept" "application/json") )) (defn default-json-roa-handler [request json-response] (assoc json-response :body (assoc (:body json-response) :_json-roa {}))) (def json-response {:status 200 :body {:x 42} }) (defn default-json-handler [request] json-response ) (deftest test-wrap-json-roa-request (let [base-resp ((json-roa.ring-middleware.request/wrap default-json-handler default-json-roa-handler) base-request)] (is (= json-response base-resp)) (is (not (-> base-resp :body :_json-roa)) "a pure json-response must not contain a _json-roa object") ) (let [json-roa-resp ((json-roa.ring-middleware.request/wrap default-json-handler default-json-roa-handler) (mock/header base-request "accept" "application/json-roa+json"))] (is json-roa-resp) (is (-> json-roa-resp :body :_json-roa) "a json-roa-response must contain a _json-roa object") ))
85537
; Copyright (C) 2014, 2015 Dr. <NAME> (<EMAIL>, <EMAIL>) ; Released under the MIT license. (ns json-roa.ring-middleware.request-test (:require [cheshire.core :as cheshire] [clj-logging-config.log4j :as logging-config] [clojure.data.json :as json] [clojure.tools.logging :as logging] [json-roa.ring-middleware.request] [ring.mock.request :as mock] ) (:use clojure.test) ) (def base-request (-> (mock/request :post "/test") (mock/header "accept" "application/json") )) (defn default-json-roa-handler [request json-response] (assoc json-response :body (assoc (:body json-response) :_json-roa {}))) (def json-response {:status 200 :body {:x 42} }) (defn default-json-handler [request] json-response ) (deftest test-wrap-json-roa-request (let [base-resp ((json-roa.ring-middleware.request/wrap default-json-handler default-json-roa-handler) base-request)] (is (= json-response base-resp)) (is (not (-> base-resp :body :_json-roa)) "a pure json-response must not contain a _json-roa object") ) (let [json-roa-resp ((json-roa.ring-middleware.request/wrap default-json-handler default-json-roa-handler) (mock/header base-request "accept" "application/json-roa+json"))] (is json-roa-resp) (is (-> json-roa-resp :body :_json-roa) "a json-roa-response must contain a _json-roa object") ))
true
; Copyright (C) 2014, 2015 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.request-test (:require [cheshire.core :as cheshire] [clj-logging-config.log4j :as logging-config] [clojure.data.json :as json] [clojure.tools.logging :as logging] [json-roa.ring-middleware.request] [ring.mock.request :as mock] ) (:use clojure.test) ) (def base-request (-> (mock/request :post "/test") (mock/header "accept" "application/json") )) (defn default-json-roa-handler [request json-response] (assoc json-response :body (assoc (:body json-response) :_json-roa {}))) (def json-response {:status 200 :body {:x 42} }) (defn default-json-handler [request] json-response ) (deftest test-wrap-json-roa-request (let [base-resp ((json-roa.ring-middleware.request/wrap default-json-handler default-json-roa-handler) base-request)] (is (= json-response base-resp)) (is (not (-> base-resp :body :_json-roa)) "a pure json-response must not contain a _json-roa object") ) (let [json-roa-resp ((json-roa.ring-middleware.request/wrap default-json-handler default-json-roa-handler) (mock/header base-request "accept" "application/json-roa+json"))] (is json-roa-resp) (is (-> json-roa-resp :body :_json-roa) "a json-roa-response must contain a _json-roa object") ))
[ { "context": " \"keyserver.ubuntu.com\"\n \"E56151BF\")\n (debian/install {:mesos mesos-version\n ", "end": 1911, "score": 0.7058489918708801, "start": 1903, "tag": "KEY", "value": "E56151BF" } ]
flink-jepsen/src/jepsen/flink/mesos.clj
YCjia/flink
1
;; Licensed to the Apache Software Foundation (ASF) under one ;; or more contributor license agreements. See the NOTICE file ;; distributed with this work for additional information ;; regarding copyright ownership. The ASF licenses this file ;; to you under the Apache License, Version 2.0 (the ;; "License"); you may not use this file except in compliance ;; with the License. You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns jepsen.flink.mesos (:require [clojure.tools.logging :refer :all] [jepsen [control :as c] [db :as db] [util :as util :refer [meh]]] [jepsen.control.util :as cu] [jepsen.os.debian :as debian] [jepsen.flink.zookeeper :refer [zookeeper-uri]])) ;;; Mesos (def master-count 1) (def master-pidfile "/var/run/mesos/master.pid") (def slave-pidfile "/var/run/mesos/slave.pid") (def master-dir "/var/lib/mesos/master") (def slave-dir "/var/lib/mesos/slave") (def log-dir "/var/log/mesos") (def master-bin "/usr/sbin/mesos-master") (def slave-bin "/usr/sbin/mesos-slave") (def zk-namespace :mesos) ;;; Marathon (def marathon-bin "/usr/bin/marathon") (def zk-marathon-namespace "marathon") (def marathon-pidfile "/var/run/mesos/marathon.pid") (def marathon-rest-port 8080) (defn install! [test node mesos-version marathon-version] (c/su (debian/add-repo! :mesosphere "deb http://repos.mesosphere.com/debian jessie main" "keyserver.ubuntu.com" "E56151BF") (debian/install {:mesos mesos-version :marathon marathon-version}) (c/exec :mkdir :-p "/var/run/mesos") (c/exec :mkdir :-p master-dir) (c/exec :mkdir :-p slave-dir))) ;;; Mesos functions (defn start-master! [test node] (when (some #{node} (take master-count (sort (:nodes test)))) (info node "Starting mesos master") (c/su (c/exec :start-stop-daemon :--background :--chdir master-dir :--exec "/usr/bin/env" :--make-pidfile :--no-close :--oknodo :--pidfile master-pidfile :--start :-- "GLOG_v=1" master-bin (str "--hostname=" (name node)) (str "--log_dir=" log-dir) (str "--offer_timeout=30secs") (str "--quorum=" (util/majority master-count)) (str "--registry_fetch_timeout=120secs") (str "--registry_store_timeout=5secs") (str "--work_dir=" master-dir) (str "--zk=" (zookeeper-uri test zk-namespace)) :>> (str log-dir "/master.stdout") (c/lit "2>&1"))))) (defn start-slave! [test node] (when-not (some #{node} (take master-count (sort (:nodes test)))) (info node "Starting mesos slave") (c/su (c/exec :start-stop-daemon :--start :--background :--chdir slave-dir :--exec slave-bin :--make-pidfile :--no-close :--pidfile slave-pidfile :--oknodo :-- (str "--hostname=" (name node)) (str "--log_dir=" log-dir) (str "--master=" (zookeeper-uri test zk-namespace)) (str "--recovery_timeout=30secs") (str "--work_dir=" slave-dir) :>> (str log-dir "/slave.stdout") (c/lit "2>&1"))))) (defn stop-master! [node] (info node "Stopping mesos master") (meh (c/exec :killall :-9 :mesos-master)) (meh (c/exec :rm :-rf master-pidfile))) (defn stop-slave! [node] (info node "Stopping mesos slave") (meh (c/exec :killall :-9 :mesos-slave)) (meh (c/exec :rm :-rf slave-pidfile))) ;;; Marathon functions (defn start-marathon! [test node] (when (= node (first (sort (:nodes test)))) (info "Start marathon") (c/su (c/exec :start-stop-daemon :--start :--background :--exec marathon-bin :--make-pidfile :--no-close :--pidfile marathon-pidfile :-- (c/lit (str "--hostname " node)) (c/lit (str "--master " (zookeeper-uri test zk-namespace))) (c/lit (str "--zk " (zookeeper-uri test zk-marathon-namespace))) :>> (str log-dir "/marathon.stdout") (c/lit "2>&1"))))) (defn stop-marathon! [] (cu/grepkill! "marathon")) (defn marathon-base-url [test] (str "http://" (first (sort (:nodes test))) ":" marathon-rest-port)) (defn db [mesos-version marathon-version] (reify db/DB (setup! [this test node] (install! test node mesos-version marathon-version) (start-master! test node) (start-slave! test node) (start-marathon! test node)) (teardown! [this test node] (stop-slave! node) (stop-master! node) (stop-marathon!)) db/LogFiles (log-files [_ test node] (if (cu/exists? log-dir) (cu/ls-full log-dir) []))))
40067
;; Licensed to the Apache Software Foundation (ASF) under one ;; or more contributor license agreements. See the NOTICE file ;; distributed with this work for additional information ;; regarding copyright ownership. The ASF licenses this file ;; to you under the Apache License, Version 2.0 (the ;; "License"); you may not use this file except in compliance ;; with the License. You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns jepsen.flink.mesos (:require [clojure.tools.logging :refer :all] [jepsen [control :as c] [db :as db] [util :as util :refer [meh]]] [jepsen.control.util :as cu] [jepsen.os.debian :as debian] [jepsen.flink.zookeeper :refer [zookeeper-uri]])) ;;; Mesos (def master-count 1) (def master-pidfile "/var/run/mesos/master.pid") (def slave-pidfile "/var/run/mesos/slave.pid") (def master-dir "/var/lib/mesos/master") (def slave-dir "/var/lib/mesos/slave") (def log-dir "/var/log/mesos") (def master-bin "/usr/sbin/mesos-master") (def slave-bin "/usr/sbin/mesos-slave") (def zk-namespace :mesos) ;;; Marathon (def marathon-bin "/usr/bin/marathon") (def zk-marathon-namespace "marathon") (def marathon-pidfile "/var/run/mesos/marathon.pid") (def marathon-rest-port 8080) (defn install! [test node mesos-version marathon-version] (c/su (debian/add-repo! :mesosphere "deb http://repos.mesosphere.com/debian jessie main" "keyserver.ubuntu.com" "<KEY>") (debian/install {:mesos mesos-version :marathon marathon-version}) (c/exec :mkdir :-p "/var/run/mesos") (c/exec :mkdir :-p master-dir) (c/exec :mkdir :-p slave-dir))) ;;; Mesos functions (defn start-master! [test node] (when (some #{node} (take master-count (sort (:nodes test)))) (info node "Starting mesos master") (c/su (c/exec :start-stop-daemon :--background :--chdir master-dir :--exec "/usr/bin/env" :--make-pidfile :--no-close :--oknodo :--pidfile master-pidfile :--start :-- "GLOG_v=1" master-bin (str "--hostname=" (name node)) (str "--log_dir=" log-dir) (str "--offer_timeout=30secs") (str "--quorum=" (util/majority master-count)) (str "--registry_fetch_timeout=120secs") (str "--registry_store_timeout=5secs") (str "--work_dir=" master-dir) (str "--zk=" (zookeeper-uri test zk-namespace)) :>> (str log-dir "/master.stdout") (c/lit "2>&1"))))) (defn start-slave! [test node] (when-not (some #{node} (take master-count (sort (:nodes test)))) (info node "Starting mesos slave") (c/su (c/exec :start-stop-daemon :--start :--background :--chdir slave-dir :--exec slave-bin :--make-pidfile :--no-close :--pidfile slave-pidfile :--oknodo :-- (str "--hostname=" (name node)) (str "--log_dir=" log-dir) (str "--master=" (zookeeper-uri test zk-namespace)) (str "--recovery_timeout=30secs") (str "--work_dir=" slave-dir) :>> (str log-dir "/slave.stdout") (c/lit "2>&1"))))) (defn stop-master! [node] (info node "Stopping mesos master") (meh (c/exec :killall :-9 :mesos-master)) (meh (c/exec :rm :-rf master-pidfile))) (defn stop-slave! [node] (info node "Stopping mesos slave") (meh (c/exec :killall :-9 :mesos-slave)) (meh (c/exec :rm :-rf slave-pidfile))) ;;; Marathon functions (defn start-marathon! [test node] (when (= node (first (sort (:nodes test)))) (info "Start marathon") (c/su (c/exec :start-stop-daemon :--start :--background :--exec marathon-bin :--make-pidfile :--no-close :--pidfile marathon-pidfile :-- (c/lit (str "--hostname " node)) (c/lit (str "--master " (zookeeper-uri test zk-namespace))) (c/lit (str "--zk " (zookeeper-uri test zk-marathon-namespace))) :>> (str log-dir "/marathon.stdout") (c/lit "2>&1"))))) (defn stop-marathon! [] (cu/grepkill! "marathon")) (defn marathon-base-url [test] (str "http://" (first (sort (:nodes test))) ":" marathon-rest-port)) (defn db [mesos-version marathon-version] (reify db/DB (setup! [this test node] (install! test node mesos-version marathon-version) (start-master! test node) (start-slave! test node) (start-marathon! test node)) (teardown! [this test node] (stop-slave! node) (stop-master! node) (stop-marathon!)) db/LogFiles (log-files [_ test node] (if (cu/exists? log-dir) (cu/ls-full log-dir) []))))
true
;; Licensed to the Apache Software Foundation (ASF) under one ;; or more contributor license agreements. See the NOTICE file ;; distributed with this work for additional information ;; regarding copyright ownership. The ASF licenses this file ;; to you under the Apache License, Version 2.0 (the ;; "License"); you may not use this file except in compliance ;; with the License. You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns jepsen.flink.mesos (:require [clojure.tools.logging :refer :all] [jepsen [control :as c] [db :as db] [util :as util :refer [meh]]] [jepsen.control.util :as cu] [jepsen.os.debian :as debian] [jepsen.flink.zookeeper :refer [zookeeper-uri]])) ;;; Mesos (def master-count 1) (def master-pidfile "/var/run/mesos/master.pid") (def slave-pidfile "/var/run/mesos/slave.pid") (def master-dir "/var/lib/mesos/master") (def slave-dir "/var/lib/mesos/slave") (def log-dir "/var/log/mesos") (def master-bin "/usr/sbin/mesos-master") (def slave-bin "/usr/sbin/mesos-slave") (def zk-namespace :mesos) ;;; Marathon (def marathon-bin "/usr/bin/marathon") (def zk-marathon-namespace "marathon") (def marathon-pidfile "/var/run/mesos/marathon.pid") (def marathon-rest-port 8080) (defn install! [test node mesos-version marathon-version] (c/su (debian/add-repo! :mesosphere "deb http://repos.mesosphere.com/debian jessie main" "keyserver.ubuntu.com" "PI:KEY:<KEY>END_PI") (debian/install {:mesos mesos-version :marathon marathon-version}) (c/exec :mkdir :-p "/var/run/mesos") (c/exec :mkdir :-p master-dir) (c/exec :mkdir :-p slave-dir))) ;;; Mesos functions (defn start-master! [test node] (when (some #{node} (take master-count (sort (:nodes test)))) (info node "Starting mesos master") (c/su (c/exec :start-stop-daemon :--background :--chdir master-dir :--exec "/usr/bin/env" :--make-pidfile :--no-close :--oknodo :--pidfile master-pidfile :--start :-- "GLOG_v=1" master-bin (str "--hostname=" (name node)) (str "--log_dir=" log-dir) (str "--offer_timeout=30secs") (str "--quorum=" (util/majority master-count)) (str "--registry_fetch_timeout=120secs") (str "--registry_store_timeout=5secs") (str "--work_dir=" master-dir) (str "--zk=" (zookeeper-uri test zk-namespace)) :>> (str log-dir "/master.stdout") (c/lit "2>&1"))))) (defn start-slave! [test node] (when-not (some #{node} (take master-count (sort (:nodes test)))) (info node "Starting mesos slave") (c/su (c/exec :start-stop-daemon :--start :--background :--chdir slave-dir :--exec slave-bin :--make-pidfile :--no-close :--pidfile slave-pidfile :--oknodo :-- (str "--hostname=" (name node)) (str "--log_dir=" log-dir) (str "--master=" (zookeeper-uri test zk-namespace)) (str "--recovery_timeout=30secs") (str "--work_dir=" slave-dir) :>> (str log-dir "/slave.stdout") (c/lit "2>&1"))))) (defn stop-master! [node] (info node "Stopping mesos master") (meh (c/exec :killall :-9 :mesos-master)) (meh (c/exec :rm :-rf master-pidfile))) (defn stop-slave! [node] (info node "Stopping mesos slave") (meh (c/exec :killall :-9 :mesos-slave)) (meh (c/exec :rm :-rf slave-pidfile))) ;;; Marathon functions (defn start-marathon! [test node] (when (= node (first (sort (:nodes test)))) (info "Start marathon") (c/su (c/exec :start-stop-daemon :--start :--background :--exec marathon-bin :--make-pidfile :--no-close :--pidfile marathon-pidfile :-- (c/lit (str "--hostname " node)) (c/lit (str "--master " (zookeeper-uri test zk-namespace))) (c/lit (str "--zk " (zookeeper-uri test zk-marathon-namespace))) :>> (str log-dir "/marathon.stdout") (c/lit "2>&1"))))) (defn stop-marathon! [] (cu/grepkill! "marathon")) (defn marathon-base-url [test] (str "http://" (first (sort (:nodes test))) ":" marathon-rest-port)) (defn db [mesos-version marathon-version] (reify db/DB (setup! [this test node] (install! test node mesos-version marathon-version) (start-master! test node) (start-slave! test node) (start-marathon! test node)) (teardown! [this test node] (stop-slave! node) (stop-master! node) (stop-marathon!)) db/LogFiles (log-files [_ test node] (if (cu/exists? log-dir) (cu/ls-full log-dir) []))))
[ { "context": "uri \"\" INVALID\n :uri 0 INVALID\n :email \"name@google.com\" \"name@google.com\"\n :email \"http://google.co", "end": 617, "score": 0.9998713731765747, "start": 602, "tag": "EMAIL", "value": "name@google.com" }, { "context": " :uri 0 INVALID\n :email \"name@google.com\" \"name@google.com\"\n :email \"http://google.com\" INVALID\n :", "end": 635, "score": 0.9997984170913696, "start": 620, "tag": "EMAIL", "value": "name@google.com" } ]
test/tableschema_clj/types/string_test.clj
frictionlessdata/tableschema-clj
6
(ns tableschema-clj.types.string-test (:require [tableschema-clj.types.string :refer :all] [clojure.spec.gen.alpha :as gen] [clojure.spec.alpha :as s] [clojure.test :refer :all])) (defonce INVALID :clojure.spec.alpha/invalid) (deftest test-cast-string (are [format value result] (= (cast-string format value) result) :default "string" "string" :default "" "" :default true INVALID :default 0 INVALID :uri "http://google.com" "http://google.com" :uri "string" INVALID :uri "" INVALID :uri 0 INVALID :email "name@google.com" "name@google.com" :email "http://google.com" INVALID :email "string" INVALID :email "" INVALID :email 0 INVALID :binary "dGVzdA==" "dGVzdA==" :binary "" "" :binary 0 INVALID :uuid "76ae35fa-66d6-4499-9ae9-daaa16865446" "76ae35fa-66d6-4499-9ae9-daaa16865446" :uuid "string" INVALID :uuid "" INVALID :uuid 0 INVALID :notaformat "string" INVALID ))
48922
(ns tableschema-clj.types.string-test (:require [tableschema-clj.types.string :refer :all] [clojure.spec.gen.alpha :as gen] [clojure.spec.alpha :as s] [clojure.test :refer :all])) (defonce INVALID :clojure.spec.alpha/invalid) (deftest test-cast-string (are [format value result] (= (cast-string format value) result) :default "string" "string" :default "" "" :default true INVALID :default 0 INVALID :uri "http://google.com" "http://google.com" :uri "string" INVALID :uri "" INVALID :uri 0 INVALID :email "<EMAIL>" "<EMAIL>" :email "http://google.com" INVALID :email "string" INVALID :email "" INVALID :email 0 INVALID :binary "dGVzdA==" "dGVzdA==" :binary "" "" :binary 0 INVALID :uuid "76ae35fa-66d6-4499-9ae9-daaa16865446" "76ae35fa-66d6-4499-9ae9-daaa16865446" :uuid "string" INVALID :uuid "" INVALID :uuid 0 INVALID :notaformat "string" INVALID ))
true
(ns tableschema-clj.types.string-test (:require [tableschema-clj.types.string :refer :all] [clojure.spec.gen.alpha :as gen] [clojure.spec.alpha :as s] [clojure.test :refer :all])) (defonce INVALID :clojure.spec.alpha/invalid) (deftest test-cast-string (are [format value result] (= (cast-string format value) result) :default "string" "string" :default "" "" :default true INVALID :default 0 INVALID :uri "http://google.com" "http://google.com" :uri "string" INVALID :uri "" INVALID :uri 0 INVALID :email "PI:EMAIL:<EMAIL>END_PI" "PI:EMAIL:<EMAIL>END_PI" :email "http://google.com" INVALID :email "string" INVALID :email "" INVALID :email 0 INVALID :binary "dGVzdA==" "dGVzdA==" :binary "" "" :binary 0 INVALID :uuid "76ae35fa-66d6-4499-9ae9-daaa16865446" "76ae35fa-66d6-4499-9ae9-daaa16865446" :uuid "string" INVALID :uuid "" INVALID :uuid 0 INVALID :notaformat "string" INVALID ))
[ { "context": ".0.html\"\n :year 2013\n :key \"apache-2.0\"\n :author \"stylefruits GmbH\"}\n :url \"", "end": 245, "score": 0.9752136468887329, "start": 235, "tag": "KEY", "value": "apache-2.0" }, { "context": " :key \"apache-2.0\"\n :author \"stylefruits GmbH\"}\n :url \"https://github.com/stylefruits/gniazdo\"", "end": 284, "score": 0.7656916975975037, "start": 273, "tag": "EMAIL", "value": "fruits GmbH" }, { "context": "or \"stylefruits GmbH\"}\n :url \"https://github.com/stylefruits/gniazdo\"\n :dependencies [[org.clojure/clojure \"1", "end": 325, "score": 0.9851755499839783, "start": 314, "tag": "USERNAME", "value": "stylefruits" } ]
project.clj
liftoffio/gniazdo
0
(defproject stylefruits/gniazdo "1.1.4" :description "A WebSocket client for Clojure" :license {:name "Apache License 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0.html" :year 2013 :key "apache-2.0" :author "stylefruits GmbH"} :url "https://github.com/stylefruits/gniazdo" :dependencies [[org.clojure/clojure "1.5.1"] [org.eclipse.jetty.websocket/websocket-client "9.4.29.v20200521"]] :repl-options {:init-ns gniazdo.core} :jvm-opts ["-Dorg.eclipse.jetty.websocket.client.LEVEL=WARN"] :profiles {:dev {:dependencies [[http-kit "2.3.0"]]}})
63647
(defproject stylefruits/gniazdo "1.1.4" :description "A WebSocket client for Clojure" :license {:name "Apache License 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0.html" :year 2013 :key "<KEY>" :author "style<EMAIL>"} :url "https://github.com/stylefruits/gniazdo" :dependencies [[org.clojure/clojure "1.5.1"] [org.eclipse.jetty.websocket/websocket-client "9.4.29.v20200521"]] :repl-options {:init-ns gniazdo.core} :jvm-opts ["-Dorg.eclipse.jetty.websocket.client.LEVEL=WARN"] :profiles {:dev {:dependencies [[http-kit "2.3.0"]]}})
true
(defproject stylefruits/gniazdo "1.1.4" :description "A WebSocket client for Clojure" :license {:name "Apache License 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0.html" :year 2013 :key "PI:KEY:<KEY>END_PI" :author "stylePI:EMAIL:<EMAIL>END_PI"} :url "https://github.com/stylefruits/gniazdo" :dependencies [[org.clojure/clojure "1.5.1"] [org.eclipse.jetty.websocket/websocket-client "9.4.29.v20200521"]] :repl-options {:init-ns gniazdo.core} :jvm-opts ["-Dorg.eclipse.jetty.websocket.client.LEVEL=WARN"] :profiles {:dev {:dependencies [[http-kit "2.3.0"]]}})
[ { "context": "xamples\"\n (is (= 357 (d/decode-boarding-pass \"FBFBBFFRLR\")))\n (is (= 567 (d/decode-boarding-pass \"BFFFB", "end": 194, "score": 0.9573792219161987, "start": 185, "tag": "PASSWORD", "value": "BFBBFFRLR" }, { "context": "FRLR\")))\n (is (= 567 (d/decode-boarding-pass \"BFFFBBFRRR\")))\n (is (= 119 (d/decode-boarding-pass \"FFFBB", "end": 249, "score": 0.9037036895751953, "start": 240, "tag": "PASSWORD", "value": "FFFBBFRRR" }, { "context": "RR\")))\n (is (= 119 (d/decode-boarding-pass \"FFFBBBFRRR\")))\n (is (= 820 (d/decode-boarding-pass \"BBFFB", "end": 304, "score": 0.7147282958030701, "start": 297, "tag": "PASSWORD", "value": "BBBFRRR" }, { "context": "RRR\")))\n (is (= 820 (d/decode-boarding-pass \"BBFFBBFRLL\"))))\n\n (testing \"Actual input\"\n (is (= 806 (d", "end": 359, "score": 0.842164158821106, "start": 351, "tag": "PASSWORD", "value": "FFBBFRLL" } ]
test/advent/2020/test_day5.clj
skazhy/advent
0
(ns advent.2020.test-day5 (:require [clojure.test :refer :all] [advent.2020.day5 :as d])) (deftest puzzle1 (testing "Examples" (is (= 357 (d/decode-boarding-pass "FBFBBFFRLR"))) (is (= 567 (d/decode-boarding-pass "BFFFBBFRRR"))) (is (= 119 (d/decode-boarding-pass "FFFBBBFRRR"))) (is (= 820 (d/decode-boarding-pass "BBFFBBFRLL")))) (testing "Actual input" (is (= 806 (d/puzzle1 d/puzzle-input))))) (deftest puzzle2 (testing "Actual input" (is (= 562 (d/puzzle2 d/puzzle-input)))))
12406
(ns advent.2020.test-day5 (:require [clojure.test :refer :all] [advent.2020.day5 :as d])) (deftest puzzle1 (testing "Examples" (is (= 357 (d/decode-boarding-pass "F<PASSWORD>"))) (is (= 567 (d/decode-boarding-pass "B<PASSWORD>"))) (is (= 119 (d/decode-boarding-pass "FFF<PASSWORD>"))) (is (= 820 (d/decode-boarding-pass "BB<PASSWORD>")))) (testing "Actual input" (is (= 806 (d/puzzle1 d/puzzle-input))))) (deftest puzzle2 (testing "Actual input" (is (= 562 (d/puzzle2 d/puzzle-input)))))
true
(ns advent.2020.test-day5 (:require [clojure.test :refer :all] [advent.2020.day5 :as d])) (deftest puzzle1 (testing "Examples" (is (= 357 (d/decode-boarding-pass "FPI:PASSWORD:<PASSWORD>END_PI"))) (is (= 567 (d/decode-boarding-pass "BPI:PASSWORD:<PASSWORD>END_PI"))) (is (= 119 (d/decode-boarding-pass "FFFPI:PASSWORD:<PASSWORD>END_PI"))) (is (= 820 (d/decode-boarding-pass "BBPI:PASSWORD:<PASSWORD>END_PI")))) (testing "Actual input" (is (= 806 (d/puzzle1 d/puzzle-input))))) (deftest puzzle2 (testing "Actual input" (is (= 562 (d/puzzle2 d/puzzle-input)))))
[ { "context": "teger/parseInt max)\n :ch (nth ch 0)\n :password password}\n ))\n\n(defn read-database [filename]\n (with-ope", "end": 252, "score": 0.9916467070579529, "start": 244, "tag": "PASSWORD", "value": "password" } ]
src/main/clojure/day2.clj
wmichaelshirk/2020-Advent-of-Code
0
(ns day2 (:require [clojure.java.io :as io])) (defn parse-line [line] (let [[_ min max ch password] (re-matches #"(\d+)-(\d+) (\w): (\w+)" line)] {:min (Integer/parseInt min) :max (Integer/parseInt max) :ch (nth ch 0) :password password} )) (defn read-database [filename] (with-open [rdr (io/reader filename)] (->> rdr line-seq (mapv parse-line)))) (defn valid-password? [{:keys [min max ch password]}] (let [times (get (frequencies password) ch 0)] (<= min times max))) (defn valid-password2? [{:keys [min max ch password]}] (not= (= ch (nth password (dec min))) (= ch (nth password (dec max))))) (defn part-1 [] (->> "./src/main/resources/input_day_2.txt" read-database (filter valid-password?) count)) (defn part-2 [] (->> "./src/main/resources/input_day_2.txt" read-database (filter valid-password2?) count)) (defn run [_] (println "Part 1: " (part-1)) (println "Part 2: " (part-2)))
25178
(ns day2 (:require [clojure.java.io :as io])) (defn parse-line [line] (let [[_ min max ch password] (re-matches #"(\d+)-(\d+) (\w): (\w+)" line)] {:min (Integer/parseInt min) :max (Integer/parseInt max) :ch (nth ch 0) :password <PASSWORD>} )) (defn read-database [filename] (with-open [rdr (io/reader filename)] (->> rdr line-seq (mapv parse-line)))) (defn valid-password? [{:keys [min max ch password]}] (let [times (get (frequencies password) ch 0)] (<= min times max))) (defn valid-password2? [{:keys [min max ch password]}] (not= (= ch (nth password (dec min))) (= ch (nth password (dec max))))) (defn part-1 [] (->> "./src/main/resources/input_day_2.txt" read-database (filter valid-password?) count)) (defn part-2 [] (->> "./src/main/resources/input_day_2.txt" read-database (filter valid-password2?) count)) (defn run [_] (println "Part 1: " (part-1)) (println "Part 2: " (part-2)))
true
(ns day2 (:require [clojure.java.io :as io])) (defn parse-line [line] (let [[_ min max ch password] (re-matches #"(\d+)-(\d+) (\w): (\w+)" line)] {:min (Integer/parseInt min) :max (Integer/parseInt max) :ch (nth ch 0) :password PI:PASSWORD:<PASSWORD>END_PI} )) (defn read-database [filename] (with-open [rdr (io/reader filename)] (->> rdr line-seq (mapv parse-line)))) (defn valid-password? [{:keys [min max ch password]}] (let [times (get (frequencies password) ch 0)] (<= min times max))) (defn valid-password2? [{:keys [min max ch password]}] (not= (= ch (nth password (dec min))) (= ch (nth password (dec max))))) (defn part-1 [] (->> "./src/main/resources/input_day_2.txt" read-database (filter valid-password?) count)) (defn part-2 [] (->> "./src/main/resources/input_day_2.txt" read-database (filter valid-password2?) count)) (defn run [_] (println "Part 1: " (part-1)) (println "Part 2: " (part-2)))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998664855957031, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": "tice, or any other, from this software.\n\n; Author: Frantisek Sodomka, Robert Lachlan\n\n(ns palisades.lakes.test.p2.core", "end": 491, "score": 0.9998656511306763, "start": 474, "tag": "NAME", "value": "Frantisek Sodomka" }, { "context": " from this software.\n\n; Author: Frantisek Sodomka, Robert Lachlan\n\n(ns palisades.lakes.test.p2.core\n \n {:doc \"Tes", "end": 507, "score": 0.999854564666748, "start": 493, "tag": "NAME", "value": "Robert Lachlan" } ]
src/test/clojure/palisades/lakes/test/p2/core.clj
palisades-lakes/collection-experiments
0
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Author: Frantisek Sodomka, Robert Lachlan (ns palisades.lakes.test.p2.core {:doc "Test for the projective plane P2." :author "palisades dot lakes at gmail dot com" :version "2017-12-08"} (:require [clojure.test :as test]) (:import [palisades.lakes.java.p2 D2 H2 Equivalent Rescale])) ;;---------------------------------------------------------------- (test/deftest rescale (let [p0 (D2/make 1.0 2.0) p1 (H2/make 1.0 2.0) p2 (H2/make 2.0 4.0 2.0) p3 (Rescale/rescale 2.0 p0) p4 (Rescale/rescale 2.0 p1) p5 (Rescale/rescale 2.0 p2) pp [p0 p1 p2 p3 p4 p5]] (doseq [pi pp pj pp] (test/is (Equivalent/approximately pi pj) (print-str pi "\n" pj)) (test/is (Equivalent/approximately pi pj (Math/ulp 1.0)) (print-str pi "\n" pj))))) ;;----------------------------------------------------------------
52889
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Author: <NAME>, <NAME> (ns palisades.lakes.test.p2.core {:doc "Test for the projective plane P2." :author "palisades dot lakes at gmail dot com" :version "2017-12-08"} (:require [clojure.test :as test]) (:import [palisades.lakes.java.p2 D2 H2 Equivalent Rescale])) ;;---------------------------------------------------------------- (test/deftest rescale (let [p0 (D2/make 1.0 2.0) p1 (H2/make 1.0 2.0) p2 (H2/make 2.0 4.0 2.0) p3 (Rescale/rescale 2.0 p0) p4 (Rescale/rescale 2.0 p1) p5 (Rescale/rescale 2.0 p2) pp [p0 p1 p2 p3 p4 p5]] (doseq [pi pp pj pp] (test/is (Equivalent/approximately pi pj) (print-str pi "\n" pj)) (test/is (Equivalent/approximately pi pj (Math/ulp 1.0)) (print-str pi "\n" pj))))) ;;----------------------------------------------------------------
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Author: PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI (ns palisades.lakes.test.p2.core {:doc "Test for the projective plane P2." :author "palisades dot lakes at gmail dot com" :version "2017-12-08"} (:require [clojure.test :as test]) (:import [palisades.lakes.java.p2 D2 H2 Equivalent Rescale])) ;;---------------------------------------------------------------- (test/deftest rescale (let [p0 (D2/make 1.0 2.0) p1 (H2/make 1.0 2.0) p2 (H2/make 2.0 4.0 2.0) p3 (Rescale/rescale 2.0 p0) p4 (Rescale/rescale 2.0 p1) p5 (Rescale/rescale 2.0 p2) pp [p0 p1 p2 p3 p4 p5]] (doseq [pi pp pj pp] (test/is (Equivalent/approximately pi pj) (print-str pi "\n" pj)) (test/is (Equivalent/approximately pi pj (Math/ulp 1.0)) (print-str pi "\n" pj))))) ;;----------------------------------------------------------------
[ { "context": "- Natural deduction -- tests\n\n; Copyright (c) 2016 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu", "end": 88, "score": 0.9998692870140076, "start": 74, "tag": "NAME", "value": "Burkhardt Renz" } ]
test/lwb/nd/roths_prop_test.clj
esb-lwb/lwb
22
; lwb Logic WorkBench -- Natural deduction -- tests ; Copyright (c) 2016 Burkhardt Renz, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.nd.roths-prop-test (:require [clojure.test :refer :all] [lwb.nd.rules :refer :all] [lwb.nd.repl :refer :all])) (defn setup [] (load-logic :prop)) (defn fixture [f] (setup) (f)) (use-fixtures :once fixture) (deftest and-test (is (= (roth-structure-forward :and-i) [:g1 :g1 :c?] )) (is (= (apply-roth :and-i '(A B :?)) ;(step-f :and-i m n) '[(and A B)])) (is (= (apply-roth :and-i '(A :? :?)) ;(step-f :and-i m) '[_0 (and A _0)])) (is (= (apply-roth :and-i '(:? B :?)) ;(step-f :and-i :? n) '[_0 (and _0 B)])) (is (= (roth-structure-backward :and-i) [:cm :gb :gb] )) (is (= (apply-roth :and-i '(:? :? (and A B))) ; (step-b :and-i k) '[A B])) (is (= (apply-roth :and-i '(A :? (and A B))) ; (step-b :and-i k m) '[B])) (is (= (apply-roth :and-i '(:? B (and A B))) ; (step-b :and-i k :? n) '[A])) (is (= (roth-structure-forward :and-e1) [:gm :c?] )) (is (= (apply-roth :and-e1 '((and A B) :?)) ; (step-f :and-e1 m) '[A])) (is (= (roth-structure-backward :and-e1) [:cm :g?] )) (is (= (apply-roth :and-e1 '(:? A)) ; (step-b :and-e1 k) '[(and A _0)])) ; :and-e2 analogous ) (deftest or-test (is (= (roth-structure-forward :or-i1) [:gm :c?] )) (is (= (apply-roth :or-i1 '(A :?)) ; (step-f :or-i1 m) '[(or A _0)])) (is (= (roth-structure-backward :or-i1) [:cm :g?] )) (is (= (apply-roth :or-i1 '(:? (or A B))) ; (step-b :or-i1 k) '[A])) ; :or-i2 analogous (is (= (roth-structure-forward :or-e) [:gm :g? :g? :co] )) (is (= (apply-roth :or-e '((or A B) :? :? :?)) ; (step-f :or-e m) '[(infer A _0) (infer B _0) _0])) (is (= (apply-roth :or-e '((or A B) :? :? X)) ; (step-f :or-e m k) '[(infer A X) (infer B X)])) (is (= (roth-structure-backward :or-e) [:cm :go :g? :g?] )) (is (= (apply-roth :or-e '(:? :? :? X)) ; (step-b :or-e k) '[(or _0 _1) (infer _0 X) (infer _1 X)])) (is (= (apply-roth :or-e '((or A B) :? :? X)) ; (step-b :or-e k m) '[(infer A X) (infer B X)])) ) (deftest impl-test (is (= (roth-structure-forward :impl-i) ; backward only nil)) (is (= (roth-structure-backward :impl-i) [:cm :g?] )) (is (= (apply-roth :impl-i '(:? (impl A B))) ; (step-b :impl-i k) '[(infer A B)])) (is (= (roth-structure-forward :impl-e) [:g1 :g1 :c?] )) (is (= (apply-roth :impl-e '((impl A B) A :?)) ; (step-f :impl-e m n) '[B])) (is (= (apply-roth :impl-e '((impl A B) :? :?)); (step-f :impl-e m) -> (impl A B)... A B '[A B])) (is (= (apply-roth :impl-e '((impl A B) :? B)); (step-f :impl-e m :? k) -> (impl A B) ... A B '[A])) (is (= (roth-structure-backward :impl-e) [:cm :gb :gb] )) (is (= (apply-roth :impl-e '(:? :? B)) ; (step-b :impl-e k) -> ... (impl V1 B) ... V1 B '[(impl _0 B) _0])) (is (= (apply-roth :impl-e '(:? A B)) ; (step-b :impl-e k ? n) -> A ... (impl A B) B '[(impl A B)])) (is (= (apply-roth :impl-e '((impl A B) :? B)); (step-b :impl-e k m) -> (impl A B) ... A B '[A])) ) (deftest not-test (is (= (roth-structure-forward :not-i) ; backward only nil)) (is (= (roth-structure-backward :not-i) [:cm :g?] )) (is (= (apply-roth :not-i '(:? (not A))) ; (step-b :not-i k) '[(infer A contradiction)])) (is (= (roth-structure-forward :not-e) [:g1 :g1 :c?] )) (is (= (apply-roth :not-e '((not A) A :?)) ; (step-b :not-i m n) '[contradiction])) (is (= (apply-roth :not-e '((not A) :? :?)) ; (step-f :not-e m) -> (not A) ... A contradiction '[A contradiction])) (is (= (apply-roth :not-e '(:? A :?)) ; (step-f :not-e :? n) -> A ... (not A) contradiction '[(not A) contradiction])) (is (= (roth-structure-backward :not-e) [:cm :gb :gb] )) (is (= (apply-roth :not-e '(:? :? contradiction)); (step-b :not-e k) -> ... (not V1) ... V1 contradiction '[(not _0) _0])) (is (= (apply-roth :not-e '((not A) :? contradiction)); (step-b :not-e k m) -> (not A) ... A contradiction '[A])) (is (= (apply-roth :not-e '(:? A contradiction)); (step-b :not-e k :? n) -> A ... (not A) contradiction '[(not A)])) ) (deftest raa-test (is (= (roth-structure-forward :raa) ; backward only nil)) (is (= (roth-structure-backward :raa) [:cm :g?] )) (is (= (apply-roth :raa '(:? A)) ; (step-b :raa k) '[(infer (not A) contradiction)])) (is (= (roth-structure-forward :efq) [:gm :c?] )) (is (= (apply-roth :efq '(contradiction :?)) ; (step-f :efq m) '[_0])) (is (= (roth-structure-backward :efq) [:cm :g?] )) (is (= (apply-roth :efq '(:? A)) ; (step-b :efq k) '[contradiction])) ) ; theorem without given (deftest tnd-test (is (= (roth-structure-forward :tnd) [:c?])) (is (= (apply-roth :tnd '(:?)) ; (step-f :tnd) '[(or _0 (not _0))])) (is (= (roth-structure-backward :tnd) ; forward only nil)) ) ; theorem with one given (deftest notnot-test (is (= (roth-structure-forward :notnot-i) [:gm :c?])) (is (= (apply-roth :notnot-i '(A :?)) ; (step-f :notnot-i m) '[(not (not A))])) (is (= (roth-structure-backward :notnot-i) [:cm :g?])) (is (= (apply-roth :notnot-i '(:? (not (not A)))); (step-b :not-not-i k) '[A])) ) ; theorem with two givens (deftest mt-test (is (= (roth-structure-forward :mt) [:g1 :g1 :c?])) (is (= (apply-roth :mt '((impl A B) (not B) :?)); (step-f :mt m n) '[(not A)])) (is (= (apply-roth :mt '((impl A B) :? :?)) ; (step-f :mt m) '[(not B) (not A)])) (is (= (apply-roth :mt '( :? (not B) :?)) ; (step-f :mt :? n) '[(impl _0 B) (not _0)])) (is (= (roth-structure-backward :mt) [:cm :gb :gb])) (is (= (apply-roth :mt '(:? :? (not A))) ; (step-b :mt k) '[(impl A _0) (not _0)])) (is (= (apply-roth :mt '(:? (not B) (not A))) ; (step-b :mt k ? n) '[(impl A B)])) (is (= (apply-roth :mt '((impl A B) :? (not A))); (step-b :impl-e k m) '[(not B)])) ) (run-tests)
62563
; lwb Logic WorkBench -- Natural deduction -- tests ; Copyright (c) 2016 <NAME>, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.nd.roths-prop-test (:require [clojure.test :refer :all] [lwb.nd.rules :refer :all] [lwb.nd.repl :refer :all])) (defn setup [] (load-logic :prop)) (defn fixture [f] (setup) (f)) (use-fixtures :once fixture) (deftest and-test (is (= (roth-structure-forward :and-i) [:g1 :g1 :c?] )) (is (= (apply-roth :and-i '(A B :?)) ;(step-f :and-i m n) '[(and A B)])) (is (= (apply-roth :and-i '(A :? :?)) ;(step-f :and-i m) '[_0 (and A _0)])) (is (= (apply-roth :and-i '(:? B :?)) ;(step-f :and-i :? n) '[_0 (and _0 B)])) (is (= (roth-structure-backward :and-i) [:cm :gb :gb] )) (is (= (apply-roth :and-i '(:? :? (and A B))) ; (step-b :and-i k) '[A B])) (is (= (apply-roth :and-i '(A :? (and A B))) ; (step-b :and-i k m) '[B])) (is (= (apply-roth :and-i '(:? B (and A B))) ; (step-b :and-i k :? n) '[A])) (is (= (roth-structure-forward :and-e1) [:gm :c?] )) (is (= (apply-roth :and-e1 '((and A B) :?)) ; (step-f :and-e1 m) '[A])) (is (= (roth-structure-backward :and-e1) [:cm :g?] )) (is (= (apply-roth :and-e1 '(:? A)) ; (step-b :and-e1 k) '[(and A _0)])) ; :and-e2 analogous ) (deftest or-test (is (= (roth-structure-forward :or-i1) [:gm :c?] )) (is (= (apply-roth :or-i1 '(A :?)) ; (step-f :or-i1 m) '[(or A _0)])) (is (= (roth-structure-backward :or-i1) [:cm :g?] )) (is (= (apply-roth :or-i1 '(:? (or A B))) ; (step-b :or-i1 k) '[A])) ; :or-i2 analogous (is (= (roth-structure-forward :or-e) [:gm :g? :g? :co] )) (is (= (apply-roth :or-e '((or A B) :? :? :?)) ; (step-f :or-e m) '[(infer A _0) (infer B _0) _0])) (is (= (apply-roth :or-e '((or A B) :? :? X)) ; (step-f :or-e m k) '[(infer A X) (infer B X)])) (is (= (roth-structure-backward :or-e) [:cm :go :g? :g?] )) (is (= (apply-roth :or-e '(:? :? :? X)) ; (step-b :or-e k) '[(or _0 _1) (infer _0 X) (infer _1 X)])) (is (= (apply-roth :or-e '((or A B) :? :? X)) ; (step-b :or-e k m) '[(infer A X) (infer B X)])) ) (deftest impl-test (is (= (roth-structure-forward :impl-i) ; backward only nil)) (is (= (roth-structure-backward :impl-i) [:cm :g?] )) (is (= (apply-roth :impl-i '(:? (impl A B))) ; (step-b :impl-i k) '[(infer A B)])) (is (= (roth-structure-forward :impl-e) [:g1 :g1 :c?] )) (is (= (apply-roth :impl-e '((impl A B) A :?)) ; (step-f :impl-e m n) '[B])) (is (= (apply-roth :impl-e '((impl A B) :? :?)); (step-f :impl-e m) -> (impl A B)... A B '[A B])) (is (= (apply-roth :impl-e '((impl A B) :? B)); (step-f :impl-e m :? k) -> (impl A B) ... A B '[A])) (is (= (roth-structure-backward :impl-e) [:cm :gb :gb] )) (is (= (apply-roth :impl-e '(:? :? B)) ; (step-b :impl-e k) -> ... (impl V1 B) ... V1 B '[(impl _0 B) _0])) (is (= (apply-roth :impl-e '(:? A B)) ; (step-b :impl-e k ? n) -> A ... (impl A B) B '[(impl A B)])) (is (= (apply-roth :impl-e '((impl A B) :? B)); (step-b :impl-e k m) -> (impl A B) ... A B '[A])) ) (deftest not-test (is (= (roth-structure-forward :not-i) ; backward only nil)) (is (= (roth-structure-backward :not-i) [:cm :g?] )) (is (= (apply-roth :not-i '(:? (not A))) ; (step-b :not-i k) '[(infer A contradiction)])) (is (= (roth-structure-forward :not-e) [:g1 :g1 :c?] )) (is (= (apply-roth :not-e '((not A) A :?)) ; (step-b :not-i m n) '[contradiction])) (is (= (apply-roth :not-e '((not A) :? :?)) ; (step-f :not-e m) -> (not A) ... A contradiction '[A contradiction])) (is (= (apply-roth :not-e '(:? A :?)) ; (step-f :not-e :? n) -> A ... (not A) contradiction '[(not A) contradiction])) (is (= (roth-structure-backward :not-e) [:cm :gb :gb] )) (is (= (apply-roth :not-e '(:? :? contradiction)); (step-b :not-e k) -> ... (not V1) ... V1 contradiction '[(not _0) _0])) (is (= (apply-roth :not-e '((not A) :? contradiction)); (step-b :not-e k m) -> (not A) ... A contradiction '[A])) (is (= (apply-roth :not-e '(:? A contradiction)); (step-b :not-e k :? n) -> A ... (not A) contradiction '[(not A)])) ) (deftest raa-test (is (= (roth-structure-forward :raa) ; backward only nil)) (is (= (roth-structure-backward :raa) [:cm :g?] )) (is (= (apply-roth :raa '(:? A)) ; (step-b :raa k) '[(infer (not A) contradiction)])) (is (= (roth-structure-forward :efq) [:gm :c?] )) (is (= (apply-roth :efq '(contradiction :?)) ; (step-f :efq m) '[_0])) (is (= (roth-structure-backward :efq) [:cm :g?] )) (is (= (apply-roth :efq '(:? A)) ; (step-b :efq k) '[contradiction])) ) ; theorem without given (deftest tnd-test (is (= (roth-structure-forward :tnd) [:c?])) (is (= (apply-roth :tnd '(:?)) ; (step-f :tnd) '[(or _0 (not _0))])) (is (= (roth-structure-backward :tnd) ; forward only nil)) ) ; theorem with one given (deftest notnot-test (is (= (roth-structure-forward :notnot-i) [:gm :c?])) (is (= (apply-roth :notnot-i '(A :?)) ; (step-f :notnot-i m) '[(not (not A))])) (is (= (roth-structure-backward :notnot-i) [:cm :g?])) (is (= (apply-roth :notnot-i '(:? (not (not A)))); (step-b :not-not-i k) '[A])) ) ; theorem with two givens (deftest mt-test (is (= (roth-structure-forward :mt) [:g1 :g1 :c?])) (is (= (apply-roth :mt '((impl A B) (not B) :?)); (step-f :mt m n) '[(not A)])) (is (= (apply-roth :mt '((impl A B) :? :?)) ; (step-f :mt m) '[(not B) (not A)])) (is (= (apply-roth :mt '( :? (not B) :?)) ; (step-f :mt :? n) '[(impl _0 B) (not _0)])) (is (= (roth-structure-backward :mt) [:cm :gb :gb])) (is (= (apply-roth :mt '(:? :? (not A))) ; (step-b :mt k) '[(impl A _0) (not _0)])) (is (= (apply-roth :mt '(:? (not B) (not A))) ; (step-b :mt k ? n) '[(impl A B)])) (is (= (apply-roth :mt '((impl A B) :? (not A))); (step-b :impl-e k m) '[(not B)])) ) (run-tests)
true
; lwb Logic WorkBench -- Natural deduction -- tests ; Copyright (c) 2016 PI:NAME:<NAME>END_PI, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.nd.roths-prop-test (:require [clojure.test :refer :all] [lwb.nd.rules :refer :all] [lwb.nd.repl :refer :all])) (defn setup [] (load-logic :prop)) (defn fixture [f] (setup) (f)) (use-fixtures :once fixture) (deftest and-test (is (= (roth-structure-forward :and-i) [:g1 :g1 :c?] )) (is (= (apply-roth :and-i '(A B :?)) ;(step-f :and-i m n) '[(and A B)])) (is (= (apply-roth :and-i '(A :? :?)) ;(step-f :and-i m) '[_0 (and A _0)])) (is (= (apply-roth :and-i '(:? B :?)) ;(step-f :and-i :? n) '[_0 (and _0 B)])) (is (= (roth-structure-backward :and-i) [:cm :gb :gb] )) (is (= (apply-roth :and-i '(:? :? (and A B))) ; (step-b :and-i k) '[A B])) (is (= (apply-roth :and-i '(A :? (and A B))) ; (step-b :and-i k m) '[B])) (is (= (apply-roth :and-i '(:? B (and A B))) ; (step-b :and-i k :? n) '[A])) (is (= (roth-structure-forward :and-e1) [:gm :c?] )) (is (= (apply-roth :and-e1 '((and A B) :?)) ; (step-f :and-e1 m) '[A])) (is (= (roth-structure-backward :and-e1) [:cm :g?] )) (is (= (apply-roth :and-e1 '(:? A)) ; (step-b :and-e1 k) '[(and A _0)])) ; :and-e2 analogous ) (deftest or-test (is (= (roth-structure-forward :or-i1) [:gm :c?] )) (is (= (apply-roth :or-i1 '(A :?)) ; (step-f :or-i1 m) '[(or A _0)])) (is (= (roth-structure-backward :or-i1) [:cm :g?] )) (is (= (apply-roth :or-i1 '(:? (or A B))) ; (step-b :or-i1 k) '[A])) ; :or-i2 analogous (is (= (roth-structure-forward :or-e) [:gm :g? :g? :co] )) (is (= (apply-roth :or-e '((or A B) :? :? :?)) ; (step-f :or-e m) '[(infer A _0) (infer B _0) _0])) (is (= (apply-roth :or-e '((or A B) :? :? X)) ; (step-f :or-e m k) '[(infer A X) (infer B X)])) (is (= (roth-structure-backward :or-e) [:cm :go :g? :g?] )) (is (= (apply-roth :or-e '(:? :? :? X)) ; (step-b :or-e k) '[(or _0 _1) (infer _0 X) (infer _1 X)])) (is (= (apply-roth :or-e '((or A B) :? :? X)) ; (step-b :or-e k m) '[(infer A X) (infer B X)])) ) (deftest impl-test (is (= (roth-structure-forward :impl-i) ; backward only nil)) (is (= (roth-structure-backward :impl-i) [:cm :g?] )) (is (= (apply-roth :impl-i '(:? (impl A B))) ; (step-b :impl-i k) '[(infer A B)])) (is (= (roth-structure-forward :impl-e) [:g1 :g1 :c?] )) (is (= (apply-roth :impl-e '((impl A B) A :?)) ; (step-f :impl-e m n) '[B])) (is (= (apply-roth :impl-e '((impl A B) :? :?)); (step-f :impl-e m) -> (impl A B)... A B '[A B])) (is (= (apply-roth :impl-e '((impl A B) :? B)); (step-f :impl-e m :? k) -> (impl A B) ... A B '[A])) (is (= (roth-structure-backward :impl-e) [:cm :gb :gb] )) (is (= (apply-roth :impl-e '(:? :? B)) ; (step-b :impl-e k) -> ... (impl V1 B) ... V1 B '[(impl _0 B) _0])) (is (= (apply-roth :impl-e '(:? A B)) ; (step-b :impl-e k ? n) -> A ... (impl A B) B '[(impl A B)])) (is (= (apply-roth :impl-e '((impl A B) :? B)); (step-b :impl-e k m) -> (impl A B) ... A B '[A])) ) (deftest not-test (is (= (roth-structure-forward :not-i) ; backward only nil)) (is (= (roth-structure-backward :not-i) [:cm :g?] )) (is (= (apply-roth :not-i '(:? (not A))) ; (step-b :not-i k) '[(infer A contradiction)])) (is (= (roth-structure-forward :not-e) [:g1 :g1 :c?] )) (is (= (apply-roth :not-e '((not A) A :?)) ; (step-b :not-i m n) '[contradiction])) (is (= (apply-roth :not-e '((not A) :? :?)) ; (step-f :not-e m) -> (not A) ... A contradiction '[A contradiction])) (is (= (apply-roth :not-e '(:? A :?)) ; (step-f :not-e :? n) -> A ... (not A) contradiction '[(not A) contradiction])) (is (= (roth-structure-backward :not-e) [:cm :gb :gb] )) (is (= (apply-roth :not-e '(:? :? contradiction)); (step-b :not-e k) -> ... (not V1) ... V1 contradiction '[(not _0) _0])) (is (= (apply-roth :not-e '((not A) :? contradiction)); (step-b :not-e k m) -> (not A) ... A contradiction '[A])) (is (= (apply-roth :not-e '(:? A contradiction)); (step-b :not-e k :? n) -> A ... (not A) contradiction '[(not A)])) ) (deftest raa-test (is (= (roth-structure-forward :raa) ; backward only nil)) (is (= (roth-structure-backward :raa) [:cm :g?] )) (is (= (apply-roth :raa '(:? A)) ; (step-b :raa k) '[(infer (not A) contradiction)])) (is (= (roth-structure-forward :efq) [:gm :c?] )) (is (= (apply-roth :efq '(contradiction :?)) ; (step-f :efq m) '[_0])) (is (= (roth-structure-backward :efq) [:cm :g?] )) (is (= (apply-roth :efq '(:? A)) ; (step-b :efq k) '[contradiction])) ) ; theorem without given (deftest tnd-test (is (= (roth-structure-forward :tnd) [:c?])) (is (= (apply-roth :tnd '(:?)) ; (step-f :tnd) '[(or _0 (not _0))])) (is (= (roth-structure-backward :tnd) ; forward only nil)) ) ; theorem with one given (deftest notnot-test (is (= (roth-structure-forward :notnot-i) [:gm :c?])) (is (= (apply-roth :notnot-i '(A :?)) ; (step-f :notnot-i m) '[(not (not A))])) (is (= (roth-structure-backward :notnot-i) [:cm :g?])) (is (= (apply-roth :notnot-i '(:? (not (not A)))); (step-b :not-not-i k) '[A])) ) ; theorem with two givens (deftest mt-test (is (= (roth-structure-forward :mt) [:g1 :g1 :c?])) (is (= (apply-roth :mt '((impl A B) (not B) :?)); (step-f :mt m n) '[(not A)])) (is (= (apply-roth :mt '((impl A B) :? :?)) ; (step-f :mt m) '[(not B) (not A)])) (is (= (apply-roth :mt '( :? (not B) :?)) ; (step-f :mt :? n) '[(impl _0 B) (not _0)])) (is (= (roth-structure-backward :mt) [:cm :gb :gb])) (is (= (apply-roth :mt '(:? :? (not A))) ; (step-b :mt k) '[(impl A _0) (not _0)])) (is (= (apply-roth :mt '(:? (not B) (not A))) ; (step-b :mt k ? n) '[(impl A B)])) (is (= (apply-roth :mt '((impl A B) :? (not A))); (step-b :impl-e k m) '[(not B)])) ) (run-tests)
[ { "context": "r substantial portions of the Software.\n\n; Author: Jeremy Kelley <jeremy.kelley@hp.com> @nod\n\n\n;;; Parses cef type", "end": 702, "score": 0.999894380569458, "start": 689, "tag": "NAME", "value": "Jeremy Kelley" }, { "context": "rtions of the Software.\n\n; Author: Jeremy Kelley <jeremy.kelley@hp.com> @nod\n\n\n;;; Parses cef type input into a native h", "end": 724, "score": 0.9999217987060547, "start": 704, "tag": "EMAIL", "value": "jeremy.kelley@hp.com" } ]
src/cefp/cefp.clj
hpsec/cefp
4
; (c) Copyright 2013 Hewlett-Packard Development Company, L.P. ; Licensed under the MIT License. ; 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. ; Author: Jeremy Kelley <jeremy.kelley@hp.com> @nod ;;; Parses cef type input into a native hash. ;;; for now, sort of ignores the key type. ambiguity isn't a bad thing. (ns cefp.cefp (:use [clojure.string :only (split)]) ) ; CEF connector prefixes with pipe delimited before getting to key value data (defn find-kv [cefs] (last (split cefs #"\|" 8)) ) (defn keyval [s] (map #(take-last 2 %) (map #(re-find #"(\w+)=(.*)" %) (split s #" (?=\w+=)")) ) ) ; convenience: keywords to symbols (defn symval [k v] [(keyword k) v]) ; accepts key val pairs and returns dict (defn cef-parse [cefkv] (into {} (map (fn [[k v]] (symval k v)) (keyval cefkv))) ) ; accepts line from Syslog CEF and returns dict (defn cef-from-line [line] (cef-parse (find-kv line)) ) (defn -main [] (println (split "k=v mydog=the cat.is-a beast" #" (?=\w+=)")) )
16950
; (c) Copyright 2013 Hewlett-Packard Development Company, L.P. ; Licensed under the MIT License. ; 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. ; Author: <NAME> <<EMAIL>> @nod ;;; Parses cef type input into a native hash. ;;; for now, sort of ignores the key type. ambiguity isn't a bad thing. (ns cefp.cefp (:use [clojure.string :only (split)]) ) ; CEF connector prefixes with pipe delimited before getting to key value data (defn find-kv [cefs] (last (split cefs #"\|" 8)) ) (defn keyval [s] (map #(take-last 2 %) (map #(re-find #"(\w+)=(.*)" %) (split s #" (?=\w+=)")) ) ) ; convenience: keywords to symbols (defn symval [k v] [(keyword k) v]) ; accepts key val pairs and returns dict (defn cef-parse [cefkv] (into {} (map (fn [[k v]] (symval k v)) (keyval cefkv))) ) ; accepts line from Syslog CEF and returns dict (defn cef-from-line [line] (cef-parse (find-kv line)) ) (defn -main [] (println (split "k=v mydog=the cat.is-a beast" #" (?=\w+=)")) )
true
; (c) Copyright 2013 Hewlett-Packard Development Company, L.P. ; Licensed under the MIT License. ; 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. ; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> @nod ;;; Parses cef type input into a native hash. ;;; for now, sort of ignores the key type. ambiguity isn't a bad thing. (ns cefp.cefp (:use [clojure.string :only (split)]) ) ; CEF connector prefixes with pipe delimited before getting to key value data (defn find-kv [cefs] (last (split cefs #"\|" 8)) ) (defn keyval [s] (map #(take-last 2 %) (map #(re-find #"(\w+)=(.*)" %) (split s #" (?=\w+=)")) ) ) ; convenience: keywords to symbols (defn symval [k v] [(keyword k) v]) ; accepts key val pairs and returns dict (defn cef-parse [cefkv] (into {} (map (fn [[k v]] (symval k v)) (keyval cefkv))) ) ; accepts line from Syslog CEF and returns dict (defn cef-from-line [line] (cef-parse (find-kv line)) ) (defn -main [] (println (split "k=v mydog=the cat.is-a beast" #" (?=\w+=)")) )
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998151063919067, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": ", even\n;; in advanced compilation. See CLJS-1853 - António Monteiro\n;; (def ^{:private true} write-option-table\n;; ", "end": 23613, "score": 0.9638292193412781, "start": 23597, "tag": "NAME", "value": "António Monteiro" } ]
docs/js/compiled/out/cljs/pprint.cljs
kazesberger/git-ws-deck
0
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns cljs.pprint (:refer-clojure :exclude [deftype print println pr prn float?]) (:require-macros [cljs.pprint :as m :refer [with-pretty-writer getf setf deftype pprint-logical-block print-length-loop defdirectives formatter-out]]) (:require [cljs.core :refer [IWriter IDeref]] [clojure.string :as string] [goog.string :as gstring]) (:import [goog.string StringBuffer])) ;;====================================================================== ;; override print fns to use *out* ;;====================================================================== (defn- print [& more] (-write *out* (apply print-str more))) (defn- println [& more] (apply print more) (-write *out* \newline)) (defn- print-char [c] (-write *out* (condp = c \backspace "\\backspace" \tab "\\tab" \newline "\\newline" \formfeed "\\formfeed" \return "\\return" \" "\\\"" \\ "\\\\" (str "\\" c)))) (defn- ^:dynamic pr [& more] (-write *out* (apply pr-str more))) (defn- prn [& more] (apply pr more) (-write *out* \newline)) ;;====================================================================== ;; cljs specific utils ;;====================================================================== (defn ^boolean float? "Returns true if n is an float." [n] (and (number? n) (not ^boolean (js/isNaN n)) (not (identical? n js/Infinity)) (not (== (js/parseFloat n) (js/parseInt n 10))))) (defn char-code "Convert char to int" [c] (cond (number? c) c (and (string? c) (== (.-length c) 1)) (.charCodeAt c 0) :else (throw (js/Error. "Argument to char must be a character or number")))) ;;====================================================================== ;; Utilities ;;====================================================================== (defn- map-passing-context [func initial-context lis] (loop [context initial-context lis lis acc []] (if (empty? lis) [acc context] (let [this (first lis) remainder (next lis) [result new-context] (apply func [this context])] (recur new-context remainder (conj acc result)))))) (defn- consume [func initial-context] (loop [context initial-context acc []] (let [[result new-context] (apply func [context])] (if (not result) [acc new-context] (recur new-context (conj acc result)))))) (defn- consume-while [func initial-context] (loop [context initial-context acc []] (let [[result continue new-context] (apply func [context])] (if (not continue) [acc context] (recur new-context (conj acc result)))))) (defn- unzip-map [m] "Take a map that has pairs in the value slots and produce a pair of maps, the first having all the first elements of the pairs and the second all the second elements of the pairs" [(into {} (for [[k [v1 v2]] m] [k v1])) (into {} (for [[k [v1 v2]] m] [k v2]))]) (defn- tuple-map [m v1] "For all the values, v, in the map, replace them with [v v1]" (into {} (for [[k v] m] [k [v v1]]))) (defn- rtrim [s c] "Trim all instances of c from the end of sequence s" (let [len (count s)] (if (and (pos? len) (= (nth s (dec (count s))) c)) (loop [n (dec len)] (cond (neg? n) "" (not (= (nth s n) c)) (subs s 0 (inc n)) true (recur (dec n)))) s))) (defn- ltrim [s c] "Trim all instances of c from the beginning of sequence s" (let [len (count s)] (if (and (pos? len) (= (nth s 0) c)) (loop [n 0] (if (or (= n len) (not (= (nth s n) c))) (subs s n) (recur (inc n)))) s))) (defn- prefix-count [aseq val] "Return the number of times that val occurs at the start of sequence aseq, if val is a seq itself, count the number of times any element of val occurs at the beginning of aseq" (let [test (if (coll? val) (set val) #{val})] (loop [pos 0] (if (or (= pos (count aseq)) (not (test (nth aseq pos)))) pos (recur (inc pos)))))) ;; Flush the pretty-print buffer without flushing the underlying stream (defprotocol IPrettyFlush (-ppflush [pp])) ;;====================================================================== ;; column_writer.clj ;;====================================================================== (def ^:dynamic ^{:private true} *default-page-width* 72) (defn- get-field [this sym] (sym @@this)) (defn- set-field [this sym new-val] (swap! @this assoc sym new-val)) (defn- get-column [this] (get-field this :cur)) (defn- get-line [this] (get-field this :line)) (defn- get-max-column [this] (get-field this :max)) (defn- set-max-column [this new-max] (set-field this :max new-max) nil) (defn- get-writer [this] (get-field this :base)) ;; Why is the c argument an integer? (defn- c-write-char [this c] (if (= c \newline) (do (set-field this :cur 0) (set-field this :line (inc (get-field this :line)))) (set-field this :cur (inc (get-field this :cur)))) (-write (get-field this :base) c)) (defn- column-writer ([writer] (column-writer writer *default-page-width*)) ([writer max-columns] (let [fields (atom {:max max-columns, :cur 0, :line 0 :base writer})] (reify IDeref (-deref [_] fields) IWriter (-flush [_] (-flush writer)) (-write ;;-write isn't multi-arity, so need different way to do this #_([this ^chars cbuf ^Number off ^Number len] (let [writer (get-field this :base)] (-write writer cbuf off len))) [this x] (condp = (type x) js/String (let [s x nl (.lastIndexOf s \newline)] (if (neg? nl) (set-field this :cur (+ (get-field this :cur) (count s))) (do (set-field this :cur (- (count s) nl 1)) (set-field this :line (+ (get-field this :line) (count (filter #(= % \newline) s)))))) (-write (get-field this :base) s)) js/Number (c-write-char this x))))))) ;;====================================================================== ;; pretty_writer.clj ;;====================================================================== ;;====================================================================== ;; Forward declarations ;;====================================================================== (declare ^{:arglists '([this])} get-miser-width) ;;====================================================================== ;; The data structures used by pretty-writer ;;====================================================================== (defrecord ^{:private true} logical-block [parent section start-col indent done-nl intra-block-nl prefix per-line-prefix suffix logical-block-callback]) (defn- ancestor? [parent child] (loop [child (:parent child)] (cond (nil? child) false (identical? parent child) true :else (recur (:parent child))))) (defn- buffer-length [l] (let [l (seq l)] (if l (- (:end-pos (last l)) (:start-pos (first l))) 0))) ;; A blob of characters (aka a string) (deftype buffer-blob :data :trailing-white-space :start-pos :end-pos) ;; A newline (deftype nl-t :type :logical-block :start-pos :end-pos) (deftype start-block-t :logical-block :start-pos :end-pos) (deftype end-block-t :logical-block :start-pos :end-pos) (deftype indent-t :logical-block :relative-to :offset :start-pos :end-pos) (def ^:private pp-newline (fn [] "\n")) (declare emit-nl) (defmulti ^{:private true} write-token #(:type-tag %2)) (defmethod write-token :start-block-t [this token] (when-let [cb (getf :logical-block-callback)] (cb :start)) (let [lb (:logical-block token)] (when-let [prefix (:prefix lb)] (-write (getf :base) prefix)) (let [col (get-column (getf :base))] (reset! (:start-col lb) col) (reset! (:indent lb) col)))) (defmethod write-token :end-block-t [this token] (when-let [cb (getf :logical-block-callback)] (cb :end)) (when-let [suffix (:suffix (:logical-block token))] (-write (getf :base) suffix))) (defmethod write-token :indent-t [this token] (let [lb (:logical-block token)] (reset! (:indent lb) (+ (:offset token) (condp = (:relative-to token) :block @(:start-col lb) :current (get-column (getf :base))))))) (defmethod write-token :buffer-blob [this token] (-write (getf :base) (:data token))) (defmethod write-token :nl-t [this token] (if (or (= (:type token) :mandatory) (and (not (= (:type token) :fill)) @(:done-nl (:logical-block token)))) (emit-nl this token) (if-let [tws (getf :trailing-white-space)] (-write (getf :base) tws))) (setf :trailing-white-space nil)) (defn- write-tokens [this tokens force-trailing-whitespace] (doseq [token tokens] (if-not (= (:type-tag token) :nl-t) (if-let [tws (getf :trailing-white-space)] (-write (getf :base) tws))) (write-token this token) (setf :trailing-white-space (:trailing-white-space token)) (let [tws (getf :trailing-white-space)] (when (and force-trailing-whitespace tws) (-write (getf :base) tws) (setf :trailing-white-space nil))))) ;;====================================================================== ;; emit-nl? method defs for each type of new line. This makes ;; the decision about whether to print this type of new line. ;;====================================================================== (defn- tokens-fit? [this tokens] (let [maxcol (get-max-column (getf :base))] (or (nil? maxcol) (< (+ (get-column (getf :base)) (buffer-length tokens)) maxcol)))) (defn- linear-nl? [this lb section] (or @(:done-nl lb) (not (tokens-fit? this section)))) (defn- miser-nl? [this lb section] (let [miser-width (get-miser-width this) maxcol (get-max-column (getf :base))] (and miser-width maxcol (>= @(:start-col lb) (- maxcol miser-width)) (linear-nl? this lb section)))) (defmulti ^{:private true} emit-nl? (fn [t _ _ _] (:type t))) (defmethod emit-nl? :linear [newl this section _] (let [lb (:logical-block newl)] (linear-nl? this lb section))) (defmethod emit-nl? :miser [newl this section _] (let [lb (:logical-block newl)] (miser-nl? this lb section))) (defmethod emit-nl? :fill [newl this section subsection] (let [lb (:logical-block newl)] (or @(:intra-block-nl lb) (not (tokens-fit? this subsection)) (miser-nl? this lb section)))) (defmethod emit-nl? :mandatory [_ _ _ _] true) ;;====================================================================== ;; Various support functions ;;====================================================================== (defn- get-section [buffer] (let [nl (first buffer) lb (:logical-block nl) section (seq (take-while #(not (and (nl-t? %) (ancestor? (:logical-block %) lb))) (next buffer)))] [section (seq (drop (inc (count section)) buffer))])) (defn- get-sub-section [buffer] (let [nl (first buffer) lb (:logical-block nl) section (seq (take-while #(let [nl-lb (:logical-block %)] (not (and (nl-t? %) (or (= nl-lb lb) (ancestor? nl-lb lb))))) (next buffer)))] section)) (defn- update-nl-state [lb] (reset! (:intra-block-nl lb) true) (reset! (:done-nl lb) true) (loop [lb (:parent lb)] (if lb (do (reset! (:done-nl lb) true) (reset! (:intra-block-nl lb) true) (recur (:parent lb)))))) (defn- emit-nl [this nl] (-write (getf :base) (pp-newline)) (setf :trailing-white-space nil) (let [lb (:logical-block nl) prefix (:per-line-prefix lb)] (if prefix (-write (getf :base) prefix)) (let [istr (apply str (repeat (- @(:indent lb) (count prefix)) \space))] (-write (getf :base) istr)) (update-nl-state lb))) (defn- split-at-newline [tokens] (let [pre (seq (take-while #(not (nl-t? %)) tokens))] [pre (seq (drop (count pre) tokens))])) ;; write-token-string is called when the set of tokens in the buffer ;; is long than the available space on the line (defn- write-token-string [this tokens] (let [[a b] (split-at-newline tokens)] (if a (write-tokens this a false)) (if b (let [[section remainder] (get-section b) newl (first b)] (let [do-nl (emit-nl? newl this section (get-sub-section b)) result (if do-nl (do (emit-nl this newl) (next b)) b) long-section (not (tokens-fit? this result)) result (if long-section (let [rem2 (write-token-string this section)] (if (= rem2 section) (do ; If that didn't produce any output, it has no nls ; so we'll force it (write-tokens this section false) remainder) (into [] (concat rem2 remainder)))) result)] result))))) (defn- write-line [this] (loop [buffer (getf :buffer)] (setf :buffer (into [] buffer)) (if (not (tokens-fit? this buffer)) (let [new-buffer (write-token-string this buffer)] (if-not (identical? buffer new-buffer) (recur new-buffer)))))) ;; Add a buffer token to the buffer and see if it's time to start ;; writing (defn- add-to-buffer [this token] (setf :buffer (conj (getf :buffer) token)) (if (not (tokens-fit? this (getf :buffer))) (write-line this))) ;; Write all the tokens that have been buffered (defn- write-buffered-output [this] (write-line this) (if-let [buf (getf :buffer)] (do (write-tokens this buf true) (setf :buffer [])))) (defn- write-white-space [this] (when-let [tws (getf :trailing-white-space)] (-write (getf :base) tws) (setf :trailing-white-space nil))) ;;; If there are newlines in the string, print the lines up until the last newline, ;;; making the appropriate adjustments. Return the remainder of the string (defn- write-initial-lines [^Writer this ^String s] (let [lines (string/split s "\n" -1)] (if (= (count lines) 1) s (let [^String prefix (:per-line-prefix (first (getf :logical-blocks))) ^String l (first lines)] (if (= :buffering (getf :mode)) (let [oldpos (getf :pos) newpos (+ oldpos (count l))] (setf :pos newpos) (add-to-buffer this (make-buffer-blob l nil oldpos newpos)) (write-buffered-output this)) (do (write-white-space this) (-write (getf :base) l))) (-write (getf :base) \newline) (doseq [^String l (next (butlast lines))] (-write (getf :base) l) (-write (getf :base) (pp-newline)) (if prefix (-write (getf :base) prefix))) (setf :buffering :writing) (last lines))))) (defn- p-write-char [this c] (if (= (getf :mode) :writing) (do (write-white-space this) (-write (getf :base) c)) (if (= c \newline) (write-initial-lines this \newline) (let [oldpos (getf :pos) newpos (inc oldpos)] (setf :pos newpos) (add-to-buffer this (make-buffer-blob (char c) nil oldpos newpos)))))) ;;====================================================================== ;; Initialize the pretty-writer instance ;;====================================================================== (defn- pretty-writer [writer max-columns miser-width] (let [lb (logical-block. nil nil (atom 0) (atom 0) (atom false) (atom false) nil nil nil nil) ; NOTE: may want to just `specify!` #js { ... fields ... } with the protocols fields (atom {:pretty-writer true :base (column-writer writer max-columns) :logical-blocks lb :sections nil :mode :writing :buffer [] :buffer-block lb :buffer-level 1 :miser-width miser-width :trailing-white-space nil :pos 0})] (reify IDeref (-deref [_] fields) IWriter (-write [this x] (condp = (type x) js/String (let [s0 (write-initial-lines this x) s (string/replace-first s0 #"\s+$" "") white-space (subs s0 (count s)) mode (getf :mode)] (if (= mode :writing) (do (write-white-space this) (-write (getf :base) s) (setf :trailing-white-space white-space)) (let [oldpos (getf :pos) newpos (+ oldpos (count s0))] (setf :pos newpos) (add-to-buffer this (make-buffer-blob s white-space oldpos newpos))))) js/Number (p-write-char this x))) (-flush [this] (-ppflush this) (-flush (getf :base))) IPrettyFlush (-ppflush [this] (if (= (getf :mode) :buffering) (do (write-tokens this (getf :buffer) true) (setf :buffer [])) (write-white-space this))) ))) ;;====================================================================== ;; Methods for pretty-writer ;;====================================================================== (defn- start-block [this prefix per-line-prefix suffix] (let [lb (logical-block. (getf :logical-blocks) nil (atom 0) (atom 0) (atom false) (atom false) prefix per-line-prefix suffix nil)] (setf :logical-blocks lb) (if (= (getf :mode) :writing) (do (write-white-space this) (when-let [cb (getf :logical-block-callback)] (cb :start)) (if prefix (-write (getf :base) prefix)) (let [col (get-column (getf :base))] (reset! (:start-col lb) col) (reset! (:indent lb) col))) (let [oldpos (getf :pos) newpos (+ oldpos (if prefix (count prefix) 0))] (setf :pos newpos) (add-to-buffer this (make-start-block-t lb oldpos newpos)))))) (defn- end-block [this] (let [lb (getf :logical-blocks) suffix (:suffix lb)] (if (= (getf :mode) :writing) (do (write-white-space this) (if suffix (-write (getf :base) suffix)) (when-let [cb (getf :logical-block-callback)] (cb :end))) (let [oldpos (getf :pos) newpos (+ oldpos (if suffix (count suffix) 0))] (setf :pos newpos) (add-to-buffer this (make-end-block-t lb oldpos newpos)))) (setf :logical-blocks (:parent lb)))) (defn- nl [this type] (setf :mode :buffering) (let [pos (getf :pos)] (add-to-buffer this (make-nl-t type (getf :logical-blocks) pos pos)))) (defn- indent [this relative-to offset] (let [lb (getf :logical-blocks)] (if (= (getf :mode) :writing) (do (write-white-space this) (reset! (:indent lb) (+ offset (condp = relative-to :block @(:start-col lb) :current (get-column (getf :base)))))) (let [pos (getf :pos)] (add-to-buffer this (make-indent-t lb relative-to offset pos pos)))))) (defn- get-miser-width [this] (getf :miser-width)) ;;====================================================================== ;; pprint_base.clj ;;====================================================================== ;;====================================================================== ;; Variables that control the pretty printer ;;====================================================================== ;; *print-length*, *print-level*, *print-namespace-maps* and *print-dup* are defined in cljs.core (def ^:dynamic ^{:doc "Bind to true if you want write to use pretty printing"} *print-pretty* true) (defonce ^:dynamic ^{:doc "The pretty print dispatch function. Use with-pprint-dispatch or set-pprint-dispatch to modify." :added "1.2"} *print-pprint-dispatch* nil) (def ^:dynamic ^{:doc "Pretty printing will try to avoid anything going beyond this column. Set it to nil to have pprint let the line be arbitrarily long. This will ignore all non-mandatory newlines.", :added "1.2"} *print-right-margin* 72) (def ^:dynamic ^{:doc "The column at which to enter miser style. Depending on the dispatch table, miser style add newlines in more places to try to keep lines short allowing for further levels of nesting.", :added "1.2"} *print-miser-width* 40) ;;; TODO implement output limiting (def ^:dynamic ^{:private true, :doc "Maximum number of lines to print in a pretty print instance (N.B. This is not yet used)"} *print-lines* nil) ;;; TODO: implement circle and shared (def ^:dynamic ^{:private true, :doc "Mark circular structures (N.B. This is not yet used)"} *print-circle* nil) ;;; TODO: should we just use *print-dup* here? (def ^:dynamic ^{:private true, :doc "Mark repeated structures rather than repeat them (N.B. This is not yet used)"} *print-shared* nil) (def ^:dynamic ^{:doc "Don't print namespaces with symbols. This is particularly useful when pretty printing the results of macro expansions" :added "1.2"} *print-suppress-namespaces* nil) ;;; TODO: support print-base and print-radix in cl-format ;;; TODO: support print-base and print-radix in rationals (def ^:dynamic ^{:doc "Print a radix specifier in front of integers and rationals. If *print-base* is 2, 8, or 16, then the radix specifier used is #b, #o, or #x, respectively. Otherwise the radix specifier is in the form #XXr where XX is the decimal value of *print-base* " :added "1.2"} *print-radix* nil) (def ^:dynamic ^{:doc "The base to use for printing integers and rationals." :added "1.2"} *print-base* 10) ;;====================================================================== ;; Internal variables that keep track of where we are in the ;; structure ;;====================================================================== (def ^:dynamic ^{:private true} *current-level* 0) (def ^:dynamic ^{:private true} *current-length* nil) ;;====================================================================== ;; Support for the write function ;;====================================================================== (declare ^{:arglists '([n])} format-simple-number) ;; This map causes var metadata to be included in the compiled output, even ;; in advanced compilation. See CLJS-1853 - António Monteiro ;; (def ^{:private true} write-option-table ;; {;:array *print-array* ;; :base #'cljs.pprint/*print-base*, ;; ;;:case *print-case*, ;; :circle #'cljs.pprint/*print-circle*, ;; ;;:escape *print-escape*, ;; ;;:gensym *print-gensym*, ;; :length #'cljs.core/*print-length*, ;; :level #'cljs.core/*print-level*, ;; :lines #'cljs.pprint/*print-lines*, ;; :miser-width #'cljs.pprint/*print-miser-width*, ;; :dispatch #'cljs.pprint/*print-pprint-dispatch*, ;; :pretty #'cljs.pprint/*print-pretty*, ;; :radix #'cljs.pprint/*print-radix*, ;; :readably #'cljs.core/*print-readably*, ;; :right-margin #'cljs.pprint/*print-right-margin*, ;; :suppress-namespaces #'cljs.pprint/*print-suppress-namespaces*}) (defn- table-ize [t m] (apply hash-map (mapcat #(when-let [v (get t (key %))] [v (val %)]) m))) (defn- pretty-writer? "Return true iff x is a PrettyWriter" [x] (and (satisfies? IDeref x) (:pretty-writer @@x))) (defn- make-pretty-writer "Wrap base-writer in a PrettyWriter with the specified right-margin and miser-width" [base-writer right-margin miser-width] (pretty-writer base-writer right-margin miser-width)) (defn write-out "Write an object to *out* subject to the current bindings of the printer control variables. Use the kw-args argument to override individual variables for this call (and any recursive calls). *out* must be a PrettyWriter if pretty printing is enabled. This is the responsibility of the caller. This method is primarily intended for use by pretty print dispatch functions that already know that the pretty printer will have set up their environment appropriately. Normal library clients should use the standard \"write\" interface. " [object] (let [length-reached (and *current-length* *print-length* (>= *current-length* *print-length*))] (if-not *print-pretty* (pr object) (if length-reached (-write *out* "...") ;;TODO could this (incorrectly) print ... on the next line? (do (if *current-length* (set! *current-length* (inc *current-length*))) (*print-pprint-dispatch* object)))) length-reached)) (defn write "Write an object subject to the current bindings of the printer control variables. Use the kw-args argument to override individual variables for this call (and any recursive calls). Returns the string result if :stream is nil or nil otherwise. The following keyword arguments can be passed with values: Keyword Meaning Default value :stream Writer for output or nil true (indicates *out*) :base Base to use for writing rationals Current value of *print-base* :circle* If true, mark circular structures Current value of *print-circle* :length Maximum elements to show in sublists Current value of *print-length* :level Maximum depth Current value of *print-level* :lines* Maximum lines of output Current value of *print-lines* :miser-width Width to enter miser mode Current value of *print-miser-width* :dispatch The pretty print dispatch function Current value of *print-pprint-dispatch* :pretty If true, do pretty printing Current value of *print-pretty* :radix If true, prepend a radix specifier Current value of *print-radix* :readably* If true, print readably Current value of *print-readably* :right-margin The column for the right margin Current value of *print-right-margin* :suppress-namespaces If true, no namespaces in symbols Current value of *print-suppress-namespaces* * = not yet supported " [object & kw-args] (let [options (merge {:stream true} (apply hash-map kw-args))] ;;TODO rewrite this as a macro (binding [cljs.pprint/*print-base* (:base options cljs.pprint/*print-base*) ;;:case *print-case*, cljs.pprint/*print-circle* (:circle options cljs.pprint/*print-circle*) ;;:escape *print-escape* ;;:gensym *print-gensym* cljs.core/*print-length* (:length options cljs.core/*print-length*) cljs.core/*print-level* (:level options cljs.core/*print-level*) cljs.pprint/*print-lines* (:lines options cljs.pprint/*print-lines*) cljs.pprint/*print-miser-width* (:miser-width options cljs.pprint/*print-miser-width*) cljs.pprint/*print-pprint-dispatch* (:dispatch options cljs.pprint/*print-pprint-dispatch*) cljs.pprint/*print-pretty* (:pretty options cljs.pprint/*print-pretty*) cljs.pprint/*print-radix* (:radix options cljs.pprint/*print-radix*) cljs.core/*print-readably* (:readably options cljs.core/*print-readably*) cljs.pprint/*print-right-margin* (:right-margin options cljs.pprint/*print-right-margin*) cljs.pprint/*print-suppress-namespaces* (:suppress-namespaces options cljs.pprint/*print-suppress-namespaces*)] ;;TODO enable printing base #_[bindings (if (or (not (= *print-base* 10)) *print-radix*) {#'pr pr-with-base} {})] (binding [] (let [sb (StringBuffer.) optval (if (contains? options :stream) (:stream options) true) base-writer (if (or (true? optval) (nil? optval)) (StringBufferWriter. sb) optval)] (if *print-pretty* (with-pretty-writer base-writer (write-out object)) (binding [*out* base-writer] (pr object))) (if (true? optval) (string-print (str sb))) (if (nil? optval) (str sb))))))) (defn pprint ([object] (let [sb (StringBuffer.)] (binding [*out* (StringBufferWriter. sb)] (pprint object *out*) (string-print (str sb))))) ([object writer] (with-pretty-writer writer (binding [*print-pretty* true] (write-out object)) (if (not (= 0 (get-column *out*))) (-write *out* \newline))))) (defn set-pprint-dispatch [function] (set! *print-pprint-dispatch* function) nil) ;;====================================================================== ;; Support for the functional interface to the pretty printer ;;====================================================================== (defn- check-enumerated-arg [arg choices] (if-not (choices arg) ;; TODO clean up choices string (throw (js/Error. (str "Bad argument: " arg ". It must be one of " choices))))) (defn- level-exceeded [] (and *print-level* (>= *current-level* *print-level*))) (defn pprint-newline "Print a conditional newline to a pretty printing stream. kind specifies if the newline is :linear, :miser, :fill, or :mandatory. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer." [kind] (check-enumerated-arg kind #{:linear :miser :fill :mandatory}) (nl *out* kind)) (defn pprint-indent "Create an indent at this point in the pretty printing stream. This defines how following lines are indented. relative-to can be either :block or :current depending whether the indent should be computed relative to the start of the logical block or the current column position. n is an offset. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer." [relative-to n] (check-enumerated-arg relative-to #{:block :current}) (indent *out* relative-to n)) ;; TODO a real implementation for pprint-tab (defn pprint-tab "Tab at this point in the pretty printing stream. kind specifies whether the tab is :line, :section, :line-relative, or :section-relative. Colnum and colinc specify the target column and the increment to move the target forward if the output is already past the original target. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer. THIS FUNCTION IS NOT YET IMPLEMENTED." {:added "1.2"} [kind colnum colinc] (check-enumerated-arg kind #{:line :section :line-relative :section-relative}) (throw (js/Error. "pprint-tab is not yet implemented"))) ;;====================================================================== ;; cl_format.clj ;;====================================================================== ;; Forward references (declare ^{:arglists '([format-str])} compile-format) (declare ^{:arglists '([stream format args] [format args])} execute-format) (declare ^{:arglists '([s])} init-navigator) ;; End forward references (defn cl-format "An implementation of a Common Lisp compatible format function. cl-format formats its arguments to an output stream or string based on the format control string given. It supports sophisticated formatting of structured data. Writer satisfies IWriter, true to output via *print-fn* or nil to output to a string, format-in is the format control string and the remaining arguments are the data to be formatted. The format control string is a string to be output with embedded 'format directives' describing how to format the various arguments passed in. If writer is nil, cl-format returns the formatted result string. Otherwise, cl-format returns nil. For example: (let [results [46 38 22]] (cl-format true \"There ~[are~;is~:;are~]~:* ~d result~:p: ~{~d~^, ~}~%\" (count results) results)) Prints via *print-fn*: There are 3 results: 46, 38, 22 Detailed documentation on format control strings is available in the \"Common Lisp the Language, 2nd edition\", Chapter 22 (available online at: http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000) and in the Common Lisp HyperSpec at http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm" {:see-also [["http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000" "Common Lisp the Language"] ["http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm" "Common Lisp HyperSpec"]]} [writer format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format writer compiled-format navigator))) (def ^:dynamic ^{:private true} *format-str* nil) (defn- format-error [message offset] (let [full-message (str message \newline *format-str* \newline (apply str (repeat offset \space)) "^" \newline)] (throw (js/Error full-message)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Argument navigators manage the argument list ;; as the format statement moves through the list ;; (possibly going forwards and backwards as it does so) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord ^{:private true} arg-navigator [seq rest pos]) (defn- init-navigator "Create a new arg-navigator from the sequence with the position set to 0" {:skip-wiki true} [s] (let [s (seq s)] (arg-navigator. s s 0))) ;; TODO call format-error with offset (defn- next-arg [navigator] (let [rst (:rest navigator)] (if rst [(first rst) (arg-navigator. (:seq navigator) (next rst) (inc (:pos navigator)))] (throw (js/Error "Not enough arguments for format definition"))))) (defn- next-arg-or-nil [navigator] (let [rst (:rest navigator)] (if rst [(first rst) (arg-navigator. (:seq navigator) (next rst) (inc (:pos navigator)))] [nil navigator]))) ;; Get an argument off the arg list and compile it if it's not already compiled (defn- get-format-arg [navigator] (let [[raw-format navigator] (next-arg navigator) compiled-format (if (string? raw-format) (compile-format raw-format) raw-format)] [compiled-format navigator])) (declare relative-reposition) (defn- absolute-reposition [navigator position] (if (>= position (:pos navigator)) (relative-reposition navigator (- (:pos navigator) position)) (arg-navigator. (:seq navigator) (drop position (:seq navigator)) position))) (defn- relative-reposition [navigator position] (let [newpos (+ (:pos navigator) position)] (if (neg? position) (absolute-reposition navigator newpos) (arg-navigator. (:seq navigator) (drop position (:rest navigator)) newpos)))) (defrecord ^{:private true} compiled-directive [func def params offset]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; When looking at the parameter list, we may need to manipulate ;; the argument list as well (for 'V' and '#' parameter types). ;; We hide all of this behind a function, but clients need to ;; manage changing arg navigator ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO: validate parameters when they come from arg list (defn- realize-parameter [[param [raw-val offset]] navigator] (let [[real-param new-navigator] (cond (contains? #{:at :colon} param) ;pass flags through unchanged - this really isn't necessary [raw-val navigator] (= raw-val :parameter-from-args) (next-arg navigator) (= raw-val :remaining-arg-count) [(count (:rest navigator)) navigator] true [raw-val navigator])] [[param [real-param offset]] new-navigator])) (defn- realize-parameter-list [parameter-map navigator] (let [[pairs new-navigator] (map-passing-context realize-parameter navigator parameter-map)] [(into {} pairs) new-navigator])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Functions that support individual directives ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Common handling code for ~A and ~S ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare ^{:arglists '([base val])} opt-base-str) (def ^{:private true} special-radix-markers {2 "#b" 8 "#o" 16 "#x"}) (defn- format-simple-number [n] (cond (integer? n) (if (= *print-base* 10) (str n (if *print-radix* ".")) (str (if *print-radix* (or (get special-radix-markers *print-base*) (str "#" *print-base* "r"))) (opt-base-str *print-base* n))) ;;(ratio? n) ;;no ratio support :else nil)) (defn- format-ascii [print-func params arg-navigator offsets] (let [[arg arg-navigator] (next-arg arg-navigator) base-output (or (format-simple-number arg) (print-func arg)) base-width (.-length base-output) min-width (+ base-width (:minpad params)) width (if (>= min-width (:mincol params)) min-width (+ min-width (* (+ (quot (- (:mincol params) min-width 1) (:colinc params)) 1) (:colinc params)))) chars (apply str (repeat (- width base-width) (:padchar params)))] (if (:at params) (print (str chars base-output)) (print (str base-output chars))) arg-navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the integer directives ~D, ~X, ~O, ~B and some ;; of ~R ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- integral? "returns true if a number is actually an integer (that is, has no fractional part)" [x] (cond (integer? x) true ;;(decimal? x) ;;no decimal support (float? x) (= x (Math/floor x)) ;;(ratio? x) ;;no ratio support :else false)) (defn- remainders "Return the list of remainders (essentially the 'digits') of val in the given base" [base val] (reverse (first (consume #(if (pos? %) [(rem % base) (quot % base)] [nil nil]) val)))) ;; TODO: xlated-val does not seem to be used here. ;; NB (defn- base-str "Return val as a string in the given base" [base val] (if (zero? val) "0" (let [xlated-val (cond ;(float? val) (bigdec val) ;;No bigdec ;(ratio? val) nil ;;No ratio :else val)] (apply str (map #(if (< % 10) (char (+ (char-code \0) %)) (char (+ (char-code \a) (- % 10)))) (remainders base val)))))) ;;Not sure if this is accurate or necessary (def ^{:private true} javascript-base-formats {8 "%o", 10 "%d", 16 "%x"}) (defn- opt-base-str "Return val as a string in the given base. No cljs format, so no improved performance." [base val] (base-str base val)) (defn- group-by* [unit lis] (reverse (first (consume (fn [x] [(seq (reverse (take unit x))) (seq (drop unit x))]) (reverse lis))))) (defn- format-integer [base params arg-navigator offsets] (let [[arg arg-navigator] (next-arg arg-navigator)] (if (integral? arg) (let [neg (neg? arg) pos-arg (if neg (- arg) arg) raw-str (opt-base-str base pos-arg) group-str (if (:colon params) (let [groups (map #(apply str %) (group-by* (:commainterval params) raw-str)) commas (repeat (count groups) (:commachar params))] (apply str (next (interleave commas groups)))) raw-str) signed-str (cond neg (str "-" group-str) (:at params) (str "+" group-str) true group-str) padded-str (if (< (.-length signed-str) (:mincol params)) (str (apply str (repeat (- (:mincol params) (.-length signed-str)) (:padchar params))) signed-str) signed-str)] (print padded-str)) (format-ascii print-str {:mincol (:mincol params) :colinc 1 :minpad 0 :padchar (:padchar params) :at true} (init-navigator [arg]) nil)) arg-navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for english formats (~R and ~:R) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} english-cardinal-units ["zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine" "ten" "eleven" "twelve" "thirteen" "fourteen" "fifteen" "sixteen" "seventeen" "eighteen" "nineteen"]) (def ^{:private true} english-ordinal-units ["zeroth" "first" "second" "third" "fourth" "fifth" "sixth" "seventh" "eighth" "ninth" "tenth" "eleventh" "twelfth" "thirteenth" "fourteenth" "fifteenth" "sixteenth" "seventeenth" "eighteenth" "nineteenth"]) (def ^{:private true} english-cardinal-tens ["" "" "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty" "ninety"]) (def ^{:private true} english-ordinal-tens ["" "" "twentieth" "thirtieth" "fortieth" "fiftieth" "sixtieth" "seventieth" "eightieth" "ninetieth"]) ;; We use "short scale" for our units (see http://en.wikipedia.org/wiki/Long_and_short_scales) ;; Number names from http://www.jimloy.com/math/billion.htm ;; We follow the rules for writing numbers from the Blue Book ;; (http://www.grammarbook.com/numbers/numbers.asp) (def ^{:private true} english-scale-numbers ["" "thousand" "million" "billion" "trillion" "quadrillion" "quintillion" "sextillion" "septillion" "octillion" "nonillion" "decillion" "undecillion" "duodecillion" "tredecillion" "quattuordecillion" "quindecillion" "sexdecillion" "septendecillion" "octodecillion" "novemdecillion" "vigintillion"]) (defn- format-simple-cardinal "Convert a number less than 1000 to a cardinal english string" [num] (let [hundreds (quot num 100) tens (rem num 100)] (str (if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred")) (if (and (pos? hundreds) (pos? tens)) " ") (if (pos? tens) (if (< tens 20) (nth english-cardinal-units tens) (let [ten-digit (quot tens 10) unit-digit (rem tens 10)] (str (if (pos? ten-digit) (nth english-cardinal-tens ten-digit)) (if (and (pos? ten-digit) (pos? unit-digit)) "-") (if (pos? unit-digit) (nth english-cardinal-units unit-digit))))))))) (defn- add-english-scales "Take a sequence of parts, add scale numbers (e.g., million) and combine into a string offset is a factor of 10^3 to multiply by" [parts offset] (let [cnt (count parts)] (loop [acc [] pos (dec cnt) this (first parts) remainder (next parts)] (if (nil? remainder) (str (apply str (interpose ", " acc)) (if (and (not (empty? this)) (not (empty? acc))) ", ") this (if (and (not (empty? this)) (pos? (+ pos offset))) (str " " (nth english-scale-numbers (+ pos offset))))) (recur (if (empty? this) acc (conj acc (str this " " (nth english-scale-numbers (+ pos offset))))) (dec pos) (first remainder) (next remainder)))))) (defn- format-cardinal-english [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (= 0 arg) (print "zero") (let [abs-arg (if (neg? arg) (- arg) arg) ; some numbers are too big for Math/abs (is this true?) parts (remainders 1000 abs-arg)] (if (<= (count parts) (count english-scale-numbers)) (let [parts-strs (map format-simple-cardinal parts) full-str (add-english-scales parts-strs 0)] (print (str (if (neg? arg) "minus ") full-str))) (format-integer ;; for numbers > 10^63, we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0})))) navigator)) (defn- format-simple-ordinal "Convert a number less than 1000 to a ordinal english string Note this should only be used for the last one in the sequence" [num] (let [hundreds (quot num 100) tens (rem num 100)] (str (if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred")) (if (and (pos? hundreds) (pos? tens)) " ") (if (pos? tens) (if (< tens 20) (nth english-ordinal-units tens) (let [ten-digit (quot tens 10) unit-digit (rem tens 10)] (if (and (pos? ten-digit) (not (pos? unit-digit))) (nth english-ordinal-tens ten-digit) (str (if (pos? ten-digit) (nth english-cardinal-tens ten-digit)) (if (and (pos? ten-digit) (pos? unit-digit)) "-") (if (pos? unit-digit) (nth english-ordinal-units unit-digit)))))) (if (pos? hundreds) "th"))))) (defn- format-ordinal-english [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (= 0 arg) (print "zeroth") (let [abs-arg (if (neg? arg) (- arg) arg) ; some numbers are too big for Math/abs (is this true?) parts (remainders 1000 abs-arg)] (if (<= (count parts) (count english-scale-numbers)) (let [parts-strs (map format-simple-cardinal (drop-last parts)) head-str (add-english-scales parts-strs 1) tail-str (format-simple-ordinal (last parts))] (print (str (if (neg? arg) "minus ") (cond (and (not (empty? head-str)) (not (empty? tail-str))) (str head-str ", " tail-str) (not (empty? head-str)) (str head-str "th") :else tail-str)))) (do (format-integer ;for numbers > 10^63, we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0}) (let [low-two-digits (rem arg 100) not-teens (or (< 11 low-two-digits) (> 19 low-two-digits)) low-digit (rem low-two-digits 10)] (print (cond (and (== low-digit 1) not-teens) "st" (and (== low-digit 2) not-teens) "nd" (and (== low-digit 3) not-teens) "rd" :else "th"))))))) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for roman numeral formats (~@R and ~@:R) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} old-roman-table [[ "I" "II" "III" "IIII" "V" "VI" "VII" "VIII" "VIIII"] [ "X" "XX" "XXX" "XXXX" "L" "LX" "LXX" "LXXX" "LXXXX"] [ "C" "CC" "CCC" "CCCC" "D" "DC" "DCC" "DCCC" "DCCCC"] [ "M" "MM" "MMM"]]) (def ^{:private true} new-roman-table [[ "I" "II" "III" "IV" "V" "VI" "VII" "VIII" "IX"] [ "X" "XX" "XXX" "XL" "L" "LX" "LXX" "LXXX" "XC"] [ "C" "CC" "CCC" "CD" "D" "DC" "DCC" "DCCC" "CM"] [ "M" "MM" "MMM"]]) (defn- format-roman "Format a roman numeral using the specified look-up table" [table params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (and (number? arg) (> arg 0) (< arg 4000)) (let [digits (remainders 10 arg)] (loop [acc [] pos (dec (count digits)) digits digits] (if (empty? digits) (print (apply str acc)) (let [digit (first digits)] (recur (if (= 0 digit) acc (conj acc (nth (nth table pos) (dec digit)))) (dec pos) (next digits)))))) (format-integer ; for anything <= 0 or > 3999, we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0})) navigator)) (defn- format-old-roman [params navigator offsets] (format-roman old-roman-table params navigator offsets)) (defn- format-new-roman [params navigator offsets] (format-roman new-roman-table params navigator offsets)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for character formats (~C) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} special-chars {8 "Backspace", 9 "Tab", 10 "Newline", 13 "Return", 32 "Space"}) (defn- pretty-character [params navigator offsets] (let [[c navigator] (next-arg navigator) as-int (char-code c) base-char (bit-and as-int 127) meta (bit-and as-int 128) special (get special-chars base-char)] (if (> meta 0) (print "Meta-")) (print (cond special special (< base-char 32) (str "Control-" (char (+ base-char 64))) (= base-char 127) "Control-?" :else (char base-char))) navigator)) (defn- readable-character [params navigator offsets] (let [[c navigator] (next-arg navigator)] (condp = (:char-format params) \o (cl-format true "\\o~3, '0o" (char-code c)) \u (cl-format true "\\u~4, '0x" (char-code c)) nil (print-char c)) navigator)) (defn- plain-character [params navigator offsets] (let [[char navigator] (next-arg navigator)] (print char) navigator)) ;; Check to see if a result is an abort (~^) construct ;; TODO: move these funcs somewhere more appropriate (defn- abort? [context] (let [token (first context)] (or (= :up-arrow token) (= :colon-up-arrow token)))) ;; Handle the execution of "sub-clauses" in bracket constructions (defn- execute-sub-format [format args base-args] (second (map-passing-context (fn [element context] (if (abort? context) [nil context] ; just keep passing it along (let [[params args] (realize-parameter-list (:params element) context) [params offsets] (unzip-map params) params (assoc params :base-args base-args)] [nil (apply (:func element) [params args offsets])]))) args format))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for real number formats ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO - return exponent as int to eliminate double conversion (defn- float-parts-base "Produce string parts for the mantissa (normalize 1-9) and exponent" [f] (let [s (string/lower-case (str f)) exploc (.indexOf s \e) dotloc (.indexOf s \.)] (if (neg? exploc) (if (neg? dotloc) [s (str (dec (count s)))] [(str (subs s 0 dotloc) (subs s (inc dotloc))) (str (dec dotloc))]) (if (neg? dotloc) [(subs s 0 exploc) (subs s (inc exploc))] [(str (subs s 0 1) (subs s 2 exploc)) (subs s (inc exploc))])))) (defn- float-parts "Take care of leading and trailing zeros in decomposed floats" [f] (let [[m e] (float-parts-base f) m1 (rtrim m \0) m2 (ltrim m1 \0) delta (- (count m1) (count m2)) e (if (and (pos? (count e)) (= (nth e 0) \+)) (subs e 1) e)] (if (empty? m2) ["0" 0] [m2 (- (js/parseInt e 10) delta)]))) (defn- inc-s "Assumption: The input string consists of one or more decimal digits, and no other characters. Return a string containing one or more decimal digits containing a decimal number one larger than the input string. The output string will always be the same length as the input string, or one character longer." [s] (let [len-1 (dec (count s))] (loop [i (int len-1)] (cond (neg? i) (apply str "1" (repeat (inc len-1) "0")) (= \9 (.charAt s i)) (recur (dec i)) :else (apply str (subs s 0 i) (char (inc (char-code (.charAt s i)))) (repeat (- len-1 i) "0")))))) (defn- round-str [m e d w] (if (or d w) (let [len (count m) ;; Every formatted floating point number should include at ;; least one decimal digit and a decimal point. w (if w (max 2 w) ;;NB: if w doesn't exist, it won't ever be used because d will ;; satisfy the cond below. cljs gives a compilation warning if ;; we don't provide a value here. 0) round-pos (cond ;; If d was given, that forces the rounding ;; position, regardless of any width that may ;; have been specified. d (+ e d 1) ;; Otherwise w was specified, so pick round-pos ;; based upon that. ;; If e>=0, then abs value of number is >= 1.0, ;; and e+1 is number of decimal digits before the ;; decimal point when the number is written ;; without scientific notation. Never round the ;; number before the decimal point. (>= e 0) (max (inc e) (dec w)) ;; e < 0, so number abs value < 1.0 :else (+ w e)) [m1 e1 round-pos len] (if (= round-pos 0) [(str "0" m) (inc e) 1 (inc len)] [m e round-pos len])] (if round-pos (if (neg? round-pos) ["0" 0 false] (if (> len round-pos) (let [round-char (nth m1 round-pos) result (subs m1 0 round-pos)] (if (>= (char-code round-char) (char-code \5)) (let [round-up-result (inc-s result) expanded (> (count round-up-result) (count result))] [(if expanded (subs round-up-result 0 (dec (count round-up-result))) round-up-result) e1 expanded]) [result e1 false])) [m e false])) [m e false])) [m e false])) (defn- expand-fixed [m e d] (let [[m1 e1] (if (neg? e) [(str (apply str (repeat (dec (- e)) \0)) m) -1] [m e]) len (count m1) target-len (if d (+ e1 d 1) (inc e1))] (if (< len target-len) (str m1 (apply str (repeat (- target-len len) \0))) m1))) (defn- insert-decimal "Insert the decimal point at the right spot in the number to match an exponent" [m e] (if (neg? e) (str "." m) (let [loc (inc e)] (str (subs m 0 loc) "." (subs m loc))))) (defn- get-fixed [m e d] (insert-decimal (expand-fixed m e d) e)) (defn- insert-scaled-decimal "Insert the decimal point at the right spot in the number to match an exponent" [m k] (if (neg? k) (str "." m) (str (subs m 0 k) "." (subs m k)))) ;;TODO: No ratio, so not sure what to do here (defn- convert-ratio [x] x) ;; the function to render ~F directives ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases (defn- fixed-float [params navigator offsets] (let [w (:w params) d (:d params) [arg navigator] (next-arg navigator) [sign abs] (if (neg? arg) ["-" (- arg)] ["+" arg]) abs (convert-ratio abs) [mantissa exp] (float-parts abs) scaled-exp (+ exp (:k params)) add-sign (or (:at params) (neg? arg)) append-zero (and (not d) (<= (dec (count mantissa)) scaled-exp)) [rounded-mantissa scaled-exp expanded] (round-str mantissa scaled-exp d (if w (- w (if add-sign 1 0)))) fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d) fixed-repr (if (and w d (>= d 1) (= (.charAt fixed-repr 0) \0) (= (.charAt fixed-repr 1) \.) (> (count fixed-repr) (- w (if add-sign 1 0)))) (subs fixed-repr 1) ;chop off leading 0 fixed-repr) prepend-zero (= (first fixed-repr) \.)] (if w (let [len (count fixed-repr) signed-len (if add-sign (inc len) len) prepend-zero (and prepend-zero (not (>= signed-len w))) append-zero (and append-zero (not (>= signed-len w))) full-len (if (or prepend-zero append-zero) (inc signed-len) signed-len)] (if (and (> full-len w) (:overflowchar params)) (print (apply str (repeat w (:overflowchar params)))) (print (str (apply str (repeat (- w full-len) (:padchar params))) (if add-sign sign) (if prepend-zero "0") fixed-repr (if append-zero "0"))))) (print (str (if add-sign sign) (if prepend-zero "0") fixed-repr (if append-zero "0")))) navigator)) ;; the function to render ~E directives ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases ;; TODO: define ~E representation for Infinity (defn- exponential-float [params navigator offset] (let [[arg navigator] (next-arg navigator) arg (convert-ratio arg)] (loop [[mantissa exp] (float-parts (if (neg? arg) (- arg) arg))] (let [w (:w params) d (:d params) e (:e params) k (:k params) expchar (or (:exponentchar params) \E) add-sign (or (:at params) (neg? arg)) prepend-zero (<= k 0) scaled-exp (- exp (dec k)) scaled-exp-str (str (Math/abs scaled-exp)) scaled-exp-str (str expchar (if (neg? scaled-exp) \- \+) (if e (apply str (repeat (- e (count scaled-exp-str)) \0))) scaled-exp-str) exp-width (count scaled-exp-str) base-mantissa-width (count mantissa) scaled-mantissa (str (apply str (repeat (- k) \0)) mantissa (if d (apply str (repeat (- d (dec base-mantissa-width) (if (neg? k) (- k) 0)) \0)))) w-mantissa (if w (- w exp-width)) [rounded-mantissa _ incr-exp] (round-str scaled-mantissa 0 (cond (= k 0) (dec d) (pos? k) d (neg? k) (dec d)) (if w-mantissa (- w-mantissa (if add-sign 1 0)))) full-mantissa (insert-scaled-decimal rounded-mantissa k) append-zero (and (= k (count rounded-mantissa)) (nil? d))] (if (not incr-exp) (if w (let [len (+ (count full-mantissa) exp-width) signed-len (if add-sign (inc len) len) prepend-zero (and prepend-zero (not (= signed-len w))) full-len (if prepend-zero (inc signed-len) signed-len) append-zero (and append-zero (< full-len w))] (if (and (or (> full-len w) (and e (> (- exp-width 2) e))) (:overflowchar params)) (print (apply str (repeat w (:overflowchar params)))) (print (str (apply str (repeat (- w full-len (if append-zero 1 0)) (:padchar params))) (if add-sign (if (neg? arg) \- \+)) (if prepend-zero "0") full-mantissa (if append-zero "0") scaled-exp-str)))) (print (str (if add-sign (if (neg? arg) \- \+)) (if prepend-zero "0") full-mantissa (if append-zero "0") scaled-exp-str))) (recur [rounded-mantissa (inc exp)])))) navigator)) ;; the function to render ~G directives ;; This just figures out whether to pass the request off to ~F or ~E based ;; on the algorithm in CLtL. ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases ;; TODO: refactor so that float-parts isn't called twice (defn- general-float [params navigator offsets] (let [[arg _] (next-arg navigator) arg (convert-ratio arg) [mantissa exp] (float-parts (if (neg? arg) (- arg) arg)) w (:w params) d (:d params) e (:e params) n (if (= arg 0.0) 0 (inc exp)) ee (if e (+ e 2) 4) ww (if w (- w ee)) d (if d d (max (count mantissa) (min n 7))) dd (- d n)] (if (<= 0 dd d) (let [navigator (fixed-float {:w ww, :d dd, :k 0, :overflowchar (:overflowchar params), :padchar (:padchar params), :at (:at params)} navigator offsets)] (print (apply str (repeat ee \space))) navigator) (exponential-float params navigator offsets)))) ;; the function to render ~$ directives ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases (defn- dollar-float [params navigator offsets] (let [[arg navigator] (next-arg navigator) [mantissa exp] (float-parts (Math/abs arg)) d (:d params) ; digits after the decimal n (:n params) ; minimum digits before the decimal w (:w params) ; minimum field width add-sign (or (:at params) (neg? arg)) [rounded-mantissa scaled-exp expanded] (round-str mantissa exp d nil) fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d) full-repr (str (apply str (repeat (- n (.indexOf fixed-repr \.)) \0)) fixed-repr) full-len (+ (count full-repr) (if add-sign 1 0))] (print (str (if (and (:colon params) add-sign) (if (neg? arg) \- \+)) (apply str (repeat (- w full-len) (:padchar params))) (if (and (not (:colon params)) add-sign) (if (neg? arg) \- \+)) full-repr)) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the '~[...~]' conditional construct in its ;; different flavors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ~[...~] without any modifiers chooses one of the clauses based on the param or ;; next argument ;; TODO check arg is positive int (defn- choice-conditional [params arg-navigator offsets] (let [arg (:selector params) [arg navigator] (if arg [arg arg-navigator] (next-arg arg-navigator)) clauses (:clauses params) clause (if (or (neg? arg) (>= arg (count clauses))) (first (:else params)) (nth clauses arg))] (if clause (execute-sub-format clause navigator (:base-args params)) navigator))) ;; ~:[...~] with the colon reads the next argument treating it as a truth value (defn- boolean-conditional [params arg-navigator offsets] (let [[arg navigator] (next-arg arg-navigator) clauses (:clauses params) clause (if arg (second clauses) (first clauses))] (if clause (execute-sub-format clause navigator (:base-args params)) navigator))) ;; ~@[...~] with the at sign executes the conditional if the next arg is not ;; nil/false without consuming the arg (defn- check-arg-conditional [params arg-navigator offsets] (let [[arg navigator] (next-arg arg-navigator) clauses (:clauses params) clause (if arg (first clauses))] (if arg (if clause (execute-sub-format clause arg-navigator (:base-args params)) arg-navigator) navigator))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the '~{...~}' iteration construct in its ;; different flavors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ~{...~} without any modifiers uses the next argument as an argument list that ;; is consumed by all the iterations (defn- iterate-sublist [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator]) [arg-list navigator] (next-arg navigator) args (init-navigator arg-list)] (loop [count 0 args args last-pos (int -1)] (if (and (not max-count) (= (:pos args) last-pos) (> count 1)) ;; TODO get the offset in here and call format exception (throw (js/Error "%{ construct not consuming any arguments: Infinite loop!"))) (if (or (and (empty? (:rest args)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause args (:base-args params))] (if (= :up-arrow (first iter-result)) navigator (recur (inc count) iter-result (:pos args)))))))) ;; ~:{...~} with the colon treats the next argument as a list of sublists. Each of the ;; sublists is used as the arglist for a single iteration. (defn- iterate-list-of-sublists [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator]) [arg-list navigator] (next-arg navigator)] (loop [count 0 arg-list arg-list] (if (or (and (empty? arg-list) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause (init-navigator (first arg-list)) (init-navigator (next arg-list)))] (if (= :colon-up-arrow (first iter-result)) navigator (recur (inc count) (next arg-list)))))))) ;; ~@{...~} with the at sign uses the main argument list as the arguments to the iterations ;; is consumed by all the iterations (defn- iterate-main-list [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator])] (loop [count 0 navigator navigator last-pos (int -1)] (if (and (not max-count) (= (:pos navigator) last-pos) (> count 1)) ;; TODO get the offset in here and call format exception (throw (js/Error "%@{ construct not consuming any arguments: Infinite loop!"))) (if (or (and (empty? (:rest navigator)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause navigator (:base-args params))] (if (= :up-arrow (first iter-result)) (second iter-result) (recur (inc count) iter-result (:pos navigator)))))))) ;; ~@:{...~} with both colon and at sign uses the main argument list as a set of sublists, one ;; of which is consumed with each iteration (defn- iterate-main-sublists [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator])] (loop [count 0 navigator navigator] (if (or (and (empty? (:rest navigator)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [[sublist navigator] (next-arg-or-nil navigator) iter-result (execute-sub-format clause (init-navigator sublist) navigator)] (if (= :colon-up-arrow (first iter-result)) navigator (recur (inc count) navigator))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; The '~< directive has two completely different meanings ;; in the '~<...~>' form it does justification, but with ;; ~<...~:>' it represents the logical block operation of the ;; pretty printer. ;; ;; Unfortunately, the current architecture decides what function ;; to call at form parsing time before the sub-clauses have been ;; folded, so it is left to run-time to make the decision. ;; ;; TODO: make it possible to make these decisions at compile-time. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare ^{:arglists '([params navigator offsets])} format-logical-block) (declare ^{:arglists '([params navigator offsets])} justify-clauses) (defn- logical-block-or-justify [params navigator offsets] (if (:colon (:right-params params)) (format-logical-block params navigator offsets) (justify-clauses params navigator offsets))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the '~<...~>' justification directive ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- render-clauses [clauses navigator base-navigator] (loop [clauses clauses acc [] navigator navigator] (if (empty? clauses) [acc navigator] (let [clause (first clauses) [iter-result result-str] (let [sb (StringBuffer.)] (binding [*out* (StringBufferWriter. sb)] [(execute-sub-format clause navigator base-navigator) (str sb)]))] (if (= :up-arrow (first iter-result)) [acc (second iter-result)] (recur (next clauses) (conj acc result-str) iter-result)))))) ;; TODO support for ~:; constructions (defn- justify-clauses [params navigator offsets] (let [[[eol-str] new-navigator] (when-let [else (:else params)] (render-clauses else navigator (:base-args params))) navigator (or new-navigator navigator) [else-params new-navigator] (when-let [p (:else-params params)] (realize-parameter-list p navigator)) navigator (or new-navigator navigator) min-remaining (or (first (:min-remaining else-params)) 0) max-columns (or (first (:max-columns else-params)) (get-max-column *out*)) clauses (:clauses params) [strs navigator] (render-clauses clauses navigator (:base-args params)) slots (max 1 (+ (dec (count strs)) (if (:colon params) 1 0) (if (:at params) 1 0))) chars (reduce + (map count strs)) mincol (:mincol params) minpad (:minpad params) colinc (:colinc params) minout (+ chars (* slots minpad)) result-columns (if (<= minout mincol) mincol (+ mincol (* colinc (+ 1 (quot (- minout mincol 1) colinc))))) total-pad (- result-columns chars) pad (max minpad (quot total-pad slots)) extra-pad (- total-pad (* pad slots)) pad-str (apply str (repeat pad (:padchar params)))] (if (and eol-str (> (+ (get-column (:base @@*out*)) min-remaining result-columns) max-columns)) (print eol-str)) (loop [slots slots extra-pad extra-pad strs strs pad-only (or (:colon params) (and (= (count strs) 1) (not (:at params))))] (if (seq strs) (do (print (str (if (not pad-only) (first strs)) (if (or pad-only (next strs) (:at params)) pad-str) (if (pos? extra-pad) (:padchar params)))) (recur (dec slots) (dec extra-pad) (if pad-only strs (next strs)) false)))) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Support for case modification with ~(...~). ;;; We do this by wrapping the underlying writer with ;;; a special writer to do the appropriate modification. This ;;; allows us to support arbitrary-sized output and sources ;;; that may block. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- downcase-writer "Returns a proxy that wraps writer, converting all characters to lower case" [writer] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity, not sure of importance #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (string/lower-case s))) js/Number (let [c x] ;;TODO need to enforce integers only? (-write writer (string/lower-case (char c)))))))) (defn- upcase-writer "Returns a proxy that wraps writer, converting all characters to upper case" [writer] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity, not sure of importance #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (string/upper-case s))) js/Number (let [c x] ;;TODO need to enforce integers only? (-write writer (string/upper-case (char c)))))))) (defn- capitalize-string "Capitalizes the words in a string. If first? is false, don't capitalize the first character of the string even if it's a letter." [s first?] (let [f (first s) s (if (and first? f (gstring/isUnicodeChar f)) (str (string/upper-case f) (subs s 1)) s)] (apply str (first (consume (fn [s] (if (empty? s) [nil nil] (let [m (.exec (js/RegExp "\\W\\w" "g") s) offset (and m (inc (.-index m)))] (if offset [(str (subs s 0 offset) (string/upper-case (nth s offset))) (subs s (inc offset))] [s nil])))) s))))) (defn- capitalize-word-writer "Returns a proxy that wraps writer, capitalizing all words" [writer] (let [last-was-whitespace? (atom true)] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (capitalize-string (.toLowerCase s) @last-was-whitespace?)) (when (pos? (.-length s)) (reset! last-was-whitespace? (gstring/isEmptyOrWhitespace (nth s (dec (count s))))))) js/Number (let [c (char x)] (let [mod-c (if @last-was-whitespace? (string/upper-case c) c)] (-write writer mod-c) (reset! last-was-whitespace? (gstring/isEmptyOrWhitespace c))))))))) (defn- init-cap-writer "Returns a proxy that wraps writer, capitalizing the first word" [writer] (let [capped (atom false)] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s (string/lower-case x)] (if (not @capped) (let [m (.exec (js/RegExp "\\S" "g") s) offset (and m (.-index m))] (if offset (do (-write writer (str (subs s 0 offset) (string/upper-case (nth s offset)) (string/lower-case (subs s (inc offset))))) (reset! capped true)) (-write writer s))) (-write writer (string/lower-case s)))) js/Number (let [c (char x)] (if (and (not @capped) (gstring/isUnicodeChar c)) (do (reset! capped true) (-write writer (string/upper-case c))) (-write writer (string/lower-case c))))))))) (defn- modify-case [make-writer params navigator offsets] (let [clause (first (:clauses params))] (binding [*out* (make-writer *out*)] (execute-sub-format clause navigator (:base-args params))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; If necessary, wrap the writer in a PrettyWriter object ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO update this doc string to show correct way to print (defn get-pretty-writer "Returns the IWriter passed in wrapped in a pretty writer proxy, unless it's already a pretty writer. Generally, it is unnecessary to call this function, since pprint, write, and cl-format all call it if they need to. However if you want the state to be preserved across calls, you will want to wrap them with this. For example, when you want to generate column-aware output with multiple calls to cl-format, do it like in this example: (defn print-table [aseq column-width] (binding [*out* (get-pretty-writer *out*)] (doseq [row aseq] (doseq [col row] (cl-format true \"~4D~7,vT\" col column-width)) (prn)))) Now when you run: user> (print-table (map #(vector % (* % %) (* % % %)) (range 1 11)) 8) It prints a table of squares and cubes for the numbers from 1 to 10: 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000" [writer] (if (pretty-writer? writer) writer (pretty-writer writer *print-right-margin* *print-miser-width*))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Support for column-aware operations ~&, ~T ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fresh-line "Make a newline if *out* is not already at the beginning of the line. If *out* is not a pretty writer (which keeps track of columns), this function always outputs a newline." [] (if (satisfies? IDeref *out*) (if (not (= 0 (get-column (:base @@*out*)))) (prn)) (prn))) (defn- absolute-tabulation [params navigator offsets] (let [colnum (:colnum params) colinc (:colinc params) current (get-column (:base @@*out*)) space-count (cond (< current colnum) (- colnum current) (= colinc 0) 0 :else (- colinc (rem (- current colnum) colinc)))] (print (apply str (repeat space-count \space)))) navigator) (defn- relative-tabulation [params navigator offsets] (let [colrel (:colnum params) colinc (:colinc params) start-col (+ colrel (get-column (:base @@*out*))) offset (if (pos? colinc) (rem start-col colinc) 0) space-count (+ colrel (if (= 0 offset) 0 (- colinc offset)))] (print (apply str (repeat space-count \space)))) navigator) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Support for accessing the pretty printer from a format ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO: support ~@; per-line-prefix separator ;; TODO: get the whole format wrapped so we can start the lb at any column (defn- format-logical-block [params navigator offsets] (let [clauses (:clauses params) clause-count (count clauses) prefix (cond (> clause-count 1) (:string (:params (first (first clauses)))) (:colon params) "(") body (nth clauses (if (> clause-count 1) 1 0)) suffix (cond (> clause-count 2) (:string (:params (first (nth clauses 2)))) (:colon params) ")") [arg navigator] (next-arg navigator)] (pprint-logical-block :prefix prefix :suffix suffix (execute-sub-format body (init-navigator arg) (:base-args params))) navigator)) (defn- set-indent [params navigator offsets] (let [relative-to (if (:colon params) :current :block)] (pprint-indent relative-to (:n params)) navigator)) ;;; TODO: support ~:T section options for ~T (defn- conditional-newline [params navigator offsets] (let [kind (if (:colon params) (if (:at params) :mandatory :fill) (if (:at params) :miser :linear))] (pprint-newline kind) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The table of directives we support, each with its params, ;;; properties, and the compilation function ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defdirectives (\A [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} #(format-ascii print-str %1 %2 %3)) (\S [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} #(format-ascii pr-str %1 %2 %3)) (\D [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 10 %1 %2 %3)) (\B [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 2 %1 %2 %3)) (\O [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 8 %1 %2 %3)) (\X [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 16 %1 %2 %3)) (\R [:base [nil js/Number] :mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} (do (cond ; ~R is overloaded with bizareness (first (:base params)) #(format-integer (:base %1) %1 %2 %3) (and (:at params) (:colon params)) #(format-old-roman %1 %2 %3) (:at params) #(format-new-roman %1 %2 %3) (:colon params) #(format-ordinal-english %1 %2 %3) true #(format-cardinal-english %1 %2 %3)))) (\P [] #{:at :colon :both} {} (fn [params navigator offsets] (let [navigator (if (:colon params) (relative-reposition navigator -1) navigator) strs (if (:at params) ["y" "ies"] ["" "s"]) [arg navigator] (next-arg navigator)] (print (if (= arg 1) (first strs) (second strs))) navigator))) (\C [:char-format [nil js/String]] #{:at :colon :both} {} (cond (:colon params) pretty-character (:at params) readable-character :else plain-character)) (\F [:w [nil js/Number] :d [nil js/Number] :k [0 js/Number] :overflowchar [nil js/String] :padchar [\space js/String]] #{:at} {} fixed-float) (\E [:w [nil js/Number] :d [nil js/Number] :e [nil js/Number] :k [1 js/Number] :overflowchar [nil js/String] :padchar [\space js/String] :exponentchar [nil js/String]] #{:at} {} exponential-float) (\G [:w [nil js/Number] :d [nil js/Number] :e [nil js/Number] :k [1 js/Number] :overflowchar [nil js/String] :padchar [\space js/String] :exponentchar [nil js/String]] #{:at} {} general-float) (\$ [:d [2 js/Number] :n [1 js/Number] :w [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} dollar-float) (\% [:count [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (dotimes [i (:count params)] (prn)) arg-navigator)) (\& [:count [1 js/Number]] #{:pretty} {} (fn [params arg-navigator offsets] (let [cnt (:count params)] (if (pos? cnt) (fresh-line)) (dotimes [i (dec cnt)] (prn))) arg-navigator)) (\| [:count [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (dotimes [i (:count params)] (print \formfeed)) arg-navigator)) (\~ [:n [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (let [n (:n params)] (print (apply str (repeat n \~))) arg-navigator))) (\newline ;; Whitespace supression is handled in the compilation loop [] #{:colon :at} {} (fn [params arg-navigator offsets] (if (:at params) (prn)) arg-navigator)) (\T [:colnum [1 js/Number] :colinc [1 js/Number]] #{:at :pretty} {} (if (:at params) #(relative-tabulation %1 %2 %3) #(absolute-tabulation %1 %2 %3))) (\* [:n [1 js/Number]] #{:colon :at} {} (fn [params navigator offsets] (let [n (:n params)] (if (:at params) (absolute-reposition navigator n) (relative-reposition navigator (if (:colon params) (- n) n)))))) (\? [] #{:at} {} (if (:at params) (fn [params navigator offsets] ; args from main arg list (let [[subformat navigator] (get-format-arg navigator)] (execute-sub-format subformat navigator (:base-args params)))) (fn [params navigator offsets] ; args from sub-list (let [[subformat navigator] (get-format-arg navigator) [subargs navigator] (next-arg navigator) sub-navigator (init-navigator subargs)] (execute-sub-format subformat sub-navigator (:base-args params)) navigator)))) (\( [] #{:colon :at :both} {:right \), :allows-separator nil, :else nil} (let [mod-case-writer (cond (and (:at params) (:colon params)) upcase-writer (:colon params) capitalize-word-writer (:at params) init-cap-writer :else downcase-writer)] #(modify-case mod-case-writer %1 %2 %3))) (\) [] #{} {} nil) (\[ [:selector [nil js/Number]] #{:colon :at} {:right \], :allows-separator true, :else :last} (cond (:colon params) boolean-conditional (:at params) check-arg-conditional true choice-conditional)) (\; [:min-remaining [nil js/Number] :max-columns [nil js/Number]] #{:colon} {:separator true} nil) (\] [] #{} {} nil) (\{ [:max-iterations [nil js/Number]] #{:colon :at :both} {:right \}, :allows-separator false} (cond (and (:at params) (:colon params)) iterate-main-sublists (:colon params) iterate-list-of-sublists (:at params) iterate-main-list true iterate-sublist)) (\} [] #{:colon} {} nil) (\< [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:colon :at :both :pretty} {:right \>, :allows-separator true, :else :first} logical-block-or-justify) (\> [] #{:colon} {} nil) ;; TODO: detect errors in cases where colon not allowed (\^ [:arg1 [nil js/Number] :arg2 [nil js/Number] :arg3 [nil js/Number]] #{:colon} {} (fn [params navigator offsets] (let [arg1 (:arg1 params) arg2 (:arg2 params) arg3 (:arg3 params) exit (if (:colon params) :colon-up-arrow :up-arrow)] (cond (and arg1 arg2 arg3) (if (<= arg1 arg2 arg3) [exit navigator] navigator) (and arg1 arg2) (if (= arg1 arg2) [exit navigator] navigator) arg1 (if (= arg1 0) [exit navigator] navigator) true ; TODO: handle looking up the arglist stack for info (if (if (:colon params) (empty? (:rest (:base-args params))) (empty? (:rest navigator))) [exit navigator] navigator))))) (\W [] #{:at :colon :both :pretty} {} (if (or (:at params) (:colon params)) (let [bindings (concat (if (:at params) [:level nil :length nil] []) (if (:colon params) [:pretty true] []))] (fn [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (apply write arg bindings) [:up-arrow navigator] navigator)))) (fn [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (write-out arg) [:up-arrow navigator] navigator))))) (\_ [] #{:at :colon :both} {} conditional-newline) (\I [:n [0 js/Number]] #{:colon} {} set-indent) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Code to manage the parameters and flags associated with each ;; directive in the format string. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} param-pattern #"^([vV]|#|('.)|([+-]?\d+)|(?=,))") (def ^{:private true} special-params #{:parameter-from-args :remaining-arg-count}) (defn- extract-param [[s offset saw-comma]] (let [m (js/RegExp. (.-source param-pattern) "g") param (.exec m s)] (if param (let [token-str (first param) remainder (subs s (.-lastIndex m)) new-offset (+ offset (.-lastIndex m))] (if (not (= \, (nth remainder 0))) [[token-str offset] [remainder new-offset false]] [[token-str offset] [(subs remainder 1) (inc new-offset) true]])) (if saw-comma (format-error "Badly formed parameters in format directive" offset) [nil [s offset]])))) (defn- extract-params [s offset] (consume extract-param [s offset false])) (defn- translate-param "Translate the string representation of a param to the internalized representation" [[p offset]] [(cond (= (.-length p) 0) nil (and (= (.-length p) 1) (contains? #{\v \V} (nth p 0))) :parameter-from-args (and (= (.-length p) 1) (= \# (nth p 0))) :remaining-arg-count (and (= (.-length p) 2) (= \' (nth p 0))) (nth p 1) true (js/parseInt p 10)) offset]) (def ^{:private true} flag-defs {\: :colon, \@ :at}) (defn- extract-flags [s offset] (consume (fn [[s offset flags]] (if (empty? s) [nil [s offset flags]] (let [flag (get flag-defs (first s))] (if flag (if (contains? flags flag) (format-error (str "Flag \"" (first s) "\" appears more than once in a directive") offset) [true [(subs s 1) (inc offset) (assoc flags flag [true offset])]]) [nil [s offset flags]])))) [s offset {}])) (defn- check-flags [def flags] (let [allowed (:flags def)] (if (and (not (:at allowed)) (:at flags)) (format-error (str "\"@\" is an illegal flag for format directive \"" (:directive def) "\"") (nth (:at flags) 1))) (if (and (not (:colon allowed)) (:colon flags)) (format-error (str "\":\" is an illegal flag for format directive \"" (:directive def) "\"") (nth (:colon flags) 1))) (if (and (not (:both allowed)) (:at flags) (:colon flags)) (format-error (str "Cannot combine \"@\" and \":\" flags for format directive \"" (:directive def) "\"") (min (nth (:colon flags) 1) (nth (:at flags) 1)))))) (defn- map-params "Takes a directive definition and the list of actual parameters and a map of flags and returns a map of the parameters and flags with defaults filled in. We check to make sure that there are the right types and number of parameters as well." [def params flags offset] (check-flags def flags) (if (> (count params) (count (:params def))) (format-error (cl-format nil "Too many parameters for directive \"~C\": ~D~:* ~[were~;was~:;were~] specified but only ~D~:* ~[are~;is~:;are~] allowed" (:directive def) (count params) (count (:params def))) (second (first params)))) (doall (map #(let [val (first %1)] (if (not (or (nil? val) (contains? special-params val) (= (second (second %2)) (type val)))) (format-error (str "Parameter " (name (first %2)) " has bad type in directive \"" (:directive def) "\": " (type val)) (second %1))) ) params (:params def))) (merge ; create the result map (into (array-map) ; start with the default values, make sure the order is right (reverse (for [[name [default]] (:params def)] [name [default offset]]))) (reduce #(apply assoc %1 %2) {} (filter #(first (nth % 1)) (zipmap (keys (:params def)) params))) ; add the specified parameters, filtering out nils flags)); and finally add the flags (defn- compile-directive [s offset] (let [[raw-params [rest offset]] (extract-params s offset) [_ [rest offset flags]] (extract-flags rest offset) directive (first rest) def (get directive-table (string/upper-case directive)) params (if def (map-params def (map translate-param raw-params) flags offset))] (if (not directive) (format-error "Format string ended in the middle of a directive" offset)) (if (not def) (format-error (str "Directive \"" directive "\" is undefined") offset)) [(compiled-directive. ((:generator-fn def) params offset) def params offset) (let [remainder (subs rest 1) offset (inc offset) trim? (and (= \newline (:directive def)) (not (:colon params))) trim-count (if trim? (prefix-count remainder [\space \tab]) 0) remainder (subs remainder trim-count) offset (+ offset trim-count)] [remainder offset])])) (defn- compile-raw-string [s offset] (compiled-directive. (fn [_ a _] (print s) a) nil {:string s} offset)) (defn- right-bracket [this] (:right (:bracket-info (:def this)))) (defn- separator? [this] (:separator (:bracket-info (:def this)))) (defn- else-separator? [this] (and (:separator (:bracket-info (:def this))) (:colon (:params this)))) (declare ^{:arglists '([bracket-info offset remainder])} collect-clauses) (defn- process-bracket [this remainder] (let [[subex remainder] (collect-clauses (:bracket-info (:def this)) (:offset this) remainder)] [(compiled-directive. (:func this) (:def this) (merge (:params this) (tuple-map subex (:offset this))) (:offset this)) remainder])) (defn- process-clause [bracket-info offset remainder] (consume (fn [remainder] (if (empty? remainder) (format-error "No closing bracket found." offset) (let [this (first remainder) remainder (next remainder)] (cond (right-bracket this) (process-bracket this remainder) (= (:right bracket-info) (:directive (:def this))) [ nil [:right-bracket (:params this) nil remainder]] (else-separator? this) [nil [:else nil (:params this) remainder]] (separator? this) [nil [:separator nil nil remainder]] ;; TODO: check to make sure that there are no params on ~; true [this remainder])))) remainder)) (defn- collect-clauses [bracket-info offset remainder] (second (consume (fn [[clause-map saw-else remainder]] (let [[clause [type right-params else-params remainder]] (process-clause bracket-info offset remainder)] (cond (= type :right-bracket) [nil [(merge-with concat clause-map {(if saw-else :else :clauses) [clause] :right-params right-params}) remainder]] (= type :else) (cond (:else clause-map) (format-error "Two else clauses (\"~:;\") inside bracket construction." offset) (not (:else bracket-info)) (format-error "An else clause (\"~:;\") is in a bracket type that doesn't support it." offset) (and (= :first (:else bracket-info)) (seq (:clauses clause-map))) (format-error "The else clause (\"~:;\") is only allowed in the first position for this directive." offset) true ; if the ~:; is in the last position, the else clause ; is next, this was a regular clause (if (= :first (:else bracket-info)) [true [(merge-with concat clause-map {:else [clause] :else-params else-params}) false remainder]] [true [(merge-with concat clause-map {:clauses [clause]}) true remainder]])) (= type :separator) (cond saw-else (format-error "A plain clause (with \"~;\") follows an else clause (\"~:;\") inside bracket construction." offset) (not (:allows-separator bracket-info)) (format-error "A separator (\"~;\") is in a bracket type that doesn't support it." offset) true [true [(merge-with concat clause-map {:clauses [clause]}) false remainder]])))) [{:clauses []} false remainder]))) (defn- process-nesting "Take a linearly compiled format and process the bracket directives to give it the appropriate tree structure" [format] (first (consume (fn [remainder] (let [this (first remainder) remainder (next remainder) bracket (:bracket-info (:def this))] (if (:right bracket) (process-bracket this remainder) [this remainder]))) format))) (defn- compile-format "Compiles format-str into a compiled format which can be used as an argument to cl-format just like a plain format string. Use this function for improved performance when you're using the same format string repeatedly" [format-str] (binding [*format-str* format-str] (process-nesting (first (consume (fn [[s offset]] (if (empty? s) [nil s] (let [tilde (.indexOf s \~)] (cond (neg? tilde) [(compile-raw-string s offset) ["" (+ offset (.-length s))]] (zero? tilde) (compile-directive (subs s 1) (inc offset)) true [(compile-raw-string (subs s 0 tilde) offset) [(subs s tilde) (+ tilde offset)]])))) [format-str 0]))))) (defn- needs-pretty "determine whether a given compiled format has any directives that depend on the column number or pretty printing" [format] (loop [format format] (if (empty? format) false (if (or (:pretty (:flags (:def (first format)))) (some needs-pretty (first (:clauses (:params (first format))))) (some needs-pretty (first (:else (:params (first format)))))) true (recur (next format)))))) ;;NB We depart from the original api. In clj, if execute-format is called multiple times with the same stream or ;; called on *out*, the results are different than if the same calls are made with different streams or printing ;; to a string. The reason is that mutating the underlying stream changes the result by changing spacing. ;; ;; clj: ;; * stream => "1 2 3" ;; * true (prints to *out*) => "1 2 3" ;; * nil (prints to string) => "1 2 3" ;; cljs: ;; * stream => "1 2 3" ;; * true (prints via *print-fn*) => "1 2 3" ;; * nil (prints to string) => "1 2 3" (defn- execute-format "Executes the format with the arguments." {:skip-wiki true} ([stream format args] (let [sb (StringBuffer.) real-stream (if (or (not stream) (true? stream)) (StringBufferWriter. sb) stream) wrapped-stream (if (and (needs-pretty format) (not (pretty-writer? real-stream))) (get-pretty-writer real-stream) real-stream)] (binding [*out* wrapped-stream] (try (execute-format format args) (finally (if-not (identical? real-stream wrapped-stream) (-flush wrapped-stream)))) (cond (not stream) (str sb) (true? stream) (string-print (str sb)) :else nil)))) ([format args] (map-passing-context (fn [element context] (if (abort? context) [nil context] (let [[params args] (realize-parameter-list (:params element) context) [params offsets] (unzip-map params) params (assoc params :base-args args)] [nil (apply (:func element) [params args offsets])]))) args format) nil)) ;;; This is a bad idea, but it prevents us from leaking private symbols ;;; This should all be replaced by really compiled formats anyway. (def ^{:private true} cached-compile (memoize compile-format)) ;;====================================================================== ;; dispatch.clj ;;====================================================================== (defn- use-method "Installs a function as a new method of multimethod associated with dispatch-value. " [multifn dispatch-val func] (-add-method multifn dispatch-val func)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implementations of specific dispatch table entries ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Handle forms that can be "back-translated" to reader macros ;;; Not all reader macros can be dealt with this way or at all. ;;; Macros that we can't deal with at all are: ;;; ; - The comment character is absorbed by the reader and never is part of the form ;;; ` - Is fully processed at read time into a lisp expression (which will contain concats ;;; and regular quotes). ;;; ~@ - Also fully eaten by the processing of ` and can't be used outside. ;;; , - is whitespace and is lost (like all other whitespace). Formats can generate commas ;;; where they deem them useful to help readability. ;;; ^ - Adding metadata completely disappears at read time and the data appears to be ;;; completely lost. ;;; ;;; Most other syntax stuff is dealt with directly by the formats (like (), [], {}, and #{}) ;;; or directly by printing the objects using Clojure's built-in print functions (like ;;; :keyword, \char, or ""). The notable exception is #() which is special-cased. (def ^{:private true} reader-macros {'quote "'" 'var "#'" 'clojure.core/deref "@", 'clojure.core/unquote "~" 'cljs.core/deref "@", 'cljs.core/unquote "~"}) (defn- pprint-reader-macro [alis] (let [macro-char (reader-macros (first alis))] (when (and macro-char (= 2 (count alis))) (-write *out* macro-char) (write-out (second alis)) true))) ;;====================================================================== ;; Dispatch for the basic data types when interpreted ;; as data (as opposed to code). ;;====================================================================== ;;; TODO: inline these formatter statements into funcs so that we ;;; are a little easier on the stack. (Or, do "real" compilation, a ;;; la Common Lisp) ;;; (def pprint-simple-list (formatter-out "~:<~@{~w~^ ~_~}~:>")) (defn- pprint-simple-list [alis] (pprint-logical-block :prefix "(" :suffix ")" (print-length-loop [alis (seq alis)] (when alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (recur (next alis))))))) (defn- pprint-list [alis] (if-not (pprint-reader-macro alis) (pprint-simple-list alis))) ;;; (def pprint-vector (formatter-out "~<[~;~@{~w~^ ~_~}~;]~:>")) (defn- pprint-vector [avec] (pprint-logical-block :prefix "[" :suffix "]" (print-length-loop [aseq (seq avec)] (when aseq (write-out (first aseq)) (when (next aseq) (-write *out* " ") (pprint-newline :linear) (recur (next aseq))))))) (def ^{:private true} pprint-array (formatter-out "~<[~;~@{~w~^, ~:_~}~;]~:>")) ;;; (def pprint-map (formatter-out "~<{~;~@{~<~w~^ ~_~w~:>~^, ~_~}~;}~:>")) (defn- pprint-map [amap] (let [[ns lift-map] (when (not (record? amap)) (#'cljs.core/lift-ns amap)) amap (or lift-map amap) prefix (if ns (str "#:" ns "{") "{")] (pprint-logical-block :prefix prefix :suffix "}" (print-length-loop [aseq (seq amap)] (when aseq ;;compiler gets confused with nested macro if it isn't namespaced ;;it tries to use clojure.pprint/pprint-logical-block for some reason (m/pprint-logical-block (write-out (ffirst aseq)) (-write *out* " ") (pprint-newline :linear) (set! *current-length* 0) ;always print both parts of the [k v] pair (write-out (fnext (first aseq)))) (when (next aseq) (-write *out* ", ") (pprint-newline :linear) (recur (next aseq)))))))) (defn- pprint-simple-default [obj] ;;TODO: Update to handle arrays (?) and suppressing namespaces (-write *out* (pr-str obj))) (def pprint-set (formatter-out "~<#{~;~@{~w~^ ~:_~}~;}~:>")) (def ^{:private true} type-map {"core$future_call" "Future", "core$promise" "Promise"}) (defn- map-ref-type "Map ugly type names to something simpler" [name] (or (when-let [match (re-find #"^[^$]+\$[^$]+" name)] (type-map match)) name)) (defn- pprint-ideref [o] (let [prefix (str "#<" (map-ref-type (.-name (type o))) "@" (goog/getUid o) ": ")] (pprint-logical-block :prefix prefix :suffix ">" (pprint-indent :block (-> (count prefix) (- 2) -)) (pprint-newline :linear) (write-out (if (and (satisfies? IPending o) (not (-realized? o))) :not-delivered @o))))) (def ^{:private true} pprint-pqueue (formatter-out "~<<-(~;~@{~w~^ ~_~}~;)-<~:>")) (defn- type-dispatcher [obj] (cond (instance? PersistentQueue obj) :queue (satisfies? IDeref obj) :deref (symbol? obj) :symbol (seq? obj) :list (map? obj) :map (vector? obj) :vector (set? obj) :set (nil? obj) nil :default :default)) (defmulti simple-dispatch "The pretty print dispatch function for simple data structure format." type-dispatcher) (use-method simple-dispatch :list pprint-list) (use-method simple-dispatch :vector pprint-vector) (use-method simple-dispatch :map pprint-map) (use-method simple-dispatch :set pprint-set) (use-method simple-dispatch nil #(-write *out* (pr-str nil))) (use-method simple-dispatch :default pprint-simple-default) (set-pprint-dispatch simple-dispatch) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Dispatch for the code table ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare ^{:arglists '([alis])} pprint-simple-code-list) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format the namespace ("ns") macro. This is quite complicated because of all the ;;; different forms supported and because programmers can choose lists or vectors ;;; in various places. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- brackets "Figure out which kind of brackets to use" [form] (if (vector? form) ["[" "]"] ["(" ")"])) (defn- pprint-ns-reference "Pretty print a single reference (import, use, etc.) from a namespace decl" [reference] (if (sequential? reference) (let [[start end] (brackets reference) [keyw & args] reference] (pprint-logical-block :prefix start :suffix end ((formatter-out "~w~:i") keyw) (loop [args args] (when (seq args) ((formatter-out " ")) (let [arg (first args)] (if (sequential? arg) (let [[start end] (brackets arg)] (pprint-logical-block :prefix start :suffix end (if (and (= (count arg) 3) (keyword? (second arg))) (let [[ns kw lis] arg] ((formatter-out "~w ~w ") ns kw) (if (sequential? lis) ((formatter-out (if (vector? lis) "~<[~;~@{~w~^ ~:_~}~;]~:>" "~<(~;~@{~w~^ ~:_~}~;)~:>")) lis) (write-out lis))) (apply (formatter-out "~w ~:i~@{~w~^ ~:_~}") arg))) (when (next args) ((formatter-out "~_")))) (do (write-out arg) (when (next args) ((formatter-out "~:_")))))) (recur (next args)))))) (write-out reference))) (defn- pprint-ns "The pretty print dispatch chunk for the ns macro" [alis] (if (next alis) (let [[ns-sym ns-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map references] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block :prefix "(" :suffix ")" ((formatter-out "~w ~1I~@_~w") ns-sym ns-name) (when (or doc-str attr-map (seq references)) ((formatter-out "~@:_"))) (when doc-str (cl-format true "\"~a\"~:[~;~:@_~]" doc-str (or attr-map (seq references)))) (when attr-map ((formatter-out "~w~:[~;~:@_~]") attr-map (seq references))) (loop [references references] (pprint-ns-reference (first references)) (when-let [references (next references)] (pprint-newline :linear) (recur references))))) (write-out alis))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format something that looks like a simple def (sans metadata, since the reader ;;; won't give it to us now). ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} pprint-hold-first (formatter-out "~:<~w~^ ~@_~w~^ ~_~@{~w~^ ~_~}~:>")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format something that looks like a defn or defmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format the params and body of a defn with a single arity (defn- single-defn [alis has-doc-str?] (if (seq alis) (do (if has-doc-str? ((formatter-out " ~_")) ((formatter-out " ~@_"))) ((formatter-out "~{~w~^ ~_~}") alis)))) ;;; Format the param and body sublists of a defn with multiple arities (defn- multi-defn [alis has-doc-str?] (if (seq alis) ((formatter-out " ~_~{~w~^ ~_~}") alis))) ;;; TODO: figure out how to support capturing metadata in defns (we might need a ;;; special reader) (defn- pprint-defn [alis] (if (next alis) (let [[defn-sym defn-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map stuff] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block :prefix "(" :suffix ")" ((formatter-out "~w ~1I~@_~w") defn-sym defn-name) (if doc-str ((formatter-out " ~_~w") doc-str)) (if attr-map ((formatter-out " ~_~w") attr-map)) ;; Note: the multi-defn case will work OK for malformed defns too (cond (vector? (first stuff)) (single-defn stuff (or doc-str attr-map)) :else (multi-defn stuff (or doc-str attr-map))))) (pprint-simple-code-list alis))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format something with a binding form ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- pprint-binding-form [binding-vec] (pprint-logical-block :prefix "[" :suffix "]" (print-length-loop [binding binding-vec] (when (seq binding) (pprint-logical-block binding (write-out (first binding)) (when (next binding) (-write *out* " ") (pprint-newline :miser) (write-out (second binding)))) (when (next (rest binding)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest binding)))))))) (defn- pprint-let [alis] (let [base-sym (first alis)] (pprint-logical-block :prefix "(" :suffix ")" (if (and (next alis) (vector? (second alis))) (do ((formatter-out "~w ~1I~@_") base-sym) (pprint-binding-form (second alis)) ((formatter-out " ~_~{~w~^ ~_~}") (next (rest alis)))) (pprint-simple-code-list alis))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format something that looks like "if" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} pprint-if (formatter-out "~:<~1I~w~^ ~@_~w~@{ ~_~w~}~:>")) (defn- pprint-cond [alis] (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (print-length-loop [alis (next alis)] (when alis (pprint-logical-block alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :miser) (write-out (second alis)))) (when (next (rest alis)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest alis))))))))) (defn- pprint-condp [alis] (if (> (count alis) 3) (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (apply (formatter-out "~w ~@_~w ~@_~w ~_") alis) (print-length-loop [alis (seq (drop 3 alis))] (when alis (pprint-logical-block alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :miser) (write-out (second alis)))) (when (next (rest alis)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest alis))))))) (pprint-simple-code-list alis))) ;;; The map of symbols that are defined in an enclosing #() anonymous function (def ^:dynamic ^{:private true} *symbol-map* {}) (defn- pprint-anon-func [alis] (let [args (second alis) nlis (first (rest (rest alis)))] (if (vector? args) (binding [*symbol-map* (if (= 1 (count args)) {(first args) "%"} (into {} (map #(vector %1 (str \% %2)) args (range 1 (inc (count args))))))] ((formatter-out "~<#(~;~@{~w~^ ~_~}~;)~:>") nlis)) (pprint-simple-code-list alis)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The master definitions for formatting lists in code (that is, (fn args...) or ;;; special forms). ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; This is the equivalent of (formatter-out "~:<~1I~@{~w~^ ~_~}~:>"), but is ;;; easier on the stack. (defn- pprint-simple-code-list [alis] (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (print-length-loop [alis (seq alis)] (when alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (recur (next alis))))))) ;;; Take a map with symbols as keys and add versions with no namespace. ;;; That is, if ns/sym->val is in the map, add sym->val to the result. (defn- two-forms [amap] (into {} (mapcat identity (for [x amap] [x [(symbol (name (first x))) (second x)]])))) (defn- add-core-ns [amap] (let [core "clojure.core"] (into {} (map #(let [[s f] %] (if (not (or (namespace s) (special-symbol? s))) [(symbol core (name s)) f] %)) amap)))) (def ^:dynamic ^{:private true} *code-table* (two-forms (add-core-ns {'def pprint-hold-first, 'defonce pprint-hold-first, 'defn pprint-defn, 'defn- pprint-defn, 'defmacro pprint-defn, 'fn pprint-defn, 'let pprint-let, 'loop pprint-let, 'binding pprint-let, 'with-local-vars pprint-let, 'with-open pprint-let, 'when-let pprint-let, 'if-let pprint-let, 'doseq pprint-let, 'dotimes pprint-let, 'when-first pprint-let, 'if pprint-if, 'if-not pprint-if, 'when pprint-if, 'when-not pprint-if, 'cond pprint-cond, 'condp pprint-condp, 'fn* pprint-anon-func, '. pprint-hold-first, '.. pprint-hold-first, '-> pprint-hold-first, 'locking pprint-hold-first, 'struct pprint-hold-first, 'struct-map pprint-hold-first, 'ns pprint-ns }))) (defn- pprint-code-list [alis] (if-not (pprint-reader-macro alis) (if-let [special-form (*code-table* (first alis))] (special-form alis) (pprint-simple-code-list alis)))) (defn- pprint-code-symbol [sym] (if-let [arg-num (sym *symbol-map*)] (print arg-num) (if *print-suppress-namespaces* (print (name sym)) (pr sym)))) (defmulti code-dispatch "The pretty print dispatch function for pretty printing Clojure code." {:added "1.2" :arglists '[[object]]} type-dispatcher) (use-method code-dispatch :list pprint-code-list) (use-method code-dispatch :symbol pprint-code-symbol) ;; The following are all exact copies of simple-dispatch (use-method code-dispatch :vector pprint-vector) (use-method code-dispatch :map pprint-map) (use-method code-dispatch :set pprint-set) (use-method code-dispatch :queue pprint-pqueue) (use-method code-dispatch :deref pprint-ideref) (use-method code-dispatch nil pr) (use-method code-dispatch :default pprint-simple-default) (set-pprint-dispatch simple-dispatch) ;;; For testing (comment (with-pprint-dispatch code-dispatch (pprint '(defn cl-format "An implementation of a Common Lisp compatible format function" [stream format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format stream compiled-format navigator))))) (with-pprint-dispatch code-dispatch (pprint '(defn cl-format [stream format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format stream compiled-format navigator))))) (with-pprint-dispatch code-dispatch (pprint '(defn- -write ([this x] (condp = (class x) String (let [s0 (write-initial-lines this x) s (.replaceFirst s0 "\\s+$" "") white-space (.substring s0 (count s)) mode (getf :mode)] (if (= mode :writing) (dosync (write-white-space this) (.col_write this s) (setf :trailing-white-space white-space)) (add-to-buffer this (make-buffer-blob s white-space)))) Integer (let [c ^Character x] (if (= (getf :mode) :writing) (do (write-white-space this) (.col_write this x)) (if (= c (int \newline)) (write-initial-lines this "\n") (add-to-buffer this (make-buffer-blob (str (char c)) nil)))))))))) (with-pprint-dispatch code-dispatch (pprint '(defn pprint-defn [writer alis] (if (next alis) (let [[defn-sym defn-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map stuff] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block writer :prefix "(" :suffix ")" (cl-format true "~w ~1I~@_~w" defn-sym defn-name) (if doc-str (cl-format true " ~_~w" doc-str)) (if attr-map (cl-format true " ~_~w" attr-map)) ;; Note: the multi-defn case will work OK for malformed defns too (cond (vector? (first stuff)) (single-defn stuff (or doc-str attr-map)) :else (multi-defn stuff (or doc-str attr-map))))) (pprint-simple-code-list writer alis))))) ) ;;====================================================================== ;; print_table.clj ;;====================================================================== (defn- add-padding [width s] (let [padding (max 0 (- width (count s)))] (apply str (clojure.string/join (repeat padding \space)) s))) (defn print-table "Prints a collection of maps in a textual table. Prints table headings ks, and then a line of output for each row, corresponding to the keys in ks. If ks are not specified, use the keys of the first item in rows." {:added "1.3"} ([ks rows] (when (seq rows) (let [widths (map (fn [k] (apply max (count (str k)) (map #(count (str (get % k))) rows))) ks) spacers (map #(apply str (repeat % "-")) widths) fmt-row (fn [leader divider trailer row] (str leader (apply str (interpose divider (for [[col width] (map vector (map #(get row %) ks) widths)] (add-padding width (str col))))) trailer))] (cljs.core/println) (cljs.core/println (fmt-row "| " " | " " |" (zipmap ks ks))) (cljs.core/println (fmt-row "|-" "-+-" "-|" (zipmap ks spacers))) (doseq [row rows] (cljs.core/println (fmt-row "| " " | " " |" row)))))) ([rows] (print-table (keys (first rows)) rows)))
11392
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns cljs.pprint (:refer-clojure :exclude [deftype print println pr prn float?]) (:require-macros [cljs.pprint :as m :refer [with-pretty-writer getf setf deftype pprint-logical-block print-length-loop defdirectives formatter-out]]) (:require [cljs.core :refer [IWriter IDeref]] [clojure.string :as string] [goog.string :as gstring]) (:import [goog.string StringBuffer])) ;;====================================================================== ;; override print fns to use *out* ;;====================================================================== (defn- print [& more] (-write *out* (apply print-str more))) (defn- println [& more] (apply print more) (-write *out* \newline)) (defn- print-char [c] (-write *out* (condp = c \backspace "\\backspace" \tab "\\tab" \newline "\\newline" \formfeed "\\formfeed" \return "\\return" \" "\\\"" \\ "\\\\" (str "\\" c)))) (defn- ^:dynamic pr [& more] (-write *out* (apply pr-str more))) (defn- prn [& more] (apply pr more) (-write *out* \newline)) ;;====================================================================== ;; cljs specific utils ;;====================================================================== (defn ^boolean float? "Returns true if n is an float." [n] (and (number? n) (not ^boolean (js/isNaN n)) (not (identical? n js/Infinity)) (not (== (js/parseFloat n) (js/parseInt n 10))))) (defn char-code "Convert char to int" [c] (cond (number? c) c (and (string? c) (== (.-length c) 1)) (.charCodeAt c 0) :else (throw (js/Error. "Argument to char must be a character or number")))) ;;====================================================================== ;; Utilities ;;====================================================================== (defn- map-passing-context [func initial-context lis] (loop [context initial-context lis lis acc []] (if (empty? lis) [acc context] (let [this (first lis) remainder (next lis) [result new-context] (apply func [this context])] (recur new-context remainder (conj acc result)))))) (defn- consume [func initial-context] (loop [context initial-context acc []] (let [[result new-context] (apply func [context])] (if (not result) [acc new-context] (recur new-context (conj acc result)))))) (defn- consume-while [func initial-context] (loop [context initial-context acc []] (let [[result continue new-context] (apply func [context])] (if (not continue) [acc context] (recur new-context (conj acc result)))))) (defn- unzip-map [m] "Take a map that has pairs in the value slots and produce a pair of maps, the first having all the first elements of the pairs and the second all the second elements of the pairs" [(into {} (for [[k [v1 v2]] m] [k v1])) (into {} (for [[k [v1 v2]] m] [k v2]))]) (defn- tuple-map [m v1] "For all the values, v, in the map, replace them with [v v1]" (into {} (for [[k v] m] [k [v v1]]))) (defn- rtrim [s c] "Trim all instances of c from the end of sequence s" (let [len (count s)] (if (and (pos? len) (= (nth s (dec (count s))) c)) (loop [n (dec len)] (cond (neg? n) "" (not (= (nth s n) c)) (subs s 0 (inc n)) true (recur (dec n)))) s))) (defn- ltrim [s c] "Trim all instances of c from the beginning of sequence s" (let [len (count s)] (if (and (pos? len) (= (nth s 0) c)) (loop [n 0] (if (or (= n len) (not (= (nth s n) c))) (subs s n) (recur (inc n)))) s))) (defn- prefix-count [aseq val] "Return the number of times that val occurs at the start of sequence aseq, if val is a seq itself, count the number of times any element of val occurs at the beginning of aseq" (let [test (if (coll? val) (set val) #{val})] (loop [pos 0] (if (or (= pos (count aseq)) (not (test (nth aseq pos)))) pos (recur (inc pos)))))) ;; Flush the pretty-print buffer without flushing the underlying stream (defprotocol IPrettyFlush (-ppflush [pp])) ;;====================================================================== ;; column_writer.clj ;;====================================================================== (def ^:dynamic ^{:private true} *default-page-width* 72) (defn- get-field [this sym] (sym @@this)) (defn- set-field [this sym new-val] (swap! @this assoc sym new-val)) (defn- get-column [this] (get-field this :cur)) (defn- get-line [this] (get-field this :line)) (defn- get-max-column [this] (get-field this :max)) (defn- set-max-column [this new-max] (set-field this :max new-max) nil) (defn- get-writer [this] (get-field this :base)) ;; Why is the c argument an integer? (defn- c-write-char [this c] (if (= c \newline) (do (set-field this :cur 0) (set-field this :line (inc (get-field this :line)))) (set-field this :cur (inc (get-field this :cur)))) (-write (get-field this :base) c)) (defn- column-writer ([writer] (column-writer writer *default-page-width*)) ([writer max-columns] (let [fields (atom {:max max-columns, :cur 0, :line 0 :base writer})] (reify IDeref (-deref [_] fields) IWriter (-flush [_] (-flush writer)) (-write ;;-write isn't multi-arity, so need different way to do this #_([this ^chars cbuf ^Number off ^Number len] (let [writer (get-field this :base)] (-write writer cbuf off len))) [this x] (condp = (type x) js/String (let [s x nl (.lastIndexOf s \newline)] (if (neg? nl) (set-field this :cur (+ (get-field this :cur) (count s))) (do (set-field this :cur (- (count s) nl 1)) (set-field this :line (+ (get-field this :line) (count (filter #(= % \newline) s)))))) (-write (get-field this :base) s)) js/Number (c-write-char this x))))))) ;;====================================================================== ;; pretty_writer.clj ;;====================================================================== ;;====================================================================== ;; Forward declarations ;;====================================================================== (declare ^{:arglists '([this])} get-miser-width) ;;====================================================================== ;; The data structures used by pretty-writer ;;====================================================================== (defrecord ^{:private true} logical-block [parent section start-col indent done-nl intra-block-nl prefix per-line-prefix suffix logical-block-callback]) (defn- ancestor? [parent child] (loop [child (:parent child)] (cond (nil? child) false (identical? parent child) true :else (recur (:parent child))))) (defn- buffer-length [l] (let [l (seq l)] (if l (- (:end-pos (last l)) (:start-pos (first l))) 0))) ;; A blob of characters (aka a string) (deftype buffer-blob :data :trailing-white-space :start-pos :end-pos) ;; A newline (deftype nl-t :type :logical-block :start-pos :end-pos) (deftype start-block-t :logical-block :start-pos :end-pos) (deftype end-block-t :logical-block :start-pos :end-pos) (deftype indent-t :logical-block :relative-to :offset :start-pos :end-pos) (def ^:private pp-newline (fn [] "\n")) (declare emit-nl) (defmulti ^{:private true} write-token #(:type-tag %2)) (defmethod write-token :start-block-t [this token] (when-let [cb (getf :logical-block-callback)] (cb :start)) (let [lb (:logical-block token)] (when-let [prefix (:prefix lb)] (-write (getf :base) prefix)) (let [col (get-column (getf :base))] (reset! (:start-col lb) col) (reset! (:indent lb) col)))) (defmethod write-token :end-block-t [this token] (when-let [cb (getf :logical-block-callback)] (cb :end)) (when-let [suffix (:suffix (:logical-block token))] (-write (getf :base) suffix))) (defmethod write-token :indent-t [this token] (let [lb (:logical-block token)] (reset! (:indent lb) (+ (:offset token) (condp = (:relative-to token) :block @(:start-col lb) :current (get-column (getf :base))))))) (defmethod write-token :buffer-blob [this token] (-write (getf :base) (:data token))) (defmethod write-token :nl-t [this token] (if (or (= (:type token) :mandatory) (and (not (= (:type token) :fill)) @(:done-nl (:logical-block token)))) (emit-nl this token) (if-let [tws (getf :trailing-white-space)] (-write (getf :base) tws))) (setf :trailing-white-space nil)) (defn- write-tokens [this tokens force-trailing-whitespace] (doseq [token tokens] (if-not (= (:type-tag token) :nl-t) (if-let [tws (getf :trailing-white-space)] (-write (getf :base) tws))) (write-token this token) (setf :trailing-white-space (:trailing-white-space token)) (let [tws (getf :trailing-white-space)] (when (and force-trailing-whitespace tws) (-write (getf :base) tws) (setf :trailing-white-space nil))))) ;;====================================================================== ;; emit-nl? method defs for each type of new line. This makes ;; the decision about whether to print this type of new line. ;;====================================================================== (defn- tokens-fit? [this tokens] (let [maxcol (get-max-column (getf :base))] (or (nil? maxcol) (< (+ (get-column (getf :base)) (buffer-length tokens)) maxcol)))) (defn- linear-nl? [this lb section] (or @(:done-nl lb) (not (tokens-fit? this section)))) (defn- miser-nl? [this lb section] (let [miser-width (get-miser-width this) maxcol (get-max-column (getf :base))] (and miser-width maxcol (>= @(:start-col lb) (- maxcol miser-width)) (linear-nl? this lb section)))) (defmulti ^{:private true} emit-nl? (fn [t _ _ _] (:type t))) (defmethod emit-nl? :linear [newl this section _] (let [lb (:logical-block newl)] (linear-nl? this lb section))) (defmethod emit-nl? :miser [newl this section _] (let [lb (:logical-block newl)] (miser-nl? this lb section))) (defmethod emit-nl? :fill [newl this section subsection] (let [lb (:logical-block newl)] (or @(:intra-block-nl lb) (not (tokens-fit? this subsection)) (miser-nl? this lb section)))) (defmethod emit-nl? :mandatory [_ _ _ _] true) ;;====================================================================== ;; Various support functions ;;====================================================================== (defn- get-section [buffer] (let [nl (first buffer) lb (:logical-block nl) section (seq (take-while #(not (and (nl-t? %) (ancestor? (:logical-block %) lb))) (next buffer)))] [section (seq (drop (inc (count section)) buffer))])) (defn- get-sub-section [buffer] (let [nl (first buffer) lb (:logical-block nl) section (seq (take-while #(let [nl-lb (:logical-block %)] (not (and (nl-t? %) (or (= nl-lb lb) (ancestor? nl-lb lb))))) (next buffer)))] section)) (defn- update-nl-state [lb] (reset! (:intra-block-nl lb) true) (reset! (:done-nl lb) true) (loop [lb (:parent lb)] (if lb (do (reset! (:done-nl lb) true) (reset! (:intra-block-nl lb) true) (recur (:parent lb)))))) (defn- emit-nl [this nl] (-write (getf :base) (pp-newline)) (setf :trailing-white-space nil) (let [lb (:logical-block nl) prefix (:per-line-prefix lb)] (if prefix (-write (getf :base) prefix)) (let [istr (apply str (repeat (- @(:indent lb) (count prefix)) \space))] (-write (getf :base) istr)) (update-nl-state lb))) (defn- split-at-newline [tokens] (let [pre (seq (take-while #(not (nl-t? %)) tokens))] [pre (seq (drop (count pre) tokens))])) ;; write-token-string is called when the set of tokens in the buffer ;; is long than the available space on the line (defn- write-token-string [this tokens] (let [[a b] (split-at-newline tokens)] (if a (write-tokens this a false)) (if b (let [[section remainder] (get-section b) newl (first b)] (let [do-nl (emit-nl? newl this section (get-sub-section b)) result (if do-nl (do (emit-nl this newl) (next b)) b) long-section (not (tokens-fit? this result)) result (if long-section (let [rem2 (write-token-string this section)] (if (= rem2 section) (do ; If that didn't produce any output, it has no nls ; so we'll force it (write-tokens this section false) remainder) (into [] (concat rem2 remainder)))) result)] result))))) (defn- write-line [this] (loop [buffer (getf :buffer)] (setf :buffer (into [] buffer)) (if (not (tokens-fit? this buffer)) (let [new-buffer (write-token-string this buffer)] (if-not (identical? buffer new-buffer) (recur new-buffer)))))) ;; Add a buffer token to the buffer and see if it's time to start ;; writing (defn- add-to-buffer [this token] (setf :buffer (conj (getf :buffer) token)) (if (not (tokens-fit? this (getf :buffer))) (write-line this))) ;; Write all the tokens that have been buffered (defn- write-buffered-output [this] (write-line this) (if-let [buf (getf :buffer)] (do (write-tokens this buf true) (setf :buffer [])))) (defn- write-white-space [this] (when-let [tws (getf :trailing-white-space)] (-write (getf :base) tws) (setf :trailing-white-space nil))) ;;; If there are newlines in the string, print the lines up until the last newline, ;;; making the appropriate adjustments. Return the remainder of the string (defn- write-initial-lines [^Writer this ^String s] (let [lines (string/split s "\n" -1)] (if (= (count lines) 1) s (let [^String prefix (:per-line-prefix (first (getf :logical-blocks))) ^String l (first lines)] (if (= :buffering (getf :mode)) (let [oldpos (getf :pos) newpos (+ oldpos (count l))] (setf :pos newpos) (add-to-buffer this (make-buffer-blob l nil oldpos newpos)) (write-buffered-output this)) (do (write-white-space this) (-write (getf :base) l))) (-write (getf :base) \newline) (doseq [^String l (next (butlast lines))] (-write (getf :base) l) (-write (getf :base) (pp-newline)) (if prefix (-write (getf :base) prefix))) (setf :buffering :writing) (last lines))))) (defn- p-write-char [this c] (if (= (getf :mode) :writing) (do (write-white-space this) (-write (getf :base) c)) (if (= c \newline) (write-initial-lines this \newline) (let [oldpos (getf :pos) newpos (inc oldpos)] (setf :pos newpos) (add-to-buffer this (make-buffer-blob (char c) nil oldpos newpos)))))) ;;====================================================================== ;; Initialize the pretty-writer instance ;;====================================================================== (defn- pretty-writer [writer max-columns miser-width] (let [lb (logical-block. nil nil (atom 0) (atom 0) (atom false) (atom false) nil nil nil nil) ; NOTE: may want to just `specify!` #js { ... fields ... } with the protocols fields (atom {:pretty-writer true :base (column-writer writer max-columns) :logical-blocks lb :sections nil :mode :writing :buffer [] :buffer-block lb :buffer-level 1 :miser-width miser-width :trailing-white-space nil :pos 0})] (reify IDeref (-deref [_] fields) IWriter (-write [this x] (condp = (type x) js/String (let [s0 (write-initial-lines this x) s (string/replace-first s0 #"\s+$" "") white-space (subs s0 (count s)) mode (getf :mode)] (if (= mode :writing) (do (write-white-space this) (-write (getf :base) s) (setf :trailing-white-space white-space)) (let [oldpos (getf :pos) newpos (+ oldpos (count s0))] (setf :pos newpos) (add-to-buffer this (make-buffer-blob s white-space oldpos newpos))))) js/Number (p-write-char this x))) (-flush [this] (-ppflush this) (-flush (getf :base))) IPrettyFlush (-ppflush [this] (if (= (getf :mode) :buffering) (do (write-tokens this (getf :buffer) true) (setf :buffer [])) (write-white-space this))) ))) ;;====================================================================== ;; Methods for pretty-writer ;;====================================================================== (defn- start-block [this prefix per-line-prefix suffix] (let [lb (logical-block. (getf :logical-blocks) nil (atom 0) (atom 0) (atom false) (atom false) prefix per-line-prefix suffix nil)] (setf :logical-blocks lb) (if (= (getf :mode) :writing) (do (write-white-space this) (when-let [cb (getf :logical-block-callback)] (cb :start)) (if prefix (-write (getf :base) prefix)) (let [col (get-column (getf :base))] (reset! (:start-col lb) col) (reset! (:indent lb) col))) (let [oldpos (getf :pos) newpos (+ oldpos (if prefix (count prefix) 0))] (setf :pos newpos) (add-to-buffer this (make-start-block-t lb oldpos newpos)))))) (defn- end-block [this] (let [lb (getf :logical-blocks) suffix (:suffix lb)] (if (= (getf :mode) :writing) (do (write-white-space this) (if suffix (-write (getf :base) suffix)) (when-let [cb (getf :logical-block-callback)] (cb :end))) (let [oldpos (getf :pos) newpos (+ oldpos (if suffix (count suffix) 0))] (setf :pos newpos) (add-to-buffer this (make-end-block-t lb oldpos newpos)))) (setf :logical-blocks (:parent lb)))) (defn- nl [this type] (setf :mode :buffering) (let [pos (getf :pos)] (add-to-buffer this (make-nl-t type (getf :logical-blocks) pos pos)))) (defn- indent [this relative-to offset] (let [lb (getf :logical-blocks)] (if (= (getf :mode) :writing) (do (write-white-space this) (reset! (:indent lb) (+ offset (condp = relative-to :block @(:start-col lb) :current (get-column (getf :base)))))) (let [pos (getf :pos)] (add-to-buffer this (make-indent-t lb relative-to offset pos pos)))))) (defn- get-miser-width [this] (getf :miser-width)) ;;====================================================================== ;; pprint_base.clj ;;====================================================================== ;;====================================================================== ;; Variables that control the pretty printer ;;====================================================================== ;; *print-length*, *print-level*, *print-namespace-maps* and *print-dup* are defined in cljs.core (def ^:dynamic ^{:doc "Bind to true if you want write to use pretty printing"} *print-pretty* true) (defonce ^:dynamic ^{:doc "The pretty print dispatch function. Use with-pprint-dispatch or set-pprint-dispatch to modify." :added "1.2"} *print-pprint-dispatch* nil) (def ^:dynamic ^{:doc "Pretty printing will try to avoid anything going beyond this column. Set it to nil to have pprint let the line be arbitrarily long. This will ignore all non-mandatory newlines.", :added "1.2"} *print-right-margin* 72) (def ^:dynamic ^{:doc "The column at which to enter miser style. Depending on the dispatch table, miser style add newlines in more places to try to keep lines short allowing for further levels of nesting.", :added "1.2"} *print-miser-width* 40) ;;; TODO implement output limiting (def ^:dynamic ^{:private true, :doc "Maximum number of lines to print in a pretty print instance (N.B. This is not yet used)"} *print-lines* nil) ;;; TODO: implement circle and shared (def ^:dynamic ^{:private true, :doc "Mark circular structures (N.B. This is not yet used)"} *print-circle* nil) ;;; TODO: should we just use *print-dup* here? (def ^:dynamic ^{:private true, :doc "Mark repeated structures rather than repeat them (N.B. This is not yet used)"} *print-shared* nil) (def ^:dynamic ^{:doc "Don't print namespaces with symbols. This is particularly useful when pretty printing the results of macro expansions" :added "1.2"} *print-suppress-namespaces* nil) ;;; TODO: support print-base and print-radix in cl-format ;;; TODO: support print-base and print-radix in rationals (def ^:dynamic ^{:doc "Print a radix specifier in front of integers and rationals. If *print-base* is 2, 8, or 16, then the radix specifier used is #b, #o, or #x, respectively. Otherwise the radix specifier is in the form #XXr where XX is the decimal value of *print-base* " :added "1.2"} *print-radix* nil) (def ^:dynamic ^{:doc "The base to use for printing integers and rationals." :added "1.2"} *print-base* 10) ;;====================================================================== ;; Internal variables that keep track of where we are in the ;; structure ;;====================================================================== (def ^:dynamic ^{:private true} *current-level* 0) (def ^:dynamic ^{:private true} *current-length* nil) ;;====================================================================== ;; Support for the write function ;;====================================================================== (declare ^{:arglists '([n])} format-simple-number) ;; This map causes var metadata to be included in the compiled output, even ;; in advanced compilation. See CLJS-1853 - <NAME> ;; (def ^{:private true} write-option-table ;; {;:array *print-array* ;; :base #'cljs.pprint/*print-base*, ;; ;;:case *print-case*, ;; :circle #'cljs.pprint/*print-circle*, ;; ;;:escape *print-escape*, ;; ;;:gensym *print-gensym*, ;; :length #'cljs.core/*print-length*, ;; :level #'cljs.core/*print-level*, ;; :lines #'cljs.pprint/*print-lines*, ;; :miser-width #'cljs.pprint/*print-miser-width*, ;; :dispatch #'cljs.pprint/*print-pprint-dispatch*, ;; :pretty #'cljs.pprint/*print-pretty*, ;; :radix #'cljs.pprint/*print-radix*, ;; :readably #'cljs.core/*print-readably*, ;; :right-margin #'cljs.pprint/*print-right-margin*, ;; :suppress-namespaces #'cljs.pprint/*print-suppress-namespaces*}) (defn- table-ize [t m] (apply hash-map (mapcat #(when-let [v (get t (key %))] [v (val %)]) m))) (defn- pretty-writer? "Return true iff x is a PrettyWriter" [x] (and (satisfies? IDeref x) (:pretty-writer @@x))) (defn- make-pretty-writer "Wrap base-writer in a PrettyWriter with the specified right-margin and miser-width" [base-writer right-margin miser-width] (pretty-writer base-writer right-margin miser-width)) (defn write-out "Write an object to *out* subject to the current bindings of the printer control variables. Use the kw-args argument to override individual variables for this call (and any recursive calls). *out* must be a PrettyWriter if pretty printing is enabled. This is the responsibility of the caller. This method is primarily intended for use by pretty print dispatch functions that already know that the pretty printer will have set up their environment appropriately. Normal library clients should use the standard \"write\" interface. " [object] (let [length-reached (and *current-length* *print-length* (>= *current-length* *print-length*))] (if-not *print-pretty* (pr object) (if length-reached (-write *out* "...") ;;TODO could this (incorrectly) print ... on the next line? (do (if *current-length* (set! *current-length* (inc *current-length*))) (*print-pprint-dispatch* object)))) length-reached)) (defn write "Write an object subject to the current bindings of the printer control variables. Use the kw-args argument to override individual variables for this call (and any recursive calls). Returns the string result if :stream is nil or nil otherwise. The following keyword arguments can be passed with values: Keyword Meaning Default value :stream Writer for output or nil true (indicates *out*) :base Base to use for writing rationals Current value of *print-base* :circle* If true, mark circular structures Current value of *print-circle* :length Maximum elements to show in sublists Current value of *print-length* :level Maximum depth Current value of *print-level* :lines* Maximum lines of output Current value of *print-lines* :miser-width Width to enter miser mode Current value of *print-miser-width* :dispatch The pretty print dispatch function Current value of *print-pprint-dispatch* :pretty If true, do pretty printing Current value of *print-pretty* :radix If true, prepend a radix specifier Current value of *print-radix* :readably* If true, print readably Current value of *print-readably* :right-margin The column for the right margin Current value of *print-right-margin* :suppress-namespaces If true, no namespaces in symbols Current value of *print-suppress-namespaces* * = not yet supported " [object & kw-args] (let [options (merge {:stream true} (apply hash-map kw-args))] ;;TODO rewrite this as a macro (binding [cljs.pprint/*print-base* (:base options cljs.pprint/*print-base*) ;;:case *print-case*, cljs.pprint/*print-circle* (:circle options cljs.pprint/*print-circle*) ;;:escape *print-escape* ;;:gensym *print-gensym* cljs.core/*print-length* (:length options cljs.core/*print-length*) cljs.core/*print-level* (:level options cljs.core/*print-level*) cljs.pprint/*print-lines* (:lines options cljs.pprint/*print-lines*) cljs.pprint/*print-miser-width* (:miser-width options cljs.pprint/*print-miser-width*) cljs.pprint/*print-pprint-dispatch* (:dispatch options cljs.pprint/*print-pprint-dispatch*) cljs.pprint/*print-pretty* (:pretty options cljs.pprint/*print-pretty*) cljs.pprint/*print-radix* (:radix options cljs.pprint/*print-radix*) cljs.core/*print-readably* (:readably options cljs.core/*print-readably*) cljs.pprint/*print-right-margin* (:right-margin options cljs.pprint/*print-right-margin*) cljs.pprint/*print-suppress-namespaces* (:suppress-namespaces options cljs.pprint/*print-suppress-namespaces*)] ;;TODO enable printing base #_[bindings (if (or (not (= *print-base* 10)) *print-radix*) {#'pr pr-with-base} {})] (binding [] (let [sb (StringBuffer.) optval (if (contains? options :stream) (:stream options) true) base-writer (if (or (true? optval) (nil? optval)) (StringBufferWriter. sb) optval)] (if *print-pretty* (with-pretty-writer base-writer (write-out object)) (binding [*out* base-writer] (pr object))) (if (true? optval) (string-print (str sb))) (if (nil? optval) (str sb))))))) (defn pprint ([object] (let [sb (StringBuffer.)] (binding [*out* (StringBufferWriter. sb)] (pprint object *out*) (string-print (str sb))))) ([object writer] (with-pretty-writer writer (binding [*print-pretty* true] (write-out object)) (if (not (= 0 (get-column *out*))) (-write *out* \newline))))) (defn set-pprint-dispatch [function] (set! *print-pprint-dispatch* function) nil) ;;====================================================================== ;; Support for the functional interface to the pretty printer ;;====================================================================== (defn- check-enumerated-arg [arg choices] (if-not (choices arg) ;; TODO clean up choices string (throw (js/Error. (str "Bad argument: " arg ". It must be one of " choices))))) (defn- level-exceeded [] (and *print-level* (>= *current-level* *print-level*))) (defn pprint-newline "Print a conditional newline to a pretty printing stream. kind specifies if the newline is :linear, :miser, :fill, or :mandatory. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer." [kind] (check-enumerated-arg kind #{:linear :miser :fill :mandatory}) (nl *out* kind)) (defn pprint-indent "Create an indent at this point in the pretty printing stream. This defines how following lines are indented. relative-to can be either :block or :current depending whether the indent should be computed relative to the start of the logical block or the current column position. n is an offset. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer." [relative-to n] (check-enumerated-arg relative-to #{:block :current}) (indent *out* relative-to n)) ;; TODO a real implementation for pprint-tab (defn pprint-tab "Tab at this point in the pretty printing stream. kind specifies whether the tab is :line, :section, :line-relative, or :section-relative. Colnum and colinc specify the target column and the increment to move the target forward if the output is already past the original target. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer. THIS FUNCTION IS NOT YET IMPLEMENTED." {:added "1.2"} [kind colnum colinc] (check-enumerated-arg kind #{:line :section :line-relative :section-relative}) (throw (js/Error. "pprint-tab is not yet implemented"))) ;;====================================================================== ;; cl_format.clj ;;====================================================================== ;; Forward references (declare ^{:arglists '([format-str])} compile-format) (declare ^{:arglists '([stream format args] [format args])} execute-format) (declare ^{:arglists '([s])} init-navigator) ;; End forward references (defn cl-format "An implementation of a Common Lisp compatible format function. cl-format formats its arguments to an output stream or string based on the format control string given. It supports sophisticated formatting of structured data. Writer satisfies IWriter, true to output via *print-fn* or nil to output to a string, format-in is the format control string and the remaining arguments are the data to be formatted. The format control string is a string to be output with embedded 'format directives' describing how to format the various arguments passed in. If writer is nil, cl-format returns the formatted result string. Otherwise, cl-format returns nil. For example: (let [results [46 38 22]] (cl-format true \"There ~[are~;is~:;are~]~:* ~d result~:p: ~{~d~^, ~}~%\" (count results) results)) Prints via *print-fn*: There are 3 results: 46, 38, 22 Detailed documentation on format control strings is available in the \"Common Lisp the Language, 2nd edition\", Chapter 22 (available online at: http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000) and in the Common Lisp HyperSpec at http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm" {:see-also [["http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000" "Common Lisp the Language"] ["http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm" "Common Lisp HyperSpec"]]} [writer format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format writer compiled-format navigator))) (def ^:dynamic ^{:private true} *format-str* nil) (defn- format-error [message offset] (let [full-message (str message \newline *format-str* \newline (apply str (repeat offset \space)) "^" \newline)] (throw (js/Error full-message)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Argument navigators manage the argument list ;; as the format statement moves through the list ;; (possibly going forwards and backwards as it does so) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord ^{:private true} arg-navigator [seq rest pos]) (defn- init-navigator "Create a new arg-navigator from the sequence with the position set to 0" {:skip-wiki true} [s] (let [s (seq s)] (arg-navigator. s s 0))) ;; TODO call format-error with offset (defn- next-arg [navigator] (let [rst (:rest navigator)] (if rst [(first rst) (arg-navigator. (:seq navigator) (next rst) (inc (:pos navigator)))] (throw (js/Error "Not enough arguments for format definition"))))) (defn- next-arg-or-nil [navigator] (let [rst (:rest navigator)] (if rst [(first rst) (arg-navigator. (:seq navigator) (next rst) (inc (:pos navigator)))] [nil navigator]))) ;; Get an argument off the arg list and compile it if it's not already compiled (defn- get-format-arg [navigator] (let [[raw-format navigator] (next-arg navigator) compiled-format (if (string? raw-format) (compile-format raw-format) raw-format)] [compiled-format navigator])) (declare relative-reposition) (defn- absolute-reposition [navigator position] (if (>= position (:pos navigator)) (relative-reposition navigator (- (:pos navigator) position)) (arg-navigator. (:seq navigator) (drop position (:seq navigator)) position))) (defn- relative-reposition [navigator position] (let [newpos (+ (:pos navigator) position)] (if (neg? position) (absolute-reposition navigator newpos) (arg-navigator. (:seq navigator) (drop position (:rest navigator)) newpos)))) (defrecord ^{:private true} compiled-directive [func def params offset]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; When looking at the parameter list, we may need to manipulate ;; the argument list as well (for 'V' and '#' parameter types). ;; We hide all of this behind a function, but clients need to ;; manage changing arg navigator ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO: validate parameters when they come from arg list (defn- realize-parameter [[param [raw-val offset]] navigator] (let [[real-param new-navigator] (cond (contains? #{:at :colon} param) ;pass flags through unchanged - this really isn't necessary [raw-val navigator] (= raw-val :parameter-from-args) (next-arg navigator) (= raw-val :remaining-arg-count) [(count (:rest navigator)) navigator] true [raw-val navigator])] [[param [real-param offset]] new-navigator])) (defn- realize-parameter-list [parameter-map navigator] (let [[pairs new-navigator] (map-passing-context realize-parameter navigator parameter-map)] [(into {} pairs) new-navigator])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Functions that support individual directives ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Common handling code for ~A and ~S ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare ^{:arglists '([base val])} opt-base-str) (def ^{:private true} special-radix-markers {2 "#b" 8 "#o" 16 "#x"}) (defn- format-simple-number [n] (cond (integer? n) (if (= *print-base* 10) (str n (if *print-radix* ".")) (str (if *print-radix* (or (get special-radix-markers *print-base*) (str "#" *print-base* "r"))) (opt-base-str *print-base* n))) ;;(ratio? n) ;;no ratio support :else nil)) (defn- format-ascii [print-func params arg-navigator offsets] (let [[arg arg-navigator] (next-arg arg-navigator) base-output (or (format-simple-number arg) (print-func arg)) base-width (.-length base-output) min-width (+ base-width (:minpad params)) width (if (>= min-width (:mincol params)) min-width (+ min-width (* (+ (quot (- (:mincol params) min-width 1) (:colinc params)) 1) (:colinc params)))) chars (apply str (repeat (- width base-width) (:padchar params)))] (if (:at params) (print (str chars base-output)) (print (str base-output chars))) arg-navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the integer directives ~D, ~X, ~O, ~B and some ;; of ~R ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- integral? "returns true if a number is actually an integer (that is, has no fractional part)" [x] (cond (integer? x) true ;;(decimal? x) ;;no decimal support (float? x) (= x (Math/floor x)) ;;(ratio? x) ;;no ratio support :else false)) (defn- remainders "Return the list of remainders (essentially the 'digits') of val in the given base" [base val] (reverse (first (consume #(if (pos? %) [(rem % base) (quot % base)] [nil nil]) val)))) ;; TODO: xlated-val does not seem to be used here. ;; NB (defn- base-str "Return val as a string in the given base" [base val] (if (zero? val) "0" (let [xlated-val (cond ;(float? val) (bigdec val) ;;No bigdec ;(ratio? val) nil ;;No ratio :else val)] (apply str (map #(if (< % 10) (char (+ (char-code \0) %)) (char (+ (char-code \a) (- % 10)))) (remainders base val)))))) ;;Not sure if this is accurate or necessary (def ^{:private true} javascript-base-formats {8 "%o", 10 "%d", 16 "%x"}) (defn- opt-base-str "Return val as a string in the given base. No cljs format, so no improved performance." [base val] (base-str base val)) (defn- group-by* [unit lis] (reverse (first (consume (fn [x] [(seq (reverse (take unit x))) (seq (drop unit x))]) (reverse lis))))) (defn- format-integer [base params arg-navigator offsets] (let [[arg arg-navigator] (next-arg arg-navigator)] (if (integral? arg) (let [neg (neg? arg) pos-arg (if neg (- arg) arg) raw-str (opt-base-str base pos-arg) group-str (if (:colon params) (let [groups (map #(apply str %) (group-by* (:commainterval params) raw-str)) commas (repeat (count groups) (:commachar params))] (apply str (next (interleave commas groups)))) raw-str) signed-str (cond neg (str "-" group-str) (:at params) (str "+" group-str) true group-str) padded-str (if (< (.-length signed-str) (:mincol params)) (str (apply str (repeat (- (:mincol params) (.-length signed-str)) (:padchar params))) signed-str) signed-str)] (print padded-str)) (format-ascii print-str {:mincol (:mincol params) :colinc 1 :minpad 0 :padchar (:padchar params) :at true} (init-navigator [arg]) nil)) arg-navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for english formats (~R and ~:R) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} english-cardinal-units ["zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine" "ten" "eleven" "twelve" "thirteen" "fourteen" "fifteen" "sixteen" "seventeen" "eighteen" "nineteen"]) (def ^{:private true} english-ordinal-units ["zeroth" "first" "second" "third" "fourth" "fifth" "sixth" "seventh" "eighth" "ninth" "tenth" "eleventh" "twelfth" "thirteenth" "fourteenth" "fifteenth" "sixteenth" "seventeenth" "eighteenth" "nineteenth"]) (def ^{:private true} english-cardinal-tens ["" "" "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty" "ninety"]) (def ^{:private true} english-ordinal-tens ["" "" "twentieth" "thirtieth" "fortieth" "fiftieth" "sixtieth" "seventieth" "eightieth" "ninetieth"]) ;; We use "short scale" for our units (see http://en.wikipedia.org/wiki/Long_and_short_scales) ;; Number names from http://www.jimloy.com/math/billion.htm ;; We follow the rules for writing numbers from the Blue Book ;; (http://www.grammarbook.com/numbers/numbers.asp) (def ^{:private true} english-scale-numbers ["" "thousand" "million" "billion" "trillion" "quadrillion" "quintillion" "sextillion" "septillion" "octillion" "nonillion" "decillion" "undecillion" "duodecillion" "tredecillion" "quattuordecillion" "quindecillion" "sexdecillion" "septendecillion" "octodecillion" "novemdecillion" "vigintillion"]) (defn- format-simple-cardinal "Convert a number less than 1000 to a cardinal english string" [num] (let [hundreds (quot num 100) tens (rem num 100)] (str (if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred")) (if (and (pos? hundreds) (pos? tens)) " ") (if (pos? tens) (if (< tens 20) (nth english-cardinal-units tens) (let [ten-digit (quot tens 10) unit-digit (rem tens 10)] (str (if (pos? ten-digit) (nth english-cardinal-tens ten-digit)) (if (and (pos? ten-digit) (pos? unit-digit)) "-") (if (pos? unit-digit) (nth english-cardinal-units unit-digit))))))))) (defn- add-english-scales "Take a sequence of parts, add scale numbers (e.g., million) and combine into a string offset is a factor of 10^3 to multiply by" [parts offset] (let [cnt (count parts)] (loop [acc [] pos (dec cnt) this (first parts) remainder (next parts)] (if (nil? remainder) (str (apply str (interpose ", " acc)) (if (and (not (empty? this)) (not (empty? acc))) ", ") this (if (and (not (empty? this)) (pos? (+ pos offset))) (str " " (nth english-scale-numbers (+ pos offset))))) (recur (if (empty? this) acc (conj acc (str this " " (nth english-scale-numbers (+ pos offset))))) (dec pos) (first remainder) (next remainder)))))) (defn- format-cardinal-english [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (= 0 arg) (print "zero") (let [abs-arg (if (neg? arg) (- arg) arg) ; some numbers are too big for Math/abs (is this true?) parts (remainders 1000 abs-arg)] (if (<= (count parts) (count english-scale-numbers)) (let [parts-strs (map format-simple-cardinal parts) full-str (add-english-scales parts-strs 0)] (print (str (if (neg? arg) "minus ") full-str))) (format-integer ;; for numbers > 10^63, we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0})))) navigator)) (defn- format-simple-ordinal "Convert a number less than 1000 to a ordinal english string Note this should only be used for the last one in the sequence" [num] (let [hundreds (quot num 100) tens (rem num 100)] (str (if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred")) (if (and (pos? hundreds) (pos? tens)) " ") (if (pos? tens) (if (< tens 20) (nth english-ordinal-units tens) (let [ten-digit (quot tens 10) unit-digit (rem tens 10)] (if (and (pos? ten-digit) (not (pos? unit-digit))) (nth english-ordinal-tens ten-digit) (str (if (pos? ten-digit) (nth english-cardinal-tens ten-digit)) (if (and (pos? ten-digit) (pos? unit-digit)) "-") (if (pos? unit-digit) (nth english-ordinal-units unit-digit)))))) (if (pos? hundreds) "th"))))) (defn- format-ordinal-english [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (= 0 arg) (print "zeroth") (let [abs-arg (if (neg? arg) (- arg) arg) ; some numbers are too big for Math/abs (is this true?) parts (remainders 1000 abs-arg)] (if (<= (count parts) (count english-scale-numbers)) (let [parts-strs (map format-simple-cardinal (drop-last parts)) head-str (add-english-scales parts-strs 1) tail-str (format-simple-ordinal (last parts))] (print (str (if (neg? arg) "minus ") (cond (and (not (empty? head-str)) (not (empty? tail-str))) (str head-str ", " tail-str) (not (empty? head-str)) (str head-str "th") :else tail-str)))) (do (format-integer ;for numbers > 10^63, we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0}) (let [low-two-digits (rem arg 100) not-teens (or (< 11 low-two-digits) (> 19 low-two-digits)) low-digit (rem low-two-digits 10)] (print (cond (and (== low-digit 1) not-teens) "st" (and (== low-digit 2) not-teens) "nd" (and (== low-digit 3) not-teens) "rd" :else "th"))))))) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for roman numeral formats (~@R and ~@:R) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} old-roman-table [[ "I" "II" "III" "IIII" "V" "VI" "VII" "VIII" "VIIII"] [ "X" "XX" "XXX" "XXXX" "L" "LX" "LXX" "LXXX" "LXXXX"] [ "C" "CC" "CCC" "CCCC" "D" "DC" "DCC" "DCCC" "DCCCC"] [ "M" "MM" "MMM"]]) (def ^{:private true} new-roman-table [[ "I" "II" "III" "IV" "V" "VI" "VII" "VIII" "IX"] [ "X" "XX" "XXX" "XL" "L" "LX" "LXX" "LXXX" "XC"] [ "C" "CC" "CCC" "CD" "D" "DC" "DCC" "DCCC" "CM"] [ "M" "MM" "MMM"]]) (defn- format-roman "Format a roman numeral using the specified look-up table" [table params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (and (number? arg) (> arg 0) (< arg 4000)) (let [digits (remainders 10 arg)] (loop [acc [] pos (dec (count digits)) digits digits] (if (empty? digits) (print (apply str acc)) (let [digit (first digits)] (recur (if (= 0 digit) acc (conj acc (nth (nth table pos) (dec digit)))) (dec pos) (next digits)))))) (format-integer ; for anything <= 0 or > 3999, we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0})) navigator)) (defn- format-old-roman [params navigator offsets] (format-roman old-roman-table params navigator offsets)) (defn- format-new-roman [params navigator offsets] (format-roman new-roman-table params navigator offsets)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for character formats (~C) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} special-chars {8 "Backspace", 9 "Tab", 10 "Newline", 13 "Return", 32 "Space"}) (defn- pretty-character [params navigator offsets] (let [[c navigator] (next-arg navigator) as-int (char-code c) base-char (bit-and as-int 127) meta (bit-and as-int 128) special (get special-chars base-char)] (if (> meta 0) (print "Meta-")) (print (cond special special (< base-char 32) (str "Control-" (char (+ base-char 64))) (= base-char 127) "Control-?" :else (char base-char))) navigator)) (defn- readable-character [params navigator offsets] (let [[c navigator] (next-arg navigator)] (condp = (:char-format params) \o (cl-format true "\\o~3, '0o" (char-code c)) \u (cl-format true "\\u~4, '0x" (char-code c)) nil (print-char c)) navigator)) (defn- plain-character [params navigator offsets] (let [[char navigator] (next-arg navigator)] (print char) navigator)) ;; Check to see if a result is an abort (~^) construct ;; TODO: move these funcs somewhere more appropriate (defn- abort? [context] (let [token (first context)] (or (= :up-arrow token) (= :colon-up-arrow token)))) ;; Handle the execution of "sub-clauses" in bracket constructions (defn- execute-sub-format [format args base-args] (second (map-passing-context (fn [element context] (if (abort? context) [nil context] ; just keep passing it along (let [[params args] (realize-parameter-list (:params element) context) [params offsets] (unzip-map params) params (assoc params :base-args base-args)] [nil (apply (:func element) [params args offsets])]))) args format))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for real number formats ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO - return exponent as int to eliminate double conversion (defn- float-parts-base "Produce string parts for the mantissa (normalize 1-9) and exponent" [f] (let [s (string/lower-case (str f)) exploc (.indexOf s \e) dotloc (.indexOf s \.)] (if (neg? exploc) (if (neg? dotloc) [s (str (dec (count s)))] [(str (subs s 0 dotloc) (subs s (inc dotloc))) (str (dec dotloc))]) (if (neg? dotloc) [(subs s 0 exploc) (subs s (inc exploc))] [(str (subs s 0 1) (subs s 2 exploc)) (subs s (inc exploc))])))) (defn- float-parts "Take care of leading and trailing zeros in decomposed floats" [f] (let [[m e] (float-parts-base f) m1 (rtrim m \0) m2 (ltrim m1 \0) delta (- (count m1) (count m2)) e (if (and (pos? (count e)) (= (nth e 0) \+)) (subs e 1) e)] (if (empty? m2) ["0" 0] [m2 (- (js/parseInt e 10) delta)]))) (defn- inc-s "Assumption: The input string consists of one or more decimal digits, and no other characters. Return a string containing one or more decimal digits containing a decimal number one larger than the input string. The output string will always be the same length as the input string, or one character longer." [s] (let [len-1 (dec (count s))] (loop [i (int len-1)] (cond (neg? i) (apply str "1" (repeat (inc len-1) "0")) (= \9 (.charAt s i)) (recur (dec i)) :else (apply str (subs s 0 i) (char (inc (char-code (.charAt s i)))) (repeat (- len-1 i) "0")))))) (defn- round-str [m e d w] (if (or d w) (let [len (count m) ;; Every formatted floating point number should include at ;; least one decimal digit and a decimal point. w (if w (max 2 w) ;;NB: if w doesn't exist, it won't ever be used because d will ;; satisfy the cond below. cljs gives a compilation warning if ;; we don't provide a value here. 0) round-pos (cond ;; If d was given, that forces the rounding ;; position, regardless of any width that may ;; have been specified. d (+ e d 1) ;; Otherwise w was specified, so pick round-pos ;; based upon that. ;; If e>=0, then abs value of number is >= 1.0, ;; and e+1 is number of decimal digits before the ;; decimal point when the number is written ;; without scientific notation. Never round the ;; number before the decimal point. (>= e 0) (max (inc e) (dec w)) ;; e < 0, so number abs value < 1.0 :else (+ w e)) [m1 e1 round-pos len] (if (= round-pos 0) [(str "0" m) (inc e) 1 (inc len)] [m e round-pos len])] (if round-pos (if (neg? round-pos) ["0" 0 false] (if (> len round-pos) (let [round-char (nth m1 round-pos) result (subs m1 0 round-pos)] (if (>= (char-code round-char) (char-code \5)) (let [round-up-result (inc-s result) expanded (> (count round-up-result) (count result))] [(if expanded (subs round-up-result 0 (dec (count round-up-result))) round-up-result) e1 expanded]) [result e1 false])) [m e false])) [m e false])) [m e false])) (defn- expand-fixed [m e d] (let [[m1 e1] (if (neg? e) [(str (apply str (repeat (dec (- e)) \0)) m) -1] [m e]) len (count m1) target-len (if d (+ e1 d 1) (inc e1))] (if (< len target-len) (str m1 (apply str (repeat (- target-len len) \0))) m1))) (defn- insert-decimal "Insert the decimal point at the right spot in the number to match an exponent" [m e] (if (neg? e) (str "." m) (let [loc (inc e)] (str (subs m 0 loc) "." (subs m loc))))) (defn- get-fixed [m e d] (insert-decimal (expand-fixed m e d) e)) (defn- insert-scaled-decimal "Insert the decimal point at the right spot in the number to match an exponent" [m k] (if (neg? k) (str "." m) (str (subs m 0 k) "." (subs m k)))) ;;TODO: No ratio, so not sure what to do here (defn- convert-ratio [x] x) ;; the function to render ~F directives ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases (defn- fixed-float [params navigator offsets] (let [w (:w params) d (:d params) [arg navigator] (next-arg navigator) [sign abs] (if (neg? arg) ["-" (- arg)] ["+" arg]) abs (convert-ratio abs) [mantissa exp] (float-parts abs) scaled-exp (+ exp (:k params)) add-sign (or (:at params) (neg? arg)) append-zero (and (not d) (<= (dec (count mantissa)) scaled-exp)) [rounded-mantissa scaled-exp expanded] (round-str mantissa scaled-exp d (if w (- w (if add-sign 1 0)))) fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d) fixed-repr (if (and w d (>= d 1) (= (.charAt fixed-repr 0) \0) (= (.charAt fixed-repr 1) \.) (> (count fixed-repr) (- w (if add-sign 1 0)))) (subs fixed-repr 1) ;chop off leading 0 fixed-repr) prepend-zero (= (first fixed-repr) \.)] (if w (let [len (count fixed-repr) signed-len (if add-sign (inc len) len) prepend-zero (and prepend-zero (not (>= signed-len w))) append-zero (and append-zero (not (>= signed-len w))) full-len (if (or prepend-zero append-zero) (inc signed-len) signed-len)] (if (and (> full-len w) (:overflowchar params)) (print (apply str (repeat w (:overflowchar params)))) (print (str (apply str (repeat (- w full-len) (:padchar params))) (if add-sign sign) (if prepend-zero "0") fixed-repr (if append-zero "0"))))) (print (str (if add-sign sign) (if prepend-zero "0") fixed-repr (if append-zero "0")))) navigator)) ;; the function to render ~E directives ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases ;; TODO: define ~E representation for Infinity (defn- exponential-float [params navigator offset] (let [[arg navigator] (next-arg navigator) arg (convert-ratio arg)] (loop [[mantissa exp] (float-parts (if (neg? arg) (- arg) arg))] (let [w (:w params) d (:d params) e (:e params) k (:k params) expchar (or (:exponentchar params) \E) add-sign (or (:at params) (neg? arg)) prepend-zero (<= k 0) scaled-exp (- exp (dec k)) scaled-exp-str (str (Math/abs scaled-exp)) scaled-exp-str (str expchar (if (neg? scaled-exp) \- \+) (if e (apply str (repeat (- e (count scaled-exp-str)) \0))) scaled-exp-str) exp-width (count scaled-exp-str) base-mantissa-width (count mantissa) scaled-mantissa (str (apply str (repeat (- k) \0)) mantissa (if d (apply str (repeat (- d (dec base-mantissa-width) (if (neg? k) (- k) 0)) \0)))) w-mantissa (if w (- w exp-width)) [rounded-mantissa _ incr-exp] (round-str scaled-mantissa 0 (cond (= k 0) (dec d) (pos? k) d (neg? k) (dec d)) (if w-mantissa (- w-mantissa (if add-sign 1 0)))) full-mantissa (insert-scaled-decimal rounded-mantissa k) append-zero (and (= k (count rounded-mantissa)) (nil? d))] (if (not incr-exp) (if w (let [len (+ (count full-mantissa) exp-width) signed-len (if add-sign (inc len) len) prepend-zero (and prepend-zero (not (= signed-len w))) full-len (if prepend-zero (inc signed-len) signed-len) append-zero (and append-zero (< full-len w))] (if (and (or (> full-len w) (and e (> (- exp-width 2) e))) (:overflowchar params)) (print (apply str (repeat w (:overflowchar params)))) (print (str (apply str (repeat (- w full-len (if append-zero 1 0)) (:padchar params))) (if add-sign (if (neg? arg) \- \+)) (if prepend-zero "0") full-mantissa (if append-zero "0") scaled-exp-str)))) (print (str (if add-sign (if (neg? arg) \- \+)) (if prepend-zero "0") full-mantissa (if append-zero "0") scaled-exp-str))) (recur [rounded-mantissa (inc exp)])))) navigator)) ;; the function to render ~G directives ;; This just figures out whether to pass the request off to ~F or ~E based ;; on the algorithm in CLtL. ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases ;; TODO: refactor so that float-parts isn't called twice (defn- general-float [params navigator offsets] (let [[arg _] (next-arg navigator) arg (convert-ratio arg) [mantissa exp] (float-parts (if (neg? arg) (- arg) arg)) w (:w params) d (:d params) e (:e params) n (if (= arg 0.0) 0 (inc exp)) ee (if e (+ e 2) 4) ww (if w (- w ee)) d (if d d (max (count mantissa) (min n 7))) dd (- d n)] (if (<= 0 dd d) (let [navigator (fixed-float {:w ww, :d dd, :k 0, :overflowchar (:overflowchar params), :padchar (:padchar params), :at (:at params)} navigator offsets)] (print (apply str (repeat ee \space))) navigator) (exponential-float params navigator offsets)))) ;; the function to render ~$ directives ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases (defn- dollar-float [params navigator offsets] (let [[arg navigator] (next-arg navigator) [mantissa exp] (float-parts (Math/abs arg)) d (:d params) ; digits after the decimal n (:n params) ; minimum digits before the decimal w (:w params) ; minimum field width add-sign (or (:at params) (neg? arg)) [rounded-mantissa scaled-exp expanded] (round-str mantissa exp d nil) fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d) full-repr (str (apply str (repeat (- n (.indexOf fixed-repr \.)) \0)) fixed-repr) full-len (+ (count full-repr) (if add-sign 1 0))] (print (str (if (and (:colon params) add-sign) (if (neg? arg) \- \+)) (apply str (repeat (- w full-len) (:padchar params))) (if (and (not (:colon params)) add-sign) (if (neg? arg) \- \+)) full-repr)) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the '~[...~]' conditional construct in its ;; different flavors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ~[...~] without any modifiers chooses one of the clauses based on the param or ;; next argument ;; TODO check arg is positive int (defn- choice-conditional [params arg-navigator offsets] (let [arg (:selector params) [arg navigator] (if arg [arg arg-navigator] (next-arg arg-navigator)) clauses (:clauses params) clause (if (or (neg? arg) (>= arg (count clauses))) (first (:else params)) (nth clauses arg))] (if clause (execute-sub-format clause navigator (:base-args params)) navigator))) ;; ~:[...~] with the colon reads the next argument treating it as a truth value (defn- boolean-conditional [params arg-navigator offsets] (let [[arg navigator] (next-arg arg-navigator) clauses (:clauses params) clause (if arg (second clauses) (first clauses))] (if clause (execute-sub-format clause navigator (:base-args params)) navigator))) ;; ~@[...~] with the at sign executes the conditional if the next arg is not ;; nil/false without consuming the arg (defn- check-arg-conditional [params arg-navigator offsets] (let [[arg navigator] (next-arg arg-navigator) clauses (:clauses params) clause (if arg (first clauses))] (if arg (if clause (execute-sub-format clause arg-navigator (:base-args params)) arg-navigator) navigator))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the '~{...~}' iteration construct in its ;; different flavors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ~{...~} without any modifiers uses the next argument as an argument list that ;; is consumed by all the iterations (defn- iterate-sublist [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator]) [arg-list navigator] (next-arg navigator) args (init-navigator arg-list)] (loop [count 0 args args last-pos (int -1)] (if (and (not max-count) (= (:pos args) last-pos) (> count 1)) ;; TODO get the offset in here and call format exception (throw (js/Error "%{ construct not consuming any arguments: Infinite loop!"))) (if (or (and (empty? (:rest args)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause args (:base-args params))] (if (= :up-arrow (first iter-result)) navigator (recur (inc count) iter-result (:pos args)))))))) ;; ~:{...~} with the colon treats the next argument as a list of sublists. Each of the ;; sublists is used as the arglist for a single iteration. (defn- iterate-list-of-sublists [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator]) [arg-list navigator] (next-arg navigator)] (loop [count 0 arg-list arg-list] (if (or (and (empty? arg-list) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause (init-navigator (first arg-list)) (init-navigator (next arg-list)))] (if (= :colon-up-arrow (first iter-result)) navigator (recur (inc count) (next arg-list)))))))) ;; ~@{...~} with the at sign uses the main argument list as the arguments to the iterations ;; is consumed by all the iterations (defn- iterate-main-list [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator])] (loop [count 0 navigator navigator last-pos (int -1)] (if (and (not max-count) (= (:pos navigator) last-pos) (> count 1)) ;; TODO get the offset in here and call format exception (throw (js/Error "%@{ construct not consuming any arguments: Infinite loop!"))) (if (or (and (empty? (:rest navigator)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause navigator (:base-args params))] (if (= :up-arrow (first iter-result)) (second iter-result) (recur (inc count) iter-result (:pos navigator)))))))) ;; ~@:{...~} with both colon and at sign uses the main argument list as a set of sublists, one ;; of which is consumed with each iteration (defn- iterate-main-sublists [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator])] (loop [count 0 navigator navigator] (if (or (and (empty? (:rest navigator)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [[sublist navigator] (next-arg-or-nil navigator) iter-result (execute-sub-format clause (init-navigator sublist) navigator)] (if (= :colon-up-arrow (first iter-result)) navigator (recur (inc count) navigator))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; The '~< directive has two completely different meanings ;; in the '~<...~>' form it does justification, but with ;; ~<...~:>' it represents the logical block operation of the ;; pretty printer. ;; ;; Unfortunately, the current architecture decides what function ;; to call at form parsing time before the sub-clauses have been ;; folded, so it is left to run-time to make the decision. ;; ;; TODO: make it possible to make these decisions at compile-time. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare ^{:arglists '([params navigator offsets])} format-logical-block) (declare ^{:arglists '([params navigator offsets])} justify-clauses) (defn- logical-block-or-justify [params navigator offsets] (if (:colon (:right-params params)) (format-logical-block params navigator offsets) (justify-clauses params navigator offsets))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the '~<...~>' justification directive ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- render-clauses [clauses navigator base-navigator] (loop [clauses clauses acc [] navigator navigator] (if (empty? clauses) [acc navigator] (let [clause (first clauses) [iter-result result-str] (let [sb (StringBuffer.)] (binding [*out* (StringBufferWriter. sb)] [(execute-sub-format clause navigator base-navigator) (str sb)]))] (if (= :up-arrow (first iter-result)) [acc (second iter-result)] (recur (next clauses) (conj acc result-str) iter-result)))))) ;; TODO support for ~:; constructions (defn- justify-clauses [params navigator offsets] (let [[[eol-str] new-navigator] (when-let [else (:else params)] (render-clauses else navigator (:base-args params))) navigator (or new-navigator navigator) [else-params new-navigator] (when-let [p (:else-params params)] (realize-parameter-list p navigator)) navigator (or new-navigator navigator) min-remaining (or (first (:min-remaining else-params)) 0) max-columns (or (first (:max-columns else-params)) (get-max-column *out*)) clauses (:clauses params) [strs navigator] (render-clauses clauses navigator (:base-args params)) slots (max 1 (+ (dec (count strs)) (if (:colon params) 1 0) (if (:at params) 1 0))) chars (reduce + (map count strs)) mincol (:mincol params) minpad (:minpad params) colinc (:colinc params) minout (+ chars (* slots minpad)) result-columns (if (<= minout mincol) mincol (+ mincol (* colinc (+ 1 (quot (- minout mincol 1) colinc))))) total-pad (- result-columns chars) pad (max minpad (quot total-pad slots)) extra-pad (- total-pad (* pad slots)) pad-str (apply str (repeat pad (:padchar params)))] (if (and eol-str (> (+ (get-column (:base @@*out*)) min-remaining result-columns) max-columns)) (print eol-str)) (loop [slots slots extra-pad extra-pad strs strs pad-only (or (:colon params) (and (= (count strs) 1) (not (:at params))))] (if (seq strs) (do (print (str (if (not pad-only) (first strs)) (if (or pad-only (next strs) (:at params)) pad-str) (if (pos? extra-pad) (:padchar params)))) (recur (dec slots) (dec extra-pad) (if pad-only strs (next strs)) false)))) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Support for case modification with ~(...~). ;;; We do this by wrapping the underlying writer with ;;; a special writer to do the appropriate modification. This ;;; allows us to support arbitrary-sized output and sources ;;; that may block. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- downcase-writer "Returns a proxy that wraps writer, converting all characters to lower case" [writer] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity, not sure of importance #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (string/lower-case s))) js/Number (let [c x] ;;TODO need to enforce integers only? (-write writer (string/lower-case (char c)))))))) (defn- upcase-writer "Returns a proxy that wraps writer, converting all characters to upper case" [writer] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity, not sure of importance #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (string/upper-case s))) js/Number (let [c x] ;;TODO need to enforce integers only? (-write writer (string/upper-case (char c)))))))) (defn- capitalize-string "Capitalizes the words in a string. If first? is false, don't capitalize the first character of the string even if it's a letter." [s first?] (let [f (first s) s (if (and first? f (gstring/isUnicodeChar f)) (str (string/upper-case f) (subs s 1)) s)] (apply str (first (consume (fn [s] (if (empty? s) [nil nil] (let [m (.exec (js/RegExp "\\W\\w" "g") s) offset (and m (inc (.-index m)))] (if offset [(str (subs s 0 offset) (string/upper-case (nth s offset))) (subs s (inc offset))] [s nil])))) s))))) (defn- capitalize-word-writer "Returns a proxy that wraps writer, capitalizing all words" [writer] (let [last-was-whitespace? (atom true)] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (capitalize-string (.toLowerCase s) @last-was-whitespace?)) (when (pos? (.-length s)) (reset! last-was-whitespace? (gstring/isEmptyOrWhitespace (nth s (dec (count s))))))) js/Number (let [c (char x)] (let [mod-c (if @last-was-whitespace? (string/upper-case c) c)] (-write writer mod-c) (reset! last-was-whitespace? (gstring/isEmptyOrWhitespace c))))))))) (defn- init-cap-writer "Returns a proxy that wraps writer, capitalizing the first word" [writer] (let [capped (atom false)] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s (string/lower-case x)] (if (not @capped) (let [m (.exec (js/RegExp "\\S" "g") s) offset (and m (.-index m))] (if offset (do (-write writer (str (subs s 0 offset) (string/upper-case (nth s offset)) (string/lower-case (subs s (inc offset))))) (reset! capped true)) (-write writer s))) (-write writer (string/lower-case s)))) js/Number (let [c (char x)] (if (and (not @capped) (gstring/isUnicodeChar c)) (do (reset! capped true) (-write writer (string/upper-case c))) (-write writer (string/lower-case c))))))))) (defn- modify-case [make-writer params navigator offsets] (let [clause (first (:clauses params))] (binding [*out* (make-writer *out*)] (execute-sub-format clause navigator (:base-args params))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; If necessary, wrap the writer in a PrettyWriter object ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO update this doc string to show correct way to print (defn get-pretty-writer "Returns the IWriter passed in wrapped in a pretty writer proxy, unless it's already a pretty writer. Generally, it is unnecessary to call this function, since pprint, write, and cl-format all call it if they need to. However if you want the state to be preserved across calls, you will want to wrap them with this. For example, when you want to generate column-aware output with multiple calls to cl-format, do it like in this example: (defn print-table [aseq column-width] (binding [*out* (get-pretty-writer *out*)] (doseq [row aseq] (doseq [col row] (cl-format true \"~4D~7,vT\" col column-width)) (prn)))) Now when you run: user> (print-table (map #(vector % (* % %) (* % % %)) (range 1 11)) 8) It prints a table of squares and cubes for the numbers from 1 to 10: 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000" [writer] (if (pretty-writer? writer) writer (pretty-writer writer *print-right-margin* *print-miser-width*))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Support for column-aware operations ~&, ~T ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fresh-line "Make a newline if *out* is not already at the beginning of the line. If *out* is not a pretty writer (which keeps track of columns), this function always outputs a newline." [] (if (satisfies? IDeref *out*) (if (not (= 0 (get-column (:base @@*out*)))) (prn)) (prn))) (defn- absolute-tabulation [params navigator offsets] (let [colnum (:colnum params) colinc (:colinc params) current (get-column (:base @@*out*)) space-count (cond (< current colnum) (- colnum current) (= colinc 0) 0 :else (- colinc (rem (- current colnum) colinc)))] (print (apply str (repeat space-count \space)))) navigator) (defn- relative-tabulation [params navigator offsets] (let [colrel (:colnum params) colinc (:colinc params) start-col (+ colrel (get-column (:base @@*out*))) offset (if (pos? colinc) (rem start-col colinc) 0) space-count (+ colrel (if (= 0 offset) 0 (- colinc offset)))] (print (apply str (repeat space-count \space)))) navigator) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Support for accessing the pretty printer from a format ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO: support ~@; per-line-prefix separator ;; TODO: get the whole format wrapped so we can start the lb at any column (defn- format-logical-block [params navigator offsets] (let [clauses (:clauses params) clause-count (count clauses) prefix (cond (> clause-count 1) (:string (:params (first (first clauses)))) (:colon params) "(") body (nth clauses (if (> clause-count 1) 1 0)) suffix (cond (> clause-count 2) (:string (:params (first (nth clauses 2)))) (:colon params) ")") [arg navigator] (next-arg navigator)] (pprint-logical-block :prefix prefix :suffix suffix (execute-sub-format body (init-navigator arg) (:base-args params))) navigator)) (defn- set-indent [params navigator offsets] (let [relative-to (if (:colon params) :current :block)] (pprint-indent relative-to (:n params)) navigator)) ;;; TODO: support ~:T section options for ~T (defn- conditional-newline [params navigator offsets] (let [kind (if (:colon params) (if (:at params) :mandatory :fill) (if (:at params) :miser :linear))] (pprint-newline kind) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The table of directives we support, each with its params, ;;; properties, and the compilation function ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defdirectives (\A [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} #(format-ascii print-str %1 %2 %3)) (\S [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} #(format-ascii pr-str %1 %2 %3)) (\D [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 10 %1 %2 %3)) (\B [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 2 %1 %2 %3)) (\O [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 8 %1 %2 %3)) (\X [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 16 %1 %2 %3)) (\R [:base [nil js/Number] :mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} (do (cond ; ~R is overloaded with bizareness (first (:base params)) #(format-integer (:base %1) %1 %2 %3) (and (:at params) (:colon params)) #(format-old-roman %1 %2 %3) (:at params) #(format-new-roman %1 %2 %3) (:colon params) #(format-ordinal-english %1 %2 %3) true #(format-cardinal-english %1 %2 %3)))) (\P [] #{:at :colon :both} {} (fn [params navigator offsets] (let [navigator (if (:colon params) (relative-reposition navigator -1) navigator) strs (if (:at params) ["y" "ies"] ["" "s"]) [arg navigator] (next-arg navigator)] (print (if (= arg 1) (first strs) (second strs))) navigator))) (\C [:char-format [nil js/String]] #{:at :colon :both} {} (cond (:colon params) pretty-character (:at params) readable-character :else plain-character)) (\F [:w [nil js/Number] :d [nil js/Number] :k [0 js/Number] :overflowchar [nil js/String] :padchar [\space js/String]] #{:at} {} fixed-float) (\E [:w [nil js/Number] :d [nil js/Number] :e [nil js/Number] :k [1 js/Number] :overflowchar [nil js/String] :padchar [\space js/String] :exponentchar [nil js/String]] #{:at} {} exponential-float) (\G [:w [nil js/Number] :d [nil js/Number] :e [nil js/Number] :k [1 js/Number] :overflowchar [nil js/String] :padchar [\space js/String] :exponentchar [nil js/String]] #{:at} {} general-float) (\$ [:d [2 js/Number] :n [1 js/Number] :w [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} dollar-float) (\% [:count [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (dotimes [i (:count params)] (prn)) arg-navigator)) (\& [:count [1 js/Number]] #{:pretty} {} (fn [params arg-navigator offsets] (let [cnt (:count params)] (if (pos? cnt) (fresh-line)) (dotimes [i (dec cnt)] (prn))) arg-navigator)) (\| [:count [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (dotimes [i (:count params)] (print \formfeed)) arg-navigator)) (\~ [:n [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (let [n (:n params)] (print (apply str (repeat n \~))) arg-navigator))) (\newline ;; Whitespace supression is handled in the compilation loop [] #{:colon :at} {} (fn [params arg-navigator offsets] (if (:at params) (prn)) arg-navigator)) (\T [:colnum [1 js/Number] :colinc [1 js/Number]] #{:at :pretty} {} (if (:at params) #(relative-tabulation %1 %2 %3) #(absolute-tabulation %1 %2 %3))) (\* [:n [1 js/Number]] #{:colon :at} {} (fn [params navigator offsets] (let [n (:n params)] (if (:at params) (absolute-reposition navigator n) (relative-reposition navigator (if (:colon params) (- n) n)))))) (\? [] #{:at} {} (if (:at params) (fn [params navigator offsets] ; args from main arg list (let [[subformat navigator] (get-format-arg navigator)] (execute-sub-format subformat navigator (:base-args params)))) (fn [params navigator offsets] ; args from sub-list (let [[subformat navigator] (get-format-arg navigator) [subargs navigator] (next-arg navigator) sub-navigator (init-navigator subargs)] (execute-sub-format subformat sub-navigator (:base-args params)) navigator)))) (\( [] #{:colon :at :both} {:right \), :allows-separator nil, :else nil} (let [mod-case-writer (cond (and (:at params) (:colon params)) upcase-writer (:colon params) capitalize-word-writer (:at params) init-cap-writer :else downcase-writer)] #(modify-case mod-case-writer %1 %2 %3))) (\) [] #{} {} nil) (\[ [:selector [nil js/Number]] #{:colon :at} {:right \], :allows-separator true, :else :last} (cond (:colon params) boolean-conditional (:at params) check-arg-conditional true choice-conditional)) (\; [:min-remaining [nil js/Number] :max-columns [nil js/Number]] #{:colon} {:separator true} nil) (\] [] #{} {} nil) (\{ [:max-iterations [nil js/Number]] #{:colon :at :both} {:right \}, :allows-separator false} (cond (and (:at params) (:colon params)) iterate-main-sublists (:colon params) iterate-list-of-sublists (:at params) iterate-main-list true iterate-sublist)) (\} [] #{:colon} {} nil) (\< [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:colon :at :both :pretty} {:right \>, :allows-separator true, :else :first} logical-block-or-justify) (\> [] #{:colon} {} nil) ;; TODO: detect errors in cases where colon not allowed (\^ [:arg1 [nil js/Number] :arg2 [nil js/Number] :arg3 [nil js/Number]] #{:colon} {} (fn [params navigator offsets] (let [arg1 (:arg1 params) arg2 (:arg2 params) arg3 (:arg3 params) exit (if (:colon params) :colon-up-arrow :up-arrow)] (cond (and arg1 arg2 arg3) (if (<= arg1 arg2 arg3) [exit navigator] navigator) (and arg1 arg2) (if (= arg1 arg2) [exit navigator] navigator) arg1 (if (= arg1 0) [exit navigator] navigator) true ; TODO: handle looking up the arglist stack for info (if (if (:colon params) (empty? (:rest (:base-args params))) (empty? (:rest navigator))) [exit navigator] navigator))))) (\W [] #{:at :colon :both :pretty} {} (if (or (:at params) (:colon params)) (let [bindings (concat (if (:at params) [:level nil :length nil] []) (if (:colon params) [:pretty true] []))] (fn [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (apply write arg bindings) [:up-arrow navigator] navigator)))) (fn [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (write-out arg) [:up-arrow navigator] navigator))))) (\_ [] #{:at :colon :both} {} conditional-newline) (\I [:n [0 js/Number]] #{:colon} {} set-indent) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Code to manage the parameters and flags associated with each ;; directive in the format string. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} param-pattern #"^([vV]|#|('.)|([+-]?\d+)|(?=,))") (def ^{:private true} special-params #{:parameter-from-args :remaining-arg-count}) (defn- extract-param [[s offset saw-comma]] (let [m (js/RegExp. (.-source param-pattern) "g") param (.exec m s)] (if param (let [token-str (first param) remainder (subs s (.-lastIndex m)) new-offset (+ offset (.-lastIndex m))] (if (not (= \, (nth remainder 0))) [[token-str offset] [remainder new-offset false]] [[token-str offset] [(subs remainder 1) (inc new-offset) true]])) (if saw-comma (format-error "Badly formed parameters in format directive" offset) [nil [s offset]])))) (defn- extract-params [s offset] (consume extract-param [s offset false])) (defn- translate-param "Translate the string representation of a param to the internalized representation" [[p offset]] [(cond (= (.-length p) 0) nil (and (= (.-length p) 1) (contains? #{\v \V} (nth p 0))) :parameter-from-args (and (= (.-length p) 1) (= \# (nth p 0))) :remaining-arg-count (and (= (.-length p) 2) (= \' (nth p 0))) (nth p 1) true (js/parseInt p 10)) offset]) (def ^{:private true} flag-defs {\: :colon, \@ :at}) (defn- extract-flags [s offset] (consume (fn [[s offset flags]] (if (empty? s) [nil [s offset flags]] (let [flag (get flag-defs (first s))] (if flag (if (contains? flags flag) (format-error (str "Flag \"" (first s) "\" appears more than once in a directive") offset) [true [(subs s 1) (inc offset) (assoc flags flag [true offset])]]) [nil [s offset flags]])))) [s offset {}])) (defn- check-flags [def flags] (let [allowed (:flags def)] (if (and (not (:at allowed)) (:at flags)) (format-error (str "\"@\" is an illegal flag for format directive \"" (:directive def) "\"") (nth (:at flags) 1))) (if (and (not (:colon allowed)) (:colon flags)) (format-error (str "\":\" is an illegal flag for format directive \"" (:directive def) "\"") (nth (:colon flags) 1))) (if (and (not (:both allowed)) (:at flags) (:colon flags)) (format-error (str "Cannot combine \"@\" and \":\" flags for format directive \"" (:directive def) "\"") (min (nth (:colon flags) 1) (nth (:at flags) 1)))))) (defn- map-params "Takes a directive definition and the list of actual parameters and a map of flags and returns a map of the parameters and flags with defaults filled in. We check to make sure that there are the right types and number of parameters as well." [def params flags offset] (check-flags def flags) (if (> (count params) (count (:params def))) (format-error (cl-format nil "Too many parameters for directive \"~C\": ~D~:* ~[were~;was~:;were~] specified but only ~D~:* ~[are~;is~:;are~] allowed" (:directive def) (count params) (count (:params def))) (second (first params)))) (doall (map #(let [val (first %1)] (if (not (or (nil? val) (contains? special-params val) (= (second (second %2)) (type val)))) (format-error (str "Parameter " (name (first %2)) " has bad type in directive \"" (:directive def) "\": " (type val)) (second %1))) ) params (:params def))) (merge ; create the result map (into (array-map) ; start with the default values, make sure the order is right (reverse (for [[name [default]] (:params def)] [name [default offset]]))) (reduce #(apply assoc %1 %2) {} (filter #(first (nth % 1)) (zipmap (keys (:params def)) params))) ; add the specified parameters, filtering out nils flags)); and finally add the flags (defn- compile-directive [s offset] (let [[raw-params [rest offset]] (extract-params s offset) [_ [rest offset flags]] (extract-flags rest offset) directive (first rest) def (get directive-table (string/upper-case directive)) params (if def (map-params def (map translate-param raw-params) flags offset))] (if (not directive) (format-error "Format string ended in the middle of a directive" offset)) (if (not def) (format-error (str "Directive \"" directive "\" is undefined") offset)) [(compiled-directive. ((:generator-fn def) params offset) def params offset) (let [remainder (subs rest 1) offset (inc offset) trim? (and (= \newline (:directive def)) (not (:colon params))) trim-count (if trim? (prefix-count remainder [\space \tab]) 0) remainder (subs remainder trim-count) offset (+ offset trim-count)] [remainder offset])])) (defn- compile-raw-string [s offset] (compiled-directive. (fn [_ a _] (print s) a) nil {:string s} offset)) (defn- right-bracket [this] (:right (:bracket-info (:def this)))) (defn- separator? [this] (:separator (:bracket-info (:def this)))) (defn- else-separator? [this] (and (:separator (:bracket-info (:def this))) (:colon (:params this)))) (declare ^{:arglists '([bracket-info offset remainder])} collect-clauses) (defn- process-bracket [this remainder] (let [[subex remainder] (collect-clauses (:bracket-info (:def this)) (:offset this) remainder)] [(compiled-directive. (:func this) (:def this) (merge (:params this) (tuple-map subex (:offset this))) (:offset this)) remainder])) (defn- process-clause [bracket-info offset remainder] (consume (fn [remainder] (if (empty? remainder) (format-error "No closing bracket found." offset) (let [this (first remainder) remainder (next remainder)] (cond (right-bracket this) (process-bracket this remainder) (= (:right bracket-info) (:directive (:def this))) [ nil [:right-bracket (:params this) nil remainder]] (else-separator? this) [nil [:else nil (:params this) remainder]] (separator? this) [nil [:separator nil nil remainder]] ;; TODO: check to make sure that there are no params on ~; true [this remainder])))) remainder)) (defn- collect-clauses [bracket-info offset remainder] (second (consume (fn [[clause-map saw-else remainder]] (let [[clause [type right-params else-params remainder]] (process-clause bracket-info offset remainder)] (cond (= type :right-bracket) [nil [(merge-with concat clause-map {(if saw-else :else :clauses) [clause] :right-params right-params}) remainder]] (= type :else) (cond (:else clause-map) (format-error "Two else clauses (\"~:;\") inside bracket construction." offset) (not (:else bracket-info)) (format-error "An else clause (\"~:;\") is in a bracket type that doesn't support it." offset) (and (= :first (:else bracket-info)) (seq (:clauses clause-map))) (format-error "The else clause (\"~:;\") is only allowed in the first position for this directive." offset) true ; if the ~:; is in the last position, the else clause ; is next, this was a regular clause (if (= :first (:else bracket-info)) [true [(merge-with concat clause-map {:else [clause] :else-params else-params}) false remainder]] [true [(merge-with concat clause-map {:clauses [clause]}) true remainder]])) (= type :separator) (cond saw-else (format-error "A plain clause (with \"~;\") follows an else clause (\"~:;\") inside bracket construction." offset) (not (:allows-separator bracket-info)) (format-error "A separator (\"~;\") is in a bracket type that doesn't support it." offset) true [true [(merge-with concat clause-map {:clauses [clause]}) false remainder]])))) [{:clauses []} false remainder]))) (defn- process-nesting "Take a linearly compiled format and process the bracket directives to give it the appropriate tree structure" [format] (first (consume (fn [remainder] (let [this (first remainder) remainder (next remainder) bracket (:bracket-info (:def this))] (if (:right bracket) (process-bracket this remainder) [this remainder]))) format))) (defn- compile-format "Compiles format-str into a compiled format which can be used as an argument to cl-format just like a plain format string. Use this function for improved performance when you're using the same format string repeatedly" [format-str] (binding [*format-str* format-str] (process-nesting (first (consume (fn [[s offset]] (if (empty? s) [nil s] (let [tilde (.indexOf s \~)] (cond (neg? tilde) [(compile-raw-string s offset) ["" (+ offset (.-length s))]] (zero? tilde) (compile-directive (subs s 1) (inc offset)) true [(compile-raw-string (subs s 0 tilde) offset) [(subs s tilde) (+ tilde offset)]])))) [format-str 0]))))) (defn- needs-pretty "determine whether a given compiled format has any directives that depend on the column number or pretty printing" [format] (loop [format format] (if (empty? format) false (if (or (:pretty (:flags (:def (first format)))) (some needs-pretty (first (:clauses (:params (first format))))) (some needs-pretty (first (:else (:params (first format)))))) true (recur (next format)))))) ;;NB We depart from the original api. In clj, if execute-format is called multiple times with the same stream or ;; called on *out*, the results are different than if the same calls are made with different streams or printing ;; to a string. The reason is that mutating the underlying stream changes the result by changing spacing. ;; ;; clj: ;; * stream => "1 2 3" ;; * true (prints to *out*) => "1 2 3" ;; * nil (prints to string) => "1 2 3" ;; cljs: ;; * stream => "1 2 3" ;; * true (prints via *print-fn*) => "1 2 3" ;; * nil (prints to string) => "1 2 3" (defn- execute-format "Executes the format with the arguments." {:skip-wiki true} ([stream format args] (let [sb (StringBuffer.) real-stream (if (or (not stream) (true? stream)) (StringBufferWriter. sb) stream) wrapped-stream (if (and (needs-pretty format) (not (pretty-writer? real-stream))) (get-pretty-writer real-stream) real-stream)] (binding [*out* wrapped-stream] (try (execute-format format args) (finally (if-not (identical? real-stream wrapped-stream) (-flush wrapped-stream)))) (cond (not stream) (str sb) (true? stream) (string-print (str sb)) :else nil)))) ([format args] (map-passing-context (fn [element context] (if (abort? context) [nil context] (let [[params args] (realize-parameter-list (:params element) context) [params offsets] (unzip-map params) params (assoc params :base-args args)] [nil (apply (:func element) [params args offsets])]))) args format) nil)) ;;; This is a bad idea, but it prevents us from leaking private symbols ;;; This should all be replaced by really compiled formats anyway. (def ^{:private true} cached-compile (memoize compile-format)) ;;====================================================================== ;; dispatch.clj ;;====================================================================== (defn- use-method "Installs a function as a new method of multimethod associated with dispatch-value. " [multifn dispatch-val func] (-add-method multifn dispatch-val func)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implementations of specific dispatch table entries ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Handle forms that can be "back-translated" to reader macros ;;; Not all reader macros can be dealt with this way or at all. ;;; Macros that we can't deal with at all are: ;;; ; - The comment character is absorbed by the reader and never is part of the form ;;; ` - Is fully processed at read time into a lisp expression (which will contain concats ;;; and regular quotes). ;;; ~@ - Also fully eaten by the processing of ` and can't be used outside. ;;; , - is whitespace and is lost (like all other whitespace). Formats can generate commas ;;; where they deem them useful to help readability. ;;; ^ - Adding metadata completely disappears at read time and the data appears to be ;;; completely lost. ;;; ;;; Most other syntax stuff is dealt with directly by the formats (like (), [], {}, and #{}) ;;; or directly by printing the objects using Clojure's built-in print functions (like ;;; :keyword, \char, or ""). The notable exception is #() which is special-cased. (def ^{:private true} reader-macros {'quote "'" 'var "#'" 'clojure.core/deref "@", 'clojure.core/unquote "~" 'cljs.core/deref "@", 'cljs.core/unquote "~"}) (defn- pprint-reader-macro [alis] (let [macro-char (reader-macros (first alis))] (when (and macro-char (= 2 (count alis))) (-write *out* macro-char) (write-out (second alis)) true))) ;;====================================================================== ;; Dispatch for the basic data types when interpreted ;; as data (as opposed to code). ;;====================================================================== ;;; TODO: inline these formatter statements into funcs so that we ;;; are a little easier on the stack. (Or, do "real" compilation, a ;;; la Common Lisp) ;;; (def pprint-simple-list (formatter-out "~:<~@{~w~^ ~_~}~:>")) (defn- pprint-simple-list [alis] (pprint-logical-block :prefix "(" :suffix ")" (print-length-loop [alis (seq alis)] (when alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (recur (next alis))))))) (defn- pprint-list [alis] (if-not (pprint-reader-macro alis) (pprint-simple-list alis))) ;;; (def pprint-vector (formatter-out "~<[~;~@{~w~^ ~_~}~;]~:>")) (defn- pprint-vector [avec] (pprint-logical-block :prefix "[" :suffix "]" (print-length-loop [aseq (seq avec)] (when aseq (write-out (first aseq)) (when (next aseq) (-write *out* " ") (pprint-newline :linear) (recur (next aseq))))))) (def ^{:private true} pprint-array (formatter-out "~<[~;~@{~w~^, ~:_~}~;]~:>")) ;;; (def pprint-map (formatter-out "~<{~;~@{~<~w~^ ~_~w~:>~^, ~_~}~;}~:>")) (defn- pprint-map [amap] (let [[ns lift-map] (when (not (record? amap)) (#'cljs.core/lift-ns amap)) amap (or lift-map amap) prefix (if ns (str "#:" ns "{") "{")] (pprint-logical-block :prefix prefix :suffix "}" (print-length-loop [aseq (seq amap)] (when aseq ;;compiler gets confused with nested macro if it isn't namespaced ;;it tries to use clojure.pprint/pprint-logical-block for some reason (m/pprint-logical-block (write-out (ffirst aseq)) (-write *out* " ") (pprint-newline :linear) (set! *current-length* 0) ;always print both parts of the [k v] pair (write-out (fnext (first aseq)))) (when (next aseq) (-write *out* ", ") (pprint-newline :linear) (recur (next aseq)))))))) (defn- pprint-simple-default [obj] ;;TODO: Update to handle arrays (?) and suppressing namespaces (-write *out* (pr-str obj))) (def pprint-set (formatter-out "~<#{~;~@{~w~^ ~:_~}~;}~:>")) (def ^{:private true} type-map {"core$future_call" "Future", "core$promise" "Promise"}) (defn- map-ref-type "Map ugly type names to something simpler" [name] (or (when-let [match (re-find #"^[^$]+\$[^$]+" name)] (type-map match)) name)) (defn- pprint-ideref [o] (let [prefix (str "#<" (map-ref-type (.-name (type o))) "@" (goog/getUid o) ": ")] (pprint-logical-block :prefix prefix :suffix ">" (pprint-indent :block (-> (count prefix) (- 2) -)) (pprint-newline :linear) (write-out (if (and (satisfies? IPending o) (not (-realized? o))) :not-delivered @o))))) (def ^{:private true} pprint-pqueue (formatter-out "~<<-(~;~@{~w~^ ~_~}~;)-<~:>")) (defn- type-dispatcher [obj] (cond (instance? PersistentQueue obj) :queue (satisfies? IDeref obj) :deref (symbol? obj) :symbol (seq? obj) :list (map? obj) :map (vector? obj) :vector (set? obj) :set (nil? obj) nil :default :default)) (defmulti simple-dispatch "The pretty print dispatch function for simple data structure format." type-dispatcher) (use-method simple-dispatch :list pprint-list) (use-method simple-dispatch :vector pprint-vector) (use-method simple-dispatch :map pprint-map) (use-method simple-dispatch :set pprint-set) (use-method simple-dispatch nil #(-write *out* (pr-str nil))) (use-method simple-dispatch :default pprint-simple-default) (set-pprint-dispatch simple-dispatch) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Dispatch for the code table ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare ^{:arglists '([alis])} pprint-simple-code-list) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format the namespace ("ns") macro. This is quite complicated because of all the ;;; different forms supported and because programmers can choose lists or vectors ;;; in various places. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- brackets "Figure out which kind of brackets to use" [form] (if (vector? form) ["[" "]"] ["(" ")"])) (defn- pprint-ns-reference "Pretty print a single reference (import, use, etc.) from a namespace decl" [reference] (if (sequential? reference) (let [[start end] (brackets reference) [keyw & args] reference] (pprint-logical-block :prefix start :suffix end ((formatter-out "~w~:i") keyw) (loop [args args] (when (seq args) ((formatter-out " ")) (let [arg (first args)] (if (sequential? arg) (let [[start end] (brackets arg)] (pprint-logical-block :prefix start :suffix end (if (and (= (count arg) 3) (keyword? (second arg))) (let [[ns kw lis] arg] ((formatter-out "~w ~w ") ns kw) (if (sequential? lis) ((formatter-out (if (vector? lis) "~<[~;~@{~w~^ ~:_~}~;]~:>" "~<(~;~@{~w~^ ~:_~}~;)~:>")) lis) (write-out lis))) (apply (formatter-out "~w ~:i~@{~w~^ ~:_~}") arg))) (when (next args) ((formatter-out "~_")))) (do (write-out arg) (when (next args) ((formatter-out "~:_")))))) (recur (next args)))))) (write-out reference))) (defn- pprint-ns "The pretty print dispatch chunk for the ns macro" [alis] (if (next alis) (let [[ns-sym ns-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map references] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block :prefix "(" :suffix ")" ((formatter-out "~w ~1I~@_~w") ns-sym ns-name) (when (or doc-str attr-map (seq references)) ((formatter-out "~@:_"))) (when doc-str (cl-format true "\"~a\"~:[~;~:@_~]" doc-str (or attr-map (seq references)))) (when attr-map ((formatter-out "~w~:[~;~:@_~]") attr-map (seq references))) (loop [references references] (pprint-ns-reference (first references)) (when-let [references (next references)] (pprint-newline :linear) (recur references))))) (write-out alis))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format something that looks like a simple def (sans metadata, since the reader ;;; won't give it to us now). ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} pprint-hold-first (formatter-out "~:<~w~^ ~@_~w~^ ~_~@{~w~^ ~_~}~:>")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format something that looks like a defn or defmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format the params and body of a defn with a single arity (defn- single-defn [alis has-doc-str?] (if (seq alis) (do (if has-doc-str? ((formatter-out " ~_")) ((formatter-out " ~@_"))) ((formatter-out "~{~w~^ ~_~}") alis)))) ;;; Format the param and body sublists of a defn with multiple arities (defn- multi-defn [alis has-doc-str?] (if (seq alis) ((formatter-out " ~_~{~w~^ ~_~}") alis))) ;;; TODO: figure out how to support capturing metadata in defns (we might need a ;;; special reader) (defn- pprint-defn [alis] (if (next alis) (let [[defn-sym defn-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map stuff] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block :prefix "(" :suffix ")" ((formatter-out "~w ~1I~@_~w") defn-sym defn-name) (if doc-str ((formatter-out " ~_~w") doc-str)) (if attr-map ((formatter-out " ~_~w") attr-map)) ;; Note: the multi-defn case will work OK for malformed defns too (cond (vector? (first stuff)) (single-defn stuff (or doc-str attr-map)) :else (multi-defn stuff (or doc-str attr-map))))) (pprint-simple-code-list alis))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format something with a binding form ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- pprint-binding-form [binding-vec] (pprint-logical-block :prefix "[" :suffix "]" (print-length-loop [binding binding-vec] (when (seq binding) (pprint-logical-block binding (write-out (first binding)) (when (next binding) (-write *out* " ") (pprint-newline :miser) (write-out (second binding)))) (when (next (rest binding)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest binding)))))))) (defn- pprint-let [alis] (let [base-sym (first alis)] (pprint-logical-block :prefix "(" :suffix ")" (if (and (next alis) (vector? (second alis))) (do ((formatter-out "~w ~1I~@_") base-sym) (pprint-binding-form (second alis)) ((formatter-out " ~_~{~w~^ ~_~}") (next (rest alis)))) (pprint-simple-code-list alis))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format something that looks like "if" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} pprint-if (formatter-out "~:<~1I~w~^ ~@_~w~@{ ~_~w~}~:>")) (defn- pprint-cond [alis] (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (print-length-loop [alis (next alis)] (when alis (pprint-logical-block alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :miser) (write-out (second alis)))) (when (next (rest alis)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest alis))))))))) (defn- pprint-condp [alis] (if (> (count alis) 3) (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (apply (formatter-out "~w ~@_~w ~@_~w ~_") alis) (print-length-loop [alis (seq (drop 3 alis))] (when alis (pprint-logical-block alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :miser) (write-out (second alis)))) (when (next (rest alis)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest alis))))))) (pprint-simple-code-list alis))) ;;; The map of symbols that are defined in an enclosing #() anonymous function (def ^:dynamic ^{:private true} *symbol-map* {}) (defn- pprint-anon-func [alis] (let [args (second alis) nlis (first (rest (rest alis)))] (if (vector? args) (binding [*symbol-map* (if (= 1 (count args)) {(first args) "%"} (into {} (map #(vector %1 (str \% %2)) args (range 1 (inc (count args))))))] ((formatter-out "~<#(~;~@{~w~^ ~_~}~;)~:>") nlis)) (pprint-simple-code-list alis)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The master definitions for formatting lists in code (that is, (fn args...) or ;;; special forms). ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; This is the equivalent of (formatter-out "~:<~1I~@{~w~^ ~_~}~:>"), but is ;;; easier on the stack. (defn- pprint-simple-code-list [alis] (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (print-length-loop [alis (seq alis)] (when alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (recur (next alis))))))) ;;; Take a map with symbols as keys and add versions with no namespace. ;;; That is, if ns/sym->val is in the map, add sym->val to the result. (defn- two-forms [amap] (into {} (mapcat identity (for [x amap] [x [(symbol (name (first x))) (second x)]])))) (defn- add-core-ns [amap] (let [core "clojure.core"] (into {} (map #(let [[s f] %] (if (not (or (namespace s) (special-symbol? s))) [(symbol core (name s)) f] %)) amap)))) (def ^:dynamic ^{:private true} *code-table* (two-forms (add-core-ns {'def pprint-hold-first, 'defonce pprint-hold-first, 'defn pprint-defn, 'defn- pprint-defn, 'defmacro pprint-defn, 'fn pprint-defn, 'let pprint-let, 'loop pprint-let, 'binding pprint-let, 'with-local-vars pprint-let, 'with-open pprint-let, 'when-let pprint-let, 'if-let pprint-let, 'doseq pprint-let, 'dotimes pprint-let, 'when-first pprint-let, 'if pprint-if, 'if-not pprint-if, 'when pprint-if, 'when-not pprint-if, 'cond pprint-cond, 'condp pprint-condp, 'fn* pprint-anon-func, '. pprint-hold-first, '.. pprint-hold-first, '-> pprint-hold-first, 'locking pprint-hold-first, 'struct pprint-hold-first, 'struct-map pprint-hold-first, 'ns pprint-ns }))) (defn- pprint-code-list [alis] (if-not (pprint-reader-macro alis) (if-let [special-form (*code-table* (first alis))] (special-form alis) (pprint-simple-code-list alis)))) (defn- pprint-code-symbol [sym] (if-let [arg-num (sym *symbol-map*)] (print arg-num) (if *print-suppress-namespaces* (print (name sym)) (pr sym)))) (defmulti code-dispatch "The pretty print dispatch function for pretty printing Clojure code." {:added "1.2" :arglists '[[object]]} type-dispatcher) (use-method code-dispatch :list pprint-code-list) (use-method code-dispatch :symbol pprint-code-symbol) ;; The following are all exact copies of simple-dispatch (use-method code-dispatch :vector pprint-vector) (use-method code-dispatch :map pprint-map) (use-method code-dispatch :set pprint-set) (use-method code-dispatch :queue pprint-pqueue) (use-method code-dispatch :deref pprint-ideref) (use-method code-dispatch nil pr) (use-method code-dispatch :default pprint-simple-default) (set-pprint-dispatch simple-dispatch) ;;; For testing (comment (with-pprint-dispatch code-dispatch (pprint '(defn cl-format "An implementation of a Common Lisp compatible format function" [stream format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format stream compiled-format navigator))))) (with-pprint-dispatch code-dispatch (pprint '(defn cl-format [stream format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format stream compiled-format navigator))))) (with-pprint-dispatch code-dispatch (pprint '(defn- -write ([this x] (condp = (class x) String (let [s0 (write-initial-lines this x) s (.replaceFirst s0 "\\s+$" "") white-space (.substring s0 (count s)) mode (getf :mode)] (if (= mode :writing) (dosync (write-white-space this) (.col_write this s) (setf :trailing-white-space white-space)) (add-to-buffer this (make-buffer-blob s white-space)))) Integer (let [c ^Character x] (if (= (getf :mode) :writing) (do (write-white-space this) (.col_write this x)) (if (= c (int \newline)) (write-initial-lines this "\n") (add-to-buffer this (make-buffer-blob (str (char c)) nil)))))))))) (with-pprint-dispatch code-dispatch (pprint '(defn pprint-defn [writer alis] (if (next alis) (let [[defn-sym defn-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map stuff] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block writer :prefix "(" :suffix ")" (cl-format true "~w ~1I~@_~w" defn-sym defn-name) (if doc-str (cl-format true " ~_~w" doc-str)) (if attr-map (cl-format true " ~_~w" attr-map)) ;; Note: the multi-defn case will work OK for malformed defns too (cond (vector? (first stuff)) (single-defn stuff (or doc-str attr-map)) :else (multi-defn stuff (or doc-str attr-map))))) (pprint-simple-code-list writer alis))))) ) ;;====================================================================== ;; print_table.clj ;;====================================================================== (defn- add-padding [width s] (let [padding (max 0 (- width (count s)))] (apply str (clojure.string/join (repeat padding \space)) s))) (defn print-table "Prints a collection of maps in a textual table. Prints table headings ks, and then a line of output for each row, corresponding to the keys in ks. If ks are not specified, use the keys of the first item in rows." {:added "1.3"} ([ks rows] (when (seq rows) (let [widths (map (fn [k] (apply max (count (str k)) (map #(count (str (get % k))) rows))) ks) spacers (map #(apply str (repeat % "-")) widths) fmt-row (fn [leader divider trailer row] (str leader (apply str (interpose divider (for [[col width] (map vector (map #(get row %) ks) widths)] (add-padding width (str col))))) trailer))] (cljs.core/println) (cljs.core/println (fmt-row "| " " | " " |" (zipmap ks ks))) (cljs.core/println (fmt-row "|-" "-+-" "-|" (zipmap ks spacers))) (doseq [row rows] (cljs.core/println (fmt-row "| " " | " " |" row)))))) ([rows] (print-table (keys (first rows)) rows)))
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns cljs.pprint (:refer-clojure :exclude [deftype print println pr prn float?]) (:require-macros [cljs.pprint :as m :refer [with-pretty-writer getf setf deftype pprint-logical-block print-length-loop defdirectives formatter-out]]) (:require [cljs.core :refer [IWriter IDeref]] [clojure.string :as string] [goog.string :as gstring]) (:import [goog.string StringBuffer])) ;;====================================================================== ;; override print fns to use *out* ;;====================================================================== (defn- print [& more] (-write *out* (apply print-str more))) (defn- println [& more] (apply print more) (-write *out* \newline)) (defn- print-char [c] (-write *out* (condp = c \backspace "\\backspace" \tab "\\tab" \newline "\\newline" \formfeed "\\formfeed" \return "\\return" \" "\\\"" \\ "\\\\" (str "\\" c)))) (defn- ^:dynamic pr [& more] (-write *out* (apply pr-str more))) (defn- prn [& more] (apply pr more) (-write *out* \newline)) ;;====================================================================== ;; cljs specific utils ;;====================================================================== (defn ^boolean float? "Returns true if n is an float." [n] (and (number? n) (not ^boolean (js/isNaN n)) (not (identical? n js/Infinity)) (not (== (js/parseFloat n) (js/parseInt n 10))))) (defn char-code "Convert char to int" [c] (cond (number? c) c (and (string? c) (== (.-length c) 1)) (.charCodeAt c 0) :else (throw (js/Error. "Argument to char must be a character or number")))) ;;====================================================================== ;; Utilities ;;====================================================================== (defn- map-passing-context [func initial-context lis] (loop [context initial-context lis lis acc []] (if (empty? lis) [acc context] (let [this (first lis) remainder (next lis) [result new-context] (apply func [this context])] (recur new-context remainder (conj acc result)))))) (defn- consume [func initial-context] (loop [context initial-context acc []] (let [[result new-context] (apply func [context])] (if (not result) [acc new-context] (recur new-context (conj acc result)))))) (defn- consume-while [func initial-context] (loop [context initial-context acc []] (let [[result continue new-context] (apply func [context])] (if (not continue) [acc context] (recur new-context (conj acc result)))))) (defn- unzip-map [m] "Take a map that has pairs in the value slots and produce a pair of maps, the first having all the first elements of the pairs and the second all the second elements of the pairs" [(into {} (for [[k [v1 v2]] m] [k v1])) (into {} (for [[k [v1 v2]] m] [k v2]))]) (defn- tuple-map [m v1] "For all the values, v, in the map, replace them with [v v1]" (into {} (for [[k v] m] [k [v v1]]))) (defn- rtrim [s c] "Trim all instances of c from the end of sequence s" (let [len (count s)] (if (and (pos? len) (= (nth s (dec (count s))) c)) (loop [n (dec len)] (cond (neg? n) "" (not (= (nth s n) c)) (subs s 0 (inc n)) true (recur (dec n)))) s))) (defn- ltrim [s c] "Trim all instances of c from the beginning of sequence s" (let [len (count s)] (if (and (pos? len) (= (nth s 0) c)) (loop [n 0] (if (or (= n len) (not (= (nth s n) c))) (subs s n) (recur (inc n)))) s))) (defn- prefix-count [aseq val] "Return the number of times that val occurs at the start of sequence aseq, if val is a seq itself, count the number of times any element of val occurs at the beginning of aseq" (let [test (if (coll? val) (set val) #{val})] (loop [pos 0] (if (or (= pos (count aseq)) (not (test (nth aseq pos)))) pos (recur (inc pos)))))) ;; Flush the pretty-print buffer without flushing the underlying stream (defprotocol IPrettyFlush (-ppflush [pp])) ;;====================================================================== ;; column_writer.clj ;;====================================================================== (def ^:dynamic ^{:private true} *default-page-width* 72) (defn- get-field [this sym] (sym @@this)) (defn- set-field [this sym new-val] (swap! @this assoc sym new-val)) (defn- get-column [this] (get-field this :cur)) (defn- get-line [this] (get-field this :line)) (defn- get-max-column [this] (get-field this :max)) (defn- set-max-column [this new-max] (set-field this :max new-max) nil) (defn- get-writer [this] (get-field this :base)) ;; Why is the c argument an integer? (defn- c-write-char [this c] (if (= c \newline) (do (set-field this :cur 0) (set-field this :line (inc (get-field this :line)))) (set-field this :cur (inc (get-field this :cur)))) (-write (get-field this :base) c)) (defn- column-writer ([writer] (column-writer writer *default-page-width*)) ([writer max-columns] (let [fields (atom {:max max-columns, :cur 0, :line 0 :base writer})] (reify IDeref (-deref [_] fields) IWriter (-flush [_] (-flush writer)) (-write ;;-write isn't multi-arity, so need different way to do this #_([this ^chars cbuf ^Number off ^Number len] (let [writer (get-field this :base)] (-write writer cbuf off len))) [this x] (condp = (type x) js/String (let [s x nl (.lastIndexOf s \newline)] (if (neg? nl) (set-field this :cur (+ (get-field this :cur) (count s))) (do (set-field this :cur (- (count s) nl 1)) (set-field this :line (+ (get-field this :line) (count (filter #(= % \newline) s)))))) (-write (get-field this :base) s)) js/Number (c-write-char this x))))))) ;;====================================================================== ;; pretty_writer.clj ;;====================================================================== ;;====================================================================== ;; Forward declarations ;;====================================================================== (declare ^{:arglists '([this])} get-miser-width) ;;====================================================================== ;; The data structures used by pretty-writer ;;====================================================================== (defrecord ^{:private true} logical-block [parent section start-col indent done-nl intra-block-nl prefix per-line-prefix suffix logical-block-callback]) (defn- ancestor? [parent child] (loop [child (:parent child)] (cond (nil? child) false (identical? parent child) true :else (recur (:parent child))))) (defn- buffer-length [l] (let [l (seq l)] (if l (- (:end-pos (last l)) (:start-pos (first l))) 0))) ;; A blob of characters (aka a string) (deftype buffer-blob :data :trailing-white-space :start-pos :end-pos) ;; A newline (deftype nl-t :type :logical-block :start-pos :end-pos) (deftype start-block-t :logical-block :start-pos :end-pos) (deftype end-block-t :logical-block :start-pos :end-pos) (deftype indent-t :logical-block :relative-to :offset :start-pos :end-pos) (def ^:private pp-newline (fn [] "\n")) (declare emit-nl) (defmulti ^{:private true} write-token #(:type-tag %2)) (defmethod write-token :start-block-t [this token] (when-let [cb (getf :logical-block-callback)] (cb :start)) (let [lb (:logical-block token)] (when-let [prefix (:prefix lb)] (-write (getf :base) prefix)) (let [col (get-column (getf :base))] (reset! (:start-col lb) col) (reset! (:indent lb) col)))) (defmethod write-token :end-block-t [this token] (when-let [cb (getf :logical-block-callback)] (cb :end)) (when-let [suffix (:suffix (:logical-block token))] (-write (getf :base) suffix))) (defmethod write-token :indent-t [this token] (let [lb (:logical-block token)] (reset! (:indent lb) (+ (:offset token) (condp = (:relative-to token) :block @(:start-col lb) :current (get-column (getf :base))))))) (defmethod write-token :buffer-blob [this token] (-write (getf :base) (:data token))) (defmethod write-token :nl-t [this token] (if (or (= (:type token) :mandatory) (and (not (= (:type token) :fill)) @(:done-nl (:logical-block token)))) (emit-nl this token) (if-let [tws (getf :trailing-white-space)] (-write (getf :base) tws))) (setf :trailing-white-space nil)) (defn- write-tokens [this tokens force-trailing-whitespace] (doseq [token tokens] (if-not (= (:type-tag token) :nl-t) (if-let [tws (getf :trailing-white-space)] (-write (getf :base) tws))) (write-token this token) (setf :trailing-white-space (:trailing-white-space token)) (let [tws (getf :trailing-white-space)] (when (and force-trailing-whitespace tws) (-write (getf :base) tws) (setf :trailing-white-space nil))))) ;;====================================================================== ;; emit-nl? method defs for each type of new line. This makes ;; the decision about whether to print this type of new line. ;;====================================================================== (defn- tokens-fit? [this tokens] (let [maxcol (get-max-column (getf :base))] (or (nil? maxcol) (< (+ (get-column (getf :base)) (buffer-length tokens)) maxcol)))) (defn- linear-nl? [this lb section] (or @(:done-nl lb) (not (tokens-fit? this section)))) (defn- miser-nl? [this lb section] (let [miser-width (get-miser-width this) maxcol (get-max-column (getf :base))] (and miser-width maxcol (>= @(:start-col lb) (- maxcol miser-width)) (linear-nl? this lb section)))) (defmulti ^{:private true} emit-nl? (fn [t _ _ _] (:type t))) (defmethod emit-nl? :linear [newl this section _] (let [lb (:logical-block newl)] (linear-nl? this lb section))) (defmethod emit-nl? :miser [newl this section _] (let [lb (:logical-block newl)] (miser-nl? this lb section))) (defmethod emit-nl? :fill [newl this section subsection] (let [lb (:logical-block newl)] (or @(:intra-block-nl lb) (not (tokens-fit? this subsection)) (miser-nl? this lb section)))) (defmethod emit-nl? :mandatory [_ _ _ _] true) ;;====================================================================== ;; Various support functions ;;====================================================================== (defn- get-section [buffer] (let [nl (first buffer) lb (:logical-block nl) section (seq (take-while #(not (and (nl-t? %) (ancestor? (:logical-block %) lb))) (next buffer)))] [section (seq (drop (inc (count section)) buffer))])) (defn- get-sub-section [buffer] (let [nl (first buffer) lb (:logical-block nl) section (seq (take-while #(let [nl-lb (:logical-block %)] (not (and (nl-t? %) (or (= nl-lb lb) (ancestor? nl-lb lb))))) (next buffer)))] section)) (defn- update-nl-state [lb] (reset! (:intra-block-nl lb) true) (reset! (:done-nl lb) true) (loop [lb (:parent lb)] (if lb (do (reset! (:done-nl lb) true) (reset! (:intra-block-nl lb) true) (recur (:parent lb)))))) (defn- emit-nl [this nl] (-write (getf :base) (pp-newline)) (setf :trailing-white-space nil) (let [lb (:logical-block nl) prefix (:per-line-prefix lb)] (if prefix (-write (getf :base) prefix)) (let [istr (apply str (repeat (- @(:indent lb) (count prefix)) \space))] (-write (getf :base) istr)) (update-nl-state lb))) (defn- split-at-newline [tokens] (let [pre (seq (take-while #(not (nl-t? %)) tokens))] [pre (seq (drop (count pre) tokens))])) ;; write-token-string is called when the set of tokens in the buffer ;; is long than the available space on the line (defn- write-token-string [this tokens] (let [[a b] (split-at-newline tokens)] (if a (write-tokens this a false)) (if b (let [[section remainder] (get-section b) newl (first b)] (let [do-nl (emit-nl? newl this section (get-sub-section b)) result (if do-nl (do (emit-nl this newl) (next b)) b) long-section (not (tokens-fit? this result)) result (if long-section (let [rem2 (write-token-string this section)] (if (= rem2 section) (do ; If that didn't produce any output, it has no nls ; so we'll force it (write-tokens this section false) remainder) (into [] (concat rem2 remainder)))) result)] result))))) (defn- write-line [this] (loop [buffer (getf :buffer)] (setf :buffer (into [] buffer)) (if (not (tokens-fit? this buffer)) (let [new-buffer (write-token-string this buffer)] (if-not (identical? buffer new-buffer) (recur new-buffer)))))) ;; Add a buffer token to the buffer and see if it's time to start ;; writing (defn- add-to-buffer [this token] (setf :buffer (conj (getf :buffer) token)) (if (not (tokens-fit? this (getf :buffer))) (write-line this))) ;; Write all the tokens that have been buffered (defn- write-buffered-output [this] (write-line this) (if-let [buf (getf :buffer)] (do (write-tokens this buf true) (setf :buffer [])))) (defn- write-white-space [this] (when-let [tws (getf :trailing-white-space)] (-write (getf :base) tws) (setf :trailing-white-space nil))) ;;; If there are newlines in the string, print the lines up until the last newline, ;;; making the appropriate adjustments. Return the remainder of the string (defn- write-initial-lines [^Writer this ^String s] (let [lines (string/split s "\n" -1)] (if (= (count lines) 1) s (let [^String prefix (:per-line-prefix (first (getf :logical-blocks))) ^String l (first lines)] (if (= :buffering (getf :mode)) (let [oldpos (getf :pos) newpos (+ oldpos (count l))] (setf :pos newpos) (add-to-buffer this (make-buffer-blob l nil oldpos newpos)) (write-buffered-output this)) (do (write-white-space this) (-write (getf :base) l))) (-write (getf :base) \newline) (doseq [^String l (next (butlast lines))] (-write (getf :base) l) (-write (getf :base) (pp-newline)) (if prefix (-write (getf :base) prefix))) (setf :buffering :writing) (last lines))))) (defn- p-write-char [this c] (if (= (getf :mode) :writing) (do (write-white-space this) (-write (getf :base) c)) (if (= c \newline) (write-initial-lines this \newline) (let [oldpos (getf :pos) newpos (inc oldpos)] (setf :pos newpos) (add-to-buffer this (make-buffer-blob (char c) nil oldpos newpos)))))) ;;====================================================================== ;; Initialize the pretty-writer instance ;;====================================================================== (defn- pretty-writer [writer max-columns miser-width] (let [lb (logical-block. nil nil (atom 0) (atom 0) (atom false) (atom false) nil nil nil nil) ; NOTE: may want to just `specify!` #js { ... fields ... } with the protocols fields (atom {:pretty-writer true :base (column-writer writer max-columns) :logical-blocks lb :sections nil :mode :writing :buffer [] :buffer-block lb :buffer-level 1 :miser-width miser-width :trailing-white-space nil :pos 0})] (reify IDeref (-deref [_] fields) IWriter (-write [this x] (condp = (type x) js/String (let [s0 (write-initial-lines this x) s (string/replace-first s0 #"\s+$" "") white-space (subs s0 (count s)) mode (getf :mode)] (if (= mode :writing) (do (write-white-space this) (-write (getf :base) s) (setf :trailing-white-space white-space)) (let [oldpos (getf :pos) newpos (+ oldpos (count s0))] (setf :pos newpos) (add-to-buffer this (make-buffer-blob s white-space oldpos newpos))))) js/Number (p-write-char this x))) (-flush [this] (-ppflush this) (-flush (getf :base))) IPrettyFlush (-ppflush [this] (if (= (getf :mode) :buffering) (do (write-tokens this (getf :buffer) true) (setf :buffer [])) (write-white-space this))) ))) ;;====================================================================== ;; Methods for pretty-writer ;;====================================================================== (defn- start-block [this prefix per-line-prefix suffix] (let [lb (logical-block. (getf :logical-blocks) nil (atom 0) (atom 0) (atom false) (atom false) prefix per-line-prefix suffix nil)] (setf :logical-blocks lb) (if (= (getf :mode) :writing) (do (write-white-space this) (when-let [cb (getf :logical-block-callback)] (cb :start)) (if prefix (-write (getf :base) prefix)) (let [col (get-column (getf :base))] (reset! (:start-col lb) col) (reset! (:indent lb) col))) (let [oldpos (getf :pos) newpos (+ oldpos (if prefix (count prefix) 0))] (setf :pos newpos) (add-to-buffer this (make-start-block-t lb oldpos newpos)))))) (defn- end-block [this] (let [lb (getf :logical-blocks) suffix (:suffix lb)] (if (= (getf :mode) :writing) (do (write-white-space this) (if suffix (-write (getf :base) suffix)) (when-let [cb (getf :logical-block-callback)] (cb :end))) (let [oldpos (getf :pos) newpos (+ oldpos (if suffix (count suffix) 0))] (setf :pos newpos) (add-to-buffer this (make-end-block-t lb oldpos newpos)))) (setf :logical-blocks (:parent lb)))) (defn- nl [this type] (setf :mode :buffering) (let [pos (getf :pos)] (add-to-buffer this (make-nl-t type (getf :logical-blocks) pos pos)))) (defn- indent [this relative-to offset] (let [lb (getf :logical-blocks)] (if (= (getf :mode) :writing) (do (write-white-space this) (reset! (:indent lb) (+ offset (condp = relative-to :block @(:start-col lb) :current (get-column (getf :base)))))) (let [pos (getf :pos)] (add-to-buffer this (make-indent-t lb relative-to offset pos pos)))))) (defn- get-miser-width [this] (getf :miser-width)) ;;====================================================================== ;; pprint_base.clj ;;====================================================================== ;;====================================================================== ;; Variables that control the pretty printer ;;====================================================================== ;; *print-length*, *print-level*, *print-namespace-maps* and *print-dup* are defined in cljs.core (def ^:dynamic ^{:doc "Bind to true if you want write to use pretty printing"} *print-pretty* true) (defonce ^:dynamic ^{:doc "The pretty print dispatch function. Use with-pprint-dispatch or set-pprint-dispatch to modify." :added "1.2"} *print-pprint-dispatch* nil) (def ^:dynamic ^{:doc "Pretty printing will try to avoid anything going beyond this column. Set it to nil to have pprint let the line be arbitrarily long. This will ignore all non-mandatory newlines.", :added "1.2"} *print-right-margin* 72) (def ^:dynamic ^{:doc "The column at which to enter miser style. Depending on the dispatch table, miser style add newlines in more places to try to keep lines short allowing for further levels of nesting.", :added "1.2"} *print-miser-width* 40) ;;; TODO implement output limiting (def ^:dynamic ^{:private true, :doc "Maximum number of lines to print in a pretty print instance (N.B. This is not yet used)"} *print-lines* nil) ;;; TODO: implement circle and shared (def ^:dynamic ^{:private true, :doc "Mark circular structures (N.B. This is not yet used)"} *print-circle* nil) ;;; TODO: should we just use *print-dup* here? (def ^:dynamic ^{:private true, :doc "Mark repeated structures rather than repeat them (N.B. This is not yet used)"} *print-shared* nil) (def ^:dynamic ^{:doc "Don't print namespaces with symbols. This is particularly useful when pretty printing the results of macro expansions" :added "1.2"} *print-suppress-namespaces* nil) ;;; TODO: support print-base and print-radix in cl-format ;;; TODO: support print-base and print-radix in rationals (def ^:dynamic ^{:doc "Print a radix specifier in front of integers and rationals. If *print-base* is 2, 8, or 16, then the radix specifier used is #b, #o, or #x, respectively. Otherwise the radix specifier is in the form #XXr where XX is the decimal value of *print-base* " :added "1.2"} *print-radix* nil) (def ^:dynamic ^{:doc "The base to use for printing integers and rationals." :added "1.2"} *print-base* 10) ;;====================================================================== ;; Internal variables that keep track of where we are in the ;; structure ;;====================================================================== (def ^:dynamic ^{:private true} *current-level* 0) (def ^:dynamic ^{:private true} *current-length* nil) ;;====================================================================== ;; Support for the write function ;;====================================================================== (declare ^{:arglists '([n])} format-simple-number) ;; This map causes var metadata to be included in the compiled output, even ;; in advanced compilation. See CLJS-1853 - PI:NAME:<NAME>END_PI ;; (def ^{:private true} write-option-table ;; {;:array *print-array* ;; :base #'cljs.pprint/*print-base*, ;; ;;:case *print-case*, ;; :circle #'cljs.pprint/*print-circle*, ;; ;;:escape *print-escape*, ;; ;;:gensym *print-gensym*, ;; :length #'cljs.core/*print-length*, ;; :level #'cljs.core/*print-level*, ;; :lines #'cljs.pprint/*print-lines*, ;; :miser-width #'cljs.pprint/*print-miser-width*, ;; :dispatch #'cljs.pprint/*print-pprint-dispatch*, ;; :pretty #'cljs.pprint/*print-pretty*, ;; :radix #'cljs.pprint/*print-radix*, ;; :readably #'cljs.core/*print-readably*, ;; :right-margin #'cljs.pprint/*print-right-margin*, ;; :suppress-namespaces #'cljs.pprint/*print-suppress-namespaces*}) (defn- table-ize [t m] (apply hash-map (mapcat #(when-let [v (get t (key %))] [v (val %)]) m))) (defn- pretty-writer? "Return true iff x is a PrettyWriter" [x] (and (satisfies? IDeref x) (:pretty-writer @@x))) (defn- make-pretty-writer "Wrap base-writer in a PrettyWriter with the specified right-margin and miser-width" [base-writer right-margin miser-width] (pretty-writer base-writer right-margin miser-width)) (defn write-out "Write an object to *out* subject to the current bindings of the printer control variables. Use the kw-args argument to override individual variables for this call (and any recursive calls). *out* must be a PrettyWriter if pretty printing is enabled. This is the responsibility of the caller. This method is primarily intended for use by pretty print dispatch functions that already know that the pretty printer will have set up their environment appropriately. Normal library clients should use the standard \"write\" interface. " [object] (let [length-reached (and *current-length* *print-length* (>= *current-length* *print-length*))] (if-not *print-pretty* (pr object) (if length-reached (-write *out* "...") ;;TODO could this (incorrectly) print ... on the next line? (do (if *current-length* (set! *current-length* (inc *current-length*))) (*print-pprint-dispatch* object)))) length-reached)) (defn write "Write an object subject to the current bindings of the printer control variables. Use the kw-args argument to override individual variables for this call (and any recursive calls). Returns the string result if :stream is nil or nil otherwise. The following keyword arguments can be passed with values: Keyword Meaning Default value :stream Writer for output or nil true (indicates *out*) :base Base to use for writing rationals Current value of *print-base* :circle* If true, mark circular structures Current value of *print-circle* :length Maximum elements to show in sublists Current value of *print-length* :level Maximum depth Current value of *print-level* :lines* Maximum lines of output Current value of *print-lines* :miser-width Width to enter miser mode Current value of *print-miser-width* :dispatch The pretty print dispatch function Current value of *print-pprint-dispatch* :pretty If true, do pretty printing Current value of *print-pretty* :radix If true, prepend a radix specifier Current value of *print-radix* :readably* If true, print readably Current value of *print-readably* :right-margin The column for the right margin Current value of *print-right-margin* :suppress-namespaces If true, no namespaces in symbols Current value of *print-suppress-namespaces* * = not yet supported " [object & kw-args] (let [options (merge {:stream true} (apply hash-map kw-args))] ;;TODO rewrite this as a macro (binding [cljs.pprint/*print-base* (:base options cljs.pprint/*print-base*) ;;:case *print-case*, cljs.pprint/*print-circle* (:circle options cljs.pprint/*print-circle*) ;;:escape *print-escape* ;;:gensym *print-gensym* cljs.core/*print-length* (:length options cljs.core/*print-length*) cljs.core/*print-level* (:level options cljs.core/*print-level*) cljs.pprint/*print-lines* (:lines options cljs.pprint/*print-lines*) cljs.pprint/*print-miser-width* (:miser-width options cljs.pprint/*print-miser-width*) cljs.pprint/*print-pprint-dispatch* (:dispatch options cljs.pprint/*print-pprint-dispatch*) cljs.pprint/*print-pretty* (:pretty options cljs.pprint/*print-pretty*) cljs.pprint/*print-radix* (:radix options cljs.pprint/*print-radix*) cljs.core/*print-readably* (:readably options cljs.core/*print-readably*) cljs.pprint/*print-right-margin* (:right-margin options cljs.pprint/*print-right-margin*) cljs.pprint/*print-suppress-namespaces* (:suppress-namespaces options cljs.pprint/*print-suppress-namespaces*)] ;;TODO enable printing base #_[bindings (if (or (not (= *print-base* 10)) *print-radix*) {#'pr pr-with-base} {})] (binding [] (let [sb (StringBuffer.) optval (if (contains? options :stream) (:stream options) true) base-writer (if (or (true? optval) (nil? optval)) (StringBufferWriter. sb) optval)] (if *print-pretty* (with-pretty-writer base-writer (write-out object)) (binding [*out* base-writer] (pr object))) (if (true? optval) (string-print (str sb))) (if (nil? optval) (str sb))))))) (defn pprint ([object] (let [sb (StringBuffer.)] (binding [*out* (StringBufferWriter. sb)] (pprint object *out*) (string-print (str sb))))) ([object writer] (with-pretty-writer writer (binding [*print-pretty* true] (write-out object)) (if (not (= 0 (get-column *out*))) (-write *out* \newline))))) (defn set-pprint-dispatch [function] (set! *print-pprint-dispatch* function) nil) ;;====================================================================== ;; Support for the functional interface to the pretty printer ;;====================================================================== (defn- check-enumerated-arg [arg choices] (if-not (choices arg) ;; TODO clean up choices string (throw (js/Error. (str "Bad argument: " arg ". It must be one of " choices))))) (defn- level-exceeded [] (and *print-level* (>= *current-level* *print-level*))) (defn pprint-newline "Print a conditional newline to a pretty printing stream. kind specifies if the newline is :linear, :miser, :fill, or :mandatory. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer." [kind] (check-enumerated-arg kind #{:linear :miser :fill :mandatory}) (nl *out* kind)) (defn pprint-indent "Create an indent at this point in the pretty printing stream. This defines how following lines are indented. relative-to can be either :block or :current depending whether the indent should be computed relative to the start of the logical block or the current column position. n is an offset. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer." [relative-to n] (check-enumerated-arg relative-to #{:block :current}) (indent *out* relative-to n)) ;; TODO a real implementation for pprint-tab (defn pprint-tab "Tab at this point in the pretty printing stream. kind specifies whether the tab is :line, :section, :line-relative, or :section-relative. Colnum and colinc specify the target column and the increment to move the target forward if the output is already past the original target. This function is intended for use when writing custom dispatch functions. Output is sent to *out* which must be a pretty printing writer. THIS FUNCTION IS NOT YET IMPLEMENTED." {:added "1.2"} [kind colnum colinc] (check-enumerated-arg kind #{:line :section :line-relative :section-relative}) (throw (js/Error. "pprint-tab is not yet implemented"))) ;;====================================================================== ;; cl_format.clj ;;====================================================================== ;; Forward references (declare ^{:arglists '([format-str])} compile-format) (declare ^{:arglists '([stream format args] [format args])} execute-format) (declare ^{:arglists '([s])} init-navigator) ;; End forward references (defn cl-format "An implementation of a Common Lisp compatible format function. cl-format formats its arguments to an output stream or string based on the format control string given. It supports sophisticated formatting of structured data. Writer satisfies IWriter, true to output via *print-fn* or nil to output to a string, format-in is the format control string and the remaining arguments are the data to be formatted. The format control string is a string to be output with embedded 'format directives' describing how to format the various arguments passed in. If writer is nil, cl-format returns the formatted result string. Otherwise, cl-format returns nil. For example: (let [results [46 38 22]] (cl-format true \"There ~[are~;is~:;are~]~:* ~d result~:p: ~{~d~^, ~}~%\" (count results) results)) Prints via *print-fn*: There are 3 results: 46, 38, 22 Detailed documentation on format control strings is available in the \"Common Lisp the Language, 2nd edition\", Chapter 22 (available online at: http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000) and in the Common Lisp HyperSpec at http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm" {:see-also [["http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000" "Common Lisp the Language"] ["http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm" "Common Lisp HyperSpec"]]} [writer format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format writer compiled-format navigator))) (def ^:dynamic ^{:private true} *format-str* nil) (defn- format-error [message offset] (let [full-message (str message \newline *format-str* \newline (apply str (repeat offset \space)) "^" \newline)] (throw (js/Error full-message)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Argument navigators manage the argument list ;; as the format statement moves through the list ;; (possibly going forwards and backwards as it does so) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord ^{:private true} arg-navigator [seq rest pos]) (defn- init-navigator "Create a new arg-navigator from the sequence with the position set to 0" {:skip-wiki true} [s] (let [s (seq s)] (arg-navigator. s s 0))) ;; TODO call format-error with offset (defn- next-arg [navigator] (let [rst (:rest navigator)] (if rst [(first rst) (arg-navigator. (:seq navigator) (next rst) (inc (:pos navigator)))] (throw (js/Error "Not enough arguments for format definition"))))) (defn- next-arg-or-nil [navigator] (let [rst (:rest navigator)] (if rst [(first rst) (arg-navigator. (:seq navigator) (next rst) (inc (:pos navigator)))] [nil navigator]))) ;; Get an argument off the arg list and compile it if it's not already compiled (defn- get-format-arg [navigator] (let [[raw-format navigator] (next-arg navigator) compiled-format (if (string? raw-format) (compile-format raw-format) raw-format)] [compiled-format navigator])) (declare relative-reposition) (defn- absolute-reposition [navigator position] (if (>= position (:pos navigator)) (relative-reposition navigator (- (:pos navigator) position)) (arg-navigator. (:seq navigator) (drop position (:seq navigator)) position))) (defn- relative-reposition [navigator position] (let [newpos (+ (:pos navigator) position)] (if (neg? position) (absolute-reposition navigator newpos) (arg-navigator. (:seq navigator) (drop position (:rest navigator)) newpos)))) (defrecord ^{:private true} compiled-directive [func def params offset]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; When looking at the parameter list, we may need to manipulate ;; the argument list as well (for 'V' and '#' parameter types). ;; We hide all of this behind a function, but clients need to ;; manage changing arg navigator ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO: validate parameters when they come from arg list (defn- realize-parameter [[param [raw-val offset]] navigator] (let [[real-param new-navigator] (cond (contains? #{:at :colon} param) ;pass flags through unchanged - this really isn't necessary [raw-val navigator] (= raw-val :parameter-from-args) (next-arg navigator) (= raw-val :remaining-arg-count) [(count (:rest navigator)) navigator] true [raw-val navigator])] [[param [real-param offset]] new-navigator])) (defn- realize-parameter-list [parameter-map navigator] (let [[pairs new-navigator] (map-passing-context realize-parameter navigator parameter-map)] [(into {} pairs) new-navigator])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Functions that support individual directives ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Common handling code for ~A and ~S ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare ^{:arglists '([base val])} opt-base-str) (def ^{:private true} special-radix-markers {2 "#b" 8 "#o" 16 "#x"}) (defn- format-simple-number [n] (cond (integer? n) (if (= *print-base* 10) (str n (if *print-radix* ".")) (str (if *print-radix* (or (get special-radix-markers *print-base*) (str "#" *print-base* "r"))) (opt-base-str *print-base* n))) ;;(ratio? n) ;;no ratio support :else nil)) (defn- format-ascii [print-func params arg-navigator offsets] (let [[arg arg-navigator] (next-arg arg-navigator) base-output (or (format-simple-number arg) (print-func arg)) base-width (.-length base-output) min-width (+ base-width (:minpad params)) width (if (>= min-width (:mincol params)) min-width (+ min-width (* (+ (quot (- (:mincol params) min-width 1) (:colinc params)) 1) (:colinc params)))) chars (apply str (repeat (- width base-width) (:padchar params)))] (if (:at params) (print (str chars base-output)) (print (str base-output chars))) arg-navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the integer directives ~D, ~X, ~O, ~B and some ;; of ~R ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- integral? "returns true if a number is actually an integer (that is, has no fractional part)" [x] (cond (integer? x) true ;;(decimal? x) ;;no decimal support (float? x) (= x (Math/floor x)) ;;(ratio? x) ;;no ratio support :else false)) (defn- remainders "Return the list of remainders (essentially the 'digits') of val in the given base" [base val] (reverse (first (consume #(if (pos? %) [(rem % base) (quot % base)] [nil nil]) val)))) ;; TODO: xlated-val does not seem to be used here. ;; NB (defn- base-str "Return val as a string in the given base" [base val] (if (zero? val) "0" (let [xlated-val (cond ;(float? val) (bigdec val) ;;No bigdec ;(ratio? val) nil ;;No ratio :else val)] (apply str (map #(if (< % 10) (char (+ (char-code \0) %)) (char (+ (char-code \a) (- % 10)))) (remainders base val)))))) ;;Not sure if this is accurate or necessary (def ^{:private true} javascript-base-formats {8 "%o", 10 "%d", 16 "%x"}) (defn- opt-base-str "Return val as a string in the given base. No cljs format, so no improved performance." [base val] (base-str base val)) (defn- group-by* [unit lis] (reverse (first (consume (fn [x] [(seq (reverse (take unit x))) (seq (drop unit x))]) (reverse lis))))) (defn- format-integer [base params arg-navigator offsets] (let [[arg arg-navigator] (next-arg arg-navigator)] (if (integral? arg) (let [neg (neg? arg) pos-arg (if neg (- arg) arg) raw-str (opt-base-str base pos-arg) group-str (if (:colon params) (let [groups (map #(apply str %) (group-by* (:commainterval params) raw-str)) commas (repeat (count groups) (:commachar params))] (apply str (next (interleave commas groups)))) raw-str) signed-str (cond neg (str "-" group-str) (:at params) (str "+" group-str) true group-str) padded-str (if (< (.-length signed-str) (:mincol params)) (str (apply str (repeat (- (:mincol params) (.-length signed-str)) (:padchar params))) signed-str) signed-str)] (print padded-str)) (format-ascii print-str {:mincol (:mincol params) :colinc 1 :minpad 0 :padchar (:padchar params) :at true} (init-navigator [arg]) nil)) arg-navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for english formats (~R and ~:R) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} english-cardinal-units ["zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine" "ten" "eleven" "twelve" "thirteen" "fourteen" "fifteen" "sixteen" "seventeen" "eighteen" "nineteen"]) (def ^{:private true} english-ordinal-units ["zeroth" "first" "second" "third" "fourth" "fifth" "sixth" "seventh" "eighth" "ninth" "tenth" "eleventh" "twelfth" "thirteenth" "fourteenth" "fifteenth" "sixteenth" "seventeenth" "eighteenth" "nineteenth"]) (def ^{:private true} english-cardinal-tens ["" "" "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty" "ninety"]) (def ^{:private true} english-ordinal-tens ["" "" "twentieth" "thirtieth" "fortieth" "fiftieth" "sixtieth" "seventieth" "eightieth" "ninetieth"]) ;; We use "short scale" for our units (see http://en.wikipedia.org/wiki/Long_and_short_scales) ;; Number names from http://www.jimloy.com/math/billion.htm ;; We follow the rules for writing numbers from the Blue Book ;; (http://www.grammarbook.com/numbers/numbers.asp) (def ^{:private true} english-scale-numbers ["" "thousand" "million" "billion" "trillion" "quadrillion" "quintillion" "sextillion" "septillion" "octillion" "nonillion" "decillion" "undecillion" "duodecillion" "tredecillion" "quattuordecillion" "quindecillion" "sexdecillion" "septendecillion" "octodecillion" "novemdecillion" "vigintillion"]) (defn- format-simple-cardinal "Convert a number less than 1000 to a cardinal english string" [num] (let [hundreds (quot num 100) tens (rem num 100)] (str (if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred")) (if (and (pos? hundreds) (pos? tens)) " ") (if (pos? tens) (if (< tens 20) (nth english-cardinal-units tens) (let [ten-digit (quot tens 10) unit-digit (rem tens 10)] (str (if (pos? ten-digit) (nth english-cardinal-tens ten-digit)) (if (and (pos? ten-digit) (pos? unit-digit)) "-") (if (pos? unit-digit) (nth english-cardinal-units unit-digit))))))))) (defn- add-english-scales "Take a sequence of parts, add scale numbers (e.g., million) and combine into a string offset is a factor of 10^3 to multiply by" [parts offset] (let [cnt (count parts)] (loop [acc [] pos (dec cnt) this (first parts) remainder (next parts)] (if (nil? remainder) (str (apply str (interpose ", " acc)) (if (and (not (empty? this)) (not (empty? acc))) ", ") this (if (and (not (empty? this)) (pos? (+ pos offset))) (str " " (nth english-scale-numbers (+ pos offset))))) (recur (if (empty? this) acc (conj acc (str this " " (nth english-scale-numbers (+ pos offset))))) (dec pos) (first remainder) (next remainder)))))) (defn- format-cardinal-english [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (= 0 arg) (print "zero") (let [abs-arg (if (neg? arg) (- arg) arg) ; some numbers are too big for Math/abs (is this true?) parts (remainders 1000 abs-arg)] (if (<= (count parts) (count english-scale-numbers)) (let [parts-strs (map format-simple-cardinal parts) full-str (add-english-scales parts-strs 0)] (print (str (if (neg? arg) "minus ") full-str))) (format-integer ;; for numbers > 10^63, we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0})))) navigator)) (defn- format-simple-ordinal "Convert a number less than 1000 to a ordinal english string Note this should only be used for the last one in the sequence" [num] (let [hundreds (quot num 100) tens (rem num 100)] (str (if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred")) (if (and (pos? hundreds) (pos? tens)) " ") (if (pos? tens) (if (< tens 20) (nth english-ordinal-units tens) (let [ten-digit (quot tens 10) unit-digit (rem tens 10)] (if (and (pos? ten-digit) (not (pos? unit-digit))) (nth english-ordinal-tens ten-digit) (str (if (pos? ten-digit) (nth english-cardinal-tens ten-digit)) (if (and (pos? ten-digit) (pos? unit-digit)) "-") (if (pos? unit-digit) (nth english-ordinal-units unit-digit)))))) (if (pos? hundreds) "th"))))) (defn- format-ordinal-english [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (= 0 arg) (print "zeroth") (let [abs-arg (if (neg? arg) (- arg) arg) ; some numbers are too big for Math/abs (is this true?) parts (remainders 1000 abs-arg)] (if (<= (count parts) (count english-scale-numbers)) (let [parts-strs (map format-simple-cardinal (drop-last parts)) head-str (add-english-scales parts-strs 1) tail-str (format-simple-ordinal (last parts))] (print (str (if (neg? arg) "minus ") (cond (and (not (empty? head-str)) (not (empty? tail-str))) (str head-str ", " tail-str) (not (empty? head-str)) (str head-str "th") :else tail-str)))) (do (format-integer ;for numbers > 10^63, we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0}) (let [low-two-digits (rem arg 100) not-teens (or (< 11 low-two-digits) (> 19 low-two-digits)) low-digit (rem low-two-digits 10)] (print (cond (and (== low-digit 1) not-teens) "st" (and (== low-digit 2) not-teens) "nd" (and (== low-digit 3) not-teens) "rd" :else "th"))))))) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for roman numeral formats (~@R and ~@:R) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} old-roman-table [[ "I" "II" "III" "IIII" "V" "VI" "VII" "VIII" "VIIII"] [ "X" "XX" "XXX" "XXXX" "L" "LX" "LXX" "LXXX" "LXXXX"] [ "C" "CC" "CCC" "CCCC" "D" "DC" "DCC" "DCCC" "DCCCC"] [ "M" "MM" "MMM"]]) (def ^{:private true} new-roman-table [[ "I" "II" "III" "IV" "V" "VI" "VII" "VIII" "IX"] [ "X" "XX" "XXX" "XL" "L" "LX" "LXX" "LXXX" "XC"] [ "C" "CC" "CCC" "CD" "D" "DC" "DCC" "DCCC" "CM"] [ "M" "MM" "MMM"]]) (defn- format-roman "Format a roman numeral using the specified look-up table" [table params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (and (number? arg) (> arg 0) (< arg 4000)) (let [digits (remainders 10 arg)] (loop [acc [] pos (dec (count digits)) digits digits] (if (empty? digits) (print (apply str acc)) (let [digit (first digits)] (recur (if (= 0 digit) acc (conj acc (nth (nth table pos) (dec digit)))) (dec pos) (next digits)))))) (format-integer ; for anything <= 0 or > 3999, we fall back on ~D 10 {:mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true} (init-navigator [arg]) {:mincol 0, :padchar 0, :commachar 0 :commainterval 0})) navigator)) (defn- format-old-roman [params navigator offsets] (format-roman old-roman-table params navigator offsets)) (defn- format-new-roman [params navigator offsets] (format-roman new-roman-table params navigator offsets)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for character formats (~C) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} special-chars {8 "Backspace", 9 "Tab", 10 "Newline", 13 "Return", 32 "Space"}) (defn- pretty-character [params navigator offsets] (let [[c navigator] (next-arg navigator) as-int (char-code c) base-char (bit-and as-int 127) meta (bit-and as-int 128) special (get special-chars base-char)] (if (> meta 0) (print "Meta-")) (print (cond special special (< base-char 32) (str "Control-" (char (+ base-char 64))) (= base-char 127) "Control-?" :else (char base-char))) navigator)) (defn- readable-character [params navigator offsets] (let [[c navigator] (next-arg navigator)] (condp = (:char-format params) \o (cl-format true "\\o~3, '0o" (char-code c)) \u (cl-format true "\\u~4, '0x" (char-code c)) nil (print-char c)) navigator)) (defn- plain-character [params navigator offsets] (let [[char navigator] (next-arg navigator)] (print char) navigator)) ;; Check to see if a result is an abort (~^) construct ;; TODO: move these funcs somewhere more appropriate (defn- abort? [context] (let [token (first context)] (or (= :up-arrow token) (= :colon-up-arrow token)))) ;; Handle the execution of "sub-clauses" in bracket constructions (defn- execute-sub-format [format args base-args] (second (map-passing-context (fn [element context] (if (abort? context) [nil context] ; just keep passing it along (let [[params args] (realize-parameter-list (:params element) context) [params offsets] (unzip-map params) params (assoc params :base-args base-args)] [nil (apply (:func element) [params args offsets])]))) args format))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for real number formats ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO - return exponent as int to eliminate double conversion (defn- float-parts-base "Produce string parts for the mantissa (normalize 1-9) and exponent" [f] (let [s (string/lower-case (str f)) exploc (.indexOf s \e) dotloc (.indexOf s \.)] (if (neg? exploc) (if (neg? dotloc) [s (str (dec (count s)))] [(str (subs s 0 dotloc) (subs s (inc dotloc))) (str (dec dotloc))]) (if (neg? dotloc) [(subs s 0 exploc) (subs s (inc exploc))] [(str (subs s 0 1) (subs s 2 exploc)) (subs s (inc exploc))])))) (defn- float-parts "Take care of leading and trailing zeros in decomposed floats" [f] (let [[m e] (float-parts-base f) m1 (rtrim m \0) m2 (ltrim m1 \0) delta (- (count m1) (count m2)) e (if (and (pos? (count e)) (= (nth e 0) \+)) (subs e 1) e)] (if (empty? m2) ["0" 0] [m2 (- (js/parseInt e 10) delta)]))) (defn- inc-s "Assumption: The input string consists of one or more decimal digits, and no other characters. Return a string containing one or more decimal digits containing a decimal number one larger than the input string. The output string will always be the same length as the input string, or one character longer." [s] (let [len-1 (dec (count s))] (loop [i (int len-1)] (cond (neg? i) (apply str "1" (repeat (inc len-1) "0")) (= \9 (.charAt s i)) (recur (dec i)) :else (apply str (subs s 0 i) (char (inc (char-code (.charAt s i)))) (repeat (- len-1 i) "0")))))) (defn- round-str [m e d w] (if (or d w) (let [len (count m) ;; Every formatted floating point number should include at ;; least one decimal digit and a decimal point. w (if w (max 2 w) ;;NB: if w doesn't exist, it won't ever be used because d will ;; satisfy the cond below. cljs gives a compilation warning if ;; we don't provide a value here. 0) round-pos (cond ;; If d was given, that forces the rounding ;; position, regardless of any width that may ;; have been specified. d (+ e d 1) ;; Otherwise w was specified, so pick round-pos ;; based upon that. ;; If e>=0, then abs value of number is >= 1.0, ;; and e+1 is number of decimal digits before the ;; decimal point when the number is written ;; without scientific notation. Never round the ;; number before the decimal point. (>= e 0) (max (inc e) (dec w)) ;; e < 0, so number abs value < 1.0 :else (+ w e)) [m1 e1 round-pos len] (if (= round-pos 0) [(str "0" m) (inc e) 1 (inc len)] [m e round-pos len])] (if round-pos (if (neg? round-pos) ["0" 0 false] (if (> len round-pos) (let [round-char (nth m1 round-pos) result (subs m1 0 round-pos)] (if (>= (char-code round-char) (char-code \5)) (let [round-up-result (inc-s result) expanded (> (count round-up-result) (count result))] [(if expanded (subs round-up-result 0 (dec (count round-up-result))) round-up-result) e1 expanded]) [result e1 false])) [m e false])) [m e false])) [m e false])) (defn- expand-fixed [m e d] (let [[m1 e1] (if (neg? e) [(str (apply str (repeat (dec (- e)) \0)) m) -1] [m e]) len (count m1) target-len (if d (+ e1 d 1) (inc e1))] (if (< len target-len) (str m1 (apply str (repeat (- target-len len) \0))) m1))) (defn- insert-decimal "Insert the decimal point at the right spot in the number to match an exponent" [m e] (if (neg? e) (str "." m) (let [loc (inc e)] (str (subs m 0 loc) "." (subs m loc))))) (defn- get-fixed [m e d] (insert-decimal (expand-fixed m e d) e)) (defn- insert-scaled-decimal "Insert the decimal point at the right spot in the number to match an exponent" [m k] (if (neg? k) (str "." m) (str (subs m 0 k) "." (subs m k)))) ;;TODO: No ratio, so not sure what to do here (defn- convert-ratio [x] x) ;; the function to render ~F directives ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases (defn- fixed-float [params navigator offsets] (let [w (:w params) d (:d params) [arg navigator] (next-arg navigator) [sign abs] (if (neg? arg) ["-" (- arg)] ["+" arg]) abs (convert-ratio abs) [mantissa exp] (float-parts abs) scaled-exp (+ exp (:k params)) add-sign (or (:at params) (neg? arg)) append-zero (and (not d) (<= (dec (count mantissa)) scaled-exp)) [rounded-mantissa scaled-exp expanded] (round-str mantissa scaled-exp d (if w (- w (if add-sign 1 0)))) fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d) fixed-repr (if (and w d (>= d 1) (= (.charAt fixed-repr 0) \0) (= (.charAt fixed-repr 1) \.) (> (count fixed-repr) (- w (if add-sign 1 0)))) (subs fixed-repr 1) ;chop off leading 0 fixed-repr) prepend-zero (= (first fixed-repr) \.)] (if w (let [len (count fixed-repr) signed-len (if add-sign (inc len) len) prepend-zero (and prepend-zero (not (>= signed-len w))) append-zero (and append-zero (not (>= signed-len w))) full-len (if (or prepend-zero append-zero) (inc signed-len) signed-len)] (if (and (> full-len w) (:overflowchar params)) (print (apply str (repeat w (:overflowchar params)))) (print (str (apply str (repeat (- w full-len) (:padchar params))) (if add-sign sign) (if prepend-zero "0") fixed-repr (if append-zero "0"))))) (print (str (if add-sign sign) (if prepend-zero "0") fixed-repr (if append-zero "0")))) navigator)) ;; the function to render ~E directives ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases ;; TODO: define ~E representation for Infinity (defn- exponential-float [params navigator offset] (let [[arg navigator] (next-arg navigator) arg (convert-ratio arg)] (loop [[mantissa exp] (float-parts (if (neg? arg) (- arg) arg))] (let [w (:w params) d (:d params) e (:e params) k (:k params) expchar (or (:exponentchar params) \E) add-sign (or (:at params) (neg? arg)) prepend-zero (<= k 0) scaled-exp (- exp (dec k)) scaled-exp-str (str (Math/abs scaled-exp)) scaled-exp-str (str expchar (if (neg? scaled-exp) \- \+) (if e (apply str (repeat (- e (count scaled-exp-str)) \0))) scaled-exp-str) exp-width (count scaled-exp-str) base-mantissa-width (count mantissa) scaled-mantissa (str (apply str (repeat (- k) \0)) mantissa (if d (apply str (repeat (- d (dec base-mantissa-width) (if (neg? k) (- k) 0)) \0)))) w-mantissa (if w (- w exp-width)) [rounded-mantissa _ incr-exp] (round-str scaled-mantissa 0 (cond (= k 0) (dec d) (pos? k) d (neg? k) (dec d)) (if w-mantissa (- w-mantissa (if add-sign 1 0)))) full-mantissa (insert-scaled-decimal rounded-mantissa k) append-zero (and (= k (count rounded-mantissa)) (nil? d))] (if (not incr-exp) (if w (let [len (+ (count full-mantissa) exp-width) signed-len (if add-sign (inc len) len) prepend-zero (and prepend-zero (not (= signed-len w))) full-len (if prepend-zero (inc signed-len) signed-len) append-zero (and append-zero (< full-len w))] (if (and (or (> full-len w) (and e (> (- exp-width 2) e))) (:overflowchar params)) (print (apply str (repeat w (:overflowchar params)))) (print (str (apply str (repeat (- w full-len (if append-zero 1 0)) (:padchar params))) (if add-sign (if (neg? arg) \- \+)) (if prepend-zero "0") full-mantissa (if append-zero "0") scaled-exp-str)))) (print (str (if add-sign (if (neg? arg) \- \+)) (if prepend-zero "0") full-mantissa (if append-zero "0") scaled-exp-str))) (recur [rounded-mantissa (inc exp)])))) navigator)) ;; the function to render ~G directives ;; This just figures out whether to pass the request off to ~F or ~E based ;; on the algorithm in CLtL. ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases ;; TODO: refactor so that float-parts isn't called twice (defn- general-float [params navigator offsets] (let [[arg _] (next-arg navigator) arg (convert-ratio arg) [mantissa exp] (float-parts (if (neg? arg) (- arg) arg)) w (:w params) d (:d params) e (:e params) n (if (= arg 0.0) 0 (inc exp)) ee (if e (+ e 2) 4) ww (if w (- w ee)) d (if d d (max (count mantissa) (min n 7))) dd (- d n)] (if (<= 0 dd d) (let [navigator (fixed-float {:w ww, :d dd, :k 0, :overflowchar (:overflowchar params), :padchar (:padchar params), :at (:at params)} navigator offsets)] (print (apply str (repeat ee \space))) navigator) (exponential-float params navigator offsets)))) ;; the function to render ~$ directives ;; TODO: support rationals. Back off to ~D/~A in the appropriate cases (defn- dollar-float [params navigator offsets] (let [[arg navigator] (next-arg navigator) [mantissa exp] (float-parts (Math/abs arg)) d (:d params) ; digits after the decimal n (:n params) ; minimum digits before the decimal w (:w params) ; minimum field width add-sign (or (:at params) (neg? arg)) [rounded-mantissa scaled-exp expanded] (round-str mantissa exp d nil) fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d) full-repr (str (apply str (repeat (- n (.indexOf fixed-repr \.)) \0)) fixed-repr) full-len (+ (count full-repr) (if add-sign 1 0))] (print (str (if (and (:colon params) add-sign) (if (neg? arg) \- \+)) (apply str (repeat (- w full-len) (:padchar params))) (if (and (not (:colon params)) add-sign) (if (neg? arg) \- \+)) full-repr)) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the '~[...~]' conditional construct in its ;; different flavors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ~[...~] without any modifiers chooses one of the clauses based on the param or ;; next argument ;; TODO check arg is positive int (defn- choice-conditional [params arg-navigator offsets] (let [arg (:selector params) [arg navigator] (if arg [arg arg-navigator] (next-arg arg-navigator)) clauses (:clauses params) clause (if (or (neg? arg) (>= arg (count clauses))) (first (:else params)) (nth clauses arg))] (if clause (execute-sub-format clause navigator (:base-args params)) navigator))) ;; ~:[...~] with the colon reads the next argument treating it as a truth value (defn- boolean-conditional [params arg-navigator offsets] (let [[arg navigator] (next-arg arg-navigator) clauses (:clauses params) clause (if arg (second clauses) (first clauses))] (if clause (execute-sub-format clause navigator (:base-args params)) navigator))) ;; ~@[...~] with the at sign executes the conditional if the next arg is not ;; nil/false without consuming the arg (defn- check-arg-conditional [params arg-navigator offsets] (let [[arg navigator] (next-arg arg-navigator) clauses (:clauses params) clause (if arg (first clauses))] (if arg (if clause (execute-sub-format clause arg-navigator (:base-args params)) arg-navigator) navigator))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the '~{...~}' iteration construct in its ;; different flavors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ~{...~} without any modifiers uses the next argument as an argument list that ;; is consumed by all the iterations (defn- iterate-sublist [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator]) [arg-list navigator] (next-arg navigator) args (init-navigator arg-list)] (loop [count 0 args args last-pos (int -1)] (if (and (not max-count) (= (:pos args) last-pos) (> count 1)) ;; TODO get the offset in here and call format exception (throw (js/Error "%{ construct not consuming any arguments: Infinite loop!"))) (if (or (and (empty? (:rest args)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause args (:base-args params))] (if (= :up-arrow (first iter-result)) navigator (recur (inc count) iter-result (:pos args)))))))) ;; ~:{...~} with the colon treats the next argument as a list of sublists. Each of the ;; sublists is used as the arglist for a single iteration. (defn- iterate-list-of-sublists [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator]) [arg-list navigator] (next-arg navigator)] (loop [count 0 arg-list arg-list] (if (or (and (empty? arg-list) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause (init-navigator (first arg-list)) (init-navigator (next arg-list)))] (if (= :colon-up-arrow (first iter-result)) navigator (recur (inc count) (next arg-list)))))))) ;; ~@{...~} with the at sign uses the main argument list as the arguments to the iterations ;; is consumed by all the iterations (defn- iterate-main-list [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator])] (loop [count 0 navigator navigator last-pos (int -1)] (if (and (not max-count) (= (:pos navigator) last-pos) (> count 1)) ;; TODO get the offset in here and call format exception (throw (js/Error "%@{ construct not consuming any arguments: Infinite loop!"))) (if (or (and (empty? (:rest navigator)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [iter-result (execute-sub-format clause navigator (:base-args params))] (if (= :up-arrow (first iter-result)) (second iter-result) (recur (inc count) iter-result (:pos navigator)))))))) ;; ~@:{...~} with both colon and at sign uses the main argument list as a set of sublists, one ;; of which is consumed with each iteration (defn- iterate-main-sublists [params navigator offsets] (let [max-count (:max-iterations params) param-clause (first (:clauses params)) [clause navigator] (if (empty? param-clause) (get-format-arg navigator) [param-clause navigator])] (loop [count 0 navigator navigator] (if (or (and (empty? (:rest navigator)) (or (not (:colon (:right-params params))) (> count 0))) (and max-count (>= count max-count))) navigator (let [[sublist navigator] (next-arg-or-nil navigator) iter-result (execute-sub-format clause (init-navigator sublist) navigator)] (if (= :colon-up-arrow (first iter-result)) navigator (recur (inc count) navigator))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; The '~< directive has two completely different meanings ;; in the '~<...~>' form it does justification, but with ;; ~<...~:>' it represents the logical block operation of the ;; pretty printer. ;; ;; Unfortunately, the current architecture decides what function ;; to call at form parsing time before the sub-clauses have been ;; folded, so it is left to run-time to make the decision. ;; ;; TODO: make it possible to make these decisions at compile-time. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare ^{:arglists '([params navigator offsets])} format-logical-block) (declare ^{:arglists '([params navigator offsets])} justify-clauses) (defn- logical-block-or-justify [params navigator offsets] (if (:colon (:right-params params)) (format-logical-block params navigator offsets) (justify-clauses params navigator offsets))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Support for the '~<...~>' justification directive ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- render-clauses [clauses navigator base-navigator] (loop [clauses clauses acc [] navigator navigator] (if (empty? clauses) [acc navigator] (let [clause (first clauses) [iter-result result-str] (let [sb (StringBuffer.)] (binding [*out* (StringBufferWriter. sb)] [(execute-sub-format clause navigator base-navigator) (str sb)]))] (if (= :up-arrow (first iter-result)) [acc (second iter-result)] (recur (next clauses) (conj acc result-str) iter-result)))))) ;; TODO support for ~:; constructions (defn- justify-clauses [params navigator offsets] (let [[[eol-str] new-navigator] (when-let [else (:else params)] (render-clauses else navigator (:base-args params))) navigator (or new-navigator navigator) [else-params new-navigator] (when-let [p (:else-params params)] (realize-parameter-list p navigator)) navigator (or new-navigator navigator) min-remaining (or (first (:min-remaining else-params)) 0) max-columns (or (first (:max-columns else-params)) (get-max-column *out*)) clauses (:clauses params) [strs navigator] (render-clauses clauses navigator (:base-args params)) slots (max 1 (+ (dec (count strs)) (if (:colon params) 1 0) (if (:at params) 1 0))) chars (reduce + (map count strs)) mincol (:mincol params) minpad (:minpad params) colinc (:colinc params) minout (+ chars (* slots minpad)) result-columns (if (<= minout mincol) mincol (+ mincol (* colinc (+ 1 (quot (- minout mincol 1) colinc))))) total-pad (- result-columns chars) pad (max minpad (quot total-pad slots)) extra-pad (- total-pad (* pad slots)) pad-str (apply str (repeat pad (:padchar params)))] (if (and eol-str (> (+ (get-column (:base @@*out*)) min-remaining result-columns) max-columns)) (print eol-str)) (loop [slots slots extra-pad extra-pad strs strs pad-only (or (:colon params) (and (= (count strs) 1) (not (:at params))))] (if (seq strs) (do (print (str (if (not pad-only) (first strs)) (if (or pad-only (next strs) (:at params)) pad-str) (if (pos? extra-pad) (:padchar params)))) (recur (dec slots) (dec extra-pad) (if pad-only strs (next strs)) false)))) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Support for case modification with ~(...~). ;;; We do this by wrapping the underlying writer with ;;; a special writer to do the appropriate modification. This ;;; allows us to support arbitrary-sized output and sources ;;; that may block. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- downcase-writer "Returns a proxy that wraps writer, converting all characters to lower case" [writer] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity, not sure of importance #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (string/lower-case s))) js/Number (let [c x] ;;TODO need to enforce integers only? (-write writer (string/lower-case (char c)))))))) (defn- upcase-writer "Returns a proxy that wraps writer, converting all characters to upper case" [writer] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity, not sure of importance #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (string/upper-case s))) js/Number (let [c x] ;;TODO need to enforce integers only? (-write writer (string/upper-case (char c)))))))) (defn- capitalize-string "Capitalizes the words in a string. If first? is false, don't capitalize the first character of the string even if it's a letter." [s first?] (let [f (first s) s (if (and first? f (gstring/isUnicodeChar f)) (str (string/upper-case f) (subs s 1)) s)] (apply str (first (consume (fn [s] (if (empty? s) [nil nil] (let [m (.exec (js/RegExp "\\W\\w" "g") s) offset (and m (inc (.-index m)))] (if offset [(str (subs s 0 offset) (string/upper-case (nth s offset))) (subs s (inc offset))] [s nil])))) s))))) (defn- capitalize-word-writer "Returns a proxy that wraps writer, capitalizing all words" [writer] (let [last-was-whitespace? (atom true)] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s x] (-write writer (capitalize-string (.toLowerCase s) @last-was-whitespace?)) (when (pos? (.-length s)) (reset! last-was-whitespace? (gstring/isEmptyOrWhitespace (nth s (dec (count s))))))) js/Number (let [c (char x)] (let [mod-c (if @last-was-whitespace? (string/upper-case c) c)] (-write writer mod-c) (reset! last-was-whitespace? (gstring/isEmptyOrWhitespace c))))))))) (defn- init-cap-writer "Returns a proxy that wraps writer, capitalizing the first word" [writer] (let [capped (atom false)] (reify IWriter (-flush [_] (-flush writer)) (-write ;;no multi-arity #_([^chars cbuf ^Integer off ^Integer len] (.write writer cbuf off len)) [this x] (condp = (type x) js/String (let [s (string/lower-case x)] (if (not @capped) (let [m (.exec (js/RegExp "\\S" "g") s) offset (and m (.-index m))] (if offset (do (-write writer (str (subs s 0 offset) (string/upper-case (nth s offset)) (string/lower-case (subs s (inc offset))))) (reset! capped true)) (-write writer s))) (-write writer (string/lower-case s)))) js/Number (let [c (char x)] (if (and (not @capped) (gstring/isUnicodeChar c)) (do (reset! capped true) (-write writer (string/upper-case c))) (-write writer (string/lower-case c))))))))) (defn- modify-case [make-writer params navigator offsets] (let [clause (first (:clauses params))] (binding [*out* (make-writer *out*)] (execute-sub-format clause navigator (:base-args params))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; If necessary, wrap the writer in a PrettyWriter object ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO update this doc string to show correct way to print (defn get-pretty-writer "Returns the IWriter passed in wrapped in a pretty writer proxy, unless it's already a pretty writer. Generally, it is unnecessary to call this function, since pprint, write, and cl-format all call it if they need to. However if you want the state to be preserved across calls, you will want to wrap them with this. For example, when you want to generate column-aware output with multiple calls to cl-format, do it like in this example: (defn print-table [aseq column-width] (binding [*out* (get-pretty-writer *out*)] (doseq [row aseq] (doseq [col row] (cl-format true \"~4D~7,vT\" col column-width)) (prn)))) Now when you run: user> (print-table (map #(vector % (* % %) (* % % %)) (range 1 11)) 8) It prints a table of squares and cubes for the numbers from 1 to 10: 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000" [writer] (if (pretty-writer? writer) writer (pretty-writer writer *print-right-margin* *print-miser-width*))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Support for column-aware operations ~&, ~T ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn fresh-line "Make a newline if *out* is not already at the beginning of the line. If *out* is not a pretty writer (which keeps track of columns), this function always outputs a newline." [] (if (satisfies? IDeref *out*) (if (not (= 0 (get-column (:base @@*out*)))) (prn)) (prn))) (defn- absolute-tabulation [params navigator offsets] (let [colnum (:colnum params) colinc (:colinc params) current (get-column (:base @@*out*)) space-count (cond (< current colnum) (- colnum current) (= colinc 0) 0 :else (- colinc (rem (- current colnum) colinc)))] (print (apply str (repeat space-count \space)))) navigator) (defn- relative-tabulation [params navigator offsets] (let [colrel (:colnum params) colinc (:colinc params) start-col (+ colrel (get-column (:base @@*out*))) offset (if (pos? colinc) (rem start-col colinc) 0) space-count (+ colrel (if (= 0 offset) 0 (- colinc offset)))] (print (apply str (repeat space-count \space)))) navigator) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Support for accessing the pretty printer from a format ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TODO: support ~@; per-line-prefix separator ;; TODO: get the whole format wrapped so we can start the lb at any column (defn- format-logical-block [params navigator offsets] (let [clauses (:clauses params) clause-count (count clauses) prefix (cond (> clause-count 1) (:string (:params (first (first clauses)))) (:colon params) "(") body (nth clauses (if (> clause-count 1) 1 0)) suffix (cond (> clause-count 2) (:string (:params (first (nth clauses 2)))) (:colon params) ")") [arg navigator] (next-arg navigator)] (pprint-logical-block :prefix prefix :suffix suffix (execute-sub-format body (init-navigator arg) (:base-args params))) navigator)) (defn- set-indent [params navigator offsets] (let [relative-to (if (:colon params) :current :block)] (pprint-indent relative-to (:n params)) navigator)) ;;; TODO: support ~:T section options for ~T (defn- conditional-newline [params navigator offsets] (let [kind (if (:colon params) (if (:at params) :mandatory :fill) (if (:at params) :miser :linear))] (pprint-newline kind) navigator)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The table of directives we support, each with its params, ;;; properties, and the compilation function ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defdirectives (\A [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} #(format-ascii print-str %1 %2 %3)) (\S [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} #(format-ascii pr-str %1 %2 %3)) (\D [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 10 %1 %2 %3)) (\B [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 2 %1 %2 %3)) (\O [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 8 %1 %2 %3)) (\X [:mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} #(format-integer 16 %1 %2 %3)) (\R [:base [nil js/Number] :mincol [0 js/Number] :padchar [\space js/String] :commachar [\, js/String] :commainterval [3 js/Number]] #{:at :colon :both} {} (do (cond ; ~R is overloaded with bizareness (first (:base params)) #(format-integer (:base %1) %1 %2 %3) (and (:at params) (:colon params)) #(format-old-roman %1 %2 %3) (:at params) #(format-new-roman %1 %2 %3) (:colon params) #(format-ordinal-english %1 %2 %3) true #(format-cardinal-english %1 %2 %3)))) (\P [] #{:at :colon :both} {} (fn [params navigator offsets] (let [navigator (if (:colon params) (relative-reposition navigator -1) navigator) strs (if (:at params) ["y" "ies"] ["" "s"]) [arg navigator] (next-arg navigator)] (print (if (= arg 1) (first strs) (second strs))) navigator))) (\C [:char-format [nil js/String]] #{:at :colon :both} {} (cond (:colon params) pretty-character (:at params) readable-character :else plain-character)) (\F [:w [nil js/Number] :d [nil js/Number] :k [0 js/Number] :overflowchar [nil js/String] :padchar [\space js/String]] #{:at} {} fixed-float) (\E [:w [nil js/Number] :d [nil js/Number] :e [nil js/Number] :k [1 js/Number] :overflowchar [nil js/String] :padchar [\space js/String] :exponentchar [nil js/String]] #{:at} {} exponential-float) (\G [:w [nil js/Number] :d [nil js/Number] :e [nil js/Number] :k [1 js/Number] :overflowchar [nil js/String] :padchar [\space js/String] :exponentchar [nil js/String]] #{:at} {} general-float) (\$ [:d [2 js/Number] :n [1 js/Number] :w [0 js/Number] :padchar [\space js/String]] #{:at :colon :both} {} dollar-float) (\% [:count [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (dotimes [i (:count params)] (prn)) arg-navigator)) (\& [:count [1 js/Number]] #{:pretty} {} (fn [params arg-navigator offsets] (let [cnt (:count params)] (if (pos? cnt) (fresh-line)) (dotimes [i (dec cnt)] (prn))) arg-navigator)) (\| [:count [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (dotimes [i (:count params)] (print \formfeed)) arg-navigator)) (\~ [:n [1 js/Number]] #{} {} (fn [params arg-navigator offsets] (let [n (:n params)] (print (apply str (repeat n \~))) arg-navigator))) (\newline ;; Whitespace supression is handled in the compilation loop [] #{:colon :at} {} (fn [params arg-navigator offsets] (if (:at params) (prn)) arg-navigator)) (\T [:colnum [1 js/Number] :colinc [1 js/Number]] #{:at :pretty} {} (if (:at params) #(relative-tabulation %1 %2 %3) #(absolute-tabulation %1 %2 %3))) (\* [:n [1 js/Number]] #{:colon :at} {} (fn [params navigator offsets] (let [n (:n params)] (if (:at params) (absolute-reposition navigator n) (relative-reposition navigator (if (:colon params) (- n) n)))))) (\? [] #{:at} {} (if (:at params) (fn [params navigator offsets] ; args from main arg list (let [[subformat navigator] (get-format-arg navigator)] (execute-sub-format subformat navigator (:base-args params)))) (fn [params navigator offsets] ; args from sub-list (let [[subformat navigator] (get-format-arg navigator) [subargs navigator] (next-arg navigator) sub-navigator (init-navigator subargs)] (execute-sub-format subformat sub-navigator (:base-args params)) navigator)))) (\( [] #{:colon :at :both} {:right \), :allows-separator nil, :else nil} (let [mod-case-writer (cond (and (:at params) (:colon params)) upcase-writer (:colon params) capitalize-word-writer (:at params) init-cap-writer :else downcase-writer)] #(modify-case mod-case-writer %1 %2 %3))) (\) [] #{} {} nil) (\[ [:selector [nil js/Number]] #{:colon :at} {:right \], :allows-separator true, :else :last} (cond (:colon params) boolean-conditional (:at params) check-arg-conditional true choice-conditional)) (\; [:min-remaining [nil js/Number] :max-columns [nil js/Number]] #{:colon} {:separator true} nil) (\] [] #{} {} nil) (\{ [:max-iterations [nil js/Number]] #{:colon :at :both} {:right \}, :allows-separator false} (cond (and (:at params) (:colon params)) iterate-main-sublists (:colon params) iterate-list-of-sublists (:at params) iterate-main-list true iterate-sublist)) (\} [] #{:colon} {} nil) (\< [:mincol [0 js/Number] :colinc [1 js/Number] :minpad [0 js/Number] :padchar [\space js/String]] #{:colon :at :both :pretty} {:right \>, :allows-separator true, :else :first} logical-block-or-justify) (\> [] #{:colon} {} nil) ;; TODO: detect errors in cases where colon not allowed (\^ [:arg1 [nil js/Number] :arg2 [nil js/Number] :arg3 [nil js/Number]] #{:colon} {} (fn [params navigator offsets] (let [arg1 (:arg1 params) arg2 (:arg2 params) arg3 (:arg3 params) exit (if (:colon params) :colon-up-arrow :up-arrow)] (cond (and arg1 arg2 arg3) (if (<= arg1 arg2 arg3) [exit navigator] navigator) (and arg1 arg2) (if (= arg1 arg2) [exit navigator] navigator) arg1 (if (= arg1 0) [exit navigator] navigator) true ; TODO: handle looking up the arglist stack for info (if (if (:colon params) (empty? (:rest (:base-args params))) (empty? (:rest navigator))) [exit navigator] navigator))))) (\W [] #{:at :colon :both :pretty} {} (if (or (:at params) (:colon params)) (let [bindings (concat (if (:at params) [:level nil :length nil] []) (if (:colon params) [:pretty true] []))] (fn [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (apply write arg bindings) [:up-arrow navigator] navigator)))) (fn [params navigator offsets] (let [[arg navigator] (next-arg navigator)] (if (write-out arg) [:up-arrow navigator] navigator))))) (\_ [] #{:at :colon :both} {} conditional-newline) (\I [:n [0 js/Number]] #{:colon} {} set-indent) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Code to manage the parameters and flags associated with each ;; directive in the format string. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} param-pattern #"^([vV]|#|('.)|([+-]?\d+)|(?=,))") (def ^{:private true} special-params #{:parameter-from-args :remaining-arg-count}) (defn- extract-param [[s offset saw-comma]] (let [m (js/RegExp. (.-source param-pattern) "g") param (.exec m s)] (if param (let [token-str (first param) remainder (subs s (.-lastIndex m)) new-offset (+ offset (.-lastIndex m))] (if (not (= \, (nth remainder 0))) [[token-str offset] [remainder new-offset false]] [[token-str offset] [(subs remainder 1) (inc new-offset) true]])) (if saw-comma (format-error "Badly formed parameters in format directive" offset) [nil [s offset]])))) (defn- extract-params [s offset] (consume extract-param [s offset false])) (defn- translate-param "Translate the string representation of a param to the internalized representation" [[p offset]] [(cond (= (.-length p) 0) nil (and (= (.-length p) 1) (contains? #{\v \V} (nth p 0))) :parameter-from-args (and (= (.-length p) 1) (= \# (nth p 0))) :remaining-arg-count (and (= (.-length p) 2) (= \' (nth p 0))) (nth p 1) true (js/parseInt p 10)) offset]) (def ^{:private true} flag-defs {\: :colon, \@ :at}) (defn- extract-flags [s offset] (consume (fn [[s offset flags]] (if (empty? s) [nil [s offset flags]] (let [flag (get flag-defs (first s))] (if flag (if (contains? flags flag) (format-error (str "Flag \"" (first s) "\" appears more than once in a directive") offset) [true [(subs s 1) (inc offset) (assoc flags flag [true offset])]]) [nil [s offset flags]])))) [s offset {}])) (defn- check-flags [def flags] (let [allowed (:flags def)] (if (and (not (:at allowed)) (:at flags)) (format-error (str "\"@\" is an illegal flag for format directive \"" (:directive def) "\"") (nth (:at flags) 1))) (if (and (not (:colon allowed)) (:colon flags)) (format-error (str "\":\" is an illegal flag for format directive \"" (:directive def) "\"") (nth (:colon flags) 1))) (if (and (not (:both allowed)) (:at flags) (:colon flags)) (format-error (str "Cannot combine \"@\" and \":\" flags for format directive \"" (:directive def) "\"") (min (nth (:colon flags) 1) (nth (:at flags) 1)))))) (defn- map-params "Takes a directive definition and the list of actual parameters and a map of flags and returns a map of the parameters and flags with defaults filled in. We check to make sure that there are the right types and number of parameters as well." [def params flags offset] (check-flags def flags) (if (> (count params) (count (:params def))) (format-error (cl-format nil "Too many parameters for directive \"~C\": ~D~:* ~[were~;was~:;were~] specified but only ~D~:* ~[are~;is~:;are~] allowed" (:directive def) (count params) (count (:params def))) (second (first params)))) (doall (map #(let [val (first %1)] (if (not (or (nil? val) (contains? special-params val) (= (second (second %2)) (type val)))) (format-error (str "Parameter " (name (first %2)) " has bad type in directive \"" (:directive def) "\": " (type val)) (second %1))) ) params (:params def))) (merge ; create the result map (into (array-map) ; start with the default values, make sure the order is right (reverse (for [[name [default]] (:params def)] [name [default offset]]))) (reduce #(apply assoc %1 %2) {} (filter #(first (nth % 1)) (zipmap (keys (:params def)) params))) ; add the specified parameters, filtering out nils flags)); and finally add the flags (defn- compile-directive [s offset] (let [[raw-params [rest offset]] (extract-params s offset) [_ [rest offset flags]] (extract-flags rest offset) directive (first rest) def (get directive-table (string/upper-case directive)) params (if def (map-params def (map translate-param raw-params) flags offset))] (if (not directive) (format-error "Format string ended in the middle of a directive" offset)) (if (not def) (format-error (str "Directive \"" directive "\" is undefined") offset)) [(compiled-directive. ((:generator-fn def) params offset) def params offset) (let [remainder (subs rest 1) offset (inc offset) trim? (and (= \newline (:directive def)) (not (:colon params))) trim-count (if trim? (prefix-count remainder [\space \tab]) 0) remainder (subs remainder trim-count) offset (+ offset trim-count)] [remainder offset])])) (defn- compile-raw-string [s offset] (compiled-directive. (fn [_ a _] (print s) a) nil {:string s} offset)) (defn- right-bracket [this] (:right (:bracket-info (:def this)))) (defn- separator? [this] (:separator (:bracket-info (:def this)))) (defn- else-separator? [this] (and (:separator (:bracket-info (:def this))) (:colon (:params this)))) (declare ^{:arglists '([bracket-info offset remainder])} collect-clauses) (defn- process-bracket [this remainder] (let [[subex remainder] (collect-clauses (:bracket-info (:def this)) (:offset this) remainder)] [(compiled-directive. (:func this) (:def this) (merge (:params this) (tuple-map subex (:offset this))) (:offset this)) remainder])) (defn- process-clause [bracket-info offset remainder] (consume (fn [remainder] (if (empty? remainder) (format-error "No closing bracket found." offset) (let [this (first remainder) remainder (next remainder)] (cond (right-bracket this) (process-bracket this remainder) (= (:right bracket-info) (:directive (:def this))) [ nil [:right-bracket (:params this) nil remainder]] (else-separator? this) [nil [:else nil (:params this) remainder]] (separator? this) [nil [:separator nil nil remainder]] ;; TODO: check to make sure that there are no params on ~; true [this remainder])))) remainder)) (defn- collect-clauses [bracket-info offset remainder] (second (consume (fn [[clause-map saw-else remainder]] (let [[clause [type right-params else-params remainder]] (process-clause bracket-info offset remainder)] (cond (= type :right-bracket) [nil [(merge-with concat clause-map {(if saw-else :else :clauses) [clause] :right-params right-params}) remainder]] (= type :else) (cond (:else clause-map) (format-error "Two else clauses (\"~:;\") inside bracket construction." offset) (not (:else bracket-info)) (format-error "An else clause (\"~:;\") is in a bracket type that doesn't support it." offset) (and (= :first (:else bracket-info)) (seq (:clauses clause-map))) (format-error "The else clause (\"~:;\") is only allowed in the first position for this directive." offset) true ; if the ~:; is in the last position, the else clause ; is next, this was a regular clause (if (= :first (:else bracket-info)) [true [(merge-with concat clause-map {:else [clause] :else-params else-params}) false remainder]] [true [(merge-with concat clause-map {:clauses [clause]}) true remainder]])) (= type :separator) (cond saw-else (format-error "A plain clause (with \"~;\") follows an else clause (\"~:;\") inside bracket construction." offset) (not (:allows-separator bracket-info)) (format-error "A separator (\"~;\") is in a bracket type that doesn't support it." offset) true [true [(merge-with concat clause-map {:clauses [clause]}) false remainder]])))) [{:clauses []} false remainder]))) (defn- process-nesting "Take a linearly compiled format and process the bracket directives to give it the appropriate tree structure" [format] (first (consume (fn [remainder] (let [this (first remainder) remainder (next remainder) bracket (:bracket-info (:def this))] (if (:right bracket) (process-bracket this remainder) [this remainder]))) format))) (defn- compile-format "Compiles format-str into a compiled format which can be used as an argument to cl-format just like a plain format string. Use this function for improved performance when you're using the same format string repeatedly" [format-str] (binding [*format-str* format-str] (process-nesting (first (consume (fn [[s offset]] (if (empty? s) [nil s] (let [tilde (.indexOf s \~)] (cond (neg? tilde) [(compile-raw-string s offset) ["" (+ offset (.-length s))]] (zero? tilde) (compile-directive (subs s 1) (inc offset)) true [(compile-raw-string (subs s 0 tilde) offset) [(subs s tilde) (+ tilde offset)]])))) [format-str 0]))))) (defn- needs-pretty "determine whether a given compiled format has any directives that depend on the column number or pretty printing" [format] (loop [format format] (if (empty? format) false (if (or (:pretty (:flags (:def (first format)))) (some needs-pretty (first (:clauses (:params (first format))))) (some needs-pretty (first (:else (:params (first format)))))) true (recur (next format)))))) ;;NB We depart from the original api. In clj, if execute-format is called multiple times with the same stream or ;; called on *out*, the results are different than if the same calls are made with different streams or printing ;; to a string. The reason is that mutating the underlying stream changes the result by changing spacing. ;; ;; clj: ;; * stream => "1 2 3" ;; * true (prints to *out*) => "1 2 3" ;; * nil (prints to string) => "1 2 3" ;; cljs: ;; * stream => "1 2 3" ;; * true (prints via *print-fn*) => "1 2 3" ;; * nil (prints to string) => "1 2 3" (defn- execute-format "Executes the format with the arguments." {:skip-wiki true} ([stream format args] (let [sb (StringBuffer.) real-stream (if (or (not stream) (true? stream)) (StringBufferWriter. sb) stream) wrapped-stream (if (and (needs-pretty format) (not (pretty-writer? real-stream))) (get-pretty-writer real-stream) real-stream)] (binding [*out* wrapped-stream] (try (execute-format format args) (finally (if-not (identical? real-stream wrapped-stream) (-flush wrapped-stream)))) (cond (not stream) (str sb) (true? stream) (string-print (str sb)) :else nil)))) ([format args] (map-passing-context (fn [element context] (if (abort? context) [nil context] (let [[params args] (realize-parameter-list (:params element) context) [params offsets] (unzip-map params) params (assoc params :base-args args)] [nil (apply (:func element) [params args offsets])]))) args format) nil)) ;;; This is a bad idea, but it prevents us from leaking private symbols ;;; This should all be replaced by really compiled formats anyway. (def ^{:private true} cached-compile (memoize compile-format)) ;;====================================================================== ;; dispatch.clj ;;====================================================================== (defn- use-method "Installs a function as a new method of multimethod associated with dispatch-value. " [multifn dispatch-val func] (-add-method multifn dispatch-val func)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implementations of specific dispatch table entries ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Handle forms that can be "back-translated" to reader macros ;;; Not all reader macros can be dealt with this way or at all. ;;; Macros that we can't deal with at all are: ;;; ; - The comment character is absorbed by the reader and never is part of the form ;;; ` - Is fully processed at read time into a lisp expression (which will contain concats ;;; and regular quotes). ;;; ~@ - Also fully eaten by the processing of ` and can't be used outside. ;;; , - is whitespace and is lost (like all other whitespace). Formats can generate commas ;;; where they deem them useful to help readability. ;;; ^ - Adding metadata completely disappears at read time and the data appears to be ;;; completely lost. ;;; ;;; Most other syntax stuff is dealt with directly by the formats (like (), [], {}, and #{}) ;;; or directly by printing the objects using Clojure's built-in print functions (like ;;; :keyword, \char, or ""). The notable exception is #() which is special-cased. (def ^{:private true} reader-macros {'quote "'" 'var "#'" 'clojure.core/deref "@", 'clojure.core/unquote "~" 'cljs.core/deref "@", 'cljs.core/unquote "~"}) (defn- pprint-reader-macro [alis] (let [macro-char (reader-macros (first alis))] (when (and macro-char (= 2 (count alis))) (-write *out* macro-char) (write-out (second alis)) true))) ;;====================================================================== ;; Dispatch for the basic data types when interpreted ;; as data (as opposed to code). ;;====================================================================== ;;; TODO: inline these formatter statements into funcs so that we ;;; are a little easier on the stack. (Or, do "real" compilation, a ;;; la Common Lisp) ;;; (def pprint-simple-list (formatter-out "~:<~@{~w~^ ~_~}~:>")) (defn- pprint-simple-list [alis] (pprint-logical-block :prefix "(" :suffix ")" (print-length-loop [alis (seq alis)] (when alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (recur (next alis))))))) (defn- pprint-list [alis] (if-not (pprint-reader-macro alis) (pprint-simple-list alis))) ;;; (def pprint-vector (formatter-out "~<[~;~@{~w~^ ~_~}~;]~:>")) (defn- pprint-vector [avec] (pprint-logical-block :prefix "[" :suffix "]" (print-length-loop [aseq (seq avec)] (when aseq (write-out (first aseq)) (when (next aseq) (-write *out* " ") (pprint-newline :linear) (recur (next aseq))))))) (def ^{:private true} pprint-array (formatter-out "~<[~;~@{~w~^, ~:_~}~;]~:>")) ;;; (def pprint-map (formatter-out "~<{~;~@{~<~w~^ ~_~w~:>~^, ~_~}~;}~:>")) (defn- pprint-map [amap] (let [[ns lift-map] (when (not (record? amap)) (#'cljs.core/lift-ns amap)) amap (or lift-map amap) prefix (if ns (str "#:" ns "{") "{")] (pprint-logical-block :prefix prefix :suffix "}" (print-length-loop [aseq (seq amap)] (when aseq ;;compiler gets confused with nested macro if it isn't namespaced ;;it tries to use clojure.pprint/pprint-logical-block for some reason (m/pprint-logical-block (write-out (ffirst aseq)) (-write *out* " ") (pprint-newline :linear) (set! *current-length* 0) ;always print both parts of the [k v] pair (write-out (fnext (first aseq)))) (when (next aseq) (-write *out* ", ") (pprint-newline :linear) (recur (next aseq)))))))) (defn- pprint-simple-default [obj] ;;TODO: Update to handle arrays (?) and suppressing namespaces (-write *out* (pr-str obj))) (def pprint-set (formatter-out "~<#{~;~@{~w~^ ~:_~}~;}~:>")) (def ^{:private true} type-map {"core$future_call" "Future", "core$promise" "Promise"}) (defn- map-ref-type "Map ugly type names to something simpler" [name] (or (when-let [match (re-find #"^[^$]+\$[^$]+" name)] (type-map match)) name)) (defn- pprint-ideref [o] (let [prefix (str "#<" (map-ref-type (.-name (type o))) "@" (goog/getUid o) ": ")] (pprint-logical-block :prefix prefix :suffix ">" (pprint-indent :block (-> (count prefix) (- 2) -)) (pprint-newline :linear) (write-out (if (and (satisfies? IPending o) (not (-realized? o))) :not-delivered @o))))) (def ^{:private true} pprint-pqueue (formatter-out "~<<-(~;~@{~w~^ ~_~}~;)-<~:>")) (defn- type-dispatcher [obj] (cond (instance? PersistentQueue obj) :queue (satisfies? IDeref obj) :deref (symbol? obj) :symbol (seq? obj) :list (map? obj) :map (vector? obj) :vector (set? obj) :set (nil? obj) nil :default :default)) (defmulti simple-dispatch "The pretty print dispatch function for simple data structure format." type-dispatcher) (use-method simple-dispatch :list pprint-list) (use-method simple-dispatch :vector pprint-vector) (use-method simple-dispatch :map pprint-map) (use-method simple-dispatch :set pprint-set) (use-method simple-dispatch nil #(-write *out* (pr-str nil))) (use-method simple-dispatch :default pprint-simple-default) (set-pprint-dispatch simple-dispatch) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Dispatch for the code table ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare ^{:arglists '([alis])} pprint-simple-code-list) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format the namespace ("ns") macro. This is quite complicated because of all the ;;; different forms supported and because programmers can choose lists or vectors ;;; in various places. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- brackets "Figure out which kind of brackets to use" [form] (if (vector? form) ["[" "]"] ["(" ")"])) (defn- pprint-ns-reference "Pretty print a single reference (import, use, etc.) from a namespace decl" [reference] (if (sequential? reference) (let [[start end] (brackets reference) [keyw & args] reference] (pprint-logical-block :prefix start :suffix end ((formatter-out "~w~:i") keyw) (loop [args args] (when (seq args) ((formatter-out " ")) (let [arg (first args)] (if (sequential? arg) (let [[start end] (brackets arg)] (pprint-logical-block :prefix start :suffix end (if (and (= (count arg) 3) (keyword? (second arg))) (let [[ns kw lis] arg] ((formatter-out "~w ~w ") ns kw) (if (sequential? lis) ((formatter-out (if (vector? lis) "~<[~;~@{~w~^ ~:_~}~;]~:>" "~<(~;~@{~w~^ ~:_~}~;)~:>")) lis) (write-out lis))) (apply (formatter-out "~w ~:i~@{~w~^ ~:_~}") arg))) (when (next args) ((formatter-out "~_")))) (do (write-out arg) (when (next args) ((formatter-out "~:_")))))) (recur (next args)))))) (write-out reference))) (defn- pprint-ns "The pretty print dispatch chunk for the ns macro" [alis] (if (next alis) (let [[ns-sym ns-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map references] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block :prefix "(" :suffix ")" ((formatter-out "~w ~1I~@_~w") ns-sym ns-name) (when (or doc-str attr-map (seq references)) ((formatter-out "~@:_"))) (when doc-str (cl-format true "\"~a\"~:[~;~:@_~]" doc-str (or attr-map (seq references)))) (when attr-map ((formatter-out "~w~:[~;~:@_~]") attr-map (seq references))) (loop [references references] (pprint-ns-reference (first references)) (when-let [references (next references)] (pprint-newline :linear) (recur references))))) (write-out alis))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format something that looks like a simple def (sans metadata, since the reader ;;; won't give it to us now). ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} pprint-hold-first (formatter-out "~:<~w~^ ~@_~w~^ ~_~@{~w~^ ~_~}~:>")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format something that looks like a defn or defmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format the params and body of a defn with a single arity (defn- single-defn [alis has-doc-str?] (if (seq alis) (do (if has-doc-str? ((formatter-out " ~_")) ((formatter-out " ~@_"))) ((formatter-out "~{~w~^ ~_~}") alis)))) ;;; Format the param and body sublists of a defn with multiple arities (defn- multi-defn [alis has-doc-str?] (if (seq alis) ((formatter-out " ~_~{~w~^ ~_~}") alis))) ;;; TODO: figure out how to support capturing metadata in defns (we might need a ;;; special reader) (defn- pprint-defn [alis] (if (next alis) (let [[defn-sym defn-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map stuff] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block :prefix "(" :suffix ")" ((formatter-out "~w ~1I~@_~w") defn-sym defn-name) (if doc-str ((formatter-out " ~_~w") doc-str)) (if attr-map ((formatter-out " ~_~w") attr-map)) ;; Note: the multi-defn case will work OK for malformed defns too (cond (vector? (first stuff)) (single-defn stuff (or doc-str attr-map)) :else (multi-defn stuff (or doc-str attr-map))))) (pprint-simple-code-list alis))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format something with a binding form ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- pprint-binding-form [binding-vec] (pprint-logical-block :prefix "[" :suffix "]" (print-length-loop [binding binding-vec] (when (seq binding) (pprint-logical-block binding (write-out (first binding)) (when (next binding) (-write *out* " ") (pprint-newline :miser) (write-out (second binding)))) (when (next (rest binding)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest binding)))))))) (defn- pprint-let [alis] (let [base-sym (first alis)] (pprint-logical-block :prefix "(" :suffix ")" (if (and (next alis) (vector? (second alis))) (do ((formatter-out "~w ~1I~@_") base-sym) (pprint-binding-form (second alis)) ((formatter-out " ~_~{~w~^ ~_~}") (next (rest alis)))) (pprint-simple-code-list alis))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Format something that looks like "if" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:private true} pprint-if (formatter-out "~:<~1I~w~^ ~@_~w~@{ ~_~w~}~:>")) (defn- pprint-cond [alis] (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (print-length-loop [alis (next alis)] (when alis (pprint-logical-block alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :miser) (write-out (second alis)))) (when (next (rest alis)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest alis))))))))) (defn- pprint-condp [alis] (if (> (count alis) 3) (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (apply (formatter-out "~w ~@_~w ~@_~w ~_") alis) (print-length-loop [alis (seq (drop 3 alis))] (when alis (pprint-logical-block alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :miser) (write-out (second alis)))) (when (next (rest alis)) (-write *out* " ") (pprint-newline :linear) (recur (next (rest alis))))))) (pprint-simple-code-list alis))) ;;; The map of symbols that are defined in an enclosing #() anonymous function (def ^:dynamic ^{:private true} *symbol-map* {}) (defn- pprint-anon-func [alis] (let [args (second alis) nlis (first (rest (rest alis)))] (if (vector? args) (binding [*symbol-map* (if (= 1 (count args)) {(first args) "%"} (into {} (map #(vector %1 (str \% %2)) args (range 1 (inc (count args))))))] ((formatter-out "~<#(~;~@{~w~^ ~_~}~;)~:>") nlis)) (pprint-simple-code-list alis)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The master definitions for formatting lists in code (that is, (fn args...) or ;;; special forms). ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; This is the equivalent of (formatter-out "~:<~1I~@{~w~^ ~_~}~:>"), but is ;;; easier on the stack. (defn- pprint-simple-code-list [alis] (pprint-logical-block :prefix "(" :suffix ")" (pprint-indent :block 1) (print-length-loop [alis (seq alis)] (when alis (write-out (first alis)) (when (next alis) (-write *out* " ") (pprint-newline :linear) (recur (next alis))))))) ;;; Take a map with symbols as keys and add versions with no namespace. ;;; That is, if ns/sym->val is in the map, add sym->val to the result. (defn- two-forms [amap] (into {} (mapcat identity (for [x amap] [x [(symbol (name (first x))) (second x)]])))) (defn- add-core-ns [amap] (let [core "clojure.core"] (into {} (map #(let [[s f] %] (if (not (or (namespace s) (special-symbol? s))) [(symbol core (name s)) f] %)) amap)))) (def ^:dynamic ^{:private true} *code-table* (two-forms (add-core-ns {'def pprint-hold-first, 'defonce pprint-hold-first, 'defn pprint-defn, 'defn- pprint-defn, 'defmacro pprint-defn, 'fn pprint-defn, 'let pprint-let, 'loop pprint-let, 'binding pprint-let, 'with-local-vars pprint-let, 'with-open pprint-let, 'when-let pprint-let, 'if-let pprint-let, 'doseq pprint-let, 'dotimes pprint-let, 'when-first pprint-let, 'if pprint-if, 'if-not pprint-if, 'when pprint-if, 'when-not pprint-if, 'cond pprint-cond, 'condp pprint-condp, 'fn* pprint-anon-func, '. pprint-hold-first, '.. pprint-hold-first, '-> pprint-hold-first, 'locking pprint-hold-first, 'struct pprint-hold-first, 'struct-map pprint-hold-first, 'ns pprint-ns }))) (defn- pprint-code-list [alis] (if-not (pprint-reader-macro alis) (if-let [special-form (*code-table* (first alis))] (special-form alis) (pprint-simple-code-list alis)))) (defn- pprint-code-symbol [sym] (if-let [arg-num (sym *symbol-map*)] (print arg-num) (if *print-suppress-namespaces* (print (name sym)) (pr sym)))) (defmulti code-dispatch "The pretty print dispatch function for pretty printing Clojure code." {:added "1.2" :arglists '[[object]]} type-dispatcher) (use-method code-dispatch :list pprint-code-list) (use-method code-dispatch :symbol pprint-code-symbol) ;; The following are all exact copies of simple-dispatch (use-method code-dispatch :vector pprint-vector) (use-method code-dispatch :map pprint-map) (use-method code-dispatch :set pprint-set) (use-method code-dispatch :queue pprint-pqueue) (use-method code-dispatch :deref pprint-ideref) (use-method code-dispatch nil pr) (use-method code-dispatch :default pprint-simple-default) (set-pprint-dispatch simple-dispatch) ;;; For testing (comment (with-pprint-dispatch code-dispatch (pprint '(defn cl-format "An implementation of a Common Lisp compatible format function" [stream format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format stream compiled-format navigator))))) (with-pprint-dispatch code-dispatch (pprint '(defn cl-format [stream format-in & args] (let [compiled-format (if (string? format-in) (compile-format format-in) format-in) navigator (init-navigator args)] (execute-format stream compiled-format navigator))))) (with-pprint-dispatch code-dispatch (pprint '(defn- -write ([this x] (condp = (class x) String (let [s0 (write-initial-lines this x) s (.replaceFirst s0 "\\s+$" "") white-space (.substring s0 (count s)) mode (getf :mode)] (if (= mode :writing) (dosync (write-white-space this) (.col_write this s) (setf :trailing-white-space white-space)) (add-to-buffer this (make-buffer-blob s white-space)))) Integer (let [c ^Character x] (if (= (getf :mode) :writing) (do (write-white-space this) (.col_write this x)) (if (= c (int \newline)) (write-initial-lines this "\n") (add-to-buffer this (make-buffer-blob (str (char c)) nil)))))))))) (with-pprint-dispatch code-dispatch (pprint '(defn pprint-defn [writer alis] (if (next alis) (let [[defn-sym defn-name & stuff] alis [doc-str stuff] (if (string? (first stuff)) [(first stuff) (next stuff)] [nil stuff]) [attr-map stuff] (if (map? (first stuff)) [(first stuff) (next stuff)] [nil stuff])] (pprint-logical-block writer :prefix "(" :suffix ")" (cl-format true "~w ~1I~@_~w" defn-sym defn-name) (if doc-str (cl-format true " ~_~w" doc-str)) (if attr-map (cl-format true " ~_~w" attr-map)) ;; Note: the multi-defn case will work OK for malformed defns too (cond (vector? (first stuff)) (single-defn stuff (or doc-str attr-map)) :else (multi-defn stuff (or doc-str attr-map))))) (pprint-simple-code-list writer alis))))) ) ;;====================================================================== ;; print_table.clj ;;====================================================================== (defn- add-padding [width s] (let [padding (max 0 (- width (count s)))] (apply str (clojure.string/join (repeat padding \space)) s))) (defn print-table "Prints a collection of maps in a textual table. Prints table headings ks, and then a line of output for each row, corresponding to the keys in ks. If ks are not specified, use the keys of the first item in rows." {:added "1.3"} ([ks rows] (when (seq rows) (let [widths (map (fn [k] (apply max (count (str k)) (map #(count (str (get % k))) rows))) ks) spacers (map #(apply str (repeat % "-")) widths) fmt-row (fn [leader divider trailer row] (str leader (apply str (interpose divider (for [[col width] (map vector (map #(get row %) ks) widths)] (add-padding width (str col))))) trailer))] (cljs.core/println) (cljs.core/println (fmt-row "| " " | " " |" (zipmap ks ks))) (cljs.core/println (fmt-row "|-" "-+-" "-|" (zipmap ks spacers))) (doseq [row rows] (cljs.core/println (fmt-row "| " " | " " |" row)))))) ([rows] (print-table (keys (first rows)) rows)))
[ { "context": " #fhir/code\"text/cql\"\n :data #fhir/base64Binary\"bGlicmFyeSBSZXRyaWV2ZQp1c2luZyBGSElSIHZlcnNpb24gJzQuMC4wJwppbmNsdWRlIEZISVJIZWxwZXJzIHZlcnNpb24gJzQuMC4wJwoKY29udGV4dCBQYXRpZW50CgpkZWZpbmUgSW5Jbml0aWFsUG9wdWxhdGlvbjoKICB0cnVlCgpkZWZpbmUgR2VuZGVyOgogIFBhdGllbnQuZ2VuZGVyCg==\"})\n\n\n(deftest handler-test\n (testing \"Returns Not", "end": 2021, "score": 0.9978246688842773, "start": 1796, "tag": "KEY", "value": "bGlicmFyeSBSZXRyaWV2ZQp1c2luZyBGSElSIHZlcnNpb24gJzQuMC4wJwppbmNsdWRlIEZISVJIZWxwZXJzIHZlcnNpb24gJzQuMC4wJwoKY29udGV4dCBQYXRpZW50CgpkZWZpbmUgSW5Jbml0aWFsUG9wdWxhdGlvbjoKICB0cnVlCgpkZWZpbmUgR2VuZGVyOgogIFBhdGllbnQuZ2VuZGVyCg==\"" }, { "context": " :data #fhir/base64Binary\"bGlicmFyeSBSZXRyaWV2ZQp1c2luZyBGSElSIHZlcnNpb24gJzQuMC4wJwp", "end": 10391, "score": 0.6963821053504944, "start": 10383, "tag": "KEY", "value": "GlicmFye" }, { "context": " :data #fhir/base64Binary\"bGlicmFyeSBSZXRyaWV2ZQp1c2luZyBGSElSIHZlcnNpb24gJzQuMC4wJwppbmNsdWRlIEZISVJ", "end": 10407, "score": 0.8709503412246704, "start": 10397, "tag": "KEY", "value": "yaWV2ZQp1c" }, { "context": "data #fhir/base64Binary\"bGlicmFyeSBSZXRyaWV2ZQp1c2luZyBGSElSIHZlcnNpb24gJzQuMC4wJwppbmNsdWRlIEZISVJIZW", "end": 10410, "score": 0.6781713366508484, "start": 10408, "tag": "KEY", "value": "lu" }, { "context": " #fhir/base64Binary\"bGlicmFyeSBSZXRyaWV2ZQp1c2luZyBGSElSIHZlcnNpb24gJzQuMC4wJwppbmNsdWRlIEZISVJIZWxwZXJzIHZlcnNpb24gJzQuMC4wJwoKY29udGV4dCBQYXRpZW50CgpkZWZpbmUgSW5Jbml0aWFsUG9wdWxhdGlvbjoKICBQYXRpZW50LmdlbmRlciA9ICdtYWxlJwo=\"}]}]\n [:put\n ", "end": 10587, "score": 0.9482428431510925, "start": 10412, "tag": "KEY", "value": "BGSElSIHZlcnNpb24gJzQuMC4wJwppbmNsdWRlIEZISVJIZWxwZXJzIHZlcnNpb24gJzQuMC4wJwoKY29udGV4dCBQYXRpZW50CgpkZWZpbmUgSW5Jbml0aWFsUG9wdWxhdGlvbjoKICBQYXRpZW50LmdlbmRlciA9ICdtYWxlJwo=\"" } ]
modules/operation-measure-evaluate-measure/test/blaze/fhir/operation/evaluate_measure/handler/impl_test.clj
sencode/blaze
1
(ns blaze.fhir.operation.evaluate-measure.handler.impl-test (:require [blaze.db.api-stub :refer [mem-node-with]] [blaze.executors :as ex] [blaze.fhir.operation.evaluate-measure.handler.impl :refer [handler]] [blaze.fhir.spec.type :as type] [blaze.log] [blaze.luid :refer [luid]] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [deftest is testing]] [juxt.iota :refer [given]] [reitit.core :as reitit] [taoensso.timbre :as log]) (:import [java.time Clock Instant Year ZoneOffset])) (defn- fixture [f] (st/instrument) (log/set-level! :trace) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def clock (Clock/fixed Instant/EPOCH (ZoneOffset/ofHours 1))) (defonce executor (ex/single-thread-executor)) (def router (reitit/router [["/Patient/{id}" {:name :Patient/instance}] ["/MeasureReport/{id}/_history/{vid}" {:name :MeasureReport/versioned-instance}]] {:syntax :bracket})) (defn- handler-with [txs] (fn [request] (with-open [node (mem-node-with txs)] @((handler clock node executor) request)))) (defn- scoring-concept [code] {:fhir/type :fhir/CodeableConcept :coding [{:fhir/type :fhir/Coding :system #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-scoring" :code (type/->Code code)}]}) (defn- population-concept [code] {:fhir/type :fhir/CodeableConcept :coding [{:fhir/type :fhir/Coding :system #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" :code (type/->Code code)}]}) (defn- cql-expression [expr] {:fhir/type :fhir/Expression :language #fhir/code"text/cql" :expression expr}) (def library-content {:fhir/type :fhir/Attachment :contentType #fhir/code"text/cql" :data #fhir/base64Binary"bGlicmFyeSBSZXRyaWV2ZQp1c2luZyBGSElSIHZlcnNpb24gJzQuMC4wJwppbmNsdWRlIEZISVJIZWxwZXJzIHZlcnNpb24gJzQuMC4wJwoKY29udGV4dCBQYXRpZW50CgpkZWZpbmUgSW5Jbml0aWFsUG9wdWxhdGlvbjoKICB0cnVlCgpkZWZpbmUgR2VuZGVyOgogIFBhdGllbnQuZ2VuZGVyCg=="}) (deftest handler-test (testing "Returns Not Found on Non-Existing Measure" (testing "on type endpoint" (let [{:keys [status body]} ((handler-with []) {:path-params {:id "0"}})] (is (= 404 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"not-found"))) (testing "on instance endpoint" (let [{:keys [status body]} ((handler-with []) {:params {"measure" "url-181501"}})] (is (= 404 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"not-found")))) (testing "Returns Gone on Deleted Resource" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0"}]] [[:delete "Measure" "0"]]]) {:path-params {:id "0"}})] (is (= 410 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"deleted"))) (testing "invalid report type" (let [{:keys [status body]} ((handler-with []) {:request-method :get :params {"measure" "url-181501" "reportType" "<invalid>"}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "The reportType `<invalid>` is invalid. Please use one of `subject`, `subject-list` or `population`."))) (testing "report type of subject-list is not possible with a GET request" (let [{:keys [status body]} ((handler-with []) {:request-method :get :params {"measure" "url-181501" "reportType" "subject-list"}})] (is (= 422 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"not-supported" :diagnostics := "The reportType `subject-list` is not supported for GET requests. Please use POST."))) (testing "measure without library" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-182126"}]]]) {::reitit/router router :params {"measure" "url-182126" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 422 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"not-supported" :diagnostics := "Missing primary library. Currently only CQL expressions together with one primary library are supported." [:expression first] := "Measure.library"))) (testing "measure with non-existing library" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"]}]]]) {::reitit/router router :params {"measure" "url-181501" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "Can't find the library with canonical URI `library-url-094115`." [:expression first] := "Measure.library"))) (testing "missing content in library" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-182104" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115"}]]]) {::reitit/router router :params {"measure" "url-182104" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "Missing content in library with id `0`." [:expression first] := "Library.content"))) (testing "non text/cql content type" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-182051" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [{:fhir/type :fhir/Attachment :contentType #fhir/code"text/plain"}]}]]]) {::reitit/router router :params {"measure" "url-182051" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "Non `text/cql` content type of `text/plain` of first attachment in library with id `0`." [:expression first] := "Library.content[0].contentType"))) (testing "missing data in library content" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-182039" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [{:fhir/type :fhir/Attachment :contentType #fhir/code"text/cql"}]}]]]) {::reitit/router router :params {"measure" "url-182039" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "Missing embedded data of first attachment in library with id `0`." [:expression first] := "Library.content[0].data"))) (testing "Success" (testing "on type endpoint" (testing "as GET request" (testing "cohort scoring" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"] :scoring (scoring-concept "cohort") :group [{:fhir/type :fhir.Measure/group :population [{:fhir/type :fhir.Measure.group/population :code (population-concept "initial-population") :criteria (cql-expression "InInitialPopulation")}]}]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [{:fhir/type :fhir/Attachment :contentType #fhir/code"text/cql" :data #fhir/base64Binary"bGlicmFyeSBSZXRyaWV2ZQp1c2luZyBGSElSIHZlcnNpb24gJzQuMC4wJwppbmNsdWRlIEZISVJIZWxwZXJzIHZlcnNpb24gJzQuMC4wJwoKY29udGV4dCBQYXRpZW50CgpkZWZpbmUgSW5Jbml0aWFsUG9wdWxhdGlvbjoKICBQYXRpZW50LmdlbmRlciA9ICdtYWxlJwo="}]}] [:put {:fhir/type :fhir/Patient :id "0" :gender #fhir/code"male"}]]]) {::reitit/router router :request-method :get :params {"measure" "url-181501" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 200 status)) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015" [:group 0 :population 0 :code :coding 0 :system] := #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" [:group 0 :population 0 :code :coding 0 :code] := #fhir/code"initial-population" [:group 0 :population 0 :count] := 1))) (testing "cohort scoring with stratifiers" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"] :scoring (scoring-concept "cohort") :group [{:fhir/type :fhir.Measure/group :population [{:fhir/type :fhir.Measure.group/population :code (population-concept "initial-population") :criteria (cql-expression "InInitialPopulation")}] :stratifier [{:fhir/type :fhir.Measure.group/stratifier :code {:fhir/type :fhir/CodeableConcept :text "gender"} :criteria (cql-expression "Gender")}]}]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [library-content]}] [:put {:fhir/type :fhir/Patient :id "0" :gender #fhir/code"male"}] [:put {:fhir/type :fhir/Patient :id "1" :gender #fhir/code"female"}] [:put {:fhir/type :fhir/Patient :id "2" :gender #fhir/code"female"}]]]) {::reitit/router router :request-method :get :params {"measure" "url-181501" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 200 status)) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015" [:group 0 :population 0 :code :coding 0 :system] := #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" [:group 0 :population 0 :code :coding 0 :code] := #fhir/code"initial-population" [:group 0 :population 0 :count] := 3 [:group 0 :stratifier 0 :code 0 :text] := "gender" [:group 0 :stratifier 0 :stratum 0 :population 0 :code :coding 0 :system] := #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" [:group 0 :stratifier 0 :stratum 0 :population 0 :code :coding 0 :code] := #fhir/code"initial-population" [:group 0 :stratifier 0 :stratum 0 :population 0 :count] := 2 [:group 0 :stratifier 0 :stratum 0 :value :text] := "female" [:group 0 :stratifier 0 :stratum 1 :population 0 :code :coding 0 :system] := #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" [:group 0 :stratifier 0 :stratum 1 :population 0 :code :coding 0 :code] := #fhir/code"initial-population" [:group 0 :stratifier 0 :stratum 1 :population 0 :count] := 1 [:group 0 :stratifier 0 :stratum 1 :value :text] := "male")))) (testing "as POST request" (with-redefs [luid (constantly "C5OC2PO45UVYCD2A")] (let [{:keys [status headers body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [library-content]}]]]) {::reitit/router router :request-method :post :params {"measure" "url-181501" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 201 status)) (testing "Location header" (is (= "/MeasureReport/C5OC2PO45UVYCD2A/_history/2" (get headers "Location")))) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015"))))) (testing "on instance endpoint" (testing "as GET request" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [library-content]}]]]) {::reitit/router router :request-method :get :path-params {:id "0"} :params {"periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 200 status)) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015"))) (testing "as POST request" (with-redefs [luid (constantly "C5OC2QYKLM577GLL")] (let [{:keys [status headers body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [library-content]}]]]) {::reitit/router router :request-method :post :path-params {:id "0"} :params {"periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 201 status)) (testing "Location header" (is (= "/MeasureReport/C5OC2QYKLM577GLL/_history/2" (get headers "Location")))) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015")))))))
17965
(ns blaze.fhir.operation.evaluate-measure.handler.impl-test (:require [blaze.db.api-stub :refer [mem-node-with]] [blaze.executors :as ex] [blaze.fhir.operation.evaluate-measure.handler.impl :refer [handler]] [blaze.fhir.spec.type :as type] [blaze.log] [blaze.luid :refer [luid]] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [deftest is testing]] [juxt.iota :refer [given]] [reitit.core :as reitit] [taoensso.timbre :as log]) (:import [java.time Clock Instant Year ZoneOffset])) (defn- fixture [f] (st/instrument) (log/set-level! :trace) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def clock (Clock/fixed Instant/EPOCH (ZoneOffset/ofHours 1))) (defonce executor (ex/single-thread-executor)) (def router (reitit/router [["/Patient/{id}" {:name :Patient/instance}] ["/MeasureReport/{id}/_history/{vid}" {:name :MeasureReport/versioned-instance}]] {:syntax :bracket})) (defn- handler-with [txs] (fn [request] (with-open [node (mem-node-with txs)] @((handler clock node executor) request)))) (defn- scoring-concept [code] {:fhir/type :fhir/CodeableConcept :coding [{:fhir/type :fhir/Coding :system #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-scoring" :code (type/->Code code)}]}) (defn- population-concept [code] {:fhir/type :fhir/CodeableConcept :coding [{:fhir/type :fhir/Coding :system #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" :code (type/->Code code)}]}) (defn- cql-expression [expr] {:fhir/type :fhir/Expression :language #fhir/code"text/cql" :expression expr}) (def library-content {:fhir/type :fhir/Attachment :contentType #fhir/code"text/cql" :data #fhir/base64Binary"<KEY>}) (deftest handler-test (testing "Returns Not Found on Non-Existing Measure" (testing "on type endpoint" (let [{:keys [status body]} ((handler-with []) {:path-params {:id "0"}})] (is (= 404 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"not-found"))) (testing "on instance endpoint" (let [{:keys [status body]} ((handler-with []) {:params {"measure" "url-181501"}})] (is (= 404 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"not-found")))) (testing "Returns Gone on Deleted Resource" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0"}]] [[:delete "Measure" "0"]]]) {:path-params {:id "0"}})] (is (= 410 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"deleted"))) (testing "invalid report type" (let [{:keys [status body]} ((handler-with []) {:request-method :get :params {"measure" "url-181501" "reportType" "<invalid>"}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "The reportType `<invalid>` is invalid. Please use one of `subject`, `subject-list` or `population`."))) (testing "report type of subject-list is not possible with a GET request" (let [{:keys [status body]} ((handler-with []) {:request-method :get :params {"measure" "url-181501" "reportType" "subject-list"}})] (is (= 422 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"not-supported" :diagnostics := "The reportType `subject-list` is not supported for GET requests. Please use POST."))) (testing "measure without library" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-182126"}]]]) {::reitit/router router :params {"measure" "url-182126" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 422 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"not-supported" :diagnostics := "Missing primary library. Currently only CQL expressions together with one primary library are supported." [:expression first] := "Measure.library"))) (testing "measure with non-existing library" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"]}]]]) {::reitit/router router :params {"measure" "url-181501" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "Can't find the library with canonical URI `library-url-094115`." [:expression first] := "Measure.library"))) (testing "missing content in library" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-182104" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115"}]]]) {::reitit/router router :params {"measure" "url-182104" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "Missing content in library with id `0`." [:expression first] := "Library.content"))) (testing "non text/cql content type" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-182051" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [{:fhir/type :fhir/Attachment :contentType #fhir/code"text/plain"}]}]]]) {::reitit/router router :params {"measure" "url-182051" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "Non `text/cql` content type of `text/plain` of first attachment in library with id `0`." [:expression first] := "Library.content[0].contentType"))) (testing "missing data in library content" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-182039" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [{:fhir/type :fhir/Attachment :contentType #fhir/code"text/cql"}]}]]]) {::reitit/router router :params {"measure" "url-182039" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "Missing embedded data of first attachment in library with id `0`." [:expression first] := "Library.content[0].data"))) (testing "Success" (testing "on type endpoint" (testing "as GET request" (testing "cohort scoring" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"] :scoring (scoring-concept "cohort") :group [{:fhir/type :fhir.Measure/group :population [{:fhir/type :fhir.Measure.group/population :code (population-concept "initial-population") :criteria (cql-expression "InInitialPopulation")}]}]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [{:fhir/type :fhir/Attachment :contentType #fhir/code"text/cql" :data #fhir/base64Binary"b<KEY>SBSZXR<KEY>2<KEY>Zy<KEY>}]}] [:put {:fhir/type :fhir/Patient :id "0" :gender #fhir/code"male"}]]]) {::reitit/router router :request-method :get :params {"measure" "url-181501" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 200 status)) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015" [:group 0 :population 0 :code :coding 0 :system] := #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" [:group 0 :population 0 :code :coding 0 :code] := #fhir/code"initial-population" [:group 0 :population 0 :count] := 1))) (testing "cohort scoring with stratifiers" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"] :scoring (scoring-concept "cohort") :group [{:fhir/type :fhir.Measure/group :population [{:fhir/type :fhir.Measure.group/population :code (population-concept "initial-population") :criteria (cql-expression "InInitialPopulation")}] :stratifier [{:fhir/type :fhir.Measure.group/stratifier :code {:fhir/type :fhir/CodeableConcept :text "gender"} :criteria (cql-expression "Gender")}]}]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [library-content]}] [:put {:fhir/type :fhir/Patient :id "0" :gender #fhir/code"male"}] [:put {:fhir/type :fhir/Patient :id "1" :gender #fhir/code"female"}] [:put {:fhir/type :fhir/Patient :id "2" :gender #fhir/code"female"}]]]) {::reitit/router router :request-method :get :params {"measure" "url-181501" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 200 status)) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015" [:group 0 :population 0 :code :coding 0 :system] := #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" [:group 0 :population 0 :code :coding 0 :code] := #fhir/code"initial-population" [:group 0 :population 0 :count] := 3 [:group 0 :stratifier 0 :code 0 :text] := "gender" [:group 0 :stratifier 0 :stratum 0 :population 0 :code :coding 0 :system] := #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" [:group 0 :stratifier 0 :stratum 0 :population 0 :code :coding 0 :code] := #fhir/code"initial-population" [:group 0 :stratifier 0 :stratum 0 :population 0 :count] := 2 [:group 0 :stratifier 0 :stratum 0 :value :text] := "female" [:group 0 :stratifier 0 :stratum 1 :population 0 :code :coding 0 :system] := #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" [:group 0 :stratifier 0 :stratum 1 :population 0 :code :coding 0 :code] := #fhir/code"initial-population" [:group 0 :stratifier 0 :stratum 1 :population 0 :count] := 1 [:group 0 :stratifier 0 :stratum 1 :value :text] := "male")))) (testing "as POST request" (with-redefs [luid (constantly "C5OC2PO45UVYCD2A")] (let [{:keys [status headers body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [library-content]}]]]) {::reitit/router router :request-method :post :params {"measure" "url-181501" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 201 status)) (testing "Location header" (is (= "/MeasureReport/C5OC2PO45UVYCD2A/_history/2" (get headers "Location")))) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015"))))) (testing "on instance endpoint" (testing "as GET request" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [library-content]}]]]) {::reitit/router router :request-method :get :path-params {:id "0"} :params {"periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 200 status)) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015"))) (testing "as POST request" (with-redefs [luid (constantly "C5OC2QYKLM577GLL")] (let [{:keys [status headers body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [library-content]}]]]) {::reitit/router router :request-method :post :path-params {:id "0"} :params {"periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 201 status)) (testing "Location header" (is (= "/MeasureReport/C5OC2QYKLM577GLL/_history/2" (get headers "Location")))) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015")))))))
true
(ns blaze.fhir.operation.evaluate-measure.handler.impl-test (:require [blaze.db.api-stub :refer [mem-node-with]] [blaze.executors :as ex] [blaze.fhir.operation.evaluate-measure.handler.impl :refer [handler]] [blaze.fhir.spec.type :as type] [blaze.log] [blaze.luid :refer [luid]] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [deftest is testing]] [juxt.iota :refer [given]] [reitit.core :as reitit] [taoensso.timbre :as log]) (:import [java.time Clock Instant Year ZoneOffset])) (defn- fixture [f] (st/instrument) (log/set-level! :trace) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def clock (Clock/fixed Instant/EPOCH (ZoneOffset/ofHours 1))) (defonce executor (ex/single-thread-executor)) (def router (reitit/router [["/Patient/{id}" {:name :Patient/instance}] ["/MeasureReport/{id}/_history/{vid}" {:name :MeasureReport/versioned-instance}]] {:syntax :bracket})) (defn- handler-with [txs] (fn [request] (with-open [node (mem-node-with txs)] @((handler clock node executor) request)))) (defn- scoring-concept [code] {:fhir/type :fhir/CodeableConcept :coding [{:fhir/type :fhir/Coding :system #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-scoring" :code (type/->Code code)}]}) (defn- population-concept [code] {:fhir/type :fhir/CodeableConcept :coding [{:fhir/type :fhir/Coding :system #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" :code (type/->Code code)}]}) (defn- cql-expression [expr] {:fhir/type :fhir/Expression :language #fhir/code"text/cql" :expression expr}) (def library-content {:fhir/type :fhir/Attachment :contentType #fhir/code"text/cql" :data #fhir/base64Binary"PI:KEY:<KEY>END_PI}) (deftest handler-test (testing "Returns Not Found on Non-Existing Measure" (testing "on type endpoint" (let [{:keys [status body]} ((handler-with []) {:path-params {:id "0"}})] (is (= 404 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"not-found"))) (testing "on instance endpoint" (let [{:keys [status body]} ((handler-with []) {:params {"measure" "url-181501"}})] (is (= 404 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"not-found")))) (testing "Returns Gone on Deleted Resource" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0"}]] [[:delete "Measure" "0"]]]) {:path-params {:id "0"}})] (is (= 410 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"deleted"))) (testing "invalid report type" (let [{:keys [status body]} ((handler-with []) {:request-method :get :params {"measure" "url-181501" "reportType" "<invalid>"}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "The reportType `<invalid>` is invalid. Please use one of `subject`, `subject-list` or `population`."))) (testing "report type of subject-list is not possible with a GET request" (let [{:keys [status body]} ((handler-with []) {:request-method :get :params {"measure" "url-181501" "reportType" "subject-list"}})] (is (= 422 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"not-supported" :diagnostics := "The reportType `subject-list` is not supported for GET requests. Please use POST."))) (testing "measure without library" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-182126"}]]]) {::reitit/router router :params {"measure" "url-182126" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 422 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"not-supported" :diagnostics := "Missing primary library. Currently only CQL expressions together with one primary library are supported." [:expression first] := "Measure.library"))) (testing "measure with non-existing library" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"]}]]]) {::reitit/router router :params {"measure" "url-181501" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "Can't find the library with canonical URI `library-url-094115`." [:expression first] := "Measure.library"))) (testing "missing content in library" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-182104" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115"}]]]) {::reitit/router router :params {"measure" "url-182104" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "Missing content in library with id `0`." [:expression first] := "Library.content"))) (testing "non text/cql content type" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-182051" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [{:fhir/type :fhir/Attachment :contentType #fhir/code"text/plain"}]}]]]) {::reitit/router router :params {"measure" "url-182051" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "Non `text/cql` content type of `text/plain` of first attachment in library with id `0`." [:expression first] := "Library.content[0].contentType"))) (testing "missing data in library content" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-182039" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [{:fhir/type :fhir/Attachment :contentType #fhir/code"text/cql"}]}]]]) {::reitit/router router :params {"measure" "url-182039" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 400 status)) (is (= :fhir/OperationOutcome (:fhir/type body))) (given (-> body :issue first) :severity := #fhir/code"error" :code := #fhir/code"value" :diagnostics := "Missing embedded data of first attachment in library with id `0`." [:expression first] := "Library.content[0].data"))) (testing "Success" (testing "on type endpoint" (testing "as GET request" (testing "cohort scoring" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"] :scoring (scoring-concept "cohort") :group [{:fhir/type :fhir.Measure/group :population [{:fhir/type :fhir.Measure.group/population :code (population-concept "initial-population") :criteria (cql-expression "InInitialPopulation")}]}]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [{:fhir/type :fhir/Attachment :contentType #fhir/code"text/cql" :data #fhir/base64Binary"bPI:KEY:<KEY>END_PISBSZXRPI:KEY:<KEY>END_PI2PI:KEY:<KEY>END_PIZyPI:KEY:<KEY>END_PI}]}] [:put {:fhir/type :fhir/Patient :id "0" :gender #fhir/code"male"}]]]) {::reitit/router router :request-method :get :params {"measure" "url-181501" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 200 status)) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015" [:group 0 :population 0 :code :coding 0 :system] := #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" [:group 0 :population 0 :code :coding 0 :code] := #fhir/code"initial-population" [:group 0 :population 0 :count] := 1))) (testing "cohort scoring with stratifiers" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"] :scoring (scoring-concept "cohort") :group [{:fhir/type :fhir.Measure/group :population [{:fhir/type :fhir.Measure.group/population :code (population-concept "initial-population") :criteria (cql-expression "InInitialPopulation")}] :stratifier [{:fhir/type :fhir.Measure.group/stratifier :code {:fhir/type :fhir/CodeableConcept :text "gender"} :criteria (cql-expression "Gender")}]}]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [library-content]}] [:put {:fhir/type :fhir/Patient :id "0" :gender #fhir/code"male"}] [:put {:fhir/type :fhir/Patient :id "1" :gender #fhir/code"female"}] [:put {:fhir/type :fhir/Patient :id "2" :gender #fhir/code"female"}]]]) {::reitit/router router :request-method :get :params {"measure" "url-181501" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 200 status)) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015" [:group 0 :population 0 :code :coding 0 :system] := #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" [:group 0 :population 0 :code :coding 0 :code] := #fhir/code"initial-population" [:group 0 :population 0 :count] := 3 [:group 0 :stratifier 0 :code 0 :text] := "gender" [:group 0 :stratifier 0 :stratum 0 :population 0 :code :coding 0 :system] := #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" [:group 0 :stratifier 0 :stratum 0 :population 0 :code :coding 0 :code] := #fhir/code"initial-population" [:group 0 :stratifier 0 :stratum 0 :population 0 :count] := 2 [:group 0 :stratifier 0 :stratum 0 :value :text] := "female" [:group 0 :stratifier 0 :stratum 1 :population 0 :code :coding 0 :system] := #fhir/uri"http://terminology.hl7.org/CodeSystem/measure-population" [:group 0 :stratifier 0 :stratum 1 :population 0 :code :coding 0 :code] := #fhir/code"initial-population" [:group 0 :stratifier 0 :stratum 1 :population 0 :count] := 1 [:group 0 :stratifier 0 :stratum 1 :value :text] := "male")))) (testing "as POST request" (with-redefs [luid (constantly "C5OC2PO45UVYCD2A")] (let [{:keys [status headers body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [library-content]}]]]) {::reitit/router router :request-method :post :params {"measure" "url-181501" "periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 201 status)) (testing "Location header" (is (= "/MeasureReport/C5OC2PO45UVYCD2A/_history/2" (get headers "Location")))) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015"))))) (testing "on instance endpoint" (testing "as GET request" (let [{:keys [status body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [library-content]}]]]) {::reitit/router router :request-method :get :path-params {:id "0"} :params {"periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 200 status)) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015"))) (testing "as POST request" (with-redefs [luid (constantly "C5OC2QYKLM577GLL")] (let [{:keys [status headers body]} ((handler-with [[[:put {:fhir/type :fhir/Measure :id "0" :url #fhir/uri"url-181501" :library [#fhir/canonical"library-url-094115"]}] [:put {:fhir/type :fhir/Library :id "0" :url #fhir/uri"library-url-094115" :content [library-content]}]]]) {::reitit/router router :request-method :post :path-params {:id "0"} :params {"periodStart" (Year/of 2014) "periodEnd" (Year/of 2015)}})] (is (= 201 status)) (testing "Location header" (is (= "/MeasureReport/C5OC2QYKLM577GLL/_history/2" (get headers "Location")))) (given body :fhir/type := :fhir/MeasureReport :status := #fhir/code"complete" :type := #fhir/code"summary" :measure := #fhir/canonical"url-181501" :date := #fhir/dateTime"1970-01-01T01:00:00+01:00" [:period :start] := #fhir/dateTime"2014" [:period :end] := #fhir/dateTime"2015")))))))
[ { "context": ":as i]))\n\n;;\n;; Functor\n;;\n\n(def pirates [{:name \"Jack Sparrow\" :born 1700 :died 1740 :ship \"Black Pearl\"}\n ", "end": 272, "score": 0.9998675584793091, "start": 260, "tag": "NAME", "value": "Jack Sparrow" }, { "context": "d 1740 :ship \"Black Pearl\"}\n {:name \"Blackbeard\" :born 1680 :died 1750 :ship \"Queen Anne's R", "end": 352, "score": 0.999864399433136, "start": 342, "tag": "NAME", "value": "Blackbeard" }, { "context": "hip \"Queen Anne's Revenge\"}\n {:name \"Hector Barbossa\" :born 1680 :died 1740 :ship nil}])\n\n\n(defn pirat", "end": 448, "score": 0.9998882412910461, "start": 433, "tag": "NAME", "value": "Hector Barbossa" }, { "context": " (- died born))\n\n(comment\n\n (-> (pirate-by-name \"Jack Sparrow\")\n age) ;; 40\n\n (-> (pirate-by-name \"Davy J", "end": 677, "score": 0.9998618364334106, "start": 665, "tag": "NAME", "value": "Jack Sparrow" }, { "context": "parrow\")\n age) ;; 40\n\n (-> (pirate-by-name \"Davy Jones\")\n age) ;; NullPointerException clojure.la", "end": 731, "score": 0.9998260736465454, "start": 721, "tag": "NAME", "value": "Davy Jones" }, { "context": " _]\n (None.)))\n\n\n(->> (option (pirate-by-name \"Jack Sparrow\"))\n (fkc/fmap age)) ;; #library_design.option", "end": 1080, "score": 0.9998495578765869, "start": 1068, "tag": "NAME", "value": "Jack Sparrow" }, { "context": "option.Some{:v 40}\n\n(->> (option (pirate-by-name \"Davy Jones\"))\n (fkc/fmap age)) ;; #library_design.option", "end": 1184, "score": 0.9998444318771362, "start": 1174, "tag": "NAME", "value": "Davy Jones" }, { "context": "ign.option.None{}\n\n\n(->> (option (pirate-by-name \"Jack Sparrow\"))\n (fkc/fmap age)\n (fkc/fmap inc)\n (", "end": 1286, "score": 0.999858558177948, "start": 1274, "tag": "NAME", "value": "Jack Sparrow" }, { "context": "option.Some{:v 82}\n\n(->> (option (pirate-by-name \"Davy Jones\"))\n (fkc/fmap age)\n (fkc/fmap inc)\n (", "end": 1435, "score": 0.9998655319213867, "start": 1425, "tag": "NAME", "value": "Davy Jones" }, { "context": "_design.option.None{}\n\n\n\n(some-> (pirate-by-name \"Davy Jones\")\n age\n inc\n (* 2)) ;; nil\n\n", "end": 1576, "score": 0.9998806715011597, "start": 1566, "tag": "NAME", "value": "Davy Jones" }, { "context": " (* 2)) ;; nil\n\n\n(->> (i/future (pirate-by-name \"Jack Sparrow\"))\n (fkc/fmap age)\n (fkc/fmap inc)\n (", "end": 1671, "score": 0.9998666048049927, "start": 1659, "tag": "NAME", "value": "Jack Sparrow" }, { "context": ")\n\n(comment\n\n\n\n (let [a (some-> (pirate-by-name \"Jack Sparrow\") age)\n b (some-> (pirate-by-name \"Blackbe", "end": 2147, "score": 0.9998713731765747, "start": 2135, "tag": "NAME", "value": "Jack Sparrow" }, { "context": "Sparrow\") age)\n b (some-> (pirate-by-name \"Blackbeard\") age)\n c (some-> (pirate-by-name \"Hector ", "end": 2200, "score": 0.999812126159668, "start": 2190, "tag": "NAME", "value": "Blackbeard" }, { "context": "ckbeard\") age)\n c (some-> (pirate-by-name \"Hector Barbossa\") age)]\n (avg a b c)) ;; 56.666668\n\n (let [a ", "end": 2258, "score": 0.9998709559440613, "start": 2243, "tag": "NAME", "value": "Hector Barbossa" }, { "context": " ;; 56.666668\n\n (let [a (some-> (pirate-by-name \"Jack Sparrow\") age)\n b (some-> (pirate-by-name \"Davy Jo", "end": 2345, "score": 0.9998669028282166, "start": 2333, "tag": "NAME", "value": "Jack Sparrow" }, { "context": "Sparrow\") age)\n b (some-> (pirate-by-name \"Davy Jones\") age)\n c (some-> (pirate-by-name \"Hector ", "end": 2398, "score": 0.9998726844787598, "start": 2388, "tag": "NAME", "value": "Davy Jones" }, { "context": "y Jones\") age)\n c (some-> (pirate-by-name \"Hector Barbossa\") age)]\n (avg a b c)) ;; NullPointerException ", "end": 2456, "score": 0.9998462796211243, "start": 2441, "tag": "NAME", "value": "Hector Barbossa" }, { "context": "ers.java:961)\n\n (let [a (some-> (pirate-by-name \"Jack Sparrow\") age)\n b (some-> (pirate-by-name \"Davy Jo", "end": 2600, "score": 0.9998681545257568, "start": 2588, "tag": "NAME", "value": "Jack Sparrow" }, { "context": "Sparrow\") age)\n b (some-> (pirate-by-name \"Davy Jones\") age)\n c (some-> (pirate-by-name \"Hector ", "end": 2653, "score": 0.9998234510421753, "start": 2643, "tag": "NAME", "value": "Davy Jones" }, { "context": "y Jones\") age)\n c (some-> (pirate-by-name \"Hector Barbossa\") age)]\n (when (and a b c)\n (avg a b c)))", "end": 2711, "score": 0.9998563528060913, "start": 2696, "tag": "NAME", "value": "Hector Barbossa" }, { "context": "ge) option pirate-by-name))\n\n(let [a (age-option \"Jack Sparrow\")\n b (age-option \"Blackbeard\")\n c (age-", "end": 3315, "score": 0.9998171329498291, "start": 3303, "tag": "NAME", "value": "Jack Sparrow" }, { "context": " b (age-option \"Blackbeard\")\n c (age-option \"Hector Barbossa\")]\n (fkc/<*> (option (fkj/curry avg 3))\n ", "end": 3388, "score": 0.9959545135498047, "start": 3373, "tag": "NAME", "value": "Hector Barbossa" }, { "context": " (rest as)))))\n\n\n(let [a (age-option \"Jack Sparrow\")\n b (age-option \"Blackbeard\")\n c (age-", "end": 3952, "score": 0.9997942447662354, "start": 3940, "tag": "NAME", "value": "Jack Sparrow" }, { "context": " (age-option \"Jack Sparrow\")\n b (age-option \"Blackbeard\")\n c (age-option \"Hector Barbossa\")]\n ((ali", "end": 3986, "score": 0.8373081684112549, "start": 3976, "tag": "NAME", "value": "Blackbeard" }, { "context": " b (age-option \"Blackbeard\")\n c (age-option \"Hector Barbossa\")]\n ((alift avg) a b c))\n;; #library_design.opti", "end": 4025, "score": 0.8594363331794739, "start": 4010, "tag": "NAME", "value": "Hector Barbossa" }, { "context": "ion.Some{:v 56.666668}\n\n((alift avg) (age-option \"Jack Sparrow\")\n (age-option \"Blackbeard\")\n ", "end": 4136, "score": 0.9998229146003723, "start": 4124, "tag": "NAME", "value": "Jack Sparrow" }, { "context": "-option \"Jack Sparrow\")\n (age-option \"Blackbeard\")\n (age-option \"Hector Barbossa\"))\n;;", "end": 4175, "score": 0.7704212069511414, "start": 4165, "tag": "NAME", "value": "Blackbeard" }, { "context": "ge-option \"Blackbeard\")\n (age-option \"Hector Barbossa\"))\n;; #library_design.option.Some{:v 56.666668}\n\n", "end": 4219, "score": 0.7772570848464966, "start": 4204, "tag": "NAME", "value": "Hector Barbossa" }, { "context": "ion.Some{:v 56.666668}\n\n((alift avg) (age-option \"Jack Sparrow\")\n (age-option \"Davy Jones\")\n ", "end": 4307, "score": 0.9998185634613037, "start": 4295, "tag": "NAME", "value": "Jack Sparrow" }, { "context": "-option \"Jack Sparrow\")\n (age-option \"Davy Jones\")\n (age-option \"Hector Barbossa\"))\n;;", "end": 4346, "score": 0.9996371269226074, "start": 4336, "tag": "NAME", "value": "Davy Jones" }, { "context": "ge-option \"Davy Jones\")\n (age-option \"Hector Barbossa\"))\n;; #library_design.option.None{}\n\n\n\n((alift av", "end": 4390, "score": 0.8460866808891296, "start": 4375, "tag": "NAME", "value": "Hector Barbossa" }, { "context": "\n\n((alift avg) (i/future (some-> (pirate-by-name \"Jack Sparrow\") age))\n (i/future (some-> (pirate-by", "end": 4490, "score": 0.9998128414154053, "start": 4478, "tag": "NAME", "value": "Jack Sparrow" }, { "context": ")\n (i/future (some-> (pirate-by-name \"Blackbeard\") age))\n (i/future (some-> (pirate-by", "end": 4557, "score": 0.9821434617042542, "start": 4547, "tag": "NAME", "value": "Blackbeard" }, { "context": ")\n (i/future (some-> (pirate-by-name \"Hector Barbossa\") age)))\n;; #<Future@17b1be96: #<Success@16577601", "end": 4629, "score": 0.9991869926452637, "start": 4614, "tag": "NAME", "value": "Hector Barbossa" }, { "context": "omment\n\n (let [a (some-> (pirate-by-name \"Jack Sparrow\") age)\n b (some-> (pirate-by-nam", "end": 5159, "score": 0.9998207092285156, "start": 5147, "tag": "NAME", "value": "Jack Sparrow" }, { "context": " age)\n b (some-> (pirate-by-name \"Blackbeard\") age)\n c (some-> (pirate-by-n", "end": 5222, "score": 0.9982800483703613, "start": 5212, "tag": "NAME", "value": "Blackbeard" }, { "context": " age)\n c (some-> (pirate-by-name \"Hector Barbossa\") age)\n avg (avg a b c)\n medi", "end": 5292, "score": 0.9998852014541626, "start": 5277, "tag": "NAME", "value": "Hector Barbossa" }, { "context": "6473}\n\n\n (let [a (some-> (pirate-by-name \"Jack Sparrow\") age)\n b (some-> (pirate-by-nam", "end": 5584, "score": 0.9998794794082642, "start": 5572, "tag": "NAME", "value": "Jack Sparrow" }, { "context": " age)\n b (some-> (pirate-by-name \"Davy Jones\") age)\n c (some-> (pirate-by-n", "end": 5647, "score": 0.9998789429664612, "start": 5637, "tag": "NAME", "value": "Davy Jones" }, { "context": " age)\n c (some-> (pirate-by-name \"Hector Barbossa\") age)\n avg (avg a b c)\n medi", "end": 5717, "score": 0.9998863935470581, "start": 5702, "tag": "NAME", "value": "Hector Barbossa" }, { "context": "a:961)\n\n (let [a (some-> (pirate-by-name \"Jack Sparrow\") age)\n b (some-> (pirate-by-nam", "end": 6005, "score": 0.9998802542686462, "start": 5993, "tag": "NAME", "value": "Jack Sparrow" }, { "context": " age)\n b (some-> (pirate-by-name \"Davy Jones\") age)\n c (some-> (pirate-by-n", "end": 6068, "score": 0.9998683929443359, "start": 6058, "tag": "NAME", "value": "Davy Jones" }, { "context": " age)\n c (some-> (pirate-by-name \"Hector Barbossa\") age)\n avg (when (and a b c) (avg a ", "end": 6138, "score": 0.9998825192451477, "start": 6123, "tag": "NAME", "value": "Hector Barbossa" }, { "context": "y)\n\n(def opt-ctx (None.))\n\n(fkc/bind (age-option \"Jack Sparrow\")\n (fn [a]\n (fkc/bind (age-op", "end": 6634, "score": 0.9997713565826416, "start": 6622, "tag": "NAME", "value": "Jack Sparrow" }, { "context": " (fn [a]\n (fkc/bind (age-option \"Blackbeard\")\n (fn [b]\n ", "end": 6697, "score": 0.7540026903152466, "start": 6695, "tag": "NAME", "value": "be" }, { "context": "b]\n (fkc/bind (age-option \"Hector Barbossa\")\n (fn [c]\n ", "end": 6795, "score": 0.9438990354537964, "start": 6780, "tag": "NAME", "value": "Hector Barbossa" }, { "context": "n.option.Some{:v 170.0}\n\n(fkc/mdo [a (age-option \"Jack Sparrow\")\n b (age-option \"Blackbeard\")\n ", "end": 7036, "score": 0.9993848204612732, "start": 7024, "tag": "NAME", "value": "Jack Sparrow" }, { "context": "e-option \"Jack Sparrow\")\n b (age-option \"Blackbeard\")\n c (age-option \"Hector Barbossa\")]\n ", "end": 7074, "score": 0.9851976037025452, "start": 7064, "tag": "NAME", "value": "Blackbeard" }, { "context": "age-option \"Blackbeard\")\n c (age-option \"Hector Barbossa\")]\n (fkc/pure opt-ctx (+ a b c)))\n;; #li", "end": 7117, "score": 0.9974198341369629, "start": 7102, "tag": "NAME", "value": "Hector Barbossa" }, { "context": "w])\n\n(w/macroexpand-all '(fkc/mdo [a (age-option \"Jack Sparrow\")\n b (age-option \"Bl", "end": 7293, "score": 0.9989774823188782, "start": 7281, "tag": "NAME", "value": "Jack Sparrow" }, { "context": "ow\")\n b (age-option \"Blackbeard\")\n c (age-option \"He", "end": 7351, "score": 0.9386631846427917, "start": 7341, "tag": "NAME", "value": "Blackbeard" }, { "context": "rd\")\n c (age-option \"Hector Barbossa\")]\n (fkc/pure opt-ctx", "end": 7414, "score": 0.9944989085197449, "start": 7399, "tag": "NAME", "value": "Hector Barbossa" }, { "context": "ncomplicate.fluokitten.core/bind\n;; (age-option \"Jack Sparrow\")\n;; (fn*\n;; ([a]\n;; (uncomplicate.fluokitt", "end": 7547, "score": 0.998606264591217, "start": 7535, "tag": "NAME", "value": "Jack Sparrow" }, { "context": "mplicate.fluokitten.core/bind\n;; (age-option \"Blackbeard\")\n;; (fn*\n;; ([b]\n;; (uncomplicate", "end": 7640, "score": 0.6866108775138855, "start": 7630, "tag": "NAME", "value": "Blackbeard" }, { "context": "icate.fluokitten.core/bind\n;; (age-option \"Hector Barbossa\")\n;; (fn* ([c] (fkc/pure opt-ctx (+ a b c)", "end": 7750, "score": 0.9886376261711121, "start": 7735, "tag": "NAME", "value": "Hector Barbossa" }, { "context": " option std-dev))\n\n(fkc/mdo [a (age-option \"Jack Sparrow\")\n b (age-option \"Blackbeard\")\n ", "end": 7972, "score": 0.999330461025238, "start": 7960, "tag": "NAME", "value": "Jack Sparrow" }, { "context": "on \"Jack Sparrow\")\n b (age-option \"Blackbeard\")\n c (age-option \"Hector Barbossa\"", "end": 8016, "score": 0.9921579360961914, "start": 8006, "tag": "NAME", "value": "Blackbeard" }, { "context": "tion \"Blackbeard\")\n c (age-option \"Hector Barbossa\")\n avg (avg-opt a b c)\n med", "end": 8065, "score": 0.9978281855583191, "start": 8050, "tag": "NAME", "value": "Hector Barbossa" }, { "context": "472191289246473}}\n\n(fkc/mdo [a (age-option \"Jack Sparrow\")\n b (age-option \"Davy Jones\")\n ", "end": 8493, "score": 0.9998670816421509, "start": 8481, "tag": "NAME", "value": "Jack Sparrow" }, { "context": "on \"Jack Sparrow\")\n b (age-option \"Davy Jones\")\n c (age-option \"Hector Barbossa\"", "end": 8537, "score": 0.9998671412467957, "start": 8527, "tag": "NAME", "value": "Davy Jones" }, { "context": "tion \"Davy Jones\")\n c (age-option \"Hector Barbossa\")\n avg (avg-opt a b c)\n med", "end": 8586, "score": 0.9998894929885864, "start": 8571, "tag": "NAME", "value": "Hector Barbossa" }, { "context": "c/mdo [a (i/future (some-> (pirate-by-name \"Jack Sparrow\") age))\n b (i/future (some-> (pira", "end": 9043, "score": 0.9998509883880615, "start": 9031, "tag": "NAME", "value": "Jack Sparrow" }, { "context": " b (i/future (some-> (pirate-by-name \"Blackbeard\") age))\n c (i/future (some-> (pira", "end": 9115, "score": 0.9998657703399658, "start": 9105, "tag": "NAME", "value": "Blackbeard" }, { "context": " c (i/future (some-> (pirate-by-name \"Hector Barbossa\") age))\n avg (avg-fut a b c)\n ", "end": 9192, "score": 0.9998849630355835, "start": 9177, "tag": "NAME", "value": "Hector Barbossa" } ]
Appendix/library-design/src/library_design/option.clj
srufle/Hands-On-Reactive-Programming-with-Clojure-Second-Edition
15
(ns library-design.option (:require [uncomplicate.fluokitten.protocols :as fkp] [uncomplicate.fluokitten.core :as fkc] [uncomplicate.fluokitten.jvm :as fkj] [imminent.core :as i])) ;; ;; Functor ;; (def pirates [{:name "Jack Sparrow" :born 1700 :died 1740 :ship "Black Pearl"} {:name "Blackbeard" :born 1680 :died 1750 :ship "Queen Anne's Revenge"} {:name "Hector Barbossa" :born 1680 :died 1740 :ship nil}]) (defn pirate-by-name [name] (->> pirates (filter #(= name (:name %))) first)) (defn age [{:keys [born died]}] (- died born)) (comment (-> (pirate-by-name "Jack Sparrow") age) ;; 40 (-> (pirate-by-name "Davy Jones") age) ;; NullPointerException clojure.lang.Numbers.ops (Numbers.java:961) ) (defrecord Some [v]) (defrecord None []) (defn option [v] (if (nil? v) (None.) (Some. v))) (extend-protocol fkp/Functor Some (fmap [f g] (Some. (g (:v f)))) None (fmap [_ _] (None.))) (->> (option (pirate-by-name "Jack Sparrow")) (fkc/fmap age)) ;; #library_design.option.Some{:v 40} (->> (option (pirate-by-name "Davy Jones")) (fkc/fmap age)) ;; #library_design.option.None{} (->> (option (pirate-by-name "Jack Sparrow")) (fkc/fmap age) (fkc/fmap inc) (fkc/fmap #(* 2 %))) ;; #library_design.option.Some{:v 82} (->> (option (pirate-by-name "Davy Jones")) (fkc/fmap age) (fkc/fmap inc) (fkc/fmap #(* 2 %))) ;; #library_design.option.None{} (some-> (pirate-by-name "Davy Jones") age inc (* 2)) ;; nil (->> (i/future (pirate-by-name "Jack Sparrow")) (fkc/fmap age) (fkc/fmap inc) (fkc/fmap #(* 2 %))) ;; #<Future@30518bfc: #<Success@39bd662c: 82>> ;; Functor laws ;; Identity (= (fkc/fmap identity (option 1)) (identity (option 1))) ;; true ;; Composition (= (fkc/fmap (comp identity inc) (option 1)) (fkc/fmap identity (fkc/fmap inc (option 1)))) ;; true ;; ;; Applicative ;; (defn avg [& xs] (float (/ (apply + xs) (count xs)))) (comment (let [a (some-> (pirate-by-name "Jack Sparrow") age) b (some-> (pirate-by-name "Blackbeard") age) c (some-> (pirate-by-name "Hector Barbossa") age)] (avg a b c)) ;; 56.666668 (let [a (some-> (pirate-by-name "Jack Sparrow") age) b (some-> (pirate-by-name "Davy Jones") age) c (some-> (pirate-by-name "Hector Barbossa") age)] (avg a b c)) ;; NullPointerException clojure.lang.Numbers.ops (Numbers.java:961) (let [a (some-> (pirate-by-name "Jack Sparrow") age) b (some-> (pirate-by-name "Davy Jones") age) c (some-> (pirate-by-name "Hector Barbossa") age)] (when (and a b c) (avg a b c))) ;; nil ) (defprotocol Applicative (pure [av v]) (fapply [ag av])) (extend-protocol fkp/Applicative Some (pure [_ v] (Some. v)) (fapply [ag av] (if-let [v (:v av)] (Some. ((:v ag) v)) (None.))) None (pure [_ v] (Some. v)) (fapply [ag av] (None.))) (fkc/fapply (option inc) (option 2)) ;; #library_design.option.Some{:v 3} (fkc/fapply (option nil) (option 2)) ;; #library_design.option.None{} (def age-option (comp (partial fkc/fmap age) option pirate-by-name)) (let [a (age-option "Jack Sparrow") b (age-option "Blackbeard") c (age-option "Hector Barbossa")] (fkc/<*> (option (fkj/curry avg 3)) a b c)) ;; #library_design.option.Some{:v 56.666668} (def curried-1 (fkj/curry + 2)) (def curried-2 (fn [a] (fn [b] (+ a b)))) ((curried-1 10) 20) ;; 30 ((curried-2 10) 20) ;; 30 (defn alift "Lifts a n-ary function `f` into a applicative context" [f] (fn [& as] {:pre [(seq as)]} (let [curried (fkj/curry f (count as))] (apply fkc/<*> (fkc/fmap curried (first as)) (rest as))))) (let [a (age-option "Jack Sparrow") b (age-option "Blackbeard") c (age-option "Hector Barbossa")] ((alift avg) a b c)) ;; #library_design.option.Some{:v 56.666668} ((alift avg) (age-option "Jack Sparrow") (age-option "Blackbeard") (age-option "Hector Barbossa")) ;; #library_design.option.Some{:v 56.666668} ((alift avg) (age-option "Jack Sparrow") (age-option "Davy Jones") (age-option "Hector Barbossa")) ;; #library_design.option.None{} ((alift avg) (i/future (some-> (pirate-by-name "Jack Sparrow") age)) (i/future (some-> (pirate-by-name "Blackbeard") age)) (i/future (some-> (pirate-by-name "Hector Barbossa") age))) ;; #<Future@17b1be96: #<Success@16577601: 56.666668>> ;; ;; Monad ;; (defn median [& ns] (let [ns (sort ns) cnt (count ns) mid (bit-shift-right cnt 1)] (if (odd? cnt) (nth ns mid) (/ (+ (nth ns mid) (nth ns (dec mid))) 2)))) (defn std-dev [& samples] (let [n (count samples) mean (/ (reduce + samples) n) intermediate (map #(Math/pow (- %1 mean) 2) samples)] (Math/sqrt (/ (reduce + intermediate) n)))) (comment (let [a (some-> (pirate-by-name "Jack Sparrow") age) b (some-> (pirate-by-name "Blackbeard") age) c (some-> (pirate-by-name "Hector Barbossa") age) avg (avg a b c) median (median a b c) std-dev (std-dev a b c)] {:avg avg :median median :std-dev std-dev}) ;; {:avg 56.666668, ;; :median 60, ;; :std-dev 12.472191289246473} (let [a (some-> (pirate-by-name "Jack Sparrow") age) b (some-> (pirate-by-name "Davy Jones") age) c (some-> (pirate-by-name "Hector Barbossa") age) avg (avg a b c) median (median a b c) std-dev (std-dev a b c)] {:avg avg :median median :std-dev std-dev}) ;; NullPointerException clojure.lang.Numbers.ops (Numbers.java:961) (let [a (some-> (pirate-by-name "Jack Sparrow") age) b (some-> (pirate-by-name "Davy Jones") age) c (some-> (pirate-by-name "Hector Barbossa") age) avg (when (and a b c) (avg a b c)) median (when (and a b c) (median a b c)) std-dev (when (and a b c) (std-dev a b c))] (when (and a b c) {:avg avg :median median :std-dev std-dev})) ;; nil ) (defprotocol Monad (bind [mv g])) (extend-protocol fkp/Monad Some (bind [mv g] (g (:v mv))) None (bind [_ _] (None.))) ;; (fkc/bind (None.) identity) (def opt-ctx (None.)) (fkc/bind (age-option "Jack Sparrow") (fn [a] (fkc/bind (age-option "Blackbeard") (fn [b] (fkc/bind (age-option "Hector Barbossa") (fn [c] (fkc/pure opt-ctx (+ a b c)))))))) ;; #library_design.option.Some{:v 170.0} (fkc/mdo [a (age-option "Jack Sparrow") b (age-option "Blackbeard") c (age-option "Hector Barbossa")] (fkc/pure opt-ctx (+ a b c))) ;; #library_design.option.Some{:v 170.0} (require '[clojure.walk :as w]) (w/macroexpand-all '(fkc/mdo [a (age-option "Jack Sparrow") b (age-option "Blackbeard") c (age-option "Hector Barbossa")] (fkc/pure opt-ctx (+ a b c)))) ;; (uncomplicate.fluokitten.core/bind ;; (age-option "Jack Sparrow") ;; (fn* ;; ([a] ;; (uncomplicate.fluokitten.core/bind ;; (age-option "Blackbeard") ;; (fn* ;; ([b] ;; (uncomplicate.fluokitten.core/bind ;; (age-option "Hector Barbossa") ;; (fn* ([c] (fkc/pure opt-ctx (+ a b c))))))))))) (def avg-opt (comp option avg)) (def median-opt (comp option median)) (def std-dev-opt (comp option std-dev)) (fkc/mdo [a (age-option "Jack Sparrow") b (age-option "Blackbeard") c (age-option "Hector Barbossa") avg (avg-opt a b c) median (median-opt a b c) std-dev (std-dev-opt a b c)] (fkc/pure opt-ctx {:avg avg :median median :std-dev std-dev})) ;; #library_design.option.Some{:v {:avg 56.666668, ;; :median 60, ;; :std-dev 12.472191289246473}} (fkc/mdo [a (age-option "Jack Sparrow") b (age-option "Davy Jones") c (age-option "Hector Barbossa") avg (avg-opt a b c) median (median-opt a b c) std-dev (std-dev-opt a b c)] (fkc/pure opt-ctx {:avg avg :median median :std-dev std-dev})) ;; #library_design.option.None{} (def avg-fut (comp i/future-call avg)) (def median-fut (comp i/future-call median)) (def std-dev-fut (comp i/future-call std-dev)) (fkc/mdo [a (i/future (some-> (pirate-by-name "Jack Sparrow") age)) b (i/future (some-> (pirate-by-name "Blackbeard") age)) c (i/future (some-> (pirate-by-name "Hector Barbossa") age)) avg (avg-fut a b c) median (median-fut a b c) std-dev (std-dev-fut a b c)] (i/const-future {:avg avg :median median :std-dev std-dev})) ;; #<Future@3fd0b0d0: #<Success@1e08486b: {:avg 56.666668, ;; :median 60, ;; :std-dev 12.472191289246473}>> ;; Please note that this snippet of code generates a varying result
106792
(ns library-design.option (:require [uncomplicate.fluokitten.protocols :as fkp] [uncomplicate.fluokitten.core :as fkc] [uncomplicate.fluokitten.jvm :as fkj] [imminent.core :as i])) ;; ;; Functor ;; (def pirates [{:name "<NAME>" :born 1700 :died 1740 :ship "Black Pearl"} {:name "<NAME>" :born 1680 :died 1750 :ship "Queen Anne's Revenge"} {:name "<NAME>" :born 1680 :died 1740 :ship nil}]) (defn pirate-by-name [name] (->> pirates (filter #(= name (:name %))) first)) (defn age [{:keys [born died]}] (- died born)) (comment (-> (pirate-by-name "<NAME>") age) ;; 40 (-> (pirate-by-name "<NAME>") age) ;; NullPointerException clojure.lang.Numbers.ops (Numbers.java:961) ) (defrecord Some [v]) (defrecord None []) (defn option [v] (if (nil? v) (None.) (Some. v))) (extend-protocol fkp/Functor Some (fmap [f g] (Some. (g (:v f)))) None (fmap [_ _] (None.))) (->> (option (pirate-by-name "<NAME>")) (fkc/fmap age)) ;; #library_design.option.Some{:v 40} (->> (option (pirate-by-name "<NAME>")) (fkc/fmap age)) ;; #library_design.option.None{} (->> (option (pirate-by-name "<NAME>")) (fkc/fmap age) (fkc/fmap inc) (fkc/fmap #(* 2 %))) ;; #library_design.option.Some{:v 82} (->> (option (pirate-by-name "<NAME>")) (fkc/fmap age) (fkc/fmap inc) (fkc/fmap #(* 2 %))) ;; #library_design.option.None{} (some-> (pirate-by-name "<NAME>") age inc (* 2)) ;; nil (->> (i/future (pirate-by-name "<NAME>")) (fkc/fmap age) (fkc/fmap inc) (fkc/fmap #(* 2 %))) ;; #<Future@30518bfc: #<Success@39bd662c: 82>> ;; Functor laws ;; Identity (= (fkc/fmap identity (option 1)) (identity (option 1))) ;; true ;; Composition (= (fkc/fmap (comp identity inc) (option 1)) (fkc/fmap identity (fkc/fmap inc (option 1)))) ;; true ;; ;; Applicative ;; (defn avg [& xs] (float (/ (apply + xs) (count xs)))) (comment (let [a (some-> (pirate-by-name "<NAME>") age) b (some-> (pirate-by-name "<NAME>") age) c (some-> (pirate-by-name "<NAME>") age)] (avg a b c)) ;; 56.666668 (let [a (some-> (pirate-by-name "<NAME>") age) b (some-> (pirate-by-name "<NAME>") age) c (some-> (pirate-by-name "<NAME>") age)] (avg a b c)) ;; NullPointerException clojure.lang.Numbers.ops (Numbers.java:961) (let [a (some-> (pirate-by-name "<NAME>") age) b (some-> (pirate-by-name "<NAME>") age) c (some-> (pirate-by-name "<NAME>") age)] (when (and a b c) (avg a b c))) ;; nil ) (defprotocol Applicative (pure [av v]) (fapply [ag av])) (extend-protocol fkp/Applicative Some (pure [_ v] (Some. v)) (fapply [ag av] (if-let [v (:v av)] (Some. ((:v ag) v)) (None.))) None (pure [_ v] (Some. v)) (fapply [ag av] (None.))) (fkc/fapply (option inc) (option 2)) ;; #library_design.option.Some{:v 3} (fkc/fapply (option nil) (option 2)) ;; #library_design.option.None{} (def age-option (comp (partial fkc/fmap age) option pirate-by-name)) (let [a (age-option "<NAME>") b (age-option "Blackbeard") c (age-option "<NAME>")] (fkc/<*> (option (fkj/curry avg 3)) a b c)) ;; #library_design.option.Some{:v 56.666668} (def curried-1 (fkj/curry + 2)) (def curried-2 (fn [a] (fn [b] (+ a b)))) ((curried-1 10) 20) ;; 30 ((curried-2 10) 20) ;; 30 (defn alift "Lifts a n-ary function `f` into a applicative context" [f] (fn [& as] {:pre [(seq as)]} (let [curried (fkj/curry f (count as))] (apply fkc/<*> (fkc/fmap curried (first as)) (rest as))))) (let [a (age-option "<NAME>") b (age-option "<NAME>") c (age-option "<NAME>")] ((alift avg) a b c)) ;; #library_design.option.Some{:v 56.666668} ((alift avg) (age-option "<NAME>") (age-option "<NAME>") (age-option "<NAME>")) ;; #library_design.option.Some{:v 56.666668} ((alift avg) (age-option "<NAME>") (age-option "<NAME>") (age-option "<NAME>")) ;; #library_design.option.None{} ((alift avg) (i/future (some-> (pirate-by-name "<NAME>") age)) (i/future (some-> (pirate-by-name "<NAME>") age)) (i/future (some-> (pirate-by-name "<NAME>") age))) ;; #<Future@17b1be96: #<Success@16577601: 56.666668>> ;; ;; Monad ;; (defn median [& ns] (let [ns (sort ns) cnt (count ns) mid (bit-shift-right cnt 1)] (if (odd? cnt) (nth ns mid) (/ (+ (nth ns mid) (nth ns (dec mid))) 2)))) (defn std-dev [& samples] (let [n (count samples) mean (/ (reduce + samples) n) intermediate (map #(Math/pow (- %1 mean) 2) samples)] (Math/sqrt (/ (reduce + intermediate) n)))) (comment (let [a (some-> (pirate-by-name "<NAME>") age) b (some-> (pirate-by-name "<NAME>") age) c (some-> (pirate-by-name "<NAME>") age) avg (avg a b c) median (median a b c) std-dev (std-dev a b c)] {:avg avg :median median :std-dev std-dev}) ;; {:avg 56.666668, ;; :median 60, ;; :std-dev 12.472191289246473} (let [a (some-> (pirate-by-name "<NAME>") age) b (some-> (pirate-by-name "<NAME>") age) c (some-> (pirate-by-name "<NAME>") age) avg (avg a b c) median (median a b c) std-dev (std-dev a b c)] {:avg avg :median median :std-dev std-dev}) ;; NullPointerException clojure.lang.Numbers.ops (Numbers.java:961) (let [a (some-> (pirate-by-name "<NAME>") age) b (some-> (pirate-by-name "<NAME>") age) c (some-> (pirate-by-name "<NAME>") age) avg (when (and a b c) (avg a b c)) median (when (and a b c) (median a b c)) std-dev (when (and a b c) (std-dev a b c))] (when (and a b c) {:avg avg :median median :std-dev std-dev})) ;; nil ) (defprotocol Monad (bind [mv g])) (extend-protocol fkp/Monad Some (bind [mv g] (g (:v mv))) None (bind [_ _] (None.))) ;; (fkc/bind (None.) identity) (def opt-ctx (None.)) (fkc/bind (age-option "<NAME>") (fn [a] (fkc/bind (age-option "Black<NAME>ard") (fn [b] (fkc/bind (age-option "<NAME>") (fn [c] (fkc/pure opt-ctx (+ a b c)))))))) ;; #library_design.option.Some{:v 170.0} (fkc/mdo [a (age-option "<NAME>") b (age-option "<NAME>") c (age-option "<NAME>")] (fkc/pure opt-ctx (+ a b c))) ;; #library_design.option.Some{:v 170.0} (require '[clojure.walk :as w]) (w/macroexpand-all '(fkc/mdo [a (age-option "<NAME>") b (age-option "<NAME>") c (age-option "<NAME>")] (fkc/pure opt-ctx (+ a b c)))) ;; (uncomplicate.fluokitten.core/bind ;; (age-option "<NAME>") ;; (fn* ;; ([a] ;; (uncomplicate.fluokitten.core/bind ;; (age-option "<NAME>") ;; (fn* ;; ([b] ;; (uncomplicate.fluokitten.core/bind ;; (age-option "<NAME>") ;; (fn* ([c] (fkc/pure opt-ctx (+ a b c))))))))))) (def avg-opt (comp option avg)) (def median-opt (comp option median)) (def std-dev-opt (comp option std-dev)) (fkc/mdo [a (age-option "<NAME>") b (age-option "<NAME>") c (age-option "<NAME>") avg (avg-opt a b c) median (median-opt a b c) std-dev (std-dev-opt a b c)] (fkc/pure opt-ctx {:avg avg :median median :std-dev std-dev})) ;; #library_design.option.Some{:v {:avg 56.666668, ;; :median 60, ;; :std-dev 12.472191289246473}} (fkc/mdo [a (age-option "<NAME>") b (age-option "<NAME>") c (age-option "<NAME>") avg (avg-opt a b c) median (median-opt a b c) std-dev (std-dev-opt a b c)] (fkc/pure opt-ctx {:avg avg :median median :std-dev std-dev})) ;; #library_design.option.None{} (def avg-fut (comp i/future-call avg)) (def median-fut (comp i/future-call median)) (def std-dev-fut (comp i/future-call std-dev)) (fkc/mdo [a (i/future (some-> (pirate-by-name "<NAME>") age)) b (i/future (some-> (pirate-by-name "<NAME>") age)) c (i/future (some-> (pirate-by-name "<NAME>") age)) avg (avg-fut a b c) median (median-fut a b c) std-dev (std-dev-fut a b c)] (i/const-future {:avg avg :median median :std-dev std-dev})) ;; #<Future@3fd0b0d0: #<Success@1e08486b: {:avg 56.666668, ;; :median 60, ;; :std-dev 12.472191289246473}>> ;; Please note that this snippet of code generates a varying result
true
(ns library-design.option (:require [uncomplicate.fluokitten.protocols :as fkp] [uncomplicate.fluokitten.core :as fkc] [uncomplicate.fluokitten.jvm :as fkj] [imminent.core :as i])) ;; ;; Functor ;; (def pirates [{:name "PI:NAME:<NAME>END_PI" :born 1700 :died 1740 :ship "Black Pearl"} {:name "PI:NAME:<NAME>END_PI" :born 1680 :died 1750 :ship "Queen Anne's Revenge"} {:name "PI:NAME:<NAME>END_PI" :born 1680 :died 1740 :ship nil}]) (defn pirate-by-name [name] (->> pirates (filter #(= name (:name %))) first)) (defn age [{:keys [born died]}] (- died born)) (comment (-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) ;; 40 (-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) ;; NullPointerException clojure.lang.Numbers.ops (Numbers.java:961) ) (defrecord Some [v]) (defrecord None []) (defn option [v] (if (nil? v) (None.) (Some. v))) (extend-protocol fkp/Functor Some (fmap [f g] (Some. (g (:v f)))) None (fmap [_ _] (None.))) (->> (option (pirate-by-name "PI:NAME:<NAME>END_PI")) (fkc/fmap age)) ;; #library_design.option.Some{:v 40} (->> (option (pirate-by-name "PI:NAME:<NAME>END_PI")) (fkc/fmap age)) ;; #library_design.option.None{} (->> (option (pirate-by-name "PI:NAME:<NAME>END_PI")) (fkc/fmap age) (fkc/fmap inc) (fkc/fmap #(* 2 %))) ;; #library_design.option.Some{:v 82} (->> (option (pirate-by-name "PI:NAME:<NAME>END_PI")) (fkc/fmap age) (fkc/fmap inc) (fkc/fmap #(* 2 %))) ;; #library_design.option.None{} (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age inc (* 2)) ;; nil (->> (i/future (pirate-by-name "PI:NAME:<NAME>END_PI")) (fkc/fmap age) (fkc/fmap inc) (fkc/fmap #(* 2 %))) ;; #<Future@30518bfc: #<Success@39bd662c: 82>> ;; Functor laws ;; Identity (= (fkc/fmap identity (option 1)) (identity (option 1))) ;; true ;; Composition (= (fkc/fmap (comp identity inc) (option 1)) (fkc/fmap identity (fkc/fmap inc (option 1)))) ;; true ;; ;; Applicative ;; (defn avg [& xs] (float (/ (apply + xs) (count xs)))) (comment (let [a (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) b (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) c (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age)] (avg a b c)) ;; 56.666668 (let [a (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) b (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) c (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age)] (avg a b c)) ;; NullPointerException clojure.lang.Numbers.ops (Numbers.java:961) (let [a (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) b (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) c (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age)] (when (and a b c) (avg a b c))) ;; nil ) (defprotocol Applicative (pure [av v]) (fapply [ag av])) (extend-protocol fkp/Applicative Some (pure [_ v] (Some. v)) (fapply [ag av] (if-let [v (:v av)] (Some. ((:v ag) v)) (None.))) None (pure [_ v] (Some. v)) (fapply [ag av] (None.))) (fkc/fapply (option inc) (option 2)) ;; #library_design.option.Some{:v 3} (fkc/fapply (option nil) (option 2)) ;; #library_design.option.None{} (def age-option (comp (partial fkc/fmap age) option pirate-by-name)) (let [a (age-option "PI:NAME:<NAME>END_PI") b (age-option "Blackbeard") c (age-option "PI:NAME:<NAME>END_PI")] (fkc/<*> (option (fkj/curry avg 3)) a b c)) ;; #library_design.option.Some{:v 56.666668} (def curried-1 (fkj/curry + 2)) (def curried-2 (fn [a] (fn [b] (+ a b)))) ((curried-1 10) 20) ;; 30 ((curried-2 10) 20) ;; 30 (defn alift "Lifts a n-ary function `f` into a applicative context" [f] (fn [& as] {:pre [(seq as)]} (let [curried (fkj/curry f (count as))] (apply fkc/<*> (fkc/fmap curried (first as)) (rest as))))) (let [a (age-option "PI:NAME:<NAME>END_PI") b (age-option "PI:NAME:<NAME>END_PI") c (age-option "PI:NAME:<NAME>END_PI")] ((alift avg) a b c)) ;; #library_design.option.Some{:v 56.666668} ((alift avg) (age-option "PI:NAME:<NAME>END_PI") (age-option "PI:NAME:<NAME>END_PI") (age-option "PI:NAME:<NAME>END_PI")) ;; #library_design.option.Some{:v 56.666668} ((alift avg) (age-option "PI:NAME:<NAME>END_PI") (age-option "PI:NAME:<NAME>END_PI") (age-option "PI:NAME:<NAME>END_PI")) ;; #library_design.option.None{} ((alift avg) (i/future (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age)) (i/future (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age)) (i/future (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age))) ;; #<Future@17b1be96: #<Success@16577601: 56.666668>> ;; ;; Monad ;; (defn median [& ns] (let [ns (sort ns) cnt (count ns) mid (bit-shift-right cnt 1)] (if (odd? cnt) (nth ns mid) (/ (+ (nth ns mid) (nth ns (dec mid))) 2)))) (defn std-dev [& samples] (let [n (count samples) mean (/ (reduce + samples) n) intermediate (map #(Math/pow (- %1 mean) 2) samples)] (Math/sqrt (/ (reduce + intermediate) n)))) (comment (let [a (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) b (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) c (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) avg (avg a b c) median (median a b c) std-dev (std-dev a b c)] {:avg avg :median median :std-dev std-dev}) ;; {:avg 56.666668, ;; :median 60, ;; :std-dev 12.472191289246473} (let [a (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) b (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) c (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) avg (avg a b c) median (median a b c) std-dev (std-dev a b c)] {:avg avg :median median :std-dev std-dev}) ;; NullPointerException clojure.lang.Numbers.ops (Numbers.java:961) (let [a (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) b (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) c (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age) avg (when (and a b c) (avg a b c)) median (when (and a b c) (median a b c)) std-dev (when (and a b c) (std-dev a b c))] (when (and a b c) {:avg avg :median median :std-dev std-dev})) ;; nil ) (defprotocol Monad (bind [mv g])) (extend-protocol fkp/Monad Some (bind [mv g] (g (:v mv))) None (bind [_ _] (None.))) ;; (fkc/bind (None.) identity) (def opt-ctx (None.)) (fkc/bind (age-option "PI:NAME:<NAME>END_PI") (fn [a] (fkc/bind (age-option "BlackPI:NAME:<NAME>END_PIard") (fn [b] (fkc/bind (age-option "PI:NAME:<NAME>END_PI") (fn [c] (fkc/pure opt-ctx (+ a b c)))))))) ;; #library_design.option.Some{:v 170.0} (fkc/mdo [a (age-option "PI:NAME:<NAME>END_PI") b (age-option "PI:NAME:<NAME>END_PI") c (age-option "PI:NAME:<NAME>END_PI")] (fkc/pure opt-ctx (+ a b c))) ;; #library_design.option.Some{:v 170.0} (require '[clojure.walk :as w]) (w/macroexpand-all '(fkc/mdo [a (age-option "PI:NAME:<NAME>END_PI") b (age-option "PI:NAME:<NAME>END_PI") c (age-option "PI:NAME:<NAME>END_PI")] (fkc/pure opt-ctx (+ a b c)))) ;; (uncomplicate.fluokitten.core/bind ;; (age-option "PI:NAME:<NAME>END_PI") ;; (fn* ;; ([a] ;; (uncomplicate.fluokitten.core/bind ;; (age-option "PI:NAME:<NAME>END_PI") ;; (fn* ;; ([b] ;; (uncomplicate.fluokitten.core/bind ;; (age-option "PI:NAME:<NAME>END_PI") ;; (fn* ([c] (fkc/pure opt-ctx (+ a b c))))))))))) (def avg-opt (comp option avg)) (def median-opt (comp option median)) (def std-dev-opt (comp option std-dev)) (fkc/mdo [a (age-option "PI:NAME:<NAME>END_PI") b (age-option "PI:NAME:<NAME>END_PI") c (age-option "PI:NAME:<NAME>END_PI") avg (avg-opt a b c) median (median-opt a b c) std-dev (std-dev-opt a b c)] (fkc/pure opt-ctx {:avg avg :median median :std-dev std-dev})) ;; #library_design.option.Some{:v {:avg 56.666668, ;; :median 60, ;; :std-dev 12.472191289246473}} (fkc/mdo [a (age-option "PI:NAME:<NAME>END_PI") b (age-option "PI:NAME:<NAME>END_PI") c (age-option "PI:NAME:<NAME>END_PI") avg (avg-opt a b c) median (median-opt a b c) std-dev (std-dev-opt a b c)] (fkc/pure opt-ctx {:avg avg :median median :std-dev std-dev})) ;; #library_design.option.None{} (def avg-fut (comp i/future-call avg)) (def median-fut (comp i/future-call median)) (def std-dev-fut (comp i/future-call std-dev)) (fkc/mdo [a (i/future (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age)) b (i/future (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age)) c (i/future (some-> (pirate-by-name "PI:NAME:<NAME>END_PI") age)) avg (avg-fut a b c) median (median-fut a b c) std-dev (std-dev-fut a b c)] (i/const-future {:avg avg :median median :std-dev std-dev})) ;; #<Future@3fd0b0d0: #<Success@1e08486b: {:avg 56.666668, ;; :median 60, ;; :std-dev 12.472191289246473}>> ;; Please note that this snippet of code generates a varying result
[ { "context": ".\"\n [topic add-response & {:keys [key] :or {key \"resource-id\"}}]\n (try\n (when (= 201 (:status add-response", "end": 319, "score": 0.8984360694885254, "start": 308, "tag": "KEY", "value": "resource-id" }, { "context": "ce-id {})\n msg-key (if (= key \"resource-id\")\n resource-id\n ", "end": 526, "score": 0.9011039733886719, "start": 524, "tag": "KEY", "value": "id" } ]
code/src/sixsq/nuvla/server/util/kafka_crud.clj
0xbase12/api-server
6
(ns sixsq.nuvla.server.util.kafka-crud (:require [clojure.tools.logging :as log] [sixsq.nuvla.db.impl :as db] [sixsq.nuvla.server.util.kafka :as ka])) (defn publish-on-add "Publish to a `topic` based on result of add response `add-response`." [topic add-response & {:keys [key] :or {key "resource-id"}}] (try (when (= 201 (:status add-response)) (let [resource-id (-> add-response :body :resource-id) resource (db/retrieve resource-id {}) msg-key (if (= key "resource-id") resource-id ((keyword key) resource))] (ka/publish-async topic msg-key resource))) (catch Exception e (log/warn "Failed publishing to Kafka on add: " (str e)))) ) (defn publish-on-edit "Publish to a `topic` based on result of edit response `edit-response`." [topic edit-response & {:keys [key] :or {key "id"}}] (try (when (= 200 (int (:status edit-response))) (let [msg-key (-> edit-response :body (get (keyword key))) resource (:body edit-response)] (ka/publish-async topic msg-key resource))) (catch Exception e (log/warn "Failed publishing to Kafka on edit: " (str e))))) (defn publish-tombstone "Publish tombstone message for `key` to `topic`." [topic key] (try (ka/publish-async topic key nil) (catch Exception e (log/warn "Failed publishing tombstone to Kafka: " (str e)))))
49537
(ns sixsq.nuvla.server.util.kafka-crud (:require [clojure.tools.logging :as log] [sixsq.nuvla.db.impl :as db] [sixsq.nuvla.server.util.kafka :as ka])) (defn publish-on-add "Publish to a `topic` based on result of add response `add-response`." [topic add-response & {:keys [key] :or {key "<KEY>"}}] (try (when (= 201 (:status add-response)) (let [resource-id (-> add-response :body :resource-id) resource (db/retrieve resource-id {}) msg-key (if (= key "resource-<KEY>") resource-id ((keyword key) resource))] (ka/publish-async topic msg-key resource))) (catch Exception e (log/warn "Failed publishing to Kafka on add: " (str e)))) ) (defn publish-on-edit "Publish to a `topic` based on result of edit response `edit-response`." [topic edit-response & {:keys [key] :or {key "id"}}] (try (when (= 200 (int (:status edit-response))) (let [msg-key (-> edit-response :body (get (keyword key))) resource (:body edit-response)] (ka/publish-async topic msg-key resource))) (catch Exception e (log/warn "Failed publishing to Kafka on edit: " (str e))))) (defn publish-tombstone "Publish tombstone message for `key` to `topic`." [topic key] (try (ka/publish-async topic key nil) (catch Exception e (log/warn "Failed publishing tombstone to Kafka: " (str e)))))
true
(ns sixsq.nuvla.server.util.kafka-crud (:require [clojure.tools.logging :as log] [sixsq.nuvla.db.impl :as db] [sixsq.nuvla.server.util.kafka :as ka])) (defn publish-on-add "Publish to a `topic` based on result of add response `add-response`." [topic add-response & {:keys [key] :or {key "PI:KEY:<KEY>END_PI"}}] (try (when (= 201 (:status add-response)) (let [resource-id (-> add-response :body :resource-id) resource (db/retrieve resource-id {}) msg-key (if (= key "resource-PI:KEY:<KEY>END_PI") resource-id ((keyword key) resource))] (ka/publish-async topic msg-key resource))) (catch Exception e (log/warn "Failed publishing to Kafka on add: " (str e)))) ) (defn publish-on-edit "Publish to a `topic` based on result of edit response `edit-response`." [topic edit-response & {:keys [key] :or {key "id"}}] (try (when (= 200 (int (:status edit-response))) (let [msg-key (-> edit-response :body (get (keyword key))) resource (:body edit-response)] (ka/publish-async topic msg-key resource))) (catch Exception e (log/warn "Failed publishing to Kafka on edit: " (str e))))) (defn publish-tombstone "Publish tombstone message for `key` to `topic`." [topic key] (try (ka/publish-async topic key nil) (catch Exception e (log/warn "Failed publishing tombstone to Kafka: " (str e)))))
[ { "context": "uth\n {:repo s/Str\n :username s/Str\n :password s/Str})\n\n(def Clojure\n {(s/optional-key :signing-gpg-k", "end": 1118, "score": 0.9827537536621094, "start": 1113, "tag": "PASSWORD", "value": "s/Str" }, { "context": "\"755\"\n :url \"https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein\")\n (actions/remote-fil", "end": 1662, "score": 0.9979681372642517, "start": 1651, "tag": "USERNAME", "value": "technomancy" } ]
main/src/dda/pallet/dda_managed_ide/infra/clojure.clj
DomainDrivenArchitecture/dda-managed-ide
10
; Licensed to the Apache Software Foundation (ASF) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file ; to you under the Apache License, Version 2.0 (the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns dda.pallet.dda-managed-ide.infra.clojure (:require [clojure.tools.logging :as logging] [schema.core :as s] [pallet.actions :as actions] [selmer.parser :as selmer] [dda.pallet.crate.util :as util] [dda.config.commons.user-home :as user-env])) (def RepoAuth {:repo s/Str :username s/Str :password s/Str}) (def Clojure {(s/optional-key :signing-gpg-key) s/Str (s/optional-key :lein-auth) [RepoAuth]}) (def Settings #{}) (defn install-leiningen [facility] (actions/as-action (logging/info (str facility "-install system: clojure"))) "get and install lein at /opt/leiningen" (actions/directory "/opt/leiningen" :owner "root" :group "users" :mode "755") (actions/remote-file "/opt/leiningen/lein" :owner "root" :group "users" :mode "755" :url "https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein") (actions/remote-file "/etc/profile.d/lein.sh" :literal true :content (util/create-file-content ["PATH=$PATH:/opt/leiningen"]))) (s/defn lein-user-profile [lein-config :- Clojure] (selmer/render-file "lein_profiles.template" lein-config)) (s/defn configure-user-leiningen "configure lein settings" [facility :- s/Keyword os-user-name :- s/Str lein-config :- Clojure] (let [path (str (user-env/user-home-dir os-user-name) "/.lein/")] (actions/as-action (logging/info (str facility "-configure user: clojure"))) (actions/directory path :owner os-user-name :group os-user-name :mode "755") (actions/remote-file (str path "profiles.clj") :owner os-user-name :group os-user-name :literal true :content (lein-user-profile lein-config)))) (s/defn install-system [facility :- s/Keyword contains-clojure? :- s/Bool clojure :- Clojure] (when contains-clojure? (install-leiningen facility))) (s/defn configure-user [facility :- s/Keyword os-user-name :- s/Str contains-clojure? :- s/Bool clojure :- Clojure] (when contains-clojure? (configure-user-leiningen facility os-user-name clojure)))
39137
; Licensed to the Apache Software Foundation (ASF) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file ; to you under the Apache License, Version 2.0 (the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns dda.pallet.dda-managed-ide.infra.clojure (:require [clojure.tools.logging :as logging] [schema.core :as s] [pallet.actions :as actions] [selmer.parser :as selmer] [dda.pallet.crate.util :as util] [dda.config.commons.user-home :as user-env])) (def RepoAuth {:repo s/Str :username s/Str :password <PASSWORD>}) (def Clojure {(s/optional-key :signing-gpg-key) s/Str (s/optional-key :lein-auth) [RepoAuth]}) (def Settings #{}) (defn install-leiningen [facility] (actions/as-action (logging/info (str facility "-install system: clojure"))) "get and install lein at /opt/leiningen" (actions/directory "/opt/leiningen" :owner "root" :group "users" :mode "755") (actions/remote-file "/opt/leiningen/lein" :owner "root" :group "users" :mode "755" :url "https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein") (actions/remote-file "/etc/profile.d/lein.sh" :literal true :content (util/create-file-content ["PATH=$PATH:/opt/leiningen"]))) (s/defn lein-user-profile [lein-config :- Clojure] (selmer/render-file "lein_profiles.template" lein-config)) (s/defn configure-user-leiningen "configure lein settings" [facility :- s/Keyword os-user-name :- s/Str lein-config :- Clojure] (let [path (str (user-env/user-home-dir os-user-name) "/.lein/")] (actions/as-action (logging/info (str facility "-configure user: clojure"))) (actions/directory path :owner os-user-name :group os-user-name :mode "755") (actions/remote-file (str path "profiles.clj") :owner os-user-name :group os-user-name :literal true :content (lein-user-profile lein-config)))) (s/defn install-system [facility :- s/Keyword contains-clojure? :- s/Bool clojure :- Clojure] (when contains-clojure? (install-leiningen facility))) (s/defn configure-user [facility :- s/Keyword os-user-name :- s/Str contains-clojure? :- s/Bool clojure :- Clojure] (when contains-clojure? (configure-user-leiningen facility os-user-name clojure)))
true
; Licensed to the Apache Software Foundation (ASF) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file ; to you under the Apache License, Version 2.0 (the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns dda.pallet.dda-managed-ide.infra.clojure (:require [clojure.tools.logging :as logging] [schema.core :as s] [pallet.actions :as actions] [selmer.parser :as selmer] [dda.pallet.crate.util :as util] [dda.config.commons.user-home :as user-env])) (def RepoAuth {:repo s/Str :username s/Str :password PI:PASSWORD:<PASSWORD>END_PI}) (def Clojure {(s/optional-key :signing-gpg-key) s/Str (s/optional-key :lein-auth) [RepoAuth]}) (def Settings #{}) (defn install-leiningen [facility] (actions/as-action (logging/info (str facility "-install system: clojure"))) "get and install lein at /opt/leiningen" (actions/directory "/opt/leiningen" :owner "root" :group "users" :mode "755") (actions/remote-file "/opt/leiningen/lein" :owner "root" :group "users" :mode "755" :url "https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein") (actions/remote-file "/etc/profile.d/lein.sh" :literal true :content (util/create-file-content ["PATH=$PATH:/opt/leiningen"]))) (s/defn lein-user-profile [lein-config :- Clojure] (selmer/render-file "lein_profiles.template" lein-config)) (s/defn configure-user-leiningen "configure lein settings" [facility :- s/Keyword os-user-name :- s/Str lein-config :- Clojure] (let [path (str (user-env/user-home-dir os-user-name) "/.lein/")] (actions/as-action (logging/info (str facility "-configure user: clojure"))) (actions/directory path :owner os-user-name :group os-user-name :mode "755") (actions/remote-file (str path "profiles.clj") :owner os-user-name :group os-user-name :literal true :content (lein-user-profile lein-config)))) (s/defn install-system [facility :- s/Keyword contains-clojure? :- s/Bool clojure :- Clojure] (when contains-clojure? (install-leiningen facility))) (s/defn configure-user [facility :- s/Keyword os-user-name :- s/Str contains-clojure? :- s/Bool clojure :- Clojure] (when contains-clojure? (configure-user-leiningen facility os-user-name clojure)))
[ { "context": "ame,email)\n values('Sam Campos de Milho','sammilhoso@email.com')\"])\n\n (match? [#:addre", "end": 1020, "score": 0.9998976588249207, "start": 1001, "tag": "NAME", "value": "Sam Campos de Milho" }, { "context": " values('Sam Campos de Milho','sammilhoso@email.com')\"])\n\n (match? [#:address{:id 1\n ", "end": 1043, "score": 0.9999315738677979, "start": 1023, "tag": "EMAIL", "value": "sammilhoso@email.com" }, { "context": "h? [#:address{:id 1\n :name \"Sam Campos de Milho\"\n :email \"sammilhoso@email.", "end": 1128, "score": 0.9998980164527893, "start": 1109, "tag": "NAME", "value": "Sam Campos de Milho" }, { "context": "m Campos de Milho\"\n :email \"sammilhoso@email.com\"}]\n (util.database/execute! [\"select *", "end": 1181, "score": 0.999931275844574, "start": 1161, "tag": "EMAIL", "value": "sammilhoso@email.com" } ]
test/integration/parenthesin/database_test.clj
parenthesin/microservice-boilerplate-malli
4
(ns integration.parenthesin.database-test (:require [clojure.test :refer [use-fixtures]] [integration.parenthesin.util :as util] [integration.parenthesin.util.database :as util.database] [parenthesin.utils :as u] [state-flow.api :refer [defflow]] [state-flow.assertions.matcher-combinators :refer [match?]] [state-flow.core :as state-flow :refer [flow]])) (use-fixtures :once u/with-malli-intrumentation) (defflow flow-integration-database-test {:init util/start-system! :cleanup util/stop-system! :fail-fast? true} (flow "creates a table, insert data and checks return in the database" (util.database/execute! ["create table if not exists address ( id serial primary key, name varchar(32), email varchar(255))"]) (util.database/execute! ["insert into address(name,email) values('Sam Campos de Milho','sammilhoso@email.com')"]) (match? [#:address{:id 1 :name "Sam Campos de Milho" :email "sammilhoso@email.com"}] (util.database/execute! ["select * from address"]))))
50353
(ns integration.parenthesin.database-test (:require [clojure.test :refer [use-fixtures]] [integration.parenthesin.util :as util] [integration.parenthesin.util.database :as util.database] [parenthesin.utils :as u] [state-flow.api :refer [defflow]] [state-flow.assertions.matcher-combinators :refer [match?]] [state-flow.core :as state-flow :refer [flow]])) (use-fixtures :once u/with-malli-intrumentation) (defflow flow-integration-database-test {:init util/start-system! :cleanup util/stop-system! :fail-fast? true} (flow "creates a table, insert data and checks return in the database" (util.database/execute! ["create table if not exists address ( id serial primary key, name varchar(32), email varchar(255))"]) (util.database/execute! ["insert into address(name,email) values('<NAME>','<EMAIL>')"]) (match? [#:address{:id 1 :name "<NAME>" :email "<EMAIL>"}] (util.database/execute! ["select * from address"]))))
true
(ns integration.parenthesin.database-test (:require [clojure.test :refer [use-fixtures]] [integration.parenthesin.util :as util] [integration.parenthesin.util.database :as util.database] [parenthesin.utils :as u] [state-flow.api :refer [defflow]] [state-flow.assertions.matcher-combinators :refer [match?]] [state-flow.core :as state-flow :refer [flow]])) (use-fixtures :once u/with-malli-intrumentation) (defflow flow-integration-database-test {:init util/start-system! :cleanup util/stop-system! :fail-fast? true} (flow "creates a table, insert data and checks return in the database" (util.database/execute! ["create table if not exists address ( id serial primary key, name varchar(32), email varchar(255))"]) (util.database/execute! ["insert into address(name,email) values('PI:NAME:<NAME>END_PI','PI:EMAIL:<EMAIL>END_PI')"]) (match? [#:address{:id 1 :name "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}] (util.database/execute! ["select * from address"]))))
[ { "context": " Websocket support for Clojure\n\n;;; Copyright 2015 Chris Hapgood\n\n;;; Licensed under the Apache License, Version 2", "end": 112, "score": 0.9998866319656372, "start": 99, "tag": "NAME", "value": "Chris Hapgood" }, { "context": "Client Websocket Extensions- Clojure\"\n {:author \"Chris Hapgood\"}\n (:refer-clojure :exclude [await send])\n (:im", "end": 786, "score": 0.9998977780342102, "start": 773, "tag": "NAME", "value": "Chris Hapgood" } ]
src/clj/http/async/client/websocket.clj
slipset/http.async.client
116
;;; ## websocket.clj -- Asynchronous HTTP Client Websocket support for Clojure ;;; Copyright 2015 Chris Hapgood ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (ns http.async.client.websocket "Asynchronous HTTP Client Websocket Extensions- Clojure" {:author "Chris Hapgood"} (:refer-clojure :exclude [await send]) (:import (org.asynchttpclient.ws WebSocket WebSocketUpgradeHandler$Builder WebSocketListener) (org.asynchttpclient.netty.ws NettyWebSocket))) (defprotocol IWebSocket (-sendText [this text]) (-sendByte [this byte])) (extend-protocol IWebSocket NettyWebSocket (-sendText [ws text] (.sendTextFrame ws text)) (-sendByte [ws byte] (.sendBinaryFrame ws byte))) (defn send "Send message via WebSocket." [ws & {text :text byte :byte}] (when (satisfies? IWebSocket ws) (if text (-sendText ws text) (-sendByte ws byte)))) (defn- create-listener [ws text-cb byte-cb open-cb close-cb error-cb] (reify WebSocketListener (^{:tag void} onOpen [_ #^WebSocket soc] (reset! ws soc) (when open-cb (open-cb soc))) (onClose [_ ws* code reason] (when close-cb (close-cb ws* code reason)) (reset! ws nil)) (^{:tag void} onError [_ #^Throwable t] (reset! ws nil) (when error-cb (error-cb @ws t))) (onTextFrame [_ s _ _] (when text-cb (text-cb @ws s))) (onBinaryFrame [_ b _ _] (when byte-cb (byte-cb @ws b))))) (defn upgrade-handler "Creates a WebSocketUpgradeHandler" {:tag WebSocket} [& {text-cb :text byte-cb :byte open-cb :open close-cb :close error-cb :error}] {:pre [(not (and text-cb byte-cb))]} (let [b (WebSocketUpgradeHandler$Builder.) ws (atom nil)] (.addWebSocketListener b (create-listener ws text-cb byte-cb open-cb close-cb error-cb)) (.build b)))
105174
;;; ## websocket.clj -- Asynchronous HTTP Client Websocket support for Clojure ;;; Copyright 2015 <NAME> ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (ns http.async.client.websocket "Asynchronous HTTP Client Websocket Extensions- Clojure" {:author "<NAME>"} (:refer-clojure :exclude [await send]) (:import (org.asynchttpclient.ws WebSocket WebSocketUpgradeHandler$Builder WebSocketListener) (org.asynchttpclient.netty.ws NettyWebSocket))) (defprotocol IWebSocket (-sendText [this text]) (-sendByte [this byte])) (extend-protocol IWebSocket NettyWebSocket (-sendText [ws text] (.sendTextFrame ws text)) (-sendByte [ws byte] (.sendBinaryFrame ws byte))) (defn send "Send message via WebSocket." [ws & {text :text byte :byte}] (when (satisfies? IWebSocket ws) (if text (-sendText ws text) (-sendByte ws byte)))) (defn- create-listener [ws text-cb byte-cb open-cb close-cb error-cb] (reify WebSocketListener (^{:tag void} onOpen [_ #^WebSocket soc] (reset! ws soc) (when open-cb (open-cb soc))) (onClose [_ ws* code reason] (when close-cb (close-cb ws* code reason)) (reset! ws nil)) (^{:tag void} onError [_ #^Throwable t] (reset! ws nil) (when error-cb (error-cb @ws t))) (onTextFrame [_ s _ _] (when text-cb (text-cb @ws s))) (onBinaryFrame [_ b _ _] (when byte-cb (byte-cb @ws b))))) (defn upgrade-handler "Creates a WebSocketUpgradeHandler" {:tag WebSocket} [& {text-cb :text byte-cb :byte open-cb :open close-cb :close error-cb :error}] {:pre [(not (and text-cb byte-cb))]} (let [b (WebSocketUpgradeHandler$Builder.) ws (atom nil)] (.addWebSocketListener b (create-listener ws text-cb byte-cb open-cb close-cb error-cb)) (.build b)))
true
;;; ## websocket.clj -- Asynchronous HTTP Client Websocket support for Clojure ;;; Copyright 2015 PI:NAME:<NAME>END_PI ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (ns http.async.client.websocket "Asynchronous HTTP Client Websocket Extensions- Clojure" {:author "PI:NAME:<NAME>END_PI"} (:refer-clojure :exclude [await send]) (:import (org.asynchttpclient.ws WebSocket WebSocketUpgradeHandler$Builder WebSocketListener) (org.asynchttpclient.netty.ws NettyWebSocket))) (defprotocol IWebSocket (-sendText [this text]) (-sendByte [this byte])) (extend-protocol IWebSocket NettyWebSocket (-sendText [ws text] (.sendTextFrame ws text)) (-sendByte [ws byte] (.sendBinaryFrame ws byte))) (defn send "Send message via WebSocket." [ws & {text :text byte :byte}] (when (satisfies? IWebSocket ws) (if text (-sendText ws text) (-sendByte ws byte)))) (defn- create-listener [ws text-cb byte-cb open-cb close-cb error-cb] (reify WebSocketListener (^{:tag void} onOpen [_ #^WebSocket soc] (reset! ws soc) (when open-cb (open-cb soc))) (onClose [_ ws* code reason] (when close-cb (close-cb ws* code reason)) (reset! ws nil)) (^{:tag void} onError [_ #^Throwable t] (reset! ws nil) (when error-cb (error-cb @ws t))) (onTextFrame [_ s _ _] (when text-cb (text-cb @ws s))) (onBinaryFrame [_ b _ _] (when byte-cb (byte-cb @ws b))))) (defn upgrade-handler "Creates a WebSocketUpgradeHandler" {:tag WebSocket} [& {text-cb :text byte-cb :byte open-cb :open close-cb :close error-cb :error}] {:pre [(not (and text-cb byte-cb))]} (let [b (WebSocketUpgradeHandler$Builder.) ws (atom nil)] (.addWebSocketListener b (create-listener ws text-cb byte-cb open-cb close-cb error-cb)) (.build b)))
[ { "context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.test.basal.meta\n", "end": 597, "score": 0.999852180480957, "start": 584, "tag": "NAME", "value": "Kenneth Leung" } ]
src/test/clojure/czlab/test/basal/meta.clj
llnek/xlib
0
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, Kenneth Leung. All rights reserved. (ns czlab.test.basal.meta (:require [clojure.test :as ct] [clojure.string :as cs] [czlab.basal.meta :as m] [czlab.basal.core :refer [ensure?? ensure-thrown??] :as c])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- f1 ([]) ([x]) ([x y]) ([x y {:keys [ff]}])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- f2 ([]) ([x]) ([x y]) ([x y {:keys [ff]}]) ([x y f p d & z])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/deftest test-meta (ensure?? "count-arity" (let [[r v?] (m/count-arity f1)] (and (false? v?) (contains? r 0) (contains? r 1) (contains? r 2) (contains? r 3)))) (ensure?? "count-arity" (let [[r v?] (m/count-arity (fn [a b]))] (and (false? v?) (contains? r 2)))) (ensure?? "count-arity" (let [[r v?] (m/count-arity f2)] (and (true? v?) (contains? r 0) (contains? r 1) (contains? r 2) (contains? r 3) (contains? r 5)))) (ensure?? "is-child?" (m/is-child? Number Integer)) (ensure?? "is-child?" (m/is-child? Number (Integer. 3))) (ensure?? "is-boolean?" (m/is-boolean? (class (boolean true)))) (ensure?? "is-char?" (m/is-char? (class (char 3)))) (ensure?? "is-int?" (m/is-int? (class (int 3)))) (ensure?? "is-long?" (m/is-long? (class (long 3)))) (ensure?? "is-float?" (m/is-float? (class (float 3.2)))) (ensure?? "is-double?" (m/is-double? (class (double 3.2)))) (ensure?? "is-byte?" (m/is-byte? (class (aget (byte-array 1) 0)))) (ensure?? "is-short?" (m/is-short? (class (short 3)))) (ensure?? "is-string?" (m/is-string? (class ""))) (ensure?? "is-bytes?" (m/is-bytes? (class (byte-array 0)))) (ensure?? "is-bytes?" (not (m/is-bytes? nil))) (ensure?? "is-chars?" (not (m/is-chars? nil))) (ensure?? "forname" (not (nil? (m/forname "java.lang.String")))) (ensure?? "load-class" (not (nil? (m/load-class "java.lang.String")))) (ensure?? "obj<>" (c/is? java.lang.StringBuilder (m/obj<> "java.lang.StringBuilder" String "a"))) (ensure?? "list-parents" (== 1 (count (m/list-parents (Class/forName "java.lang.String"))))) (ensure?? "list-methods" (>= (count (m/list-methods (Class/forName "java.lang.String"))) 40)) (ensure?? "list-fields" (>= (count (m/list-fields (Class/forName "java.lang.String"))) 5)) (ensure?? "test-end" (== 1 1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ct/deftest ^:test-meta basal-test-meta (ct/is (c/clj-test?? test-meta))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
48364
;; 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. ;; ;; Copyright © 2013-2022, <NAME>. All rights reserved. (ns czlab.test.basal.meta (:require [clojure.test :as ct] [clojure.string :as cs] [czlab.basal.meta :as m] [czlab.basal.core :refer [ensure?? ensure-thrown??] :as c])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- f1 ([]) ([x]) ([x y]) ([x y {:keys [ff]}])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- f2 ([]) ([x]) ([x y]) ([x y {:keys [ff]}]) ([x y f p d & z])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/deftest test-meta (ensure?? "count-arity" (let [[r v?] (m/count-arity f1)] (and (false? v?) (contains? r 0) (contains? r 1) (contains? r 2) (contains? r 3)))) (ensure?? "count-arity" (let [[r v?] (m/count-arity (fn [a b]))] (and (false? v?) (contains? r 2)))) (ensure?? "count-arity" (let [[r v?] (m/count-arity f2)] (and (true? v?) (contains? r 0) (contains? r 1) (contains? r 2) (contains? r 3) (contains? r 5)))) (ensure?? "is-child?" (m/is-child? Number Integer)) (ensure?? "is-child?" (m/is-child? Number (Integer. 3))) (ensure?? "is-boolean?" (m/is-boolean? (class (boolean true)))) (ensure?? "is-char?" (m/is-char? (class (char 3)))) (ensure?? "is-int?" (m/is-int? (class (int 3)))) (ensure?? "is-long?" (m/is-long? (class (long 3)))) (ensure?? "is-float?" (m/is-float? (class (float 3.2)))) (ensure?? "is-double?" (m/is-double? (class (double 3.2)))) (ensure?? "is-byte?" (m/is-byte? (class (aget (byte-array 1) 0)))) (ensure?? "is-short?" (m/is-short? (class (short 3)))) (ensure?? "is-string?" (m/is-string? (class ""))) (ensure?? "is-bytes?" (m/is-bytes? (class (byte-array 0)))) (ensure?? "is-bytes?" (not (m/is-bytes? nil))) (ensure?? "is-chars?" (not (m/is-chars? nil))) (ensure?? "forname" (not (nil? (m/forname "java.lang.String")))) (ensure?? "load-class" (not (nil? (m/load-class "java.lang.String")))) (ensure?? "obj<>" (c/is? java.lang.StringBuilder (m/obj<> "java.lang.StringBuilder" String "a"))) (ensure?? "list-parents" (== 1 (count (m/list-parents (Class/forName "java.lang.String"))))) (ensure?? "list-methods" (>= (count (m/list-methods (Class/forName "java.lang.String"))) 40)) (ensure?? "list-fields" (>= (count (m/list-fields (Class/forName "java.lang.String"))) 5)) (ensure?? "test-end" (== 1 1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ct/deftest ^:test-meta basal-test-meta (ct/is (c/clj-test?? test-meta))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
true
;; 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. ;; ;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved. (ns czlab.test.basal.meta (:require [clojure.test :as ct] [clojure.string :as cs] [czlab.basal.meta :as m] [czlab.basal.core :refer [ensure?? ensure-thrown??] :as c])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- f1 ([]) ([x]) ([x y]) ([x y {:keys [ff]}])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- f2 ([]) ([x]) ([x y]) ([x y {:keys [ff]}]) ([x y f p d & z])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/deftest test-meta (ensure?? "count-arity" (let [[r v?] (m/count-arity f1)] (and (false? v?) (contains? r 0) (contains? r 1) (contains? r 2) (contains? r 3)))) (ensure?? "count-arity" (let [[r v?] (m/count-arity (fn [a b]))] (and (false? v?) (contains? r 2)))) (ensure?? "count-arity" (let [[r v?] (m/count-arity f2)] (and (true? v?) (contains? r 0) (contains? r 1) (contains? r 2) (contains? r 3) (contains? r 5)))) (ensure?? "is-child?" (m/is-child? Number Integer)) (ensure?? "is-child?" (m/is-child? Number (Integer. 3))) (ensure?? "is-boolean?" (m/is-boolean? (class (boolean true)))) (ensure?? "is-char?" (m/is-char? (class (char 3)))) (ensure?? "is-int?" (m/is-int? (class (int 3)))) (ensure?? "is-long?" (m/is-long? (class (long 3)))) (ensure?? "is-float?" (m/is-float? (class (float 3.2)))) (ensure?? "is-double?" (m/is-double? (class (double 3.2)))) (ensure?? "is-byte?" (m/is-byte? (class (aget (byte-array 1) 0)))) (ensure?? "is-short?" (m/is-short? (class (short 3)))) (ensure?? "is-string?" (m/is-string? (class ""))) (ensure?? "is-bytes?" (m/is-bytes? (class (byte-array 0)))) (ensure?? "is-bytes?" (not (m/is-bytes? nil))) (ensure?? "is-chars?" (not (m/is-chars? nil))) (ensure?? "forname" (not (nil? (m/forname "java.lang.String")))) (ensure?? "load-class" (not (nil? (m/load-class "java.lang.String")))) (ensure?? "obj<>" (c/is? java.lang.StringBuilder (m/obj<> "java.lang.StringBuilder" String "a"))) (ensure?? "list-parents" (== 1 (count (m/list-parents (Class/forName "java.lang.String"))))) (ensure?? "list-methods" (>= (count (m/list-methods (Class/forName "java.lang.String"))) 40)) (ensure?? "list-fields" (>= (count (m/list-fields (Class/forName "java.lang.String"))) 5)) (ensure?? "test-end" (== 1 1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ct/deftest ^:test-meta basal-test-meta (ct/is (c/clj-test?? test-meta))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": " Map\n; Date: March 17, 2016.\n; Authors:\n; A01371743 Luis Eduardo Ballinas Aguilar\n;------------------", "end": 147, "score": 0.9917981624603271, "start": 138, "tag": "USERNAME", "value": "A01371743" }, { "context": "e: March 17, 2016.\n; Authors:\n; A01371743 Luis Eduardo Ballinas Aguilar\n;------------------------------------------------", "end": 177, "score": 0.9998390078544617, "start": 148, "tag": "NAME", "value": "Luis Eduardo Ballinas Aguilar" } ]
4clojure/problem_118.clj
lu15v/TC2006
0
;---------------------------------------------------------- ; Problem 118: Re-implement Map ; Date: March 17, 2016. ; Authors: ; A01371743 Luis Eduardo Ballinas Aguilar ;---------------------------------------------------------- (use 'clojure.test) (def problem118 (fn [f x] (if(empty? x) nil (lazy-seq (cons (f (first x)) (problem118 f (rest x))))))) (deftest test-problem118 (is(= [3 4 5 6 7] (problem118 inc [2 3 4 5 6]))) (is(= (repeat 10 nil) (problem118 (fn [_] nil) (range 10)))) (is(= [1000000 1000001] (->> (problem118 inc (range)) (drop (dec 1000000)) (take 2))))) (run-tests)
62962
;---------------------------------------------------------- ; Problem 118: Re-implement Map ; Date: March 17, 2016. ; Authors: ; A01371743 <NAME> ;---------------------------------------------------------- (use 'clojure.test) (def problem118 (fn [f x] (if(empty? x) nil (lazy-seq (cons (f (first x)) (problem118 f (rest x))))))) (deftest test-problem118 (is(= [3 4 5 6 7] (problem118 inc [2 3 4 5 6]))) (is(= (repeat 10 nil) (problem118 (fn [_] nil) (range 10)))) (is(= [1000000 1000001] (->> (problem118 inc (range)) (drop (dec 1000000)) (take 2))))) (run-tests)
true
;---------------------------------------------------------- ; Problem 118: Re-implement Map ; Date: March 17, 2016. ; Authors: ; A01371743 PI:NAME:<NAME>END_PI ;---------------------------------------------------------- (use 'clojure.test) (def problem118 (fn [f x] (if(empty? x) nil (lazy-seq (cons (f (first x)) (problem118 f (rest x))))))) (deftest test-problem118 (is(= [3 4 5 6 7] (problem118 inc [2 3 4 5 6]))) (is(= (repeat 10 nil) (problem118 (fn [_] nil) (range 10)))) (is(= [1000000 1000001] (->> (problem118 inc (range)) (drop (dec 1000000)) (take 2))))) (run-tests)
[ { "context": ".0646 -165.374 3 1.5 4 3 2 1]\n [2 \"Stout Burgers & Beers\" 11 34.0996 -118.329 2 2.0 11 2 1 1]\n ", "end": 5742, "score": 0.7142825126647949, "start": 5721, "tag": "NAME", "value": "Stout Burgers & Beers" } ]
c#-metabase/test/metabase/transforms/core_test.clj
hanakhry/Crime_Admin
0
(ns metabase.transforms.core-test (:require [clojure.test :refer :all] [medley.core :as m] [metabase.domain-entities.core :as de] [metabase.domain-entities.specs :as de.specs] [metabase.models.card :as card :refer [Card]] [metabase.models.collection :refer [Collection]] [metabase.models.table :as table :refer [Table]] [metabase.query-processor :as qp] [metabase.test :as mt] [metabase.test.domain-entities :refer :all] [metabase.test.transforms :refer :all] [metabase.transforms.core :as t] [metabase.transforms.specs :as t.specs] [metabase.util :as u] [toucan.db :as db])) (use-fixtures :each (fn [thunk] (mt/with-model-cleanup [Card Collection] (thunk)))) (def ^:private test-bindings (delay (with-test-domain-entity-specs (let [table (m/find-first (comp #{(mt/id :venues)} u/the-id) (#'t/tableset (mt/id) "PUBLIC"))] {"Venues" {:dimensions (m/map-vals de/mbql-reference (get-in table [:domain_entity :dimensions])) :entity table}})))) (deftest add-bindings-test (testing "Can we accure bindings?" (let [new-bindings {"D2" [:sum [:field-id 4]] "D3" [:field-id 5]}] (is (= (update-in @test-bindings ["Venues" :dimensions] merge new-bindings) (#'t/add-bindings @test-bindings "Venues" new-bindings))))) (testing "Gracefully handle nil" (is (= @test-bindings (#'t/add-bindings @test-bindings "Venues" nil))))) (deftest mbql-reference->col-name-test (is (= "PRICE" (#'t/mbql-reference->col-name [:field (mt/id :venues :price) nil]))) (is (= "PRICE" (#'t/mbql-reference->col-name [:field "PRICE" {:base-type :type/Integer}]))) (is (= "PRICE" (#'t/mbql-reference->col-name [{:foo [:field (mt/id :venues :price) nil]}])))) (deftest ->source-table-reference-test (testing "Can we turn a given entity into a format suitable for a query's `:source_table`?" (testing "for a Table" (is (= (mt/id :venues) (#'t/->source-table-reference (Table (mt/id :venues)))))) (testing "for a Card" (mt/with-temp Card [{card-id :id}] (is (= (str "card__" card-id) (#'t/->source-table-reference (Card card-id)))))))) (deftest tableset-test (testing "Can we get a tableset for a given schema?" (is (= (db/select-ids Table :db_id (mt/id)) (set (map u/the-id (#'t/tableset (mt/id) "PUBLIC"))))))) (deftest find-tables-with-domain-entity-test (with-test-domain-entity-specs (testing "Can we filter a tableset by domain entity?" (is (= [(mt/id :venues)] (map u/the-id (#'t/find-tables-with-domain-entity (#'t/tableset (mt/id) "PUBLIC") (@de.specs/domain-entity-specs "Venues")))))) (testing "Gracefully handle no-match" (with-test-domain-entity-specs (is (= nil (not-empty (#'t/find-tables-with-domain-entity [] (@de.specs/domain-entity-specs "Venues"))))))))) (deftest resulting-entities-test (testing "Can we extract results from the final bindings?" (with-test-transform-specs (is (= [(mt/id :venues)] (map u/the-id (#'t/resulting-entities {"VenuesEnhanced" {:entity (Table (mt/id :venues)) :dimensions {"D1" [:field-id 1]}}} (first @t.specs/transform-specs)))))))) (deftest tables-matching-requirements-test (testing "Can we find a table set matching requirements of a given spec?" (with-test-transform-specs (with-test-domain-entity-specs (is (= [(mt/id :venues)] (map u/the-id (#'t/tables-matching-requirements (#'t/tableset (mt/id) "PUBLIC") (first @t.specs/transform-specs))))))))) (deftest tableset->bindings-test (testing "Can we turn a tableset into corresponding bindings?" (with-test-domain-entity-specs (is (= @test-bindings (#'t/tableset->bindings (filter (comp #{(mt/id :venues)} u/the-id) (#'t/tableset (mt/id) "PUBLIC")))))))) (deftest validation-test (with-test-domain-entity-specs (with-test-transform-specs (testing "Is the validation of results working?" (is (#'t/validate-results {"VenuesEnhanced" {:entity (card/map->CardInstance {:result_metadata [{:name "AvgPrice"} {:name "MaxPrice"} {:name "MinPrice"}]}) :dimensions {"D1" [:field-id 1]}}} (first @t.specs/transform-specs)))) (testing "... and do we throw if we didn't get what we expected?" (is (thrown? java.lang.AssertionError (#'t/validate-results {"VenuesEnhanced" {:entity (Table (mt/id :venues)) :dimensions {"D1" [:field-id 1]}}} (first @t.specs/transform-specs)))))))) (deftest transform-test (testing "Run the transform and make sure it produces the correct result" (mt/with-test-user :rasta (with-test-domain-entity-specs (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 1.5 4 3 2 1] [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 2.0 11 2 1 1] [3 "The Apple Pan" 11 34.0406 -118.428 2 2.0 11 2 1 1]] (-> (t/apply-transform! (mt/id) "PUBLIC" test-transform-spec) first :dataset_query qp/process-query mt/rows))))))) (deftest correct-transforms-for-table-test (testing "Can we find the right transform(s) for a given table" (with-test-transform-specs (with-test-domain-entity-specs (is (= "Test transform" (-> (t/candidates (Table (mt/id :venues))) first :name)))))))
35691
(ns metabase.transforms.core-test (:require [clojure.test :refer :all] [medley.core :as m] [metabase.domain-entities.core :as de] [metabase.domain-entities.specs :as de.specs] [metabase.models.card :as card :refer [Card]] [metabase.models.collection :refer [Collection]] [metabase.models.table :as table :refer [Table]] [metabase.query-processor :as qp] [metabase.test :as mt] [metabase.test.domain-entities :refer :all] [metabase.test.transforms :refer :all] [metabase.transforms.core :as t] [metabase.transforms.specs :as t.specs] [metabase.util :as u] [toucan.db :as db])) (use-fixtures :each (fn [thunk] (mt/with-model-cleanup [Card Collection] (thunk)))) (def ^:private test-bindings (delay (with-test-domain-entity-specs (let [table (m/find-first (comp #{(mt/id :venues)} u/the-id) (#'t/tableset (mt/id) "PUBLIC"))] {"Venues" {:dimensions (m/map-vals de/mbql-reference (get-in table [:domain_entity :dimensions])) :entity table}})))) (deftest add-bindings-test (testing "Can we accure bindings?" (let [new-bindings {"D2" [:sum [:field-id 4]] "D3" [:field-id 5]}] (is (= (update-in @test-bindings ["Venues" :dimensions] merge new-bindings) (#'t/add-bindings @test-bindings "Venues" new-bindings))))) (testing "Gracefully handle nil" (is (= @test-bindings (#'t/add-bindings @test-bindings "Venues" nil))))) (deftest mbql-reference->col-name-test (is (= "PRICE" (#'t/mbql-reference->col-name [:field (mt/id :venues :price) nil]))) (is (= "PRICE" (#'t/mbql-reference->col-name [:field "PRICE" {:base-type :type/Integer}]))) (is (= "PRICE" (#'t/mbql-reference->col-name [{:foo [:field (mt/id :venues :price) nil]}])))) (deftest ->source-table-reference-test (testing "Can we turn a given entity into a format suitable for a query's `:source_table`?" (testing "for a Table" (is (= (mt/id :venues) (#'t/->source-table-reference (Table (mt/id :venues)))))) (testing "for a Card" (mt/with-temp Card [{card-id :id}] (is (= (str "card__" card-id) (#'t/->source-table-reference (Card card-id)))))))) (deftest tableset-test (testing "Can we get a tableset for a given schema?" (is (= (db/select-ids Table :db_id (mt/id)) (set (map u/the-id (#'t/tableset (mt/id) "PUBLIC"))))))) (deftest find-tables-with-domain-entity-test (with-test-domain-entity-specs (testing "Can we filter a tableset by domain entity?" (is (= [(mt/id :venues)] (map u/the-id (#'t/find-tables-with-domain-entity (#'t/tableset (mt/id) "PUBLIC") (@de.specs/domain-entity-specs "Venues")))))) (testing "Gracefully handle no-match" (with-test-domain-entity-specs (is (= nil (not-empty (#'t/find-tables-with-domain-entity [] (@de.specs/domain-entity-specs "Venues"))))))))) (deftest resulting-entities-test (testing "Can we extract results from the final bindings?" (with-test-transform-specs (is (= [(mt/id :venues)] (map u/the-id (#'t/resulting-entities {"VenuesEnhanced" {:entity (Table (mt/id :venues)) :dimensions {"D1" [:field-id 1]}}} (first @t.specs/transform-specs)))))))) (deftest tables-matching-requirements-test (testing "Can we find a table set matching requirements of a given spec?" (with-test-transform-specs (with-test-domain-entity-specs (is (= [(mt/id :venues)] (map u/the-id (#'t/tables-matching-requirements (#'t/tableset (mt/id) "PUBLIC") (first @t.specs/transform-specs))))))))) (deftest tableset->bindings-test (testing "Can we turn a tableset into corresponding bindings?" (with-test-domain-entity-specs (is (= @test-bindings (#'t/tableset->bindings (filter (comp #{(mt/id :venues)} u/the-id) (#'t/tableset (mt/id) "PUBLIC")))))))) (deftest validation-test (with-test-domain-entity-specs (with-test-transform-specs (testing "Is the validation of results working?" (is (#'t/validate-results {"VenuesEnhanced" {:entity (card/map->CardInstance {:result_metadata [{:name "AvgPrice"} {:name "MaxPrice"} {:name "MinPrice"}]}) :dimensions {"D1" [:field-id 1]}}} (first @t.specs/transform-specs)))) (testing "... and do we throw if we didn't get what we expected?" (is (thrown? java.lang.AssertionError (#'t/validate-results {"VenuesEnhanced" {:entity (Table (mt/id :venues)) :dimensions {"D1" [:field-id 1]}}} (first @t.specs/transform-specs)))))))) (deftest transform-test (testing "Run the transform and make sure it produces the correct result" (mt/with-test-user :rasta (with-test-domain-entity-specs (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 1.5 4 3 2 1] [2 "<NAME>" 11 34.0996 -118.329 2 2.0 11 2 1 1] [3 "The Apple Pan" 11 34.0406 -118.428 2 2.0 11 2 1 1]] (-> (t/apply-transform! (mt/id) "PUBLIC" test-transform-spec) first :dataset_query qp/process-query mt/rows))))))) (deftest correct-transforms-for-table-test (testing "Can we find the right transform(s) for a given table" (with-test-transform-specs (with-test-domain-entity-specs (is (= "Test transform" (-> (t/candidates (Table (mt/id :venues))) first :name)))))))
true
(ns metabase.transforms.core-test (:require [clojure.test :refer :all] [medley.core :as m] [metabase.domain-entities.core :as de] [metabase.domain-entities.specs :as de.specs] [metabase.models.card :as card :refer [Card]] [metabase.models.collection :refer [Collection]] [metabase.models.table :as table :refer [Table]] [metabase.query-processor :as qp] [metabase.test :as mt] [metabase.test.domain-entities :refer :all] [metabase.test.transforms :refer :all] [metabase.transforms.core :as t] [metabase.transforms.specs :as t.specs] [metabase.util :as u] [toucan.db :as db])) (use-fixtures :each (fn [thunk] (mt/with-model-cleanup [Card Collection] (thunk)))) (def ^:private test-bindings (delay (with-test-domain-entity-specs (let [table (m/find-first (comp #{(mt/id :venues)} u/the-id) (#'t/tableset (mt/id) "PUBLIC"))] {"Venues" {:dimensions (m/map-vals de/mbql-reference (get-in table [:domain_entity :dimensions])) :entity table}})))) (deftest add-bindings-test (testing "Can we accure bindings?" (let [new-bindings {"D2" [:sum [:field-id 4]] "D3" [:field-id 5]}] (is (= (update-in @test-bindings ["Venues" :dimensions] merge new-bindings) (#'t/add-bindings @test-bindings "Venues" new-bindings))))) (testing "Gracefully handle nil" (is (= @test-bindings (#'t/add-bindings @test-bindings "Venues" nil))))) (deftest mbql-reference->col-name-test (is (= "PRICE" (#'t/mbql-reference->col-name [:field (mt/id :venues :price) nil]))) (is (= "PRICE" (#'t/mbql-reference->col-name [:field "PRICE" {:base-type :type/Integer}]))) (is (= "PRICE" (#'t/mbql-reference->col-name [{:foo [:field (mt/id :venues :price) nil]}])))) (deftest ->source-table-reference-test (testing "Can we turn a given entity into a format suitable for a query's `:source_table`?" (testing "for a Table" (is (= (mt/id :venues) (#'t/->source-table-reference (Table (mt/id :venues)))))) (testing "for a Card" (mt/with-temp Card [{card-id :id}] (is (= (str "card__" card-id) (#'t/->source-table-reference (Card card-id)))))))) (deftest tableset-test (testing "Can we get a tableset for a given schema?" (is (= (db/select-ids Table :db_id (mt/id)) (set (map u/the-id (#'t/tableset (mt/id) "PUBLIC"))))))) (deftest find-tables-with-domain-entity-test (with-test-domain-entity-specs (testing "Can we filter a tableset by domain entity?" (is (= [(mt/id :venues)] (map u/the-id (#'t/find-tables-with-domain-entity (#'t/tableset (mt/id) "PUBLIC") (@de.specs/domain-entity-specs "Venues")))))) (testing "Gracefully handle no-match" (with-test-domain-entity-specs (is (= nil (not-empty (#'t/find-tables-with-domain-entity [] (@de.specs/domain-entity-specs "Venues"))))))))) (deftest resulting-entities-test (testing "Can we extract results from the final bindings?" (with-test-transform-specs (is (= [(mt/id :venues)] (map u/the-id (#'t/resulting-entities {"VenuesEnhanced" {:entity (Table (mt/id :venues)) :dimensions {"D1" [:field-id 1]}}} (first @t.specs/transform-specs)))))))) (deftest tables-matching-requirements-test (testing "Can we find a table set matching requirements of a given spec?" (with-test-transform-specs (with-test-domain-entity-specs (is (= [(mt/id :venues)] (map u/the-id (#'t/tables-matching-requirements (#'t/tableset (mt/id) "PUBLIC") (first @t.specs/transform-specs))))))))) (deftest tableset->bindings-test (testing "Can we turn a tableset into corresponding bindings?" (with-test-domain-entity-specs (is (= @test-bindings (#'t/tableset->bindings (filter (comp #{(mt/id :venues)} u/the-id) (#'t/tableset (mt/id) "PUBLIC")))))))) (deftest validation-test (with-test-domain-entity-specs (with-test-transform-specs (testing "Is the validation of results working?" (is (#'t/validate-results {"VenuesEnhanced" {:entity (card/map->CardInstance {:result_metadata [{:name "AvgPrice"} {:name "MaxPrice"} {:name "MinPrice"}]}) :dimensions {"D1" [:field-id 1]}}} (first @t.specs/transform-specs)))) (testing "... and do we throw if we didn't get what we expected?" (is (thrown? java.lang.AssertionError (#'t/validate-results {"VenuesEnhanced" {:entity (Table (mt/id :venues)) :dimensions {"D1" [:field-id 1]}}} (first @t.specs/transform-specs)))))))) (deftest transform-test (testing "Run the transform and make sure it produces the correct result" (mt/with-test-user :rasta (with-test-domain-entity-specs (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 1.5 4 3 2 1] [2 "PI:NAME:<NAME>END_PI" 11 34.0996 -118.329 2 2.0 11 2 1 1] [3 "The Apple Pan" 11 34.0406 -118.428 2 2.0 11 2 1 1]] (-> (t/apply-transform! (mt/id) "PUBLIC" test-transform-spec) first :dataset_query qp/process-query mt/rows))))))) (deftest correct-transforms-for-table-test (testing "Can we find the right transform(s) for a given table" (with-test-transform-specs (with-test-domain-entity-specs (is (= "Test transform" (-> (t/candidates (Table (mt/id :venues))) first :name)))))))
[ { "context": "r-id app)))))))\n\n(comment\n (get-handled-reviews \"bob\")\n (get-handled-reviews \"carl\"))\n\n(defn- check-f", "end": 14489, "score": 0.9545735716819763, "start": 14486, "tag": "NAME", "value": "bob" }, { "context": "et-handled-reviews \"bob\")\n (get-handled-reviews \"carl\"))\n\n(defn- check-for-unneeded-actions\n \"Checks w", "end": 14520, "score": 0.9922311902046204, "start": 14516, "tag": "NAME", "value": "carl" }, { "context": "ns #{...}}\n :applicant-attributes {\\\"eppn\\\" \\\"developer\\\"\n \\\"email\\\" \\\"develop", "end": 22604, "score": 0.5354211926460266, "start": 22595, "tag": "USERNAME", "value": "developer" }, { "context": "veloper\\\"\n \\\"email\\\" \\\"developer@e.mail\\\"\n \\\"displayName\\\" \\\"d", "end": 22663, "score": 0.9995403289794922, "start": 22647, "tag": "EMAIL", "value": "developer@e.mail" }, { "context": "l\\\"\n \\\"displayName\\\" \\\"deve\\\"\n \\\"surname\\\" \\\"loper", "end": 22716, "score": 0.9994689226150513, "start": 22712, "tag": "NAME", "value": "deve" }, { "context": "\"deve\\\"\n \\\"surname\\\" \\\"loper\\\"\n ...}\n :catalogu", "end": 22766, "score": 0.9996594190597534, "start": 22761, "tag": "NAME", "value": "loper" } ]
src/clj/rems/db/applications.clj
secureb2share/secureb2share-rems
0
(ns rems.db.applications "Query functions for forms and applications." (:require [cheshire.core :as cheshire] [clj-time.coerce :as time-coerce] [clj-time.core :as time] [clojure.set :refer [difference union]] [clojure.test :refer [deftest is]] [cprop.tools :refer [merge-maps]] [medley.core :refer [map-keys]] [rems.application-util :refer [editable?]] [rems.auth.util :refer [throw-forbidden]] [rems.context :as context] [rems.db.catalogue :refer [get-localized-catalogue-items]] [rems.db.core :as db] [rems.db.entitlements :as entitlements] [rems.db.licenses :as licenses] [rems.db.roles :as roles] [rems.db.users :as users] [rems.db.workflow-actors :as actors] [rems.email :as email] [rems.form-validation :as form-validation] [rems.util :refer [getx get-username update-present]] [rems.workflow.dynamic :as dynamic]) (:import [java.io ByteArrayOutputStream FileInputStream])) (defn draft? "Is the given `application-id` for an unsaved draft application?" [application-id] (nil? application-id)) ;; TODO cache application state in db instead of always computing it from events (declare get-application-state) (defn- not-empty? [args] ((complement empty?) args)) ;;; Query functions (defn handling-event? [app e] (or (contains? #{"approve" "autoapprove" "reject" "return" "review" :rems.workflow.dynamic/approved :rems.workflow.dynamic/rejected :rems.workflow.dynamic/returned} (:event e)) ;; definitely not by applicant (and (= :event/closed (:event e)) (not= (:applicantuserid app) (:actor e))) ;; not by applicant (and (= "close" (:event e)) (not= (:applicantuserid app) (:userid e))))) ;; not by applicant (defn handled? [app] (or (contains? #{"approved" "rejected" "returned" :rems.workflow.dynamic/returned :rems.workflow.dynamic/approved :rems.workflow.dynamic/rejected} (:state app)) ;; by approver action (and (contains? #{"closed" "withdrawn" :rems.workflow.dynamic/closed} (:state app)) (some (partial handling-event? app) (concat (:events app) (:dynamic-events app)))))) (defn- get-events-of-type "Returns all events of a given type that have occured in an application. Optionally a round parameter can be provided to focus on events occuring during a given round." ([app event] (filter #(= event (:event %)) (:events app))) ([app round event] (filter #(and (= event (:event %)) (= round (:round %))) (:events app)))) (defn get-approval-events "Returns all approve events within a specific round of an application." [app round] (get-events-of-type app round "approve")) (defn get-review-events "Returns all review events that have occured in an application. Optionally a round parameter can be provided to focus on reviews occuring during a given round." ([app] (get-events-of-type app "review")) ([app round] (get-events-of-type app round "review"))) (defn get-third-party-review-events "Returns all third-party-review events that have occured in an application. Optionally a round parameter can be provided to focus on third-party-reviews occuring during a given round." ([app] (get-events-of-type app "third-party-review")) ([app round] (get-events-of-type app round "third-party-review"))) (defn get-applicant-of-application [application-id] (:applicantuserid (first (db/get-applications {:id application-id})))) (declare is-commenter?) (declare can-comment?) (declare is-decider?) (declare can-decide?) (declare is-dynamic-application?) (defn reviewed? "Returns true if the application, given as parameter, has already been reviewed normally or as a 3rd party actor by the current user. Otherwise, current hasn't yet provided feedback and false is returned." ([user-id app] (let [app-state (get-application-state (:id app))] (if (is-dynamic-application? app) (or (and (is-commenter? user-id app-state) (not (can-comment? user-id (:id app)))) (and (is-decider? user-id app-state) (not (can-decide? user-id (:id app))))) (contains? (set (map :userid (concat (get-review-events app) (get-third-party-review-events app)))) user-id)))) ([user-id app round] (reviewed? user-id (update app :events (fn [events] (filter #(= round (:round %)) events)))))) (comment (reviewed? "bob" (get-application-state 23))) (declare fix-workflow-from-db) (declare is-dynamic-handler?) (defn- is-actor? [user-id actors] (assert user-id) (assert actors) (contains? (set actors) user-id)) (defn can-act-as? [user-id application role] (assert user-id) (assert application) (assert role) (or (and (= "applied" (:state application)) (is-actor? user-id (actors/get-by-role (:id application) (:curround application) role))) (and (= "approver" role) (contains? (dynamic/possible-commands user-id (get-application-state (:id application))) :rems.workflow.dynamic/approve)))) (declare get-application-state) (defn- has-actor-role? [user-id application-id role] (assert user-id) (assert application-id) (assert role) (or (is-actor? user-id (actors/get-by-role application-id role)) (is-dynamic-handler? user-id (get-application-state application-id)))) (defn- can-approve? [user-id application] (assert user-id) (assert application) (can-act-as? user-id application "approver")) (defn- is-approver? [user-id application-id] (assert user-id) (assert application-id) (has-actor-role? user-id application-id "approver")) (defn- can-review? [user-id application] (assert user-id) (assert application) (can-act-as? user-id application "reviewer")) (defn- is-reviewer? [user-id application-id] (has-actor-role? user-id application-id "reviewer")) (defn- is-third-party-reviewer? "Checks if a given user has been requested to review the given application. Additionally a specific round can be provided to narrow the check to apply only to the given round." ([user application] (->> (:events application) (filter #(and (= "review-request" (:event %)) (= user (:userid %)))) (not-empty?))) ([user round application] (is-third-party-reviewer? user (update application :events (fn [events] (filter #(= round (:round %)) events)))))) (defn- can-third-party-review? "Checks if the current user can perform a 3rd party review action on the current round for the given application." [user-id application] (and (= "applied" (:state application)) (is-third-party-reviewer? user-id (:curround application) application))) ;; TODO add to tests (defn- is-commenter? "Checks if a given user has been requested to comment the given application." ([user application] ;; TODO calculate in backend? (->> (:dynamic-events application) (mapcat :commenters) (some #{user})))) (defn- can-comment? "Checks if the current user can perform a comment action for the given application." [user-id application-id] (let [application (dynamic/assoc-possible-commands user-id (get-application-state application-id))] (contains? (get application :possible-commands) :rems.workflow.dynamic/comment))) ;; TODO add to tests (defn- is-decider? "Checks if a given user has been requested to decide on the given application." ([user application] ;; TODO calculate in backend? (->> (:dynamic-events application) (map :decider) (some #{user})))) (defn- can-decide? "Checks if the current user can perform a decide action for the given application." [user-id application-id] (let [application (dynamic/assoc-possible-commands user-id (get-application-state application-id))] (contains? (get application :possible-commands) :rems.workflow.dynamic/decide))) (defn get-approvers [application] (actors/get-by-role (:id application) "approver")) (defn get-reviewers [application] (actors/get-by-role (:id application) "reviewer")) (defn get-third-party-reviewers "Takes as an argument a structure containing application information and a optionally the workflow round. Then returns userids for all users that have been requested to review for the given round or all rounds if not given." ([application] (set (map :userid (get-events-of-type application "review-request")))) ([application round] (set (map :userid (get-events-of-type application round "review-request"))))) (defn get-handlers [application] (let [approvers (get-approvers application) reviewers (get-reviewers application) third-party-reviewers (get-third-party-reviewers application)] (union approvers reviewers third-party-reviewers))) (defn is-applicant? [user-id application] (assert user-id) (assert application) (= user-id (:applicantuserid application))) (defn may-see-application? [user-id application] (assert user-id) (assert application) (let [application-id (:id application)] (or (is-applicant? user-id application) (is-approver? user-id application-id) (is-reviewer? user-id application-id) (is-third-party-reviewer? user-id application) (is-dynamic-handler? user-id application) (is-commenter? user-id application) (is-decider? user-id application)))) (defn- can-close? [user-id application] (assert user-id) (assert application) (let [application-id (:id application)] (or (and (is-approver? user-id application-id) (= "approved" (:state application))) (and (is-applicant? user-id application) (not= "closed" (:state application)))))) (defn- can-withdraw? [user-id application] (assert user-id) (assert application) (and (is-applicant? user-id application) (= (:state application) "applied"))) (defn- translate-catalogue-item [item] (merge item (get-in item [:localizations context/*lang*]))) (defn- get-catalogue-items "Function that returns localized catalogue-items for the given application items, `ids`. Prefetched localized catalogue items, `localized-items`, can be given as a parameter to avoid excessive database calls." ([ids] (mapv translate-catalogue-item (get-localized-catalogue-items {:items ids}))) ([ids localized-items] (mapv translate-catalogue-item (filter #(some #{(:id %)} ids) localized-items)))) (defn get-catalogue-items-by-application-id "Given an `app-id`, the function queries for all the items related to that application and calls `get-catalogue-items` to return all the catalogue items for the application with localizations." [app-id] (get-catalogue-items (mapv :item (db/get-application-items {:application app-id})))) (defn- get-catalogue-items-by-application-items "Given `application-items` and `localized-items`, catalogue items with localizations, the function `get-catalogue-items` to map all the application items to the catalogue items with localizations." [application-items localized-items] (when (seq application-items) (get-catalogue-items (mapv :item application-items) localized-items))) (defn- get-applications-impl-batch "Prefetches all possibly relevant data from the database and returns all the applications, according to the query parameters, with all the events and catalogue items associated with them." [query-params] (let [events (db/get-application-events {}) application-items (db/get-application-items) localized-items (get-localized-catalogue-items)] (doall (for [app (db/get-applications query-params)] (let [catalogue-items (get-catalogue-items-by-application-items (filter #(= (:id app) (:application %)) application-items) localized-items) app-events (for [e events :when (= (:id app) (:appid e))] ;; :appid needed only for batching (dissoc e :appid))] (assoc (get-application-state app app-events) :formid (:formid (first catalogue-items)) :catalogue-items catalogue-items)))))) (comment (->> (get-applications-impl-batch {}) (mapv :id))) (defn get-user-applications [user-id] (assert user-id "Must have user-id") (->> (get-applications-impl-batch {:applicant user-id}) (remove (comp #{"closed"} :state)))) (comment (->> (get-applications-impl-batch {:applicant "developer"}) (mapv :id)) (->> (get-applications-impl-batch {:applicant "alice"}) (mapv :id))) (defn get-approvals [user-id] (->> (get-applications-impl-batch {}) (filterv (partial can-approve? user-id)))) (comment (->> (get-approvals "developer") (mapv :id))) (defn actors-of-dynamic-application [application] (map :actor (:dynamic-events application))) ;; TODO combine handled approvals and reviews as just handled applications (defn get-handled-approvals [user-id] (let [actors (db/get-actors-for-applications {:role "approver"})] (->> (get-applications-impl-batch {}) (filterv handled?) (filterv (fn [app] (let [application (get-application-state (:id app))] (if (is-dynamic-application? application) (contains? (set (actors-of-dynamic-application application)) user-id) (is-actor? user-id (actors/filter-by-application-id actors (:id app)))))))))) (comment (->> (get-handled-approvals "developer") (mapv :id))) ;; TODO: consider refactoring to finding the review events from the current user and mapping those to applications (defn get-handled-reviews [user-id] (let [actors (db/get-actors-for-applications {:role "reviewer"})] (->> (get-applications-impl-batch {}) (filterv (fn [app] (reviewed? user-id app))) (filterv (fn [app] (or (is-actor? user-id (actors/filter-by-application-id actors (:id app))) (is-third-party-reviewer? user-id app) (is-commenter? user-id app) (is-decider? user-id app))))))) (comment (get-handled-reviews "bob") (get-handled-reviews "carl")) (defn- check-for-unneeded-actions "Checks whether the current event will advance into the next workflow round and notifies to all actors, who didn't react, by email that their attention is no longer needed." [application-id round event] (when (or (= "approve" event) (= "review" event)) (let [application (get-application-state application-id) applicant-name (get-username (users/get-user-attributes (:applicantuserid application))) approvers (difference (set (actors/get-by-role application-id round "approver")) (set (map :userid (get-approval-events application round)))) reviewers (difference (set (actors/get-by-role application-id round "reviewer")) (set (map :userid (get-review-events application round)))) requestees (difference (get-third-party-reviewers application round) (set (map :userid (get-third-party-review-events application round))))] (doseq [user (union approvers reviewers requestees)] (let [user-attrs (users/get-user-attributes user)] (email/action-not-needed user-attrs applicant-name application-id)))))) (defn assoc-review-type-to-app [user-id app] (assoc app :review-type (if (is-reviewer? user-id (:id app)) :normal :third-party))) (defn get-applications-to-review "Returns applications that are waiting for a normal or 3rd party review. Type of the review, with key :review and values :normal or :third-party, are added to each application's attributes" [user-id] (->> (get-applications-impl-batch {}) (filterv (fn [app] (and (not (reviewed? user-id app)) (or (can-review? user-id app) (can-third-party-review? user-id app) (can-comment? user-id (:id app)) (can-decide? user-id (:id app)))))) (mapv (partial assoc-review-type-to-app user-id)))) (defn make-draft-application "Make a draft application with an initial set of catalogue items." [user-id catalogue-item-ids] (let [items (get-catalogue-items catalogue-item-ids)] (assert (= 1 (count (distinct (mapv :wfid items))))) (assert (= 1 (count (distinct (mapv :formid items))))) {:id nil :state "draft" :applicantuserid user-id :wfid (:wfid (first items)) :formid (:formid (first items)) :catalogue-items items :events []})) (defn- get-item-value [item form-id application-id] (let [query-params {:item (:id item) :form form-id :application application-id}] (if (= "attachment" (:type item)) (:filename (db/get-attachment query-params)) (:value (db/get-field-value query-params))))) (defn- process-item-options [options] (->> options (map (fn [{:keys [key langcode label displayorder]}] {:key key :label {(keyword langcode) label} :displayorder displayorder})) (group-by :key) (map (fn [[_key options]] (apply merge-maps options))) ; merge label translations (sort-by :displayorder) (mapv #(select-keys % [:key :label])))) (deftest process-item-options-test (is (= [{:key "yes" :label {:en "Yes" :fi "Kyllä"}} {:key "no" :label {:en "No" :fi "Ei"}}] (process-item-options [{:itemid 9, :key "no", :langcode "en", :label "No", :displayorder 1} {:itemid 9, :key "no", :langcode "fi", :label "Ei", :displayorder 1} {:itemid 9, :key "yes", :langcode "en", :label "Yes", :displayorder 0} {:itemid 9, :key "yes", :langcode "fi", :label "Kyllä", :displayorder 0}])))) (defn- process-item "Returns an item structure like this: {:id 123 :type \"texta\" :title \"Item title\" :inputprompt \"hello\" :optional true :value \"filled value or nil\"}" [application-id form-id item] {:id (:id item) :optional (:formitemoptional item) :type (:type item) ;; TODO here we do a db call per item, for licenses we do one huge ;; db call. Not sure which is better? :localizations (into {} (for [{:keys [langcode title inputprompt]} (db/get-form-item-localizations {:item (:id item)})] [(keyword langcode) {:title title :inputprompt inputprompt}])) :options (process-item-options (db/get-form-item-options {:item (:id item)})) :value (or (when-not (draft? application-id) (get-item-value item form-id application-id)) "") :maxlength (:maxlength item)}) (defn- assoc-item-previous-values [application items] (let [previous-values (:items (if (editable? (:state application)) (:submitted-form-contents application) (:previous-submitted-form-contents application)))] (for [item items] (assoc item :previous-value (get previous-values (:id item)))))) (defn- process-license [application license] (let [app-id (:id application) app-user (:applicantuserid application) license-id (:id license)] (-> license (assoc :type "license" :approved (= "approved" (:state (when application (db/get-application-license-approval {:catappid app-id :licid license-id :actoruserid app-user})))))))) (defn- get-application-licenses [application catalogue-item-ids] (mapv #(process-license application %) (licenses/get-active-licenses (or (:start application) (time/now)) {:wfid (:wfid application) :items catalogue-item-ids}))) ;;; Application phases (defn get-application-phases [state] (cond (contains? #{"rejected" :rems.workflow.dynamic/rejected} state) [{:phase :apply :completed? true :text :t.phases/apply} {:phase :approve :completed? true :rejected? true :text :t.phases/approve} {:phase :result :completed? true :rejected? true :text :t.phases/rejected}] (contains? #{"approved" :rems.workflow.dynamic/approved} state) [{:phase :apply :completed? true :text :t.phases/apply} {:phase :approve :completed? true :approved? true :text :t.phases/approve} {:phase :result :completed? true :approved? true :text :t.phases/approved}] (contains? #{"closed" :rems.workflow.dynamic/closed} state) [{:phase :apply :closed? true :text :t.phases/apply} {:phase :approve :closed? true :text :t.phases/approve} {:phase :result :closed? true :text :t.phases/approved}] (contains? #{"draft" "returned" "withdrawn" :rems.workflow.dynamic/draft} state) [{:phase :apply :active? true :text :t.phases/apply} {:phase :approve :text :t.phases/approve} {:phase :result :text :t.phases/approved}] (contains? #{"applied" :rems.workflow.dynamic/submitted} state) [{:phase :apply :completed? true :text :t.phases/apply} {:phase :approve :active? true :text :t.phases/approve} {:phase :result :text :t.phases/approved}] :else [{:phase :apply :active? true :text :t.phases/apply} {:phase :approve :text :t.phases/approve} {:phase :result :text :t.phases/approved}])) (defn get-form-for "Returns a form structure like this: {:id 7 :title \"Title\" :application {:id 3 :state \"draft\" :review-type :normal :can-approve? false :can-close? true :can-withdraw? false :can-third-party-review? false :is-applicant? true :workflow {...} :possible-actions #{...}} :applicant-attributes {\"eppn\" \"developer\" \"email\" \"developer@e.mail\" \"displayName\" \"deve\" \"surname\" \"loper\" ...} :catalogue-items [{:application 3 :item 123}] :items [{:id 123 :type \"texta\" :title \"Item title\" :inputprompt \"hello\" :optional true :value \"filled value or nil\"} ...] :licenses [{:id 2 :type \"license\" :licensetype \"link\" :title \"LGPL\" :textcontent \"http://foo\" :localizations {\"fi\" {:title \"...\" :textcontent \"...\"}} :approved false}] :phases [{:phase :apply :active? true :text :t.phases/apply} {:phase :approve :text :t.phases/approve} {:phase :result :text :t.phases/approved}]}" ([user-id application-id] (let [form (db/get-form-for-application {:application application-id}) _ (assert form) application (get-application-state application-id) application (if (is-dynamic-application? application) (dynamic/assoc-possible-commands user-id application) ; TODO move even higher? application) _ (assert application) form-id (:formid form) _ (assert form-id) catalogue-item-ids (mapv :item (db/get-application-items {:application application-id})) catalogue-items (get-catalogue-items catalogue-item-ids) items (->> (db/get-form-items {:id form-id}) (mapv #(process-item application-id form-id %)) (assoc-item-previous-values application)) description (-> (filter #(= "description" (:type %)) items) first :value) licenses (get-application-licenses application catalogue-item-ids) review-type (cond (can-review? user-id application) :normal (can-third-party-review? user-id application) :third-party :else nil)] (when application-id (when-not (may-see-application? user-id application) (throw-forbidden))) {:id form-id :title (:formtitle form) :catalogue-items catalogue-items :application (assoc application :formid form-id :catalogue-items catalogue-items ;; TODO decide if catalogue-items are part of "form" or "application" :can-approve? (can-approve? user-id application) :can-close? (can-close? user-id application) :can-withdraw? (can-withdraw? user-id application) :can-third-party-review? (can-third-party-review? user-id application) :is-applicant? (is-applicant? user-id application) :review-type review-type :description description) :applicant-attributes (users/get-user-attributes (:applicantuserid application)) :items items :licenses licenses :phases (get-application-phases (:state application))}))) (defn save-attachment! [{:keys [tempfile filename content-type]} user-id application-id item-id] (let [form (get-form-for user-id application-id) byte-array (with-open [input (FileInputStream. tempfile) buffer (ByteArrayOutputStream.)] (clojure.java.io/copy input buffer) (.toByteArray buffer))] (when-not (editable? (:state (:application form))) (throw-forbidden)) (db/save-attachment! {:application application-id :form (:id form) :item item-id :user user-id :filename filename :type content-type :data byte-array}))) (defn remove-attachment! [user-id application-id item-id] (let [form (get-form-for user-id application-id)] (when-not (editable? (:state (:application form))) (throw-forbidden)) (db/remove-attachment! {:application application-id :form (:id form) :item item-id}))) (defn get-draft-form-for "Returns a draft form structure like `get-form-for` used when a new application is created." ([application] (let [application-id (:id application) catalogue-item-ids (map :id (:catalogue-items application)) item-id (first catalogue-item-ids) form (db/get-form-for-item {:item item-id}) form-id (:formid form) catalogue-items (:catalogue-items application) items (->> (db/get-form-items {:id form-id}) (mapv #(process-item application-id form-id %)) (assoc-item-previous-values application)) licenses (get-application-licenses application catalogue-item-ids)] {:id application-id :title (:formtitle form) :catalogue-items catalogue-items :application (assoc application :can-approve? false :can-close? false :is-applicant? true :review-type nil) :applicant-attributes (users/get-user-attributes (:applicantuserid application)) :items items :licenses licenses :phases (get-application-phases (:state application))}))) (defn create-new-draft [user-id wfid] (assert user-id) (assert wfid) (:id (db/create-application! {:user user-id :wfid wfid}))) (defn create-new-draft-at-time [user-id wfid time] (:id (db/create-application! {:user user-id :wfid wfid :start time}))) ;;; Applying events (defmulti ^:private apply-event "Applies an event to an application state." ;; dispatch by event type (fn [_application event] (:event event))) (defn get-event-types "Fetch sequence of supported event names." [] (keys (methods apply-event))) (defmethod apply-event "apply" [application event] (assert (#{"draft" "returned" "withdrawn"} (:state application)) (str "Can't submit application " (pr-str application))) (assert (= (:round event) 0) (str "Apply event should have round 0" (pr-str event))) (assoc application :state "applied" :curround 0)) (defn- apply-approve [application event] (assert (= (:state application) "applied") (str "Can't approve application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and approval rounds don't match: " (pr-str application) " vs. " (pr-str event))) (if (= (:curround application) (:fnlround application)) (assoc application :state "approved") (assoc application :state "applied" :curround (inc (:curround application))))) (defmethod apply-event "approve" [application event] (apply-approve application event)) (defmethod apply-event "autoapprove" [application event] (apply-approve application event)) (defmethod apply-event "reject" [application event] (assert (= (:state application) "applied") (str "Can't reject application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and rejection rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "rejected")) (defmethod apply-event "return" [application event] (assert (= (:state application) "applied") (str "Can't return application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and rejection rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "returned" :curround 0)) (defmethod apply-event "review" [application event] (assert (= (:state application) "applied") (str "Can't review application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and review rounds don't match: " (pr-str application) " vs. " (pr-str event))) (if (= (:curround application) (:fnlround application)) (assoc application :state "approved") (assoc application :state "applied" :curround (inc (:curround application))))) (defmethod apply-event "third-party-review" [application event] (assert (= (:state application) "applied") (str "Can't review application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and review rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "applied")) (defmethod apply-event "review-request" [application event] (assert (= (:state application) "applied") (str "Can't send a review request " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and review request rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "applied")) (defmethod apply-event "withdraw" [application event] (assert (= (:state application) "applied") (str "Can't withdraw application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and withdrawal rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "withdrawn" :curround 0)) (defmethod apply-event "close" [application event] (assoc application :state "closed")) (defmethod apply-event "add-member" [application event] (let [data (cheshire/parse-string (:eventdata event)) uid (getx data "uid")] (update application :members #((fnil conj []) % uid)))) (defn- apply-events [application events] (reduce apply-event application events)) ;;; Public event api (declare get-dynamic-application-state) (defn get-application-state ([application-id] (get-application-state (first (db/get-applications {:id application-id})) (db/get-application-events {:application application-id}))) ([application events] (if (not (nil? (:workflow application))) (get-dynamic-application-state (:id application)) (let [application (-> application (dissoc :workflow) (assoc :state "draft" :curround 0) ;; reset state (assoc :events events) (assoc :last-modified (or (:time (last events)) (:start application))))] (apply-events application events))))) (comment (get-application-state 12)) (declare handle-state-change) (defn try-autoapprove-application "If application can be autoapproved (round has no approvers), add an autoapprove event. Otherwise do nothing." [user-id application] (let [application-id (:id application) round (:curround application) fnlround (:fnlround application) state (:state application)] (when (= "applied" state) (let [approvers (actors/get-by-role application-id round "approver") reviewers (actors/get-by-role application-id round "reviewer")] (when (and (empty? approvers) (empty? reviewers) (<= round fnlround)) (db/add-application-event! {:application application-id :user user-id :round round :event "autoapprove" :comment nil}) true))))) (defn- send-emails-for [application] (let [applicant-attrs (users/get-user-attributes (:applicantuserid application)) application-id (:id application) items (get-catalogue-items-by-application-id application-id) round (:curround application) state (:state application)] (if (= "applied" state) (let [approvers (actors/get-by-role application-id round "approver") reviewers (actors/get-by-role application-id round "reviewer") applicant-name (get-username applicant-attrs)] (doseq [approver approvers] (let [user-attrs (users/get-user-attributes approver)] (email/approval-request user-attrs applicant-name application-id items))) (doseq [reviewer reviewers] (let [user-attrs (users/get-user-attributes reviewer)] (email/review-request user-attrs applicant-name application-id items)))) (email/status-change-alert applicant-attrs application-id items state)))) (defn handle-state-change [user-id application-id] (let [application (get-application-state application-id)] (send-emails-for application) (entitlements/update-entitlements-for application) (when (try-autoapprove-application user-id application) (recur user-id application-id)))) (defn submit-application [applicant-id application-id] (assert applicant-id) (assert application-id) (let [application (get-application-state application-id)] (when-not (= applicant-id (:applicantuserid application)) (throw-forbidden)) (when-not (#{"draft" "returned" "withdrawn"} (:state application)) (throw-forbidden)) (db/add-application-event! {:application application-id :user applicant-id :round 0 :event "apply" :comment nil}) (email/confirm-application-creation application-id (get-catalogue-items-by-application-id application-id)) (handle-state-change applicant-id application-id))) (defn- judge-application [approver-id application-id event round msg] (assert approver-id) (assert application-id) (assert event) (assert round) (assert msg) (let [state (get-application-state application-id)] (when-not (= round (:curround state)) (throw-forbidden)) (db/add-application-event! {:application application-id :user approver-id :round round :event event :comment msg}) (check-for-unneeded-actions application-id round event) (handle-state-change approver-id application-id))) (defn approve-application [approver-id application-id round msg] (when-not (can-approve? approver-id (get-application-state application-id)) (throw-forbidden)) (judge-application approver-id application-id "approve" round msg)) (defn reject-application [user-id application-id round msg] (when-not (can-approve? user-id (get-application-state application-id)) (throw-forbidden)) (judge-application user-id application-id "reject" round msg)) (defn return-application [user-id application-id round msg] (when-not (can-approve? user-id (get-application-state application-id)) (throw-forbidden)) (judge-application user-id application-id "return" round msg)) (defn review-application [user-id application-id round msg] (when-not (can-review? user-id (get-application-state application-id)) (throw-forbidden)) (judge-application user-id application-id "review" round msg)) (defn perform-third-party-review [user-id application-id round msg] (let [application (get-application-state application-id)] (when-not (can-third-party-review? user-id application) (throw-forbidden)) (when-not (= round (:curround application)) (throw-forbidden)) (db/add-application-event! {:application application-id :user user-id :round round :event "third-party-review" :comment msg}))) (defn send-review-request [user-id application-id round msg recipients] (let [application (get-application-state application-id)] (when-not (can-approve? user-id application) (throw-forbidden)) (when-not (= round (:curround application)) (throw-forbidden)) (assert (not-empty? recipients) (str "Can't send a review request without recipients.")) (let [send-to (if (vector? recipients) recipients (vector recipients))] (doseq [recipient send-to] (when-not (is-third-party-reviewer? recipient (:curround application) application) (db/add-application-event! {:application application-id :user recipient :round round :event "review-request" :comment msg}) (roles/add-role! recipient :reviewer) (email/review-request (users/get-user-attributes recipient) (get-username (users/get-user-attributes (:applicantuserid application))) application-id (get-catalogue-items-by-application-id application-id))))))) ;; TODO better name ;; TODO consider refactoring together with judge (defn- unjudge-application "Action handling for both approver and applicant." [user-id application event round msg] (let [application-id (:id application)] (when-not (= round (:curround application)) (throw-forbidden)) (db/add-application-event! {:application application-id :user user-id :round round :event event :comment msg}) (handle-state-change user-id application-id))) (defn withdraw-application [applicant-id application-id round msg] (let [application (get-application-state application-id)] (when-not (can-withdraw? applicant-id application) (throw-forbidden)) (unjudge-application applicant-id application "withdraw" round msg))) (defn close-application [user-id application-id round msg] (let [application (get-application-state application-id)] (when-not (can-close? user-id application) (throw-forbidden)) (unjudge-application user-id application "close" round msg))) (defn add-member [user-id application-id member] (let [application (get-application-state application-id)] (when-not (= user-id (:applicantuserid application)) (throw-forbidden)) (when-not (#{"draft" "returned" "withdrawn"} (:state application)) (throw-forbidden)) (assert (users/get-user-attributes member) (str "User '" member "' must exist")) (db/add-application-event! {:application application-id :user user-id :round 0 :comment nil :event "add-member" :eventdata (cheshire/generate-string {"uid" member})}))) ;;; Dynamic workflows ;; TODO these should be in their own namespace probably ;; TODO could use schemas for these coercions (defn- fix-workflow-from-db [wf] (update (cheshire/parse-string wf keyword) :type keyword)) (defn- keyword-to-number [k] (if (keyword? k) (Integer/parseInt (name k)) k)) (defn- fix-draft-saved-event-from-db [event] (if (= :event/draft-saved (:event event)) (-> event (update :items #(map-keys keyword-to-number %)) (update :licenses #(map-keys keyword-to-number %))) event)) (defn- fix-decided-event-from-db [event] (if (= :event/decided (:event event)) (update-present event :decision keyword) event)) (defn- fix-event-from-db [event] (-> event :eventdata (cheshire/parse-string keyword) (update :event keyword) (update :time #(when % (time-coerce/from-long (Long/parseLong %)))) fix-draft-saved-event-from-db fix-decided-event-from-db)) (defn get-dynamic-application-state [application-id] (let [application (first (db/get-applications {:id application-id})) events (map fix-event-from-db (db/get-application-events {:application application-id})) fixed-application (assoc application :state ::dynamic/draft :dynamic-events events :workflow (fix-workflow-from-db (:workflow application)))] (assert (is-dynamic-application? fixed-application)) (dynamic/apply-events fixed-application events))) (defn- add-dynamic-event! [event] (db/add-application-event! {:application (:application-id event) :user (:actor event) :comment nil :round -1 :event (str (:event event)) :eventdata (cheshire/generate-string event)}) nil) (defn- valid-user? [userid] (not (nil? (users/get-user-attributes userid)))) (defn- validate-form [application-id] (let [user-id (get-applicant-of-application application-id) validation (form-validation/validate (get-form-for user-id application-id))] (when-not (= :valid validation) validation))) (def ^:private db-injections {:valid-user? valid-user? :validate-form validate-form}) (defn dynamic-command! [cmd] (assert (:application-id cmd)) (let [app (get-dynamic-application-state (:application-id cmd)) result (dynamic/handle-command cmd app db-injections)] (if (:success result) (add-dynamic-event! (:result result)) result))) (defn is-dynamic-handler? [user-id application] (contains? (set (get-in application [:workflow :handlers])) user-id)) ;; TODO use also in UI side? (defn is-dynamic-application? [application] (= :workflow/dynamic (get-in application [:workflow :type])))
22501
(ns rems.db.applications "Query functions for forms and applications." (:require [cheshire.core :as cheshire] [clj-time.coerce :as time-coerce] [clj-time.core :as time] [clojure.set :refer [difference union]] [clojure.test :refer [deftest is]] [cprop.tools :refer [merge-maps]] [medley.core :refer [map-keys]] [rems.application-util :refer [editable?]] [rems.auth.util :refer [throw-forbidden]] [rems.context :as context] [rems.db.catalogue :refer [get-localized-catalogue-items]] [rems.db.core :as db] [rems.db.entitlements :as entitlements] [rems.db.licenses :as licenses] [rems.db.roles :as roles] [rems.db.users :as users] [rems.db.workflow-actors :as actors] [rems.email :as email] [rems.form-validation :as form-validation] [rems.util :refer [getx get-username update-present]] [rems.workflow.dynamic :as dynamic]) (:import [java.io ByteArrayOutputStream FileInputStream])) (defn draft? "Is the given `application-id` for an unsaved draft application?" [application-id] (nil? application-id)) ;; TODO cache application state in db instead of always computing it from events (declare get-application-state) (defn- not-empty? [args] ((complement empty?) args)) ;;; Query functions (defn handling-event? [app e] (or (contains? #{"approve" "autoapprove" "reject" "return" "review" :rems.workflow.dynamic/approved :rems.workflow.dynamic/rejected :rems.workflow.dynamic/returned} (:event e)) ;; definitely not by applicant (and (= :event/closed (:event e)) (not= (:applicantuserid app) (:actor e))) ;; not by applicant (and (= "close" (:event e)) (not= (:applicantuserid app) (:userid e))))) ;; not by applicant (defn handled? [app] (or (contains? #{"approved" "rejected" "returned" :rems.workflow.dynamic/returned :rems.workflow.dynamic/approved :rems.workflow.dynamic/rejected} (:state app)) ;; by approver action (and (contains? #{"closed" "withdrawn" :rems.workflow.dynamic/closed} (:state app)) (some (partial handling-event? app) (concat (:events app) (:dynamic-events app)))))) (defn- get-events-of-type "Returns all events of a given type that have occured in an application. Optionally a round parameter can be provided to focus on events occuring during a given round." ([app event] (filter #(= event (:event %)) (:events app))) ([app round event] (filter #(and (= event (:event %)) (= round (:round %))) (:events app)))) (defn get-approval-events "Returns all approve events within a specific round of an application." [app round] (get-events-of-type app round "approve")) (defn get-review-events "Returns all review events that have occured in an application. Optionally a round parameter can be provided to focus on reviews occuring during a given round." ([app] (get-events-of-type app "review")) ([app round] (get-events-of-type app round "review"))) (defn get-third-party-review-events "Returns all third-party-review events that have occured in an application. Optionally a round parameter can be provided to focus on third-party-reviews occuring during a given round." ([app] (get-events-of-type app "third-party-review")) ([app round] (get-events-of-type app round "third-party-review"))) (defn get-applicant-of-application [application-id] (:applicantuserid (first (db/get-applications {:id application-id})))) (declare is-commenter?) (declare can-comment?) (declare is-decider?) (declare can-decide?) (declare is-dynamic-application?) (defn reviewed? "Returns true if the application, given as parameter, has already been reviewed normally or as a 3rd party actor by the current user. Otherwise, current hasn't yet provided feedback and false is returned." ([user-id app] (let [app-state (get-application-state (:id app))] (if (is-dynamic-application? app) (or (and (is-commenter? user-id app-state) (not (can-comment? user-id (:id app)))) (and (is-decider? user-id app-state) (not (can-decide? user-id (:id app))))) (contains? (set (map :userid (concat (get-review-events app) (get-third-party-review-events app)))) user-id)))) ([user-id app round] (reviewed? user-id (update app :events (fn [events] (filter #(= round (:round %)) events)))))) (comment (reviewed? "bob" (get-application-state 23))) (declare fix-workflow-from-db) (declare is-dynamic-handler?) (defn- is-actor? [user-id actors] (assert user-id) (assert actors) (contains? (set actors) user-id)) (defn can-act-as? [user-id application role] (assert user-id) (assert application) (assert role) (or (and (= "applied" (:state application)) (is-actor? user-id (actors/get-by-role (:id application) (:curround application) role))) (and (= "approver" role) (contains? (dynamic/possible-commands user-id (get-application-state (:id application))) :rems.workflow.dynamic/approve)))) (declare get-application-state) (defn- has-actor-role? [user-id application-id role] (assert user-id) (assert application-id) (assert role) (or (is-actor? user-id (actors/get-by-role application-id role)) (is-dynamic-handler? user-id (get-application-state application-id)))) (defn- can-approve? [user-id application] (assert user-id) (assert application) (can-act-as? user-id application "approver")) (defn- is-approver? [user-id application-id] (assert user-id) (assert application-id) (has-actor-role? user-id application-id "approver")) (defn- can-review? [user-id application] (assert user-id) (assert application) (can-act-as? user-id application "reviewer")) (defn- is-reviewer? [user-id application-id] (has-actor-role? user-id application-id "reviewer")) (defn- is-third-party-reviewer? "Checks if a given user has been requested to review the given application. Additionally a specific round can be provided to narrow the check to apply only to the given round." ([user application] (->> (:events application) (filter #(and (= "review-request" (:event %)) (= user (:userid %)))) (not-empty?))) ([user round application] (is-third-party-reviewer? user (update application :events (fn [events] (filter #(= round (:round %)) events)))))) (defn- can-third-party-review? "Checks if the current user can perform a 3rd party review action on the current round for the given application." [user-id application] (and (= "applied" (:state application)) (is-third-party-reviewer? user-id (:curround application) application))) ;; TODO add to tests (defn- is-commenter? "Checks if a given user has been requested to comment the given application." ([user application] ;; TODO calculate in backend? (->> (:dynamic-events application) (mapcat :commenters) (some #{user})))) (defn- can-comment? "Checks if the current user can perform a comment action for the given application." [user-id application-id] (let [application (dynamic/assoc-possible-commands user-id (get-application-state application-id))] (contains? (get application :possible-commands) :rems.workflow.dynamic/comment))) ;; TODO add to tests (defn- is-decider? "Checks if a given user has been requested to decide on the given application." ([user application] ;; TODO calculate in backend? (->> (:dynamic-events application) (map :decider) (some #{user})))) (defn- can-decide? "Checks if the current user can perform a decide action for the given application." [user-id application-id] (let [application (dynamic/assoc-possible-commands user-id (get-application-state application-id))] (contains? (get application :possible-commands) :rems.workflow.dynamic/decide))) (defn get-approvers [application] (actors/get-by-role (:id application) "approver")) (defn get-reviewers [application] (actors/get-by-role (:id application) "reviewer")) (defn get-third-party-reviewers "Takes as an argument a structure containing application information and a optionally the workflow round. Then returns userids for all users that have been requested to review for the given round or all rounds if not given." ([application] (set (map :userid (get-events-of-type application "review-request")))) ([application round] (set (map :userid (get-events-of-type application round "review-request"))))) (defn get-handlers [application] (let [approvers (get-approvers application) reviewers (get-reviewers application) third-party-reviewers (get-third-party-reviewers application)] (union approvers reviewers third-party-reviewers))) (defn is-applicant? [user-id application] (assert user-id) (assert application) (= user-id (:applicantuserid application))) (defn may-see-application? [user-id application] (assert user-id) (assert application) (let [application-id (:id application)] (or (is-applicant? user-id application) (is-approver? user-id application-id) (is-reviewer? user-id application-id) (is-third-party-reviewer? user-id application) (is-dynamic-handler? user-id application) (is-commenter? user-id application) (is-decider? user-id application)))) (defn- can-close? [user-id application] (assert user-id) (assert application) (let [application-id (:id application)] (or (and (is-approver? user-id application-id) (= "approved" (:state application))) (and (is-applicant? user-id application) (not= "closed" (:state application)))))) (defn- can-withdraw? [user-id application] (assert user-id) (assert application) (and (is-applicant? user-id application) (= (:state application) "applied"))) (defn- translate-catalogue-item [item] (merge item (get-in item [:localizations context/*lang*]))) (defn- get-catalogue-items "Function that returns localized catalogue-items for the given application items, `ids`. Prefetched localized catalogue items, `localized-items`, can be given as a parameter to avoid excessive database calls." ([ids] (mapv translate-catalogue-item (get-localized-catalogue-items {:items ids}))) ([ids localized-items] (mapv translate-catalogue-item (filter #(some #{(:id %)} ids) localized-items)))) (defn get-catalogue-items-by-application-id "Given an `app-id`, the function queries for all the items related to that application and calls `get-catalogue-items` to return all the catalogue items for the application with localizations." [app-id] (get-catalogue-items (mapv :item (db/get-application-items {:application app-id})))) (defn- get-catalogue-items-by-application-items "Given `application-items` and `localized-items`, catalogue items with localizations, the function `get-catalogue-items` to map all the application items to the catalogue items with localizations." [application-items localized-items] (when (seq application-items) (get-catalogue-items (mapv :item application-items) localized-items))) (defn- get-applications-impl-batch "Prefetches all possibly relevant data from the database and returns all the applications, according to the query parameters, with all the events and catalogue items associated with them." [query-params] (let [events (db/get-application-events {}) application-items (db/get-application-items) localized-items (get-localized-catalogue-items)] (doall (for [app (db/get-applications query-params)] (let [catalogue-items (get-catalogue-items-by-application-items (filter #(= (:id app) (:application %)) application-items) localized-items) app-events (for [e events :when (= (:id app) (:appid e))] ;; :appid needed only for batching (dissoc e :appid))] (assoc (get-application-state app app-events) :formid (:formid (first catalogue-items)) :catalogue-items catalogue-items)))))) (comment (->> (get-applications-impl-batch {}) (mapv :id))) (defn get-user-applications [user-id] (assert user-id "Must have user-id") (->> (get-applications-impl-batch {:applicant user-id}) (remove (comp #{"closed"} :state)))) (comment (->> (get-applications-impl-batch {:applicant "developer"}) (mapv :id)) (->> (get-applications-impl-batch {:applicant "alice"}) (mapv :id))) (defn get-approvals [user-id] (->> (get-applications-impl-batch {}) (filterv (partial can-approve? user-id)))) (comment (->> (get-approvals "developer") (mapv :id))) (defn actors-of-dynamic-application [application] (map :actor (:dynamic-events application))) ;; TODO combine handled approvals and reviews as just handled applications (defn get-handled-approvals [user-id] (let [actors (db/get-actors-for-applications {:role "approver"})] (->> (get-applications-impl-batch {}) (filterv handled?) (filterv (fn [app] (let [application (get-application-state (:id app))] (if (is-dynamic-application? application) (contains? (set (actors-of-dynamic-application application)) user-id) (is-actor? user-id (actors/filter-by-application-id actors (:id app)))))))))) (comment (->> (get-handled-approvals "developer") (mapv :id))) ;; TODO: consider refactoring to finding the review events from the current user and mapping those to applications (defn get-handled-reviews [user-id] (let [actors (db/get-actors-for-applications {:role "reviewer"})] (->> (get-applications-impl-batch {}) (filterv (fn [app] (reviewed? user-id app))) (filterv (fn [app] (or (is-actor? user-id (actors/filter-by-application-id actors (:id app))) (is-third-party-reviewer? user-id app) (is-commenter? user-id app) (is-decider? user-id app))))))) (comment (get-handled-reviews "<NAME>") (get-handled-reviews "<NAME>")) (defn- check-for-unneeded-actions "Checks whether the current event will advance into the next workflow round and notifies to all actors, who didn't react, by email that their attention is no longer needed." [application-id round event] (when (or (= "approve" event) (= "review" event)) (let [application (get-application-state application-id) applicant-name (get-username (users/get-user-attributes (:applicantuserid application))) approvers (difference (set (actors/get-by-role application-id round "approver")) (set (map :userid (get-approval-events application round)))) reviewers (difference (set (actors/get-by-role application-id round "reviewer")) (set (map :userid (get-review-events application round)))) requestees (difference (get-third-party-reviewers application round) (set (map :userid (get-third-party-review-events application round))))] (doseq [user (union approvers reviewers requestees)] (let [user-attrs (users/get-user-attributes user)] (email/action-not-needed user-attrs applicant-name application-id)))))) (defn assoc-review-type-to-app [user-id app] (assoc app :review-type (if (is-reviewer? user-id (:id app)) :normal :third-party))) (defn get-applications-to-review "Returns applications that are waiting for a normal or 3rd party review. Type of the review, with key :review and values :normal or :third-party, are added to each application's attributes" [user-id] (->> (get-applications-impl-batch {}) (filterv (fn [app] (and (not (reviewed? user-id app)) (or (can-review? user-id app) (can-third-party-review? user-id app) (can-comment? user-id (:id app)) (can-decide? user-id (:id app)))))) (mapv (partial assoc-review-type-to-app user-id)))) (defn make-draft-application "Make a draft application with an initial set of catalogue items." [user-id catalogue-item-ids] (let [items (get-catalogue-items catalogue-item-ids)] (assert (= 1 (count (distinct (mapv :wfid items))))) (assert (= 1 (count (distinct (mapv :formid items))))) {:id nil :state "draft" :applicantuserid user-id :wfid (:wfid (first items)) :formid (:formid (first items)) :catalogue-items items :events []})) (defn- get-item-value [item form-id application-id] (let [query-params {:item (:id item) :form form-id :application application-id}] (if (= "attachment" (:type item)) (:filename (db/get-attachment query-params)) (:value (db/get-field-value query-params))))) (defn- process-item-options [options] (->> options (map (fn [{:keys [key langcode label displayorder]}] {:key key :label {(keyword langcode) label} :displayorder displayorder})) (group-by :key) (map (fn [[_key options]] (apply merge-maps options))) ; merge label translations (sort-by :displayorder) (mapv #(select-keys % [:key :label])))) (deftest process-item-options-test (is (= [{:key "yes" :label {:en "Yes" :fi "Kyllä"}} {:key "no" :label {:en "No" :fi "Ei"}}] (process-item-options [{:itemid 9, :key "no", :langcode "en", :label "No", :displayorder 1} {:itemid 9, :key "no", :langcode "fi", :label "Ei", :displayorder 1} {:itemid 9, :key "yes", :langcode "en", :label "Yes", :displayorder 0} {:itemid 9, :key "yes", :langcode "fi", :label "Kyllä", :displayorder 0}])))) (defn- process-item "Returns an item structure like this: {:id 123 :type \"texta\" :title \"Item title\" :inputprompt \"hello\" :optional true :value \"filled value or nil\"}" [application-id form-id item] {:id (:id item) :optional (:formitemoptional item) :type (:type item) ;; TODO here we do a db call per item, for licenses we do one huge ;; db call. Not sure which is better? :localizations (into {} (for [{:keys [langcode title inputprompt]} (db/get-form-item-localizations {:item (:id item)})] [(keyword langcode) {:title title :inputprompt inputprompt}])) :options (process-item-options (db/get-form-item-options {:item (:id item)})) :value (or (when-not (draft? application-id) (get-item-value item form-id application-id)) "") :maxlength (:maxlength item)}) (defn- assoc-item-previous-values [application items] (let [previous-values (:items (if (editable? (:state application)) (:submitted-form-contents application) (:previous-submitted-form-contents application)))] (for [item items] (assoc item :previous-value (get previous-values (:id item)))))) (defn- process-license [application license] (let [app-id (:id application) app-user (:applicantuserid application) license-id (:id license)] (-> license (assoc :type "license" :approved (= "approved" (:state (when application (db/get-application-license-approval {:catappid app-id :licid license-id :actoruserid app-user})))))))) (defn- get-application-licenses [application catalogue-item-ids] (mapv #(process-license application %) (licenses/get-active-licenses (or (:start application) (time/now)) {:wfid (:wfid application) :items catalogue-item-ids}))) ;;; Application phases (defn get-application-phases [state] (cond (contains? #{"rejected" :rems.workflow.dynamic/rejected} state) [{:phase :apply :completed? true :text :t.phases/apply} {:phase :approve :completed? true :rejected? true :text :t.phases/approve} {:phase :result :completed? true :rejected? true :text :t.phases/rejected}] (contains? #{"approved" :rems.workflow.dynamic/approved} state) [{:phase :apply :completed? true :text :t.phases/apply} {:phase :approve :completed? true :approved? true :text :t.phases/approve} {:phase :result :completed? true :approved? true :text :t.phases/approved}] (contains? #{"closed" :rems.workflow.dynamic/closed} state) [{:phase :apply :closed? true :text :t.phases/apply} {:phase :approve :closed? true :text :t.phases/approve} {:phase :result :closed? true :text :t.phases/approved}] (contains? #{"draft" "returned" "withdrawn" :rems.workflow.dynamic/draft} state) [{:phase :apply :active? true :text :t.phases/apply} {:phase :approve :text :t.phases/approve} {:phase :result :text :t.phases/approved}] (contains? #{"applied" :rems.workflow.dynamic/submitted} state) [{:phase :apply :completed? true :text :t.phases/apply} {:phase :approve :active? true :text :t.phases/approve} {:phase :result :text :t.phases/approved}] :else [{:phase :apply :active? true :text :t.phases/apply} {:phase :approve :text :t.phases/approve} {:phase :result :text :t.phases/approved}])) (defn get-form-for "Returns a form structure like this: {:id 7 :title \"Title\" :application {:id 3 :state \"draft\" :review-type :normal :can-approve? false :can-close? true :can-withdraw? false :can-third-party-review? false :is-applicant? true :workflow {...} :possible-actions #{...}} :applicant-attributes {\"eppn\" \"developer\" \"email\" \"<EMAIL>\" \"displayName\" \"<NAME>\" \"surname\" \"<NAME>\" ...} :catalogue-items [{:application 3 :item 123}] :items [{:id 123 :type \"texta\" :title \"Item title\" :inputprompt \"hello\" :optional true :value \"filled value or nil\"} ...] :licenses [{:id 2 :type \"license\" :licensetype \"link\" :title \"LGPL\" :textcontent \"http://foo\" :localizations {\"fi\" {:title \"...\" :textcontent \"...\"}} :approved false}] :phases [{:phase :apply :active? true :text :t.phases/apply} {:phase :approve :text :t.phases/approve} {:phase :result :text :t.phases/approved}]}" ([user-id application-id] (let [form (db/get-form-for-application {:application application-id}) _ (assert form) application (get-application-state application-id) application (if (is-dynamic-application? application) (dynamic/assoc-possible-commands user-id application) ; TODO move even higher? application) _ (assert application) form-id (:formid form) _ (assert form-id) catalogue-item-ids (mapv :item (db/get-application-items {:application application-id})) catalogue-items (get-catalogue-items catalogue-item-ids) items (->> (db/get-form-items {:id form-id}) (mapv #(process-item application-id form-id %)) (assoc-item-previous-values application)) description (-> (filter #(= "description" (:type %)) items) first :value) licenses (get-application-licenses application catalogue-item-ids) review-type (cond (can-review? user-id application) :normal (can-third-party-review? user-id application) :third-party :else nil)] (when application-id (when-not (may-see-application? user-id application) (throw-forbidden))) {:id form-id :title (:formtitle form) :catalogue-items catalogue-items :application (assoc application :formid form-id :catalogue-items catalogue-items ;; TODO decide if catalogue-items are part of "form" or "application" :can-approve? (can-approve? user-id application) :can-close? (can-close? user-id application) :can-withdraw? (can-withdraw? user-id application) :can-third-party-review? (can-third-party-review? user-id application) :is-applicant? (is-applicant? user-id application) :review-type review-type :description description) :applicant-attributes (users/get-user-attributes (:applicantuserid application)) :items items :licenses licenses :phases (get-application-phases (:state application))}))) (defn save-attachment! [{:keys [tempfile filename content-type]} user-id application-id item-id] (let [form (get-form-for user-id application-id) byte-array (with-open [input (FileInputStream. tempfile) buffer (ByteArrayOutputStream.)] (clojure.java.io/copy input buffer) (.toByteArray buffer))] (when-not (editable? (:state (:application form))) (throw-forbidden)) (db/save-attachment! {:application application-id :form (:id form) :item item-id :user user-id :filename filename :type content-type :data byte-array}))) (defn remove-attachment! [user-id application-id item-id] (let [form (get-form-for user-id application-id)] (when-not (editable? (:state (:application form))) (throw-forbidden)) (db/remove-attachment! {:application application-id :form (:id form) :item item-id}))) (defn get-draft-form-for "Returns a draft form structure like `get-form-for` used when a new application is created." ([application] (let [application-id (:id application) catalogue-item-ids (map :id (:catalogue-items application)) item-id (first catalogue-item-ids) form (db/get-form-for-item {:item item-id}) form-id (:formid form) catalogue-items (:catalogue-items application) items (->> (db/get-form-items {:id form-id}) (mapv #(process-item application-id form-id %)) (assoc-item-previous-values application)) licenses (get-application-licenses application catalogue-item-ids)] {:id application-id :title (:formtitle form) :catalogue-items catalogue-items :application (assoc application :can-approve? false :can-close? false :is-applicant? true :review-type nil) :applicant-attributes (users/get-user-attributes (:applicantuserid application)) :items items :licenses licenses :phases (get-application-phases (:state application))}))) (defn create-new-draft [user-id wfid] (assert user-id) (assert wfid) (:id (db/create-application! {:user user-id :wfid wfid}))) (defn create-new-draft-at-time [user-id wfid time] (:id (db/create-application! {:user user-id :wfid wfid :start time}))) ;;; Applying events (defmulti ^:private apply-event "Applies an event to an application state." ;; dispatch by event type (fn [_application event] (:event event))) (defn get-event-types "Fetch sequence of supported event names." [] (keys (methods apply-event))) (defmethod apply-event "apply" [application event] (assert (#{"draft" "returned" "withdrawn"} (:state application)) (str "Can't submit application " (pr-str application))) (assert (= (:round event) 0) (str "Apply event should have round 0" (pr-str event))) (assoc application :state "applied" :curround 0)) (defn- apply-approve [application event] (assert (= (:state application) "applied") (str "Can't approve application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and approval rounds don't match: " (pr-str application) " vs. " (pr-str event))) (if (= (:curround application) (:fnlround application)) (assoc application :state "approved") (assoc application :state "applied" :curround (inc (:curround application))))) (defmethod apply-event "approve" [application event] (apply-approve application event)) (defmethod apply-event "autoapprove" [application event] (apply-approve application event)) (defmethod apply-event "reject" [application event] (assert (= (:state application) "applied") (str "Can't reject application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and rejection rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "rejected")) (defmethod apply-event "return" [application event] (assert (= (:state application) "applied") (str "Can't return application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and rejection rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "returned" :curround 0)) (defmethod apply-event "review" [application event] (assert (= (:state application) "applied") (str "Can't review application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and review rounds don't match: " (pr-str application) " vs. " (pr-str event))) (if (= (:curround application) (:fnlround application)) (assoc application :state "approved") (assoc application :state "applied" :curround (inc (:curround application))))) (defmethod apply-event "third-party-review" [application event] (assert (= (:state application) "applied") (str "Can't review application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and review rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "applied")) (defmethod apply-event "review-request" [application event] (assert (= (:state application) "applied") (str "Can't send a review request " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and review request rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "applied")) (defmethod apply-event "withdraw" [application event] (assert (= (:state application) "applied") (str "Can't withdraw application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and withdrawal rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "withdrawn" :curround 0)) (defmethod apply-event "close" [application event] (assoc application :state "closed")) (defmethod apply-event "add-member" [application event] (let [data (cheshire/parse-string (:eventdata event)) uid (getx data "uid")] (update application :members #((fnil conj []) % uid)))) (defn- apply-events [application events] (reduce apply-event application events)) ;;; Public event api (declare get-dynamic-application-state) (defn get-application-state ([application-id] (get-application-state (first (db/get-applications {:id application-id})) (db/get-application-events {:application application-id}))) ([application events] (if (not (nil? (:workflow application))) (get-dynamic-application-state (:id application)) (let [application (-> application (dissoc :workflow) (assoc :state "draft" :curround 0) ;; reset state (assoc :events events) (assoc :last-modified (or (:time (last events)) (:start application))))] (apply-events application events))))) (comment (get-application-state 12)) (declare handle-state-change) (defn try-autoapprove-application "If application can be autoapproved (round has no approvers), add an autoapprove event. Otherwise do nothing." [user-id application] (let [application-id (:id application) round (:curround application) fnlround (:fnlround application) state (:state application)] (when (= "applied" state) (let [approvers (actors/get-by-role application-id round "approver") reviewers (actors/get-by-role application-id round "reviewer")] (when (and (empty? approvers) (empty? reviewers) (<= round fnlround)) (db/add-application-event! {:application application-id :user user-id :round round :event "autoapprove" :comment nil}) true))))) (defn- send-emails-for [application] (let [applicant-attrs (users/get-user-attributes (:applicantuserid application)) application-id (:id application) items (get-catalogue-items-by-application-id application-id) round (:curround application) state (:state application)] (if (= "applied" state) (let [approvers (actors/get-by-role application-id round "approver") reviewers (actors/get-by-role application-id round "reviewer") applicant-name (get-username applicant-attrs)] (doseq [approver approvers] (let [user-attrs (users/get-user-attributes approver)] (email/approval-request user-attrs applicant-name application-id items))) (doseq [reviewer reviewers] (let [user-attrs (users/get-user-attributes reviewer)] (email/review-request user-attrs applicant-name application-id items)))) (email/status-change-alert applicant-attrs application-id items state)))) (defn handle-state-change [user-id application-id] (let [application (get-application-state application-id)] (send-emails-for application) (entitlements/update-entitlements-for application) (when (try-autoapprove-application user-id application) (recur user-id application-id)))) (defn submit-application [applicant-id application-id] (assert applicant-id) (assert application-id) (let [application (get-application-state application-id)] (when-not (= applicant-id (:applicantuserid application)) (throw-forbidden)) (when-not (#{"draft" "returned" "withdrawn"} (:state application)) (throw-forbidden)) (db/add-application-event! {:application application-id :user applicant-id :round 0 :event "apply" :comment nil}) (email/confirm-application-creation application-id (get-catalogue-items-by-application-id application-id)) (handle-state-change applicant-id application-id))) (defn- judge-application [approver-id application-id event round msg] (assert approver-id) (assert application-id) (assert event) (assert round) (assert msg) (let [state (get-application-state application-id)] (when-not (= round (:curround state)) (throw-forbidden)) (db/add-application-event! {:application application-id :user approver-id :round round :event event :comment msg}) (check-for-unneeded-actions application-id round event) (handle-state-change approver-id application-id))) (defn approve-application [approver-id application-id round msg] (when-not (can-approve? approver-id (get-application-state application-id)) (throw-forbidden)) (judge-application approver-id application-id "approve" round msg)) (defn reject-application [user-id application-id round msg] (when-not (can-approve? user-id (get-application-state application-id)) (throw-forbidden)) (judge-application user-id application-id "reject" round msg)) (defn return-application [user-id application-id round msg] (when-not (can-approve? user-id (get-application-state application-id)) (throw-forbidden)) (judge-application user-id application-id "return" round msg)) (defn review-application [user-id application-id round msg] (when-not (can-review? user-id (get-application-state application-id)) (throw-forbidden)) (judge-application user-id application-id "review" round msg)) (defn perform-third-party-review [user-id application-id round msg] (let [application (get-application-state application-id)] (when-not (can-third-party-review? user-id application) (throw-forbidden)) (when-not (= round (:curround application)) (throw-forbidden)) (db/add-application-event! {:application application-id :user user-id :round round :event "third-party-review" :comment msg}))) (defn send-review-request [user-id application-id round msg recipients] (let [application (get-application-state application-id)] (when-not (can-approve? user-id application) (throw-forbidden)) (when-not (= round (:curround application)) (throw-forbidden)) (assert (not-empty? recipients) (str "Can't send a review request without recipients.")) (let [send-to (if (vector? recipients) recipients (vector recipients))] (doseq [recipient send-to] (when-not (is-third-party-reviewer? recipient (:curround application) application) (db/add-application-event! {:application application-id :user recipient :round round :event "review-request" :comment msg}) (roles/add-role! recipient :reviewer) (email/review-request (users/get-user-attributes recipient) (get-username (users/get-user-attributes (:applicantuserid application))) application-id (get-catalogue-items-by-application-id application-id))))))) ;; TODO better name ;; TODO consider refactoring together with judge (defn- unjudge-application "Action handling for both approver and applicant." [user-id application event round msg] (let [application-id (:id application)] (when-not (= round (:curround application)) (throw-forbidden)) (db/add-application-event! {:application application-id :user user-id :round round :event event :comment msg}) (handle-state-change user-id application-id))) (defn withdraw-application [applicant-id application-id round msg] (let [application (get-application-state application-id)] (when-not (can-withdraw? applicant-id application) (throw-forbidden)) (unjudge-application applicant-id application "withdraw" round msg))) (defn close-application [user-id application-id round msg] (let [application (get-application-state application-id)] (when-not (can-close? user-id application) (throw-forbidden)) (unjudge-application user-id application "close" round msg))) (defn add-member [user-id application-id member] (let [application (get-application-state application-id)] (when-not (= user-id (:applicantuserid application)) (throw-forbidden)) (when-not (#{"draft" "returned" "withdrawn"} (:state application)) (throw-forbidden)) (assert (users/get-user-attributes member) (str "User '" member "' must exist")) (db/add-application-event! {:application application-id :user user-id :round 0 :comment nil :event "add-member" :eventdata (cheshire/generate-string {"uid" member})}))) ;;; Dynamic workflows ;; TODO these should be in their own namespace probably ;; TODO could use schemas for these coercions (defn- fix-workflow-from-db [wf] (update (cheshire/parse-string wf keyword) :type keyword)) (defn- keyword-to-number [k] (if (keyword? k) (Integer/parseInt (name k)) k)) (defn- fix-draft-saved-event-from-db [event] (if (= :event/draft-saved (:event event)) (-> event (update :items #(map-keys keyword-to-number %)) (update :licenses #(map-keys keyword-to-number %))) event)) (defn- fix-decided-event-from-db [event] (if (= :event/decided (:event event)) (update-present event :decision keyword) event)) (defn- fix-event-from-db [event] (-> event :eventdata (cheshire/parse-string keyword) (update :event keyword) (update :time #(when % (time-coerce/from-long (Long/parseLong %)))) fix-draft-saved-event-from-db fix-decided-event-from-db)) (defn get-dynamic-application-state [application-id] (let [application (first (db/get-applications {:id application-id})) events (map fix-event-from-db (db/get-application-events {:application application-id})) fixed-application (assoc application :state ::dynamic/draft :dynamic-events events :workflow (fix-workflow-from-db (:workflow application)))] (assert (is-dynamic-application? fixed-application)) (dynamic/apply-events fixed-application events))) (defn- add-dynamic-event! [event] (db/add-application-event! {:application (:application-id event) :user (:actor event) :comment nil :round -1 :event (str (:event event)) :eventdata (cheshire/generate-string event)}) nil) (defn- valid-user? [userid] (not (nil? (users/get-user-attributes userid)))) (defn- validate-form [application-id] (let [user-id (get-applicant-of-application application-id) validation (form-validation/validate (get-form-for user-id application-id))] (when-not (= :valid validation) validation))) (def ^:private db-injections {:valid-user? valid-user? :validate-form validate-form}) (defn dynamic-command! [cmd] (assert (:application-id cmd)) (let [app (get-dynamic-application-state (:application-id cmd)) result (dynamic/handle-command cmd app db-injections)] (if (:success result) (add-dynamic-event! (:result result)) result))) (defn is-dynamic-handler? [user-id application] (contains? (set (get-in application [:workflow :handlers])) user-id)) ;; TODO use also in UI side? (defn is-dynamic-application? [application] (= :workflow/dynamic (get-in application [:workflow :type])))
true
(ns rems.db.applications "Query functions for forms and applications." (:require [cheshire.core :as cheshire] [clj-time.coerce :as time-coerce] [clj-time.core :as time] [clojure.set :refer [difference union]] [clojure.test :refer [deftest is]] [cprop.tools :refer [merge-maps]] [medley.core :refer [map-keys]] [rems.application-util :refer [editable?]] [rems.auth.util :refer [throw-forbidden]] [rems.context :as context] [rems.db.catalogue :refer [get-localized-catalogue-items]] [rems.db.core :as db] [rems.db.entitlements :as entitlements] [rems.db.licenses :as licenses] [rems.db.roles :as roles] [rems.db.users :as users] [rems.db.workflow-actors :as actors] [rems.email :as email] [rems.form-validation :as form-validation] [rems.util :refer [getx get-username update-present]] [rems.workflow.dynamic :as dynamic]) (:import [java.io ByteArrayOutputStream FileInputStream])) (defn draft? "Is the given `application-id` for an unsaved draft application?" [application-id] (nil? application-id)) ;; TODO cache application state in db instead of always computing it from events (declare get-application-state) (defn- not-empty? [args] ((complement empty?) args)) ;;; Query functions (defn handling-event? [app e] (or (contains? #{"approve" "autoapprove" "reject" "return" "review" :rems.workflow.dynamic/approved :rems.workflow.dynamic/rejected :rems.workflow.dynamic/returned} (:event e)) ;; definitely not by applicant (and (= :event/closed (:event e)) (not= (:applicantuserid app) (:actor e))) ;; not by applicant (and (= "close" (:event e)) (not= (:applicantuserid app) (:userid e))))) ;; not by applicant (defn handled? [app] (or (contains? #{"approved" "rejected" "returned" :rems.workflow.dynamic/returned :rems.workflow.dynamic/approved :rems.workflow.dynamic/rejected} (:state app)) ;; by approver action (and (contains? #{"closed" "withdrawn" :rems.workflow.dynamic/closed} (:state app)) (some (partial handling-event? app) (concat (:events app) (:dynamic-events app)))))) (defn- get-events-of-type "Returns all events of a given type that have occured in an application. Optionally a round parameter can be provided to focus on events occuring during a given round." ([app event] (filter #(= event (:event %)) (:events app))) ([app round event] (filter #(and (= event (:event %)) (= round (:round %))) (:events app)))) (defn get-approval-events "Returns all approve events within a specific round of an application." [app round] (get-events-of-type app round "approve")) (defn get-review-events "Returns all review events that have occured in an application. Optionally a round parameter can be provided to focus on reviews occuring during a given round." ([app] (get-events-of-type app "review")) ([app round] (get-events-of-type app round "review"))) (defn get-third-party-review-events "Returns all third-party-review events that have occured in an application. Optionally a round parameter can be provided to focus on third-party-reviews occuring during a given round." ([app] (get-events-of-type app "third-party-review")) ([app round] (get-events-of-type app round "third-party-review"))) (defn get-applicant-of-application [application-id] (:applicantuserid (first (db/get-applications {:id application-id})))) (declare is-commenter?) (declare can-comment?) (declare is-decider?) (declare can-decide?) (declare is-dynamic-application?) (defn reviewed? "Returns true if the application, given as parameter, has already been reviewed normally or as a 3rd party actor by the current user. Otherwise, current hasn't yet provided feedback and false is returned." ([user-id app] (let [app-state (get-application-state (:id app))] (if (is-dynamic-application? app) (or (and (is-commenter? user-id app-state) (not (can-comment? user-id (:id app)))) (and (is-decider? user-id app-state) (not (can-decide? user-id (:id app))))) (contains? (set (map :userid (concat (get-review-events app) (get-third-party-review-events app)))) user-id)))) ([user-id app round] (reviewed? user-id (update app :events (fn [events] (filter #(= round (:round %)) events)))))) (comment (reviewed? "bob" (get-application-state 23))) (declare fix-workflow-from-db) (declare is-dynamic-handler?) (defn- is-actor? [user-id actors] (assert user-id) (assert actors) (contains? (set actors) user-id)) (defn can-act-as? [user-id application role] (assert user-id) (assert application) (assert role) (or (and (= "applied" (:state application)) (is-actor? user-id (actors/get-by-role (:id application) (:curround application) role))) (and (= "approver" role) (contains? (dynamic/possible-commands user-id (get-application-state (:id application))) :rems.workflow.dynamic/approve)))) (declare get-application-state) (defn- has-actor-role? [user-id application-id role] (assert user-id) (assert application-id) (assert role) (or (is-actor? user-id (actors/get-by-role application-id role)) (is-dynamic-handler? user-id (get-application-state application-id)))) (defn- can-approve? [user-id application] (assert user-id) (assert application) (can-act-as? user-id application "approver")) (defn- is-approver? [user-id application-id] (assert user-id) (assert application-id) (has-actor-role? user-id application-id "approver")) (defn- can-review? [user-id application] (assert user-id) (assert application) (can-act-as? user-id application "reviewer")) (defn- is-reviewer? [user-id application-id] (has-actor-role? user-id application-id "reviewer")) (defn- is-third-party-reviewer? "Checks if a given user has been requested to review the given application. Additionally a specific round can be provided to narrow the check to apply only to the given round." ([user application] (->> (:events application) (filter #(and (= "review-request" (:event %)) (= user (:userid %)))) (not-empty?))) ([user round application] (is-third-party-reviewer? user (update application :events (fn [events] (filter #(= round (:round %)) events)))))) (defn- can-third-party-review? "Checks if the current user can perform a 3rd party review action on the current round for the given application." [user-id application] (and (= "applied" (:state application)) (is-third-party-reviewer? user-id (:curround application) application))) ;; TODO add to tests (defn- is-commenter? "Checks if a given user has been requested to comment the given application." ([user application] ;; TODO calculate in backend? (->> (:dynamic-events application) (mapcat :commenters) (some #{user})))) (defn- can-comment? "Checks if the current user can perform a comment action for the given application." [user-id application-id] (let [application (dynamic/assoc-possible-commands user-id (get-application-state application-id))] (contains? (get application :possible-commands) :rems.workflow.dynamic/comment))) ;; TODO add to tests (defn- is-decider? "Checks if a given user has been requested to decide on the given application." ([user application] ;; TODO calculate in backend? (->> (:dynamic-events application) (map :decider) (some #{user})))) (defn- can-decide? "Checks if the current user can perform a decide action for the given application." [user-id application-id] (let [application (dynamic/assoc-possible-commands user-id (get-application-state application-id))] (contains? (get application :possible-commands) :rems.workflow.dynamic/decide))) (defn get-approvers [application] (actors/get-by-role (:id application) "approver")) (defn get-reviewers [application] (actors/get-by-role (:id application) "reviewer")) (defn get-third-party-reviewers "Takes as an argument a structure containing application information and a optionally the workflow round. Then returns userids for all users that have been requested to review for the given round or all rounds if not given." ([application] (set (map :userid (get-events-of-type application "review-request")))) ([application round] (set (map :userid (get-events-of-type application round "review-request"))))) (defn get-handlers [application] (let [approvers (get-approvers application) reviewers (get-reviewers application) third-party-reviewers (get-third-party-reviewers application)] (union approvers reviewers third-party-reviewers))) (defn is-applicant? [user-id application] (assert user-id) (assert application) (= user-id (:applicantuserid application))) (defn may-see-application? [user-id application] (assert user-id) (assert application) (let [application-id (:id application)] (or (is-applicant? user-id application) (is-approver? user-id application-id) (is-reviewer? user-id application-id) (is-third-party-reviewer? user-id application) (is-dynamic-handler? user-id application) (is-commenter? user-id application) (is-decider? user-id application)))) (defn- can-close? [user-id application] (assert user-id) (assert application) (let [application-id (:id application)] (or (and (is-approver? user-id application-id) (= "approved" (:state application))) (and (is-applicant? user-id application) (not= "closed" (:state application)))))) (defn- can-withdraw? [user-id application] (assert user-id) (assert application) (and (is-applicant? user-id application) (= (:state application) "applied"))) (defn- translate-catalogue-item [item] (merge item (get-in item [:localizations context/*lang*]))) (defn- get-catalogue-items "Function that returns localized catalogue-items for the given application items, `ids`. Prefetched localized catalogue items, `localized-items`, can be given as a parameter to avoid excessive database calls." ([ids] (mapv translate-catalogue-item (get-localized-catalogue-items {:items ids}))) ([ids localized-items] (mapv translate-catalogue-item (filter #(some #{(:id %)} ids) localized-items)))) (defn get-catalogue-items-by-application-id "Given an `app-id`, the function queries for all the items related to that application and calls `get-catalogue-items` to return all the catalogue items for the application with localizations." [app-id] (get-catalogue-items (mapv :item (db/get-application-items {:application app-id})))) (defn- get-catalogue-items-by-application-items "Given `application-items` and `localized-items`, catalogue items with localizations, the function `get-catalogue-items` to map all the application items to the catalogue items with localizations." [application-items localized-items] (when (seq application-items) (get-catalogue-items (mapv :item application-items) localized-items))) (defn- get-applications-impl-batch "Prefetches all possibly relevant data from the database and returns all the applications, according to the query parameters, with all the events and catalogue items associated with them." [query-params] (let [events (db/get-application-events {}) application-items (db/get-application-items) localized-items (get-localized-catalogue-items)] (doall (for [app (db/get-applications query-params)] (let [catalogue-items (get-catalogue-items-by-application-items (filter #(= (:id app) (:application %)) application-items) localized-items) app-events (for [e events :when (= (:id app) (:appid e))] ;; :appid needed only for batching (dissoc e :appid))] (assoc (get-application-state app app-events) :formid (:formid (first catalogue-items)) :catalogue-items catalogue-items)))))) (comment (->> (get-applications-impl-batch {}) (mapv :id))) (defn get-user-applications [user-id] (assert user-id "Must have user-id") (->> (get-applications-impl-batch {:applicant user-id}) (remove (comp #{"closed"} :state)))) (comment (->> (get-applications-impl-batch {:applicant "developer"}) (mapv :id)) (->> (get-applications-impl-batch {:applicant "alice"}) (mapv :id))) (defn get-approvals [user-id] (->> (get-applications-impl-batch {}) (filterv (partial can-approve? user-id)))) (comment (->> (get-approvals "developer") (mapv :id))) (defn actors-of-dynamic-application [application] (map :actor (:dynamic-events application))) ;; TODO combine handled approvals and reviews as just handled applications (defn get-handled-approvals [user-id] (let [actors (db/get-actors-for-applications {:role "approver"})] (->> (get-applications-impl-batch {}) (filterv handled?) (filterv (fn [app] (let [application (get-application-state (:id app))] (if (is-dynamic-application? application) (contains? (set (actors-of-dynamic-application application)) user-id) (is-actor? user-id (actors/filter-by-application-id actors (:id app)))))))))) (comment (->> (get-handled-approvals "developer") (mapv :id))) ;; TODO: consider refactoring to finding the review events from the current user and mapping those to applications (defn get-handled-reviews [user-id] (let [actors (db/get-actors-for-applications {:role "reviewer"})] (->> (get-applications-impl-batch {}) (filterv (fn [app] (reviewed? user-id app))) (filterv (fn [app] (or (is-actor? user-id (actors/filter-by-application-id actors (:id app))) (is-third-party-reviewer? user-id app) (is-commenter? user-id app) (is-decider? user-id app))))))) (comment (get-handled-reviews "PI:NAME:<NAME>END_PI") (get-handled-reviews "PI:NAME:<NAME>END_PI")) (defn- check-for-unneeded-actions "Checks whether the current event will advance into the next workflow round and notifies to all actors, who didn't react, by email that their attention is no longer needed." [application-id round event] (when (or (= "approve" event) (= "review" event)) (let [application (get-application-state application-id) applicant-name (get-username (users/get-user-attributes (:applicantuserid application))) approvers (difference (set (actors/get-by-role application-id round "approver")) (set (map :userid (get-approval-events application round)))) reviewers (difference (set (actors/get-by-role application-id round "reviewer")) (set (map :userid (get-review-events application round)))) requestees (difference (get-third-party-reviewers application round) (set (map :userid (get-third-party-review-events application round))))] (doseq [user (union approvers reviewers requestees)] (let [user-attrs (users/get-user-attributes user)] (email/action-not-needed user-attrs applicant-name application-id)))))) (defn assoc-review-type-to-app [user-id app] (assoc app :review-type (if (is-reviewer? user-id (:id app)) :normal :third-party))) (defn get-applications-to-review "Returns applications that are waiting for a normal or 3rd party review. Type of the review, with key :review and values :normal or :third-party, are added to each application's attributes" [user-id] (->> (get-applications-impl-batch {}) (filterv (fn [app] (and (not (reviewed? user-id app)) (or (can-review? user-id app) (can-third-party-review? user-id app) (can-comment? user-id (:id app)) (can-decide? user-id (:id app)))))) (mapv (partial assoc-review-type-to-app user-id)))) (defn make-draft-application "Make a draft application with an initial set of catalogue items." [user-id catalogue-item-ids] (let [items (get-catalogue-items catalogue-item-ids)] (assert (= 1 (count (distinct (mapv :wfid items))))) (assert (= 1 (count (distinct (mapv :formid items))))) {:id nil :state "draft" :applicantuserid user-id :wfid (:wfid (first items)) :formid (:formid (first items)) :catalogue-items items :events []})) (defn- get-item-value [item form-id application-id] (let [query-params {:item (:id item) :form form-id :application application-id}] (if (= "attachment" (:type item)) (:filename (db/get-attachment query-params)) (:value (db/get-field-value query-params))))) (defn- process-item-options [options] (->> options (map (fn [{:keys [key langcode label displayorder]}] {:key key :label {(keyword langcode) label} :displayorder displayorder})) (group-by :key) (map (fn [[_key options]] (apply merge-maps options))) ; merge label translations (sort-by :displayorder) (mapv #(select-keys % [:key :label])))) (deftest process-item-options-test (is (= [{:key "yes" :label {:en "Yes" :fi "Kyllä"}} {:key "no" :label {:en "No" :fi "Ei"}}] (process-item-options [{:itemid 9, :key "no", :langcode "en", :label "No", :displayorder 1} {:itemid 9, :key "no", :langcode "fi", :label "Ei", :displayorder 1} {:itemid 9, :key "yes", :langcode "en", :label "Yes", :displayorder 0} {:itemid 9, :key "yes", :langcode "fi", :label "Kyllä", :displayorder 0}])))) (defn- process-item "Returns an item structure like this: {:id 123 :type \"texta\" :title \"Item title\" :inputprompt \"hello\" :optional true :value \"filled value or nil\"}" [application-id form-id item] {:id (:id item) :optional (:formitemoptional item) :type (:type item) ;; TODO here we do a db call per item, for licenses we do one huge ;; db call. Not sure which is better? :localizations (into {} (for [{:keys [langcode title inputprompt]} (db/get-form-item-localizations {:item (:id item)})] [(keyword langcode) {:title title :inputprompt inputprompt}])) :options (process-item-options (db/get-form-item-options {:item (:id item)})) :value (or (when-not (draft? application-id) (get-item-value item form-id application-id)) "") :maxlength (:maxlength item)}) (defn- assoc-item-previous-values [application items] (let [previous-values (:items (if (editable? (:state application)) (:submitted-form-contents application) (:previous-submitted-form-contents application)))] (for [item items] (assoc item :previous-value (get previous-values (:id item)))))) (defn- process-license [application license] (let [app-id (:id application) app-user (:applicantuserid application) license-id (:id license)] (-> license (assoc :type "license" :approved (= "approved" (:state (when application (db/get-application-license-approval {:catappid app-id :licid license-id :actoruserid app-user})))))))) (defn- get-application-licenses [application catalogue-item-ids] (mapv #(process-license application %) (licenses/get-active-licenses (or (:start application) (time/now)) {:wfid (:wfid application) :items catalogue-item-ids}))) ;;; Application phases (defn get-application-phases [state] (cond (contains? #{"rejected" :rems.workflow.dynamic/rejected} state) [{:phase :apply :completed? true :text :t.phases/apply} {:phase :approve :completed? true :rejected? true :text :t.phases/approve} {:phase :result :completed? true :rejected? true :text :t.phases/rejected}] (contains? #{"approved" :rems.workflow.dynamic/approved} state) [{:phase :apply :completed? true :text :t.phases/apply} {:phase :approve :completed? true :approved? true :text :t.phases/approve} {:phase :result :completed? true :approved? true :text :t.phases/approved}] (contains? #{"closed" :rems.workflow.dynamic/closed} state) [{:phase :apply :closed? true :text :t.phases/apply} {:phase :approve :closed? true :text :t.phases/approve} {:phase :result :closed? true :text :t.phases/approved}] (contains? #{"draft" "returned" "withdrawn" :rems.workflow.dynamic/draft} state) [{:phase :apply :active? true :text :t.phases/apply} {:phase :approve :text :t.phases/approve} {:phase :result :text :t.phases/approved}] (contains? #{"applied" :rems.workflow.dynamic/submitted} state) [{:phase :apply :completed? true :text :t.phases/apply} {:phase :approve :active? true :text :t.phases/approve} {:phase :result :text :t.phases/approved}] :else [{:phase :apply :active? true :text :t.phases/apply} {:phase :approve :text :t.phases/approve} {:phase :result :text :t.phases/approved}])) (defn get-form-for "Returns a form structure like this: {:id 7 :title \"Title\" :application {:id 3 :state \"draft\" :review-type :normal :can-approve? false :can-close? true :can-withdraw? false :can-third-party-review? false :is-applicant? true :workflow {...} :possible-actions #{...}} :applicant-attributes {\"eppn\" \"developer\" \"email\" \"PI:EMAIL:<EMAIL>END_PI\" \"displayName\" \"PI:NAME:<NAME>END_PI\" \"surname\" \"PI:NAME:<NAME>END_PI\" ...} :catalogue-items [{:application 3 :item 123}] :items [{:id 123 :type \"texta\" :title \"Item title\" :inputprompt \"hello\" :optional true :value \"filled value or nil\"} ...] :licenses [{:id 2 :type \"license\" :licensetype \"link\" :title \"LGPL\" :textcontent \"http://foo\" :localizations {\"fi\" {:title \"...\" :textcontent \"...\"}} :approved false}] :phases [{:phase :apply :active? true :text :t.phases/apply} {:phase :approve :text :t.phases/approve} {:phase :result :text :t.phases/approved}]}" ([user-id application-id] (let [form (db/get-form-for-application {:application application-id}) _ (assert form) application (get-application-state application-id) application (if (is-dynamic-application? application) (dynamic/assoc-possible-commands user-id application) ; TODO move even higher? application) _ (assert application) form-id (:formid form) _ (assert form-id) catalogue-item-ids (mapv :item (db/get-application-items {:application application-id})) catalogue-items (get-catalogue-items catalogue-item-ids) items (->> (db/get-form-items {:id form-id}) (mapv #(process-item application-id form-id %)) (assoc-item-previous-values application)) description (-> (filter #(= "description" (:type %)) items) first :value) licenses (get-application-licenses application catalogue-item-ids) review-type (cond (can-review? user-id application) :normal (can-third-party-review? user-id application) :third-party :else nil)] (when application-id (when-not (may-see-application? user-id application) (throw-forbidden))) {:id form-id :title (:formtitle form) :catalogue-items catalogue-items :application (assoc application :formid form-id :catalogue-items catalogue-items ;; TODO decide if catalogue-items are part of "form" or "application" :can-approve? (can-approve? user-id application) :can-close? (can-close? user-id application) :can-withdraw? (can-withdraw? user-id application) :can-third-party-review? (can-third-party-review? user-id application) :is-applicant? (is-applicant? user-id application) :review-type review-type :description description) :applicant-attributes (users/get-user-attributes (:applicantuserid application)) :items items :licenses licenses :phases (get-application-phases (:state application))}))) (defn save-attachment! [{:keys [tempfile filename content-type]} user-id application-id item-id] (let [form (get-form-for user-id application-id) byte-array (with-open [input (FileInputStream. tempfile) buffer (ByteArrayOutputStream.)] (clojure.java.io/copy input buffer) (.toByteArray buffer))] (when-not (editable? (:state (:application form))) (throw-forbidden)) (db/save-attachment! {:application application-id :form (:id form) :item item-id :user user-id :filename filename :type content-type :data byte-array}))) (defn remove-attachment! [user-id application-id item-id] (let [form (get-form-for user-id application-id)] (when-not (editable? (:state (:application form))) (throw-forbidden)) (db/remove-attachment! {:application application-id :form (:id form) :item item-id}))) (defn get-draft-form-for "Returns a draft form structure like `get-form-for` used when a new application is created." ([application] (let [application-id (:id application) catalogue-item-ids (map :id (:catalogue-items application)) item-id (first catalogue-item-ids) form (db/get-form-for-item {:item item-id}) form-id (:formid form) catalogue-items (:catalogue-items application) items (->> (db/get-form-items {:id form-id}) (mapv #(process-item application-id form-id %)) (assoc-item-previous-values application)) licenses (get-application-licenses application catalogue-item-ids)] {:id application-id :title (:formtitle form) :catalogue-items catalogue-items :application (assoc application :can-approve? false :can-close? false :is-applicant? true :review-type nil) :applicant-attributes (users/get-user-attributes (:applicantuserid application)) :items items :licenses licenses :phases (get-application-phases (:state application))}))) (defn create-new-draft [user-id wfid] (assert user-id) (assert wfid) (:id (db/create-application! {:user user-id :wfid wfid}))) (defn create-new-draft-at-time [user-id wfid time] (:id (db/create-application! {:user user-id :wfid wfid :start time}))) ;;; Applying events (defmulti ^:private apply-event "Applies an event to an application state." ;; dispatch by event type (fn [_application event] (:event event))) (defn get-event-types "Fetch sequence of supported event names." [] (keys (methods apply-event))) (defmethod apply-event "apply" [application event] (assert (#{"draft" "returned" "withdrawn"} (:state application)) (str "Can't submit application " (pr-str application))) (assert (= (:round event) 0) (str "Apply event should have round 0" (pr-str event))) (assoc application :state "applied" :curround 0)) (defn- apply-approve [application event] (assert (= (:state application) "applied") (str "Can't approve application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and approval rounds don't match: " (pr-str application) " vs. " (pr-str event))) (if (= (:curround application) (:fnlround application)) (assoc application :state "approved") (assoc application :state "applied" :curround (inc (:curround application))))) (defmethod apply-event "approve" [application event] (apply-approve application event)) (defmethod apply-event "autoapprove" [application event] (apply-approve application event)) (defmethod apply-event "reject" [application event] (assert (= (:state application) "applied") (str "Can't reject application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and rejection rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "rejected")) (defmethod apply-event "return" [application event] (assert (= (:state application) "applied") (str "Can't return application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and rejection rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "returned" :curround 0)) (defmethod apply-event "review" [application event] (assert (= (:state application) "applied") (str "Can't review application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and review rounds don't match: " (pr-str application) " vs. " (pr-str event))) (if (= (:curround application) (:fnlround application)) (assoc application :state "approved") (assoc application :state "applied" :curround (inc (:curround application))))) (defmethod apply-event "third-party-review" [application event] (assert (= (:state application) "applied") (str "Can't review application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and review rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "applied")) (defmethod apply-event "review-request" [application event] (assert (= (:state application) "applied") (str "Can't send a review request " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and review request rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "applied")) (defmethod apply-event "withdraw" [application event] (assert (= (:state application) "applied") (str "Can't withdraw application " (pr-str application))) (assert (= (:curround application) (:round event)) (str "Application and withdrawal rounds don't match: " (pr-str application) " vs. " (pr-str event))) (assoc application :state "withdrawn" :curround 0)) (defmethod apply-event "close" [application event] (assoc application :state "closed")) (defmethod apply-event "add-member" [application event] (let [data (cheshire/parse-string (:eventdata event)) uid (getx data "uid")] (update application :members #((fnil conj []) % uid)))) (defn- apply-events [application events] (reduce apply-event application events)) ;;; Public event api (declare get-dynamic-application-state) (defn get-application-state ([application-id] (get-application-state (first (db/get-applications {:id application-id})) (db/get-application-events {:application application-id}))) ([application events] (if (not (nil? (:workflow application))) (get-dynamic-application-state (:id application)) (let [application (-> application (dissoc :workflow) (assoc :state "draft" :curround 0) ;; reset state (assoc :events events) (assoc :last-modified (or (:time (last events)) (:start application))))] (apply-events application events))))) (comment (get-application-state 12)) (declare handle-state-change) (defn try-autoapprove-application "If application can be autoapproved (round has no approvers), add an autoapprove event. Otherwise do nothing." [user-id application] (let [application-id (:id application) round (:curround application) fnlround (:fnlround application) state (:state application)] (when (= "applied" state) (let [approvers (actors/get-by-role application-id round "approver") reviewers (actors/get-by-role application-id round "reviewer")] (when (and (empty? approvers) (empty? reviewers) (<= round fnlround)) (db/add-application-event! {:application application-id :user user-id :round round :event "autoapprove" :comment nil}) true))))) (defn- send-emails-for [application] (let [applicant-attrs (users/get-user-attributes (:applicantuserid application)) application-id (:id application) items (get-catalogue-items-by-application-id application-id) round (:curround application) state (:state application)] (if (= "applied" state) (let [approvers (actors/get-by-role application-id round "approver") reviewers (actors/get-by-role application-id round "reviewer") applicant-name (get-username applicant-attrs)] (doseq [approver approvers] (let [user-attrs (users/get-user-attributes approver)] (email/approval-request user-attrs applicant-name application-id items))) (doseq [reviewer reviewers] (let [user-attrs (users/get-user-attributes reviewer)] (email/review-request user-attrs applicant-name application-id items)))) (email/status-change-alert applicant-attrs application-id items state)))) (defn handle-state-change [user-id application-id] (let [application (get-application-state application-id)] (send-emails-for application) (entitlements/update-entitlements-for application) (when (try-autoapprove-application user-id application) (recur user-id application-id)))) (defn submit-application [applicant-id application-id] (assert applicant-id) (assert application-id) (let [application (get-application-state application-id)] (when-not (= applicant-id (:applicantuserid application)) (throw-forbidden)) (when-not (#{"draft" "returned" "withdrawn"} (:state application)) (throw-forbidden)) (db/add-application-event! {:application application-id :user applicant-id :round 0 :event "apply" :comment nil}) (email/confirm-application-creation application-id (get-catalogue-items-by-application-id application-id)) (handle-state-change applicant-id application-id))) (defn- judge-application [approver-id application-id event round msg] (assert approver-id) (assert application-id) (assert event) (assert round) (assert msg) (let [state (get-application-state application-id)] (when-not (= round (:curround state)) (throw-forbidden)) (db/add-application-event! {:application application-id :user approver-id :round round :event event :comment msg}) (check-for-unneeded-actions application-id round event) (handle-state-change approver-id application-id))) (defn approve-application [approver-id application-id round msg] (when-not (can-approve? approver-id (get-application-state application-id)) (throw-forbidden)) (judge-application approver-id application-id "approve" round msg)) (defn reject-application [user-id application-id round msg] (when-not (can-approve? user-id (get-application-state application-id)) (throw-forbidden)) (judge-application user-id application-id "reject" round msg)) (defn return-application [user-id application-id round msg] (when-not (can-approve? user-id (get-application-state application-id)) (throw-forbidden)) (judge-application user-id application-id "return" round msg)) (defn review-application [user-id application-id round msg] (when-not (can-review? user-id (get-application-state application-id)) (throw-forbidden)) (judge-application user-id application-id "review" round msg)) (defn perform-third-party-review [user-id application-id round msg] (let [application (get-application-state application-id)] (when-not (can-third-party-review? user-id application) (throw-forbidden)) (when-not (= round (:curround application)) (throw-forbidden)) (db/add-application-event! {:application application-id :user user-id :round round :event "third-party-review" :comment msg}))) (defn send-review-request [user-id application-id round msg recipients] (let [application (get-application-state application-id)] (when-not (can-approve? user-id application) (throw-forbidden)) (when-not (= round (:curround application)) (throw-forbidden)) (assert (not-empty? recipients) (str "Can't send a review request without recipients.")) (let [send-to (if (vector? recipients) recipients (vector recipients))] (doseq [recipient send-to] (when-not (is-third-party-reviewer? recipient (:curround application) application) (db/add-application-event! {:application application-id :user recipient :round round :event "review-request" :comment msg}) (roles/add-role! recipient :reviewer) (email/review-request (users/get-user-attributes recipient) (get-username (users/get-user-attributes (:applicantuserid application))) application-id (get-catalogue-items-by-application-id application-id))))))) ;; TODO better name ;; TODO consider refactoring together with judge (defn- unjudge-application "Action handling for both approver and applicant." [user-id application event round msg] (let [application-id (:id application)] (when-not (= round (:curround application)) (throw-forbidden)) (db/add-application-event! {:application application-id :user user-id :round round :event event :comment msg}) (handle-state-change user-id application-id))) (defn withdraw-application [applicant-id application-id round msg] (let [application (get-application-state application-id)] (when-not (can-withdraw? applicant-id application) (throw-forbidden)) (unjudge-application applicant-id application "withdraw" round msg))) (defn close-application [user-id application-id round msg] (let [application (get-application-state application-id)] (when-not (can-close? user-id application) (throw-forbidden)) (unjudge-application user-id application "close" round msg))) (defn add-member [user-id application-id member] (let [application (get-application-state application-id)] (when-not (= user-id (:applicantuserid application)) (throw-forbidden)) (when-not (#{"draft" "returned" "withdrawn"} (:state application)) (throw-forbidden)) (assert (users/get-user-attributes member) (str "User '" member "' must exist")) (db/add-application-event! {:application application-id :user user-id :round 0 :comment nil :event "add-member" :eventdata (cheshire/generate-string {"uid" member})}))) ;;; Dynamic workflows ;; TODO these should be in their own namespace probably ;; TODO could use schemas for these coercions (defn- fix-workflow-from-db [wf] (update (cheshire/parse-string wf keyword) :type keyword)) (defn- keyword-to-number [k] (if (keyword? k) (Integer/parseInt (name k)) k)) (defn- fix-draft-saved-event-from-db [event] (if (= :event/draft-saved (:event event)) (-> event (update :items #(map-keys keyword-to-number %)) (update :licenses #(map-keys keyword-to-number %))) event)) (defn- fix-decided-event-from-db [event] (if (= :event/decided (:event event)) (update-present event :decision keyword) event)) (defn- fix-event-from-db [event] (-> event :eventdata (cheshire/parse-string keyword) (update :event keyword) (update :time #(when % (time-coerce/from-long (Long/parseLong %)))) fix-draft-saved-event-from-db fix-decided-event-from-db)) (defn get-dynamic-application-state [application-id] (let [application (first (db/get-applications {:id application-id})) events (map fix-event-from-db (db/get-application-events {:application application-id})) fixed-application (assoc application :state ::dynamic/draft :dynamic-events events :workflow (fix-workflow-from-db (:workflow application)))] (assert (is-dynamic-application? fixed-application)) (dynamic/apply-events fixed-application events))) (defn- add-dynamic-event! [event] (db/add-application-event! {:application (:application-id event) :user (:actor event) :comment nil :round -1 :event (str (:event event)) :eventdata (cheshire/generate-string event)}) nil) (defn- valid-user? [userid] (not (nil? (users/get-user-attributes userid)))) (defn- validate-form [application-id] (let [user-id (get-applicant-of-application application-id) validation (form-validation/validate (get-form-for user-id application-id))] (when-not (= :valid validation) validation))) (def ^:private db-injections {:valid-user? valid-user? :validate-form validate-form}) (defn dynamic-command! [cmd] (assert (:application-id cmd)) (let [app (get-dynamic-application-state (:application-id cmd)) result (dynamic/handle-command cmd app db-injections)] (if (:success result) (add-dynamic-event! (:result result)) result))) (defn is-dynamic-handler? [user-id application] (contains? (set (get-in application [:workflow :handlers])) user-id)) ;; TODO use also in UI side? (defn is-dynamic-application? [application] (= :workflow/dynamic (get-in application [:workflow :type])))