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": ";;; Copyright 2019 Mitchell Kember. Subject to the MIT License.\n\n;;; This code is ta", "end": 34, "score": 0.999889075756073, "start": 19, "tag": "NAME", "value": "Mitchell Kember" } ]
dev/user.clj
mk12/twenty48
0
;;; Copyright 2019 Mitchell Kember. Subject to the MIT License. ;;; This code is taken from Stuart Sierra's blog post: ;;; http://thinkrelevance.com/blog/2013/06/04/clojure-workflow-reloaded (ns user (:require [clojure.tools.namespace.repl :refer [refresh]] [twenty48.system :as s])) (def system nil) (defn init [] (alter-var-root #'system (constantly (s/system :dev)))) (defn start [] (alter-var-root #'system s/start)) (defn stop [] (alter-var-root #'system #(when % (s/stop %)))) (defn go [] (init) (start)) (defn reset [] (stop) (refresh :after 'user/go))
64036
;;; Copyright 2019 <NAME>. Subject to the MIT License. ;;; This code is taken from Stuart Sierra's blog post: ;;; http://thinkrelevance.com/blog/2013/06/04/clojure-workflow-reloaded (ns user (:require [clojure.tools.namespace.repl :refer [refresh]] [twenty48.system :as s])) (def system nil) (defn init [] (alter-var-root #'system (constantly (s/system :dev)))) (defn start [] (alter-var-root #'system s/start)) (defn stop [] (alter-var-root #'system #(when % (s/stop %)))) (defn go [] (init) (start)) (defn reset [] (stop) (refresh :after 'user/go))
true
;;; Copyright 2019 PI:NAME:<NAME>END_PI. Subject to the MIT License. ;;; This code is taken from Stuart Sierra's blog post: ;;; http://thinkrelevance.com/blog/2013/06/04/clojure-workflow-reloaded (ns user (:require [clojure.tools.namespace.repl :refer [refresh]] [twenty48.system :as s])) (def system nil) (defn init [] (alter-var-root #'system (constantly (s/system :dev)))) (defn start [] (alter-var-root #'system s/start)) (defn stop [] (alter-var-root #'system #(when % (s/stop %)))) (defn go [] (init) (start)) (defn reset [] (stop) (refresh :after 'user/go))
[ { "context": "(comment\n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,", "end": 47, "score": 0.9998836517333984, "start": 35, "tag": "NAME", "value": "Ronen Narkis" }, { "context": "(comment\n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,\n Version 2.", "end": 60, "score": 0.6784868240356445, "start": 50, "tag": "EMAIL", "value": "arkisr.com" } ]
src/re_core/persistency/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 re-core.persistency.systems "systems persistency layer" (:refer-clojure :exclude [type]) (:require [es.systems :as es] [re-core.roles :refer (su? system?)] [re-core.security :refer (current-user)] [robert.hooke :as h] [re-core.persistency [users :as u] [types :as t]] [re-core.persistency.quotas :as q] [re-core.common :refer (import-logging)] [physical.validations :as ph] [kvm.validations :as kv] [freenas.validations :as fv] [openstack.validations :as ov] [aws.validations :as av] [subs.core :as subs :refer (validate! validation when-not-nil)] [puny.core :refer (entity)] [slingshot.slingshot :refer [throw+]] [puny.migrations :refer (Migration register)] [re-core.model :refer (clone hypervizors figure-virt check-validity)] [clojure.core.strint :refer (<<)] aws.model)) (import-logging) (declare perm validate-system increase-quota decrease-quota es-put es-delete) (entity {:version 1} system :indices [type env owner] :intercept { :create [perm increase-quota es-put] :read [perm] :update [perm es-put] :delete [perm decrease-quota es-delete]}) (defn assert-access "Validates that the current user can access the system, non super users can only access systems they own. All users are limited to certain environments." [{:keys [env owner] :as system}] {:pre [(current-user)]} (let [{:keys [envs username] :as curr-user} (u/get-user! ((current-user) :username))] (when-not (empty? system) (when (and (not (su? curr-user)) (not= username owner)) (throw+ {:type ::persmission-owner-violation} (<< "non super user ~{username} attempted to access a system owned by ~{owner}!")) ) (when (and (not (system? curr-user)) env (not ((into #{} envs) env))) (throw+ {:type ::persmission-env-violation} (<< "~{username} attempted to access system ~{system} in env ~{env}")))))) (defn is-system? [s] (and (map? s) (s :owner) (s :env))) (defn perm "A permission interceptor on systems access, we check both env and owner persmissions. due to the way robert.hooke works we analyse args and not fn to decide what to verify on. If we have a map we assume its a system if we have a number we assume its an id." [f & args] (let [system (first (filter map? args)) id (first (filter #(or (number? %) (and (string? %) (re-find #"\d+" %))) args)) skip (first (filter #{:skip-assert} args))] (when-not skip (trace "perm checking" f args) (if (is-system? system) (assert-access system) (assert-access (get-system id :skip-assert)))) (if skip (apply f (butlast args)) (apply f args)))) (defn decrease-quota "reducing usage quotas for owning user on delete" [f & args] (let [system (first (filter map? args))] (when (is-system? system) (q/decrease-use system))) (apply f args)) (defn increase-quota "reducing usage quotas for owning user on delete" [f & args] (if (map? (first args)) (let [id (apply f args) spec (first args)] (q/quota-assert spec) (q/increase-use spec) id) (apply f args))) (defn es-put "runs a specified es function on system fn call" [f & args] (if (map? (first args)) (let [id (apply f args) spec (first args)] (es/put (str id) spec) id) (apply f args))) (defn es-delete "reducing usage quotas for owning user on delete" [f & args] (let [system (first (filter map? args)) id (first (filter number? args))] (when-not (is-system? system) (es/delete (str id) :flush? true))) (apply f args)) (defn system-ip [id] (get-in (get-system id) [:machine :ip])) (validation :type-exists (when-not-nil t/type-exists? "type not found, create it first")) (validation :user-exists (when-not-nil u/user-exists? "user not found")) (def system-base { :owner #{:required :user-exists} :type #{:required :type-exists} :env #{:required :Keyword} }) (defn validate-system [system] (validate! system system-base :error ::non-valid-system) (check-validity system)) (defn clone-system "clones an existing system" [id {:keys [hostname owner] :as spec}] (add-system (-> (get-system id) (assoc :owner owner) (assoc-in [:machine :hostname] hostname) (clone spec)))) (defn systems-for "grabs all the systems ids that this user can see" [username] (let [{:keys [envs username] :as user} (u/get-user username)] (if (su? user) (flatten (map #(get-system-index :env (keyword %)) envs)) (get-system-index :owner username)))) (defn re-index "Re-indexes all systems available to the current user under elasticsearch." [username] (es/re-index (map #(vector % (get-system %)) (systems-for username)))) ; triggering env indexing and converting to keyword (defrecord EnvIndices [identifier] Migration (apply- [this] (doseq [id (systems-for "admin")] (update-system id (update-in (get-system id) [:env] keyword)))) (rollback [this])) ; triggering owner indexing and setting default to admin (defrecord OwnerIndices [identifier] Migration (apply- [this] (doseq [id (systems-for "admin")] (when-not ((get-system id) :owner) (update-system id (assoc (get-system id) :owner "admin"))))) (rollback [this])) ; index all existing systems into ES (defn register-migrations [] (register :systems (OwnerIndices. :systems-owner-indices)) (register :systems (EnvIndices. :systems-env-indices))) (declare validate-template) (entity {:version 1} template :id name :indices [type]) (validation :empty (fn [v] (when-not (nil? v) "value must be empty"))) (def template-base { :type #{:required :type-exists} :defaults #{:required :Map} :name #{:required :String} :description #{:String} :machine {:hostname #{:empty} :domain #{:empty}} }) (defn validate-template [template] (validate! template template-base :error ::non-valid-template) (check-validity (assoc template :as :template))) (defn templatize "Create a system from a template" [name {:keys [env machine] :as provided}] {:pre [machine (machine :hostname) (machine :domain)]} (let [{:keys [defaults] :as t} (get-template! name)] (add-system (merge-with merge t (defaults env) provided)))) (defn system-val "grabbing instance id of spec" [spec ks] (get-in (get-system (spec :system-id)) ks))
62278
(comment re-core, Copyright 2012 <NAME>, n<EMAIL> Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.) (ns re-core.persistency.systems "systems persistency layer" (:refer-clojure :exclude [type]) (:require [es.systems :as es] [re-core.roles :refer (su? system?)] [re-core.security :refer (current-user)] [robert.hooke :as h] [re-core.persistency [users :as u] [types :as t]] [re-core.persistency.quotas :as q] [re-core.common :refer (import-logging)] [physical.validations :as ph] [kvm.validations :as kv] [freenas.validations :as fv] [openstack.validations :as ov] [aws.validations :as av] [subs.core :as subs :refer (validate! validation when-not-nil)] [puny.core :refer (entity)] [slingshot.slingshot :refer [throw+]] [puny.migrations :refer (Migration register)] [re-core.model :refer (clone hypervizors figure-virt check-validity)] [clojure.core.strint :refer (<<)] aws.model)) (import-logging) (declare perm validate-system increase-quota decrease-quota es-put es-delete) (entity {:version 1} system :indices [type env owner] :intercept { :create [perm increase-quota es-put] :read [perm] :update [perm es-put] :delete [perm decrease-quota es-delete]}) (defn assert-access "Validates that the current user can access the system, non super users can only access systems they own. All users are limited to certain environments." [{:keys [env owner] :as system}] {:pre [(current-user)]} (let [{:keys [envs username] :as curr-user} (u/get-user! ((current-user) :username))] (when-not (empty? system) (when (and (not (su? curr-user)) (not= username owner)) (throw+ {:type ::persmission-owner-violation} (<< "non super user ~{username} attempted to access a system owned by ~{owner}!")) ) (when (and (not (system? curr-user)) env (not ((into #{} envs) env))) (throw+ {:type ::persmission-env-violation} (<< "~{username} attempted to access system ~{system} in env ~{env}")))))) (defn is-system? [s] (and (map? s) (s :owner) (s :env))) (defn perm "A permission interceptor on systems access, we check both env and owner persmissions. due to the way robert.hooke works we analyse args and not fn to decide what to verify on. If we have a map we assume its a system if we have a number we assume its an id." [f & args] (let [system (first (filter map? args)) id (first (filter #(or (number? %) (and (string? %) (re-find #"\d+" %))) args)) skip (first (filter #{:skip-assert} args))] (when-not skip (trace "perm checking" f args) (if (is-system? system) (assert-access system) (assert-access (get-system id :skip-assert)))) (if skip (apply f (butlast args)) (apply f args)))) (defn decrease-quota "reducing usage quotas for owning user on delete" [f & args] (let [system (first (filter map? args))] (when (is-system? system) (q/decrease-use system))) (apply f args)) (defn increase-quota "reducing usage quotas for owning user on delete" [f & args] (if (map? (first args)) (let [id (apply f args) spec (first args)] (q/quota-assert spec) (q/increase-use spec) id) (apply f args))) (defn es-put "runs a specified es function on system fn call" [f & args] (if (map? (first args)) (let [id (apply f args) spec (first args)] (es/put (str id) spec) id) (apply f args))) (defn es-delete "reducing usage quotas for owning user on delete" [f & args] (let [system (first (filter map? args)) id (first (filter number? args))] (when-not (is-system? system) (es/delete (str id) :flush? true))) (apply f args)) (defn system-ip [id] (get-in (get-system id) [:machine :ip])) (validation :type-exists (when-not-nil t/type-exists? "type not found, create it first")) (validation :user-exists (when-not-nil u/user-exists? "user not found")) (def system-base { :owner #{:required :user-exists} :type #{:required :type-exists} :env #{:required :Keyword} }) (defn validate-system [system] (validate! system system-base :error ::non-valid-system) (check-validity system)) (defn clone-system "clones an existing system" [id {:keys [hostname owner] :as spec}] (add-system (-> (get-system id) (assoc :owner owner) (assoc-in [:machine :hostname] hostname) (clone spec)))) (defn systems-for "grabs all the systems ids that this user can see" [username] (let [{:keys [envs username] :as user} (u/get-user username)] (if (su? user) (flatten (map #(get-system-index :env (keyword %)) envs)) (get-system-index :owner username)))) (defn re-index "Re-indexes all systems available to the current user under elasticsearch." [username] (es/re-index (map #(vector % (get-system %)) (systems-for username)))) ; triggering env indexing and converting to keyword (defrecord EnvIndices [identifier] Migration (apply- [this] (doseq [id (systems-for "admin")] (update-system id (update-in (get-system id) [:env] keyword)))) (rollback [this])) ; triggering owner indexing and setting default to admin (defrecord OwnerIndices [identifier] Migration (apply- [this] (doseq [id (systems-for "admin")] (when-not ((get-system id) :owner) (update-system id (assoc (get-system id) :owner "admin"))))) (rollback [this])) ; index all existing systems into ES (defn register-migrations [] (register :systems (OwnerIndices. :systems-owner-indices)) (register :systems (EnvIndices. :systems-env-indices))) (declare validate-template) (entity {:version 1} template :id name :indices [type]) (validation :empty (fn [v] (when-not (nil? v) "value must be empty"))) (def template-base { :type #{:required :type-exists} :defaults #{:required :Map} :name #{:required :String} :description #{:String} :machine {:hostname #{:empty} :domain #{:empty}} }) (defn validate-template [template] (validate! template template-base :error ::non-valid-template) (check-validity (assoc template :as :template))) (defn templatize "Create a system from a template" [name {:keys [env machine] :as provided}] {:pre [machine (machine :hostname) (machine :domain)]} (let [{:keys [defaults] :as t} (get-template! name)] (add-system (merge-with merge t (defaults env) provided)))) (defn system-val "grabbing instance id of spec" [spec ks] (get-in (get-system (spec :system-id)) ks))
true
(comment re-core, Copyright 2012 PI:NAME:<NAME>END_PI, nPI:EMAIL:<EMAIL>END_PI Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.) (ns re-core.persistency.systems "systems persistency layer" (:refer-clojure :exclude [type]) (:require [es.systems :as es] [re-core.roles :refer (su? system?)] [re-core.security :refer (current-user)] [robert.hooke :as h] [re-core.persistency [users :as u] [types :as t]] [re-core.persistency.quotas :as q] [re-core.common :refer (import-logging)] [physical.validations :as ph] [kvm.validations :as kv] [freenas.validations :as fv] [openstack.validations :as ov] [aws.validations :as av] [subs.core :as subs :refer (validate! validation when-not-nil)] [puny.core :refer (entity)] [slingshot.slingshot :refer [throw+]] [puny.migrations :refer (Migration register)] [re-core.model :refer (clone hypervizors figure-virt check-validity)] [clojure.core.strint :refer (<<)] aws.model)) (import-logging) (declare perm validate-system increase-quota decrease-quota es-put es-delete) (entity {:version 1} system :indices [type env owner] :intercept { :create [perm increase-quota es-put] :read [perm] :update [perm es-put] :delete [perm decrease-quota es-delete]}) (defn assert-access "Validates that the current user can access the system, non super users can only access systems they own. All users are limited to certain environments." [{:keys [env owner] :as system}] {:pre [(current-user)]} (let [{:keys [envs username] :as curr-user} (u/get-user! ((current-user) :username))] (when-not (empty? system) (when (and (not (su? curr-user)) (not= username owner)) (throw+ {:type ::persmission-owner-violation} (<< "non super user ~{username} attempted to access a system owned by ~{owner}!")) ) (when (and (not (system? curr-user)) env (not ((into #{} envs) env))) (throw+ {:type ::persmission-env-violation} (<< "~{username} attempted to access system ~{system} in env ~{env}")))))) (defn is-system? [s] (and (map? s) (s :owner) (s :env))) (defn perm "A permission interceptor on systems access, we check both env and owner persmissions. due to the way robert.hooke works we analyse args and not fn to decide what to verify on. If we have a map we assume its a system if we have a number we assume its an id." [f & args] (let [system (first (filter map? args)) id (first (filter #(or (number? %) (and (string? %) (re-find #"\d+" %))) args)) skip (first (filter #{:skip-assert} args))] (when-not skip (trace "perm checking" f args) (if (is-system? system) (assert-access system) (assert-access (get-system id :skip-assert)))) (if skip (apply f (butlast args)) (apply f args)))) (defn decrease-quota "reducing usage quotas for owning user on delete" [f & args] (let [system (first (filter map? args))] (when (is-system? system) (q/decrease-use system))) (apply f args)) (defn increase-quota "reducing usage quotas for owning user on delete" [f & args] (if (map? (first args)) (let [id (apply f args) spec (first args)] (q/quota-assert spec) (q/increase-use spec) id) (apply f args))) (defn es-put "runs a specified es function on system fn call" [f & args] (if (map? (first args)) (let [id (apply f args) spec (first args)] (es/put (str id) spec) id) (apply f args))) (defn es-delete "reducing usage quotas for owning user on delete" [f & args] (let [system (first (filter map? args)) id (first (filter number? args))] (when-not (is-system? system) (es/delete (str id) :flush? true))) (apply f args)) (defn system-ip [id] (get-in (get-system id) [:machine :ip])) (validation :type-exists (when-not-nil t/type-exists? "type not found, create it first")) (validation :user-exists (when-not-nil u/user-exists? "user not found")) (def system-base { :owner #{:required :user-exists} :type #{:required :type-exists} :env #{:required :Keyword} }) (defn validate-system [system] (validate! system system-base :error ::non-valid-system) (check-validity system)) (defn clone-system "clones an existing system" [id {:keys [hostname owner] :as spec}] (add-system (-> (get-system id) (assoc :owner owner) (assoc-in [:machine :hostname] hostname) (clone spec)))) (defn systems-for "grabs all the systems ids that this user can see" [username] (let [{:keys [envs username] :as user} (u/get-user username)] (if (su? user) (flatten (map #(get-system-index :env (keyword %)) envs)) (get-system-index :owner username)))) (defn re-index "Re-indexes all systems available to the current user under elasticsearch." [username] (es/re-index (map #(vector % (get-system %)) (systems-for username)))) ; triggering env indexing and converting to keyword (defrecord EnvIndices [identifier] Migration (apply- [this] (doseq [id (systems-for "admin")] (update-system id (update-in (get-system id) [:env] keyword)))) (rollback [this])) ; triggering owner indexing and setting default to admin (defrecord OwnerIndices [identifier] Migration (apply- [this] (doseq [id (systems-for "admin")] (when-not ((get-system id) :owner) (update-system id (assoc (get-system id) :owner "admin"))))) (rollback [this])) ; index all existing systems into ES (defn register-migrations [] (register :systems (OwnerIndices. :systems-owner-indices)) (register :systems (EnvIndices. :systems-env-indices))) (declare validate-template) (entity {:version 1} template :id name :indices [type]) (validation :empty (fn [v] (when-not (nil? v) "value must be empty"))) (def template-base { :type #{:required :type-exists} :defaults #{:required :Map} :name #{:required :String} :description #{:String} :machine {:hostname #{:empty} :domain #{:empty}} }) (defn validate-template [template] (validate! template template-base :error ::non-valid-template) (check-validity (assoc template :as :template))) (defn templatize "Create a system from a template" [name {:keys [env machine] :as provided}] {:pre [machine (machine :hostname) (machine :domain)]} (let [{:keys [defaults] :as t} (get-template! name)] (add-system (merge-with merge t (defaults env) provided)))) (defn system-val "grabbing instance id of spec" [spec ks] (get-in (get-system (spec :system-id)) ks))
[ { "context": ";; Copyright 2014 Timothy Brooks\n;;\n;; Licensed under the Apache License, Version ", "end": 32, "score": 0.9998677372932434, "start": 18, "tag": "NAME", "value": "Timothy Brooks" } ]
src/beehive/async.clj
tbrooks8/fault
2
;; Copyright 2014 Timothy Brooks ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns beehive.async (:require [clojure.core.async :refer [>!!]])) (defn return-channels [{:keys [success timed-out error failed any]}] (fn [future] (when any (>!! any future)) (condp = (:status future) :success (when success (>!! success future)) :timed-out (do (when timed-out (>!! timed-out future)) (when failed (>!! failed future))) :error (do (when error (>!! error future)) (when failed (>!! failed future))))))
81103
;; Copyright 2014 <NAME> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns beehive.async (:require [clojure.core.async :refer [>!!]])) (defn return-channels [{:keys [success timed-out error failed any]}] (fn [future] (when any (>!! any future)) (condp = (:status future) :success (when success (>!! success future)) :timed-out (do (when timed-out (>!! timed-out future)) (when failed (>!! failed future))) :error (do (when error (>!! error future)) (when failed (>!! failed future))))))
true
;; Copyright 2014 PI:NAME:<NAME>END_PI ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns beehive.async (:require [clojure.core.async :refer [>!!]])) (defn return-channels [{:keys [success timed-out error failed any]}] (fn [future] (when any (>!! any future)) (condp = (:status future) :success (when success (>!! success future)) :timed-out (do (when timed-out (>!! timed-out future)) (when failed (>!! failed future))) :error (do (when error (>!! error future)) (when failed (>!! failed future))))))
[ { "context": "sername or password\"\n (token {:username \"fail\" :password \"fail\"} \"nginx\")))))\n", "end": 377, "score": 0.7635136842727661, "start": 373, "tag": "USERNAME", "value": "fail" }, { "context": "rd\"\n (token {:username \"fail\" :password \"fail\"} \"nginx\")))))\n", "end": 394, "score": 0.9993622303009033, "start": 390, "tag": "PASSWORD", "value": "fail" } ]
ch16/swarmpit/test/clj/swarmpit/docker/auth/client_test.clj
vincestorm/Docker-on-Amazon-Web-Services
0
(ns swarmpit.docker.auth.client-test (:require [clojure.test :refer :all] [swarmpit.docker.auth.client :refer :all]) (:import (clojure.lang ExceptionInfo))) (deftest ^:integration dockerauth-test (testing "invalid login" (is (thrown-with-msg? ExceptionInfo #"Docker auth error: incorrect username or password" (token {:username "fail" :password "fail"} "nginx")))))
118810
(ns swarmpit.docker.auth.client-test (:require [clojure.test :refer :all] [swarmpit.docker.auth.client :refer :all]) (:import (clojure.lang ExceptionInfo))) (deftest ^:integration dockerauth-test (testing "invalid login" (is (thrown-with-msg? ExceptionInfo #"Docker auth error: incorrect username or password" (token {:username "fail" :password "<PASSWORD>"} "nginx")))))
true
(ns swarmpit.docker.auth.client-test (:require [clojure.test :refer :all] [swarmpit.docker.auth.client :refer :all]) (:import (clojure.lang ExceptionInfo))) (deftest ^:integration dockerauth-test (testing "invalid login" (is (thrown-with-msg? ExceptionInfo #"Docker auth error: incorrect username or password" (token {:username "fail" :password "PI:PASSWORD:<PASSWORD>END_PI"} "nginx")))))
[ { "context": " \"If you are unable to contact a curator, contact help@firecloud.org.\"]]})\n :onClick #(modal/push-moda", "end": 14718, "score": 0.9997288584709167, "start": 14700, "tag": "EMAIL", "value": "help@firecloud.org" } ]
src/cljs/main/broadfcui/page/workspace/summary/tab.cljs
epam/firecloud-ui
0
(ns broadfcui.page.workspace.summary.tab (:require [dmohs.react :as react] [clojure.string :as string] [broadfcui.common :as common] [broadfcui.common.components :as comps] [broadfcui.common.icons :as icons] [broadfcui.common.links :as links] [broadfcui.common.markdown :refer [MarkdownView MarkdownEditor]] [broadfcui.common.modal :as modal] [broadfcui.common.style :as style] [broadfcui.components.buttons :as buttons] [broadfcui.components.collapse :refer [Collapse]] [broadfcui.components.sticky :refer [Sticky]] [broadfcui.endpoints :as endpoints] [broadfcui.nav :as nav] [broadfcui.page.workspace.create :as create] [broadfcui.page.workspace.monitor.common :as moncommon] [broadfcui.page.workspace.summary.acl-editor :refer [AclEditor]] [broadfcui.page.workspace.summary.attribute-editor :as attributes] [broadfcui.page.workspace.summary.catalog.wizard :refer [CatalogWizard]] [broadfcui.page.workspace.summary.library-utils :as library-utils] [broadfcui.page.workspace.summary.library-view :refer [LibraryView]] [broadfcui.page.workspace.summary.publish :as publish] [broadfcui.page.workspace.summary.synchronize :as ws-sync] [broadfcui.page.workspace.workspace-common :as ws-common] [broadfcui.utils :as utils] )) (react/defc- DeleteDialog {:render (fn [{:keys [props state this]}] [comps/OKCancelForm {:header "Confirm Delete" :content [:div {} (when (:deleting? @state) [comps/Blocker {:banner "Deleting..."}]) [:p {:style {:margin 0}} "Are you sure you want to delete this workspace?"] [:p {} (str "Deleting it will delete the associated bucket data" (when (:published? props) " and unpublish the workspace from the Data Library") ".")] [comps/ErrorViewer {:error (:server-error @state)}]] :ok-button {:text "Delete" :onClick #(this :delete)}}]) :delete (fn [{:keys [props state]}] (swap! state assoc :deleting? true :server-error nil) (endpoints/call-ajax-orch {:endpoint (endpoints/delete-workspace (:workspace-id props)) :on-done (fn [{:keys [success? get-parsed-response]}] (swap! state dissoc :deleting?) (if success? (do (modal/pop-modal) (nav/go-to-path :workspaces)) (swap! state assoc :server-error (get-parsed-response false))))}))}) (react/defc- StorageCostEstimate {:render (fn [{:keys [state props]}] (let [{:keys [workspace-id]} props] [:div {:style {:lineHeight "initial"}} [:div {} "Estimated Monthly Storage Fee: " (or (:response @state) "Loading...")] [:div {:style {:fontSize "80%"}} (str "Note: the billing account associated with " (:namespace workspace-id) " will be charged.")]])) :refresh (fn [{:keys [state props]}] (endpoints/call-ajax-orch {:endpoint (endpoints/storage-cost-estimate (:workspace-id props)) :on-done (fn [{:keys [success? status-text raw-response]}] (let [[response parse-error?] (utils/parse-json-string raw-response false false)] (swap! state assoc :response (if parse-error? (str "Error parsing JSON response with status: " status-text) (let [key (if success? "estimate" "message")] (get response key (str "Error: \"" key "\" not found in JSON response with status: " status-text)))))))}))}) (react/defc- SubmissionCounter {:render (fn [{:keys [state]}] (let [{:keys [server-error submissions-count]} @state] (cond server-error [:div {} server-error] submissions-count (let [count-all (apply + (vals submissions-count))] [:div {} (str count-all " Submission" (when-not (= 1 count-all) "s")) (when (pos? count-all) [:ul {:style {:marginTop 0}} (for [[status subs] (sort submissions-count)] [:li {} (str subs " " status)])])]) :else [:div {} "Loading..."]))) :refresh (fn [{:keys [props state]}] (endpoints/call-ajax-orch {:endpoint (endpoints/count-submissions (:workspace-id props)) :on-done (fn [{:keys [success? status-text get-parsed-response]}] (if success? (swap! state assoc :submissions-count (get-parsed-response false)) (swap! state assoc :server-error status-text)))}))}) (react/defc Summary {:component-will-mount (fn [{:keys [locals]}] (swap! locals assoc :label-id (gensym "status") :body-id (gensym "summary"))) :render (fn [{:keys [state props this refs]}] (let [{:keys [server-response]} @state {:keys [workspace workspace-id request-refresh]} props {:keys [server-error]} server-response] [:div {:data-test-id "summary-tab" :data-test-state (cond (or (:updating-attrs? @state) (contains? @state :locking?)) "updating" ;; TODO: "loading" state :else "ready")} [ws-sync/SyncContainer {:ref "sync-container" :workspace-id workspace-id}] (if server-error (style/create-server-error-message server-error) (let [user-access-level (:accessLevel workspace) auth-domain (get-in workspace [:workspace :authorizationDomain]) derived (merge {:can-share? (:canShare workspace) :can-compute? (:canCompute workspace) :owner? (common/access-greater-than-equal-to? user-access-level "OWNER") :writer? (common/access-greater-than-equal-to? user-access-level "WRITER") :catalog-with-read? (and (common/access-greater-than-equal-to? user-access-level "READER") (:catalog workspace))} (utils/restructure user-access-level auth-domain))] [:div {:style {:margin "2.5rem 1.5rem" :display "flex"}} (when (:sharing? @state) [AclEditor (merge (utils/restructure user-access-level request-refresh workspace-id) {:dismiss #(swap! state dissoc :sharing?) :on-users-added (fn [new-users] ((@refs "sync-container") :check-synchronization new-users))})]) (this :-render-sidebar derived) (this :-render-main derived) (when (:updating-attrs? @state) [comps/Blocker {:banner "Updating Attributes..."}]) (when (contains? @state :locking?) [comps/Blocker {:banner (if (:locking? @state) "Locking..." "Unlocking...")}])]))])) :component-did-mount (fn [{:keys [this]}] (this :refresh)) :component-will-receive-props (fn [{:keys [props next-props state this]}] (swap! state dissoc :updating-attrs? :editing?) (when-not (= (:workspace-id props) (:workspace-id next-props)) (this :refresh))) :-render-sidebar (fn [{:keys [props state locals refs this]} {:keys [catalog-with-read? owner? writer? can-share?]}] (let [{:keys [workspace workspace-id request-refresh]} props {:keys [label-id body-id]} @locals {:keys [editing?] {:keys [library-schema billing-projects curator?]} :server-response} @state {{:keys [isLocked library-attributes description authorizationDomain]} :workspace {:keys [runningSubmissionsCount]} :workspaceSubmissionStats} workspace status (common/compute-status workspace) publishable? (and curator? (or catalog-with-read? owner?))] [:div {:style {:flex "0 0 270px" :paddingRight 30}} (when (:cloning? @state) [create/CreateDialog {:dismiss #(swap! state dissoc :cloning?) :workspace-id workspace-id :description description :auth-domain (set (map :membersGroupName authorizationDomain)) :billing-projects billing-projects}]) [:span {:id label-id} [comps/StatusLabel {:text (str status (when (= status "Running") (str " (" runningSubmissionsCount ")"))) :icon (case status "Complete" [icons/CompleteIcon {:size 36}] "Running" [icons/RunningIcon {:size 36}] "Exception" [icons/ExceptionIcon {:size 32}]) :color (style/color-for-status status)}]] [Sticky {:sticky-props {:data-check-every 1 :data-top-anchor (str label-id ":bottom") :data-btm-anchor (str body-id ":bottom")} :contents (let [ready? (and library-schema billing-projects (some? curator?))] [:div {:data-test-id "sidebar" :data-test-state (if ready? "ready" "loading") :style {:width 270}} (when-not ready? (comps/render-blocker "Loading...")) (when (and can-share? (not editing?)) [buttons/SidebarButton {:data-test-id "share-workspace-button" :style :light :margin :top :color :button-primary :text "Share..." :icon :share :onClick #(swap! state assoc :sharing? true)}]) (when (not editing?) [buttons/SidebarButton {:data-test-id "catalog-button" :style :light :color :button-primary :margin :top :icon :catalog :text "Catalog Dataset..." :onClick #(modal/push-modal [CatalogWizard (utils/restructure library-schema workspace workspace-id can-share? owner? curator? writer? catalog-with-read? request-refresh)])}]) (when (and publishable? (not editing?)) (let [working-attributes (library-utils/get-initial-attributes workspace) questions (->> (range (count (:wizard library-schema))) (map (comp first (partial library-utils/get-questions-for-page working-attributes library-schema))) (apply concat)) required-attributes (library-utils/find-required-attributes library-schema)] (if (:library:published library-attributes) [publish/UnpublishButton (utils/restructure workspace-id request-refresh)] [publish/PublishButton (merge (utils/restructure workspace-id request-refresh) {:disabled? (cond (empty? library-attributes) "Dataset attributes must be created before publishing." (seq (library-utils/validate-required (library-utils/remove-empty-values working-attributes) questions required-attributes)) "All required dataset attributes must be set before publishing.")})]))) (when (or owner? writer?) (if-not editing? [buttons/SidebarButton {:style :light :color :button-primary :margin :top :text "Edit" :icon :edit :onClick #(swap! state assoc :editing? true)}] [:div {} [buttons/SidebarButton {:style :light :color :button-primary :margin :top :text "Save" :icon :done :onClick (fn [_] (let [{:keys [success error]} ((@refs "workspace-attribute-editor") :get-attributes) new-description ((@refs "description") :get-text) new-tags ((@refs "tags-autocomplete") :get-tags)] (if error (comps/push-error error) (this :-save-attributes (assoc success :description new-description :tag:tags new-tags)))))}] [buttons/SidebarButton {:style :light :color :exception-state :margin :top :text "Cancel Editing" :icon :cancel :onClick #(swap! state dissoc :editing?)}]])) (when-not editing? [buttons/SidebarButton {:data-test-id "open-clone-workspace-modal-button" :style :light :margin :top :color :button-primary :text "Clone..." :icon :clone :disabled? (when (empty? billing-projects) (comps/no-billing-projects-message)) :onClick #(swap! state assoc :cloning? true)}]) (when (and owner? (not editing?)) [buttons/SidebarButton {:style :light :margin :top :color :button-primary :text (if isLocked "Unlock" "Lock") :icon (if isLocked :unlock :lock) :onClick #(this :-lock-or-unlock isLocked)}]) (when (and owner? (not editing?)) (let [published? (:library:published library-attributes) publisher? (and curator? (or catalog-with-read? owner?))] [buttons/SidebarButton {:data-test-id "delete-workspace-button" :style :light :margin :top :color (if isLocked :text-lighter :exception-state) :text "Delete" :icon :delete :disabled? (cond isLocked "This workspace is locked." (and published? (not publisher?)) {:type :error :header "Alert" :icon-color :warning-state :text [:div {} [:p {:style {:margin 0}} "This workspace is published in the Data Library and cannot be deleted. " "Contact a library curator to ask them to first unpublish the workspace."] [:p {} "If you are unable to contact a curator, contact help@firecloud.org."]]}) :onClick #(modal/push-modal [DeleteDialog (utils/restructure workspace-id published?)])}]))])}]])) :-render-main (fn [{:keys [props state locals]} {:keys [user-access-level auth-domain can-share? owner? curator? writer? catalog-with-read?]}] (let [{:keys [workspace workspace-id bucket-access? request-refresh]} props {:keys [editing? server-response]} @state {:keys [library-schema]} server-response {:keys [body-id]} @locals {:keys [owners] {:keys [createdBy createdDate bucketName description tags workspace-attributes library-attributes]} :workspace} workspace render-detail-box (fn [title & children] [:div {:style {:flexBasis "50%" :paddingRight "2rem" :marginBottom "2rem"}} [:div {:style {:paddingBottom "0.5rem"}} (style/create-section-header title)] (map-indexed (fn [i child] (if (even? i) (style/create-subsection-label child) (style/create-subsection-contents child))) children)]) processed-tags (flatten (map :items (vals tags)))] [:div {:style {:flex "1 1 auto" :overflow "hidden"} :id body-id} [:div {:style {:display "flex" :paddingLeft icons/fw-icon-width}} (render-detail-box "Workspace Access" "Access Level" [:span {:data-test-id "workspace-access-level"} (style/prettify-access-level user-access-level)] (str "Workspace Owner" (when (> (count owners) 1) "s")) (string/join ", " owners) "Authorization Domain" (if-not (empty? auth-domain) [:span {:data-test-id "auth-domain-groups"} (string/join ", " (map :membersGroupName auth-domain))] "None") "Created By" [:div {} [:div {} createdBy] [:div {} (common/format-date createdDate)]]) (render-detail-box "Storage & Analysis" "Google Bucket" [:div {} (case bucket-access? nil [:div {:style {:position "absolute" :marginTop "-1.5em"}} [comps/Spinner {:height "1.5ex"}]] true (links/create-external {:href (str moncommon/google-cloud-context bucketName "/") :title "Click to open the Google Cloud Storage browser for this bucket"} bucketName) false bucketName) (when writer? [StorageCostEstimate {:workspace-id workspace-id :ref "storage-estimate"}])] "Analysis Submissions" [SubmissionCounter {:workspace-id workspace-id :ref "submission-count"}])] [Collapse {:style {:marginBottom "2rem"} :title (style/create-section-header "Tags") :contents [:div {:style {:marginTop "1rem" :fontSize "90%" :lineHeight 1.5}} (cond editing? (react/create-element [comps/TagAutocomplete {:tags processed-tags :ref "tags-autocomplete"}]) (empty? processed-tags) [:em {} "No tags provided"] :else [:div {} (for [tag processed-tags] [:div {:style {:display "inline-block" :background (:tag-background style/colors) :color (:tag-foreground style/colors) :margin "0.1rem 0.1rem" :borderRadius 3 :padding "0.2rem 0.5rem"}} tag])])]}] (when editing? [:div {:style {:marginBottom "10px"}} ws-common/PHI-warning]) [Collapse {:style {:marginBottom "2rem"} :title (style/create-section-header "Description") :contents [:div {:style {:marginTop "1rem" :fontSize "90%" :lineHeight 1.5}} (let [description (not-empty description)] (cond editing? (react/create-element [MarkdownEditor {:ref "description" :initial-text description}]) description [MarkdownView {:text description}] :else [:span {:style {:fontStyle "italic"}} "No description provided"]))]}] (when (seq library-attributes) (if-not library-schema [comps/Spinner {:text "Loading Dataset Attributes" :style {:marginBottom "2rem"}}] [LibraryView (utils/restructure library-attributes library-schema workspace workspace-id request-refresh can-share? owner? curator? writer? catalog-with-read?)])) [attributes/WorkspaceAttributeViewerEditor (merge {:ref "workspace-attribute-editor" :workspace-bucket bucketName} (utils/restructure editing? writer? workspace-attributes workspace-id request-refresh))]])) :-save-attributes (fn [{:keys [props state]} new-attributes] (swap! state assoc :updating-attrs? true) (endpoints/call-ajax-orch {:endpoint (endpoints/set-workspace-attributes (:workspace-id props)) :payload new-attributes :headers utils/content-type=json :on-done (fn [{:keys [success? get-parsed-response]}] (if success? ((:request-refresh props)) (do (swap! state dissoc :updating-attrs?) (comps/push-error-response (get-parsed-response false)))))})) :-lock-or-unlock (fn [{:keys [props state]} locked-now?] (swap! state assoc :locking? (not locked-now?)) (endpoints/call-ajax-orch {:endpoint (endpoints/lock-or-unlock-workspace (:workspace-id props) locked-now?) :on-done (fn [{:keys [success? status-text status-code]}] (when-not success? (if (and (= status-code 409) (not locked-now?)) (comps/push-error "Could not lock workspace, one or more analyses are currently running") (comps/push-error (str "Error: " status-text)))) (swap! state dissoc :locking?) ((:request-refresh props)))})) :refresh (fn [{:keys [state refs]}] (swap! state dissoc :server-response) (when-let [component (@refs "storage-estimate")] (component :refresh)) ((@refs "submission-count") :refresh) (endpoints/get-billing-projects (fn [err-text projects] (if err-text (swap! state update :server-response assoc :server-error err-text) (swap! state update :server-response assoc :billing-projects (map :projectName projects))))) (endpoints/get-library-attributes (fn [{:keys [success? get-parsed-response]}] (if success? (let [response (get-parsed-response)] (swap! state update :server-response assoc :library-schema (-> response (update-in [:display :primary] (partial map keyword)) (update-in [:display :secondary] (partial map keyword))))) (swap! state update :server-response assoc :server-error "Unable to load library schema")))) (endpoints/call-ajax-orch {:endpoint endpoints/get-library-curator-status :on-done (fn [{:keys [success? get-parsed-response]}] (if success? (swap! state update :server-response assoc :curator? (:curator (get-parsed-response))) (swap! state update :server-response assoc :server-error "Unable to determine curator status")))}))})
57035
(ns broadfcui.page.workspace.summary.tab (:require [dmohs.react :as react] [clojure.string :as string] [broadfcui.common :as common] [broadfcui.common.components :as comps] [broadfcui.common.icons :as icons] [broadfcui.common.links :as links] [broadfcui.common.markdown :refer [MarkdownView MarkdownEditor]] [broadfcui.common.modal :as modal] [broadfcui.common.style :as style] [broadfcui.components.buttons :as buttons] [broadfcui.components.collapse :refer [Collapse]] [broadfcui.components.sticky :refer [Sticky]] [broadfcui.endpoints :as endpoints] [broadfcui.nav :as nav] [broadfcui.page.workspace.create :as create] [broadfcui.page.workspace.monitor.common :as moncommon] [broadfcui.page.workspace.summary.acl-editor :refer [AclEditor]] [broadfcui.page.workspace.summary.attribute-editor :as attributes] [broadfcui.page.workspace.summary.catalog.wizard :refer [CatalogWizard]] [broadfcui.page.workspace.summary.library-utils :as library-utils] [broadfcui.page.workspace.summary.library-view :refer [LibraryView]] [broadfcui.page.workspace.summary.publish :as publish] [broadfcui.page.workspace.summary.synchronize :as ws-sync] [broadfcui.page.workspace.workspace-common :as ws-common] [broadfcui.utils :as utils] )) (react/defc- DeleteDialog {:render (fn [{:keys [props state this]}] [comps/OKCancelForm {:header "Confirm Delete" :content [:div {} (when (:deleting? @state) [comps/Blocker {:banner "Deleting..."}]) [:p {:style {:margin 0}} "Are you sure you want to delete this workspace?"] [:p {} (str "Deleting it will delete the associated bucket data" (when (:published? props) " and unpublish the workspace from the Data Library") ".")] [comps/ErrorViewer {:error (:server-error @state)}]] :ok-button {:text "Delete" :onClick #(this :delete)}}]) :delete (fn [{:keys [props state]}] (swap! state assoc :deleting? true :server-error nil) (endpoints/call-ajax-orch {:endpoint (endpoints/delete-workspace (:workspace-id props)) :on-done (fn [{:keys [success? get-parsed-response]}] (swap! state dissoc :deleting?) (if success? (do (modal/pop-modal) (nav/go-to-path :workspaces)) (swap! state assoc :server-error (get-parsed-response false))))}))}) (react/defc- StorageCostEstimate {:render (fn [{:keys [state props]}] (let [{:keys [workspace-id]} props] [:div {:style {:lineHeight "initial"}} [:div {} "Estimated Monthly Storage Fee: " (or (:response @state) "Loading...")] [:div {:style {:fontSize "80%"}} (str "Note: the billing account associated with " (:namespace workspace-id) " will be charged.")]])) :refresh (fn [{:keys [state props]}] (endpoints/call-ajax-orch {:endpoint (endpoints/storage-cost-estimate (:workspace-id props)) :on-done (fn [{:keys [success? status-text raw-response]}] (let [[response parse-error?] (utils/parse-json-string raw-response false false)] (swap! state assoc :response (if parse-error? (str "Error parsing JSON response with status: " status-text) (let [key (if success? "estimate" "message")] (get response key (str "Error: \"" key "\" not found in JSON response with status: " status-text)))))))}))}) (react/defc- SubmissionCounter {:render (fn [{:keys [state]}] (let [{:keys [server-error submissions-count]} @state] (cond server-error [:div {} server-error] submissions-count (let [count-all (apply + (vals submissions-count))] [:div {} (str count-all " Submission" (when-not (= 1 count-all) "s")) (when (pos? count-all) [:ul {:style {:marginTop 0}} (for [[status subs] (sort submissions-count)] [:li {} (str subs " " status)])])]) :else [:div {} "Loading..."]))) :refresh (fn [{:keys [props state]}] (endpoints/call-ajax-orch {:endpoint (endpoints/count-submissions (:workspace-id props)) :on-done (fn [{:keys [success? status-text get-parsed-response]}] (if success? (swap! state assoc :submissions-count (get-parsed-response false)) (swap! state assoc :server-error status-text)))}))}) (react/defc Summary {:component-will-mount (fn [{:keys [locals]}] (swap! locals assoc :label-id (gensym "status") :body-id (gensym "summary"))) :render (fn [{:keys [state props this refs]}] (let [{:keys [server-response]} @state {:keys [workspace workspace-id request-refresh]} props {:keys [server-error]} server-response] [:div {:data-test-id "summary-tab" :data-test-state (cond (or (:updating-attrs? @state) (contains? @state :locking?)) "updating" ;; TODO: "loading" state :else "ready")} [ws-sync/SyncContainer {:ref "sync-container" :workspace-id workspace-id}] (if server-error (style/create-server-error-message server-error) (let [user-access-level (:accessLevel workspace) auth-domain (get-in workspace [:workspace :authorizationDomain]) derived (merge {:can-share? (:canShare workspace) :can-compute? (:canCompute workspace) :owner? (common/access-greater-than-equal-to? user-access-level "OWNER") :writer? (common/access-greater-than-equal-to? user-access-level "WRITER") :catalog-with-read? (and (common/access-greater-than-equal-to? user-access-level "READER") (:catalog workspace))} (utils/restructure user-access-level auth-domain))] [:div {:style {:margin "2.5rem 1.5rem" :display "flex"}} (when (:sharing? @state) [AclEditor (merge (utils/restructure user-access-level request-refresh workspace-id) {:dismiss #(swap! state dissoc :sharing?) :on-users-added (fn [new-users] ((@refs "sync-container") :check-synchronization new-users))})]) (this :-render-sidebar derived) (this :-render-main derived) (when (:updating-attrs? @state) [comps/Blocker {:banner "Updating Attributes..."}]) (when (contains? @state :locking?) [comps/Blocker {:banner (if (:locking? @state) "Locking..." "Unlocking...")}])]))])) :component-did-mount (fn [{:keys [this]}] (this :refresh)) :component-will-receive-props (fn [{:keys [props next-props state this]}] (swap! state dissoc :updating-attrs? :editing?) (when-not (= (:workspace-id props) (:workspace-id next-props)) (this :refresh))) :-render-sidebar (fn [{:keys [props state locals refs this]} {:keys [catalog-with-read? owner? writer? can-share?]}] (let [{:keys [workspace workspace-id request-refresh]} props {:keys [label-id body-id]} @locals {:keys [editing?] {:keys [library-schema billing-projects curator?]} :server-response} @state {{:keys [isLocked library-attributes description authorizationDomain]} :workspace {:keys [runningSubmissionsCount]} :workspaceSubmissionStats} workspace status (common/compute-status workspace) publishable? (and curator? (or catalog-with-read? owner?))] [:div {:style {:flex "0 0 270px" :paddingRight 30}} (when (:cloning? @state) [create/CreateDialog {:dismiss #(swap! state dissoc :cloning?) :workspace-id workspace-id :description description :auth-domain (set (map :membersGroupName authorizationDomain)) :billing-projects billing-projects}]) [:span {:id label-id} [comps/StatusLabel {:text (str status (when (= status "Running") (str " (" runningSubmissionsCount ")"))) :icon (case status "Complete" [icons/CompleteIcon {:size 36}] "Running" [icons/RunningIcon {:size 36}] "Exception" [icons/ExceptionIcon {:size 32}]) :color (style/color-for-status status)}]] [Sticky {:sticky-props {:data-check-every 1 :data-top-anchor (str label-id ":bottom") :data-btm-anchor (str body-id ":bottom")} :contents (let [ready? (and library-schema billing-projects (some? curator?))] [:div {:data-test-id "sidebar" :data-test-state (if ready? "ready" "loading") :style {:width 270}} (when-not ready? (comps/render-blocker "Loading...")) (when (and can-share? (not editing?)) [buttons/SidebarButton {:data-test-id "share-workspace-button" :style :light :margin :top :color :button-primary :text "Share..." :icon :share :onClick #(swap! state assoc :sharing? true)}]) (when (not editing?) [buttons/SidebarButton {:data-test-id "catalog-button" :style :light :color :button-primary :margin :top :icon :catalog :text "Catalog Dataset..." :onClick #(modal/push-modal [CatalogWizard (utils/restructure library-schema workspace workspace-id can-share? owner? curator? writer? catalog-with-read? request-refresh)])}]) (when (and publishable? (not editing?)) (let [working-attributes (library-utils/get-initial-attributes workspace) questions (->> (range (count (:wizard library-schema))) (map (comp first (partial library-utils/get-questions-for-page working-attributes library-schema))) (apply concat)) required-attributes (library-utils/find-required-attributes library-schema)] (if (:library:published library-attributes) [publish/UnpublishButton (utils/restructure workspace-id request-refresh)] [publish/PublishButton (merge (utils/restructure workspace-id request-refresh) {:disabled? (cond (empty? library-attributes) "Dataset attributes must be created before publishing." (seq (library-utils/validate-required (library-utils/remove-empty-values working-attributes) questions required-attributes)) "All required dataset attributes must be set before publishing.")})]))) (when (or owner? writer?) (if-not editing? [buttons/SidebarButton {:style :light :color :button-primary :margin :top :text "Edit" :icon :edit :onClick #(swap! state assoc :editing? true)}] [:div {} [buttons/SidebarButton {:style :light :color :button-primary :margin :top :text "Save" :icon :done :onClick (fn [_] (let [{:keys [success error]} ((@refs "workspace-attribute-editor") :get-attributes) new-description ((@refs "description") :get-text) new-tags ((@refs "tags-autocomplete") :get-tags)] (if error (comps/push-error error) (this :-save-attributes (assoc success :description new-description :tag:tags new-tags)))))}] [buttons/SidebarButton {:style :light :color :exception-state :margin :top :text "Cancel Editing" :icon :cancel :onClick #(swap! state dissoc :editing?)}]])) (when-not editing? [buttons/SidebarButton {:data-test-id "open-clone-workspace-modal-button" :style :light :margin :top :color :button-primary :text "Clone..." :icon :clone :disabled? (when (empty? billing-projects) (comps/no-billing-projects-message)) :onClick #(swap! state assoc :cloning? true)}]) (when (and owner? (not editing?)) [buttons/SidebarButton {:style :light :margin :top :color :button-primary :text (if isLocked "Unlock" "Lock") :icon (if isLocked :unlock :lock) :onClick #(this :-lock-or-unlock isLocked)}]) (when (and owner? (not editing?)) (let [published? (:library:published library-attributes) publisher? (and curator? (or catalog-with-read? owner?))] [buttons/SidebarButton {:data-test-id "delete-workspace-button" :style :light :margin :top :color (if isLocked :text-lighter :exception-state) :text "Delete" :icon :delete :disabled? (cond isLocked "This workspace is locked." (and published? (not publisher?)) {:type :error :header "Alert" :icon-color :warning-state :text [:div {} [:p {:style {:margin 0}} "This workspace is published in the Data Library and cannot be deleted. " "Contact a library curator to ask them to first unpublish the workspace."] [:p {} "If you are unable to contact a curator, contact <EMAIL>."]]}) :onClick #(modal/push-modal [DeleteDialog (utils/restructure workspace-id published?)])}]))])}]])) :-render-main (fn [{:keys [props state locals]} {:keys [user-access-level auth-domain can-share? owner? curator? writer? catalog-with-read?]}] (let [{:keys [workspace workspace-id bucket-access? request-refresh]} props {:keys [editing? server-response]} @state {:keys [library-schema]} server-response {:keys [body-id]} @locals {:keys [owners] {:keys [createdBy createdDate bucketName description tags workspace-attributes library-attributes]} :workspace} workspace render-detail-box (fn [title & children] [:div {:style {:flexBasis "50%" :paddingRight "2rem" :marginBottom "2rem"}} [:div {:style {:paddingBottom "0.5rem"}} (style/create-section-header title)] (map-indexed (fn [i child] (if (even? i) (style/create-subsection-label child) (style/create-subsection-contents child))) children)]) processed-tags (flatten (map :items (vals tags)))] [:div {:style {:flex "1 1 auto" :overflow "hidden"} :id body-id} [:div {:style {:display "flex" :paddingLeft icons/fw-icon-width}} (render-detail-box "Workspace Access" "Access Level" [:span {:data-test-id "workspace-access-level"} (style/prettify-access-level user-access-level)] (str "Workspace Owner" (when (> (count owners) 1) "s")) (string/join ", " owners) "Authorization Domain" (if-not (empty? auth-domain) [:span {:data-test-id "auth-domain-groups"} (string/join ", " (map :membersGroupName auth-domain))] "None") "Created By" [:div {} [:div {} createdBy] [:div {} (common/format-date createdDate)]]) (render-detail-box "Storage & Analysis" "Google Bucket" [:div {} (case bucket-access? nil [:div {:style {:position "absolute" :marginTop "-1.5em"}} [comps/Spinner {:height "1.5ex"}]] true (links/create-external {:href (str moncommon/google-cloud-context bucketName "/") :title "Click to open the Google Cloud Storage browser for this bucket"} bucketName) false bucketName) (when writer? [StorageCostEstimate {:workspace-id workspace-id :ref "storage-estimate"}])] "Analysis Submissions" [SubmissionCounter {:workspace-id workspace-id :ref "submission-count"}])] [Collapse {:style {:marginBottom "2rem"} :title (style/create-section-header "Tags") :contents [:div {:style {:marginTop "1rem" :fontSize "90%" :lineHeight 1.5}} (cond editing? (react/create-element [comps/TagAutocomplete {:tags processed-tags :ref "tags-autocomplete"}]) (empty? processed-tags) [:em {} "No tags provided"] :else [:div {} (for [tag processed-tags] [:div {:style {:display "inline-block" :background (:tag-background style/colors) :color (:tag-foreground style/colors) :margin "0.1rem 0.1rem" :borderRadius 3 :padding "0.2rem 0.5rem"}} tag])])]}] (when editing? [:div {:style {:marginBottom "10px"}} ws-common/PHI-warning]) [Collapse {:style {:marginBottom "2rem"} :title (style/create-section-header "Description") :contents [:div {:style {:marginTop "1rem" :fontSize "90%" :lineHeight 1.5}} (let [description (not-empty description)] (cond editing? (react/create-element [MarkdownEditor {:ref "description" :initial-text description}]) description [MarkdownView {:text description}] :else [:span {:style {:fontStyle "italic"}} "No description provided"]))]}] (when (seq library-attributes) (if-not library-schema [comps/Spinner {:text "Loading Dataset Attributes" :style {:marginBottom "2rem"}}] [LibraryView (utils/restructure library-attributes library-schema workspace workspace-id request-refresh can-share? owner? curator? writer? catalog-with-read?)])) [attributes/WorkspaceAttributeViewerEditor (merge {:ref "workspace-attribute-editor" :workspace-bucket bucketName} (utils/restructure editing? writer? workspace-attributes workspace-id request-refresh))]])) :-save-attributes (fn [{:keys [props state]} new-attributes] (swap! state assoc :updating-attrs? true) (endpoints/call-ajax-orch {:endpoint (endpoints/set-workspace-attributes (:workspace-id props)) :payload new-attributes :headers utils/content-type=json :on-done (fn [{:keys [success? get-parsed-response]}] (if success? ((:request-refresh props)) (do (swap! state dissoc :updating-attrs?) (comps/push-error-response (get-parsed-response false)))))})) :-lock-or-unlock (fn [{:keys [props state]} locked-now?] (swap! state assoc :locking? (not locked-now?)) (endpoints/call-ajax-orch {:endpoint (endpoints/lock-or-unlock-workspace (:workspace-id props) locked-now?) :on-done (fn [{:keys [success? status-text status-code]}] (when-not success? (if (and (= status-code 409) (not locked-now?)) (comps/push-error "Could not lock workspace, one or more analyses are currently running") (comps/push-error (str "Error: " status-text)))) (swap! state dissoc :locking?) ((:request-refresh props)))})) :refresh (fn [{:keys [state refs]}] (swap! state dissoc :server-response) (when-let [component (@refs "storage-estimate")] (component :refresh)) ((@refs "submission-count") :refresh) (endpoints/get-billing-projects (fn [err-text projects] (if err-text (swap! state update :server-response assoc :server-error err-text) (swap! state update :server-response assoc :billing-projects (map :projectName projects))))) (endpoints/get-library-attributes (fn [{:keys [success? get-parsed-response]}] (if success? (let [response (get-parsed-response)] (swap! state update :server-response assoc :library-schema (-> response (update-in [:display :primary] (partial map keyword)) (update-in [:display :secondary] (partial map keyword))))) (swap! state update :server-response assoc :server-error "Unable to load library schema")))) (endpoints/call-ajax-orch {:endpoint endpoints/get-library-curator-status :on-done (fn [{:keys [success? get-parsed-response]}] (if success? (swap! state update :server-response assoc :curator? (:curator (get-parsed-response))) (swap! state update :server-response assoc :server-error "Unable to determine curator status")))}))})
true
(ns broadfcui.page.workspace.summary.tab (:require [dmohs.react :as react] [clojure.string :as string] [broadfcui.common :as common] [broadfcui.common.components :as comps] [broadfcui.common.icons :as icons] [broadfcui.common.links :as links] [broadfcui.common.markdown :refer [MarkdownView MarkdownEditor]] [broadfcui.common.modal :as modal] [broadfcui.common.style :as style] [broadfcui.components.buttons :as buttons] [broadfcui.components.collapse :refer [Collapse]] [broadfcui.components.sticky :refer [Sticky]] [broadfcui.endpoints :as endpoints] [broadfcui.nav :as nav] [broadfcui.page.workspace.create :as create] [broadfcui.page.workspace.monitor.common :as moncommon] [broadfcui.page.workspace.summary.acl-editor :refer [AclEditor]] [broadfcui.page.workspace.summary.attribute-editor :as attributes] [broadfcui.page.workspace.summary.catalog.wizard :refer [CatalogWizard]] [broadfcui.page.workspace.summary.library-utils :as library-utils] [broadfcui.page.workspace.summary.library-view :refer [LibraryView]] [broadfcui.page.workspace.summary.publish :as publish] [broadfcui.page.workspace.summary.synchronize :as ws-sync] [broadfcui.page.workspace.workspace-common :as ws-common] [broadfcui.utils :as utils] )) (react/defc- DeleteDialog {:render (fn [{:keys [props state this]}] [comps/OKCancelForm {:header "Confirm Delete" :content [:div {} (when (:deleting? @state) [comps/Blocker {:banner "Deleting..."}]) [:p {:style {:margin 0}} "Are you sure you want to delete this workspace?"] [:p {} (str "Deleting it will delete the associated bucket data" (when (:published? props) " and unpublish the workspace from the Data Library") ".")] [comps/ErrorViewer {:error (:server-error @state)}]] :ok-button {:text "Delete" :onClick #(this :delete)}}]) :delete (fn [{:keys [props state]}] (swap! state assoc :deleting? true :server-error nil) (endpoints/call-ajax-orch {:endpoint (endpoints/delete-workspace (:workspace-id props)) :on-done (fn [{:keys [success? get-parsed-response]}] (swap! state dissoc :deleting?) (if success? (do (modal/pop-modal) (nav/go-to-path :workspaces)) (swap! state assoc :server-error (get-parsed-response false))))}))}) (react/defc- StorageCostEstimate {:render (fn [{:keys [state props]}] (let [{:keys [workspace-id]} props] [:div {:style {:lineHeight "initial"}} [:div {} "Estimated Monthly Storage Fee: " (or (:response @state) "Loading...")] [:div {:style {:fontSize "80%"}} (str "Note: the billing account associated with " (:namespace workspace-id) " will be charged.")]])) :refresh (fn [{:keys [state props]}] (endpoints/call-ajax-orch {:endpoint (endpoints/storage-cost-estimate (:workspace-id props)) :on-done (fn [{:keys [success? status-text raw-response]}] (let [[response parse-error?] (utils/parse-json-string raw-response false false)] (swap! state assoc :response (if parse-error? (str "Error parsing JSON response with status: " status-text) (let [key (if success? "estimate" "message")] (get response key (str "Error: \"" key "\" not found in JSON response with status: " status-text)))))))}))}) (react/defc- SubmissionCounter {:render (fn [{:keys [state]}] (let [{:keys [server-error submissions-count]} @state] (cond server-error [:div {} server-error] submissions-count (let [count-all (apply + (vals submissions-count))] [:div {} (str count-all " Submission" (when-not (= 1 count-all) "s")) (when (pos? count-all) [:ul {:style {:marginTop 0}} (for [[status subs] (sort submissions-count)] [:li {} (str subs " " status)])])]) :else [:div {} "Loading..."]))) :refresh (fn [{:keys [props state]}] (endpoints/call-ajax-orch {:endpoint (endpoints/count-submissions (:workspace-id props)) :on-done (fn [{:keys [success? status-text get-parsed-response]}] (if success? (swap! state assoc :submissions-count (get-parsed-response false)) (swap! state assoc :server-error status-text)))}))}) (react/defc Summary {:component-will-mount (fn [{:keys [locals]}] (swap! locals assoc :label-id (gensym "status") :body-id (gensym "summary"))) :render (fn [{:keys [state props this refs]}] (let [{:keys [server-response]} @state {:keys [workspace workspace-id request-refresh]} props {:keys [server-error]} server-response] [:div {:data-test-id "summary-tab" :data-test-state (cond (or (:updating-attrs? @state) (contains? @state :locking?)) "updating" ;; TODO: "loading" state :else "ready")} [ws-sync/SyncContainer {:ref "sync-container" :workspace-id workspace-id}] (if server-error (style/create-server-error-message server-error) (let [user-access-level (:accessLevel workspace) auth-domain (get-in workspace [:workspace :authorizationDomain]) derived (merge {:can-share? (:canShare workspace) :can-compute? (:canCompute workspace) :owner? (common/access-greater-than-equal-to? user-access-level "OWNER") :writer? (common/access-greater-than-equal-to? user-access-level "WRITER") :catalog-with-read? (and (common/access-greater-than-equal-to? user-access-level "READER") (:catalog workspace))} (utils/restructure user-access-level auth-domain))] [:div {:style {:margin "2.5rem 1.5rem" :display "flex"}} (when (:sharing? @state) [AclEditor (merge (utils/restructure user-access-level request-refresh workspace-id) {:dismiss #(swap! state dissoc :sharing?) :on-users-added (fn [new-users] ((@refs "sync-container") :check-synchronization new-users))})]) (this :-render-sidebar derived) (this :-render-main derived) (when (:updating-attrs? @state) [comps/Blocker {:banner "Updating Attributes..."}]) (when (contains? @state :locking?) [comps/Blocker {:banner (if (:locking? @state) "Locking..." "Unlocking...")}])]))])) :component-did-mount (fn [{:keys [this]}] (this :refresh)) :component-will-receive-props (fn [{:keys [props next-props state this]}] (swap! state dissoc :updating-attrs? :editing?) (when-not (= (:workspace-id props) (:workspace-id next-props)) (this :refresh))) :-render-sidebar (fn [{:keys [props state locals refs this]} {:keys [catalog-with-read? owner? writer? can-share?]}] (let [{:keys [workspace workspace-id request-refresh]} props {:keys [label-id body-id]} @locals {:keys [editing?] {:keys [library-schema billing-projects curator?]} :server-response} @state {{:keys [isLocked library-attributes description authorizationDomain]} :workspace {:keys [runningSubmissionsCount]} :workspaceSubmissionStats} workspace status (common/compute-status workspace) publishable? (and curator? (or catalog-with-read? owner?))] [:div {:style {:flex "0 0 270px" :paddingRight 30}} (when (:cloning? @state) [create/CreateDialog {:dismiss #(swap! state dissoc :cloning?) :workspace-id workspace-id :description description :auth-domain (set (map :membersGroupName authorizationDomain)) :billing-projects billing-projects}]) [:span {:id label-id} [comps/StatusLabel {:text (str status (when (= status "Running") (str " (" runningSubmissionsCount ")"))) :icon (case status "Complete" [icons/CompleteIcon {:size 36}] "Running" [icons/RunningIcon {:size 36}] "Exception" [icons/ExceptionIcon {:size 32}]) :color (style/color-for-status status)}]] [Sticky {:sticky-props {:data-check-every 1 :data-top-anchor (str label-id ":bottom") :data-btm-anchor (str body-id ":bottom")} :contents (let [ready? (and library-schema billing-projects (some? curator?))] [:div {:data-test-id "sidebar" :data-test-state (if ready? "ready" "loading") :style {:width 270}} (when-not ready? (comps/render-blocker "Loading...")) (when (and can-share? (not editing?)) [buttons/SidebarButton {:data-test-id "share-workspace-button" :style :light :margin :top :color :button-primary :text "Share..." :icon :share :onClick #(swap! state assoc :sharing? true)}]) (when (not editing?) [buttons/SidebarButton {:data-test-id "catalog-button" :style :light :color :button-primary :margin :top :icon :catalog :text "Catalog Dataset..." :onClick #(modal/push-modal [CatalogWizard (utils/restructure library-schema workspace workspace-id can-share? owner? curator? writer? catalog-with-read? request-refresh)])}]) (when (and publishable? (not editing?)) (let [working-attributes (library-utils/get-initial-attributes workspace) questions (->> (range (count (:wizard library-schema))) (map (comp first (partial library-utils/get-questions-for-page working-attributes library-schema))) (apply concat)) required-attributes (library-utils/find-required-attributes library-schema)] (if (:library:published library-attributes) [publish/UnpublishButton (utils/restructure workspace-id request-refresh)] [publish/PublishButton (merge (utils/restructure workspace-id request-refresh) {:disabled? (cond (empty? library-attributes) "Dataset attributes must be created before publishing." (seq (library-utils/validate-required (library-utils/remove-empty-values working-attributes) questions required-attributes)) "All required dataset attributes must be set before publishing.")})]))) (when (or owner? writer?) (if-not editing? [buttons/SidebarButton {:style :light :color :button-primary :margin :top :text "Edit" :icon :edit :onClick #(swap! state assoc :editing? true)}] [:div {} [buttons/SidebarButton {:style :light :color :button-primary :margin :top :text "Save" :icon :done :onClick (fn [_] (let [{:keys [success error]} ((@refs "workspace-attribute-editor") :get-attributes) new-description ((@refs "description") :get-text) new-tags ((@refs "tags-autocomplete") :get-tags)] (if error (comps/push-error error) (this :-save-attributes (assoc success :description new-description :tag:tags new-tags)))))}] [buttons/SidebarButton {:style :light :color :exception-state :margin :top :text "Cancel Editing" :icon :cancel :onClick #(swap! state dissoc :editing?)}]])) (when-not editing? [buttons/SidebarButton {:data-test-id "open-clone-workspace-modal-button" :style :light :margin :top :color :button-primary :text "Clone..." :icon :clone :disabled? (when (empty? billing-projects) (comps/no-billing-projects-message)) :onClick #(swap! state assoc :cloning? true)}]) (when (and owner? (not editing?)) [buttons/SidebarButton {:style :light :margin :top :color :button-primary :text (if isLocked "Unlock" "Lock") :icon (if isLocked :unlock :lock) :onClick #(this :-lock-or-unlock isLocked)}]) (when (and owner? (not editing?)) (let [published? (:library:published library-attributes) publisher? (and curator? (or catalog-with-read? owner?))] [buttons/SidebarButton {:data-test-id "delete-workspace-button" :style :light :margin :top :color (if isLocked :text-lighter :exception-state) :text "Delete" :icon :delete :disabled? (cond isLocked "This workspace is locked." (and published? (not publisher?)) {:type :error :header "Alert" :icon-color :warning-state :text [:div {} [:p {:style {:margin 0}} "This workspace is published in the Data Library and cannot be deleted. " "Contact a library curator to ask them to first unpublish the workspace."] [:p {} "If you are unable to contact a curator, contact PI:EMAIL:<EMAIL>END_PI."]]}) :onClick #(modal/push-modal [DeleteDialog (utils/restructure workspace-id published?)])}]))])}]])) :-render-main (fn [{:keys [props state locals]} {:keys [user-access-level auth-domain can-share? owner? curator? writer? catalog-with-read?]}] (let [{:keys [workspace workspace-id bucket-access? request-refresh]} props {:keys [editing? server-response]} @state {:keys [library-schema]} server-response {:keys [body-id]} @locals {:keys [owners] {:keys [createdBy createdDate bucketName description tags workspace-attributes library-attributes]} :workspace} workspace render-detail-box (fn [title & children] [:div {:style {:flexBasis "50%" :paddingRight "2rem" :marginBottom "2rem"}} [:div {:style {:paddingBottom "0.5rem"}} (style/create-section-header title)] (map-indexed (fn [i child] (if (even? i) (style/create-subsection-label child) (style/create-subsection-contents child))) children)]) processed-tags (flatten (map :items (vals tags)))] [:div {:style {:flex "1 1 auto" :overflow "hidden"} :id body-id} [:div {:style {:display "flex" :paddingLeft icons/fw-icon-width}} (render-detail-box "Workspace Access" "Access Level" [:span {:data-test-id "workspace-access-level"} (style/prettify-access-level user-access-level)] (str "Workspace Owner" (when (> (count owners) 1) "s")) (string/join ", " owners) "Authorization Domain" (if-not (empty? auth-domain) [:span {:data-test-id "auth-domain-groups"} (string/join ", " (map :membersGroupName auth-domain))] "None") "Created By" [:div {} [:div {} createdBy] [:div {} (common/format-date createdDate)]]) (render-detail-box "Storage & Analysis" "Google Bucket" [:div {} (case bucket-access? nil [:div {:style {:position "absolute" :marginTop "-1.5em"}} [comps/Spinner {:height "1.5ex"}]] true (links/create-external {:href (str moncommon/google-cloud-context bucketName "/") :title "Click to open the Google Cloud Storage browser for this bucket"} bucketName) false bucketName) (when writer? [StorageCostEstimate {:workspace-id workspace-id :ref "storage-estimate"}])] "Analysis Submissions" [SubmissionCounter {:workspace-id workspace-id :ref "submission-count"}])] [Collapse {:style {:marginBottom "2rem"} :title (style/create-section-header "Tags") :contents [:div {:style {:marginTop "1rem" :fontSize "90%" :lineHeight 1.5}} (cond editing? (react/create-element [comps/TagAutocomplete {:tags processed-tags :ref "tags-autocomplete"}]) (empty? processed-tags) [:em {} "No tags provided"] :else [:div {} (for [tag processed-tags] [:div {:style {:display "inline-block" :background (:tag-background style/colors) :color (:tag-foreground style/colors) :margin "0.1rem 0.1rem" :borderRadius 3 :padding "0.2rem 0.5rem"}} tag])])]}] (when editing? [:div {:style {:marginBottom "10px"}} ws-common/PHI-warning]) [Collapse {:style {:marginBottom "2rem"} :title (style/create-section-header "Description") :contents [:div {:style {:marginTop "1rem" :fontSize "90%" :lineHeight 1.5}} (let [description (not-empty description)] (cond editing? (react/create-element [MarkdownEditor {:ref "description" :initial-text description}]) description [MarkdownView {:text description}] :else [:span {:style {:fontStyle "italic"}} "No description provided"]))]}] (when (seq library-attributes) (if-not library-schema [comps/Spinner {:text "Loading Dataset Attributes" :style {:marginBottom "2rem"}}] [LibraryView (utils/restructure library-attributes library-schema workspace workspace-id request-refresh can-share? owner? curator? writer? catalog-with-read?)])) [attributes/WorkspaceAttributeViewerEditor (merge {:ref "workspace-attribute-editor" :workspace-bucket bucketName} (utils/restructure editing? writer? workspace-attributes workspace-id request-refresh))]])) :-save-attributes (fn [{:keys [props state]} new-attributes] (swap! state assoc :updating-attrs? true) (endpoints/call-ajax-orch {:endpoint (endpoints/set-workspace-attributes (:workspace-id props)) :payload new-attributes :headers utils/content-type=json :on-done (fn [{:keys [success? get-parsed-response]}] (if success? ((:request-refresh props)) (do (swap! state dissoc :updating-attrs?) (comps/push-error-response (get-parsed-response false)))))})) :-lock-or-unlock (fn [{:keys [props state]} locked-now?] (swap! state assoc :locking? (not locked-now?)) (endpoints/call-ajax-orch {:endpoint (endpoints/lock-or-unlock-workspace (:workspace-id props) locked-now?) :on-done (fn [{:keys [success? status-text status-code]}] (when-not success? (if (and (= status-code 409) (not locked-now?)) (comps/push-error "Could not lock workspace, one or more analyses are currently running") (comps/push-error (str "Error: " status-text)))) (swap! state dissoc :locking?) ((:request-refresh props)))})) :refresh (fn [{:keys [state refs]}] (swap! state dissoc :server-response) (when-let [component (@refs "storage-estimate")] (component :refresh)) ((@refs "submission-count") :refresh) (endpoints/get-billing-projects (fn [err-text projects] (if err-text (swap! state update :server-response assoc :server-error err-text) (swap! state update :server-response assoc :billing-projects (map :projectName projects))))) (endpoints/get-library-attributes (fn [{:keys [success? get-parsed-response]}] (if success? (let [response (get-parsed-response)] (swap! state update :server-response assoc :library-schema (-> response (update-in [:display :primary] (partial map keyword)) (update-in [:display :secondary] (partial map keyword))))) (swap! state update :server-response assoc :server-error "Unable to load library schema")))) (endpoints/call-ajax-orch {:endpoint endpoints/get-library-curator-status :on-done (fn [{:keys [success? get-parsed-response]}] (if success? (swap! state update :server-response assoc :curator? (:curator (get-parsed-response))) (swap! state update :server-response assoc :server-error "Unable to determine curator status")))}))})
[ { "context": " {:authorizationData [{:authorizationToken \"QVdTOnBhc3N3b3Jk\"}]}]\n (is (= {:username ", "end": 1045, "score": 0.8336284160614014, "start": 1029, "tag": "PASSWORD", "value": "QVdTOnBhc3N3b3Jk" }, { "context": "AWS\"\n :password \"password\"}\n (credentials/g", "end": 1154, "score": 0.9995825886726379, "start": 1146, "tag": "PASSWORD", "value": "password" }, { "context": "ecr-credential image) {:username \"AWS\" :password \"password\"}]\n (let [retriever (credentials", "end": 2296, "score": 0.9996018409729004, "start": 2288, "tag": "PASSWORD", "value": "password" }, { "context": " \"john.doe\" \"abc123\"\n [(make-retriever \"john.doe\" \"abc123\") (make-retriever)] \"john.", "end": 4109, "score": 0.7673900723457336, "start": 4101, "tag": "USERNAME", "value": "john.doe" }, { "context": "oe\" \"abc123\"\n [(make-retriever \"john.doe\" \"abc123\") (make-retriever)] \"john.doe\" \"abc", "end": 4118, "score": 0.9940155744552612, "start": 4112, "tag": "PASSWORD", "value": "abc123" }, { "context": "n.doe\" \"abc123\") (make-retriever)] \"john.doe\" \"abc123\")))\n\n (testing \"returns Optional/empty ", "end": 4162, "score": 0.9504534602165222, "start": 4154, "tag": "USERNAME", "value": "john.doe" }, { "context": "123\") (make-retriever)] \"john.doe\" \"abc123\")))\n\n (testing \"returns Optional/empty when all ", "end": 4171, "score": 0.9864367842674255, "start": 4165, "tag": "PASSWORD", "value": "abc123" } ]
test/vessel/jib/credentials_test.clj
nubank/vessel
32
(ns vessel.jib.credentials-test (:require [clojure.test :refer :all] [cognitect.aws.client.api :as aws] [matcher-combinators.standalone :as standalone] [mockfn.macros :refer [providing]] [vessel.jib.credentials :as credentials]) (:import [com.google.cloud.tools.jib.api Credential CredentialRetriever ImageReference] com.google.cloud.tools.jib.registry.credentials.CredentialRetrievalException java.util.Optional)) (deftest get-ecr-credential-test (providing [(aws/client (standalone/match? {:api :ecr :region "us-east-1"})) 'client] (testing "returns username and password to access the ECR registry that the image in question is associated to" (providing [(aws/invoke 'client {:op :GetAuthorizationToken :request {:registryIds ["591385309914"]}}) {:authorizationData [{:authorizationToken "QVdTOnBhc3N3b3Jk"}]}] (is (= {:username "AWS" :password "password"} (credentials/get-ecr-credential (ImageReference/parse "591385309914.dkr.ecr.us-east-1.amazonaws.com/application:v1.0.1")))))) (testing "throws a CredentialRetrievalException when the authentication on ECR fails" (providing [(aws/invoke 'client {:op :GetAuthorizationToken :request {:registryIds ["591385309914"]}}) {:cognitect.anomalies/category :cognitect.anomalies/incorrect}] (is (thrown? CredentialRetrievalException (credentials/get-ecr-credential (ImageReference/parse "591385309914.dkr.ecr.us-east-1.amazonaws.com/application:v1.0.1")))))))) (deftest ecr-credential-retriever-test (testing "returns the credential to access Amazon ECR" (let [image (ImageReference/parse "591385309914.dkr.ecr.us-east-1.amazonaws.com/application:v1.0.1")] (providing [(credentials/get-ecr-credential image) {:username "AWS" :password "password"}] (let [retriever (credentials/ecr-credential-retriever image) credential (.. retriever retrieve get)] (is (= "AWS" (.getUsername credential))) (is (= "password" (.getPassword credential))))))) (testing "returns Optional/empty when the image isn't associated to an ECR registry" (let [image (ImageReference/parse "docker.io/repo/application:v1.0.1")] (let [retriever (credentials/ecr-credential-retriever image)] (is (false? (.. retriever retrieve isPresent))))))) (defn make-retriever ([] (fn [_] (reify CredentialRetriever (retrieve [this] (Optional/empty))))) ([username password] (fn [_] (reify CredentialRetriever (retrieve [this] (Optional/of (Credential/from username password))))))) (deftest retriever-chain-test (testing "returns the first non-empty credential retrieved by the supplied retrievers" (let [get-credentials (fn [credentials] [(.getUsername credentials) (.getPassword credentials)])] (are [retrievers username password] (= [username password] (get-credentials (.. (credentials/retriever-chain (ImageReference/parse "repo/application:v1.0.1") retrievers) retrieve get))) [(make-retriever "john.doe" "abc123")] "john.doe" "abc123" [(make-retriever "john.doe" "abc123") (make-retriever "jd" "def456")] "john.doe" "abc123" [(make-retriever "jd" "def456") (make-retriever "john.doe" "abc123")] "jd" "def456" [(make-retriever) (make-retriever "john.doe" "abc123")] "john.doe" "abc123" [(make-retriever "john.doe" "abc123") (make-retriever)] "john.doe" "abc123"))) (testing "returns Optional/empty when all retrievers return empty credentials" (is (= (Optional/empty) (.. (credentials/retriever-chain (ImageReference/parse "repo/application:v1.0.1") [(make-retriever) (make-retriever)]) retrieve)))))
62182
(ns vessel.jib.credentials-test (:require [clojure.test :refer :all] [cognitect.aws.client.api :as aws] [matcher-combinators.standalone :as standalone] [mockfn.macros :refer [providing]] [vessel.jib.credentials :as credentials]) (:import [com.google.cloud.tools.jib.api Credential CredentialRetriever ImageReference] com.google.cloud.tools.jib.registry.credentials.CredentialRetrievalException java.util.Optional)) (deftest get-ecr-credential-test (providing [(aws/client (standalone/match? {:api :ecr :region "us-east-1"})) 'client] (testing "returns username and password to access the ECR registry that the image in question is associated to" (providing [(aws/invoke 'client {:op :GetAuthorizationToken :request {:registryIds ["591385309914"]}}) {:authorizationData [{:authorizationToken "<PASSWORD>"}]}] (is (= {:username "AWS" :password "<PASSWORD>"} (credentials/get-ecr-credential (ImageReference/parse "591385309914.dkr.ecr.us-east-1.amazonaws.com/application:v1.0.1")))))) (testing "throws a CredentialRetrievalException when the authentication on ECR fails" (providing [(aws/invoke 'client {:op :GetAuthorizationToken :request {:registryIds ["591385309914"]}}) {:cognitect.anomalies/category :cognitect.anomalies/incorrect}] (is (thrown? CredentialRetrievalException (credentials/get-ecr-credential (ImageReference/parse "591385309914.dkr.ecr.us-east-1.amazonaws.com/application:v1.0.1")))))))) (deftest ecr-credential-retriever-test (testing "returns the credential to access Amazon ECR" (let [image (ImageReference/parse "591385309914.dkr.ecr.us-east-1.amazonaws.com/application:v1.0.1")] (providing [(credentials/get-ecr-credential image) {:username "AWS" :password "<PASSWORD>"}] (let [retriever (credentials/ecr-credential-retriever image) credential (.. retriever retrieve get)] (is (= "AWS" (.getUsername credential))) (is (= "password" (.getPassword credential))))))) (testing "returns Optional/empty when the image isn't associated to an ECR registry" (let [image (ImageReference/parse "docker.io/repo/application:v1.0.1")] (let [retriever (credentials/ecr-credential-retriever image)] (is (false? (.. retriever retrieve isPresent))))))) (defn make-retriever ([] (fn [_] (reify CredentialRetriever (retrieve [this] (Optional/empty))))) ([username password] (fn [_] (reify CredentialRetriever (retrieve [this] (Optional/of (Credential/from username password))))))) (deftest retriever-chain-test (testing "returns the first non-empty credential retrieved by the supplied retrievers" (let [get-credentials (fn [credentials] [(.getUsername credentials) (.getPassword credentials)])] (are [retrievers username password] (= [username password] (get-credentials (.. (credentials/retriever-chain (ImageReference/parse "repo/application:v1.0.1") retrievers) retrieve get))) [(make-retriever "john.doe" "abc123")] "john.doe" "abc123" [(make-retriever "john.doe" "abc123") (make-retriever "jd" "def456")] "john.doe" "abc123" [(make-retriever "jd" "def456") (make-retriever "john.doe" "abc123")] "jd" "def456" [(make-retriever) (make-retriever "john.doe" "abc123")] "john.doe" "abc123" [(make-retriever "john.doe" "<PASSWORD>") (make-retriever)] "john.doe" "<PASSWORD>"))) (testing "returns Optional/empty when all retrievers return empty credentials" (is (= (Optional/empty) (.. (credentials/retriever-chain (ImageReference/parse "repo/application:v1.0.1") [(make-retriever) (make-retriever)]) retrieve)))))
true
(ns vessel.jib.credentials-test (:require [clojure.test :refer :all] [cognitect.aws.client.api :as aws] [matcher-combinators.standalone :as standalone] [mockfn.macros :refer [providing]] [vessel.jib.credentials :as credentials]) (:import [com.google.cloud.tools.jib.api Credential CredentialRetriever ImageReference] com.google.cloud.tools.jib.registry.credentials.CredentialRetrievalException java.util.Optional)) (deftest get-ecr-credential-test (providing [(aws/client (standalone/match? {:api :ecr :region "us-east-1"})) 'client] (testing "returns username and password to access the ECR registry that the image in question is associated to" (providing [(aws/invoke 'client {:op :GetAuthorizationToken :request {:registryIds ["591385309914"]}}) {:authorizationData [{:authorizationToken "PI:PASSWORD:<PASSWORD>END_PI"}]}] (is (= {:username "AWS" :password "PI:PASSWORD:<PASSWORD>END_PI"} (credentials/get-ecr-credential (ImageReference/parse "591385309914.dkr.ecr.us-east-1.amazonaws.com/application:v1.0.1")))))) (testing "throws a CredentialRetrievalException when the authentication on ECR fails" (providing [(aws/invoke 'client {:op :GetAuthorizationToken :request {:registryIds ["591385309914"]}}) {:cognitect.anomalies/category :cognitect.anomalies/incorrect}] (is (thrown? CredentialRetrievalException (credentials/get-ecr-credential (ImageReference/parse "591385309914.dkr.ecr.us-east-1.amazonaws.com/application:v1.0.1")))))))) (deftest ecr-credential-retriever-test (testing "returns the credential to access Amazon ECR" (let [image (ImageReference/parse "591385309914.dkr.ecr.us-east-1.amazonaws.com/application:v1.0.1")] (providing [(credentials/get-ecr-credential image) {:username "AWS" :password "PI:PASSWORD:<PASSWORD>END_PI"}] (let [retriever (credentials/ecr-credential-retriever image) credential (.. retriever retrieve get)] (is (= "AWS" (.getUsername credential))) (is (= "password" (.getPassword credential))))))) (testing "returns Optional/empty when the image isn't associated to an ECR registry" (let [image (ImageReference/parse "docker.io/repo/application:v1.0.1")] (let [retriever (credentials/ecr-credential-retriever image)] (is (false? (.. retriever retrieve isPresent))))))) (defn make-retriever ([] (fn [_] (reify CredentialRetriever (retrieve [this] (Optional/empty))))) ([username password] (fn [_] (reify CredentialRetriever (retrieve [this] (Optional/of (Credential/from username password))))))) (deftest retriever-chain-test (testing "returns the first non-empty credential retrieved by the supplied retrievers" (let [get-credentials (fn [credentials] [(.getUsername credentials) (.getPassword credentials)])] (are [retrievers username password] (= [username password] (get-credentials (.. (credentials/retriever-chain (ImageReference/parse "repo/application:v1.0.1") retrievers) retrieve get))) [(make-retriever "john.doe" "abc123")] "john.doe" "abc123" [(make-retriever "john.doe" "abc123") (make-retriever "jd" "def456")] "john.doe" "abc123" [(make-retriever "jd" "def456") (make-retriever "john.doe" "abc123")] "jd" "def456" [(make-retriever) (make-retriever "john.doe" "abc123")] "john.doe" "abc123" [(make-retriever "john.doe" "PI:PASSWORD:<PASSWORD>END_PI") (make-retriever)] "john.doe" "PI:PASSWORD:<PASSWORD>END_PI"))) (testing "returns Optional/empty when all retrievers return empty credentials" (is (= (Optional/empty) (.. (credentials/retriever-chain (ImageReference/parse "repo/application:v1.0.1") [(make-retriever) (make-retriever)]) retrieve)))))
[ { "context": " :meta {:abc \"123\" :email \"test@example.com\"}\n :synonyms [\"abc\" \"XXXX\"]\n ", "end": 1040, "score": 0.9999229311943054, "start": 1024, "tag": "EMAIL", "value": "test@example.com" }, { "context": " \"test-id\"\n :meta {:email \"bobby@example.com\"}\n :synonyms [\"def\"]\n ", "end": 1285, "score": 0.999920666217804, "start": 1268, "tag": "EMAIL", "value": "bobby@example.com" }, { "context": "? true\n :meta {:email \"test@example.com\"}}\n {:text \"test text\"\n ", "end": 1657, "score": 0.9999247789382935, "start": 1641, "tag": "EMAIL", "value": "test@example.com" }, { "context": "? true\n :meta {:email \"bobby@example.com\"}}\n {:text \"test text\"\n ", "end": 1907, "score": 0.9999226927757263, "start": 1890, "tag": "EMAIL", "value": "bobby@example.com" }, { "context": "? true\n :meta {:email \"test@example.com\" :abc \"123\"}}]))))\n\n(deftest dictionary-optimizat", "end": 2157, "score": 0.9999248385429382, "start": 2141, "tag": "EMAIL", "value": "test@example.com" } ]
test/beagle/dictionary_optimization_test.clj
tokenmill/beagle
46
(ns beagle.dictionary-optimization-test (:require [clojure.test :refer [deftest is]] [beagle.dictionary-optimizer :as optimizer] [beagle.phrases :as phrases])) (deftest meta-merge-test (is (optimizer/mergeable-meta? nil {:meta {:email "123"}})) (is (optimizer/mergeable-meta? {:meta {}} {:meta {:email "123"}})) (is (optimizer/mergeable-meta? {:meta {:email "123"}} nil)) (is (optimizer/mergeable-meta? {:meta {:email "123"}} {:meta {:email "123"}})) (is (optimizer/mergeable-meta? {:meta {:email "123"}} {:meta {:email "123" :total 5646}})) (is (optimizer/mergeable-meta? {:meta {:email "123" :total 5646}} {:meta {:email "123"}})) (is (not (optimizer/mergeable-meta? {:meta {:email "123"}} {:meta {:email "321"}}))) (is (not (optimizer/mergeable-meta? {:meta {:email "123" :total 5646}} {:meta {:email "123" :total 9999}}))) (is (= [{:ascii-fold? true :case-sensitive? true :id "test-id" :meta {:abc "123" :email "test@example.com"} :synonyms ["abc" "XXXX"] :text "test text"} {:ascii-fold? true :case-sensitive? true :id "test-id" :meta {:email "bobby@example.com"} :synonyms ["def"] :text "test text"}] (optimizer/aggregate-entries-by-meta [{:text "test text" :id "test-id" :synonyms ["abc"] :case-sensitive? true :ascii-fold? true :meta {:email "test@example.com"}} {:text "test text" :id "test-id" :synonyms ["def"] :case-sensitive? true :ascii-fold? true :meta {:email "bobby@example.com"}} {:text "test text" :id "test-id" :synonyms ["XXXX"] :case-sensitive? true :ascii-fold? true :meta {:email "test@example.com" :abc "123"}}])))) (deftest dictionary-optimization-test (let [dictionary [{:case-sensitive? true :ascii-fold? true :synonyms ["AAAA1"] :text "AAAA"} {:case-sensitive? true :ascii-fold? true :synonyms ["AAAA2"] :text "AAAA"} {:case-sensitive? false :ascii-fold? true :synonyms ["AAAA3"] :text "AAAA"} {:case-sensitive? true :ascii-fold? true :synonyms ["AAAA4"] :text "AAAA"} {:case-sensitive? true :ascii-fold? false :synonyms ["AAAA5"] :text "AAAA"} {:case-sensitive? true :ascii-fold? false :synonyms ["AAAA"] :text "AAAA"} {:case-sensitive? false :synonyms ["BBBB1"] :text "BBBB"} {:case-sensitive? false :synonyms ["BBBB"] :text "BBBB"}] expected-dictionary [{:text "AAAA" :synonyms ["AAAA4" "AAAA2" "AAAA1"] :case-sensitive? true :ascii-fold? true} {:case-sensitive? false :ascii-fold? true :synonyms ["AAAA3"] :text "AAAA"} {:text "AAAA" :synonyms ["AAAA5"] :case-sensitive? true :ascii-fold? false} {:text "BBBB" :synonyms ["BBBB1"] :case-sensitive? false}] optimized-dictionary (optimizer/optimize dictionary)] (is (< (count optimized-dictionary) (count dictionary))) (is (= (count expected-dictionary) (count optimized-dictionary))) (is (= (set (map #(update % :synonyms set) expected-dictionary)) (set (map #(update % :synonyms set) optimized-dictionary)))))) (deftest synonym-optimization (let [dictionary [{:text "test" :id "1" :synonyms ["beagle" "luwak1"]}] monitor-queries (phrases/dict-entries->monitor-queries dictionary {:tokenizer :standard})] (is (= 3 (count monitor-queries))) (let [highlighter-fn (phrases/highlighter dictionary {:type-name "TEST"}) anns (highlighter-fn "this is a beagle text test luwak1")] (is (= 3 (count anns))))))
116531
(ns beagle.dictionary-optimization-test (:require [clojure.test :refer [deftest is]] [beagle.dictionary-optimizer :as optimizer] [beagle.phrases :as phrases])) (deftest meta-merge-test (is (optimizer/mergeable-meta? nil {:meta {:email "123"}})) (is (optimizer/mergeable-meta? {:meta {}} {:meta {:email "123"}})) (is (optimizer/mergeable-meta? {:meta {:email "123"}} nil)) (is (optimizer/mergeable-meta? {:meta {:email "123"}} {:meta {:email "123"}})) (is (optimizer/mergeable-meta? {:meta {:email "123"}} {:meta {:email "123" :total 5646}})) (is (optimizer/mergeable-meta? {:meta {:email "123" :total 5646}} {:meta {:email "123"}})) (is (not (optimizer/mergeable-meta? {:meta {:email "123"}} {:meta {:email "321"}}))) (is (not (optimizer/mergeable-meta? {:meta {:email "123" :total 5646}} {:meta {:email "123" :total 9999}}))) (is (= [{:ascii-fold? true :case-sensitive? true :id "test-id" :meta {:abc "123" :email "<EMAIL>"} :synonyms ["abc" "XXXX"] :text "test text"} {:ascii-fold? true :case-sensitive? true :id "test-id" :meta {:email "<EMAIL>"} :synonyms ["def"] :text "test text"}] (optimizer/aggregate-entries-by-meta [{:text "test text" :id "test-id" :synonyms ["abc"] :case-sensitive? true :ascii-fold? true :meta {:email "<EMAIL>"}} {:text "test text" :id "test-id" :synonyms ["def"] :case-sensitive? true :ascii-fold? true :meta {:email "<EMAIL>"}} {:text "test text" :id "test-id" :synonyms ["XXXX"] :case-sensitive? true :ascii-fold? true :meta {:email "<EMAIL>" :abc "123"}}])))) (deftest dictionary-optimization-test (let [dictionary [{:case-sensitive? true :ascii-fold? true :synonyms ["AAAA1"] :text "AAAA"} {:case-sensitive? true :ascii-fold? true :synonyms ["AAAA2"] :text "AAAA"} {:case-sensitive? false :ascii-fold? true :synonyms ["AAAA3"] :text "AAAA"} {:case-sensitive? true :ascii-fold? true :synonyms ["AAAA4"] :text "AAAA"} {:case-sensitive? true :ascii-fold? false :synonyms ["AAAA5"] :text "AAAA"} {:case-sensitive? true :ascii-fold? false :synonyms ["AAAA"] :text "AAAA"} {:case-sensitive? false :synonyms ["BBBB1"] :text "BBBB"} {:case-sensitive? false :synonyms ["BBBB"] :text "BBBB"}] expected-dictionary [{:text "AAAA" :synonyms ["AAAA4" "AAAA2" "AAAA1"] :case-sensitive? true :ascii-fold? true} {:case-sensitive? false :ascii-fold? true :synonyms ["AAAA3"] :text "AAAA"} {:text "AAAA" :synonyms ["AAAA5"] :case-sensitive? true :ascii-fold? false} {:text "BBBB" :synonyms ["BBBB1"] :case-sensitive? false}] optimized-dictionary (optimizer/optimize dictionary)] (is (< (count optimized-dictionary) (count dictionary))) (is (= (count expected-dictionary) (count optimized-dictionary))) (is (= (set (map #(update % :synonyms set) expected-dictionary)) (set (map #(update % :synonyms set) optimized-dictionary)))))) (deftest synonym-optimization (let [dictionary [{:text "test" :id "1" :synonyms ["beagle" "luwak1"]}] monitor-queries (phrases/dict-entries->monitor-queries dictionary {:tokenizer :standard})] (is (= 3 (count monitor-queries))) (let [highlighter-fn (phrases/highlighter dictionary {:type-name "TEST"}) anns (highlighter-fn "this is a beagle text test luwak1")] (is (= 3 (count anns))))))
true
(ns beagle.dictionary-optimization-test (:require [clojure.test :refer [deftest is]] [beagle.dictionary-optimizer :as optimizer] [beagle.phrases :as phrases])) (deftest meta-merge-test (is (optimizer/mergeable-meta? nil {:meta {:email "123"}})) (is (optimizer/mergeable-meta? {:meta {}} {:meta {:email "123"}})) (is (optimizer/mergeable-meta? {:meta {:email "123"}} nil)) (is (optimizer/mergeable-meta? {:meta {:email "123"}} {:meta {:email "123"}})) (is (optimizer/mergeable-meta? {:meta {:email "123"}} {:meta {:email "123" :total 5646}})) (is (optimizer/mergeable-meta? {:meta {:email "123" :total 5646}} {:meta {:email "123"}})) (is (not (optimizer/mergeable-meta? {:meta {:email "123"}} {:meta {:email "321"}}))) (is (not (optimizer/mergeable-meta? {:meta {:email "123" :total 5646}} {:meta {:email "123" :total 9999}}))) (is (= [{:ascii-fold? true :case-sensitive? true :id "test-id" :meta {:abc "123" :email "PI:EMAIL:<EMAIL>END_PI"} :synonyms ["abc" "XXXX"] :text "test text"} {:ascii-fold? true :case-sensitive? true :id "test-id" :meta {:email "PI:EMAIL:<EMAIL>END_PI"} :synonyms ["def"] :text "test text"}] (optimizer/aggregate-entries-by-meta [{:text "test text" :id "test-id" :synonyms ["abc"] :case-sensitive? true :ascii-fold? true :meta {:email "PI:EMAIL:<EMAIL>END_PI"}} {:text "test text" :id "test-id" :synonyms ["def"] :case-sensitive? true :ascii-fold? true :meta {:email "PI:EMAIL:<EMAIL>END_PI"}} {:text "test text" :id "test-id" :synonyms ["XXXX"] :case-sensitive? true :ascii-fold? true :meta {:email "PI:EMAIL:<EMAIL>END_PI" :abc "123"}}])))) (deftest dictionary-optimization-test (let [dictionary [{:case-sensitive? true :ascii-fold? true :synonyms ["AAAA1"] :text "AAAA"} {:case-sensitive? true :ascii-fold? true :synonyms ["AAAA2"] :text "AAAA"} {:case-sensitive? false :ascii-fold? true :synonyms ["AAAA3"] :text "AAAA"} {:case-sensitive? true :ascii-fold? true :synonyms ["AAAA4"] :text "AAAA"} {:case-sensitive? true :ascii-fold? false :synonyms ["AAAA5"] :text "AAAA"} {:case-sensitive? true :ascii-fold? false :synonyms ["AAAA"] :text "AAAA"} {:case-sensitive? false :synonyms ["BBBB1"] :text "BBBB"} {:case-sensitive? false :synonyms ["BBBB"] :text "BBBB"}] expected-dictionary [{:text "AAAA" :synonyms ["AAAA4" "AAAA2" "AAAA1"] :case-sensitive? true :ascii-fold? true} {:case-sensitive? false :ascii-fold? true :synonyms ["AAAA3"] :text "AAAA"} {:text "AAAA" :synonyms ["AAAA5"] :case-sensitive? true :ascii-fold? false} {:text "BBBB" :synonyms ["BBBB1"] :case-sensitive? false}] optimized-dictionary (optimizer/optimize dictionary)] (is (< (count optimized-dictionary) (count dictionary))) (is (= (count expected-dictionary) (count optimized-dictionary))) (is (= (set (map #(update % :synonyms set) expected-dictionary)) (set (map #(update % :synonyms set) optimized-dictionary)))))) (deftest synonym-optimization (let [dictionary [{:text "test" :id "1" :synonyms ["beagle" "luwak1"]}] monitor-queries (phrases/dict-entries->monitor-queries dictionary {:tokenizer :standard})] (is (= 3 (count monitor-queries))) (let [highlighter-fn (phrases/highlighter dictionary {:type-name "TEST"}) anns (highlighter-fn "this is a beagle text test luwak1")] (is (= 3 (count anns))))))
[ { "context": ";; Copyright 2015 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache Li", "end": 31, "score": 0.9998849034309387, "start": 18, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright 2015 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache License, Version", "end": 45, "score": 0.999932587146759, "start": 33, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
test/buddy/core/padding_tests.clj
shilder/buddy-core
121
;; Copyright 2015 Andrey Antukh <niwi@niwi.nz> ;; ;; Licensed under the Apache License, Version 2.0 (the "License") ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns buddy.core.padding-tests (:require [clojure.test :refer :all] [buddy.core.codecs :as codecs] [buddy.core.bytes :as bytes] [buddy.core.padding :as padding])) (deftest pkcs7-padding (let [data (byte-array 10)] (bytes/fill! data 2) (padding/pad! data 6) (is (padding/padded? data)) (is (= (padding/count data) 4)) (let [result (padding/unpad data :pkcs7)] (is (bytes/equals? result (bytes/slice data 0 6)))))) (deftest tbc-padding (let [data (byte-array 10)] (bytes/fill! data 2) (padding/pad! data 6 :tbc) (is (padding/padded? data :tbc)) (is (= (padding/count data :tbc) 4)) (let [result (padding/unpad data :tbc)] (is (bytes/equals? result (bytes/slice data 0 6)))))) (deftest zerobyte-padding (let [data (byte-array 10)] (bytes/fill! data 2) (padding/pad! data 6 :zerobyte) (is (padding/padded? data :zerobyte)) (is (= (padding/count data :zerobyte) 4)) (let [result (padding/unpad data :zerobyte)] (is (bytes/equals? result (bytes/slice data 0 6))))))
59869
;; Copyright 2015 <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 buddy.core.padding-tests (:require [clojure.test :refer :all] [buddy.core.codecs :as codecs] [buddy.core.bytes :as bytes] [buddy.core.padding :as padding])) (deftest pkcs7-padding (let [data (byte-array 10)] (bytes/fill! data 2) (padding/pad! data 6) (is (padding/padded? data)) (is (= (padding/count data) 4)) (let [result (padding/unpad data :pkcs7)] (is (bytes/equals? result (bytes/slice data 0 6)))))) (deftest tbc-padding (let [data (byte-array 10)] (bytes/fill! data 2) (padding/pad! data 6 :tbc) (is (padding/padded? data :tbc)) (is (= (padding/count data :tbc) 4)) (let [result (padding/unpad data :tbc)] (is (bytes/equals? result (bytes/slice data 0 6)))))) (deftest zerobyte-padding (let [data (byte-array 10)] (bytes/fill! data 2) (padding/pad! data 6 :zerobyte) (is (padding/padded? data :zerobyte)) (is (= (padding/count data :zerobyte) 4)) (let [result (padding/unpad data :zerobyte)] (is (bytes/equals? result (bytes/slice data 0 6))))))
true
;; Copyright 2015 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 buddy.core.padding-tests (:require [clojure.test :refer :all] [buddy.core.codecs :as codecs] [buddy.core.bytes :as bytes] [buddy.core.padding :as padding])) (deftest pkcs7-padding (let [data (byte-array 10)] (bytes/fill! data 2) (padding/pad! data 6) (is (padding/padded? data)) (is (= (padding/count data) 4)) (let [result (padding/unpad data :pkcs7)] (is (bytes/equals? result (bytes/slice data 0 6)))))) (deftest tbc-padding (let [data (byte-array 10)] (bytes/fill! data 2) (padding/pad! data 6 :tbc) (is (padding/padded? data :tbc)) (is (= (padding/count data :tbc) 4)) (let [result (padding/unpad data :tbc)] (is (bytes/equals? result (bytes/slice data 0 6)))))) (deftest zerobyte-padding (let [data (byte-array 10)] (bytes/fill! data 2) (padding/pad! data 6 :zerobyte) (is (padding/padded? data :zerobyte)) (is (= (padding/count data :zerobyte) 4)) (let [result (padding/unpad data :zerobyte)] (is (bytes/equals? result (bytes/slice data 0 6))))))
[ { "context": "sing with ImageJ/FIJI\"\n :url \"https://github.com/funimagej/fun.imagel\"\n :license {:name \"Apache v2.0\"\n ", "end": 149, "score": 0.997048556804657, "start": 140, "tag": "USERNAME", "value": "funimagej" }, { "context": "Apache v2.0\"\n :url \"https://github.com/funimagej/fun.imagej/LICENSE\"}\n :pom-addition ([:developer", "end": 240, "score": 0.9972736239433289, "start": 231, "tag": "USERNAME", "value": "funimagej" }, { "context": " [:developer\n [:id \"kephale\"]\n [:name \"Kyle Har", "end": 348, "score": 0.9990772604942322, "start": 341, "tag": "USERNAME", "value": "kephale" }, { "context": "\"kephale\"]\n [:name \"Kyle Harrington\"]\n [:roles [:role \"", "end": 405, "score": 0.9998824000358582, "start": 390, "tag": "NAME", "value": "Kyle Harrington" }, { "context": "tributor\n [:name \"Curtis Rueden\"]\n [:properties [", "end": 820, "score": 0.9998829960823059, "start": 807, "tag": "NAME", "value": "Curtis Rueden" }, { "context": "E\n :password :env/CI_DEPLOY_PASSWORD\n :sign-releas", "end": 4440, "score": 0.7001486420631409, "start": 4418, "tag": "PASSWORD", "value": "env/CI_DEPLOY_PASSWORD" } ]
project.clj
funimagej/fun.imagej
1
(defproject fun.imagej/fun.imagej "0.4.2-SNAPSHOT" :description "Functional Image Processing with ImageJ/FIJI" :url "https://github.com/funimagej/fun.imagel" :license {:name "Apache v2.0" :url "https://github.com/funimagej/fun.imagej/LICENSE"} :pom-addition ([:developers [:developer [:id "kephale"] [:name "Kyle Harrington"] [:roles [:role "founder"] [:role "lead"] [:role "debugger"] [:role "reviewer"] [:role "support"] [:role "maintainer"]]]] [:contributors [:contributor [:name "Curtis Rueden"] [:properties [:id "ctrueden"]]]]) :dependencies [[org.clojure/clojure "1.10.1"] [seesaw "1.4.4"] [clj-random "0.1.8"] [com.kephale/random-forests-clj "8278de0"] ; Java libs ;[net.imglib2/imglib2 "b33186a" :exclusions [com.github.jnr/jffi]] [net.imglib2/imglib2 "5.12.0" :exclusions [com.github.jnr/jffi]] [net.imglib2/imglib2-algorithm "0.11.2"] [net.imglib2/imglib2-ij "2.0.0-beta-46"] [net.imglib2/imglib2-cache "1.0.0-beta-16"] [net.imglib2/imglib2-roi "0.11.0"] [net.imagej/imagej "2.2.0" :exclusions [com.github.jnr/jffi com.github.jnr/jnr-x86asm org.scijava/scripting-renjin]] [net.imagej/imagej-legacy "0.37.4"] [org.json/json "20201115"] [ome/formats-bsd "6.6.1"] [ome/formats-gpl "6.6.1"] [ome/formats-api "6.6.1"] [ome/bio-formats_plugins "6.6.1"] [org.joml/joml "1.9.25"] [graphics.scenery/scenery "96e8a96"] [sc.iview/sciview "31b4e6d" :exclusions [com.github.jnr/jffi com.github.jnr/jnr-x86asm ch.qos.logback/logback-classic org.scijava/scripting-renjin]] [net.imagej/imagej-ops "0.45.5" :exclusions [org.joml/joml]] [net.imagej/imagej-mesh "0.8.0"] [net.imagej/imagej-mesh-io "0.1.2"] ;[com.github.saalfeldlab/n5 "a3f0406"] ;[com.github.saalfeldlab/n5-ij "a5517c8"] ;[com.github.saalfeldlab/n5-imglib2 "2a211a3"] [org.janelia.saalfeldlab/n5 "2.5.0"] ;[com.github.saalfeldlab/n5-ij ""] ;[org.org.janelia.saalfeldlab/n5-ij "0.0.2-SNAPSHOT"] [org.janelia.saalfeldlab/n5-imglib2 "4.0.0"] [org.ojalgo/ojalgo "48.1.0"] [sc.fiji/Auto_Threshold "1.17.1"] [org.scijava/scijava-common "2.85.0"] [ch.qos.logback/logback-classic "1.2.3"] [org.morphonets/SNT "2b3b50c"]] :resource-paths ["src/main/resource"] :java-source-paths ["java"] :repositories [["scijava.public" "https://maven.scijava.org/content/groups/public"] ["jitpack.io" "https://jitpack.io"] ["saalfeld-lab-maven-repo" "https://saalfeldlab.github.io/maven"]] :deploy-repositories [["releases" {:url "https://maven.imagej.net/content/repositories/releases" ;; Select a GPG private key to use for ;; signing. (See "How to specify a user ;; ID" in GPG's manual.) GPG will ;; otherwise pick the first private key ;; it finds in your keyring. ;; Currently only works in :deploy-repositories ;; or as a top-level (global) setting. :username :env/CI_DEPLOY_USERNAME :password :env/CI_DEPLOY_PASSWORD :sign-releases false}] ["snapshots" {:url "https://maven.imagej.net/content/repositories/snapshots" :username :env/CI_DEPLOY_USERNAME :password :env/CI_DEPLOY_PASSWORD :sign-releases false}]] ; Try to use lein parent when we can :plugins [[lein-exec "0.3.7"]] :jvm-opts ["-Xmx32g" "-server" "-Dscenery.Renderer=OpenGLRenderer" ;"-javaagent:/Users/kyle/.m2/repository/net/imagej/ij1-patcher/0.12.3/ij1-patcher-0.12.3.jar=init" #_"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=localhost:8000"])
63729
(defproject fun.imagej/fun.imagej "0.4.2-SNAPSHOT" :description "Functional Image Processing with ImageJ/FIJI" :url "https://github.com/funimagej/fun.imagel" :license {:name "Apache v2.0" :url "https://github.com/funimagej/fun.imagej/LICENSE"} :pom-addition ([:developers [:developer [:id "kephale"] [:name "<NAME>"] [:roles [:role "founder"] [:role "lead"] [:role "debugger"] [:role "reviewer"] [:role "support"] [:role "maintainer"]]]] [:contributors [:contributor [:name "<NAME>"] [:properties [:id "ctrueden"]]]]) :dependencies [[org.clojure/clojure "1.10.1"] [seesaw "1.4.4"] [clj-random "0.1.8"] [com.kephale/random-forests-clj "8278de0"] ; Java libs ;[net.imglib2/imglib2 "b33186a" :exclusions [com.github.jnr/jffi]] [net.imglib2/imglib2 "5.12.0" :exclusions [com.github.jnr/jffi]] [net.imglib2/imglib2-algorithm "0.11.2"] [net.imglib2/imglib2-ij "2.0.0-beta-46"] [net.imglib2/imglib2-cache "1.0.0-beta-16"] [net.imglib2/imglib2-roi "0.11.0"] [net.imagej/imagej "2.2.0" :exclusions [com.github.jnr/jffi com.github.jnr/jnr-x86asm org.scijava/scripting-renjin]] [net.imagej/imagej-legacy "0.37.4"] [org.json/json "20201115"] [ome/formats-bsd "6.6.1"] [ome/formats-gpl "6.6.1"] [ome/formats-api "6.6.1"] [ome/bio-formats_plugins "6.6.1"] [org.joml/joml "1.9.25"] [graphics.scenery/scenery "96e8a96"] [sc.iview/sciview "31b4e6d" :exclusions [com.github.jnr/jffi com.github.jnr/jnr-x86asm ch.qos.logback/logback-classic org.scijava/scripting-renjin]] [net.imagej/imagej-ops "0.45.5" :exclusions [org.joml/joml]] [net.imagej/imagej-mesh "0.8.0"] [net.imagej/imagej-mesh-io "0.1.2"] ;[com.github.saalfeldlab/n5 "a3f0406"] ;[com.github.saalfeldlab/n5-ij "a5517c8"] ;[com.github.saalfeldlab/n5-imglib2 "2a211a3"] [org.janelia.saalfeldlab/n5 "2.5.0"] ;[com.github.saalfeldlab/n5-ij ""] ;[org.org.janelia.saalfeldlab/n5-ij "0.0.2-SNAPSHOT"] [org.janelia.saalfeldlab/n5-imglib2 "4.0.0"] [org.ojalgo/ojalgo "48.1.0"] [sc.fiji/Auto_Threshold "1.17.1"] [org.scijava/scijava-common "2.85.0"] [ch.qos.logback/logback-classic "1.2.3"] [org.morphonets/SNT "2b3b50c"]] :resource-paths ["src/main/resource"] :java-source-paths ["java"] :repositories [["scijava.public" "https://maven.scijava.org/content/groups/public"] ["jitpack.io" "https://jitpack.io"] ["saalfeld-lab-maven-repo" "https://saalfeldlab.github.io/maven"]] :deploy-repositories [["releases" {:url "https://maven.imagej.net/content/repositories/releases" ;; Select a GPG private key to use for ;; signing. (See "How to specify a user ;; ID" in GPG's manual.) GPG will ;; otherwise pick the first private key ;; it finds in your keyring. ;; Currently only works in :deploy-repositories ;; or as a top-level (global) setting. :username :env/CI_DEPLOY_USERNAME :password :<PASSWORD> :sign-releases false}] ["snapshots" {:url "https://maven.imagej.net/content/repositories/snapshots" :username :env/CI_DEPLOY_USERNAME :password :env/CI_DEPLOY_PASSWORD :sign-releases false}]] ; Try to use lein parent when we can :plugins [[lein-exec "0.3.7"]] :jvm-opts ["-Xmx32g" "-server" "-Dscenery.Renderer=OpenGLRenderer" ;"-javaagent:/Users/kyle/.m2/repository/net/imagej/ij1-patcher/0.12.3/ij1-patcher-0.12.3.jar=init" #_"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=localhost:8000"])
true
(defproject fun.imagej/fun.imagej "0.4.2-SNAPSHOT" :description "Functional Image Processing with ImageJ/FIJI" :url "https://github.com/funimagej/fun.imagel" :license {:name "Apache v2.0" :url "https://github.com/funimagej/fun.imagej/LICENSE"} :pom-addition ([:developers [:developer [:id "kephale"] [:name "PI:NAME:<NAME>END_PI"] [:roles [:role "founder"] [:role "lead"] [:role "debugger"] [:role "reviewer"] [:role "support"] [:role "maintainer"]]]] [:contributors [:contributor [:name "PI:NAME:<NAME>END_PI"] [:properties [:id "ctrueden"]]]]) :dependencies [[org.clojure/clojure "1.10.1"] [seesaw "1.4.4"] [clj-random "0.1.8"] [com.kephale/random-forests-clj "8278de0"] ; Java libs ;[net.imglib2/imglib2 "b33186a" :exclusions [com.github.jnr/jffi]] [net.imglib2/imglib2 "5.12.0" :exclusions [com.github.jnr/jffi]] [net.imglib2/imglib2-algorithm "0.11.2"] [net.imglib2/imglib2-ij "2.0.0-beta-46"] [net.imglib2/imglib2-cache "1.0.0-beta-16"] [net.imglib2/imglib2-roi "0.11.0"] [net.imagej/imagej "2.2.0" :exclusions [com.github.jnr/jffi com.github.jnr/jnr-x86asm org.scijava/scripting-renjin]] [net.imagej/imagej-legacy "0.37.4"] [org.json/json "20201115"] [ome/formats-bsd "6.6.1"] [ome/formats-gpl "6.6.1"] [ome/formats-api "6.6.1"] [ome/bio-formats_plugins "6.6.1"] [org.joml/joml "1.9.25"] [graphics.scenery/scenery "96e8a96"] [sc.iview/sciview "31b4e6d" :exclusions [com.github.jnr/jffi com.github.jnr/jnr-x86asm ch.qos.logback/logback-classic org.scijava/scripting-renjin]] [net.imagej/imagej-ops "0.45.5" :exclusions [org.joml/joml]] [net.imagej/imagej-mesh "0.8.0"] [net.imagej/imagej-mesh-io "0.1.2"] ;[com.github.saalfeldlab/n5 "a3f0406"] ;[com.github.saalfeldlab/n5-ij "a5517c8"] ;[com.github.saalfeldlab/n5-imglib2 "2a211a3"] [org.janelia.saalfeldlab/n5 "2.5.0"] ;[com.github.saalfeldlab/n5-ij ""] ;[org.org.janelia.saalfeldlab/n5-ij "0.0.2-SNAPSHOT"] [org.janelia.saalfeldlab/n5-imglib2 "4.0.0"] [org.ojalgo/ojalgo "48.1.0"] [sc.fiji/Auto_Threshold "1.17.1"] [org.scijava/scijava-common "2.85.0"] [ch.qos.logback/logback-classic "1.2.3"] [org.morphonets/SNT "2b3b50c"]] :resource-paths ["src/main/resource"] :java-source-paths ["java"] :repositories [["scijava.public" "https://maven.scijava.org/content/groups/public"] ["jitpack.io" "https://jitpack.io"] ["saalfeld-lab-maven-repo" "https://saalfeldlab.github.io/maven"]] :deploy-repositories [["releases" {:url "https://maven.imagej.net/content/repositories/releases" ;; Select a GPG private key to use for ;; signing. (See "How to specify a user ;; ID" in GPG's manual.) GPG will ;; otherwise pick the first private key ;; it finds in your keyring. ;; Currently only works in :deploy-repositories ;; or as a top-level (global) setting. :username :env/CI_DEPLOY_USERNAME :password :PI:PASSWORD:<PASSWORD>END_PI :sign-releases false}] ["snapshots" {:url "https://maven.imagej.net/content/repositories/snapshots" :username :env/CI_DEPLOY_USERNAME :password :env/CI_DEPLOY_PASSWORD :sign-releases false}]] ; Try to use lein parent when we can :plugins [[lein-exec "0.3.7"]] :jvm-opts ["-Xmx32g" "-server" "-Dscenery.Renderer=OpenGLRenderer" ;"-javaagent:/Users/kyle/.m2/repository/net/imagej/ij1-patcher/0.12.3/ij1-patcher-0.12.3.jar=init" #_"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=localhost:8000"])
[ { "context": "arameters, we can\"\n (let [id 1\n name \"My event\"\n description \"This is my event\"\n ", "end": 254, "score": 0.8238863945007324, "start": 246, "tag": "NAME", "value": "My event" }, { "context": "he creation fails\"\n (let [id 1\n name \"My event\"\n description \"This is my event\"\n ", "end": 734, "score": 0.8850939273834229, "start": 726, "tag": "NAME", "value": "My event" }, { "context": "rom a map, we can\"\n (let [id 1\n name \"My event\"\n description \"This is my event\"\n ", "end": 1442, "score": 0.8854104280471802, "start": 1434, "tag": "NAME", "value": "My event" }, { "context": "or 3\n data {:id 1\n :name \"My event\"\n :description \"This is my event\"\n", "end": 1591, "score": 0.7798133492469788, "start": 1583, "tag": "NAME", "value": "My event" } ]
test/baoqu/types/event_test.clj
baoqu/baoqu-core
2
(ns baoqu.types.event-test (:require [clojure.test :refer :all] [baoqu.types.event :as et])) (deftest event-creation (testing "That if we try to create an event with the correct parameters, we can" (let [id 1 name "My event" description "This is my event" circle-size 3 agreement-factor 3 event (et/event id name description circle-size agreement-factor)] (is (et/is-event? event)) (is (= (:id event) id)) (is (= (:name event) name)) (is (= (:circle-size event) circle-size)) (is (= (:agreement-factor event) agreement-factor)))) (testing "That if we use bad parameters, the creation fails" (let [id 1 name "My event" description "This is my event" circle-size 3 agreement-factor 3] (is (thrown? java.lang.AssertionError (et/event "one" name description circle-size agreement-factor))) (is (thrown? java.lang.AssertionError (et/event id {} description circle-size agreement-factor))) (is (thrown? java.lang.AssertionError (et/event id name 3 circle-size agreement-factor))) (is (thrown? java.lang.AssertionError (et/event id name description "three" agreement-factor))) (is (thrown? java.lang.AssertionError (et/event id name description circle-size []))))) (testing "That if we try to create an event from a map, we can" (let [id 1 name "My event" description "This is my event" circle-size 3 agreement-factor 3 data {:id 1 :name "My event" :description "This is my event" :circle-size 3 :agreement-factor 3} event (et/event data)] (is (et/is-event? event)) (is (= (:id event) id)) (is (= (:name event) name)) (is (= (:circle-size event) circle-size)) (is (= (:agreement-factor event) agreement-factor)))))
6499
(ns baoqu.types.event-test (:require [clojure.test :refer :all] [baoqu.types.event :as et])) (deftest event-creation (testing "That if we try to create an event with the correct parameters, we can" (let [id 1 name "<NAME>" description "This is my event" circle-size 3 agreement-factor 3 event (et/event id name description circle-size agreement-factor)] (is (et/is-event? event)) (is (= (:id event) id)) (is (= (:name event) name)) (is (= (:circle-size event) circle-size)) (is (= (:agreement-factor event) agreement-factor)))) (testing "That if we use bad parameters, the creation fails" (let [id 1 name "<NAME>" description "This is my event" circle-size 3 agreement-factor 3] (is (thrown? java.lang.AssertionError (et/event "one" name description circle-size agreement-factor))) (is (thrown? java.lang.AssertionError (et/event id {} description circle-size agreement-factor))) (is (thrown? java.lang.AssertionError (et/event id name 3 circle-size agreement-factor))) (is (thrown? java.lang.AssertionError (et/event id name description "three" agreement-factor))) (is (thrown? java.lang.AssertionError (et/event id name description circle-size []))))) (testing "That if we try to create an event from a map, we can" (let [id 1 name "<NAME>" description "This is my event" circle-size 3 agreement-factor 3 data {:id 1 :name "<NAME>" :description "This is my event" :circle-size 3 :agreement-factor 3} event (et/event data)] (is (et/is-event? event)) (is (= (:id event) id)) (is (= (:name event) name)) (is (= (:circle-size event) circle-size)) (is (= (:agreement-factor event) agreement-factor)))))
true
(ns baoqu.types.event-test (:require [clojure.test :refer :all] [baoqu.types.event :as et])) (deftest event-creation (testing "That if we try to create an event with the correct parameters, we can" (let [id 1 name "PI:NAME:<NAME>END_PI" description "This is my event" circle-size 3 agreement-factor 3 event (et/event id name description circle-size agreement-factor)] (is (et/is-event? event)) (is (= (:id event) id)) (is (= (:name event) name)) (is (= (:circle-size event) circle-size)) (is (= (:agreement-factor event) agreement-factor)))) (testing "That if we use bad parameters, the creation fails" (let [id 1 name "PI:NAME:<NAME>END_PI" description "This is my event" circle-size 3 agreement-factor 3] (is (thrown? java.lang.AssertionError (et/event "one" name description circle-size agreement-factor))) (is (thrown? java.lang.AssertionError (et/event id {} description circle-size agreement-factor))) (is (thrown? java.lang.AssertionError (et/event id name 3 circle-size agreement-factor))) (is (thrown? java.lang.AssertionError (et/event id name description "three" agreement-factor))) (is (thrown? java.lang.AssertionError (et/event id name description circle-size []))))) (testing "That if we try to create an event from a map, we can" (let [id 1 name "PI:NAME:<NAME>END_PI" description "This is my event" circle-size 3 agreement-factor 3 data {:id 1 :name "PI:NAME:<NAME>END_PI" :description "This is my event" :circle-size 3 :agreement-factor 3} event (et/event data)] (is (et/is-event? event)) (is (= (:id event) id)) (is (= (:name event) name)) (is (= (:circle-size event) circle-size)) (is (= (:agreement-factor event) agreement-factor)))))
[ { "context": "\" nil)\n(def ^:dynamic *username* \"Username\" \"root\")\n(def ^:dynamic *p", "end": 965, "score": 0.9979209303855896, "start": 957, "tag": "USERNAME", "value": "Username" }, { "context": "mic *username* \"Username\" \"root\")\n(def ^:dynamic *password* \"Password (for login ", "end": 995, "score": 0.9293684363365173, "start": 991, "tag": "USERNAME", "value": "root" }, { "context": "mic *password* \"Password (for login and sudo)\" \"root\")\n(def ^:dynamic *port* \"SSH listening port\" ", "end": 1063, "score": 0.9469189047813416, "start": 1059, "tag": "PASSWORD", "value": "root" }, { "context": " host\n {:username *username*\n :password *password*\n ", "end": 6945, "score": 0.9893423318862915, "start": 6937, "tag": "USERNAME", "value": "username" }, { "context": "ame *username*\n :password *password*\n :port *port*\n ", "end": 6990, "score": 0.9566952586174011, "start": 6982, "tag": "PASSWORD", "value": "password" }, { "context": "on and evaluates body in that scope. Options:\n\n :username\n :password\n :private-key-path\n :strict-host-ke", "end": 7577, "score": 0.5386680364608765, "start": 7569, "tag": "USERNAME", "value": "username" }, { "context": "(binding [*username* (get ~ssh :username *username*)\n *password* (get ~ssh :pass", "end": 7715, "score": 0.832647442817688, "start": 7707, "tag": "USERNAME", "value": "username" } ]
linearizable/jepsen/src/jepsen/control.clj
isabella232/comdb2
1
(ns jepsen.control "Provides SSH control over a remote node. There's a lot of dynamically bound state in this namespace because we want to make it as simple as possible for scripts to open connections to various nodes." (:require [clj-ssh.ssh :as ssh] [jepsen.util :as util :refer [real-pmap with-retry with-thread-name]] [jepsen.reconnect :as rc] [clojure.string :as str] [clojure.tools.logging :refer [warn info debug]])) ; STATE STATE STATE STATE (def ^:dynamic *host* "Current hostname" nil) (def ^:dynamic *session* "Current clj-ssh session wrapper" nil) (def ^:dynamic *trace* "Shall we trace commands?" false) (def ^:dynamic *dir* "Working directory" "/") (def ^:dynamic *sudo* "User to sudo to" nil) (def ^:dynamic *username* "Username" "root") (def ^:dynamic *password* "Password (for login and sudo)" "root") (def ^:dynamic *port* "SSH listening port" 22) (def ^:dynamic *private-key-path* "SSH identity file" nil) (def ^:dynamic *strict-host-key-checking* "Verify SSH host keys" :yes) (def ^:dynamic *retries* "How many times to retry conns" 5) (defrecord Literal [string]) (defn lit "A literal string to be passed, unescaped, to the shell." [s] (Literal. s)) (def | "A literal pipe character." (lit "|")) (defn escape "Escapes a thing for the shell. Nils are empty strings. Literal wrappers are passed through directly. The special keywords :>, :>>, and :< map to their corresponding shell I/O redirection operators. Named things like keywords and symbols use their name, escaped. Strings are escaped like normal. Sequential collections and sets have each element escaped and space-separated." [s] (cond (nil? s) "" (instance? Literal s) (:string s) (#{:> :>> :<} s) (name s) (or (sequential? s) (set? s)) (str/join " " (map escape s)) :else (let [s (if (instance? clojure.lang.Named s) (name s) (str s))] (cond ; Empty string (= "" s) "\"\"" (re-find #"[\\\$`\"\s\(\)\{\}\[\]\*\?<>&;]" s) (str "\"" (str/replace s #"([\\\$`\"])" "\\\\$1") "\"") :else s)))) (defn wrap-sudo "Wraps command in a sudo subshell." [cmd] (if *sudo* (merge cmd {:cmd (str "sudo -S -u " *sudo* " bash -c " (escape (:cmd cmd))) :in (if *password* (str *password* "\n" (:in cmd)) (:in cmd))}) cmd)) (defn wrap-cd "Wraps command by changing to the current bound directory first." [cmd] (if *dir* (assoc cmd :cmd (str "cd " (escape *dir*) "; " (:cmd cmd))) cmd)) (defn wrap-trace "Logs argument to console when tracing is enabled." [arg] (do (when *trace* (info arg)) arg)) (defn throw-on-nonzero-exit "Throws when the result of an SSH result has nonzero exit status." [result] (if (zero? (:exit result)) result (throw (RuntimeException. (str (:cmd (:action result)) " returned non-zero exit status " (:exit result) " on " (:host result) ". STDOUT:\n" (:out result) "\n\nSTDERR:\n" (:err result)))))) (defn just-stdout "Returns the stdout from an ssh result, trimming any newlines at the end." [result] (str/trim-newline (:out result))) (defn ssh* "Evaluates an SSH action against the current host. Retries packet corrupt errors." [action] (with-retry [tries *retries*] (rc/with-conn [s *session*] (assoc (ssh/ssh s action) :host *host* :action action)) (catch com.jcraft.jsch.JSchException e (if (and (pos? tries) (or (= "session is down" (.getMessage e)) (= "Packet corrupt" (.getMessage e)))) (do (Thread/sleep (+ 1000 (rand-int 1000))) (retry (dec tries))) (throw e))))) (defn exec* "Like exec, but does not escape." [& commands] (->> commands (str/join " ") (array-map :cmd) wrap-cd wrap-sudo wrap-trace ssh* throw-on-nonzero-exit just-stdout)) (defn exec "Takes a shell command and arguments, runs the command, and returns stdout, throwing if an error occurs. Escapes all arguments." [& commands] (->> commands (map escape) (apply exec*))) (defn scp* "Evaluates an SCP from the current host to the node." [current-path node-path] (warn "scp* is deprecated: use (upload current-path node-path) instead.") (rc/with-conn [s *session*] (ssh/scp-to *session* current-path node-path))) (defn upload "Copies local path(s) to remote node. Takes arguments for clj-ssh/scp-to." [& args] (with-retry [tries *retries*] (rc/with-conn [s *session*] (apply ssh/scp-to s args)) (catch com.jcraft.jsch.JSchException e (if (and (pos? tries) (or (= "session is down" (.getMessage e)) (= "Packet corrupt" (.getMessage e)))) (do (Thread/sleep (+ 1000 (rand-int 1000))) (retry (dec tries))) (throw e))))) (defn download "Copies remote paths to local node. Takes arguments for clj-ssh/scp-from. Retres failures." [& args] (with-retry [tries *retries*] (rc/with-conn [s *session*] (apply ssh/scp-from s args)) (catch com.jcraft.jsch.JSchException e (if (and (pos? tries) (or (= "session is down" (.getMessage e)) (= "Packet corrupt" (.getMessage e)))) (do (Thread/sleep (+ 1000 (rand-int 1000))) (retry (dec tries))) (throw e))))) (defn expand-path "Expands path relative to the current directory." [path] (if (re-find #"^/" path) ; Absolute path ; Relative (str *dir* (if (re-find #"/$" path) "" "/") path))) (defmacro cd "Evaluates forms in the given directory." [dir & body] `(binding [*dir* (expand-path ~dir)] ~@body)) (defmacro sudo "Evaluates forms with a particular user." [user & body] `(binding [*sudo* (name ~user)] ~@body)) (defmacro su "sudo root ..." [& body] `(sudo :root ~@body)) (defmacro trace "Evaluates forms with command tracing enabled." [& body] `(binding [*trace* true] ~@body)) (defn clj-ssh-session "Opens a raw session to the given host." [host] (let [host (name host) agent (ssh/ssh-agent {}) _ (when *private-key-path* (ssh/add-identity agent {:private-key-path *private-key-path*}))] (doto (ssh/session agent host {:username *username* :password *password* :port *port* :strict-host-key-checking *strict-host-key-checking*}) (ssh/connect)))) (defn session "Wraps clj-ssh-session in a wrapper for reconnection." [host] (rc/open! (rc/wrapper {:open #(clj-ssh-session host) :name [:control host] :close ssh/disconnect :log? true}))) (defn disconnect "Close a session" [session] (rc/close! session)) (defmacro with-ssh "Takes a map of SSH configuration and evaluates body in that scope. Options: :username :password :private-key-path :strict-host-key-checking" [ssh & body] `(binding [*username* (get ~ssh :username *username*) *password* (get ~ssh :password *password*) *port* (get ~ssh :port *port*) *private-key-path* (get ~ssh :private-key-path *private-key-path*) *strict-host-key-checking* (get ~ssh :strict-host-key-checking *strict-host-key-checking*)] ~@body)) (defmacro with-session "Binds a host and session and evaluates body. Does not open or close session; this is just for the namespace dynamics state." [host session & body] `(binding [*host* (name ~host) *session* ~session] ~@body)) (defmacro on "Opens a session to the given host and evaluates body there; and closes session when body completes." [host & body] `(let [session# (session ~host)] (try (with-session ~host session# ~@body) (finally (disconnect session#))))) (defmacro on-many "Takes a list of hosts, executes body on each host in parallel, and returns a map of hosts to return values." [hosts & body] `(let [hosts# ~hosts] (->> hosts# (map #(future (on % ~@body))) doall (map deref) (map vector hosts#) (into {})))) (defn on-nodes "Given a test, evaluates (f test node) in parallel on each node, with that node's SSH connection bound." [test f] (->> (:sessions test) (real-pmap (bound-fn [[node session]] (with-thread-name (str "jepsen node " (name node)) (with-session node session [node (f test node)])))) (into {}))) (defmacro with-test-nodes "Given a test, evaluates body in parallel on each node, with that node's SSH connection bound." [test & body] `(on-nodes ~test (fn [test# node#] ~@body))) (defn go [host] (on host (trace (cd "/" (sudo "root" (println (exec "whoami")))))))
101940
(ns jepsen.control "Provides SSH control over a remote node. There's a lot of dynamically bound state in this namespace because we want to make it as simple as possible for scripts to open connections to various nodes." (:require [clj-ssh.ssh :as ssh] [jepsen.util :as util :refer [real-pmap with-retry with-thread-name]] [jepsen.reconnect :as rc] [clojure.string :as str] [clojure.tools.logging :refer [warn info debug]])) ; STATE STATE STATE STATE (def ^:dynamic *host* "Current hostname" nil) (def ^:dynamic *session* "Current clj-ssh session wrapper" nil) (def ^:dynamic *trace* "Shall we trace commands?" false) (def ^:dynamic *dir* "Working directory" "/") (def ^:dynamic *sudo* "User to sudo to" nil) (def ^:dynamic *username* "Username" "root") (def ^:dynamic *password* "Password (for login and sudo)" "<PASSWORD>") (def ^:dynamic *port* "SSH listening port" 22) (def ^:dynamic *private-key-path* "SSH identity file" nil) (def ^:dynamic *strict-host-key-checking* "Verify SSH host keys" :yes) (def ^:dynamic *retries* "How many times to retry conns" 5) (defrecord Literal [string]) (defn lit "A literal string to be passed, unescaped, to the shell." [s] (Literal. s)) (def | "A literal pipe character." (lit "|")) (defn escape "Escapes a thing for the shell. Nils are empty strings. Literal wrappers are passed through directly. The special keywords :>, :>>, and :< map to their corresponding shell I/O redirection operators. Named things like keywords and symbols use their name, escaped. Strings are escaped like normal. Sequential collections and sets have each element escaped and space-separated." [s] (cond (nil? s) "" (instance? Literal s) (:string s) (#{:> :>> :<} s) (name s) (or (sequential? s) (set? s)) (str/join " " (map escape s)) :else (let [s (if (instance? clojure.lang.Named s) (name s) (str s))] (cond ; Empty string (= "" s) "\"\"" (re-find #"[\\\$`\"\s\(\)\{\}\[\]\*\?<>&;]" s) (str "\"" (str/replace s #"([\\\$`\"])" "\\\\$1") "\"") :else s)))) (defn wrap-sudo "Wraps command in a sudo subshell." [cmd] (if *sudo* (merge cmd {:cmd (str "sudo -S -u " *sudo* " bash -c " (escape (:cmd cmd))) :in (if *password* (str *password* "\n" (:in cmd)) (:in cmd))}) cmd)) (defn wrap-cd "Wraps command by changing to the current bound directory first." [cmd] (if *dir* (assoc cmd :cmd (str "cd " (escape *dir*) "; " (:cmd cmd))) cmd)) (defn wrap-trace "Logs argument to console when tracing is enabled." [arg] (do (when *trace* (info arg)) arg)) (defn throw-on-nonzero-exit "Throws when the result of an SSH result has nonzero exit status." [result] (if (zero? (:exit result)) result (throw (RuntimeException. (str (:cmd (:action result)) " returned non-zero exit status " (:exit result) " on " (:host result) ". STDOUT:\n" (:out result) "\n\nSTDERR:\n" (:err result)))))) (defn just-stdout "Returns the stdout from an ssh result, trimming any newlines at the end." [result] (str/trim-newline (:out result))) (defn ssh* "Evaluates an SSH action against the current host. Retries packet corrupt errors." [action] (with-retry [tries *retries*] (rc/with-conn [s *session*] (assoc (ssh/ssh s action) :host *host* :action action)) (catch com.jcraft.jsch.JSchException e (if (and (pos? tries) (or (= "session is down" (.getMessage e)) (= "Packet corrupt" (.getMessage e)))) (do (Thread/sleep (+ 1000 (rand-int 1000))) (retry (dec tries))) (throw e))))) (defn exec* "Like exec, but does not escape." [& commands] (->> commands (str/join " ") (array-map :cmd) wrap-cd wrap-sudo wrap-trace ssh* throw-on-nonzero-exit just-stdout)) (defn exec "Takes a shell command and arguments, runs the command, and returns stdout, throwing if an error occurs. Escapes all arguments." [& commands] (->> commands (map escape) (apply exec*))) (defn scp* "Evaluates an SCP from the current host to the node." [current-path node-path] (warn "scp* is deprecated: use (upload current-path node-path) instead.") (rc/with-conn [s *session*] (ssh/scp-to *session* current-path node-path))) (defn upload "Copies local path(s) to remote node. Takes arguments for clj-ssh/scp-to." [& args] (with-retry [tries *retries*] (rc/with-conn [s *session*] (apply ssh/scp-to s args)) (catch com.jcraft.jsch.JSchException e (if (and (pos? tries) (or (= "session is down" (.getMessage e)) (= "Packet corrupt" (.getMessage e)))) (do (Thread/sleep (+ 1000 (rand-int 1000))) (retry (dec tries))) (throw e))))) (defn download "Copies remote paths to local node. Takes arguments for clj-ssh/scp-from. Retres failures." [& args] (with-retry [tries *retries*] (rc/with-conn [s *session*] (apply ssh/scp-from s args)) (catch com.jcraft.jsch.JSchException e (if (and (pos? tries) (or (= "session is down" (.getMessage e)) (= "Packet corrupt" (.getMessage e)))) (do (Thread/sleep (+ 1000 (rand-int 1000))) (retry (dec tries))) (throw e))))) (defn expand-path "Expands path relative to the current directory." [path] (if (re-find #"^/" path) ; Absolute path ; Relative (str *dir* (if (re-find #"/$" path) "" "/") path))) (defmacro cd "Evaluates forms in the given directory." [dir & body] `(binding [*dir* (expand-path ~dir)] ~@body)) (defmacro sudo "Evaluates forms with a particular user." [user & body] `(binding [*sudo* (name ~user)] ~@body)) (defmacro su "sudo root ..." [& body] `(sudo :root ~@body)) (defmacro trace "Evaluates forms with command tracing enabled." [& body] `(binding [*trace* true] ~@body)) (defn clj-ssh-session "Opens a raw session to the given host." [host] (let [host (name host) agent (ssh/ssh-agent {}) _ (when *private-key-path* (ssh/add-identity agent {:private-key-path *private-key-path*}))] (doto (ssh/session agent host {:username *username* :password *<PASSWORD>* :port *port* :strict-host-key-checking *strict-host-key-checking*}) (ssh/connect)))) (defn session "Wraps clj-ssh-session in a wrapper for reconnection." [host] (rc/open! (rc/wrapper {:open #(clj-ssh-session host) :name [:control host] :close ssh/disconnect :log? true}))) (defn disconnect "Close a session" [session] (rc/close! session)) (defmacro with-ssh "Takes a map of SSH configuration and evaluates body in that scope. Options: :username :password :private-key-path :strict-host-key-checking" [ssh & body] `(binding [*username* (get ~ssh :username *username*) *password* (get ~ssh :password *password*) *port* (get ~ssh :port *port*) *private-key-path* (get ~ssh :private-key-path *private-key-path*) *strict-host-key-checking* (get ~ssh :strict-host-key-checking *strict-host-key-checking*)] ~@body)) (defmacro with-session "Binds a host and session and evaluates body. Does not open or close session; this is just for the namespace dynamics state." [host session & body] `(binding [*host* (name ~host) *session* ~session] ~@body)) (defmacro on "Opens a session to the given host and evaluates body there; and closes session when body completes." [host & body] `(let [session# (session ~host)] (try (with-session ~host session# ~@body) (finally (disconnect session#))))) (defmacro on-many "Takes a list of hosts, executes body on each host in parallel, and returns a map of hosts to return values." [hosts & body] `(let [hosts# ~hosts] (->> hosts# (map #(future (on % ~@body))) doall (map deref) (map vector hosts#) (into {})))) (defn on-nodes "Given a test, evaluates (f test node) in parallel on each node, with that node's SSH connection bound." [test f] (->> (:sessions test) (real-pmap (bound-fn [[node session]] (with-thread-name (str "jepsen node " (name node)) (with-session node session [node (f test node)])))) (into {}))) (defmacro with-test-nodes "Given a test, evaluates body in parallel on each node, with that node's SSH connection bound." [test & body] `(on-nodes ~test (fn [test# node#] ~@body))) (defn go [host] (on host (trace (cd "/" (sudo "root" (println (exec "whoami")))))))
true
(ns jepsen.control "Provides SSH control over a remote node. There's a lot of dynamically bound state in this namespace because we want to make it as simple as possible for scripts to open connections to various nodes." (:require [clj-ssh.ssh :as ssh] [jepsen.util :as util :refer [real-pmap with-retry with-thread-name]] [jepsen.reconnect :as rc] [clojure.string :as str] [clojure.tools.logging :refer [warn info debug]])) ; STATE STATE STATE STATE (def ^:dynamic *host* "Current hostname" nil) (def ^:dynamic *session* "Current clj-ssh session wrapper" nil) (def ^:dynamic *trace* "Shall we trace commands?" false) (def ^:dynamic *dir* "Working directory" "/") (def ^:dynamic *sudo* "User to sudo to" nil) (def ^:dynamic *username* "Username" "root") (def ^:dynamic *password* "Password (for login and sudo)" "PI:PASSWORD:<PASSWORD>END_PI") (def ^:dynamic *port* "SSH listening port" 22) (def ^:dynamic *private-key-path* "SSH identity file" nil) (def ^:dynamic *strict-host-key-checking* "Verify SSH host keys" :yes) (def ^:dynamic *retries* "How many times to retry conns" 5) (defrecord Literal [string]) (defn lit "A literal string to be passed, unescaped, to the shell." [s] (Literal. s)) (def | "A literal pipe character." (lit "|")) (defn escape "Escapes a thing for the shell. Nils are empty strings. Literal wrappers are passed through directly. The special keywords :>, :>>, and :< map to their corresponding shell I/O redirection operators. Named things like keywords and symbols use their name, escaped. Strings are escaped like normal. Sequential collections and sets have each element escaped and space-separated." [s] (cond (nil? s) "" (instance? Literal s) (:string s) (#{:> :>> :<} s) (name s) (or (sequential? s) (set? s)) (str/join " " (map escape s)) :else (let [s (if (instance? clojure.lang.Named s) (name s) (str s))] (cond ; Empty string (= "" s) "\"\"" (re-find #"[\\\$`\"\s\(\)\{\}\[\]\*\?<>&;]" s) (str "\"" (str/replace s #"([\\\$`\"])" "\\\\$1") "\"") :else s)))) (defn wrap-sudo "Wraps command in a sudo subshell." [cmd] (if *sudo* (merge cmd {:cmd (str "sudo -S -u " *sudo* " bash -c " (escape (:cmd cmd))) :in (if *password* (str *password* "\n" (:in cmd)) (:in cmd))}) cmd)) (defn wrap-cd "Wraps command by changing to the current bound directory first." [cmd] (if *dir* (assoc cmd :cmd (str "cd " (escape *dir*) "; " (:cmd cmd))) cmd)) (defn wrap-trace "Logs argument to console when tracing is enabled." [arg] (do (when *trace* (info arg)) arg)) (defn throw-on-nonzero-exit "Throws when the result of an SSH result has nonzero exit status." [result] (if (zero? (:exit result)) result (throw (RuntimeException. (str (:cmd (:action result)) " returned non-zero exit status " (:exit result) " on " (:host result) ". STDOUT:\n" (:out result) "\n\nSTDERR:\n" (:err result)))))) (defn just-stdout "Returns the stdout from an ssh result, trimming any newlines at the end." [result] (str/trim-newline (:out result))) (defn ssh* "Evaluates an SSH action against the current host. Retries packet corrupt errors." [action] (with-retry [tries *retries*] (rc/with-conn [s *session*] (assoc (ssh/ssh s action) :host *host* :action action)) (catch com.jcraft.jsch.JSchException e (if (and (pos? tries) (or (= "session is down" (.getMessage e)) (= "Packet corrupt" (.getMessage e)))) (do (Thread/sleep (+ 1000 (rand-int 1000))) (retry (dec tries))) (throw e))))) (defn exec* "Like exec, but does not escape." [& commands] (->> commands (str/join " ") (array-map :cmd) wrap-cd wrap-sudo wrap-trace ssh* throw-on-nonzero-exit just-stdout)) (defn exec "Takes a shell command and arguments, runs the command, and returns stdout, throwing if an error occurs. Escapes all arguments." [& commands] (->> commands (map escape) (apply exec*))) (defn scp* "Evaluates an SCP from the current host to the node." [current-path node-path] (warn "scp* is deprecated: use (upload current-path node-path) instead.") (rc/with-conn [s *session*] (ssh/scp-to *session* current-path node-path))) (defn upload "Copies local path(s) to remote node. Takes arguments for clj-ssh/scp-to." [& args] (with-retry [tries *retries*] (rc/with-conn [s *session*] (apply ssh/scp-to s args)) (catch com.jcraft.jsch.JSchException e (if (and (pos? tries) (or (= "session is down" (.getMessage e)) (= "Packet corrupt" (.getMessage e)))) (do (Thread/sleep (+ 1000 (rand-int 1000))) (retry (dec tries))) (throw e))))) (defn download "Copies remote paths to local node. Takes arguments for clj-ssh/scp-from. Retres failures." [& args] (with-retry [tries *retries*] (rc/with-conn [s *session*] (apply ssh/scp-from s args)) (catch com.jcraft.jsch.JSchException e (if (and (pos? tries) (or (= "session is down" (.getMessage e)) (= "Packet corrupt" (.getMessage e)))) (do (Thread/sleep (+ 1000 (rand-int 1000))) (retry (dec tries))) (throw e))))) (defn expand-path "Expands path relative to the current directory." [path] (if (re-find #"^/" path) ; Absolute path ; Relative (str *dir* (if (re-find #"/$" path) "" "/") path))) (defmacro cd "Evaluates forms in the given directory." [dir & body] `(binding [*dir* (expand-path ~dir)] ~@body)) (defmacro sudo "Evaluates forms with a particular user." [user & body] `(binding [*sudo* (name ~user)] ~@body)) (defmacro su "sudo root ..." [& body] `(sudo :root ~@body)) (defmacro trace "Evaluates forms with command tracing enabled." [& body] `(binding [*trace* true] ~@body)) (defn clj-ssh-session "Opens a raw session to the given host." [host] (let [host (name host) agent (ssh/ssh-agent {}) _ (when *private-key-path* (ssh/add-identity agent {:private-key-path *private-key-path*}))] (doto (ssh/session agent host {:username *username* :password *PI:PASSWORD:<PASSWORD>END_PI* :port *port* :strict-host-key-checking *strict-host-key-checking*}) (ssh/connect)))) (defn session "Wraps clj-ssh-session in a wrapper for reconnection." [host] (rc/open! (rc/wrapper {:open #(clj-ssh-session host) :name [:control host] :close ssh/disconnect :log? true}))) (defn disconnect "Close a session" [session] (rc/close! session)) (defmacro with-ssh "Takes a map of SSH configuration and evaluates body in that scope. Options: :username :password :private-key-path :strict-host-key-checking" [ssh & body] `(binding [*username* (get ~ssh :username *username*) *password* (get ~ssh :password *password*) *port* (get ~ssh :port *port*) *private-key-path* (get ~ssh :private-key-path *private-key-path*) *strict-host-key-checking* (get ~ssh :strict-host-key-checking *strict-host-key-checking*)] ~@body)) (defmacro with-session "Binds a host and session and evaluates body. Does not open or close session; this is just for the namespace dynamics state." [host session & body] `(binding [*host* (name ~host) *session* ~session] ~@body)) (defmacro on "Opens a session to the given host and evaluates body there; and closes session when body completes." [host & body] `(let [session# (session ~host)] (try (with-session ~host session# ~@body) (finally (disconnect session#))))) (defmacro on-many "Takes a list of hosts, executes body on each host in parallel, and returns a map of hosts to return values." [hosts & body] `(let [hosts# ~hosts] (->> hosts# (map #(future (on % ~@body))) doall (map deref) (map vector hosts#) (into {})))) (defn on-nodes "Given a test, evaluates (f test node) in parallel on each node, with that node's SSH connection bound." [test f] (->> (:sessions test) (real-pmap (bound-fn [[node session]] (with-thread-name (str "jepsen node " (name node)) (with-session node session [node (f test node)])))) (into {}))) (defmacro with-test-nodes "Given a test, evaluates body in parallel on each node, with that node's SSH connection bound." [test & body] `(on-nodes ~test (fn [test# node#] ~@body))) (defn go [host] (on host (trace (cd "/" (sudo "root" (println (exec "whoami")))))))
[ { "context": "\n (.withS3Key \"clojider.jar\")))))\n\n(defn- create-lambda-fn [lambda-name bucke", "end": 5558, "score": 0.8886201977729797, "start": 5546, "tag": "KEY", "value": "clojider.jar" }, { "context": " (.withS3Key \"clojider.jar\")))\n (.withRole ro", "end": 6319, "score": 0.6295937299728394, "start": 6310, "tag": "KEY", "value": "jider.jar" } ]
src/clojider/aws.clj
mhjort/clojider
76
(ns clojider.aws (:require [cheshire.core :refer [generate-string]]) (:import [com.amazonaws.services.identitymanagement AmazonIdentityManagementClient] [com.amazonaws.services.identitymanagement.model AttachRolePolicyRequest CreatePolicyRequest CreateRoleRequest DeleteRoleRequest DeletePolicyRequest ListRolePoliciesRequest DetachRolePolicyRequest] [com.amazonaws.services.lambda AWSLambdaClient] [com.amazonaws.services.lambda.model CreateFunctionRequest DeleteFunctionRequest UpdateFunctionCodeRequest FunctionCode] [com.amazonaws.auth DefaultAWSCredentialsProviderChain] [com.amazonaws.services.s3 AmazonS3Client] [com.amazonaws.regions Regions] [java.io File])) (def aws-credentials (delay (.getCredentials (DefaultAWSCredentialsProviderChain.)))) (defonce s3-client (delay (AmazonS3Client. @aws-credentials))) (defn- create-results-bucket [bucket-name region] (if (.doesBucketExist @s3-client bucket-name) (println bucket-name "already exists. Skipping creation.") (do (println "Creating bucket" bucket-name "for the results.") (if (= "us-east-1" region) (.createBucket @s3-client bucket-name) (.createBucket @s3-client bucket-name region))))) (defn- store-jar-to-bucket [bucket-name jar-path] (println "Uploading code to S3 from" jar-path) (.putObject @s3-client bucket-name "clojider.jar" (File. jar-path))) (defn- delete-results-bucket [bucket-name] (.deleteBucket @s3-client bucket-name)) (defn- delete-all-objects-from-bucket [bucket-name] (println "Deleting all objects from bucket" bucket-name) (let [object-keys (map #(.getKey %) (.getObjectSummaries (.listObjects @s3-client bucket-name)))] (doseq [object-key object-keys] (println "Deleting" object-key) (.deleteObject @s3-client bucket-name object-key)))) (def role {:Version "2012-10-17" :Statement {:Effect "Allow" :Principal {:Service "lambda.amazonaws.com"} :Action "sts:AssumeRole"}}) (defn policy [bucket-name] {:Version "2012-10-17" :Statement [{:Effect "Allow" :Action ["s3:PutObject"] :Resource (str "arn:aws:s3:::" bucket-name "/*")} {:Effect "Allow" :Action ["logs:CreateLogGroup" "logs:CreateLogStream" "logs:PutLogEvents"] :Resource ["arn:aws:logs:*:*:*"]}]}) (defn create-role-and-policy [role-name policy-name bucket-name] (println "Creating role" role-name "with policy" policy-name) (let [client (AmazonIdentityManagementClient. @aws-credentials) role (.createRole client (-> (CreateRoleRequest.) (.withRoleName role-name) (.withAssumeRolePolicyDocument (generate-string role))))] (let [policy-result (.createPolicy client (-> (CreatePolicyRequest.) (.withPolicyName policy-name) (.withPolicyDocument (generate-string (policy bucket-name)))))] (.attachRolePolicy client (-> (AttachRolePolicyRequest.) (.withPolicyArn (-> policy-result .getPolicy .getArn)) (.withRoleName role-name)))) (-> role .getRole .getArn))) (defn delete-role-and-policy [role-name policy-name] (println "Deleting role" role-name "with policy" policy-name) (let [client (AmazonIdentityManagementClient. @aws-credentials) policy-arn (.getArn (first (filter #(= policy-name (.getPolicyName %)) (.getPolicies (.listPolicies client)))))] (.detachRolePolicy client (-> (DetachRolePolicyRequest.) (.withPolicyArn policy-arn) (.withRoleName role-name))) (.deletePolicy client (-> (DeletePolicyRequest.) (.withPolicyArn policy-arn))) (.deleteRole client (-> (DeleteRoleRequest.) (.withRoleName role-name))))) (defn- create-lambda-client [region] (-> (AWSLambdaClient. @aws-credentials) (.withRegion (Regions/fromName region)))) (defn delete-lambda-fn [lambda-name region] (println "Deleting Lambda function" lambda-name "from region") (let [client (create-lambda-client region)] (.deleteFunction client (-> (DeleteFunctionRequest.) (.withFunctionName lambda-name))))) (defn- update-lambda-fn [lambda-name bucket-name region] (println "Updating Lambda function" lambda-name "in region") (let [client (create-lambda-client region)] (.updateFunctionCode client (-> (UpdateFunctionCodeRequest.) (.withFunctionName lambda-name) (.withS3Bucket bucket-name) (.withS3Key "clojider.jar"))))) (defn- create-lambda-fn [lambda-name bucket-name region role-arn] (println "Creating Lambda function" lambda-name "to region" region) (let [client (create-lambda-client region)] (.createFunction client (-> (CreateFunctionRequest.) (.withFunctionName lambda-name) (.withMemorySize (int 1536)) (.withTimeout (int 300)) (.withRuntime "java8") (.withHandler "clojider.LambdaFn") (.withCode (-> (FunctionCode.) (.withS3Bucket bucket-name) (.withS3Key "clojider.jar"))) (.withRole role-arn))))) (defn install-lambda [{:keys [region bucket file]}] (let [role (str "clojider-role-" region) policy (str "clojider-policy-" region) role-arn (create-role-and-policy role policy bucket)] (Thread/sleep (* 10 1000)) (create-results-bucket bucket region) (store-jar-to-bucket bucket file) (create-lambda-fn "clojider-load-testing-lambda" bucket region role-arn))) (defn update-lambda [{:keys [region bucket file]}] (store-jar-to-bucket bucket file) (update-lambda-fn "clojider-load-testing-lambda" bucket region)) (defn uninstall-lambda [{:keys [region bucket]}] (let [role (str "clojider-role-" region) policy (str "clojider-policy-" region)] (delete-role-and-policy role policy) (delete-lambda-fn "clojider-load-testing-lambda" region) (delete-all-objects-from-bucket bucket) (delete-results-bucket bucket)))
98995
(ns clojider.aws (:require [cheshire.core :refer [generate-string]]) (:import [com.amazonaws.services.identitymanagement AmazonIdentityManagementClient] [com.amazonaws.services.identitymanagement.model AttachRolePolicyRequest CreatePolicyRequest CreateRoleRequest DeleteRoleRequest DeletePolicyRequest ListRolePoliciesRequest DetachRolePolicyRequest] [com.amazonaws.services.lambda AWSLambdaClient] [com.amazonaws.services.lambda.model CreateFunctionRequest DeleteFunctionRequest UpdateFunctionCodeRequest FunctionCode] [com.amazonaws.auth DefaultAWSCredentialsProviderChain] [com.amazonaws.services.s3 AmazonS3Client] [com.amazonaws.regions Regions] [java.io File])) (def aws-credentials (delay (.getCredentials (DefaultAWSCredentialsProviderChain.)))) (defonce s3-client (delay (AmazonS3Client. @aws-credentials))) (defn- create-results-bucket [bucket-name region] (if (.doesBucketExist @s3-client bucket-name) (println bucket-name "already exists. Skipping creation.") (do (println "Creating bucket" bucket-name "for the results.") (if (= "us-east-1" region) (.createBucket @s3-client bucket-name) (.createBucket @s3-client bucket-name region))))) (defn- store-jar-to-bucket [bucket-name jar-path] (println "Uploading code to S3 from" jar-path) (.putObject @s3-client bucket-name "clojider.jar" (File. jar-path))) (defn- delete-results-bucket [bucket-name] (.deleteBucket @s3-client bucket-name)) (defn- delete-all-objects-from-bucket [bucket-name] (println "Deleting all objects from bucket" bucket-name) (let [object-keys (map #(.getKey %) (.getObjectSummaries (.listObjects @s3-client bucket-name)))] (doseq [object-key object-keys] (println "Deleting" object-key) (.deleteObject @s3-client bucket-name object-key)))) (def role {:Version "2012-10-17" :Statement {:Effect "Allow" :Principal {:Service "lambda.amazonaws.com"} :Action "sts:AssumeRole"}}) (defn policy [bucket-name] {:Version "2012-10-17" :Statement [{:Effect "Allow" :Action ["s3:PutObject"] :Resource (str "arn:aws:s3:::" bucket-name "/*")} {:Effect "Allow" :Action ["logs:CreateLogGroup" "logs:CreateLogStream" "logs:PutLogEvents"] :Resource ["arn:aws:logs:*:*:*"]}]}) (defn create-role-and-policy [role-name policy-name bucket-name] (println "Creating role" role-name "with policy" policy-name) (let [client (AmazonIdentityManagementClient. @aws-credentials) role (.createRole client (-> (CreateRoleRequest.) (.withRoleName role-name) (.withAssumeRolePolicyDocument (generate-string role))))] (let [policy-result (.createPolicy client (-> (CreatePolicyRequest.) (.withPolicyName policy-name) (.withPolicyDocument (generate-string (policy bucket-name)))))] (.attachRolePolicy client (-> (AttachRolePolicyRequest.) (.withPolicyArn (-> policy-result .getPolicy .getArn)) (.withRoleName role-name)))) (-> role .getRole .getArn))) (defn delete-role-and-policy [role-name policy-name] (println "Deleting role" role-name "with policy" policy-name) (let [client (AmazonIdentityManagementClient. @aws-credentials) policy-arn (.getArn (first (filter #(= policy-name (.getPolicyName %)) (.getPolicies (.listPolicies client)))))] (.detachRolePolicy client (-> (DetachRolePolicyRequest.) (.withPolicyArn policy-arn) (.withRoleName role-name))) (.deletePolicy client (-> (DeletePolicyRequest.) (.withPolicyArn policy-arn))) (.deleteRole client (-> (DeleteRoleRequest.) (.withRoleName role-name))))) (defn- create-lambda-client [region] (-> (AWSLambdaClient. @aws-credentials) (.withRegion (Regions/fromName region)))) (defn delete-lambda-fn [lambda-name region] (println "Deleting Lambda function" lambda-name "from region") (let [client (create-lambda-client region)] (.deleteFunction client (-> (DeleteFunctionRequest.) (.withFunctionName lambda-name))))) (defn- update-lambda-fn [lambda-name bucket-name region] (println "Updating Lambda function" lambda-name "in region") (let [client (create-lambda-client region)] (.updateFunctionCode client (-> (UpdateFunctionCodeRequest.) (.withFunctionName lambda-name) (.withS3Bucket bucket-name) (.withS3Key "<KEY>"))))) (defn- create-lambda-fn [lambda-name bucket-name region role-arn] (println "Creating Lambda function" lambda-name "to region" region) (let [client (create-lambda-client region)] (.createFunction client (-> (CreateFunctionRequest.) (.withFunctionName lambda-name) (.withMemorySize (int 1536)) (.withTimeout (int 300)) (.withRuntime "java8") (.withHandler "clojider.LambdaFn") (.withCode (-> (FunctionCode.) (.withS3Bucket bucket-name) (.withS3Key "clo<KEY>"))) (.withRole role-arn))))) (defn install-lambda [{:keys [region bucket file]}] (let [role (str "clojider-role-" region) policy (str "clojider-policy-" region) role-arn (create-role-and-policy role policy bucket)] (Thread/sleep (* 10 1000)) (create-results-bucket bucket region) (store-jar-to-bucket bucket file) (create-lambda-fn "clojider-load-testing-lambda" bucket region role-arn))) (defn update-lambda [{:keys [region bucket file]}] (store-jar-to-bucket bucket file) (update-lambda-fn "clojider-load-testing-lambda" bucket region)) (defn uninstall-lambda [{:keys [region bucket]}] (let [role (str "clojider-role-" region) policy (str "clojider-policy-" region)] (delete-role-and-policy role policy) (delete-lambda-fn "clojider-load-testing-lambda" region) (delete-all-objects-from-bucket bucket) (delete-results-bucket bucket)))
true
(ns clojider.aws (:require [cheshire.core :refer [generate-string]]) (:import [com.amazonaws.services.identitymanagement AmazonIdentityManagementClient] [com.amazonaws.services.identitymanagement.model AttachRolePolicyRequest CreatePolicyRequest CreateRoleRequest DeleteRoleRequest DeletePolicyRequest ListRolePoliciesRequest DetachRolePolicyRequest] [com.amazonaws.services.lambda AWSLambdaClient] [com.amazonaws.services.lambda.model CreateFunctionRequest DeleteFunctionRequest UpdateFunctionCodeRequest FunctionCode] [com.amazonaws.auth DefaultAWSCredentialsProviderChain] [com.amazonaws.services.s3 AmazonS3Client] [com.amazonaws.regions Regions] [java.io File])) (def aws-credentials (delay (.getCredentials (DefaultAWSCredentialsProviderChain.)))) (defonce s3-client (delay (AmazonS3Client. @aws-credentials))) (defn- create-results-bucket [bucket-name region] (if (.doesBucketExist @s3-client bucket-name) (println bucket-name "already exists. Skipping creation.") (do (println "Creating bucket" bucket-name "for the results.") (if (= "us-east-1" region) (.createBucket @s3-client bucket-name) (.createBucket @s3-client bucket-name region))))) (defn- store-jar-to-bucket [bucket-name jar-path] (println "Uploading code to S3 from" jar-path) (.putObject @s3-client bucket-name "clojider.jar" (File. jar-path))) (defn- delete-results-bucket [bucket-name] (.deleteBucket @s3-client bucket-name)) (defn- delete-all-objects-from-bucket [bucket-name] (println "Deleting all objects from bucket" bucket-name) (let [object-keys (map #(.getKey %) (.getObjectSummaries (.listObjects @s3-client bucket-name)))] (doseq [object-key object-keys] (println "Deleting" object-key) (.deleteObject @s3-client bucket-name object-key)))) (def role {:Version "2012-10-17" :Statement {:Effect "Allow" :Principal {:Service "lambda.amazonaws.com"} :Action "sts:AssumeRole"}}) (defn policy [bucket-name] {:Version "2012-10-17" :Statement [{:Effect "Allow" :Action ["s3:PutObject"] :Resource (str "arn:aws:s3:::" bucket-name "/*")} {:Effect "Allow" :Action ["logs:CreateLogGroup" "logs:CreateLogStream" "logs:PutLogEvents"] :Resource ["arn:aws:logs:*:*:*"]}]}) (defn create-role-and-policy [role-name policy-name bucket-name] (println "Creating role" role-name "with policy" policy-name) (let [client (AmazonIdentityManagementClient. @aws-credentials) role (.createRole client (-> (CreateRoleRequest.) (.withRoleName role-name) (.withAssumeRolePolicyDocument (generate-string role))))] (let [policy-result (.createPolicy client (-> (CreatePolicyRequest.) (.withPolicyName policy-name) (.withPolicyDocument (generate-string (policy bucket-name)))))] (.attachRolePolicy client (-> (AttachRolePolicyRequest.) (.withPolicyArn (-> policy-result .getPolicy .getArn)) (.withRoleName role-name)))) (-> role .getRole .getArn))) (defn delete-role-and-policy [role-name policy-name] (println "Deleting role" role-name "with policy" policy-name) (let [client (AmazonIdentityManagementClient. @aws-credentials) policy-arn (.getArn (first (filter #(= policy-name (.getPolicyName %)) (.getPolicies (.listPolicies client)))))] (.detachRolePolicy client (-> (DetachRolePolicyRequest.) (.withPolicyArn policy-arn) (.withRoleName role-name))) (.deletePolicy client (-> (DeletePolicyRequest.) (.withPolicyArn policy-arn))) (.deleteRole client (-> (DeleteRoleRequest.) (.withRoleName role-name))))) (defn- create-lambda-client [region] (-> (AWSLambdaClient. @aws-credentials) (.withRegion (Regions/fromName region)))) (defn delete-lambda-fn [lambda-name region] (println "Deleting Lambda function" lambda-name "from region") (let [client (create-lambda-client region)] (.deleteFunction client (-> (DeleteFunctionRequest.) (.withFunctionName lambda-name))))) (defn- update-lambda-fn [lambda-name bucket-name region] (println "Updating Lambda function" lambda-name "in region") (let [client (create-lambda-client region)] (.updateFunctionCode client (-> (UpdateFunctionCodeRequest.) (.withFunctionName lambda-name) (.withS3Bucket bucket-name) (.withS3Key "PI:KEY:<KEY>END_PI"))))) (defn- create-lambda-fn [lambda-name bucket-name region role-arn] (println "Creating Lambda function" lambda-name "to region" region) (let [client (create-lambda-client region)] (.createFunction client (-> (CreateFunctionRequest.) (.withFunctionName lambda-name) (.withMemorySize (int 1536)) (.withTimeout (int 300)) (.withRuntime "java8") (.withHandler "clojider.LambdaFn") (.withCode (-> (FunctionCode.) (.withS3Bucket bucket-name) (.withS3Key "cloPI:KEY:<KEY>END_PI"))) (.withRole role-arn))))) (defn install-lambda [{:keys [region bucket file]}] (let [role (str "clojider-role-" region) policy (str "clojider-policy-" region) role-arn (create-role-and-policy role policy bucket)] (Thread/sleep (* 10 1000)) (create-results-bucket bucket region) (store-jar-to-bucket bucket file) (create-lambda-fn "clojider-load-testing-lambda" bucket region role-arn))) (defn update-lambda [{:keys [region bucket file]}] (store-jar-to-bucket bucket file) (update-lambda-fn "clojider-load-testing-lambda" bucket region)) (defn uninstall-lambda [{:keys [region bucket]}] (let [role (str "clojider-role-" region) policy (str "clojider-policy-" region)] (delete-role-and-policy role policy) (delete-lambda-fn "clojider-load-testing-lambda" region) (delete-all-objects-from-bucket bucket) (delete-results-bucket bucket)))
[ { "context": "r as\n ; default.\n\n :user-name \"Sam\", ; This is the name that Overtone will use to r", "end": 612, "score": 0.6871851086616516, "start": 609, "tag": "NAME", "value": "Sam" } ]
docs/config.clj
ABaldwinHunter/overtone
3,870
;; Example Overtone Config. ;; ======================== ;; ;; This lives in ~/.overtone/config.clj ;; ;; This example shouldn't be perceived as being typical - it's a ;; contrived example which uses all the possible keys (typically with ;; their default values) in an attempt to introduce their existence ;; and explain their meaning and usage. { :server :internal, ; use the internal server by default. This option is ; consulted when you use overtone.live. You may also ; specify :external to boot an external server as ; default. :user-name "Sam", ; This is the name that Overtone will use to refer ; to you. For example, you see this being used in ; the boot message. :log-level :warn ; The log level (default is :warn). Options are: ; :error - only logs errors and exceptions ; :warn - logs :error messages and warnings ; :info - logs :error, :warn messages and ; operational info ; :debug - logs :error, :warn, :info and ; diagnostic information :sc-args ; Argument map used to boot the SuperCollider server ; with the following arguments: { :load-sdefs? 1 ; Load synthdefs on boot? 0 or 1 :nrt-output-sample-format nil ; Sample format for non-realtime mode :block-size 64 ; Block size :rendezvous? 0 ; Publish to rendezvous? 0 or 1 :ugens-paths nil ; A list of paths of ugen directories. If ; specified, the standard paths are NOT ; searched for plugins. :verbosity 0 ; Verbosity mode. 0 is normal behaviour, ; -1 suppress information messages, -2 ; suppresses informational and many error ; messages :nrt-output-filename nil ; Output filename for non-realtime mode :max-audio-bus 512 ; Number of audio bus channels :nrt-cmd-filename nil ; Command filename for non-realtime mode :realtime? 1 ; Run in realtime mode? If 0 then the ; other nrt flags must be set :max-w-buffers 64 ; Number of wire buffers :max-nodes 1024 ; Max number of executing nodes allowed in the server :nrt-input-filename nil ; Input filename for non-realtime mode :max-output-bus 8 ; Number of output bus channels :hw-buffer-size nil ; Hardware buffer size :pwd nil ; When using TCP, the session password ; must be the first command sent. :max-logins 64 ; Maximum number of named return ; addresses stored - also maximum number ; of tcp connections accepted. :hw-device-name nil ; Hardware device name :max-sdefs 1024 ; Max number of synthdefs allowed :hw-sample-rate nil ; Hardware sample rate :port 57711 ; Port number :restricted-path nil ; Prevents file-accesing OSC commands ; from accessing files outside the ; specified path. :max-input-bus 8 ; Number of input bus channels :nrt-output-header-format nil ; Header format for non-realtime mode :udp? 1 ; 1 means use UDP, 0 means use TCP :num-rand-seeds 64 ; Number of random seeds :in-streams nil ; Input streams enabled :max-buffers 1024 ; Number of sample buffers :out-streams nil ; Output streams enabled :max-control-bus 4096 ; Number of control bus channels :rt-mem-size 262144 ; Real time memory size }}
17593
;; Example Overtone Config. ;; ======================== ;; ;; This lives in ~/.overtone/config.clj ;; ;; This example shouldn't be perceived as being typical - it's a ;; contrived example which uses all the possible keys (typically with ;; their default values) in an attempt to introduce their existence ;; and explain their meaning and usage. { :server :internal, ; use the internal server by default. This option is ; consulted when you use overtone.live. You may also ; specify :external to boot an external server as ; default. :user-name "<NAME>", ; This is the name that Overtone will use to refer ; to you. For example, you see this being used in ; the boot message. :log-level :warn ; The log level (default is :warn). Options are: ; :error - only logs errors and exceptions ; :warn - logs :error messages and warnings ; :info - logs :error, :warn messages and ; operational info ; :debug - logs :error, :warn, :info and ; diagnostic information :sc-args ; Argument map used to boot the SuperCollider server ; with the following arguments: { :load-sdefs? 1 ; Load synthdefs on boot? 0 or 1 :nrt-output-sample-format nil ; Sample format for non-realtime mode :block-size 64 ; Block size :rendezvous? 0 ; Publish to rendezvous? 0 or 1 :ugens-paths nil ; A list of paths of ugen directories. If ; specified, the standard paths are NOT ; searched for plugins. :verbosity 0 ; Verbosity mode. 0 is normal behaviour, ; -1 suppress information messages, -2 ; suppresses informational and many error ; messages :nrt-output-filename nil ; Output filename for non-realtime mode :max-audio-bus 512 ; Number of audio bus channels :nrt-cmd-filename nil ; Command filename for non-realtime mode :realtime? 1 ; Run in realtime mode? If 0 then the ; other nrt flags must be set :max-w-buffers 64 ; Number of wire buffers :max-nodes 1024 ; Max number of executing nodes allowed in the server :nrt-input-filename nil ; Input filename for non-realtime mode :max-output-bus 8 ; Number of output bus channels :hw-buffer-size nil ; Hardware buffer size :pwd nil ; When using TCP, the session password ; must be the first command sent. :max-logins 64 ; Maximum number of named return ; addresses stored - also maximum number ; of tcp connections accepted. :hw-device-name nil ; Hardware device name :max-sdefs 1024 ; Max number of synthdefs allowed :hw-sample-rate nil ; Hardware sample rate :port 57711 ; Port number :restricted-path nil ; Prevents file-accesing OSC commands ; from accessing files outside the ; specified path. :max-input-bus 8 ; Number of input bus channels :nrt-output-header-format nil ; Header format for non-realtime mode :udp? 1 ; 1 means use UDP, 0 means use TCP :num-rand-seeds 64 ; Number of random seeds :in-streams nil ; Input streams enabled :max-buffers 1024 ; Number of sample buffers :out-streams nil ; Output streams enabled :max-control-bus 4096 ; Number of control bus channels :rt-mem-size 262144 ; Real time memory size }}
true
;; Example Overtone Config. ;; ======================== ;; ;; This lives in ~/.overtone/config.clj ;; ;; This example shouldn't be perceived as being typical - it's a ;; contrived example which uses all the possible keys (typically with ;; their default values) in an attempt to introduce their existence ;; and explain their meaning and usage. { :server :internal, ; use the internal server by default. This option is ; consulted when you use overtone.live. You may also ; specify :external to boot an external server as ; default. :user-name "PI:NAME:<NAME>END_PI", ; This is the name that Overtone will use to refer ; to you. For example, you see this being used in ; the boot message. :log-level :warn ; The log level (default is :warn). Options are: ; :error - only logs errors and exceptions ; :warn - logs :error messages and warnings ; :info - logs :error, :warn messages and ; operational info ; :debug - logs :error, :warn, :info and ; diagnostic information :sc-args ; Argument map used to boot the SuperCollider server ; with the following arguments: { :load-sdefs? 1 ; Load synthdefs on boot? 0 or 1 :nrt-output-sample-format nil ; Sample format for non-realtime mode :block-size 64 ; Block size :rendezvous? 0 ; Publish to rendezvous? 0 or 1 :ugens-paths nil ; A list of paths of ugen directories. If ; specified, the standard paths are NOT ; searched for plugins. :verbosity 0 ; Verbosity mode. 0 is normal behaviour, ; -1 suppress information messages, -2 ; suppresses informational and many error ; messages :nrt-output-filename nil ; Output filename for non-realtime mode :max-audio-bus 512 ; Number of audio bus channels :nrt-cmd-filename nil ; Command filename for non-realtime mode :realtime? 1 ; Run in realtime mode? If 0 then the ; other nrt flags must be set :max-w-buffers 64 ; Number of wire buffers :max-nodes 1024 ; Max number of executing nodes allowed in the server :nrt-input-filename nil ; Input filename for non-realtime mode :max-output-bus 8 ; Number of output bus channels :hw-buffer-size nil ; Hardware buffer size :pwd nil ; When using TCP, the session password ; must be the first command sent. :max-logins 64 ; Maximum number of named return ; addresses stored - also maximum number ; of tcp connections accepted. :hw-device-name nil ; Hardware device name :max-sdefs 1024 ; Max number of synthdefs allowed :hw-sample-rate nil ; Hardware sample rate :port 57711 ; Port number :restricted-path nil ; Prevents file-accesing OSC commands ; from accessing files outside the ; specified path. :max-input-bus 8 ; Number of input bus channels :nrt-output-header-format nil ; Header format for non-realtime mode :udp? 1 ; 1 means use UDP, 0 means use TCP :num-rand-seeds 64 ; Number of random seeds :in-streams nil ; Input streams enabled :max-buffers 1024 ; Number of sample buffers :out-streams nil ; Output streams enabled :max-control-bus 4096 ; Number of control bus channels :rt-mem-size 262144 ; Real time memory size }}
[ { "context": "5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e30175", "end": 860, "score": 0.5757166147232056, "start": 859, "tag": "KEY", "value": "5" }, { "context": "8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e3017585", "end": 862, "score": 0.5528583526611328, "start": 861, "tag": "KEY", "value": "2" }, { "context": "85a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26\"))\n", "end": 876, "score": 0.5689916014671326, "start": 869, "tag": "KEY", "value": "5f94c11" }, { "context": "7c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26\"))\n \"Hello world\"\n (| (ToBase58) (Log)\n (Fr", "end": 922, "score": 0.6689894199371338, "start": 877, "tag": "KEY", "value": "3e9402c3ac558f500199d95b6d3e301758586281dcd26" }, { "context": "055925ad1be28d6baadfd\" true)\n .hash (ECDSA.Sign \"0x1536f1d756d1abf83aaf173bc5ee3fc487c93010f18624d80bd6d4038fadd59e\") = .signature\n (Log \"Signed\")\n (ToHex) (Log \"S", "end": 1254, "score": 0.9900678992271423, "start": 1188, "tag": "KEY", "value": "0x1536f1d756d1abf83aaf173bc5ee3fc487c93010f18624d80bd6d4038fadd59e" }, { "context": " .hash (ECDSA.Recover .signature) = .pub_key1\n \"0x1536f1d756d1abf83aaf173bc5ee3fc487c93010f18624d80bd6d4038fadd59e\" (ECDSA.PublicKey) = .pub_key2\n .pub_key1 (Is .p", "end": 1433, "score": 0.9995356202125549, "start": 1367, "tag": "KEY", "value": "0x1536f1d756d1abf83aaf173bc5ee3fc487c93010f18624d80bd6d4038fadd59e" } ]
src/tests/rust.clj
fragcolor-xyz/chainblocks
12
; SPDX-License-Identifier: BSD-3-Clause ; Copyright © 2021 Fragcolor Pte. Ltd. (def Root (Node)) (schedule Root (Chain "test" "MY SECRET" (Hash.Keccak-256) = .chakey "Hello World, how are you?" (ChaChaPoly.Encrypt .chakey) (Log) (ChaChaPoly.Decrypt .chakey) (BytesToString) (Log) (Assert.Is "Hello World, how are you?" true) "" (| (Hash.Sha2-256) (ToHex) (Assert.Is "0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")) (| (Hash.Sha2-512) (ToHex) (Assert.Is "0xcf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")) (| (Hash.Sha3-256) (ToHex) (Assert.Is "0xa7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a")) (| (Hash.Sha3-512) (ToHex) (Assert.Is "0xa69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26")) "Hello world" (| (ToBase58) (Log) (FromBase58) (BytesToString) (Log) (Assert.Is "Hello world" true)) (Hash.Keccak-256) = .hash (ToHex) (Assert.Is "0xed6c11b0b5b808960df26f5bfc471d04c1995b0ffd2055925ad1be28d6baadfd" true) .hash (ECDSA.Sign "0x1536f1d756d1abf83aaf173bc5ee3fc487c93010f18624d80bd6d4038fadd59e") = .signature (Log "Signed") (ToHex) (Log "Signed Hex") .hash (ECDSA.Recover .signature) = .pub_key1 "0x1536f1d756d1abf83aaf173bc5ee3fc487c93010f18624d80bd6d4038fadd59e" (ECDSA.PublicKey) = .pub_key2 .pub_key1 (Is .pub_key2) (Log "recover worked") (Assert.Is true true) 128 (ToLEB128 :Signed false) (BytesToInts) (Log) (Assert.Is [128 1] true) (IntsToBytes) (FromLEB128 :Signed false) (Log) (Assert.Is 128 true) -1000 (ToLEB128 :Signed true) (BytesToInts) (Log) (Assert.Is [152 120] true) (IntsToBytes) (FromLEB128 :Signed true) (Log) (Assert.Is -1000 true) "hello worlds\n" (ToHex) (HexToBytes) = .payload (Count .payload) = .len "0x1220" (HexToBytes) >= .a ; sha256 multihash "0x0a" (HexToBytes) >> .b ; prefix 1 .len (ToLEB128 :Signed false) = .leblen (Count .leblen) (Math.Multiply 2) = .lenX2 .len (Math.Add 4) (Math.Add .lenX2) (ToLEB128 :Signed false) >> .b "0x080212" (HexToBytes) >> .b .leblen >> .b .payload >> .b "0x18" (HexToBytes) >> .b .leblen >> .b .b (Hash.Sha2-256) (AppendTo .a) .a (ToBase58) (Log) (Assert.Is "QmZ4tDuvesekSs4qM5ZBKpXiZGun7S2CYtEZRB3DYXkjGx" true) "../../assets/Freesample.svg" (FS.Read :Bytes true) (SVG.ToImage) (WritePNG "svgtest.png") "0x7bf19806aa6d5b31d7b7ea9e833c202e51ff8ee6311df6a036f0261f216f09ef" (| (ECDSA.PublicKey) (| (ToHex) (Log)) (| (Slice :From 1) (Hash.Keccak-256) (Slice :From 12) (ToHex) (Log "Eth Address") (Assert.Is "0x3db763bbbb1ac900eb2eb8b106218f85f9f64a13" true))) (| (ECDSA.PublicKey true) (ToHex) (Log)) "city,country,pop\nBoston,United States,4628910\nConcord,United States,42695\n" (CSV.Read) (Log) (CSV.Write) (Assert.Is "Boston,United States,4628910\nConcord,United States,42695\n" true) "\"Free trip to A,B\",\"5.89\",\"Special rate \"\"1.79\"\"\"\n" (CSV.Read :NoHeader true) (Log) (CSV.Write :NoHeader true) (Log) (Assert.Is "\"Free trip to A,B\",5.89,\"Special rate \"\"1.79\"\"\"\n" true) "city;country;pop\nBoston;United States;4628910\nConcord;United States;42695\n" (CSV.Read :NoHeader true :Separator ";") (Log) (CSV.Write :NoHeader true :Separator ";") (Assert.Is "city;country;pop\nBoston;United States;4628910\nConcord;United States;42695\n" true))) (run Root)
29482
; SPDX-License-Identifier: BSD-3-Clause ; Copyright © 2021 Fragcolor Pte. Ltd. (def Root (Node)) (schedule Root (Chain "test" "MY SECRET" (Hash.Keccak-256) = .chakey "Hello World, how are you?" (ChaChaPoly.Encrypt .chakey) (Log) (ChaChaPoly.Decrypt .chakey) (BytesToString) (Log) (Assert.Is "Hello World, how are you?" true) "" (| (Hash.Sha2-256) (ToHex) (Assert.Is "0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")) (| (Hash.Sha2-512) (ToHex) (Assert.Is "0xcf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")) (| (Hash.Sha3-256) (ToHex) (Assert.Is "0xa7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a")) (| (Hash.Sha3-512) (ToHex) (Assert.Is "0xa69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a61<KEY>b<KEY>123af1f<KEY>e<KEY>")) "Hello world" (| (ToBase58) (Log) (FromBase58) (BytesToString) (Log) (Assert.Is "Hello world" true)) (Hash.Keccak-256) = .hash (ToHex) (Assert.Is "0xed6c11b0b5b808960df26f5bfc471d04c1995b0ffd2055925ad1be28d6baadfd" true) .hash (ECDSA.Sign "<KEY>") = .signature (Log "Signed") (ToHex) (Log "Signed Hex") .hash (ECDSA.Recover .signature) = .pub_key1 "<KEY>" (ECDSA.PublicKey) = .pub_key2 .pub_key1 (Is .pub_key2) (Log "recover worked") (Assert.Is true true) 128 (ToLEB128 :Signed false) (BytesToInts) (Log) (Assert.Is [128 1] true) (IntsToBytes) (FromLEB128 :Signed false) (Log) (Assert.Is 128 true) -1000 (ToLEB128 :Signed true) (BytesToInts) (Log) (Assert.Is [152 120] true) (IntsToBytes) (FromLEB128 :Signed true) (Log) (Assert.Is -1000 true) "hello worlds\n" (ToHex) (HexToBytes) = .payload (Count .payload) = .len "0x1220" (HexToBytes) >= .a ; sha256 multihash "0x0a" (HexToBytes) >> .b ; prefix 1 .len (ToLEB128 :Signed false) = .leblen (Count .leblen) (Math.Multiply 2) = .lenX2 .len (Math.Add 4) (Math.Add .lenX2) (ToLEB128 :Signed false) >> .b "0x080212" (HexToBytes) >> .b .leblen >> .b .payload >> .b "0x18" (HexToBytes) >> .b .leblen >> .b .b (Hash.Sha2-256) (AppendTo .a) .a (ToBase58) (Log) (Assert.Is "QmZ4tDuvesekSs4qM5ZBKpXiZGun7S2CYtEZRB3DYXkjGx" true) "../../assets/Freesample.svg" (FS.Read :Bytes true) (SVG.ToImage) (WritePNG "svgtest.png") "0x7bf19806aa6d5b31d7b7ea9e833c202e51ff8ee6311df6a036f0261f216f09ef" (| (ECDSA.PublicKey) (| (ToHex) (Log)) (| (Slice :From 1) (Hash.Keccak-256) (Slice :From 12) (ToHex) (Log "Eth Address") (Assert.Is "0x3db763bbbb1ac900eb2eb8b106218f85f9f64a13" true))) (| (ECDSA.PublicKey true) (ToHex) (Log)) "city,country,pop\nBoston,United States,4628910\nConcord,United States,42695\n" (CSV.Read) (Log) (CSV.Write) (Assert.Is "Boston,United States,4628910\nConcord,United States,42695\n" true) "\"Free trip to A,B\",\"5.89\",\"Special rate \"\"1.79\"\"\"\n" (CSV.Read :NoHeader true) (Log) (CSV.Write :NoHeader true) (Log) (Assert.Is "\"Free trip to A,B\",5.89,\"Special rate \"\"1.79\"\"\"\n" true) "city;country;pop\nBoston;United States;4628910\nConcord;United States;42695\n" (CSV.Read :NoHeader true :Separator ";") (Log) (CSV.Write :NoHeader true :Separator ";") (Assert.Is "city;country;pop\nBoston;United States;4628910\nConcord;United States;42695\n" true))) (run Root)
true
; SPDX-License-Identifier: BSD-3-Clause ; Copyright © 2021 Fragcolor Pte. Ltd. (def Root (Node)) (schedule Root (Chain "test" "MY SECRET" (Hash.Keccak-256) = .chakey "Hello World, how are you?" (ChaChaPoly.Encrypt .chakey) (Log) (ChaChaPoly.Decrypt .chakey) (BytesToString) (Log) (Assert.Is "Hello World, how are you?" true) "" (| (Hash.Sha2-256) (ToHex) (Assert.Is "0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")) (| (Hash.Sha2-512) (ToHex) (Assert.Is "0xcf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")) (| (Hash.Sha3-256) (ToHex) (Assert.Is "0xa7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a")) (| (Hash.Sha3-512) (ToHex) (Assert.Is "0xa69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a61PI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PI123af1fPI:KEY:<KEY>END_PIePI:KEY:<KEY>END_PI")) "Hello world" (| (ToBase58) (Log) (FromBase58) (BytesToString) (Log) (Assert.Is "Hello world" true)) (Hash.Keccak-256) = .hash (ToHex) (Assert.Is "0xed6c11b0b5b808960df26f5bfc471d04c1995b0ffd2055925ad1be28d6baadfd" true) .hash (ECDSA.Sign "PI:KEY:<KEY>END_PI") = .signature (Log "Signed") (ToHex) (Log "Signed Hex") .hash (ECDSA.Recover .signature) = .pub_key1 "PI:KEY:<KEY>END_PI" (ECDSA.PublicKey) = .pub_key2 .pub_key1 (Is .pub_key2) (Log "recover worked") (Assert.Is true true) 128 (ToLEB128 :Signed false) (BytesToInts) (Log) (Assert.Is [128 1] true) (IntsToBytes) (FromLEB128 :Signed false) (Log) (Assert.Is 128 true) -1000 (ToLEB128 :Signed true) (BytesToInts) (Log) (Assert.Is [152 120] true) (IntsToBytes) (FromLEB128 :Signed true) (Log) (Assert.Is -1000 true) "hello worlds\n" (ToHex) (HexToBytes) = .payload (Count .payload) = .len "0x1220" (HexToBytes) >= .a ; sha256 multihash "0x0a" (HexToBytes) >> .b ; prefix 1 .len (ToLEB128 :Signed false) = .leblen (Count .leblen) (Math.Multiply 2) = .lenX2 .len (Math.Add 4) (Math.Add .lenX2) (ToLEB128 :Signed false) >> .b "0x080212" (HexToBytes) >> .b .leblen >> .b .payload >> .b "0x18" (HexToBytes) >> .b .leblen >> .b .b (Hash.Sha2-256) (AppendTo .a) .a (ToBase58) (Log) (Assert.Is "QmZ4tDuvesekSs4qM5ZBKpXiZGun7S2CYtEZRB3DYXkjGx" true) "../../assets/Freesample.svg" (FS.Read :Bytes true) (SVG.ToImage) (WritePNG "svgtest.png") "0x7bf19806aa6d5b31d7b7ea9e833c202e51ff8ee6311df6a036f0261f216f09ef" (| (ECDSA.PublicKey) (| (ToHex) (Log)) (| (Slice :From 1) (Hash.Keccak-256) (Slice :From 12) (ToHex) (Log "Eth Address") (Assert.Is "0x3db763bbbb1ac900eb2eb8b106218f85f9f64a13" true))) (| (ECDSA.PublicKey true) (ToHex) (Log)) "city,country,pop\nBoston,United States,4628910\nConcord,United States,42695\n" (CSV.Read) (Log) (CSV.Write) (Assert.Is "Boston,United States,4628910\nConcord,United States,42695\n" true) "\"Free trip to A,B\",\"5.89\",\"Special rate \"\"1.79\"\"\"\n" (CSV.Read :NoHeader true) (Log) (CSV.Write :NoHeader true) (Log) (Assert.Is "\"Free trip to A,B\",5.89,\"Special rate \"\"1.79\"\"\"\n" true) "city;country;pop\nBoston;United States;4628910\nConcord;United States;42695\n" (CSV.Read :NoHeader true :Separator ";") (Log) (CSV.Write :NoHeader true :Separator ";") (Assert.Is "city;country;pop\nBoston;United States;4628910\nConcord;United States;42695\n" true))) (run Root)
[ { "context": " (take 3 (:deck corp))) card nil))}}))\n\n(defcard \"Ad Blitz\"\n (letfn [(ab [n total]\n (when (< n t", "end": 2036, "score": 0.9991562366485596, "start": 2028, "tag": "NAME", "value": "Ad Blitz" }, { "context": "ect-completed state side eid))))))}}))\n\n(defcard \"Big Brother\"\n {:on-play\n {:req (req tagged)\n :msg \"give", "end": 12344, "score": 0.9506802558898926, "start": 12333, "tag": "NAME", "value": "Big Brother" }, { "context": " (draw state side eid 1 nil)))}})\n\n(defcard \"Hangeki\"\n {:on-play\n {:req (req (last-turn? state :r", "end": 44515, "score": 0.6264806389808655, "start": 44510, "tag": "NAME", "value": "Hange" }, { "context": " :waiting-prompt \"Runner to resolve Hangeki\"\n :prompt \"Access card? (If ", "end": 44905, "score": 0.5909397602081299, "start": 44904, "tag": "NAME", "value": "H" }, { "context": "1))}}}\n card targets))}})\n\n(defcard \"Hansei Review\"\n (let [trash-from-hq {:async true\n ", "end": 45591, "score": 0.6211221814155579, "start": 45588, "tag": "NAME", "value": "Han" }, { "context": "eid target {:unpreventable true}))}]})\n\n(defcard \"Hunter Seeker\"\n {:on-play\n {:req (req (last-turn? state :run", "end": 51981, "score": 0.9631270170211792, "start": 51968, "tag": "NAME", "value": "Hunter Seeker" }, { "context": "get-card state (:host card)) nil))}]})\n\n(defcard \"Media Blitz\"\n {:on-play\n {:async true\n :req (req ", "end": 63479, "score": 0.7360636591911316, "start": 63474, "tag": "NAME", "value": "Media" }, { "context": "d state (:host card)) nil))}]})\n\n(defcard \"Media Blitz\"\n {:on-play\n {:async true\n :req (req (pos? ", "end": 63485, "score": 0.7427449226379395, "start": 63481, "tag": "NAME", "value": "litz" }, { "context": "eid (- target (second targets))))}}}})\n\n(defcard \"Mushin No Shin\"\n {:on-play\n {:prompt \"Select a card to instal", "end": 64881, "score": 0.9695363640785217, "start": 64867, "tag": "NAME", "value": "Mushin No Shin" }, { "context": " card nil)))}})\n\n(defcard \"Shipment from Tennin\"\n {:on-play\n {:req (req (not-last-turn? state ", "end": 101813, "score": 0.8393346667289734, "start": 101807, "tag": "NAME", "value": "Tennin" }, { "context": " nil))})\n card nil))}})\n\n(defcard \"Trojan Horse\"\n {:on-play\n {:trace\n {:base 4\n :req (r", "end": 118822, "score": 0.9953275918960571, "start": 118810, "tag": "NAME", "value": "Trojan Horse" } ]
src/clj/game/cards/operations.clj
cmsd2/netrunner
0
(ns game.cards.operations (:require [game.core :refer :all] [game.utils :refer :all] [jinteki.utils :refer :all] [clojure.string :as string])) ;; Card definitions (defcard "24/7 News Cycle" {:on-play {:req (req (pos? (count (:scored corp)))) :additional-cost [:forfeit] :async true :effect (effect (continue-ability {:prompt "Select an agenda in your score area to trigger its \"when scored\" ability" :choices {:card #(and (agenda? %) (when-scored? %) (is-scored? state :corp %))} :msg (msg "trigger the \"when scored\" ability of " (:title target)) :async true :effect (effect (continue-ability (:on-score (card-def target)) target nil))} card nil))}}) (defcard "Accelerated Diagnostics" (letfn [(ad [st si e c cards] (when-let [cards (filterv #(and (operation? %) (can-pay? st si (assoc e :source c :source-type :play) c nil [:credit (play-cost st si %)])) cards)] {:async true :prompt "Select an operation to play" :choices (cancellable cards) :msg (msg "play " (:title target)) :effect (req (wait-for (play-instant state side target {:no-additional-cost true}) (let [cards (filterv #(not (same-card? % target)) cards)] (continue-ability state side (ad state side eid card cards) card nil))))}))] {:on-play {:prompt (msg "The top 3 cards of R&D are " (string/join ", " (map :title (take 3 (:deck corp)))) ".") :choices ["OK"] :async true :effect (effect (continue-ability (ad state side eid card (take 3 (:deck corp))) card nil))}})) (defcard "Ad Blitz" (letfn [(ab [n total] (when (< n total) {:async true :show-discard true :prompt "Select an Advertisement to install and rez" :choices {:card #(and (corp? %) (has-subtype? % "Advertisement") (or (in-hand? %) (in-discard? %)))} :effect (req (wait-for (corp-install state side target nil {:install-state :rezzed}) (continue-ability state side (ab (inc n) total) card nil)))}))] {:on-play {:req (req (some #(has-subtype? % "Advertisement") (concat (:discard corp) (:hand corp)))) :prompt "How many Advertisements?" :choices :credit :msg (msg "install and rez " target " Advertisements") :async true :effect (effect (continue-ability (ab 0 target) card nil))}})) (defcard "Aggressive Negotiation" {:on-play {:req (req (:scored-agenda corp-reg)) :prompt "Choose a card" :choices (req (cancellable (:deck corp) :sorted)) :msg "search R&D for a card and add it to HQ" :effect (effect (move target :hand) (shuffle! :deck))}}) (defcard "An Offer You Can't Refuse" {:on-play {:async true :prompt "Choose a server" :choices ["Archives" "R&D" "HQ"] :effect (effect (show-wait-prompt (str "Runner to decide on running " target)) (continue-ability (let [serv target] {:optional {:prompt (str "Make a run on " serv "?") :player :runner :yes-ability {:msg (str "let the Runner make a run on " serv) :async true :effect (effect (clear-wait-prompt :corp) (make-run eid serv card) (prevent-jack-out))} :no-ability {:async true :msg "add it to their score area as an agenda worth 1 agenda point" :effect (effect (clear-wait-prompt :corp) (as-agenda :corp eid card 1))}}}) card nil))}}) (defcard "Anonymous Tip" {:on-play {:msg "draw 3 cards" :async true :effect (effect (draw eid 3 nil))}}) (defcard "Archived Memories" {:on-play {:prompt "Select a card from Archives to add to HQ" :show-discard true :choices {:card #(and (corp? %) (in-discard? %))} :msg (msg "add " (if (faceup? target) (:title target) "an unseen card") " to HQ") :effect (effect (move target :hand))}}) (defcard "Argus Crackdown" {:on-play {:trash-after-resolving false} :events [{:event :successful-run :req (req (not-empty run-ices)) :msg (msg "deal 2 meat damage") :async true :effect (effect (damage eid :meat 2 {:card card}))} {:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "Ark Lockdown" {:on-play {:req (req (and (not-empty (:discard runner)) (not (zone-locked? state :runner :discard)))) :prompt "Name a card to remove all copies in the Heap from the game" :choices (req (cancellable (:discard runner) :sorted)) :msg (msg "remove all copies of " (:title target) " in the Heap from the game") :async true :effect (req (doseq [c (filter #(same-card? :title target %) (:discard runner))] (move state :runner c :rfg)) (effect-completed state side eid))}}) (defcard "Attitude Adjustment" {:on-play {:async true :effect (req (wait-for (draw state side 2 nil) (continue-ability state side {:prompt "Choose up to 2 agendas in HQ or Archives" :choices {:max 2 :card #(and (corp? %) (agenda? %) (or (in-hand? %) (in-discard? %)))} :async true :effect (req (wait-for (reveal state side targets) (wait-for (gain-credits state side (* 2 (count targets))) (doseq [c targets] (move state :corp c :deck)) (shuffle! state :corp :deck) (let [from-hq (map :title (filter in-hand? targets)) from-archives (map :title (filter in-discard? targets))] (system-msg state side (str "uses Attitude Adjustment to shuffle " (string/join " and " (filter identity [(when (not-empty from-hq) (str (string/join " and " from-hq) " from HQ")) (when (not-empty from-archives) (str (string/join " and " from-archives) " from Archives"))])) " into R&D and gain " (* 2 (count targets)) " [Credits]"))) (effect-completed state side eid))))} card nil)))}}) (defcard "Audacity" (letfn [(audacity [n] (if (< n 2) {:prompt "Choose a card on which to place an advancement" :async true :choices {:card can-be-advanced? :all true} :msg (msg "place an advancement token on " (card-str state target)) :effect (req (add-prop state :corp target :advance-counter 1 {:placed true}) (continue-ability state side (audacity (inc n)) card nil))}))] {:on-play {:req (req (and (<= 3 (count (:hand corp))) (some can-be-advanced? (all-installed state :corp)))) :async true :effect (req (system-msg state side "trashes all cards in HQ due to Audacity") (wait-for (trash-cards state side (:hand corp) {:unpreventable true}) (continue-ability state side (audacity 0) card nil)))}})) (defcard "Back Channels" {:on-play {:prompt "Select an installed card in a server to trash" :choices {:card #(and (= (last (get-zone %)) :content) (is-remote? (second (get-zone %))))} :msg (msg "trash " (card-str state target) " and gain " (* 3 (get-counters target :advancement)) " [Credits]") :async true :effect (req (wait-for (gain-credits state side (* 3 (get-counters target :advancement))) (trash state side eid target nil)))}}) (defcard "Bad Times" {:implementation "Any required program trashing is manual" :on-play {:req (req tagged) :msg "force the Runner to lose 2[mu] until the end of the turn" :effect (req (register-floating-effect state :corp card (assoc (mu+ -2) :duration :end-of-turn)) (update-mu state))}}) (defcard "Beanstalk Royalties" {:on-play {:msg "gain 3 [Credits]" :async true :effect (effect (gain-credits eid 3))}}) (defcard "Best Defense" {:on-play {:req (req (not-empty (all-installed state :runner))) :prompt (msg "Choose a Runner card with an install cost of " (count-tags state) " or less to trash") :choices {:req (req (and (runner? target) (installed? target) (not (facedown? target)) (<= (:cost target) (count-tags state))))} :msg (msg "trash " (:title target)) :async true :effect (effect (trash eid target nil))}}) (defcard "Biased Reporting" (letfn [(num-installed [state t] (count (filter #(is-type? % t) (all-active-installed state :runner))))] {:on-play {:req (req (not-empty (all-active-installed state :runner))) :prompt "Choose a card type" :choices ["Hardware" "Program" "Resource"] :async true :effect (req (let [t target n (num-installed state t)] (wait-for (resolve-ability state :runner {:waiting-prompt "Runner to choose cards to trash" :prompt (msg "Choose any number of cards of type " t " to trash") :choices {:max n :card #(and (installed? %) (is-type? % t))} :async true :effect (req (wait-for (trash-cards state :runner targets {:unpreventable true}) (let [trashed-cards async-result] (wait-for (gain-credits state :runner (count trashed-cards)) (system-msg state :runner (str "trashes " (string/join ", " (map :title trashed-cards)) " and gains " (count trashed-cards) " [Credits]")) (effect-completed state side eid)))))} card nil) (let [n (* 2 (num-installed state t))] (if (pos? n) (do (system-msg state :corp (str "uses Biased Reporting to gain " n " [Credits]")) (gain-credits state :corp eid n)) (effect-completed state side eid))))))}})) (defcard "Big Brother" {:on-play {:req (req tagged) :msg "give the Runner 2 tags" :async true :effect (effect (gain-tags :corp eid 2))}}) (defcard "Bioroid Efficiency Research" {:on-play {:req (req (some #(and (ice? %) (has-subtype? % "Bioroid") (not (rezzed? %))) (all-installed state :corp))) :choices {:card #(and (ice? %) (has-subtype? % "Bioroid") (installed? %) (not (rezzed? %)))} :msg (msg "rez " (card-str state target {:visible true}) " at no cost") :async true :effect (req (wait-for (rez state side target {:ignore-cost :all-costs}) (host state side (:card async-result) (assoc card :seen true :condition true)) (effect-completed state side eid)))} :events [{:event :end-of-encounter :condition :hosted :async true :req (req (and (same-card? (:ice context) (:host card)) (empty? (remove :broken (:subroutines (:ice context)))))) :effect (effect (system-msg :corp (str "derezzes " (:title (:ice context)) " and trashes Bioroid Efficiency Research")) (derez :corp (:ice context)) (trash :corp eid card {:unpreventable true}))}]}) (defcard "Biotic Labor" {:on-play {:msg "gain [Click][Click]" :effect (effect (gain :click 2))}}) (defcard "Blue Level Clearance" {:on-play {:msg "gain 5 [Credits] and draw 2 cards" :async true :effect (req (wait-for (gain-credits state side 5) (draw state side eid 2 nil)))}}) (defcard "BOOM!" {:on-play {:req (req (<= 2 (count-tags state))) :msg "do 7 meat damage" :async true :effect (effect (damage eid :meat 7 {:card card}))}}) (defcard "Building Blocks" {:on-play {:req (req (pos? (count (filter #(has-subtype? % "Barrier") (:hand corp))))) :prompt "Select a Barrier to install and rez" :choices {:card #(and (corp? %) (has-subtype? % "Barrier") (in-hand? %))} :msg (msg "reveal " (:title target)) :async true :effect (req (wait-for (reveal state side target) (corp-install state side eid target nil {:ignore-all-cost true :install-state :rezzed-no-cost})))}}) (defcard "Casting Call" {:on-play {:choices {:card #(and (agenda? %) (in-hand? %))} :async true :effect (req (wait-for (corp-install state side target nil {:install-state :face-up}) (let [agenda async-result] (host state side agenda (assoc card :seen true :condition true :installed true)) (system-msg state side (str "hosts Casting Call on " (:title agenda))) (effect-completed state side eid))))} :events [{:event :access :condition :hosted :async true :req (req (same-card? target (:host card))) :msg "give the Runner 2 tags" :effect (effect (gain-tags :runner eid 2))}]}) (defcard "Celebrity Gift" {:on-play {:choices {:max 5 :card #(and (corp? %) (in-hand? %))} :msg (msg "reveal " (string/join ", " (map :title (sort-by :title targets))) " and gain " (* 2 (count targets)) " [Credits]") :async true :effect (req (wait-for (reveal state side targets) (gain-credits state side eid (* 2 (count targets)))))}}) (defcard "Cerebral Cast" {:on-play {:psi {:req (req (last-turn? state :runner :successful-run)) :not-equal {:player :runner :prompt "Take 1 tag or 1 brain damage?" :choices ["1 tag" "1 brain damage"] :msg (msg "give the Runner " target) :effect (req (if (= target "1 tag") (gain-tags state :runner eid 1) (damage state side eid :brain 1 {:card card})))}}}}) (defcard "Cerebral Static" {:on-play {:msg "disable the Runner's identity" :effect (effect (disable-identity :runner))} :leave-play (effect (enable-identity :runner))}) (defcard "\"Clones are not People\"" {:events [{:event :agenda-scored :msg "add it to their score area as an agenda worth 1 agenda point" :async true :effect (req (as-agenda state :corp eid card 1))}]}) (defcard "Closed Accounts" {:on-play {:req (req tagged) :msg (msg "force the Runner to lose all " (:credit runner) " [Credits]") :async true :effect (effect (lose-credits :runner eid :all))}}) (defcard "Commercialization" {:on-play {:msg (msg "gain " (get-counters target :advancement) " [Credits]") :choices {:card #(and (ice? %) (installed? %))} :async true :effect (effect (gain-credits eid (get-counters target :advancement)))}}) (defcard "Complete Image" (letfn [(name-a-card [] {:async true :prompt "Name a Runner card" :choices {:card-title (req (and (runner? target) (not (identity? target))))} :msg (msg "name " target) :effect (effect (continue-ability (damage-ability) card targets))}) (damage-ability [] {:async true :msg "do 1 net damage" :effect (req (wait-for (damage state side :net 1 {:card card}) (let [should-continue (not (:winner @state)) cards (some #(when (same-card? (second %) card) (last %)) (turn-events state :corp :damage)) dmg (some #(when (= (:title %) target) %) cards)] (continue-ability state side (when (and should-continue dmg) (name-a-card)) card nil))))})] {:implementation "Doesn't work with Chronos Protocol: Selective Mind-mapping" :on-play {:async true :req (req (and (last-turn? state :runner :successful-run) (<= 3 (:agenda-point runner)))) :effect (effect (continue-ability (name-a-card) card nil))}})) (defcard "Consulting Visit" {:on-play {:prompt "Choose an Operation from R&D to play" :choices (req (cancellable (filter #(and (operation? %) (<= (:cost %) (:credit corp))) (:deck corp)) :sorted)) :msg (msg "search R&D for " (:title target) " and play it") :async true :effect (effect (shuffle! :deck) (system-msg "shuffles their deck") (play-instant eid target nil))}}) (defcard "Corporate Shuffle" {:on-play {:msg "shuffle all cards in HQ into R&D and draw 5 cards" :async true :effect (effect (shuffle-into-deck :hand) (draw eid 5 nil))}}) (defcard "Cyberdex Trial" {:on-play {:msg "purge virus counters" :effect (effect (purge))}}) (defcard "Death and Taxes" {:implementation "Credit gain mandatory to save on wait-prompts, adjust credits manually if credit not wanted." :events [{:event :runner-install :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))} {:event :runner-trash :req (req (installed? (:card target))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Dedication Ceremony" {:on-play {:prompt "Select a faceup card" :choices {:card #(or (and (corp? %) (rezzed? %)) (and (runner? %) (or (installed? %) (:host %)) (not (facedown? %))))} :msg (msg "place 3 advancement tokens on " (card-str state target)) :effect (effect (add-counter target :advancement 3 {:placed true}) (register-turn-flag! target :can-score (fn [state side card] (if (same-card? card target) ((constantly false) (toast state :corp "Cannot score due to Dedication Ceremony." "warning")) true))))}}) (defcard "Defective Brainchips" {:events [{:event :pre-damage :req (req (= target :brain)) :msg "do 1 additional brain damage" :once :per-turn :effect (effect (damage-bonus :brain 1))}]}) (defcard "Digital Rights Management" {:implementation "Does not prevent scoring agendas installed later in the turn" :on-play {:req (req (and (< 1 (:turn @state)) (not (some #{:hq} (:successful-run runner-reg-last))))) :prompt "Choose an Agenda" ; ToDo: When floating triggers are implemented, this should be an effect that listens to :corp-install as Clot does :choices (req (conj (vec (filter agenda? (:deck corp))) "None")) :msg (msg (if (not= "None" target) (str "add " (:title target) " to HQ and shuffle R&D") "shuffle R&D")) :effect (let [end-effect (req (system-msg state side "can not score agendas for the remainder of the turn") (swap! state assoc-in [:corp :register :cannot-score] (filter agenda? (all-installed state :corp))) (effect-completed state side eid))] (req (wait-for (resolve-ability state side (when-not (= "None" target) {:async true :effect (req (wait-for (reveal state side target) (move state side target :hand) (effect-completed state side eid)))}) card targets) (shuffle! state side :deck) (continue-ability state side {:prompt "You may install a card in HQ" :choices {:card #(and (in-hand? %) (corp? %) (not (operation? %)))} :effect (req (wait-for (resolve-ability state side (let [card-to-install target] {:prompt (str "Choose a location to install " (:title target)) :choices (remove #{"HQ" "R&D" "Archives"} (corp-install-list state target)) :async true :effect (effect (corp-install eid card-to-install target nil))}) target nil) (end-effect state side eid card targets))) :cancel-effect (effect (system-msg "does not use Digital Rights Management to install a card") (end-effect eid card targets))} card nil))))}}) (defcard "Distract the Masses" (let [shuffle-two {:async true :effect (effect (shuffle-into-rd-effect eid card 2))} trash-from-hq {:async true :prompt "Select up to 2 cards in HQ to trash" :choices {:max 2 :card #(and (corp? %) (in-hand? %))} :msg (msg "trash " (quantify (count targets) "card") " from HQ") :effect (req (wait-for (trash-cards state side targets nil) (continue-ability state side shuffle-two card nil))) :cancel-effect (effect (continue-ability shuffle-two card nil))}] {:on-play {:rfg-instead-of-trashing true :msg "give The Runner 2 [Credits]" :async true :effect (req (wait-for (gain-credits state :runner 2) (continue-ability state side trash-from-hq card nil)))}})) (defcard "Diversified Portfolio" (letfn [(number-of-non-empty-remotes [state] (count (filter #(not (empty? %)) (map #(:content (second %)) (get-remotes state)))))] {:on-play {:msg (msg "gain " (number-of-non-empty-remotes state) " [Credits]") :async true :effect (effect (gain-credits eid (number-of-non-empty-remotes state)))}})) (defcard "Divert Power" {:on-play {:prompt "Select any number of cards to derez" :choices {:card #(and (installed? %) (rezzed? %)) :max (req (count (filter rezzed? (all-installed state :corp))))} :async true :effect (req (doseq [c targets] (derez state side c)) (let [discount (* -3 (count targets))] (continue-ability state side {:async true :prompt "Select a card to rez" :choices {:card #(and (installed? %) (corp? %) (not (rezzed? %)) (not (agenda? %)))} :effect (effect (rez eid target {:cost-bonus discount}))} card nil)))}}) (defcard "Door to Door" {:events [{:event :runner-turn-begins :trace {:base 1 :label "Do 1 meat damage if Runner is tagged, or give the Runner 1 tag" :successful {:msg (msg (if tagged "do 1 meat damage" "give the Runner 1 tag")) :async true :effect (req (if tagged (damage state side eid :meat 1 {:card card}) (gain-tags state :corp eid 1)))}}}]}) (defcard "Eavesdrop" {:on-play {:choices {:card #(and (ice? %) (installed? %))} :msg (msg "give " (card-str state target {:visible false}) " additional text") :effect (effect (host target (assoc card :seen true :condition true)))} :events [{:event :encounter-ice :condition :hosted :trace {:base 3 :req (req (same-card? current-ice (:host card))) :successful {:msg "give the Runner 1 tag" :async true :effect (effect (gain-tags :runner eid 1))}}}]}) (defcard "Economic Warfare" {:on-play {:req (req (and (last-turn? state :runner :successful-run) (can-pay? state :runner (assoc eid :source card :source-type :ability) card nil :credit 4))) :msg "make the runner lose 4 [Credits]" :async true :effect (effect (lose-credits :runner eid 4))}}) (defcard "Election Day" {:on-play {:req (req (->> (get-in @state [:corp :hand]) (filter #(not (same-card? % card))) count pos?)) :msg (msg "trash all cards in HQ and draw 5 cards") :async true :effect (req (wait-for (trash-cards state side (get-in @state [:corp :hand])) (draw state side eid 5 nil)))}}) (defcard "Enforced Curfew" {:on-play {:msg "reduce the Runner's maximum hand size by 1"} :constant-effects [(runner-hand-size+ -1)]}) (defcard "Enforcing Loyalty" {:on-play {:trace {:base 3 :label "Trash a card not matching the faction of the Runner's identity" :successful {:async true :prompt "Select an installed card not matching the faction of the Runner's identity" :choices {:req (req (and (installed? target) (runner? target) (not= (:faction (:identity runner)) (:faction target))))} :msg (msg "trash " (:title target)) :effect (effect (trash eid target nil))}}}}) (defcard "Enhanced Login Protocol" {:on-play {:msg (str "uses Enhanced Login Protocol to add an additional cost of [Click]" " to make the first run not through a card ability this turn")} :constant-effects [{:type :run-additional-cost :req (req (and (no-event? state side :run #(:click-run (:cost-args (first %)))) (:click-run (second targets)))) :value [:click 1]}]}) (defcard "Exchange of Information" {:on-play {:req (req (and tagged (seq (:scored runner)) (seq (:scored corp)))) :prompt "Select a stolen agenda in the Runner's score area to swap" :choices {:req (req (in-runner-scored? state side target))} :async true :effect (effect (continue-ability (let [stolen target] {:prompt (msg "Select a scored agenda to swap for " (:title stolen)) :choices {:req (req (in-corp-scored? state side target))} :msg (msg "swap " (:title target) " for " (:title stolen)) :effect (effect (swap-agendas target stolen))}) card nil))}}) (defcard "Fast Break" {:on-play {:req (req (-> runner :scored count pos?)) :async true :effect (req (let [X (-> runner :scored count) draw {:async true :prompt "Draw how many cards?" :choices {:number (req X) :max (req X) :default (req 1)} :msg (msg "draw " target " cards") :effect (effect (draw eid target nil))} install-cards (fn install-cards [server n] {:prompt "Select a card to install" :choices {:card #(and (corp? %) (not (operation? %)) (in-hand? %) (seq (filter (fn [c] (= server c)) (corp-install-list state %))))} :effect (req (wait-for (corp-install state side target server nil) (let [server (remote->name (second (:zone async-result)))] (if (< n X) (continue-ability state side (install-cards server (inc n)) card nil) (effect-completed state side eid)))))}) select-server {:async true :prompt "Install cards in which server?" :choices (req (conj (vec (get-remote-names state)) "New remote")) :effect (effect (continue-ability (install-cards target 1) card nil))}] (wait-for (gain-credits state :corp X) (wait-for (resolve-ability state side draw card nil) (continue-ability state side select-server card nil)))))}}) (defcard "Fast Track" {:on-play {:prompt "Choose an Agenda" :choices (req (cancellable (filter agenda? (:deck corp)) :sorted)) :async true :effect (req (system-msg state side (str "adds " (:title target) " to HQ and shuffle R&D")) (wait-for (reveal state side target) (shuffle! state side :deck) (move state side target :hand) (effect-completed state side eid)))}}) (defcard "Financial Collapse" (letfn [(count-resources [state] (* 2 (count (filter resource? (all-active-installed state :runner)))))] {:on-play {:optional {:req (req (and (<= 6 (:credit runner)) (pos? (count-resources state)))) :player :runner :waiting-prompt "Runner to trash a resource to prevent Financial Collapse" :prompt "Trash a resource to prevent Financial Collapse?" :yes-ability {:prompt "Select a resource to trash" :choices {:card #(and (resource? %) (installed? %))} :async true :effect (effect (system-msg :runner (str "trashes " (:title target) " to prevent Financial Collapse")) (trash :runner eid target {:unpreventable true}))} :no-ability {:player :corp :async true :msg (msg "make the Runner lose " (count-resources state) " [Credits]") :effect (effect (lose-credits :runner eid (count-resources state)))}}}})) (defcard "Focus Group" {:on-play {:req (req (last-turn? state :runner :successful-run)) :prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :async true :effect (req (let [type target numtargets (count (filter #(= type (:type %)) (:hand runner)))] (system-msg state :corp (str "uses Focus Group to choose " target " and reveal the Runner's Grip (" (string/join ", " (map :title (sort-by :title (:hand runner)))) ")")) (wait-for (reveal state side (:hand runner)) (continue-ability state :corp (when (pos? numtargets) {:async true :prompt "Pay how many credits?" :choices {:number (req numtargets)} :effect (req (let [c target] (if (can-pay? state side (assoc eid :source card :source-type :ability) card (:title card) :credit c) (let [new-eid (make-eid state {:source card :source-type :ability})] (wait-for (pay state :corp new-eid card :credit c) (when-let [payment-str (:msg async-result)] (system-msg state :corp payment-str)) (continue-ability state :corp {:msg (msg "place " (quantify c " advancement token") " on " (card-str state target)) :choices {:card installed?} :effect (effect (add-prop target :advance-counter c {:placed true}))} card nil))) (effect-completed state side eid))))}) card nil))))}}) (defcard "Foxfire" {:on-play {:trace {:base 7 :successful {:prompt "Select 1 card to trash" :choices {:card #(and (installed? %) (or (has-subtype? % "Virtual") (has-subtype? % "Link")))} :msg "trash 1 virtual resource or link" :async true :effect (effect (system-msg (str "trashes " (:title target))) (trash eid target nil))}}}}) (defcard "Freelancer" {:on-play {:req (req tagged) :msg (msg "trash " (string/join ", " (map :title (sort-by :title targets)))) :choices {:max 2 :card #(and (installed? %) (resource? %))} :async true :effect (effect (trash-cards :runner eid targets))}}) (defcard "Friends in High Places" (let [fhelper (fn fhp [n] {:prompt "Select a card in Archives to install with Friends in High Places" :async true :show-discard true :choices {:card #(and (corp? %) (not (operation? %)) (in-discard? %))} :effect (req (wait-for (corp-install state side target nil nil) (do (system-msg state side (str "uses Friends in High Places to " (corp-install-msg target))) (if (< n 2) (continue-ability state side (fhp (inc n)) card nil) (effect-completed state side eid)))))})] {:on-play {:async true :effect (effect (continue-ability (fhelper 1) card nil))} })) (defcard "Fully Operational" (letfn [(full-servers [state] (filter #(and (not-empty (:content %)) (not-empty (:ices %))) (vals (get-remotes state)))) (repeat-choice [current total] ;; if current > total, this ability will auto-resolve and finish the chain of async methods. (when (<= current total) {:async true :prompt (str "Choice " current " of " total ": Gain 2 [Credits] or draw 2 cards? ") :choices ["Gain 2 [Credits]" "Draw 2 cards"] :msg (msg (string/lower-case target)) :effect (req (if (= target "Gain 2 [Credits]") (wait-for (gain-credits state :corp 2) (continue-ability state side (repeat-choice (inc current) total) card nil)) (wait-for (draw state :corp 2 nil) ; don't proceed with the next choice until the draw is done (continue-ability state side (repeat-choice (inc current) total) card nil))))}))] {:on-play {:msg (msg "uses Fully Operational to make " (quantify (inc (count (full-servers state))) "gain/draw decision")) :async true :effect (effect (continue-ability (repeat-choice 1 (inc (count (full-servers state)))) card nil))}})) (defcard "Game Changer" {:on-play {:rfg-instead-of-trashing true :effect (effect (gain :click (count (:scored runner))))}}) (defcard "Game Over" {:on-play {:req (req (last-turn? state :runner :stole-agenda)) :prompt "Choose a card type" :choices ["Hardware" "Program" "Resource"] :async true :effect (req (let [card-type target trashtargets (filter #(and (is-type? % card-type) (not (has-subtype? % "Icebreaker"))) (all-active-installed state :runner)) numtargets (count trashtargets) typemsg (str (when (= card-type "Program") "non-Icebreaker ") card-type (when-not (= card-type "Hardware") "s"))] (system-msg state :corp (str "chooses to trash all " typemsg)) (wait-for (resolve-ability state :runner {:async true :req (req (<= 3 (:credit runner))) :waiting-prompt "Runner to prevent trashes" :prompt (msg "Prevent any " typemsg " from being trashed? Pay 3 [Credits] per card.") :choices {:max (req (min numtargets (quot (total-available-credits state :runner eid card) 3))) :card #(and (installed? %) (is-type? % card-type) (not (has-subtype? % "Icebreaker")))} :effect (req (wait-for (pay state :runner card :credit (* 3 (count targets))) (system-msg state :runner (str (:msg async-result) " to prevent the trashing of " (string/join ", " (map :title (sort-by :title targets))))) (effect-completed state side (make-result eid targets))))} card nil) (let [prevented async-result] (when (not async-result) (system-msg state :runner (str "chooses to not prevent Corp trashing all " typemsg))) (wait-for (trash-cards state side (clojure.set/difference (set trashtargets) (set prevented))) (system-msg state :corp (str "trashes all " (when (seq prevented) "other ") typemsg ": " (string/join ", " (map :title (sort-by :title async-result))))) (wait-for (gain-bad-publicity state :corp 1) (when async-result (system-msg state :corp "takes 1 bad publicity from Game Over")) (effect-completed state side eid)))))))}}) (defcard "Genotyping" {:on-play {:msg "trash the top 2 cards of R&D" :rfg-instead-of-trashing true :async true :effect (req (wait-for (mill state :corp :corp 2) (shuffle-into-rd-effect state side eid card 4)))}}) (defcard "Green Level Clearance" {:on-play {:msg "gain 3 [Credits] and draw 1 card" :async true :effect (req (wait-for (gain-credits state side 3) (draw state side eid 1 nil)))}}) (defcard "Hangeki" {:on-play {:req (req (last-turn? state :runner :trashed-card)) :prompt "Choose an installed Corp card" :choices {:card #(and (corp? %) (installed? %))} :async true :effect (effect (continue-ability {:optional {:player :runner :async true :waiting-prompt "Runner to resolve Hangeki" :prompt "Access card? (If not, add Hangeki to your score area worth -1 agenda point)" :yes-ability {:async true :effect (req (wait-for (access-card state side target) (update! state side (assoc card :rfg-instead-of-trashing true)) (effect-completed state side eid)))} :no-ability {:async true :msg "add it to the Runner's score area as an agenda worth -1 agenda point" :effect (effect (as-agenda :runner eid card -1))}}} card targets))}}) (defcard "Hansei Review" (let [trash-from-hq {:async true :req (req (pos? (count (:hand corp)))) :prompt "Select a card in HQ to trash" :choices {:max 1 :all true :card #(and (corp? %) (in-hand? %))} :msg "trash a card from HQ" :effect (effect (trash-cards eid targets))}] {:on-play {:async true :msg "gain 10 [Credits]" :effect (req (wait-for (gain-credits state :corp 10) (continue-ability state side trash-from-hq card nil)))}})) (defcard "Hard-Hitting News" {:on-play {:trace {:base 4 :req (req (last-turn? state :runner :made-run)) :label "Give the Runner 4 tags" :successful {:async true :msg "give the Runner 4 tags" :effect (effect (gain-tags eid 4))}}}}) (defcard "Hasty Relocation" (letfn [(hr-final [chosen original] {:prompt (str "The top cards of R&D will be " (string/join ", " (map :title chosen)) ".") :choices ["Done" "Start over"] :async true :effect (req (if (= target "Done") (do (doseq [c (reverse chosen)] (move state :corp c :deck {:front true})) (clear-wait-prompt state :runner) (effect-completed state side eid)) (continue-ability state side (hr-choice original '() 3 original) card nil)))}) (hr-choice [remaining chosen n original] {:prompt "Choose a card to move next onto R&D" :choices remaining :async true :effect (req (let [chosen (cons target chosen)] (if (< (count chosen) n) (continue-ability state side (hr-choice (remove-once #(= target %) remaining) chosen n original) card nil) (continue-ability state side (hr-final chosen original) card nil))))})] {:on-play {:additional-cost [:trash-from-deck 1] :msg "trash the top card of R&D, draw 3 cards, and add 3 cards in HQ to the top of R&D" :waiting-prompt "Corp to add 3 cards in HQ to the top of R&D" :async true :effect (req (wait-for (draw state side 3 nil) (let [from (get-in @state [:corp :hand])] (continue-ability state :corp (hr-choice from '() 3 from) card nil))))}})) (defcard "Hatchet Job" {:on-play {:trace {:base 5 :successful {:choices {:card #(and (installed? %) (runner? %) (not (has-subtype? % "Virtual")))} :msg "add an installed non-virtual card to the Runner's grip" :effect (effect (move :runner target :hand true))}}}}) (defcard "Hedge Fund" {:on-play {:msg "gain 9 [Credits]" :async true :effect (effect (gain-credits eid 9))}}) (defcard "Hellion Alpha Test" {:on-play {:trace {:base 2 :req (req (last-turn? state :runner :installed-resource)) :successful {:msg "add a Resource to the top of the Stack" :choices {:card #(and (installed? %) (resource? %))} :effect (effect (move :runner target :deck {:front true}) (system-msg (str "adds " (:title target) " to the top of the Stack")))} :unsuccessful {:msg "take 1 bad publicity" :effect (effect (gain-bad-publicity :corp 1))}}}}) (defcard "Hellion Beta Test" {:on-play {:trace {:base 2 :req (req (last-turn? state :runner :trashed-card)) :label "Trash 2 installed non-program cards or take 1 bad publicity" :successful {:choices {:max (req (min 2 (count (filter #(or (facedown? %) (not (program? %))) (concat (all-installed state :corp) (all-installed state :runner)))))) :all true :card #(and (installed? %) (not (program? %)))} :msg (msg "trash " (string/join ", " (map :title (sort-by :title targets)))) :async true :effect (effect (trash-cards eid targets))} :unsuccessful {:msg "take 1 bad publicity" :async true :effect (effect (gain-bad-publicity :corp eid 1))}}}}) (defcard "Heritage Committee" {:on-play {:async true :effect (req (wait-for (draw state side 3 nil) (continue-ability state side {:prompt "Select a card in HQ to put on top of R&D" :choices {:card #(and (corp? %) (in-hand? %))} :msg "draw 3 cards and add 1 card from HQ to the top of R&D" :effect (effect (move target :deck {:front true}))} card nil)))}}) (defcard "High-Profile Target" (letfn [(dmg-count [state] (* 2 (count-tags state)))] {:on-play {:req (req tagged) :msg (msg "do " (dmg-count state) " meat damage") :async true :effect (effect (damage eid :meat (dmg-count state) {:card card}))}})) (defcard "Housekeeping" {:events [{:event :runner-install :req (req (first-event? state side :runner-install)) :player :runner :prompt "Select a card from your Grip to trash for Housekeeping" :choices {:card #(and (runner? %) (in-hand? %))} :async true :msg (msg "force the Runner to trash" (:title target) " from their grip") :effect (effect (trash :runner eid target {:unpreventable true}))}]}) (defcard "Hunter Seeker" {:on-play {:req (req (last-turn? state :runner :stole-agenda)) :prompt "Choose a card to trash" :choices {:card installed?} :msg (msg "trash " (card-str state target)) :async true :effect (effect (trash eid target nil))}}) (defcard "Hyoubu Precog Manifold" {:on-play {:trash-after-resolving false :prompt "Choose a server" :choices (req servers) :msg (msg "choose " target) :effect (effect (update! (assoc-in card [:special :hyoubu-precog-target] target)))} :events [{:event :successful-run :psi {:req (req (= (zone->name (get-in @state [:run :server])) (get-in card [:special :hyoubu-precog-target]))) :not-equal {:msg "end the run" :async true :effect (effect (end-run eid card))}}} {:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "Interns" {:on-play {:prompt "Select a card to install from Archives or HQ" :show-discard true :not-distinct true :choices {:card #(and (not (operation? %)) (corp? %) (or (in-hand? %) (in-discard? %)))} :msg (msg (corp-install-msg target)) :async true :effect (effect (corp-install eid target nil {:ignore-install-cost true}))}}) (defcard "Invasion of Privacy" (letfn [(iop [x] {:async true :req (req (->> (:hand runner) (filter #(or (resource? %) (event? %))) count pos?)) :prompt "Choose a resource or event to trash" :msg (msg "trash " (:title target)) :choices (req (cancellable (filter #(or (resource? %) (event? %)) (:hand runner)) :sorted)) :effect (req (wait-for (trash state side target nil) (if (pos? x) (continue-ability state side (iop (dec x)) card nil) (effect-completed state side eid))))})] {:on-play {:trace {:base 2 :successful {:msg "reveal the Runner's Grip and trash up to X resources or events" :async true :effect (req (wait-for (reveal state side (:hand runner)) (let [x (- target (second targets))] (system-msg state :corp (str "reveals the Runner's Grip ( " (string/join ", " (map :title (sort-by :title (:hand runner)))) " ) and can trash up to " x " resources or events")) (continue-ability state side (iop (dec x)) card nil))))} :unsuccessful {:msg "take 1 bad publicity" :async true :effect (effect (gain-bad-publicity :corp eid 1))}}}})) (defcard "IPO" {:on-play {:msg "gain 13 [Credits]" :async true :effect (effect (gain-credits eid 13))}}) (defcard "Kakurenbo" (let [install-abi {:async true :prompt "Select an agenda, asset or upgrade to install from Archives and place 2 advancement tokens on" :show-discard true :not-distinct true :choices {:card #(and (or (agenda? %) (asset? %) (upgrade? %)) (in-discard? %))} :effect (req (wait-for (corp-install state side (make-eid state {:source card :source-type :corp-install}) target nil nil) (system-msg state side "uses Kakurenbo to place 2 advancements counters on it") (add-prop state side eid async-result :advance-counter 2 {:placed true})))}] {:on-play {:prompt "Select any number of cards in HQ to trash" :rfg-instead-of-trashing true :choices {:max (req (count (:hand corp))) :card #(and (corp? %) (in-hand? %))} :msg (msg "trash " (count targets) " cards in HQ") :async true :effect (req (wait-for (trash-cards state side targets {:unpreventable true}) (doseq [c (:discard (:corp @state))] (update! state side (assoc-in c [:seen] false))) (shuffle! state :corp :discard) (continue-ability state side install-abi card nil))) :cancel-effect (req (doseq [c (:discard (:corp @state))] (update! state side (assoc-in c [:seen] false))) (shuffle! state :corp :discard) (continue-ability state side install-abi card nil))}})) (defcard "Kill Switch" (let [trace-for-brain-damage {:msg (msg "reveal that they accessed " (:title (or (:card context) target))) :trace {:base 3 :req (req (or (agenda? (:card context)) (agenda? target))) :successful {:msg "do 1 brain damage" :async true :effect (effect (damage :runner eid :brain 1 {:card card}))}}}] {:events [(assoc trace-for-brain-damage :event :access :interactive (req (agenda? target))) (assoc trace-for-brain-damage :event :agenda-scored)]})) (defcard "Lag Time" {:on-play {:effect (effect (update-all-ice))} :constant-effects [{:type :ice-strength :value 1}] :leave-play (effect (update-all-ice))}) (defcard "Lateral Growth" {:on-play {:msg "gain 4 [Credits]" :async true :effect (req (wait-for (gain-credits state side 4) (continue-ability state side {:player :corp :prompt "Select a card to install" :choices {:card #(and (corp? %) (not (operation? %)) (in-hand? %))} :async true :msg (msg (corp-install-msg target)) :effect (effect (corp-install eid target nil nil))} card nil)))}}) (defcard "Liquidation" {:on-play {:req (req (some #(and (rezzed? %) (not (agenda? %))) (all-installed state :corp))) :prompt "Select any number of rezzed cards to trash" :choices {:max (req (count (filter #(not (agenda? %)) (all-active-installed state :corp)))) :card #(and (rezzed? %) (not (agenda? %)))} :msg (msg "trash " (string/join ", " (map :title targets)) " and gain " (* (count targets) 3) " [Credits]") :async true :effect (req (wait-for (trash-cards state side targets nil) (gain-credits state side eid (* (count targets) 3))))}}) (defcard "Load Testing" {:on-play {:msg "make the Runner lose [Click] when their next turn begins"} :events [{:event :runner-turn-begins :duration :until-runner-turn-begins :msg "make the Runner lose [Click]" :effect (effect (lose :runner :click 1))}]}) (defcard "Localized Product Line" {:on-play {:prompt "Choose a card" :choices (req (cancellable (:deck corp) :sorted)) :async true :effect (effect (continue-ability (let [title (:title target) copies (filter #(= (:title %) title) (:deck corp))] {:prompt "How many copies?" :choices {:number (req (count copies))} :msg (msg "add " (quantify target "cop" "y" "ies") " of " title " to HQ") :effect (req (shuffle! state :corp :deck) (doseq [copy (take target copies)] (move state side copy :hand)))}) card nil))}}) (defcard "Manhunt" {:events [{:event :successful-run :interactive (req true) :trace {:req (req (first-event? state side :successful-run)) :base 2 :successful {:msg "give the Runner 1 tag" :async true :effect (effect (gain-tags eid 1))}}}]}) (defcard "Market Forces" (letfn [(credit-diff [state] (min (* 3 (count-tags state)) (get-in @state [:runner :credit])))] {:on-play {:req (req tagged) :msg (msg (let [c (credit-diff state)] (str "make the runner lose " c " [Credits], and gain " c " [Credits]"))) :async true :effect (req (let [c (credit-diff state)] (wait-for (lose-credits state :runner c) (gain-credits state :corp eid c))))}})) (defcard "Mass Commercialization" {:on-play {:msg (msg "gain " (* 2 (count (filter #(pos? (get-counters % :advancement)) (get-all-installed state)))) " [Credits]") :async true :effect (effect (gain-credits eid (* 2 (count (filter #(pos? (get-counters % :advancement)) (get-all-installed state))))))}}) (defcard "MCA Informant" {:on-play {:req (req (not-empty (filter #(has-subtype? % "Connection") (all-active-installed state :runner)))) :prompt "Choose a connection to host MCA Informant on" :choices {:card #(and (runner? %) (has-subtype? % "Connection") (installed? %))} :msg (msg "host it on " (card-str state target) ". The Runner has an additional tag") :effect (req (host state side (get-card state target) (assoc card :seen true :condition true)))} :constant-effects [{:type :tags :value 1}] :leave-play (req (system-msg state :corp "trashes MCA Informant")) :runner-abilities [{:label "Trash MCA Informant host" :cost [:click 1 :credit 2] :req (req (= :runner side)) :async true :effect (effect (system-msg :runner (str "spends [Click] and 2 [Credits] to trash " (card-str state (:host card)))) (trash :runner eid (get-card state (:host card)) nil))}]}) (defcard "Media Blitz" {:on-play {:async true :req (req (pos? (count (:scored runner)))) :effect (effect (continue-ability {:prompt "Select an agenda in the runner's score area" :choices {:card #(and (agenda? %) (is-scored? state :runner %))} :effect (req (update! state side (assoc card :title (:title target) :abilities (ability-init (card-def target)))) (card-init state side (get-card state card) {:resolve-effect false :init-data true}) (update! state side (assoc (get-card state card) :title "Media Blitz")))} card nil))}}) (defcard "Medical Research Fundraiser" {:on-play {:msg "gain 8 [Credits]. The Runner gains 3 [Credits]" :async true :effect (req (wait-for (gain-credits state side 8) (gain-credits state :runner eid 3)))}}) (defcard "Midseason Replacements" {:on-play {:trace {:req (req (last-turn? state :runner :stole-agenda)) :base 6 :label "Trace 6 - Give the Runner X tags" :successful {:msg "give the Runner X tags" :async true :effect (effect (system-msg (str "gives the Runner " (- target (second targets)) " tags")) (gain-tags eid (- target (second targets))))}}}}) (defcard "Mushin No Shin" {:on-play {:prompt "Select a card to install from HQ" :choices {:card #(and (not (operation? %)) (corp? %) (in-hand? %))} :async true :effect (req (wait-for (corp-install state side target "New remote" nil) (let [installed-card async-result] (add-prop state side installed-card :advance-counter 3 {:placed true}) (register-turn-flag! state side card :can-rez (fn [state side card] (if (same-card? card installed-card) ((constantly false) (toast state :corp "Cannot rez due to Mushin No Shin." "warning")) true))) (register-turn-flag! state side card :can-score (fn [state side card] (if (same-card? card installed-card) ((constantly false) (toast state :corp "Cannot score due to Mushin No Shin." "warning")) true))) (effect-completed state side eid))))}}) (defcard "Mutate" {:on-play {:req (req (some #(and (ice? %) (rezzed? %)) (all-installed state :corp))) :prompt "Select a rezzed piece of ice to trash" :choices {:card #(and (ice? %) (rezzed? %))} :async true :effect (req (let [index (card-index state target) [revealed-cards r] (split-with (complement ice?) (get-in @state [:corp :deck])) titles (->> (conj (vec revealed-cards) (first r)) (filter identity) (map :title))] (wait-for (trash state :corp target nil) (shuffle! state :corp :deck) (system-msg state side (str "uses Mutate to trash " (:title target))) (wait-for (reveal state side revealed-cards) (system-msg state side (str "reveals " (clojure.string/join ", " titles) " from R&D")) (let [ice (first r) zone (zone->name (second (get-zone target)))] (if ice (do (system-msg state side (str "uses Mutate to install and rez " (:title ice) " from R&D at no cost")) (corp-install state side eid ice zone {:ignore-all-cost true :install-state :rezzed-no-cost :display-message false :index index})) (do (system-msg state side "does not find any ICE to install from R&D") (effect-completed state side eid))))))))}}) (defcard "NAPD Cordon" {:on-play {:trash-after-resolving false} :events [{:event :pre-steal-cost :effect (req (let [counter (get-counters target :advancement)] (steal-cost-bonus state side [:credit (+ 4 (* 2 counter))])))} {:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "Neural EMP" {:on-play {:req (req (last-turn? state :runner :made-run)) :msg "do 1 net damage" :async true :effect (effect (damage eid :net 1 {:card card}))}}) (defcard "Neurospike" {:on-play {:msg (msg "do " (:scored-agenda corp-reg 0) " net damage") :async true :effect (effect (damage eid :net (:scored-agenda corp-reg 0) {:card card}))}}) (defcard "NEXT Activation Command" {:on-play {:trash-after-resolving false} :constant-effects [{:type :ice-strength :value 2} {:type :prevent-ability :req (req (let [target-card (first targets) ability (second targets)] (and (not (has-subtype? target-card "Icebreaker")) (:break ability)))) :value true}] :events [{:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "O₂ Shortage" {:on-play {:async true :effect (req (if (empty? (:hand runner)) (do (gain state :corp :click 2) (system-msg state side "uses O₂ Shortage to gain [Click][Click]") (effect-completed state side eid)) (continue-ability state side {:optional {:waiting-prompt "Runner to decide whether or not to trash a card from their Grip" :prompt "Trash 1 random card from your Grip?" :player :runner :yes-ability {:async true :effect (effect (trash-cards :runner eid (take 1 (shuffle (:hand runner))) nil))} :no-ability {:msg "gain [Click][Click]" :effect (effect (gain :corp :click 2))}}} card nil)))}}) (defcard "Observe and Destroy" {:on-play {:additional-cost [:tag 1] :req (req (and (pos? (count-real-tags state)) (< (:credit runner) 6))) :prompt "Select an installed card to trash" :choices {:card #(and (runner? %) (installed? %))} :msg (msg "remove 1 Runner tag and trash " (card-str state target)) :async true :effect (effect (trash eid target nil))}}) (defcard "Oversight AI" {:on-play {:choices {:card #(and (ice? %) (not (rezzed? %)) (= (last (get-zone %)) :ices))} :msg (msg "rez " (card-str state target) " at no cost") :async true :effect (req (wait-for (rez state side target {:ignore-cost :all-costs :no-msg true}) (host state side (:card async-result) (assoc card :seen true :condition true)) (effect-completed state side eid)))} :events [{:event :subroutines-broken :condition :hosted :async true :req (req (and (same-card? target (:host card)) (empty? (remove :broken (:subroutines target))))) :msg (msg "trash itself and " (card-str state target)) :effect (effect (trash :corp eid target {:unpreventable true}))}]}) (defcard "Patch" {:on-play {:choices {:card #(and (ice? %) (rezzed? %))} :msg (msg "give +2 strength to " (card-str state target)) :effect (req (let [card (host state side target (assoc card :seen true :condition true))] (update-ice-strength state side (get-card state target))))} :constant-effects [{:type :ice-strength :req (req (same-card? target (:host card))) :value 2}]}) (defcard "Paywall Implementation" {:events [{:event :successful-run :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Peak Efficiency" {:on-play {:msg (msg "gain " (reduce (fn [c server] (+ c (count (filter (fn [ice] (:rezzed ice)) (:ices server))))) 0 (flatten (seq (:servers corp)))) " [Credits]") :async true :effect (effect (gain-credits eid (reduce (fn [c server] (+ c (count (filter (fn [ice] (:rezzed ice)) (:ices server))))) 0 (flatten (seq (:servers corp))))))}}) (defcard "Power Grid Overload" {:on-play {:trace {:base 2 :req (req (last-turn? state :runner :made-run)) :successful {:msg "trash 1 piece of hardware" :async true :effect (effect (continue-ability (let [max-cost (- target (second targets))] {:choices {:card #(and (hardware? %) (<= (:cost %) max-cost))} :msg (msg "trash " (:title target)) :effect (effect (trash eid target nil))}) card nil))}}}}) (defcard "Power Shutdown" {:on-play {:req (req (and (last-turn? state :runner :made-run) (not-empty (filter #(or (hardware? %) (program? %)) (all-active-installed state :runner))))) :prompt "Trash how many cards from the top R&D?" :choices {:number (req (count (:deck corp)))} :msg (msg "trash " target " cards from the top of R&D") :async true :effect (req (wait-for (mill state :corp :corp target) (continue-ability state :runner (let [n target] {:async true :prompt "Select a Program or piece of Hardware to trash" :choices {:card #(and (or (hardware? %) (program? %)) (<= (:cost %) n))} :msg (msg "trash " (:title target)) :effect (effect (trash eid target nil))}) card nil)))}}) (defcard "Precognition" {:on-play {:msg "rearrange the top 5 cards of R&D" :waiting-prompt "Corp to rearrange the top cards of R&D" :async true :effect (effect (continue-ability (let [from (take 5 (:deck corp))] (when (pos? (count from)) (reorder-choice :corp :runner from '() (count from) from))) card nil))}}) (defcard "Predictive Algorithm" {:events [{:event :pre-steal-cost :effect (effect (steal-cost-bonus [:credit 2]))}]}) (defcard "Predictive Planogram" {:on-play {:prompt "Choose one" :choices (req ["Gain 3 [Credits]" "Draw 3 cards" (when tagged "Gain 3 [Credits] and draw 3 cards")]) :msg (msg (string/lower-case target)) :async true :effect (req (case target "Gain 3 [Credits]" (gain-credits state :corp eid 3) "Draw 3 cards" (draw state :corp eid 3 nil) "Gain 3 [Credits] and draw 3 cards" (wait-for (gain-credits state :corp 3) (draw state :corp eid 3 nil)) ; else (effect-completed state side eid)))}}) (defcard "Preemptive Action" {:on-play {:rfg-instead-of-trashing true :async true :effect (effect (shuffle-into-rd-effect eid card 3 true))}}) (defcard "Priority Construction" (letfn [(install-card [chosen] {:prompt "Select a remote server" :choices (req (conj (vec (get-remote-names state)) "New remote")) :async true :effect (effect (corp-install eid (assoc chosen :advance-counter 3) target {:ignore-all-cost true}))})] {:on-play {:prompt "Choose a piece of ICE in HQ to install" :choices {:card #(and (in-hand? %) (corp? %) (ice? %))} :msg "install an ICE from HQ and place 3 advancements on it" :cancel-effect (req (effect-completed state side eid)) :async true :effect (effect (continue-ability (install-card target) card nil))}})) (defcard "Product Recall" {:on-play {:prompt "Select a rezzed asset or upgrade to trash" :choices {:card #(and (rezzed? %) (or (asset? %) (upgrade? %)))} :msg (msg "trash " (card-str state target) " and gain " (trash-cost state side target) " [Credits]") :async true :effect (req (wait-for (trash state side target {:unpreventable true}) (gain-credits state :corp eid (trash-cost state side target))))}}) (defcard "Psychographics" {:on-play {:req (req tagged) :prompt "Pay how many credits?" :choices {:number (req (count-tags state))} :async true :effect (req (let [c target] (if (can-pay? state side (assoc eid :source card :source-type :ability) card (:title card) :credit c) (let [new-eid (make-eid state {:source card :source-type :ability})] (wait-for (pay state :corp new-eid card :credit c) (when-let [payment-str (:msg async-result)] (system-msg state :corp payment-str)) (continue-ability state side {:msg (msg "place " (quantify c " advancement token") " on " (card-str state target)) :choices {:card can-be-advanced?} :effect (effect (add-prop target :advance-counter c {:placed true}))} card nil))) (effect-completed state side eid))))}}) (defcard "Psychokinesis" (letfn [(choose-card [state cards] (let [allowed-cards (filter #(some #{"New remote"} (installable-servers state %)) cards)] {:prompt "Select an agenda, asset, or upgrade to install" :choices (conj (vec allowed-cards) "None") :async true :effect (req (if (or (= target "None") (ice? target) (operation? target)) (do (system-msg state side "does not install an asset, agenda, or upgrade") (effect-completed state side eid)) (continue-ability state side (install-card target) card nil)))})) (install-card [chosen] {:prompt "Select a remote server" :choices (req (conj (vec (get-remote-names state)) "New remote")) :async true :effect (effect (corp-install eid chosen target nil))})] {:on-play {:req (req (pos? (count (:deck corp)))) :msg (msg "look at the top " (quantify (count (take 5 (:deck corp))) "card") " of R&D") :waiting-prompt "Corp to look at the top cards of R&D" :async true :effect (effect (continue-ability (let [top-5 (take 5 (:deck corp))] (choose-card state top-5)) card nil))}})) (defcard "Public Trail" {:on-play {:req (req (last-turn? state :runner :successful-run)) :player :runner :msg (msg "force the Runner to " (decapitalize target)) :prompt "Pick one" :choices (req ["Take 1 tag" (when (can-pay? state :runner (assoc eid :source card :source-type :ability) card (:title card) :credit 8) "Pay 8 [Credits]")]) :async true :effect (req (if (= target "Pay 8 [Credits]") (wait-for (pay state :runner card :credit 8) (system-msg state :runner (:msg async-result)) (effect-completed state side eid)) (gain-tags state :corp eid 1)))}}) (defcard "Punitive Counterstrike" {:on-play {:trace {:base 5 :successful {:async true :msg (msg "do " (:stole-agenda runner-reg-last 0) " meat damage") :effect (effect (damage eid :meat (:stole-agenda runner-reg-last 0) {:card card}))}}}}) (defcard "Reclamation Order" {:on-play {:prompt "Select a card from Archives" :show-discard true :choices {:card #(and (corp? %) (not= (:title %) "Reclamation Order") (in-discard? %))} :msg (msg "name " (:title target)) :async true :effect (req (let [title (:title target) cards (filter #(= title (:title %)) (:discard corp)) n (count cards)] (continue-ability state side {:prompt (str "Choose how many copies of " title " to reveal") :choices {:number (req n)} :msg (msg "reveal " (quantify target "cop" "y" "ies") " of " title " from Archives" (when (pos? target) (str " and add " (if (= 1 target) "it" "them") " to HQ"))) :async true :effect (req (wait-for (reveal state side cards) (doseq [c (->> cards (sort-by :seen) reverse (take target))] (move state side c :hand)) (effect-completed state side eid)))} card nil)))}}) (defcard "Recruiting Trip" (let [rthelp (fn rt [total left selected] (if (pos? left) {:prompt (str "Choose a Sysop (" (inc (- total left)) "/" total ")") :choices (req (cancellable (filter #(and (has-subtype? % "Sysop") (not-any? #{(:title %)} selected)) (:deck corp)) :sorted)) :msg (msg "put " (:title target) " into HQ") :async true :effect (req (move state side target :hand) (continue-ability state side (rt total (dec left) (cons (:title target) selected)) card nil))} {:effect (effect (shuffle! :corp :deck)) :msg (msg "shuffle R&D")}))] {:on-play {:prompt "How many Sysops?" :choices :credit :msg (msg "search for " target " Sysops") :async true :effect (effect (continue-ability (rthelp target target []) card nil))}})) (defcard "Red Level Clearance" (let [all [{:msg "gain 2 [Credits]" :async true :effect (effect (gain-credits eid 2))} {:msg "draw 2 cards" :async true :effect (effect (draw eid 2 nil))} {:msg "gain [Click]" :effect (effect (gain :click 1))} {:prompt "Choose a non-agenda to install" :msg "install a non-agenda from hand" :choices {:card #(and (not (agenda? %)) (not (operation? %)) (in-hand? %))} :async true :effect (effect (corp-install eid target nil nil))}] can-install? (fn [hand] (seq (remove #(or (agenda? %) (operation? %)) hand))) choice (fn choice [abis chose-once] {:prompt "Choose an ability to resolve" :choices (map #(capitalize (:msg %)) abis) :async true :effect (req (let [chosen (some #(when (= target (capitalize (:msg %))) %) abis)] (if (or (not= target "Install a non-agenda from hand") (and (= target "Install a non-agenda from hand") (can-install? (:hand corp)))) (wait-for (resolve-ability state side chosen card nil) (if (false? chose-once) (continue-ability state side (choice (remove #(= % chosen) abis) true) card nil) (effect-completed state side eid))) (continue-ability state side (choice abis chose-once) card nil))))})] {:on-play {:waiting-prompt "Corp to use Red Level Clearance" :async true :effect (effect (continue-ability (choice all false) card nil))}})) (defcard "Red Planet Couriers" {:on-play {:req (req (some #(can-be-advanced? %) (all-installed state :corp))) :prompt "Select an installed card that can be advanced" :choices {:card can-be-advanced?} :async true :effect (req (let [installed (get-all-installed state) total-adv (reduce + (map #(get-counters % :advancement) installed))] (doseq [c installed] (add-prop state side c :advance-counter (- (get-counters c :advancement)) {:placed true})) (add-prop state side target :advance-counter total-adv {:placed true}) (update-all-ice state side) (system-msg state side (str "uses Red Planet Couriers to move " total-adv " advancement tokens to " (card-str state target))) (effect-completed state side eid)))}}) (defcard "Replanting" (letfn [(replant [n] {:prompt "Select a card to install with Replanting" :async true :choices {:card #(and (corp? %) (not (operation? %)) (in-hand? %))} :effect (req (wait-for (corp-install state side target nil {:ignore-all-cost true}) (if (< n 2) (continue-ability state side (replant (inc n)) card nil) (effect-completed state side eid))))})] {:on-play {:prompt "Select an installed card to add to HQ" :choices {:card #(and (corp? %) (installed? %))} :msg (msg "add " (card-str state target) " to HQ, then install 2 cards ignoring all costs") :async true :effect (req (move state side target :hand) (continue-ability state side (replant 1) card nil))}})) (defcard "Restore" {:on-play {:prompt "Select a card in Archives to install & rez" :show-discard true :choices {:card #(and (corp? %) (not (operation? %)) (in-discard? %))} :async true :effect (req (wait-for (corp-install state side target nil {:install-state :rezzed}) (let [seen (assoc target :seen true)] (system-msg state side (str "uses Restore to " (corp-install-msg seen))) (let [leftover (filter #(= (:title target) (:title %)) (-> @state :corp :discard))] (when (seq leftover) (doseq [c leftover] (move state side c :rfg)) (system-msg state side (str "removes " (count leftover) " copies of " (:title target) " from the game")))) (effect-completed state side eid))))}}) (defcard "Restoring Face" {:on-play {:prompt "Select a Sysop, Executive or Clone to trash" :msg (msg "trash " (:title target) " to remove 2 bad publicity") :choices {:card #(or (has-subtype? % "Clone") (has-subtype? % "Executive") (has-subtype? % "Sysop"))} :async true :effect (req (wait-for (lose-bad-publicity state side 2) (wait-for (resolve-ability state side (when (facedown? target) {:async true :effect (effect (reveal eid target))}) card targets) (trash state side eid target nil))))}}) (defcard "Retribution" {:on-play {:req (req (and tagged (->> (all-installed state :runner) (filter #(or (hardware? %) (program? %))) not-empty))) :prompt "Choose a program or hardware to trash" :choices {:req (req (and (installed? target) (or (program? target) (hardware? target))))} :msg (msg "trash " (card-str state target)) :async true :effect (effect (trash eid target))}}) (defcard "Restructure" {:on-play {:msg "gain 15 [Credits]" :async true :effect (effect (gain-credits eid 15))}}) (defcard "Reuse" {:on-play {:prompt (msg "Select up to " (quantify (count (:hand corp)) "card") " in HQ to trash") :choices {:max (req (count (:hand corp))) :card #(and (corp? %) (in-hand? %))} :msg (msg (let [m (count targets)] (str "trash " (quantify m "card") " and gain " (* 2 m) " [Credits]"))) :async true :effect (req (wait-for (trash-cards state side targets {:unpreventable true}) (gain-credits state side eid (* 2 (count async-result)))))}}) (defcard "Reverse Infection" {:on-play {:prompt "Choose one:" :choices ["Purge virus counters" "Gain 2 [Credits]"] :async true :effect (req (if (= target "Gain 2 [Credits]") (wait-for (gain-credits state side 2) (system-msg state side "uses Reverse Infection to gain 2 [Credits]") (effect-completed state side eid)) (let [pre-purge-virus (number-of-virus-counters state)] (purge state side) (let [post-purge-virus (number-of-virus-counters state) num-virus-purged (- pre-purge-virus post-purge-virus) num-to-trash (quot num-virus-purged 3)] (wait-for (mill state :corp :runner num-to-trash) (system-msg state side (str "uses Reverse Infection to purge " (quantify num-virus-purged "virus counter") " and trash " (quantify num-to-trash "card") " from the top of the stack")) (effect-completed state side eid))))))}}) (defcard "Rework" {:on-play {:prompt "Select a card from HQ to shuffle into R&D" :choices {:card #(and (corp? %) (in-hand? %))} :msg "shuffle a card from HQ into R&D" :effect (effect (move target :deck) (shuffle! :deck))}}) (defcard "Riot Suppression" {:on-play {:rfg-instead-of-trashing true :optional {:req (req (last-turn? state :runner :trashed-card)) :waiting-prompt "Runner to decide if they will take 1 brain damage" :prompt "Take 1 brain damage to prevent having 3 fewer clicks next turn?" :player :runner :yes-ability {:async true :effect (effect (system-msg "suffers 1 brain damage to prevent losing 3[Click] to Riot Suppression") (damage eid :brain 1 {:card card}))} :no-ability {:msg "give the Runner 3 fewer [Click] next turn" :effect (req (swap! state update-in [:runner :extra-click-temp] (fnil #(- % 3) 0)))}}}}) (defcard "Rolling Brownout" {:on-play {:msg "increase the play cost of operations and events by 1 [Credits]"} :constant-effects [{:type :play-cost :value 1}] :events [{:event :play-event :once :per-turn :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Rover Algorithm" {:on-play {:choices {:card #(and (ice? %) (rezzed? %))} :msg (msg "host it as a condition counter on " (card-str state target)) :effect (effect (host target (assoc card :installed true :seen true :condition true)) (update-ice-strength (get-card state target)))} :constant-effects [{:type :ice-strength :req (req (same-card? target (:host card))) :value (req (get-counters card :power))}] :events [{:event :pass-ice :condition :hosted :req (req (same-card? (:ice context) (:host card))) :msg (msg "add 1 power counter to itself") :effect (effect (add-counter card :power 1))}]}) (defcard "Sacrifice" {:on-play {:req (req (and (pos? (count-bad-pub state)) (some #(pos? (:agendapoints %)) (:scored corp)))) :additional-cost [:forfeit] :async true :effect (req (let [bp-lost (max 0 (min (:agendapoints (last (:rfg corp))) (count-bad-pub state)))] (system-msg state side (str "uses Sacrifice to lose " bp-lost " bad publicity and gain " bp-lost " [Credits]")) (if (pos? bp-lost) (wait-for (lose-bad-publicity state side bp-lost) (gain-credits state side eid bp-lost)) (effect-completed state side eid))))}}) (defcard "Salem's Hospitality" {:on-play {:prompt "Name a Runner card" :choices {:card-title (req (and (runner? target) (not (identity? target))))} :async true :effect (req (system-msg state side (str "uses Salem's Hospitality to reveal the Runner's Grip ( " (string/join ", " (map :title (sort-by :title (:hand runner)))) " ) and trash any copies of " target)) (let [cards (filter #(= target (:title %)) (:hand runner))] (wait-for (reveal state side cards) (trash-cards state side eid cards {:unpreventable true}))))}}) (defcard "Scapenet" {:on-play {:trace {:req (req (last-turn? state :runner :successful-run)) :base 7 :successful {:prompt "Choose an installed virtual or chip card to remove from game" :choices {:card #(and (installed? %) (or (has-subtype? % "Virtual") (has-subtype? % "Chip")))} :msg (msg "remove " (card-str state target) " from game") :async true :effect (effect (move :runner target :rfg) (effect-completed eid))}}}}) (defcard "Scarcity of Resources" {:on-play {:msg "increase the install cost of resources by 2"} :constant-effects [{:type :install-cost :req (req (resource? target)) :value 2}]}) (defcard "Scorched Earth" {:on-play {:req (req tagged) :msg "do 4 meat damage" :async true :effect (effect (damage eid :meat 4 {:card card}))}}) (defcard "SEA Source" {:on-play {:trace {:base 3 :req (req (last-turn? state :runner :successful-run)) :label "Trace 3 - Give the Runner 1 tag" :successful {:msg "give the Runner 1 tag" :async true :effect (effect (gain-tags :corp eid 1))}}}}) (defcard "Seamless Launch" {:on-play {:prompt "Select target" :req (req (some #(and (corp? %) (installed? %) (not (= :this-turn (installed? %)))) (all-installed state :corp))) :choices {:card #(and (corp? %) (installed? %) (not (= :this-turn (installed? %))))} :msg (msg "place 2 advancement tokens on " (card-str state target)) :async true :effect (effect (add-prop eid target :advance-counter 2 {:placed true}))}}) (defcard "Secure and Protect" {:on-play {:interactive (req true) :waiting-prompt "Corp to use Secure and Protect" :async true :effect (req (if (seq (filter ice? (:deck corp))) (continue-ability state side {:async true :prompt "Choose a piece of ice" :choices (req (filter ice? (:deck corp))) :effect (effect (continue-ability (let [chosen-ice target] {:async true :prompt (str "Select where to install " (:title chosen-ice)) :choices ["Archives" "R&D" "HQ"] :msg (msg "reveal " (:title chosen-ice) " and install it, paying 3 [Credit] less") :effect (req (wait-for (reveal state side chosen-ice) (shuffle! state side :deck) (corp-install state side eid chosen-ice target {:cost-bonus -3})))}) card nil))} card nil) (do (shuffle! state side :deck) (effect-completed state side eid))))}}) (defcard "Self-Growth Program" {:on-play {:req (req tagged) :prompt "Select two installed Runner cards" :choices {:card #(and (installed? %) (runner? %)) :max 2} :msg (msg (str "move " (string/join ", " (map :title targets)) " to the Runner's grip")) :effect (req (doseq [c targets] (move state :runner c :hand)))}}) (defcard "Service Outage" {:on-play {:msg "add a cost of 1 [Credit] for the Runner to make the first run each turn"} :constant-effects [{:type :run-additional-cost :req (req (no-event? state side :run)) :value [:credit 1]}]}) (defcard "Shipment from Kaguya" {:on-play {:choices {:max 2 :card #(and (corp? %) (installed? %) (can-be-advanced? %))} :msg (msg "place 1 advancement token on " (count targets) " cards") :effect (req (doseq [t targets] (add-prop state :corp t :advance-counter 1 {:placed true})))}}) (defcard "Shipment from MirrorMorph" (letfn [(shelper [n] (when (< n 3) {:async true :prompt "Select a card to install with Shipment from MirrorMorph" :choices {:card #(and (corp? %) (not (operation? %)) (in-hand? %))} :effect (req (wait-for (corp-install state side target nil nil) (continue-ability state side (shelper (inc n)) card nil)))}))] {:on-play {:async true :effect (effect (continue-ability (shelper 0) card nil))}})) (defcard "Shipment from SanSan" {:on-play {:choices ["0" "1" "2"] :prompt "How many advancement tokens?" :async true :effect (req (let [c (str->int target)] (continue-ability state side {:choices {:card can-be-advanced?} :msg (msg "place " c " advancement tokens on " (card-str state target)) :effect (effect (add-prop :corp target :advance-counter c {:placed true}))} card nil)))}}) (defcard "Shipment from Tennin" {:on-play {:req (req (not-last-turn? state :runner :successful-run)) :choices {:card #(and (corp? %) (installed? %))} :msg (msg "place 2 advancement tokens on " (card-str state target)) :effect (effect (add-prop target :advance-counter 2 {:placed true}))}}) (defcard "Shoot the Moon" (letfn [(rez-helper [ice] (when (seq ice) {:async true :effect (req (wait-for (rez state side (first ice) {:ignore-cost :all-costs}) (continue-ability state side (rez-helper (rest ice)) card nil)))}))] {:on-play {:req (req tagged) :choices {:card #(and (ice? %) (not (rezzed? %))) :max (req (min (count-tags state) (reduce (fn [c server] (+ c (count (filter #(not (:rezzed %)) (:ices server))))) 0 (flatten (seq (:servers corp))))))} :async true :effect (effect (continue-ability (rez-helper targets) card nil))}})) (defcard "Snatch and Grab" {:on-play {:trace {:base 3 :successful {:waiting-prompt "Corp to use Snatch and Grab" :msg "trash a connection" :choices {:card #(has-subtype? % "Connection")} :async true :effect (effect (continue-ability (let [c target] {:optional {:player :runner :waiting-prompt "Runner to decide if they will take 1 tag" :prompt (str "Take 1 tag to prevent " (:title c) " from being trashed?") :yes-ability {:async true :msg (msg "take 1 tag to prevent " (:title c) " from being trashed") :effect (effect (gain-tags :runner eid 1 {:unpreventable true}))} :no-ability {:async true :msg (msg "trash " (:title c)) :effect (effect (trash :corp eid c nil))}}}) card nil))}}}}) (defcard "Special Report" {:on-play {:prompt "Select any number of cards in HQ to shuffle into R&D" :choices {:max (req (count (:hand corp))) :card #(and (corp? %) (in-hand? %))} :msg (msg "shuffle " (count targets) " cards in HQ into R&D and draw " (count targets) " cards") :async true :effect (req (doseq [c targets] (move state side c :deck)) (shuffle! state side :deck) (draw state side eid (count targets) nil))}}) (defcard "Sprint" {:on-play {:async true :effect (req (wait-for (draw state side 3 nil) (system-msg state side (str "uses Sprint to draw " (quantify (count async-result) "card"))) (continue-ability state side {:prompt "Select 2 cards in HQ to shuffle" :choices {:max 2 :card #(and (corp? %) (in-hand? %))} :msg "shuffles 2 cards from HQ into R&D" :effect (req (doseq [c targets] (move state side c :deck)) (shuffle! state side :deck))} card nil)))}}) (defcard "Standard Procedure" {:on-play {:req (req (last-turn? state :runner :successful-run)) :prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :msg (msg "name " target ", revealing " (string/join ", " (map :title (:hand runner))) " in the Runner's Grip, and gains " (* 2 (count (filter #(is-type? % target) (:hand runner)))) " [Credits]") :async true :effect (req (wait-for (reveal state side (:hand runner)) (gain-credits state :corp eid (* 2 (count (filter #(is-type? % target) (:hand runner)))))))}}) (defcard "Stock Buy-Back" {:on-play {:msg (msg "gain " (* 3 (count (:scored runner))) " [Credits]") :async true :effect (effect (gain-credits eid (* 3 (count (:scored runner)))))}}) (defcard "Sub Boost" (let [new-sub {:label "[Sub Boost]: End the run"}] {:sub-effect {:label "End the run" :msg "end the run" :async true :effect (effect (end-run eid card))} :on-play {:choices {:card #(and (ice? %) (rezzed? %))} :msg (msg "make " (card-str state target) " gain Barrier and \"[Subroutine] End the run\"") :effect (req (add-extra-sub! state :corp (get-card state target) new-sub (:cid card)) (host state side (get-card state target) (assoc card :seen true :condition true)))} :constant-effects [{:type :gain-subtype :req (req (and (same-card? target (:host card)) (rezzed? target))) :value "Barrier"}] :leave-play (req (remove-extra-subs! state :corp (:host card) (:cid card))) :events [{:event :rez :req (req (same-card? (:card context) (:host card))) :effect (req (add-extra-sub! state :corp (get-card state (:card context)) new-sub (:cid card)))}]})) (defcard "Subcontract" (letfn [(sc [i sccard] {:prompt "Select an operation in HQ to play" :choices {:card #(and (corp? %) (operation? %) (in-hand? %))} :async true :msg (msg "play " (:title target)) :effect (req (wait-for (play-instant state side target nil) (if (and (not (get-in @state [:corp :register :terminal])) (< i 2)) (continue-ability state side (sc (inc i) sccard) sccard nil) (effect-completed state side eid))))})] {:on-play {:req (req tagged) :async true :effect (effect (continue-ability (sc 1 card) card nil))}})) (defcard "Subliminal Messaging" {:on-play {:msg "gain 1 [Credits]" :async true :effect (req (wait-for (gain-credits state side 1) (continue-ability state side {:once :per-turn :once-key :subliminal-messaging :msg "gain [Click]" :effect (effect (gain :corp :click 1))} card nil)))} :events [{:event :corp-phase-12 :location :discard :optional {:req (req (not-last-turn? state :runner :made-run)) :prompt "Add Subliminal Messaging to HQ?" :yes-ability {:msg "add Subliminal Messaging to HQ" :effect (effect (move card :hand))}}}]}) (defcard "Success" (letfn [(advance-n-times [state side eid card target n] (if (pos? n) (wait-for (advance state :corp (make-eid state {:source card}) (get-card state target) :no-cost) (advance-n-times state side eid card target (dec n))) (effect-completed state side eid)))] {:on-play {:additional-cost [:forfeit] :choices {:card can-be-advanced?} :msg (msg "advance " (card-str state target) " " (quantify (get-advancement-requirement (cost-target eid :forfeit)) "time")) :async true :effect (effect (advance-n-times eid card target (get-advancement-requirement (cost-target eid :forfeit))))}})) (defcard "Successful Demonstration" {:on-play {:req (req (last-turn? state :runner :unsuccessful-run)) :msg "gain 7 [Credits]" :async true :effect (effect (gain-credits eid 7))}}) (defcard "Sunset" (letfn [(sun [serv] {:prompt "Select two pieces of ICE to swap positions" :choices {:card #(and (= serv (get-zone %)) (ice? %)) :max 2} :async true :effect (req (if (= (count targets) 2) (do (swap-ice state side (first targets) (second targets)) (system-msg state side (str "uses Sunset to swap " (card-str state (first targets)) " with " (card-str state (second targets)))) (continue-ability state side (sun serv) card nil)) (do (system-msg state side "has finished rearranging ICE") (effect-completed state side eid))))})] {:on-play {:prompt "Choose a server" :choices (req servers) :msg (msg "rearrange ICE protecting " target) :async true :effect (req (let [serv (conj (server->zone state target) :ices)] (continue-ability state side (sun serv) card nil)))}})) (defcard "Surveillance Sweep" {:events [{:event :pre-init-trace :req (req run) :effect (req (swap! state assoc-in [:trace :player] :runner))}]}) (defcard "Sweeps Week" {:on-play {:msg (msg "gain " (count (:hand runner)) " [Credits]") :async true :effect (effect (gain-credits eid (count (:hand runner))))}}) (defcard "SYNC Rerouting" {:on-play {:trash-after-resolving false} :events [{:event :run :async true :msg (msg "force the Runner to " (decapitalize target)) :player :runner :prompt "Pay 4 [Credits] or take 1 tag?" :choices ["Pay 4 [Credits]" "Take 1 tag"] :effect (req (if (= target "Pay 4 [Credits]") (wait-for (pay state :runner card :credit 4) (system-msg state :runner (:msg async-result)) (effect-completed state side eid)) (gain-tags state :corp eid 1 nil)))} {:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "Targeted Marketing" (let [gaincr {:req (req (= (:title (:card context)) (get-in card [:special :marketing-target]))) :async true :msg (msg "gain 10 [Credits] from " (:marketing-target card)) :effect (effect (gain-credits :corp eid 10))}] {:on-play {:prompt "Name a Runner card" :choices {:card-title (req (and (runner? target) (not (identity? target))))} :effect (effect (update! (assoc-in card [:special :marketing-target] target)) (system-msg (str "uses Targeted Marketing to name " target)))} :events [(assoc gaincr :event :runner-install) (assoc gaincr :event :play-event)]})) (defcard "The All-Seeing I" (let [trash-all-resources {:msg "trash all resources" :async true :effect (effect (trash-cards :corp eid (filter resource? (all-active-installed state :runner))))}] {:on-play {:req (req tagged) :async true :effect (effect (continue-ability (if (pos? (count-bad-pub state)) {:optional {:player :runner :prompt "Remove 1 bad publicity to prevent all resources from being trashed?" :yes-ability {:msg "remove 1 bad publicity, preventing all resources from being trashed" :async true :effect (effect (lose-bad-publicity eid 1))} :no-ability trash-all-resources}} trash-all-resources) card nil))}})) (defcard "Threat Assessment" {:on-play {:req (req (last-turn? state :runner :trashed-card)) :prompt "Select an installed Runner card" :choices {:card #(and (runner? %) (installed? %))} :rfg-instead-of-trashing true :async true :effect (effect (continue-ability (let [chosen target] {:player :runner :waiting-prompt "Runner to resolve Threat Assessment" :prompt (str "Add " (:title chosen) " to the top of the Stack or take 2 tags?") :choices [(str "Move " (:title chosen)) "Take 2 tags"] :async true :effect (req (if (= target "Take 2 tags") (do (system-msg state side "chooses to take 2 tags") (gain-tags state :runner eid 2)) (do (system-msg state side (str "chooses to move " (:title chosen) " to the Stack")) (move state :runner chosen :deck {:front true}) (effect-completed state side eid))))}) card nil))}}) (defcard "Threat Level Alpha" {:on-play {:trace {:base 1 :successful {:label "Give the Runner X tags" :async true :effect (req (let [tags (max 1 (count-tags state))] (gain-tags state :corp eid tags) (system-msg state side (str "uses Threat Level Alpha to give the Runner " (quantify tags "tag")))))}}}}) (defcard "Too Big to Fail" {:on-play {:req (req (< (:credit corp) 10)) :msg "gain 7 [Credits] and take 1 bad publicity" :async true :effect (req (wait-for (gain-credits state side 7) (gain-bad-publicity state :corp eid 1)))}}) (defcard "Traffic Accident" {:on-play {:req (req (<= 2 (count-tags state))) :msg "do 2 meat damage" :async true :effect (effect (damage eid :meat 2 {:card card}))}}) (defcard "Transparency Initiative" {:constant-effects [{:type :gain-subtype :req (req (and (same-card? target (:host card)) (rezzed? target))) :value "Public"}] :on-play {:choices {:card #(and (agenda? %) (installed? %) (not (faceup? %)))} :effect (req (let [target (update! state side (assoc target :seen true :rezzed true)) card (host state side target (assoc card :seen true :condition true))] (register-events state side card [{:event :advance :location :hosted :req (req (same-card? (:host card) target)) :async true :msg "gain 1 [Credit]" :effect (effect (gain-credits eid 1))}])))}}) (defcard "Trick of Light" {:on-play {:req (req (let [advanceable (some can-be-advanced? (get-all-installed state)) advanced (some #(get-counters % :advancement) (get-all-installed state))] (and advanceable advanced))) :choices {:card #(and (pos? (get-counters % :advancement)) (installed? %))} :async true :effect (effect (continue-ability (let [fr target] {:async true :prompt "Move how many advancement tokens?" :choices (take (inc (get-counters fr :advancement)) ["0" "1" "2"]) :effect (effect (continue-ability (let [c (str->int target)] {:prompt "Move to where?" :choices {:card #(and (not (same-card? fr %)) (can-be-advanced? %))} :msg (msg "move " c " advancement tokens from " (card-str state fr) " to " (card-str state target)) :effect (effect (add-prop :corp target :advance-counter c {:placed true}) (add-prop :corp fr :advance-counter (- c) {:placed true}))}) card nil))}) card nil))}}) (defcard "Trojan Horse" {:on-play {:trace {:base 4 :req (req (:accessed-cards runner-reg-last)) :label "Trace 4 - Trash a program" :successful {:async true :effect (req (let [exceed (- target (second targets))] (continue-ability state side {:async true :prompt (str "Select a program with an install cost of no more than " exceed "[Credits]") :choices {:card #(and (program? %) (installed? %) (>= exceed (:cost %)))} :msg (msg "trash " (card-str state target)) :effect (effect (trash eid target nil))} card nil)))}}}}) (defcard "Ultraviolet Clearance" {:on-play {:async true :effect (req (wait-for (gain-credits state side 10) (wait-for (draw state side 4 nil) (continue-ability state side {:prompt "Choose a card in HQ to install" :choices {:card #(and (in-hand? %) (corp? %) (not (operation? %)))} :msg "gain 10 [Credits], draw 4 cards, and install 1 card from HQ" :cancel-effect (req (effect-completed state side eid)) :async true :effect (effect (corp-install eid target nil nil))} card nil))))}}) (defcard "Under the Bus" {:on-play {:req (req (and (last-turn? state :runner :accessed-cards) (not-empty (filter #(and (resource? %) (has-subtype? % "Connection")) (all-active-installed state :runner))))) :prompt "Choose a connection to trash" :choices {:card #(and (runner? %) (resource? %) (has-subtype? % "Connection") (installed? %))} :msg (msg "trash " (:title target) " and take 1 bad publicity") :async true :effect (req (wait-for (trash state side target nil) (gain-bad-publicity state :corp eid 1)))}}) (defcard "Violet Level Clearance" {:on-play {:msg "gain 8 [Credits] and draw 4 cards" :async true :effect (req (wait-for (gain-credits state side 8) (draw state side eid 4 nil)))}}) (defcard "Voter Intimidation" {:on-play {:psi {:req (req (seq (:scored runner))) :not-equal {:player :corp :async true :prompt "Select a resource to trash" :choices {:card #(and (installed? %) (resource? %))} :msg (msg "trash " (:title target)) :effect (effect (trash eid target nil))}}}}) (defcard "Wake Up Call" {:on-play {:rfg-instead-of-trashing true :req (req (last-turn? state :runner :trashed-card)) :prompt "Select a piece of hardware or non-virtual resource" :choices {:card #(or (hardware? %) (and (resource? %) (not (has-subtype? % "Virtual"))))} :async true :effect (effect (continue-ability (let [chosen target wake card] {:player :runner :waiting-prompt "Runner to resolve Wake Up Call" :prompt (str "Trash " (:title chosen) " or suffer 4 meat damage?") :choices [(str "Trash " (:title chosen)) "4 meat damage"] :async true :effect (req (if (= target "4 meat damage") (do (system-msg state side "chooses to suffer meat damage") (damage state side eid :meat 4 {:card wake :unboostable true})) (do (system-msg state side (str "chooses to trash " (:title chosen))) (trash state side eid chosen nil))))}) card nil))}}) (defcard "Wetwork Refit" (let [new-sub {:label "[Wetwork Refit] Do 1 brain damage"}] {:on-play {:choices {:card #(and (ice? %) (has-subtype? % "Bioroid") (rezzed? %))} :msg (msg "give " (card-str state target) " \"[Subroutine] Do 1 brain damage\" before all its other subroutines") :effect (req (add-extra-sub! state :corp target new-sub (:cid card) {:front true}) (host state side (get-card state target) (assoc card :seen true :condition true)))} :sub-effect (do-brain-damage 1) :leave-play (req (remove-extra-subs! state :corp (:host card) (:cid card))) :events [{:event :rez :req (req (same-card? (:card context) (:host card))) :effect (req (add-extra-sub! state :corp (get-card state (:card context)) new-sub (:cid card) {:front true}))}]})) (defcard "Witness Tampering" {:on-play {:msg "remove 2 bad publicity" :effect (effect (lose-bad-publicity 2))}})
28710
(ns game.cards.operations (:require [game.core :refer :all] [game.utils :refer :all] [jinteki.utils :refer :all] [clojure.string :as string])) ;; Card definitions (defcard "24/7 News Cycle" {:on-play {:req (req (pos? (count (:scored corp)))) :additional-cost [:forfeit] :async true :effect (effect (continue-ability {:prompt "Select an agenda in your score area to trigger its \"when scored\" ability" :choices {:card #(and (agenda? %) (when-scored? %) (is-scored? state :corp %))} :msg (msg "trigger the \"when scored\" ability of " (:title target)) :async true :effect (effect (continue-ability (:on-score (card-def target)) target nil))} card nil))}}) (defcard "Accelerated Diagnostics" (letfn [(ad [st si e c cards] (when-let [cards (filterv #(and (operation? %) (can-pay? st si (assoc e :source c :source-type :play) c nil [:credit (play-cost st si %)])) cards)] {:async true :prompt "Select an operation to play" :choices (cancellable cards) :msg (msg "play " (:title target)) :effect (req (wait-for (play-instant state side target {:no-additional-cost true}) (let [cards (filterv #(not (same-card? % target)) cards)] (continue-ability state side (ad state side eid card cards) card nil))))}))] {:on-play {:prompt (msg "The top 3 cards of R&D are " (string/join ", " (map :title (take 3 (:deck corp)))) ".") :choices ["OK"] :async true :effect (effect (continue-ability (ad state side eid card (take 3 (:deck corp))) card nil))}})) (defcard "<NAME>" (letfn [(ab [n total] (when (< n total) {:async true :show-discard true :prompt "Select an Advertisement to install and rez" :choices {:card #(and (corp? %) (has-subtype? % "Advertisement") (or (in-hand? %) (in-discard? %)))} :effect (req (wait-for (corp-install state side target nil {:install-state :rezzed}) (continue-ability state side (ab (inc n) total) card nil)))}))] {:on-play {:req (req (some #(has-subtype? % "Advertisement") (concat (:discard corp) (:hand corp)))) :prompt "How many Advertisements?" :choices :credit :msg (msg "install and rez " target " Advertisements") :async true :effect (effect (continue-ability (ab 0 target) card nil))}})) (defcard "Aggressive Negotiation" {:on-play {:req (req (:scored-agenda corp-reg)) :prompt "Choose a card" :choices (req (cancellable (:deck corp) :sorted)) :msg "search R&D for a card and add it to HQ" :effect (effect (move target :hand) (shuffle! :deck))}}) (defcard "An Offer You Can't Refuse" {:on-play {:async true :prompt "Choose a server" :choices ["Archives" "R&D" "HQ"] :effect (effect (show-wait-prompt (str "Runner to decide on running " target)) (continue-ability (let [serv target] {:optional {:prompt (str "Make a run on " serv "?") :player :runner :yes-ability {:msg (str "let the Runner make a run on " serv) :async true :effect (effect (clear-wait-prompt :corp) (make-run eid serv card) (prevent-jack-out))} :no-ability {:async true :msg "add it to their score area as an agenda worth 1 agenda point" :effect (effect (clear-wait-prompt :corp) (as-agenda :corp eid card 1))}}}) card nil))}}) (defcard "Anonymous Tip" {:on-play {:msg "draw 3 cards" :async true :effect (effect (draw eid 3 nil))}}) (defcard "Archived Memories" {:on-play {:prompt "Select a card from Archives to add to HQ" :show-discard true :choices {:card #(and (corp? %) (in-discard? %))} :msg (msg "add " (if (faceup? target) (:title target) "an unseen card") " to HQ") :effect (effect (move target :hand))}}) (defcard "Argus Crackdown" {:on-play {:trash-after-resolving false} :events [{:event :successful-run :req (req (not-empty run-ices)) :msg (msg "deal 2 meat damage") :async true :effect (effect (damage eid :meat 2 {:card card}))} {:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "Ark Lockdown" {:on-play {:req (req (and (not-empty (:discard runner)) (not (zone-locked? state :runner :discard)))) :prompt "Name a card to remove all copies in the Heap from the game" :choices (req (cancellable (:discard runner) :sorted)) :msg (msg "remove all copies of " (:title target) " in the Heap from the game") :async true :effect (req (doseq [c (filter #(same-card? :title target %) (:discard runner))] (move state :runner c :rfg)) (effect-completed state side eid))}}) (defcard "Attitude Adjustment" {:on-play {:async true :effect (req (wait-for (draw state side 2 nil) (continue-ability state side {:prompt "Choose up to 2 agendas in HQ or Archives" :choices {:max 2 :card #(and (corp? %) (agenda? %) (or (in-hand? %) (in-discard? %)))} :async true :effect (req (wait-for (reveal state side targets) (wait-for (gain-credits state side (* 2 (count targets))) (doseq [c targets] (move state :corp c :deck)) (shuffle! state :corp :deck) (let [from-hq (map :title (filter in-hand? targets)) from-archives (map :title (filter in-discard? targets))] (system-msg state side (str "uses Attitude Adjustment to shuffle " (string/join " and " (filter identity [(when (not-empty from-hq) (str (string/join " and " from-hq) " from HQ")) (when (not-empty from-archives) (str (string/join " and " from-archives) " from Archives"))])) " into R&D and gain " (* 2 (count targets)) " [Credits]"))) (effect-completed state side eid))))} card nil)))}}) (defcard "Audacity" (letfn [(audacity [n] (if (< n 2) {:prompt "Choose a card on which to place an advancement" :async true :choices {:card can-be-advanced? :all true} :msg (msg "place an advancement token on " (card-str state target)) :effect (req (add-prop state :corp target :advance-counter 1 {:placed true}) (continue-ability state side (audacity (inc n)) card nil))}))] {:on-play {:req (req (and (<= 3 (count (:hand corp))) (some can-be-advanced? (all-installed state :corp)))) :async true :effect (req (system-msg state side "trashes all cards in HQ due to Audacity") (wait-for (trash-cards state side (:hand corp) {:unpreventable true}) (continue-ability state side (audacity 0) card nil)))}})) (defcard "Back Channels" {:on-play {:prompt "Select an installed card in a server to trash" :choices {:card #(and (= (last (get-zone %)) :content) (is-remote? (second (get-zone %))))} :msg (msg "trash " (card-str state target) " and gain " (* 3 (get-counters target :advancement)) " [Credits]") :async true :effect (req (wait-for (gain-credits state side (* 3 (get-counters target :advancement))) (trash state side eid target nil)))}}) (defcard "Bad Times" {:implementation "Any required program trashing is manual" :on-play {:req (req tagged) :msg "force the Runner to lose 2[mu] until the end of the turn" :effect (req (register-floating-effect state :corp card (assoc (mu+ -2) :duration :end-of-turn)) (update-mu state))}}) (defcard "Beanstalk Royalties" {:on-play {:msg "gain 3 [Credits]" :async true :effect (effect (gain-credits eid 3))}}) (defcard "Best Defense" {:on-play {:req (req (not-empty (all-installed state :runner))) :prompt (msg "Choose a Runner card with an install cost of " (count-tags state) " or less to trash") :choices {:req (req (and (runner? target) (installed? target) (not (facedown? target)) (<= (:cost target) (count-tags state))))} :msg (msg "trash " (:title target)) :async true :effect (effect (trash eid target nil))}}) (defcard "Biased Reporting" (letfn [(num-installed [state t] (count (filter #(is-type? % t) (all-active-installed state :runner))))] {:on-play {:req (req (not-empty (all-active-installed state :runner))) :prompt "Choose a card type" :choices ["Hardware" "Program" "Resource"] :async true :effect (req (let [t target n (num-installed state t)] (wait-for (resolve-ability state :runner {:waiting-prompt "Runner to choose cards to trash" :prompt (msg "Choose any number of cards of type " t " to trash") :choices {:max n :card #(and (installed? %) (is-type? % t))} :async true :effect (req (wait-for (trash-cards state :runner targets {:unpreventable true}) (let [trashed-cards async-result] (wait-for (gain-credits state :runner (count trashed-cards)) (system-msg state :runner (str "trashes " (string/join ", " (map :title trashed-cards)) " and gains " (count trashed-cards) " [Credits]")) (effect-completed state side eid)))))} card nil) (let [n (* 2 (num-installed state t))] (if (pos? n) (do (system-msg state :corp (str "uses Biased Reporting to gain " n " [Credits]")) (gain-credits state :corp eid n)) (effect-completed state side eid))))))}})) (defcard "<NAME>" {:on-play {:req (req tagged) :msg "give the Runner 2 tags" :async true :effect (effect (gain-tags :corp eid 2))}}) (defcard "Bioroid Efficiency Research" {:on-play {:req (req (some #(and (ice? %) (has-subtype? % "Bioroid") (not (rezzed? %))) (all-installed state :corp))) :choices {:card #(and (ice? %) (has-subtype? % "Bioroid") (installed? %) (not (rezzed? %)))} :msg (msg "rez " (card-str state target {:visible true}) " at no cost") :async true :effect (req (wait-for (rez state side target {:ignore-cost :all-costs}) (host state side (:card async-result) (assoc card :seen true :condition true)) (effect-completed state side eid)))} :events [{:event :end-of-encounter :condition :hosted :async true :req (req (and (same-card? (:ice context) (:host card)) (empty? (remove :broken (:subroutines (:ice context)))))) :effect (effect (system-msg :corp (str "derezzes " (:title (:ice context)) " and trashes Bioroid Efficiency Research")) (derez :corp (:ice context)) (trash :corp eid card {:unpreventable true}))}]}) (defcard "Biotic Labor" {:on-play {:msg "gain [Click][Click]" :effect (effect (gain :click 2))}}) (defcard "Blue Level Clearance" {:on-play {:msg "gain 5 [Credits] and draw 2 cards" :async true :effect (req (wait-for (gain-credits state side 5) (draw state side eid 2 nil)))}}) (defcard "BOOM!" {:on-play {:req (req (<= 2 (count-tags state))) :msg "do 7 meat damage" :async true :effect (effect (damage eid :meat 7 {:card card}))}}) (defcard "Building Blocks" {:on-play {:req (req (pos? (count (filter #(has-subtype? % "Barrier") (:hand corp))))) :prompt "Select a Barrier to install and rez" :choices {:card #(and (corp? %) (has-subtype? % "Barrier") (in-hand? %))} :msg (msg "reveal " (:title target)) :async true :effect (req (wait-for (reveal state side target) (corp-install state side eid target nil {:ignore-all-cost true :install-state :rezzed-no-cost})))}}) (defcard "Casting Call" {:on-play {:choices {:card #(and (agenda? %) (in-hand? %))} :async true :effect (req (wait-for (corp-install state side target nil {:install-state :face-up}) (let [agenda async-result] (host state side agenda (assoc card :seen true :condition true :installed true)) (system-msg state side (str "hosts Casting Call on " (:title agenda))) (effect-completed state side eid))))} :events [{:event :access :condition :hosted :async true :req (req (same-card? target (:host card))) :msg "give the Runner 2 tags" :effect (effect (gain-tags :runner eid 2))}]}) (defcard "Celebrity Gift" {:on-play {:choices {:max 5 :card #(and (corp? %) (in-hand? %))} :msg (msg "reveal " (string/join ", " (map :title (sort-by :title targets))) " and gain " (* 2 (count targets)) " [Credits]") :async true :effect (req (wait-for (reveal state side targets) (gain-credits state side eid (* 2 (count targets)))))}}) (defcard "Cerebral Cast" {:on-play {:psi {:req (req (last-turn? state :runner :successful-run)) :not-equal {:player :runner :prompt "Take 1 tag or 1 brain damage?" :choices ["1 tag" "1 brain damage"] :msg (msg "give the Runner " target) :effect (req (if (= target "1 tag") (gain-tags state :runner eid 1) (damage state side eid :brain 1 {:card card})))}}}}) (defcard "Cerebral Static" {:on-play {:msg "disable the Runner's identity" :effect (effect (disable-identity :runner))} :leave-play (effect (enable-identity :runner))}) (defcard "\"Clones are not People\"" {:events [{:event :agenda-scored :msg "add it to their score area as an agenda worth 1 agenda point" :async true :effect (req (as-agenda state :corp eid card 1))}]}) (defcard "Closed Accounts" {:on-play {:req (req tagged) :msg (msg "force the Runner to lose all " (:credit runner) " [Credits]") :async true :effect (effect (lose-credits :runner eid :all))}}) (defcard "Commercialization" {:on-play {:msg (msg "gain " (get-counters target :advancement) " [Credits]") :choices {:card #(and (ice? %) (installed? %))} :async true :effect (effect (gain-credits eid (get-counters target :advancement)))}}) (defcard "Complete Image" (letfn [(name-a-card [] {:async true :prompt "Name a Runner card" :choices {:card-title (req (and (runner? target) (not (identity? target))))} :msg (msg "name " target) :effect (effect (continue-ability (damage-ability) card targets))}) (damage-ability [] {:async true :msg "do 1 net damage" :effect (req (wait-for (damage state side :net 1 {:card card}) (let [should-continue (not (:winner @state)) cards (some #(when (same-card? (second %) card) (last %)) (turn-events state :corp :damage)) dmg (some #(when (= (:title %) target) %) cards)] (continue-ability state side (when (and should-continue dmg) (name-a-card)) card nil))))})] {:implementation "Doesn't work with Chronos Protocol: Selective Mind-mapping" :on-play {:async true :req (req (and (last-turn? state :runner :successful-run) (<= 3 (:agenda-point runner)))) :effect (effect (continue-ability (name-a-card) card nil))}})) (defcard "Consulting Visit" {:on-play {:prompt "Choose an Operation from R&D to play" :choices (req (cancellable (filter #(and (operation? %) (<= (:cost %) (:credit corp))) (:deck corp)) :sorted)) :msg (msg "search R&D for " (:title target) " and play it") :async true :effect (effect (shuffle! :deck) (system-msg "shuffles their deck") (play-instant eid target nil))}}) (defcard "Corporate Shuffle" {:on-play {:msg "shuffle all cards in HQ into R&D and draw 5 cards" :async true :effect (effect (shuffle-into-deck :hand) (draw eid 5 nil))}}) (defcard "Cyberdex Trial" {:on-play {:msg "purge virus counters" :effect (effect (purge))}}) (defcard "Death and Taxes" {:implementation "Credit gain mandatory to save on wait-prompts, adjust credits manually if credit not wanted." :events [{:event :runner-install :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))} {:event :runner-trash :req (req (installed? (:card target))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Dedication Ceremony" {:on-play {:prompt "Select a faceup card" :choices {:card #(or (and (corp? %) (rezzed? %)) (and (runner? %) (or (installed? %) (:host %)) (not (facedown? %))))} :msg (msg "place 3 advancement tokens on " (card-str state target)) :effect (effect (add-counter target :advancement 3 {:placed true}) (register-turn-flag! target :can-score (fn [state side card] (if (same-card? card target) ((constantly false) (toast state :corp "Cannot score due to Dedication Ceremony." "warning")) true))))}}) (defcard "Defective Brainchips" {:events [{:event :pre-damage :req (req (= target :brain)) :msg "do 1 additional brain damage" :once :per-turn :effect (effect (damage-bonus :brain 1))}]}) (defcard "Digital Rights Management" {:implementation "Does not prevent scoring agendas installed later in the turn" :on-play {:req (req (and (< 1 (:turn @state)) (not (some #{:hq} (:successful-run runner-reg-last))))) :prompt "Choose an Agenda" ; ToDo: When floating triggers are implemented, this should be an effect that listens to :corp-install as Clot does :choices (req (conj (vec (filter agenda? (:deck corp))) "None")) :msg (msg (if (not= "None" target) (str "add " (:title target) " to HQ and shuffle R&D") "shuffle R&D")) :effect (let [end-effect (req (system-msg state side "can not score agendas for the remainder of the turn") (swap! state assoc-in [:corp :register :cannot-score] (filter agenda? (all-installed state :corp))) (effect-completed state side eid))] (req (wait-for (resolve-ability state side (when-not (= "None" target) {:async true :effect (req (wait-for (reveal state side target) (move state side target :hand) (effect-completed state side eid)))}) card targets) (shuffle! state side :deck) (continue-ability state side {:prompt "You may install a card in HQ" :choices {:card #(and (in-hand? %) (corp? %) (not (operation? %)))} :effect (req (wait-for (resolve-ability state side (let [card-to-install target] {:prompt (str "Choose a location to install " (:title target)) :choices (remove #{"HQ" "R&D" "Archives"} (corp-install-list state target)) :async true :effect (effect (corp-install eid card-to-install target nil))}) target nil) (end-effect state side eid card targets))) :cancel-effect (effect (system-msg "does not use Digital Rights Management to install a card") (end-effect eid card targets))} card nil))))}}) (defcard "Distract the Masses" (let [shuffle-two {:async true :effect (effect (shuffle-into-rd-effect eid card 2))} trash-from-hq {:async true :prompt "Select up to 2 cards in HQ to trash" :choices {:max 2 :card #(and (corp? %) (in-hand? %))} :msg (msg "trash " (quantify (count targets) "card") " from HQ") :effect (req (wait-for (trash-cards state side targets nil) (continue-ability state side shuffle-two card nil))) :cancel-effect (effect (continue-ability shuffle-two card nil))}] {:on-play {:rfg-instead-of-trashing true :msg "give The Runner 2 [Credits]" :async true :effect (req (wait-for (gain-credits state :runner 2) (continue-ability state side trash-from-hq card nil)))}})) (defcard "Diversified Portfolio" (letfn [(number-of-non-empty-remotes [state] (count (filter #(not (empty? %)) (map #(:content (second %)) (get-remotes state)))))] {:on-play {:msg (msg "gain " (number-of-non-empty-remotes state) " [Credits]") :async true :effect (effect (gain-credits eid (number-of-non-empty-remotes state)))}})) (defcard "Divert Power" {:on-play {:prompt "Select any number of cards to derez" :choices {:card #(and (installed? %) (rezzed? %)) :max (req (count (filter rezzed? (all-installed state :corp))))} :async true :effect (req (doseq [c targets] (derez state side c)) (let [discount (* -3 (count targets))] (continue-ability state side {:async true :prompt "Select a card to rez" :choices {:card #(and (installed? %) (corp? %) (not (rezzed? %)) (not (agenda? %)))} :effect (effect (rez eid target {:cost-bonus discount}))} card nil)))}}) (defcard "Door to Door" {:events [{:event :runner-turn-begins :trace {:base 1 :label "Do 1 meat damage if Runner is tagged, or give the Runner 1 tag" :successful {:msg (msg (if tagged "do 1 meat damage" "give the Runner 1 tag")) :async true :effect (req (if tagged (damage state side eid :meat 1 {:card card}) (gain-tags state :corp eid 1)))}}}]}) (defcard "Eavesdrop" {:on-play {:choices {:card #(and (ice? %) (installed? %))} :msg (msg "give " (card-str state target {:visible false}) " additional text") :effect (effect (host target (assoc card :seen true :condition true)))} :events [{:event :encounter-ice :condition :hosted :trace {:base 3 :req (req (same-card? current-ice (:host card))) :successful {:msg "give the Runner 1 tag" :async true :effect (effect (gain-tags :runner eid 1))}}}]}) (defcard "Economic Warfare" {:on-play {:req (req (and (last-turn? state :runner :successful-run) (can-pay? state :runner (assoc eid :source card :source-type :ability) card nil :credit 4))) :msg "make the runner lose 4 [Credits]" :async true :effect (effect (lose-credits :runner eid 4))}}) (defcard "Election Day" {:on-play {:req (req (->> (get-in @state [:corp :hand]) (filter #(not (same-card? % card))) count pos?)) :msg (msg "trash all cards in HQ and draw 5 cards") :async true :effect (req (wait-for (trash-cards state side (get-in @state [:corp :hand])) (draw state side eid 5 nil)))}}) (defcard "Enforced Curfew" {:on-play {:msg "reduce the Runner's maximum hand size by 1"} :constant-effects [(runner-hand-size+ -1)]}) (defcard "Enforcing Loyalty" {:on-play {:trace {:base 3 :label "Trash a card not matching the faction of the Runner's identity" :successful {:async true :prompt "Select an installed card not matching the faction of the Runner's identity" :choices {:req (req (and (installed? target) (runner? target) (not= (:faction (:identity runner)) (:faction target))))} :msg (msg "trash " (:title target)) :effect (effect (trash eid target nil))}}}}) (defcard "Enhanced Login Protocol" {:on-play {:msg (str "uses Enhanced Login Protocol to add an additional cost of [Click]" " to make the first run not through a card ability this turn")} :constant-effects [{:type :run-additional-cost :req (req (and (no-event? state side :run #(:click-run (:cost-args (first %)))) (:click-run (second targets)))) :value [:click 1]}]}) (defcard "Exchange of Information" {:on-play {:req (req (and tagged (seq (:scored runner)) (seq (:scored corp)))) :prompt "Select a stolen agenda in the Runner's score area to swap" :choices {:req (req (in-runner-scored? state side target))} :async true :effect (effect (continue-ability (let [stolen target] {:prompt (msg "Select a scored agenda to swap for " (:title stolen)) :choices {:req (req (in-corp-scored? state side target))} :msg (msg "swap " (:title target) " for " (:title stolen)) :effect (effect (swap-agendas target stolen))}) card nil))}}) (defcard "Fast Break" {:on-play {:req (req (-> runner :scored count pos?)) :async true :effect (req (let [X (-> runner :scored count) draw {:async true :prompt "Draw how many cards?" :choices {:number (req X) :max (req X) :default (req 1)} :msg (msg "draw " target " cards") :effect (effect (draw eid target nil))} install-cards (fn install-cards [server n] {:prompt "Select a card to install" :choices {:card #(and (corp? %) (not (operation? %)) (in-hand? %) (seq (filter (fn [c] (= server c)) (corp-install-list state %))))} :effect (req (wait-for (corp-install state side target server nil) (let [server (remote->name (second (:zone async-result)))] (if (< n X) (continue-ability state side (install-cards server (inc n)) card nil) (effect-completed state side eid)))))}) select-server {:async true :prompt "Install cards in which server?" :choices (req (conj (vec (get-remote-names state)) "New remote")) :effect (effect (continue-ability (install-cards target 1) card nil))}] (wait-for (gain-credits state :corp X) (wait-for (resolve-ability state side draw card nil) (continue-ability state side select-server card nil)))))}}) (defcard "Fast Track" {:on-play {:prompt "Choose an Agenda" :choices (req (cancellable (filter agenda? (:deck corp)) :sorted)) :async true :effect (req (system-msg state side (str "adds " (:title target) " to HQ and shuffle R&D")) (wait-for (reveal state side target) (shuffle! state side :deck) (move state side target :hand) (effect-completed state side eid)))}}) (defcard "Financial Collapse" (letfn [(count-resources [state] (* 2 (count (filter resource? (all-active-installed state :runner)))))] {:on-play {:optional {:req (req (and (<= 6 (:credit runner)) (pos? (count-resources state)))) :player :runner :waiting-prompt "Runner to trash a resource to prevent Financial Collapse" :prompt "Trash a resource to prevent Financial Collapse?" :yes-ability {:prompt "Select a resource to trash" :choices {:card #(and (resource? %) (installed? %))} :async true :effect (effect (system-msg :runner (str "trashes " (:title target) " to prevent Financial Collapse")) (trash :runner eid target {:unpreventable true}))} :no-ability {:player :corp :async true :msg (msg "make the Runner lose " (count-resources state) " [Credits]") :effect (effect (lose-credits :runner eid (count-resources state)))}}}})) (defcard "Focus Group" {:on-play {:req (req (last-turn? state :runner :successful-run)) :prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :async true :effect (req (let [type target numtargets (count (filter #(= type (:type %)) (:hand runner)))] (system-msg state :corp (str "uses Focus Group to choose " target " and reveal the Runner's Grip (" (string/join ", " (map :title (sort-by :title (:hand runner)))) ")")) (wait-for (reveal state side (:hand runner)) (continue-ability state :corp (when (pos? numtargets) {:async true :prompt "Pay how many credits?" :choices {:number (req numtargets)} :effect (req (let [c target] (if (can-pay? state side (assoc eid :source card :source-type :ability) card (:title card) :credit c) (let [new-eid (make-eid state {:source card :source-type :ability})] (wait-for (pay state :corp new-eid card :credit c) (when-let [payment-str (:msg async-result)] (system-msg state :corp payment-str)) (continue-ability state :corp {:msg (msg "place " (quantify c " advancement token") " on " (card-str state target)) :choices {:card installed?} :effect (effect (add-prop target :advance-counter c {:placed true}))} card nil))) (effect-completed state side eid))))}) card nil))))}}) (defcard "Foxfire" {:on-play {:trace {:base 7 :successful {:prompt "Select 1 card to trash" :choices {:card #(and (installed? %) (or (has-subtype? % "Virtual") (has-subtype? % "Link")))} :msg "trash 1 virtual resource or link" :async true :effect (effect (system-msg (str "trashes " (:title target))) (trash eid target nil))}}}}) (defcard "Freelancer" {:on-play {:req (req tagged) :msg (msg "trash " (string/join ", " (map :title (sort-by :title targets)))) :choices {:max 2 :card #(and (installed? %) (resource? %))} :async true :effect (effect (trash-cards :runner eid targets))}}) (defcard "Friends in High Places" (let [fhelper (fn fhp [n] {:prompt "Select a card in Archives to install with Friends in High Places" :async true :show-discard true :choices {:card #(and (corp? %) (not (operation? %)) (in-discard? %))} :effect (req (wait-for (corp-install state side target nil nil) (do (system-msg state side (str "uses Friends in High Places to " (corp-install-msg target))) (if (< n 2) (continue-ability state side (fhp (inc n)) card nil) (effect-completed state side eid)))))})] {:on-play {:async true :effect (effect (continue-ability (fhelper 1) card nil))} })) (defcard "Fully Operational" (letfn [(full-servers [state] (filter #(and (not-empty (:content %)) (not-empty (:ices %))) (vals (get-remotes state)))) (repeat-choice [current total] ;; if current > total, this ability will auto-resolve and finish the chain of async methods. (when (<= current total) {:async true :prompt (str "Choice " current " of " total ": Gain 2 [Credits] or draw 2 cards? ") :choices ["Gain 2 [Credits]" "Draw 2 cards"] :msg (msg (string/lower-case target)) :effect (req (if (= target "Gain 2 [Credits]") (wait-for (gain-credits state :corp 2) (continue-ability state side (repeat-choice (inc current) total) card nil)) (wait-for (draw state :corp 2 nil) ; don't proceed with the next choice until the draw is done (continue-ability state side (repeat-choice (inc current) total) card nil))))}))] {:on-play {:msg (msg "uses Fully Operational to make " (quantify (inc (count (full-servers state))) "gain/draw decision")) :async true :effect (effect (continue-ability (repeat-choice 1 (inc (count (full-servers state)))) card nil))}})) (defcard "Game Changer" {:on-play {:rfg-instead-of-trashing true :effect (effect (gain :click (count (:scored runner))))}}) (defcard "Game Over" {:on-play {:req (req (last-turn? state :runner :stole-agenda)) :prompt "Choose a card type" :choices ["Hardware" "Program" "Resource"] :async true :effect (req (let [card-type target trashtargets (filter #(and (is-type? % card-type) (not (has-subtype? % "Icebreaker"))) (all-active-installed state :runner)) numtargets (count trashtargets) typemsg (str (when (= card-type "Program") "non-Icebreaker ") card-type (when-not (= card-type "Hardware") "s"))] (system-msg state :corp (str "chooses to trash all " typemsg)) (wait-for (resolve-ability state :runner {:async true :req (req (<= 3 (:credit runner))) :waiting-prompt "Runner to prevent trashes" :prompt (msg "Prevent any " typemsg " from being trashed? Pay 3 [Credits] per card.") :choices {:max (req (min numtargets (quot (total-available-credits state :runner eid card) 3))) :card #(and (installed? %) (is-type? % card-type) (not (has-subtype? % "Icebreaker")))} :effect (req (wait-for (pay state :runner card :credit (* 3 (count targets))) (system-msg state :runner (str (:msg async-result) " to prevent the trashing of " (string/join ", " (map :title (sort-by :title targets))))) (effect-completed state side (make-result eid targets))))} card nil) (let [prevented async-result] (when (not async-result) (system-msg state :runner (str "chooses to not prevent Corp trashing all " typemsg))) (wait-for (trash-cards state side (clojure.set/difference (set trashtargets) (set prevented))) (system-msg state :corp (str "trashes all " (when (seq prevented) "other ") typemsg ": " (string/join ", " (map :title (sort-by :title async-result))))) (wait-for (gain-bad-publicity state :corp 1) (when async-result (system-msg state :corp "takes 1 bad publicity from Game Over")) (effect-completed state side eid)))))))}}) (defcard "Genotyping" {:on-play {:msg "trash the top 2 cards of R&D" :rfg-instead-of-trashing true :async true :effect (req (wait-for (mill state :corp :corp 2) (shuffle-into-rd-effect state side eid card 4)))}}) (defcard "Green Level Clearance" {:on-play {:msg "gain 3 [Credits] and draw 1 card" :async true :effect (req (wait-for (gain-credits state side 3) (draw state side eid 1 nil)))}}) (defcard "<NAME>ki" {:on-play {:req (req (last-turn? state :runner :trashed-card)) :prompt "Choose an installed Corp card" :choices {:card #(and (corp? %) (installed? %))} :async true :effect (effect (continue-ability {:optional {:player :runner :async true :waiting-prompt "Runner to resolve <NAME>angeki" :prompt "Access card? (If not, add Hangeki to your score area worth -1 agenda point)" :yes-ability {:async true :effect (req (wait-for (access-card state side target) (update! state side (assoc card :rfg-instead-of-trashing true)) (effect-completed state side eid)))} :no-ability {:async true :msg "add it to the Runner's score area as an agenda worth -1 agenda point" :effect (effect (as-agenda :runner eid card -1))}}} card targets))}}) (defcard "<NAME>sei Review" (let [trash-from-hq {:async true :req (req (pos? (count (:hand corp)))) :prompt "Select a card in HQ to trash" :choices {:max 1 :all true :card #(and (corp? %) (in-hand? %))} :msg "trash a card from HQ" :effect (effect (trash-cards eid targets))}] {:on-play {:async true :msg "gain 10 [Credits]" :effect (req (wait-for (gain-credits state :corp 10) (continue-ability state side trash-from-hq card nil)))}})) (defcard "Hard-Hitting News" {:on-play {:trace {:base 4 :req (req (last-turn? state :runner :made-run)) :label "Give the Runner 4 tags" :successful {:async true :msg "give the Runner 4 tags" :effect (effect (gain-tags eid 4))}}}}) (defcard "Hasty Relocation" (letfn [(hr-final [chosen original] {:prompt (str "The top cards of R&D will be " (string/join ", " (map :title chosen)) ".") :choices ["Done" "Start over"] :async true :effect (req (if (= target "Done") (do (doseq [c (reverse chosen)] (move state :corp c :deck {:front true})) (clear-wait-prompt state :runner) (effect-completed state side eid)) (continue-ability state side (hr-choice original '() 3 original) card nil)))}) (hr-choice [remaining chosen n original] {:prompt "Choose a card to move next onto R&D" :choices remaining :async true :effect (req (let [chosen (cons target chosen)] (if (< (count chosen) n) (continue-ability state side (hr-choice (remove-once #(= target %) remaining) chosen n original) card nil) (continue-ability state side (hr-final chosen original) card nil))))})] {:on-play {:additional-cost [:trash-from-deck 1] :msg "trash the top card of R&D, draw 3 cards, and add 3 cards in HQ to the top of R&D" :waiting-prompt "Corp to add 3 cards in HQ to the top of R&D" :async true :effect (req (wait-for (draw state side 3 nil) (let [from (get-in @state [:corp :hand])] (continue-ability state :corp (hr-choice from '() 3 from) card nil))))}})) (defcard "Hatchet Job" {:on-play {:trace {:base 5 :successful {:choices {:card #(and (installed? %) (runner? %) (not (has-subtype? % "Virtual")))} :msg "add an installed non-virtual card to the Runner's grip" :effect (effect (move :runner target :hand true))}}}}) (defcard "Hedge Fund" {:on-play {:msg "gain 9 [Credits]" :async true :effect (effect (gain-credits eid 9))}}) (defcard "Hellion Alpha Test" {:on-play {:trace {:base 2 :req (req (last-turn? state :runner :installed-resource)) :successful {:msg "add a Resource to the top of the Stack" :choices {:card #(and (installed? %) (resource? %))} :effect (effect (move :runner target :deck {:front true}) (system-msg (str "adds " (:title target) " to the top of the Stack")))} :unsuccessful {:msg "take 1 bad publicity" :effect (effect (gain-bad-publicity :corp 1))}}}}) (defcard "Hellion Beta Test" {:on-play {:trace {:base 2 :req (req (last-turn? state :runner :trashed-card)) :label "Trash 2 installed non-program cards or take 1 bad publicity" :successful {:choices {:max (req (min 2 (count (filter #(or (facedown? %) (not (program? %))) (concat (all-installed state :corp) (all-installed state :runner)))))) :all true :card #(and (installed? %) (not (program? %)))} :msg (msg "trash " (string/join ", " (map :title (sort-by :title targets)))) :async true :effect (effect (trash-cards eid targets))} :unsuccessful {:msg "take 1 bad publicity" :async true :effect (effect (gain-bad-publicity :corp eid 1))}}}}) (defcard "Heritage Committee" {:on-play {:async true :effect (req (wait-for (draw state side 3 nil) (continue-ability state side {:prompt "Select a card in HQ to put on top of R&D" :choices {:card #(and (corp? %) (in-hand? %))} :msg "draw 3 cards and add 1 card from HQ to the top of R&D" :effect (effect (move target :deck {:front true}))} card nil)))}}) (defcard "High-Profile Target" (letfn [(dmg-count [state] (* 2 (count-tags state)))] {:on-play {:req (req tagged) :msg (msg "do " (dmg-count state) " meat damage") :async true :effect (effect (damage eid :meat (dmg-count state) {:card card}))}})) (defcard "Housekeeping" {:events [{:event :runner-install :req (req (first-event? state side :runner-install)) :player :runner :prompt "Select a card from your Grip to trash for Housekeeping" :choices {:card #(and (runner? %) (in-hand? %))} :async true :msg (msg "force the Runner to trash" (:title target) " from their grip") :effect (effect (trash :runner eid target {:unpreventable true}))}]}) (defcard "<NAME>" {:on-play {:req (req (last-turn? state :runner :stole-agenda)) :prompt "Choose a card to trash" :choices {:card installed?} :msg (msg "trash " (card-str state target)) :async true :effect (effect (trash eid target nil))}}) (defcard "Hyoubu Precog Manifold" {:on-play {:trash-after-resolving false :prompt "Choose a server" :choices (req servers) :msg (msg "choose " target) :effect (effect (update! (assoc-in card [:special :hyoubu-precog-target] target)))} :events [{:event :successful-run :psi {:req (req (= (zone->name (get-in @state [:run :server])) (get-in card [:special :hyoubu-precog-target]))) :not-equal {:msg "end the run" :async true :effect (effect (end-run eid card))}}} {:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "Interns" {:on-play {:prompt "Select a card to install from Archives or HQ" :show-discard true :not-distinct true :choices {:card #(and (not (operation? %)) (corp? %) (or (in-hand? %) (in-discard? %)))} :msg (msg (corp-install-msg target)) :async true :effect (effect (corp-install eid target nil {:ignore-install-cost true}))}}) (defcard "Invasion of Privacy" (letfn [(iop [x] {:async true :req (req (->> (:hand runner) (filter #(or (resource? %) (event? %))) count pos?)) :prompt "Choose a resource or event to trash" :msg (msg "trash " (:title target)) :choices (req (cancellable (filter #(or (resource? %) (event? %)) (:hand runner)) :sorted)) :effect (req (wait-for (trash state side target nil) (if (pos? x) (continue-ability state side (iop (dec x)) card nil) (effect-completed state side eid))))})] {:on-play {:trace {:base 2 :successful {:msg "reveal the Runner's Grip and trash up to X resources or events" :async true :effect (req (wait-for (reveal state side (:hand runner)) (let [x (- target (second targets))] (system-msg state :corp (str "reveals the Runner's Grip ( " (string/join ", " (map :title (sort-by :title (:hand runner)))) " ) and can trash up to " x " resources or events")) (continue-ability state side (iop (dec x)) card nil))))} :unsuccessful {:msg "take 1 bad publicity" :async true :effect (effect (gain-bad-publicity :corp eid 1))}}}})) (defcard "IPO" {:on-play {:msg "gain 13 [Credits]" :async true :effect (effect (gain-credits eid 13))}}) (defcard "Kakurenbo" (let [install-abi {:async true :prompt "Select an agenda, asset or upgrade to install from Archives and place 2 advancement tokens on" :show-discard true :not-distinct true :choices {:card #(and (or (agenda? %) (asset? %) (upgrade? %)) (in-discard? %))} :effect (req (wait-for (corp-install state side (make-eid state {:source card :source-type :corp-install}) target nil nil) (system-msg state side "uses Kakurenbo to place 2 advancements counters on it") (add-prop state side eid async-result :advance-counter 2 {:placed true})))}] {:on-play {:prompt "Select any number of cards in HQ to trash" :rfg-instead-of-trashing true :choices {:max (req (count (:hand corp))) :card #(and (corp? %) (in-hand? %))} :msg (msg "trash " (count targets) " cards in HQ") :async true :effect (req (wait-for (trash-cards state side targets {:unpreventable true}) (doseq [c (:discard (:corp @state))] (update! state side (assoc-in c [:seen] false))) (shuffle! state :corp :discard) (continue-ability state side install-abi card nil))) :cancel-effect (req (doseq [c (:discard (:corp @state))] (update! state side (assoc-in c [:seen] false))) (shuffle! state :corp :discard) (continue-ability state side install-abi card nil))}})) (defcard "Kill Switch" (let [trace-for-brain-damage {:msg (msg "reveal that they accessed " (:title (or (:card context) target))) :trace {:base 3 :req (req (or (agenda? (:card context)) (agenda? target))) :successful {:msg "do 1 brain damage" :async true :effect (effect (damage :runner eid :brain 1 {:card card}))}}}] {:events [(assoc trace-for-brain-damage :event :access :interactive (req (agenda? target))) (assoc trace-for-brain-damage :event :agenda-scored)]})) (defcard "Lag Time" {:on-play {:effect (effect (update-all-ice))} :constant-effects [{:type :ice-strength :value 1}] :leave-play (effect (update-all-ice))}) (defcard "Lateral Growth" {:on-play {:msg "gain 4 [Credits]" :async true :effect (req (wait-for (gain-credits state side 4) (continue-ability state side {:player :corp :prompt "Select a card to install" :choices {:card #(and (corp? %) (not (operation? %)) (in-hand? %))} :async true :msg (msg (corp-install-msg target)) :effect (effect (corp-install eid target nil nil))} card nil)))}}) (defcard "Liquidation" {:on-play {:req (req (some #(and (rezzed? %) (not (agenda? %))) (all-installed state :corp))) :prompt "Select any number of rezzed cards to trash" :choices {:max (req (count (filter #(not (agenda? %)) (all-active-installed state :corp)))) :card #(and (rezzed? %) (not (agenda? %)))} :msg (msg "trash " (string/join ", " (map :title targets)) " and gain " (* (count targets) 3) " [Credits]") :async true :effect (req (wait-for (trash-cards state side targets nil) (gain-credits state side eid (* (count targets) 3))))}}) (defcard "Load Testing" {:on-play {:msg "make the Runner lose [Click] when their next turn begins"} :events [{:event :runner-turn-begins :duration :until-runner-turn-begins :msg "make the Runner lose [Click]" :effect (effect (lose :runner :click 1))}]}) (defcard "Localized Product Line" {:on-play {:prompt "Choose a card" :choices (req (cancellable (:deck corp) :sorted)) :async true :effect (effect (continue-ability (let [title (:title target) copies (filter #(= (:title %) title) (:deck corp))] {:prompt "How many copies?" :choices {:number (req (count copies))} :msg (msg "add " (quantify target "cop" "y" "ies") " of " title " to HQ") :effect (req (shuffle! state :corp :deck) (doseq [copy (take target copies)] (move state side copy :hand)))}) card nil))}}) (defcard "Manhunt" {:events [{:event :successful-run :interactive (req true) :trace {:req (req (first-event? state side :successful-run)) :base 2 :successful {:msg "give the Runner 1 tag" :async true :effect (effect (gain-tags eid 1))}}}]}) (defcard "Market Forces" (letfn [(credit-diff [state] (min (* 3 (count-tags state)) (get-in @state [:runner :credit])))] {:on-play {:req (req tagged) :msg (msg (let [c (credit-diff state)] (str "make the runner lose " c " [Credits], and gain " c " [Credits]"))) :async true :effect (req (let [c (credit-diff state)] (wait-for (lose-credits state :runner c) (gain-credits state :corp eid c))))}})) (defcard "Mass Commercialization" {:on-play {:msg (msg "gain " (* 2 (count (filter #(pos? (get-counters % :advancement)) (get-all-installed state)))) " [Credits]") :async true :effect (effect (gain-credits eid (* 2 (count (filter #(pos? (get-counters % :advancement)) (get-all-installed state))))))}}) (defcard "MCA Informant" {:on-play {:req (req (not-empty (filter #(has-subtype? % "Connection") (all-active-installed state :runner)))) :prompt "Choose a connection to host MCA Informant on" :choices {:card #(and (runner? %) (has-subtype? % "Connection") (installed? %))} :msg (msg "host it on " (card-str state target) ". The Runner has an additional tag") :effect (req (host state side (get-card state target) (assoc card :seen true :condition true)))} :constant-effects [{:type :tags :value 1}] :leave-play (req (system-msg state :corp "trashes MCA Informant")) :runner-abilities [{:label "Trash MCA Informant host" :cost [:click 1 :credit 2] :req (req (= :runner side)) :async true :effect (effect (system-msg :runner (str "spends [Click] and 2 [Credits] to trash " (card-str state (:host card)))) (trash :runner eid (get-card state (:host card)) nil))}]}) (defcard "<NAME> B<NAME>" {:on-play {:async true :req (req (pos? (count (:scored runner)))) :effect (effect (continue-ability {:prompt "Select an agenda in the runner's score area" :choices {:card #(and (agenda? %) (is-scored? state :runner %))} :effect (req (update! state side (assoc card :title (:title target) :abilities (ability-init (card-def target)))) (card-init state side (get-card state card) {:resolve-effect false :init-data true}) (update! state side (assoc (get-card state card) :title "Media Blitz")))} card nil))}}) (defcard "Medical Research Fundraiser" {:on-play {:msg "gain 8 [Credits]. The Runner gains 3 [Credits]" :async true :effect (req (wait-for (gain-credits state side 8) (gain-credits state :runner eid 3)))}}) (defcard "Midseason Replacements" {:on-play {:trace {:req (req (last-turn? state :runner :stole-agenda)) :base 6 :label "Trace 6 - Give the Runner X tags" :successful {:msg "give the Runner X tags" :async true :effect (effect (system-msg (str "gives the Runner " (- target (second targets)) " tags")) (gain-tags eid (- target (second targets))))}}}}) (defcard "<NAME>" {:on-play {:prompt "Select a card to install from HQ" :choices {:card #(and (not (operation? %)) (corp? %) (in-hand? %))} :async true :effect (req (wait-for (corp-install state side target "New remote" nil) (let [installed-card async-result] (add-prop state side installed-card :advance-counter 3 {:placed true}) (register-turn-flag! state side card :can-rez (fn [state side card] (if (same-card? card installed-card) ((constantly false) (toast state :corp "Cannot rez due to Mushin No Shin." "warning")) true))) (register-turn-flag! state side card :can-score (fn [state side card] (if (same-card? card installed-card) ((constantly false) (toast state :corp "Cannot score due to Mushin No Shin." "warning")) true))) (effect-completed state side eid))))}}) (defcard "Mutate" {:on-play {:req (req (some #(and (ice? %) (rezzed? %)) (all-installed state :corp))) :prompt "Select a rezzed piece of ice to trash" :choices {:card #(and (ice? %) (rezzed? %))} :async true :effect (req (let [index (card-index state target) [revealed-cards r] (split-with (complement ice?) (get-in @state [:corp :deck])) titles (->> (conj (vec revealed-cards) (first r)) (filter identity) (map :title))] (wait-for (trash state :corp target nil) (shuffle! state :corp :deck) (system-msg state side (str "uses Mutate to trash " (:title target))) (wait-for (reveal state side revealed-cards) (system-msg state side (str "reveals " (clojure.string/join ", " titles) " from R&D")) (let [ice (first r) zone (zone->name (second (get-zone target)))] (if ice (do (system-msg state side (str "uses Mutate to install and rez " (:title ice) " from R&D at no cost")) (corp-install state side eid ice zone {:ignore-all-cost true :install-state :rezzed-no-cost :display-message false :index index})) (do (system-msg state side "does not find any ICE to install from R&D") (effect-completed state side eid))))))))}}) (defcard "NAPD Cordon" {:on-play {:trash-after-resolving false} :events [{:event :pre-steal-cost :effect (req (let [counter (get-counters target :advancement)] (steal-cost-bonus state side [:credit (+ 4 (* 2 counter))])))} {:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "Neural EMP" {:on-play {:req (req (last-turn? state :runner :made-run)) :msg "do 1 net damage" :async true :effect (effect (damage eid :net 1 {:card card}))}}) (defcard "Neurospike" {:on-play {:msg (msg "do " (:scored-agenda corp-reg 0) " net damage") :async true :effect (effect (damage eid :net (:scored-agenda corp-reg 0) {:card card}))}}) (defcard "NEXT Activation Command" {:on-play {:trash-after-resolving false} :constant-effects [{:type :ice-strength :value 2} {:type :prevent-ability :req (req (let [target-card (first targets) ability (second targets)] (and (not (has-subtype? target-card "Icebreaker")) (:break ability)))) :value true}] :events [{:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "O₂ Shortage" {:on-play {:async true :effect (req (if (empty? (:hand runner)) (do (gain state :corp :click 2) (system-msg state side "uses O₂ Shortage to gain [Click][Click]") (effect-completed state side eid)) (continue-ability state side {:optional {:waiting-prompt "Runner to decide whether or not to trash a card from their Grip" :prompt "Trash 1 random card from your Grip?" :player :runner :yes-ability {:async true :effect (effect (trash-cards :runner eid (take 1 (shuffle (:hand runner))) nil))} :no-ability {:msg "gain [Click][Click]" :effect (effect (gain :corp :click 2))}}} card nil)))}}) (defcard "Observe and Destroy" {:on-play {:additional-cost [:tag 1] :req (req (and (pos? (count-real-tags state)) (< (:credit runner) 6))) :prompt "Select an installed card to trash" :choices {:card #(and (runner? %) (installed? %))} :msg (msg "remove 1 Runner tag and trash " (card-str state target)) :async true :effect (effect (trash eid target nil))}}) (defcard "Oversight AI" {:on-play {:choices {:card #(and (ice? %) (not (rezzed? %)) (= (last (get-zone %)) :ices))} :msg (msg "rez " (card-str state target) " at no cost") :async true :effect (req (wait-for (rez state side target {:ignore-cost :all-costs :no-msg true}) (host state side (:card async-result) (assoc card :seen true :condition true)) (effect-completed state side eid)))} :events [{:event :subroutines-broken :condition :hosted :async true :req (req (and (same-card? target (:host card)) (empty? (remove :broken (:subroutines target))))) :msg (msg "trash itself and " (card-str state target)) :effect (effect (trash :corp eid target {:unpreventable true}))}]}) (defcard "Patch" {:on-play {:choices {:card #(and (ice? %) (rezzed? %))} :msg (msg "give +2 strength to " (card-str state target)) :effect (req (let [card (host state side target (assoc card :seen true :condition true))] (update-ice-strength state side (get-card state target))))} :constant-effects [{:type :ice-strength :req (req (same-card? target (:host card))) :value 2}]}) (defcard "Paywall Implementation" {:events [{:event :successful-run :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Peak Efficiency" {:on-play {:msg (msg "gain " (reduce (fn [c server] (+ c (count (filter (fn [ice] (:rezzed ice)) (:ices server))))) 0 (flatten (seq (:servers corp)))) " [Credits]") :async true :effect (effect (gain-credits eid (reduce (fn [c server] (+ c (count (filter (fn [ice] (:rezzed ice)) (:ices server))))) 0 (flatten (seq (:servers corp))))))}}) (defcard "Power Grid Overload" {:on-play {:trace {:base 2 :req (req (last-turn? state :runner :made-run)) :successful {:msg "trash 1 piece of hardware" :async true :effect (effect (continue-ability (let [max-cost (- target (second targets))] {:choices {:card #(and (hardware? %) (<= (:cost %) max-cost))} :msg (msg "trash " (:title target)) :effect (effect (trash eid target nil))}) card nil))}}}}) (defcard "Power Shutdown" {:on-play {:req (req (and (last-turn? state :runner :made-run) (not-empty (filter #(or (hardware? %) (program? %)) (all-active-installed state :runner))))) :prompt "Trash how many cards from the top R&D?" :choices {:number (req (count (:deck corp)))} :msg (msg "trash " target " cards from the top of R&D") :async true :effect (req (wait-for (mill state :corp :corp target) (continue-ability state :runner (let [n target] {:async true :prompt "Select a Program or piece of Hardware to trash" :choices {:card #(and (or (hardware? %) (program? %)) (<= (:cost %) n))} :msg (msg "trash " (:title target)) :effect (effect (trash eid target nil))}) card nil)))}}) (defcard "Precognition" {:on-play {:msg "rearrange the top 5 cards of R&D" :waiting-prompt "Corp to rearrange the top cards of R&D" :async true :effect (effect (continue-ability (let [from (take 5 (:deck corp))] (when (pos? (count from)) (reorder-choice :corp :runner from '() (count from) from))) card nil))}}) (defcard "Predictive Algorithm" {:events [{:event :pre-steal-cost :effect (effect (steal-cost-bonus [:credit 2]))}]}) (defcard "Predictive Planogram" {:on-play {:prompt "Choose one" :choices (req ["Gain 3 [Credits]" "Draw 3 cards" (when tagged "Gain 3 [Credits] and draw 3 cards")]) :msg (msg (string/lower-case target)) :async true :effect (req (case target "Gain 3 [Credits]" (gain-credits state :corp eid 3) "Draw 3 cards" (draw state :corp eid 3 nil) "Gain 3 [Credits] and draw 3 cards" (wait-for (gain-credits state :corp 3) (draw state :corp eid 3 nil)) ; else (effect-completed state side eid)))}}) (defcard "Preemptive Action" {:on-play {:rfg-instead-of-trashing true :async true :effect (effect (shuffle-into-rd-effect eid card 3 true))}}) (defcard "Priority Construction" (letfn [(install-card [chosen] {:prompt "Select a remote server" :choices (req (conj (vec (get-remote-names state)) "New remote")) :async true :effect (effect (corp-install eid (assoc chosen :advance-counter 3) target {:ignore-all-cost true}))})] {:on-play {:prompt "Choose a piece of ICE in HQ to install" :choices {:card #(and (in-hand? %) (corp? %) (ice? %))} :msg "install an ICE from HQ and place 3 advancements on it" :cancel-effect (req (effect-completed state side eid)) :async true :effect (effect (continue-ability (install-card target) card nil))}})) (defcard "Product Recall" {:on-play {:prompt "Select a rezzed asset or upgrade to trash" :choices {:card #(and (rezzed? %) (or (asset? %) (upgrade? %)))} :msg (msg "trash " (card-str state target) " and gain " (trash-cost state side target) " [Credits]") :async true :effect (req (wait-for (trash state side target {:unpreventable true}) (gain-credits state :corp eid (trash-cost state side target))))}}) (defcard "Psychographics" {:on-play {:req (req tagged) :prompt "Pay how many credits?" :choices {:number (req (count-tags state))} :async true :effect (req (let [c target] (if (can-pay? state side (assoc eid :source card :source-type :ability) card (:title card) :credit c) (let [new-eid (make-eid state {:source card :source-type :ability})] (wait-for (pay state :corp new-eid card :credit c) (when-let [payment-str (:msg async-result)] (system-msg state :corp payment-str)) (continue-ability state side {:msg (msg "place " (quantify c " advancement token") " on " (card-str state target)) :choices {:card can-be-advanced?} :effect (effect (add-prop target :advance-counter c {:placed true}))} card nil))) (effect-completed state side eid))))}}) (defcard "Psychokinesis" (letfn [(choose-card [state cards] (let [allowed-cards (filter #(some #{"New remote"} (installable-servers state %)) cards)] {:prompt "Select an agenda, asset, or upgrade to install" :choices (conj (vec allowed-cards) "None") :async true :effect (req (if (or (= target "None") (ice? target) (operation? target)) (do (system-msg state side "does not install an asset, agenda, or upgrade") (effect-completed state side eid)) (continue-ability state side (install-card target) card nil)))})) (install-card [chosen] {:prompt "Select a remote server" :choices (req (conj (vec (get-remote-names state)) "New remote")) :async true :effect (effect (corp-install eid chosen target nil))})] {:on-play {:req (req (pos? (count (:deck corp)))) :msg (msg "look at the top " (quantify (count (take 5 (:deck corp))) "card") " of R&D") :waiting-prompt "Corp to look at the top cards of R&D" :async true :effect (effect (continue-ability (let [top-5 (take 5 (:deck corp))] (choose-card state top-5)) card nil))}})) (defcard "Public Trail" {:on-play {:req (req (last-turn? state :runner :successful-run)) :player :runner :msg (msg "force the Runner to " (decapitalize target)) :prompt "Pick one" :choices (req ["Take 1 tag" (when (can-pay? state :runner (assoc eid :source card :source-type :ability) card (:title card) :credit 8) "Pay 8 [Credits]")]) :async true :effect (req (if (= target "Pay 8 [Credits]") (wait-for (pay state :runner card :credit 8) (system-msg state :runner (:msg async-result)) (effect-completed state side eid)) (gain-tags state :corp eid 1)))}}) (defcard "Punitive Counterstrike" {:on-play {:trace {:base 5 :successful {:async true :msg (msg "do " (:stole-agenda runner-reg-last 0) " meat damage") :effect (effect (damage eid :meat (:stole-agenda runner-reg-last 0) {:card card}))}}}}) (defcard "Reclamation Order" {:on-play {:prompt "Select a card from Archives" :show-discard true :choices {:card #(and (corp? %) (not= (:title %) "Reclamation Order") (in-discard? %))} :msg (msg "name " (:title target)) :async true :effect (req (let [title (:title target) cards (filter #(= title (:title %)) (:discard corp)) n (count cards)] (continue-ability state side {:prompt (str "Choose how many copies of " title " to reveal") :choices {:number (req n)} :msg (msg "reveal " (quantify target "cop" "y" "ies") " of " title " from Archives" (when (pos? target) (str " and add " (if (= 1 target) "it" "them") " to HQ"))) :async true :effect (req (wait-for (reveal state side cards) (doseq [c (->> cards (sort-by :seen) reverse (take target))] (move state side c :hand)) (effect-completed state side eid)))} card nil)))}}) (defcard "Recruiting Trip" (let [rthelp (fn rt [total left selected] (if (pos? left) {:prompt (str "Choose a Sysop (" (inc (- total left)) "/" total ")") :choices (req (cancellable (filter #(and (has-subtype? % "Sysop") (not-any? #{(:title %)} selected)) (:deck corp)) :sorted)) :msg (msg "put " (:title target) " into HQ") :async true :effect (req (move state side target :hand) (continue-ability state side (rt total (dec left) (cons (:title target) selected)) card nil))} {:effect (effect (shuffle! :corp :deck)) :msg (msg "shuffle R&D")}))] {:on-play {:prompt "How many Sysops?" :choices :credit :msg (msg "search for " target " Sysops") :async true :effect (effect (continue-ability (rthelp target target []) card nil))}})) (defcard "Red Level Clearance" (let [all [{:msg "gain 2 [Credits]" :async true :effect (effect (gain-credits eid 2))} {:msg "draw 2 cards" :async true :effect (effect (draw eid 2 nil))} {:msg "gain [Click]" :effect (effect (gain :click 1))} {:prompt "Choose a non-agenda to install" :msg "install a non-agenda from hand" :choices {:card #(and (not (agenda? %)) (not (operation? %)) (in-hand? %))} :async true :effect (effect (corp-install eid target nil nil))}] can-install? (fn [hand] (seq (remove #(or (agenda? %) (operation? %)) hand))) choice (fn choice [abis chose-once] {:prompt "Choose an ability to resolve" :choices (map #(capitalize (:msg %)) abis) :async true :effect (req (let [chosen (some #(when (= target (capitalize (:msg %))) %) abis)] (if (or (not= target "Install a non-agenda from hand") (and (= target "Install a non-agenda from hand") (can-install? (:hand corp)))) (wait-for (resolve-ability state side chosen card nil) (if (false? chose-once) (continue-ability state side (choice (remove #(= % chosen) abis) true) card nil) (effect-completed state side eid))) (continue-ability state side (choice abis chose-once) card nil))))})] {:on-play {:waiting-prompt "Corp to use Red Level Clearance" :async true :effect (effect (continue-ability (choice all false) card nil))}})) (defcard "Red Planet Couriers" {:on-play {:req (req (some #(can-be-advanced? %) (all-installed state :corp))) :prompt "Select an installed card that can be advanced" :choices {:card can-be-advanced?} :async true :effect (req (let [installed (get-all-installed state) total-adv (reduce + (map #(get-counters % :advancement) installed))] (doseq [c installed] (add-prop state side c :advance-counter (- (get-counters c :advancement)) {:placed true})) (add-prop state side target :advance-counter total-adv {:placed true}) (update-all-ice state side) (system-msg state side (str "uses Red Planet Couriers to move " total-adv " advancement tokens to " (card-str state target))) (effect-completed state side eid)))}}) (defcard "Replanting" (letfn [(replant [n] {:prompt "Select a card to install with Replanting" :async true :choices {:card #(and (corp? %) (not (operation? %)) (in-hand? %))} :effect (req (wait-for (corp-install state side target nil {:ignore-all-cost true}) (if (< n 2) (continue-ability state side (replant (inc n)) card nil) (effect-completed state side eid))))})] {:on-play {:prompt "Select an installed card to add to HQ" :choices {:card #(and (corp? %) (installed? %))} :msg (msg "add " (card-str state target) " to HQ, then install 2 cards ignoring all costs") :async true :effect (req (move state side target :hand) (continue-ability state side (replant 1) card nil))}})) (defcard "Restore" {:on-play {:prompt "Select a card in Archives to install & rez" :show-discard true :choices {:card #(and (corp? %) (not (operation? %)) (in-discard? %))} :async true :effect (req (wait-for (corp-install state side target nil {:install-state :rezzed}) (let [seen (assoc target :seen true)] (system-msg state side (str "uses Restore to " (corp-install-msg seen))) (let [leftover (filter #(= (:title target) (:title %)) (-> @state :corp :discard))] (when (seq leftover) (doseq [c leftover] (move state side c :rfg)) (system-msg state side (str "removes " (count leftover) " copies of " (:title target) " from the game")))) (effect-completed state side eid))))}}) (defcard "Restoring Face" {:on-play {:prompt "Select a Sysop, Executive or Clone to trash" :msg (msg "trash " (:title target) " to remove 2 bad publicity") :choices {:card #(or (has-subtype? % "Clone") (has-subtype? % "Executive") (has-subtype? % "Sysop"))} :async true :effect (req (wait-for (lose-bad-publicity state side 2) (wait-for (resolve-ability state side (when (facedown? target) {:async true :effect (effect (reveal eid target))}) card targets) (trash state side eid target nil))))}}) (defcard "Retribution" {:on-play {:req (req (and tagged (->> (all-installed state :runner) (filter #(or (hardware? %) (program? %))) not-empty))) :prompt "Choose a program or hardware to trash" :choices {:req (req (and (installed? target) (or (program? target) (hardware? target))))} :msg (msg "trash " (card-str state target)) :async true :effect (effect (trash eid target))}}) (defcard "Restructure" {:on-play {:msg "gain 15 [Credits]" :async true :effect (effect (gain-credits eid 15))}}) (defcard "Reuse" {:on-play {:prompt (msg "Select up to " (quantify (count (:hand corp)) "card") " in HQ to trash") :choices {:max (req (count (:hand corp))) :card #(and (corp? %) (in-hand? %))} :msg (msg (let [m (count targets)] (str "trash " (quantify m "card") " and gain " (* 2 m) " [Credits]"))) :async true :effect (req (wait-for (trash-cards state side targets {:unpreventable true}) (gain-credits state side eid (* 2 (count async-result)))))}}) (defcard "Reverse Infection" {:on-play {:prompt "Choose one:" :choices ["Purge virus counters" "Gain 2 [Credits]"] :async true :effect (req (if (= target "Gain 2 [Credits]") (wait-for (gain-credits state side 2) (system-msg state side "uses Reverse Infection to gain 2 [Credits]") (effect-completed state side eid)) (let [pre-purge-virus (number-of-virus-counters state)] (purge state side) (let [post-purge-virus (number-of-virus-counters state) num-virus-purged (- pre-purge-virus post-purge-virus) num-to-trash (quot num-virus-purged 3)] (wait-for (mill state :corp :runner num-to-trash) (system-msg state side (str "uses Reverse Infection to purge " (quantify num-virus-purged "virus counter") " and trash " (quantify num-to-trash "card") " from the top of the stack")) (effect-completed state side eid))))))}}) (defcard "Rework" {:on-play {:prompt "Select a card from HQ to shuffle into R&D" :choices {:card #(and (corp? %) (in-hand? %))} :msg "shuffle a card from HQ into R&D" :effect (effect (move target :deck) (shuffle! :deck))}}) (defcard "Riot Suppression" {:on-play {:rfg-instead-of-trashing true :optional {:req (req (last-turn? state :runner :trashed-card)) :waiting-prompt "Runner to decide if they will take 1 brain damage" :prompt "Take 1 brain damage to prevent having 3 fewer clicks next turn?" :player :runner :yes-ability {:async true :effect (effect (system-msg "suffers 1 brain damage to prevent losing 3[Click] to Riot Suppression") (damage eid :brain 1 {:card card}))} :no-ability {:msg "give the Runner 3 fewer [Click] next turn" :effect (req (swap! state update-in [:runner :extra-click-temp] (fnil #(- % 3) 0)))}}}}) (defcard "Rolling Brownout" {:on-play {:msg "increase the play cost of operations and events by 1 [Credits]"} :constant-effects [{:type :play-cost :value 1}] :events [{:event :play-event :once :per-turn :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Rover Algorithm" {:on-play {:choices {:card #(and (ice? %) (rezzed? %))} :msg (msg "host it as a condition counter on " (card-str state target)) :effect (effect (host target (assoc card :installed true :seen true :condition true)) (update-ice-strength (get-card state target)))} :constant-effects [{:type :ice-strength :req (req (same-card? target (:host card))) :value (req (get-counters card :power))}] :events [{:event :pass-ice :condition :hosted :req (req (same-card? (:ice context) (:host card))) :msg (msg "add 1 power counter to itself") :effect (effect (add-counter card :power 1))}]}) (defcard "Sacrifice" {:on-play {:req (req (and (pos? (count-bad-pub state)) (some #(pos? (:agendapoints %)) (:scored corp)))) :additional-cost [:forfeit] :async true :effect (req (let [bp-lost (max 0 (min (:agendapoints (last (:rfg corp))) (count-bad-pub state)))] (system-msg state side (str "uses Sacrifice to lose " bp-lost " bad publicity and gain " bp-lost " [Credits]")) (if (pos? bp-lost) (wait-for (lose-bad-publicity state side bp-lost) (gain-credits state side eid bp-lost)) (effect-completed state side eid))))}}) (defcard "Salem's Hospitality" {:on-play {:prompt "Name a Runner card" :choices {:card-title (req (and (runner? target) (not (identity? target))))} :async true :effect (req (system-msg state side (str "uses Salem's Hospitality to reveal the Runner's Grip ( " (string/join ", " (map :title (sort-by :title (:hand runner)))) " ) and trash any copies of " target)) (let [cards (filter #(= target (:title %)) (:hand runner))] (wait-for (reveal state side cards) (trash-cards state side eid cards {:unpreventable true}))))}}) (defcard "Scapenet" {:on-play {:trace {:req (req (last-turn? state :runner :successful-run)) :base 7 :successful {:prompt "Choose an installed virtual or chip card to remove from game" :choices {:card #(and (installed? %) (or (has-subtype? % "Virtual") (has-subtype? % "Chip")))} :msg (msg "remove " (card-str state target) " from game") :async true :effect (effect (move :runner target :rfg) (effect-completed eid))}}}}) (defcard "Scarcity of Resources" {:on-play {:msg "increase the install cost of resources by 2"} :constant-effects [{:type :install-cost :req (req (resource? target)) :value 2}]}) (defcard "Scorched Earth" {:on-play {:req (req tagged) :msg "do 4 meat damage" :async true :effect (effect (damage eid :meat 4 {:card card}))}}) (defcard "SEA Source" {:on-play {:trace {:base 3 :req (req (last-turn? state :runner :successful-run)) :label "Trace 3 - Give the Runner 1 tag" :successful {:msg "give the Runner 1 tag" :async true :effect (effect (gain-tags :corp eid 1))}}}}) (defcard "Seamless Launch" {:on-play {:prompt "Select target" :req (req (some #(and (corp? %) (installed? %) (not (= :this-turn (installed? %)))) (all-installed state :corp))) :choices {:card #(and (corp? %) (installed? %) (not (= :this-turn (installed? %))))} :msg (msg "place 2 advancement tokens on " (card-str state target)) :async true :effect (effect (add-prop eid target :advance-counter 2 {:placed true}))}}) (defcard "Secure and Protect" {:on-play {:interactive (req true) :waiting-prompt "Corp to use Secure and Protect" :async true :effect (req (if (seq (filter ice? (:deck corp))) (continue-ability state side {:async true :prompt "Choose a piece of ice" :choices (req (filter ice? (:deck corp))) :effect (effect (continue-ability (let [chosen-ice target] {:async true :prompt (str "Select where to install " (:title chosen-ice)) :choices ["Archives" "R&D" "HQ"] :msg (msg "reveal " (:title chosen-ice) " and install it, paying 3 [Credit] less") :effect (req (wait-for (reveal state side chosen-ice) (shuffle! state side :deck) (corp-install state side eid chosen-ice target {:cost-bonus -3})))}) card nil))} card nil) (do (shuffle! state side :deck) (effect-completed state side eid))))}}) (defcard "Self-Growth Program" {:on-play {:req (req tagged) :prompt "Select two installed Runner cards" :choices {:card #(and (installed? %) (runner? %)) :max 2} :msg (msg (str "move " (string/join ", " (map :title targets)) " to the Runner's grip")) :effect (req (doseq [c targets] (move state :runner c :hand)))}}) (defcard "Service Outage" {:on-play {:msg "add a cost of 1 [Credit] for the Runner to make the first run each turn"} :constant-effects [{:type :run-additional-cost :req (req (no-event? state side :run)) :value [:credit 1]}]}) (defcard "Shipment from Kaguya" {:on-play {:choices {:max 2 :card #(and (corp? %) (installed? %) (can-be-advanced? %))} :msg (msg "place 1 advancement token on " (count targets) " cards") :effect (req (doseq [t targets] (add-prop state :corp t :advance-counter 1 {:placed true})))}}) (defcard "Shipment from MirrorMorph" (letfn [(shelper [n] (when (< n 3) {:async true :prompt "Select a card to install with Shipment from MirrorMorph" :choices {:card #(and (corp? %) (not (operation? %)) (in-hand? %))} :effect (req (wait-for (corp-install state side target nil nil) (continue-ability state side (shelper (inc n)) card nil)))}))] {:on-play {:async true :effect (effect (continue-ability (shelper 0) card nil))}})) (defcard "Shipment from SanSan" {:on-play {:choices ["0" "1" "2"] :prompt "How many advancement tokens?" :async true :effect (req (let [c (str->int target)] (continue-ability state side {:choices {:card can-be-advanced?} :msg (msg "place " c " advancement tokens on " (card-str state target)) :effect (effect (add-prop :corp target :advance-counter c {:placed true}))} card nil)))}}) (defcard "Shipment from <NAME>" {:on-play {:req (req (not-last-turn? state :runner :successful-run)) :choices {:card #(and (corp? %) (installed? %))} :msg (msg "place 2 advancement tokens on " (card-str state target)) :effect (effect (add-prop target :advance-counter 2 {:placed true}))}}) (defcard "Shoot the Moon" (letfn [(rez-helper [ice] (when (seq ice) {:async true :effect (req (wait-for (rez state side (first ice) {:ignore-cost :all-costs}) (continue-ability state side (rez-helper (rest ice)) card nil)))}))] {:on-play {:req (req tagged) :choices {:card #(and (ice? %) (not (rezzed? %))) :max (req (min (count-tags state) (reduce (fn [c server] (+ c (count (filter #(not (:rezzed %)) (:ices server))))) 0 (flatten (seq (:servers corp))))))} :async true :effect (effect (continue-ability (rez-helper targets) card nil))}})) (defcard "Snatch and Grab" {:on-play {:trace {:base 3 :successful {:waiting-prompt "Corp to use Snatch and Grab" :msg "trash a connection" :choices {:card #(has-subtype? % "Connection")} :async true :effect (effect (continue-ability (let [c target] {:optional {:player :runner :waiting-prompt "Runner to decide if they will take 1 tag" :prompt (str "Take 1 tag to prevent " (:title c) " from being trashed?") :yes-ability {:async true :msg (msg "take 1 tag to prevent " (:title c) " from being trashed") :effect (effect (gain-tags :runner eid 1 {:unpreventable true}))} :no-ability {:async true :msg (msg "trash " (:title c)) :effect (effect (trash :corp eid c nil))}}}) card nil))}}}}) (defcard "Special Report" {:on-play {:prompt "Select any number of cards in HQ to shuffle into R&D" :choices {:max (req (count (:hand corp))) :card #(and (corp? %) (in-hand? %))} :msg (msg "shuffle " (count targets) " cards in HQ into R&D and draw " (count targets) " cards") :async true :effect (req (doseq [c targets] (move state side c :deck)) (shuffle! state side :deck) (draw state side eid (count targets) nil))}}) (defcard "Sprint" {:on-play {:async true :effect (req (wait-for (draw state side 3 nil) (system-msg state side (str "uses Sprint to draw " (quantify (count async-result) "card"))) (continue-ability state side {:prompt "Select 2 cards in HQ to shuffle" :choices {:max 2 :card #(and (corp? %) (in-hand? %))} :msg "shuffles 2 cards from HQ into R&D" :effect (req (doseq [c targets] (move state side c :deck)) (shuffle! state side :deck))} card nil)))}}) (defcard "Standard Procedure" {:on-play {:req (req (last-turn? state :runner :successful-run)) :prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :msg (msg "name " target ", revealing " (string/join ", " (map :title (:hand runner))) " in the Runner's Grip, and gains " (* 2 (count (filter #(is-type? % target) (:hand runner)))) " [Credits]") :async true :effect (req (wait-for (reveal state side (:hand runner)) (gain-credits state :corp eid (* 2 (count (filter #(is-type? % target) (:hand runner)))))))}}) (defcard "Stock Buy-Back" {:on-play {:msg (msg "gain " (* 3 (count (:scored runner))) " [Credits]") :async true :effect (effect (gain-credits eid (* 3 (count (:scored runner)))))}}) (defcard "Sub Boost" (let [new-sub {:label "[Sub Boost]: End the run"}] {:sub-effect {:label "End the run" :msg "end the run" :async true :effect (effect (end-run eid card))} :on-play {:choices {:card #(and (ice? %) (rezzed? %))} :msg (msg "make " (card-str state target) " gain Barrier and \"[Subroutine] End the run\"") :effect (req (add-extra-sub! state :corp (get-card state target) new-sub (:cid card)) (host state side (get-card state target) (assoc card :seen true :condition true)))} :constant-effects [{:type :gain-subtype :req (req (and (same-card? target (:host card)) (rezzed? target))) :value "Barrier"}] :leave-play (req (remove-extra-subs! state :corp (:host card) (:cid card))) :events [{:event :rez :req (req (same-card? (:card context) (:host card))) :effect (req (add-extra-sub! state :corp (get-card state (:card context)) new-sub (:cid card)))}]})) (defcard "Subcontract" (letfn [(sc [i sccard] {:prompt "Select an operation in HQ to play" :choices {:card #(and (corp? %) (operation? %) (in-hand? %))} :async true :msg (msg "play " (:title target)) :effect (req (wait-for (play-instant state side target nil) (if (and (not (get-in @state [:corp :register :terminal])) (< i 2)) (continue-ability state side (sc (inc i) sccard) sccard nil) (effect-completed state side eid))))})] {:on-play {:req (req tagged) :async true :effect (effect (continue-ability (sc 1 card) card nil))}})) (defcard "Subliminal Messaging" {:on-play {:msg "gain 1 [Credits]" :async true :effect (req (wait-for (gain-credits state side 1) (continue-ability state side {:once :per-turn :once-key :subliminal-messaging :msg "gain [Click]" :effect (effect (gain :corp :click 1))} card nil)))} :events [{:event :corp-phase-12 :location :discard :optional {:req (req (not-last-turn? state :runner :made-run)) :prompt "Add Subliminal Messaging to HQ?" :yes-ability {:msg "add Subliminal Messaging to HQ" :effect (effect (move card :hand))}}}]}) (defcard "Success" (letfn [(advance-n-times [state side eid card target n] (if (pos? n) (wait-for (advance state :corp (make-eid state {:source card}) (get-card state target) :no-cost) (advance-n-times state side eid card target (dec n))) (effect-completed state side eid)))] {:on-play {:additional-cost [:forfeit] :choices {:card can-be-advanced?} :msg (msg "advance " (card-str state target) " " (quantify (get-advancement-requirement (cost-target eid :forfeit)) "time")) :async true :effect (effect (advance-n-times eid card target (get-advancement-requirement (cost-target eid :forfeit))))}})) (defcard "Successful Demonstration" {:on-play {:req (req (last-turn? state :runner :unsuccessful-run)) :msg "gain 7 [Credits]" :async true :effect (effect (gain-credits eid 7))}}) (defcard "Sunset" (letfn [(sun [serv] {:prompt "Select two pieces of ICE to swap positions" :choices {:card #(and (= serv (get-zone %)) (ice? %)) :max 2} :async true :effect (req (if (= (count targets) 2) (do (swap-ice state side (first targets) (second targets)) (system-msg state side (str "uses Sunset to swap " (card-str state (first targets)) " with " (card-str state (second targets)))) (continue-ability state side (sun serv) card nil)) (do (system-msg state side "has finished rearranging ICE") (effect-completed state side eid))))})] {:on-play {:prompt "Choose a server" :choices (req servers) :msg (msg "rearrange ICE protecting " target) :async true :effect (req (let [serv (conj (server->zone state target) :ices)] (continue-ability state side (sun serv) card nil)))}})) (defcard "Surveillance Sweep" {:events [{:event :pre-init-trace :req (req run) :effect (req (swap! state assoc-in [:trace :player] :runner))}]}) (defcard "Sweeps Week" {:on-play {:msg (msg "gain " (count (:hand runner)) " [Credits]") :async true :effect (effect (gain-credits eid (count (:hand runner))))}}) (defcard "SYNC Rerouting" {:on-play {:trash-after-resolving false} :events [{:event :run :async true :msg (msg "force the Runner to " (decapitalize target)) :player :runner :prompt "Pay 4 [Credits] or take 1 tag?" :choices ["Pay 4 [Credits]" "Take 1 tag"] :effect (req (if (= target "Pay 4 [Credits]") (wait-for (pay state :runner card :credit 4) (system-msg state :runner (:msg async-result)) (effect-completed state side eid)) (gain-tags state :corp eid 1 nil)))} {:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "Targeted Marketing" (let [gaincr {:req (req (= (:title (:card context)) (get-in card [:special :marketing-target]))) :async true :msg (msg "gain 10 [Credits] from " (:marketing-target card)) :effect (effect (gain-credits :corp eid 10))}] {:on-play {:prompt "Name a Runner card" :choices {:card-title (req (and (runner? target) (not (identity? target))))} :effect (effect (update! (assoc-in card [:special :marketing-target] target)) (system-msg (str "uses Targeted Marketing to name " target)))} :events [(assoc gaincr :event :runner-install) (assoc gaincr :event :play-event)]})) (defcard "The All-Seeing I" (let [trash-all-resources {:msg "trash all resources" :async true :effect (effect (trash-cards :corp eid (filter resource? (all-active-installed state :runner))))}] {:on-play {:req (req tagged) :async true :effect (effect (continue-ability (if (pos? (count-bad-pub state)) {:optional {:player :runner :prompt "Remove 1 bad publicity to prevent all resources from being trashed?" :yes-ability {:msg "remove 1 bad publicity, preventing all resources from being trashed" :async true :effect (effect (lose-bad-publicity eid 1))} :no-ability trash-all-resources}} trash-all-resources) card nil))}})) (defcard "Threat Assessment" {:on-play {:req (req (last-turn? state :runner :trashed-card)) :prompt "Select an installed Runner card" :choices {:card #(and (runner? %) (installed? %))} :rfg-instead-of-trashing true :async true :effect (effect (continue-ability (let [chosen target] {:player :runner :waiting-prompt "Runner to resolve Threat Assessment" :prompt (str "Add " (:title chosen) " to the top of the Stack or take 2 tags?") :choices [(str "Move " (:title chosen)) "Take 2 tags"] :async true :effect (req (if (= target "Take 2 tags") (do (system-msg state side "chooses to take 2 tags") (gain-tags state :runner eid 2)) (do (system-msg state side (str "chooses to move " (:title chosen) " to the Stack")) (move state :runner chosen :deck {:front true}) (effect-completed state side eid))))}) card nil))}}) (defcard "Threat Level Alpha" {:on-play {:trace {:base 1 :successful {:label "Give the Runner X tags" :async true :effect (req (let [tags (max 1 (count-tags state))] (gain-tags state :corp eid tags) (system-msg state side (str "uses Threat Level Alpha to give the Runner " (quantify tags "tag")))))}}}}) (defcard "Too Big to Fail" {:on-play {:req (req (< (:credit corp) 10)) :msg "gain 7 [Credits] and take 1 bad publicity" :async true :effect (req (wait-for (gain-credits state side 7) (gain-bad-publicity state :corp eid 1)))}}) (defcard "Traffic Accident" {:on-play {:req (req (<= 2 (count-tags state))) :msg "do 2 meat damage" :async true :effect (effect (damage eid :meat 2 {:card card}))}}) (defcard "Transparency Initiative" {:constant-effects [{:type :gain-subtype :req (req (and (same-card? target (:host card)) (rezzed? target))) :value "Public"}] :on-play {:choices {:card #(and (agenda? %) (installed? %) (not (faceup? %)))} :effect (req (let [target (update! state side (assoc target :seen true :rezzed true)) card (host state side target (assoc card :seen true :condition true))] (register-events state side card [{:event :advance :location :hosted :req (req (same-card? (:host card) target)) :async true :msg "gain 1 [Credit]" :effect (effect (gain-credits eid 1))}])))}}) (defcard "Trick of Light" {:on-play {:req (req (let [advanceable (some can-be-advanced? (get-all-installed state)) advanced (some #(get-counters % :advancement) (get-all-installed state))] (and advanceable advanced))) :choices {:card #(and (pos? (get-counters % :advancement)) (installed? %))} :async true :effect (effect (continue-ability (let [fr target] {:async true :prompt "Move how many advancement tokens?" :choices (take (inc (get-counters fr :advancement)) ["0" "1" "2"]) :effect (effect (continue-ability (let [c (str->int target)] {:prompt "Move to where?" :choices {:card #(and (not (same-card? fr %)) (can-be-advanced? %))} :msg (msg "move " c " advancement tokens from " (card-str state fr) " to " (card-str state target)) :effect (effect (add-prop :corp target :advance-counter c {:placed true}) (add-prop :corp fr :advance-counter (- c) {:placed true}))}) card nil))}) card nil))}}) (defcard "<NAME>" {:on-play {:trace {:base 4 :req (req (:accessed-cards runner-reg-last)) :label "Trace 4 - Trash a program" :successful {:async true :effect (req (let [exceed (- target (second targets))] (continue-ability state side {:async true :prompt (str "Select a program with an install cost of no more than " exceed "[Credits]") :choices {:card #(and (program? %) (installed? %) (>= exceed (:cost %)))} :msg (msg "trash " (card-str state target)) :effect (effect (trash eid target nil))} card nil)))}}}}) (defcard "Ultraviolet Clearance" {:on-play {:async true :effect (req (wait-for (gain-credits state side 10) (wait-for (draw state side 4 nil) (continue-ability state side {:prompt "Choose a card in HQ to install" :choices {:card #(and (in-hand? %) (corp? %) (not (operation? %)))} :msg "gain 10 [Credits], draw 4 cards, and install 1 card from HQ" :cancel-effect (req (effect-completed state side eid)) :async true :effect (effect (corp-install eid target nil nil))} card nil))))}}) (defcard "Under the Bus" {:on-play {:req (req (and (last-turn? state :runner :accessed-cards) (not-empty (filter #(and (resource? %) (has-subtype? % "Connection")) (all-active-installed state :runner))))) :prompt "Choose a connection to trash" :choices {:card #(and (runner? %) (resource? %) (has-subtype? % "Connection") (installed? %))} :msg (msg "trash " (:title target) " and take 1 bad publicity") :async true :effect (req (wait-for (trash state side target nil) (gain-bad-publicity state :corp eid 1)))}}) (defcard "Violet Level Clearance" {:on-play {:msg "gain 8 [Credits] and draw 4 cards" :async true :effect (req (wait-for (gain-credits state side 8) (draw state side eid 4 nil)))}}) (defcard "Voter Intimidation" {:on-play {:psi {:req (req (seq (:scored runner))) :not-equal {:player :corp :async true :prompt "Select a resource to trash" :choices {:card #(and (installed? %) (resource? %))} :msg (msg "trash " (:title target)) :effect (effect (trash eid target nil))}}}}) (defcard "Wake Up Call" {:on-play {:rfg-instead-of-trashing true :req (req (last-turn? state :runner :trashed-card)) :prompt "Select a piece of hardware or non-virtual resource" :choices {:card #(or (hardware? %) (and (resource? %) (not (has-subtype? % "Virtual"))))} :async true :effect (effect (continue-ability (let [chosen target wake card] {:player :runner :waiting-prompt "Runner to resolve Wake Up Call" :prompt (str "Trash " (:title chosen) " or suffer 4 meat damage?") :choices [(str "Trash " (:title chosen)) "4 meat damage"] :async true :effect (req (if (= target "4 meat damage") (do (system-msg state side "chooses to suffer meat damage") (damage state side eid :meat 4 {:card wake :unboostable true})) (do (system-msg state side (str "chooses to trash " (:title chosen))) (trash state side eid chosen nil))))}) card nil))}}) (defcard "Wetwork Refit" (let [new-sub {:label "[Wetwork Refit] Do 1 brain damage"}] {:on-play {:choices {:card #(and (ice? %) (has-subtype? % "Bioroid") (rezzed? %))} :msg (msg "give " (card-str state target) " \"[Subroutine] Do 1 brain damage\" before all its other subroutines") :effect (req (add-extra-sub! state :corp target new-sub (:cid card) {:front true}) (host state side (get-card state target) (assoc card :seen true :condition true)))} :sub-effect (do-brain-damage 1) :leave-play (req (remove-extra-subs! state :corp (:host card) (:cid card))) :events [{:event :rez :req (req (same-card? (:card context) (:host card))) :effect (req (add-extra-sub! state :corp (get-card state (:card context)) new-sub (:cid card) {:front true}))}]})) (defcard "Witness Tampering" {:on-play {:msg "remove 2 bad publicity" :effect (effect (lose-bad-publicity 2))}})
true
(ns game.cards.operations (:require [game.core :refer :all] [game.utils :refer :all] [jinteki.utils :refer :all] [clojure.string :as string])) ;; Card definitions (defcard "24/7 News Cycle" {:on-play {:req (req (pos? (count (:scored corp)))) :additional-cost [:forfeit] :async true :effect (effect (continue-ability {:prompt "Select an agenda in your score area to trigger its \"when scored\" ability" :choices {:card #(and (agenda? %) (when-scored? %) (is-scored? state :corp %))} :msg (msg "trigger the \"when scored\" ability of " (:title target)) :async true :effect (effect (continue-ability (:on-score (card-def target)) target nil))} card nil))}}) (defcard "Accelerated Diagnostics" (letfn [(ad [st si e c cards] (when-let [cards (filterv #(and (operation? %) (can-pay? st si (assoc e :source c :source-type :play) c nil [:credit (play-cost st si %)])) cards)] {:async true :prompt "Select an operation to play" :choices (cancellable cards) :msg (msg "play " (:title target)) :effect (req (wait-for (play-instant state side target {:no-additional-cost true}) (let [cards (filterv #(not (same-card? % target)) cards)] (continue-ability state side (ad state side eid card cards) card nil))))}))] {:on-play {:prompt (msg "The top 3 cards of R&D are " (string/join ", " (map :title (take 3 (:deck corp)))) ".") :choices ["OK"] :async true :effect (effect (continue-ability (ad state side eid card (take 3 (:deck corp))) card nil))}})) (defcard "PI:NAME:<NAME>END_PI" (letfn [(ab [n total] (when (< n total) {:async true :show-discard true :prompt "Select an Advertisement to install and rez" :choices {:card #(and (corp? %) (has-subtype? % "Advertisement") (or (in-hand? %) (in-discard? %)))} :effect (req (wait-for (corp-install state side target nil {:install-state :rezzed}) (continue-ability state side (ab (inc n) total) card nil)))}))] {:on-play {:req (req (some #(has-subtype? % "Advertisement") (concat (:discard corp) (:hand corp)))) :prompt "How many Advertisements?" :choices :credit :msg (msg "install and rez " target " Advertisements") :async true :effect (effect (continue-ability (ab 0 target) card nil))}})) (defcard "Aggressive Negotiation" {:on-play {:req (req (:scored-agenda corp-reg)) :prompt "Choose a card" :choices (req (cancellable (:deck corp) :sorted)) :msg "search R&D for a card and add it to HQ" :effect (effect (move target :hand) (shuffle! :deck))}}) (defcard "An Offer You Can't Refuse" {:on-play {:async true :prompt "Choose a server" :choices ["Archives" "R&D" "HQ"] :effect (effect (show-wait-prompt (str "Runner to decide on running " target)) (continue-ability (let [serv target] {:optional {:prompt (str "Make a run on " serv "?") :player :runner :yes-ability {:msg (str "let the Runner make a run on " serv) :async true :effect (effect (clear-wait-prompt :corp) (make-run eid serv card) (prevent-jack-out))} :no-ability {:async true :msg "add it to their score area as an agenda worth 1 agenda point" :effect (effect (clear-wait-prompt :corp) (as-agenda :corp eid card 1))}}}) card nil))}}) (defcard "Anonymous Tip" {:on-play {:msg "draw 3 cards" :async true :effect (effect (draw eid 3 nil))}}) (defcard "Archived Memories" {:on-play {:prompt "Select a card from Archives to add to HQ" :show-discard true :choices {:card #(and (corp? %) (in-discard? %))} :msg (msg "add " (if (faceup? target) (:title target) "an unseen card") " to HQ") :effect (effect (move target :hand))}}) (defcard "Argus Crackdown" {:on-play {:trash-after-resolving false} :events [{:event :successful-run :req (req (not-empty run-ices)) :msg (msg "deal 2 meat damage") :async true :effect (effect (damage eid :meat 2 {:card card}))} {:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "Ark Lockdown" {:on-play {:req (req (and (not-empty (:discard runner)) (not (zone-locked? state :runner :discard)))) :prompt "Name a card to remove all copies in the Heap from the game" :choices (req (cancellable (:discard runner) :sorted)) :msg (msg "remove all copies of " (:title target) " in the Heap from the game") :async true :effect (req (doseq [c (filter #(same-card? :title target %) (:discard runner))] (move state :runner c :rfg)) (effect-completed state side eid))}}) (defcard "Attitude Adjustment" {:on-play {:async true :effect (req (wait-for (draw state side 2 nil) (continue-ability state side {:prompt "Choose up to 2 agendas in HQ or Archives" :choices {:max 2 :card #(and (corp? %) (agenda? %) (or (in-hand? %) (in-discard? %)))} :async true :effect (req (wait-for (reveal state side targets) (wait-for (gain-credits state side (* 2 (count targets))) (doseq [c targets] (move state :corp c :deck)) (shuffle! state :corp :deck) (let [from-hq (map :title (filter in-hand? targets)) from-archives (map :title (filter in-discard? targets))] (system-msg state side (str "uses Attitude Adjustment to shuffle " (string/join " and " (filter identity [(when (not-empty from-hq) (str (string/join " and " from-hq) " from HQ")) (when (not-empty from-archives) (str (string/join " and " from-archives) " from Archives"))])) " into R&D and gain " (* 2 (count targets)) " [Credits]"))) (effect-completed state side eid))))} card nil)))}}) (defcard "Audacity" (letfn [(audacity [n] (if (< n 2) {:prompt "Choose a card on which to place an advancement" :async true :choices {:card can-be-advanced? :all true} :msg (msg "place an advancement token on " (card-str state target)) :effect (req (add-prop state :corp target :advance-counter 1 {:placed true}) (continue-ability state side (audacity (inc n)) card nil))}))] {:on-play {:req (req (and (<= 3 (count (:hand corp))) (some can-be-advanced? (all-installed state :corp)))) :async true :effect (req (system-msg state side "trashes all cards in HQ due to Audacity") (wait-for (trash-cards state side (:hand corp) {:unpreventable true}) (continue-ability state side (audacity 0) card nil)))}})) (defcard "Back Channels" {:on-play {:prompt "Select an installed card in a server to trash" :choices {:card #(and (= (last (get-zone %)) :content) (is-remote? (second (get-zone %))))} :msg (msg "trash " (card-str state target) " and gain " (* 3 (get-counters target :advancement)) " [Credits]") :async true :effect (req (wait-for (gain-credits state side (* 3 (get-counters target :advancement))) (trash state side eid target nil)))}}) (defcard "Bad Times" {:implementation "Any required program trashing is manual" :on-play {:req (req tagged) :msg "force the Runner to lose 2[mu] until the end of the turn" :effect (req (register-floating-effect state :corp card (assoc (mu+ -2) :duration :end-of-turn)) (update-mu state))}}) (defcard "Beanstalk Royalties" {:on-play {:msg "gain 3 [Credits]" :async true :effect (effect (gain-credits eid 3))}}) (defcard "Best Defense" {:on-play {:req (req (not-empty (all-installed state :runner))) :prompt (msg "Choose a Runner card with an install cost of " (count-tags state) " or less to trash") :choices {:req (req (and (runner? target) (installed? target) (not (facedown? target)) (<= (:cost target) (count-tags state))))} :msg (msg "trash " (:title target)) :async true :effect (effect (trash eid target nil))}}) (defcard "Biased Reporting" (letfn [(num-installed [state t] (count (filter #(is-type? % t) (all-active-installed state :runner))))] {:on-play {:req (req (not-empty (all-active-installed state :runner))) :prompt "Choose a card type" :choices ["Hardware" "Program" "Resource"] :async true :effect (req (let [t target n (num-installed state t)] (wait-for (resolve-ability state :runner {:waiting-prompt "Runner to choose cards to trash" :prompt (msg "Choose any number of cards of type " t " to trash") :choices {:max n :card #(and (installed? %) (is-type? % t))} :async true :effect (req (wait-for (trash-cards state :runner targets {:unpreventable true}) (let [trashed-cards async-result] (wait-for (gain-credits state :runner (count trashed-cards)) (system-msg state :runner (str "trashes " (string/join ", " (map :title trashed-cards)) " and gains " (count trashed-cards) " [Credits]")) (effect-completed state side eid)))))} card nil) (let [n (* 2 (num-installed state t))] (if (pos? n) (do (system-msg state :corp (str "uses Biased Reporting to gain " n " [Credits]")) (gain-credits state :corp eid n)) (effect-completed state side eid))))))}})) (defcard "PI:NAME:<NAME>END_PI" {:on-play {:req (req tagged) :msg "give the Runner 2 tags" :async true :effect (effect (gain-tags :corp eid 2))}}) (defcard "Bioroid Efficiency Research" {:on-play {:req (req (some #(and (ice? %) (has-subtype? % "Bioroid") (not (rezzed? %))) (all-installed state :corp))) :choices {:card #(and (ice? %) (has-subtype? % "Bioroid") (installed? %) (not (rezzed? %)))} :msg (msg "rez " (card-str state target {:visible true}) " at no cost") :async true :effect (req (wait-for (rez state side target {:ignore-cost :all-costs}) (host state side (:card async-result) (assoc card :seen true :condition true)) (effect-completed state side eid)))} :events [{:event :end-of-encounter :condition :hosted :async true :req (req (and (same-card? (:ice context) (:host card)) (empty? (remove :broken (:subroutines (:ice context)))))) :effect (effect (system-msg :corp (str "derezzes " (:title (:ice context)) " and trashes Bioroid Efficiency Research")) (derez :corp (:ice context)) (trash :corp eid card {:unpreventable true}))}]}) (defcard "Biotic Labor" {:on-play {:msg "gain [Click][Click]" :effect (effect (gain :click 2))}}) (defcard "Blue Level Clearance" {:on-play {:msg "gain 5 [Credits] and draw 2 cards" :async true :effect (req (wait-for (gain-credits state side 5) (draw state side eid 2 nil)))}}) (defcard "BOOM!" {:on-play {:req (req (<= 2 (count-tags state))) :msg "do 7 meat damage" :async true :effect (effect (damage eid :meat 7 {:card card}))}}) (defcard "Building Blocks" {:on-play {:req (req (pos? (count (filter #(has-subtype? % "Barrier") (:hand corp))))) :prompt "Select a Barrier to install and rez" :choices {:card #(and (corp? %) (has-subtype? % "Barrier") (in-hand? %))} :msg (msg "reveal " (:title target)) :async true :effect (req (wait-for (reveal state side target) (corp-install state side eid target nil {:ignore-all-cost true :install-state :rezzed-no-cost})))}}) (defcard "Casting Call" {:on-play {:choices {:card #(and (agenda? %) (in-hand? %))} :async true :effect (req (wait-for (corp-install state side target nil {:install-state :face-up}) (let [agenda async-result] (host state side agenda (assoc card :seen true :condition true :installed true)) (system-msg state side (str "hosts Casting Call on " (:title agenda))) (effect-completed state side eid))))} :events [{:event :access :condition :hosted :async true :req (req (same-card? target (:host card))) :msg "give the Runner 2 tags" :effect (effect (gain-tags :runner eid 2))}]}) (defcard "Celebrity Gift" {:on-play {:choices {:max 5 :card #(and (corp? %) (in-hand? %))} :msg (msg "reveal " (string/join ", " (map :title (sort-by :title targets))) " and gain " (* 2 (count targets)) " [Credits]") :async true :effect (req (wait-for (reveal state side targets) (gain-credits state side eid (* 2 (count targets)))))}}) (defcard "Cerebral Cast" {:on-play {:psi {:req (req (last-turn? state :runner :successful-run)) :not-equal {:player :runner :prompt "Take 1 tag or 1 brain damage?" :choices ["1 tag" "1 brain damage"] :msg (msg "give the Runner " target) :effect (req (if (= target "1 tag") (gain-tags state :runner eid 1) (damage state side eid :brain 1 {:card card})))}}}}) (defcard "Cerebral Static" {:on-play {:msg "disable the Runner's identity" :effect (effect (disable-identity :runner))} :leave-play (effect (enable-identity :runner))}) (defcard "\"Clones are not People\"" {:events [{:event :agenda-scored :msg "add it to their score area as an agenda worth 1 agenda point" :async true :effect (req (as-agenda state :corp eid card 1))}]}) (defcard "Closed Accounts" {:on-play {:req (req tagged) :msg (msg "force the Runner to lose all " (:credit runner) " [Credits]") :async true :effect (effect (lose-credits :runner eid :all))}}) (defcard "Commercialization" {:on-play {:msg (msg "gain " (get-counters target :advancement) " [Credits]") :choices {:card #(and (ice? %) (installed? %))} :async true :effect (effect (gain-credits eid (get-counters target :advancement)))}}) (defcard "Complete Image" (letfn [(name-a-card [] {:async true :prompt "Name a Runner card" :choices {:card-title (req (and (runner? target) (not (identity? target))))} :msg (msg "name " target) :effect (effect (continue-ability (damage-ability) card targets))}) (damage-ability [] {:async true :msg "do 1 net damage" :effect (req (wait-for (damage state side :net 1 {:card card}) (let [should-continue (not (:winner @state)) cards (some #(when (same-card? (second %) card) (last %)) (turn-events state :corp :damage)) dmg (some #(when (= (:title %) target) %) cards)] (continue-ability state side (when (and should-continue dmg) (name-a-card)) card nil))))})] {:implementation "Doesn't work with Chronos Protocol: Selective Mind-mapping" :on-play {:async true :req (req (and (last-turn? state :runner :successful-run) (<= 3 (:agenda-point runner)))) :effect (effect (continue-ability (name-a-card) card nil))}})) (defcard "Consulting Visit" {:on-play {:prompt "Choose an Operation from R&D to play" :choices (req (cancellable (filter #(and (operation? %) (<= (:cost %) (:credit corp))) (:deck corp)) :sorted)) :msg (msg "search R&D for " (:title target) " and play it") :async true :effect (effect (shuffle! :deck) (system-msg "shuffles their deck") (play-instant eid target nil))}}) (defcard "Corporate Shuffle" {:on-play {:msg "shuffle all cards in HQ into R&D and draw 5 cards" :async true :effect (effect (shuffle-into-deck :hand) (draw eid 5 nil))}}) (defcard "Cyberdex Trial" {:on-play {:msg "purge virus counters" :effect (effect (purge))}}) (defcard "Death and Taxes" {:implementation "Credit gain mandatory to save on wait-prompts, adjust credits manually if credit not wanted." :events [{:event :runner-install :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))} {:event :runner-trash :req (req (installed? (:card target))) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Dedication Ceremony" {:on-play {:prompt "Select a faceup card" :choices {:card #(or (and (corp? %) (rezzed? %)) (and (runner? %) (or (installed? %) (:host %)) (not (facedown? %))))} :msg (msg "place 3 advancement tokens on " (card-str state target)) :effect (effect (add-counter target :advancement 3 {:placed true}) (register-turn-flag! target :can-score (fn [state side card] (if (same-card? card target) ((constantly false) (toast state :corp "Cannot score due to Dedication Ceremony." "warning")) true))))}}) (defcard "Defective Brainchips" {:events [{:event :pre-damage :req (req (= target :brain)) :msg "do 1 additional brain damage" :once :per-turn :effect (effect (damage-bonus :brain 1))}]}) (defcard "Digital Rights Management" {:implementation "Does not prevent scoring agendas installed later in the turn" :on-play {:req (req (and (< 1 (:turn @state)) (not (some #{:hq} (:successful-run runner-reg-last))))) :prompt "Choose an Agenda" ; ToDo: When floating triggers are implemented, this should be an effect that listens to :corp-install as Clot does :choices (req (conj (vec (filter agenda? (:deck corp))) "None")) :msg (msg (if (not= "None" target) (str "add " (:title target) " to HQ and shuffle R&D") "shuffle R&D")) :effect (let [end-effect (req (system-msg state side "can not score agendas for the remainder of the turn") (swap! state assoc-in [:corp :register :cannot-score] (filter agenda? (all-installed state :corp))) (effect-completed state side eid))] (req (wait-for (resolve-ability state side (when-not (= "None" target) {:async true :effect (req (wait-for (reveal state side target) (move state side target :hand) (effect-completed state side eid)))}) card targets) (shuffle! state side :deck) (continue-ability state side {:prompt "You may install a card in HQ" :choices {:card #(and (in-hand? %) (corp? %) (not (operation? %)))} :effect (req (wait-for (resolve-ability state side (let [card-to-install target] {:prompt (str "Choose a location to install " (:title target)) :choices (remove #{"HQ" "R&D" "Archives"} (corp-install-list state target)) :async true :effect (effect (corp-install eid card-to-install target nil))}) target nil) (end-effect state side eid card targets))) :cancel-effect (effect (system-msg "does not use Digital Rights Management to install a card") (end-effect eid card targets))} card nil))))}}) (defcard "Distract the Masses" (let [shuffle-two {:async true :effect (effect (shuffle-into-rd-effect eid card 2))} trash-from-hq {:async true :prompt "Select up to 2 cards in HQ to trash" :choices {:max 2 :card #(and (corp? %) (in-hand? %))} :msg (msg "trash " (quantify (count targets) "card") " from HQ") :effect (req (wait-for (trash-cards state side targets nil) (continue-ability state side shuffle-two card nil))) :cancel-effect (effect (continue-ability shuffle-two card nil))}] {:on-play {:rfg-instead-of-trashing true :msg "give The Runner 2 [Credits]" :async true :effect (req (wait-for (gain-credits state :runner 2) (continue-ability state side trash-from-hq card nil)))}})) (defcard "Diversified Portfolio" (letfn [(number-of-non-empty-remotes [state] (count (filter #(not (empty? %)) (map #(:content (second %)) (get-remotes state)))))] {:on-play {:msg (msg "gain " (number-of-non-empty-remotes state) " [Credits]") :async true :effect (effect (gain-credits eid (number-of-non-empty-remotes state)))}})) (defcard "Divert Power" {:on-play {:prompt "Select any number of cards to derez" :choices {:card #(and (installed? %) (rezzed? %)) :max (req (count (filter rezzed? (all-installed state :corp))))} :async true :effect (req (doseq [c targets] (derez state side c)) (let [discount (* -3 (count targets))] (continue-ability state side {:async true :prompt "Select a card to rez" :choices {:card #(and (installed? %) (corp? %) (not (rezzed? %)) (not (agenda? %)))} :effect (effect (rez eid target {:cost-bonus discount}))} card nil)))}}) (defcard "Door to Door" {:events [{:event :runner-turn-begins :trace {:base 1 :label "Do 1 meat damage if Runner is tagged, or give the Runner 1 tag" :successful {:msg (msg (if tagged "do 1 meat damage" "give the Runner 1 tag")) :async true :effect (req (if tagged (damage state side eid :meat 1 {:card card}) (gain-tags state :corp eid 1)))}}}]}) (defcard "Eavesdrop" {:on-play {:choices {:card #(and (ice? %) (installed? %))} :msg (msg "give " (card-str state target {:visible false}) " additional text") :effect (effect (host target (assoc card :seen true :condition true)))} :events [{:event :encounter-ice :condition :hosted :trace {:base 3 :req (req (same-card? current-ice (:host card))) :successful {:msg "give the Runner 1 tag" :async true :effect (effect (gain-tags :runner eid 1))}}}]}) (defcard "Economic Warfare" {:on-play {:req (req (and (last-turn? state :runner :successful-run) (can-pay? state :runner (assoc eid :source card :source-type :ability) card nil :credit 4))) :msg "make the runner lose 4 [Credits]" :async true :effect (effect (lose-credits :runner eid 4))}}) (defcard "Election Day" {:on-play {:req (req (->> (get-in @state [:corp :hand]) (filter #(not (same-card? % card))) count pos?)) :msg (msg "trash all cards in HQ and draw 5 cards") :async true :effect (req (wait-for (trash-cards state side (get-in @state [:corp :hand])) (draw state side eid 5 nil)))}}) (defcard "Enforced Curfew" {:on-play {:msg "reduce the Runner's maximum hand size by 1"} :constant-effects [(runner-hand-size+ -1)]}) (defcard "Enforcing Loyalty" {:on-play {:trace {:base 3 :label "Trash a card not matching the faction of the Runner's identity" :successful {:async true :prompt "Select an installed card not matching the faction of the Runner's identity" :choices {:req (req (and (installed? target) (runner? target) (not= (:faction (:identity runner)) (:faction target))))} :msg (msg "trash " (:title target)) :effect (effect (trash eid target nil))}}}}) (defcard "Enhanced Login Protocol" {:on-play {:msg (str "uses Enhanced Login Protocol to add an additional cost of [Click]" " to make the first run not through a card ability this turn")} :constant-effects [{:type :run-additional-cost :req (req (and (no-event? state side :run #(:click-run (:cost-args (first %)))) (:click-run (second targets)))) :value [:click 1]}]}) (defcard "Exchange of Information" {:on-play {:req (req (and tagged (seq (:scored runner)) (seq (:scored corp)))) :prompt "Select a stolen agenda in the Runner's score area to swap" :choices {:req (req (in-runner-scored? state side target))} :async true :effect (effect (continue-ability (let [stolen target] {:prompt (msg "Select a scored agenda to swap for " (:title stolen)) :choices {:req (req (in-corp-scored? state side target))} :msg (msg "swap " (:title target) " for " (:title stolen)) :effect (effect (swap-agendas target stolen))}) card nil))}}) (defcard "Fast Break" {:on-play {:req (req (-> runner :scored count pos?)) :async true :effect (req (let [X (-> runner :scored count) draw {:async true :prompt "Draw how many cards?" :choices {:number (req X) :max (req X) :default (req 1)} :msg (msg "draw " target " cards") :effect (effect (draw eid target nil))} install-cards (fn install-cards [server n] {:prompt "Select a card to install" :choices {:card #(and (corp? %) (not (operation? %)) (in-hand? %) (seq (filter (fn [c] (= server c)) (corp-install-list state %))))} :effect (req (wait-for (corp-install state side target server nil) (let [server (remote->name (second (:zone async-result)))] (if (< n X) (continue-ability state side (install-cards server (inc n)) card nil) (effect-completed state side eid)))))}) select-server {:async true :prompt "Install cards in which server?" :choices (req (conj (vec (get-remote-names state)) "New remote")) :effect (effect (continue-ability (install-cards target 1) card nil))}] (wait-for (gain-credits state :corp X) (wait-for (resolve-ability state side draw card nil) (continue-ability state side select-server card nil)))))}}) (defcard "Fast Track" {:on-play {:prompt "Choose an Agenda" :choices (req (cancellable (filter agenda? (:deck corp)) :sorted)) :async true :effect (req (system-msg state side (str "adds " (:title target) " to HQ and shuffle R&D")) (wait-for (reveal state side target) (shuffle! state side :deck) (move state side target :hand) (effect-completed state side eid)))}}) (defcard "Financial Collapse" (letfn [(count-resources [state] (* 2 (count (filter resource? (all-active-installed state :runner)))))] {:on-play {:optional {:req (req (and (<= 6 (:credit runner)) (pos? (count-resources state)))) :player :runner :waiting-prompt "Runner to trash a resource to prevent Financial Collapse" :prompt "Trash a resource to prevent Financial Collapse?" :yes-ability {:prompt "Select a resource to trash" :choices {:card #(and (resource? %) (installed? %))} :async true :effect (effect (system-msg :runner (str "trashes " (:title target) " to prevent Financial Collapse")) (trash :runner eid target {:unpreventable true}))} :no-ability {:player :corp :async true :msg (msg "make the Runner lose " (count-resources state) " [Credits]") :effect (effect (lose-credits :runner eid (count-resources state)))}}}})) (defcard "Focus Group" {:on-play {:req (req (last-turn? state :runner :successful-run)) :prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :async true :effect (req (let [type target numtargets (count (filter #(= type (:type %)) (:hand runner)))] (system-msg state :corp (str "uses Focus Group to choose " target " and reveal the Runner's Grip (" (string/join ", " (map :title (sort-by :title (:hand runner)))) ")")) (wait-for (reveal state side (:hand runner)) (continue-ability state :corp (when (pos? numtargets) {:async true :prompt "Pay how many credits?" :choices {:number (req numtargets)} :effect (req (let [c target] (if (can-pay? state side (assoc eid :source card :source-type :ability) card (:title card) :credit c) (let [new-eid (make-eid state {:source card :source-type :ability})] (wait-for (pay state :corp new-eid card :credit c) (when-let [payment-str (:msg async-result)] (system-msg state :corp payment-str)) (continue-ability state :corp {:msg (msg "place " (quantify c " advancement token") " on " (card-str state target)) :choices {:card installed?} :effect (effect (add-prop target :advance-counter c {:placed true}))} card nil))) (effect-completed state side eid))))}) card nil))))}}) (defcard "Foxfire" {:on-play {:trace {:base 7 :successful {:prompt "Select 1 card to trash" :choices {:card #(and (installed? %) (or (has-subtype? % "Virtual") (has-subtype? % "Link")))} :msg "trash 1 virtual resource or link" :async true :effect (effect (system-msg (str "trashes " (:title target))) (trash eid target nil))}}}}) (defcard "Freelancer" {:on-play {:req (req tagged) :msg (msg "trash " (string/join ", " (map :title (sort-by :title targets)))) :choices {:max 2 :card #(and (installed? %) (resource? %))} :async true :effect (effect (trash-cards :runner eid targets))}}) (defcard "Friends in High Places" (let [fhelper (fn fhp [n] {:prompt "Select a card in Archives to install with Friends in High Places" :async true :show-discard true :choices {:card #(and (corp? %) (not (operation? %)) (in-discard? %))} :effect (req (wait-for (corp-install state side target nil nil) (do (system-msg state side (str "uses Friends in High Places to " (corp-install-msg target))) (if (< n 2) (continue-ability state side (fhp (inc n)) card nil) (effect-completed state side eid)))))})] {:on-play {:async true :effect (effect (continue-ability (fhelper 1) card nil))} })) (defcard "Fully Operational" (letfn [(full-servers [state] (filter #(and (not-empty (:content %)) (not-empty (:ices %))) (vals (get-remotes state)))) (repeat-choice [current total] ;; if current > total, this ability will auto-resolve and finish the chain of async methods. (when (<= current total) {:async true :prompt (str "Choice " current " of " total ": Gain 2 [Credits] or draw 2 cards? ") :choices ["Gain 2 [Credits]" "Draw 2 cards"] :msg (msg (string/lower-case target)) :effect (req (if (= target "Gain 2 [Credits]") (wait-for (gain-credits state :corp 2) (continue-ability state side (repeat-choice (inc current) total) card nil)) (wait-for (draw state :corp 2 nil) ; don't proceed with the next choice until the draw is done (continue-ability state side (repeat-choice (inc current) total) card nil))))}))] {:on-play {:msg (msg "uses Fully Operational to make " (quantify (inc (count (full-servers state))) "gain/draw decision")) :async true :effect (effect (continue-ability (repeat-choice 1 (inc (count (full-servers state)))) card nil))}})) (defcard "Game Changer" {:on-play {:rfg-instead-of-trashing true :effect (effect (gain :click (count (:scored runner))))}}) (defcard "Game Over" {:on-play {:req (req (last-turn? state :runner :stole-agenda)) :prompt "Choose a card type" :choices ["Hardware" "Program" "Resource"] :async true :effect (req (let [card-type target trashtargets (filter #(and (is-type? % card-type) (not (has-subtype? % "Icebreaker"))) (all-active-installed state :runner)) numtargets (count trashtargets) typemsg (str (when (= card-type "Program") "non-Icebreaker ") card-type (when-not (= card-type "Hardware") "s"))] (system-msg state :corp (str "chooses to trash all " typemsg)) (wait-for (resolve-ability state :runner {:async true :req (req (<= 3 (:credit runner))) :waiting-prompt "Runner to prevent trashes" :prompt (msg "Prevent any " typemsg " from being trashed? Pay 3 [Credits] per card.") :choices {:max (req (min numtargets (quot (total-available-credits state :runner eid card) 3))) :card #(and (installed? %) (is-type? % card-type) (not (has-subtype? % "Icebreaker")))} :effect (req (wait-for (pay state :runner card :credit (* 3 (count targets))) (system-msg state :runner (str (:msg async-result) " to prevent the trashing of " (string/join ", " (map :title (sort-by :title targets))))) (effect-completed state side (make-result eid targets))))} card nil) (let [prevented async-result] (when (not async-result) (system-msg state :runner (str "chooses to not prevent Corp trashing all " typemsg))) (wait-for (trash-cards state side (clojure.set/difference (set trashtargets) (set prevented))) (system-msg state :corp (str "trashes all " (when (seq prevented) "other ") typemsg ": " (string/join ", " (map :title (sort-by :title async-result))))) (wait-for (gain-bad-publicity state :corp 1) (when async-result (system-msg state :corp "takes 1 bad publicity from Game Over")) (effect-completed state side eid)))))))}}) (defcard "Genotyping" {:on-play {:msg "trash the top 2 cards of R&D" :rfg-instead-of-trashing true :async true :effect (req (wait-for (mill state :corp :corp 2) (shuffle-into-rd-effect state side eid card 4)))}}) (defcard "Green Level Clearance" {:on-play {:msg "gain 3 [Credits] and draw 1 card" :async true :effect (req (wait-for (gain-credits state side 3) (draw state side eid 1 nil)))}}) (defcard "PI:NAME:<NAME>END_PIki" {:on-play {:req (req (last-turn? state :runner :trashed-card)) :prompt "Choose an installed Corp card" :choices {:card #(and (corp? %) (installed? %))} :async true :effect (effect (continue-ability {:optional {:player :runner :async true :waiting-prompt "Runner to resolve PI:NAME:<NAME>END_PIangeki" :prompt "Access card? (If not, add Hangeki to your score area worth -1 agenda point)" :yes-ability {:async true :effect (req (wait-for (access-card state side target) (update! state side (assoc card :rfg-instead-of-trashing true)) (effect-completed state side eid)))} :no-ability {:async true :msg "add it to the Runner's score area as an agenda worth -1 agenda point" :effect (effect (as-agenda :runner eid card -1))}}} card targets))}}) (defcard "PI:NAME:<NAME>END_PIsei Review" (let [trash-from-hq {:async true :req (req (pos? (count (:hand corp)))) :prompt "Select a card in HQ to trash" :choices {:max 1 :all true :card #(and (corp? %) (in-hand? %))} :msg "trash a card from HQ" :effect (effect (trash-cards eid targets))}] {:on-play {:async true :msg "gain 10 [Credits]" :effect (req (wait-for (gain-credits state :corp 10) (continue-ability state side trash-from-hq card nil)))}})) (defcard "Hard-Hitting News" {:on-play {:trace {:base 4 :req (req (last-turn? state :runner :made-run)) :label "Give the Runner 4 tags" :successful {:async true :msg "give the Runner 4 tags" :effect (effect (gain-tags eid 4))}}}}) (defcard "Hasty Relocation" (letfn [(hr-final [chosen original] {:prompt (str "The top cards of R&D will be " (string/join ", " (map :title chosen)) ".") :choices ["Done" "Start over"] :async true :effect (req (if (= target "Done") (do (doseq [c (reverse chosen)] (move state :corp c :deck {:front true})) (clear-wait-prompt state :runner) (effect-completed state side eid)) (continue-ability state side (hr-choice original '() 3 original) card nil)))}) (hr-choice [remaining chosen n original] {:prompt "Choose a card to move next onto R&D" :choices remaining :async true :effect (req (let [chosen (cons target chosen)] (if (< (count chosen) n) (continue-ability state side (hr-choice (remove-once #(= target %) remaining) chosen n original) card nil) (continue-ability state side (hr-final chosen original) card nil))))})] {:on-play {:additional-cost [:trash-from-deck 1] :msg "trash the top card of R&D, draw 3 cards, and add 3 cards in HQ to the top of R&D" :waiting-prompt "Corp to add 3 cards in HQ to the top of R&D" :async true :effect (req (wait-for (draw state side 3 nil) (let [from (get-in @state [:corp :hand])] (continue-ability state :corp (hr-choice from '() 3 from) card nil))))}})) (defcard "Hatchet Job" {:on-play {:trace {:base 5 :successful {:choices {:card #(and (installed? %) (runner? %) (not (has-subtype? % "Virtual")))} :msg "add an installed non-virtual card to the Runner's grip" :effect (effect (move :runner target :hand true))}}}}) (defcard "Hedge Fund" {:on-play {:msg "gain 9 [Credits]" :async true :effect (effect (gain-credits eid 9))}}) (defcard "Hellion Alpha Test" {:on-play {:trace {:base 2 :req (req (last-turn? state :runner :installed-resource)) :successful {:msg "add a Resource to the top of the Stack" :choices {:card #(and (installed? %) (resource? %))} :effect (effect (move :runner target :deck {:front true}) (system-msg (str "adds " (:title target) " to the top of the Stack")))} :unsuccessful {:msg "take 1 bad publicity" :effect (effect (gain-bad-publicity :corp 1))}}}}) (defcard "Hellion Beta Test" {:on-play {:trace {:base 2 :req (req (last-turn? state :runner :trashed-card)) :label "Trash 2 installed non-program cards or take 1 bad publicity" :successful {:choices {:max (req (min 2 (count (filter #(or (facedown? %) (not (program? %))) (concat (all-installed state :corp) (all-installed state :runner)))))) :all true :card #(and (installed? %) (not (program? %)))} :msg (msg "trash " (string/join ", " (map :title (sort-by :title targets)))) :async true :effect (effect (trash-cards eid targets))} :unsuccessful {:msg "take 1 bad publicity" :async true :effect (effect (gain-bad-publicity :corp eid 1))}}}}) (defcard "Heritage Committee" {:on-play {:async true :effect (req (wait-for (draw state side 3 nil) (continue-ability state side {:prompt "Select a card in HQ to put on top of R&D" :choices {:card #(and (corp? %) (in-hand? %))} :msg "draw 3 cards and add 1 card from HQ to the top of R&D" :effect (effect (move target :deck {:front true}))} card nil)))}}) (defcard "High-Profile Target" (letfn [(dmg-count [state] (* 2 (count-tags state)))] {:on-play {:req (req tagged) :msg (msg "do " (dmg-count state) " meat damage") :async true :effect (effect (damage eid :meat (dmg-count state) {:card card}))}})) (defcard "Housekeeping" {:events [{:event :runner-install :req (req (first-event? state side :runner-install)) :player :runner :prompt "Select a card from your Grip to trash for Housekeeping" :choices {:card #(and (runner? %) (in-hand? %))} :async true :msg (msg "force the Runner to trash" (:title target) " from their grip") :effect (effect (trash :runner eid target {:unpreventable true}))}]}) (defcard "PI:NAME:<NAME>END_PI" {:on-play {:req (req (last-turn? state :runner :stole-agenda)) :prompt "Choose a card to trash" :choices {:card installed?} :msg (msg "trash " (card-str state target)) :async true :effect (effect (trash eid target nil))}}) (defcard "Hyoubu Precog Manifold" {:on-play {:trash-after-resolving false :prompt "Choose a server" :choices (req servers) :msg (msg "choose " target) :effect (effect (update! (assoc-in card [:special :hyoubu-precog-target] target)))} :events [{:event :successful-run :psi {:req (req (= (zone->name (get-in @state [:run :server])) (get-in card [:special :hyoubu-precog-target]))) :not-equal {:msg "end the run" :async true :effect (effect (end-run eid card))}}} {:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "Interns" {:on-play {:prompt "Select a card to install from Archives or HQ" :show-discard true :not-distinct true :choices {:card #(and (not (operation? %)) (corp? %) (or (in-hand? %) (in-discard? %)))} :msg (msg (corp-install-msg target)) :async true :effect (effect (corp-install eid target nil {:ignore-install-cost true}))}}) (defcard "Invasion of Privacy" (letfn [(iop [x] {:async true :req (req (->> (:hand runner) (filter #(or (resource? %) (event? %))) count pos?)) :prompt "Choose a resource or event to trash" :msg (msg "trash " (:title target)) :choices (req (cancellable (filter #(or (resource? %) (event? %)) (:hand runner)) :sorted)) :effect (req (wait-for (trash state side target nil) (if (pos? x) (continue-ability state side (iop (dec x)) card nil) (effect-completed state side eid))))})] {:on-play {:trace {:base 2 :successful {:msg "reveal the Runner's Grip and trash up to X resources or events" :async true :effect (req (wait-for (reveal state side (:hand runner)) (let [x (- target (second targets))] (system-msg state :corp (str "reveals the Runner's Grip ( " (string/join ", " (map :title (sort-by :title (:hand runner)))) " ) and can trash up to " x " resources or events")) (continue-ability state side (iop (dec x)) card nil))))} :unsuccessful {:msg "take 1 bad publicity" :async true :effect (effect (gain-bad-publicity :corp eid 1))}}}})) (defcard "IPO" {:on-play {:msg "gain 13 [Credits]" :async true :effect (effect (gain-credits eid 13))}}) (defcard "Kakurenbo" (let [install-abi {:async true :prompt "Select an agenda, asset or upgrade to install from Archives and place 2 advancement tokens on" :show-discard true :not-distinct true :choices {:card #(and (or (agenda? %) (asset? %) (upgrade? %)) (in-discard? %))} :effect (req (wait-for (corp-install state side (make-eid state {:source card :source-type :corp-install}) target nil nil) (system-msg state side "uses Kakurenbo to place 2 advancements counters on it") (add-prop state side eid async-result :advance-counter 2 {:placed true})))}] {:on-play {:prompt "Select any number of cards in HQ to trash" :rfg-instead-of-trashing true :choices {:max (req (count (:hand corp))) :card #(and (corp? %) (in-hand? %))} :msg (msg "trash " (count targets) " cards in HQ") :async true :effect (req (wait-for (trash-cards state side targets {:unpreventable true}) (doseq [c (:discard (:corp @state))] (update! state side (assoc-in c [:seen] false))) (shuffle! state :corp :discard) (continue-ability state side install-abi card nil))) :cancel-effect (req (doseq [c (:discard (:corp @state))] (update! state side (assoc-in c [:seen] false))) (shuffle! state :corp :discard) (continue-ability state side install-abi card nil))}})) (defcard "Kill Switch" (let [trace-for-brain-damage {:msg (msg "reveal that they accessed " (:title (or (:card context) target))) :trace {:base 3 :req (req (or (agenda? (:card context)) (agenda? target))) :successful {:msg "do 1 brain damage" :async true :effect (effect (damage :runner eid :brain 1 {:card card}))}}}] {:events [(assoc trace-for-brain-damage :event :access :interactive (req (agenda? target))) (assoc trace-for-brain-damage :event :agenda-scored)]})) (defcard "Lag Time" {:on-play {:effect (effect (update-all-ice))} :constant-effects [{:type :ice-strength :value 1}] :leave-play (effect (update-all-ice))}) (defcard "Lateral Growth" {:on-play {:msg "gain 4 [Credits]" :async true :effect (req (wait-for (gain-credits state side 4) (continue-ability state side {:player :corp :prompt "Select a card to install" :choices {:card #(and (corp? %) (not (operation? %)) (in-hand? %))} :async true :msg (msg (corp-install-msg target)) :effect (effect (corp-install eid target nil nil))} card nil)))}}) (defcard "Liquidation" {:on-play {:req (req (some #(and (rezzed? %) (not (agenda? %))) (all-installed state :corp))) :prompt "Select any number of rezzed cards to trash" :choices {:max (req (count (filter #(not (agenda? %)) (all-active-installed state :corp)))) :card #(and (rezzed? %) (not (agenda? %)))} :msg (msg "trash " (string/join ", " (map :title targets)) " and gain " (* (count targets) 3) " [Credits]") :async true :effect (req (wait-for (trash-cards state side targets nil) (gain-credits state side eid (* (count targets) 3))))}}) (defcard "Load Testing" {:on-play {:msg "make the Runner lose [Click] when their next turn begins"} :events [{:event :runner-turn-begins :duration :until-runner-turn-begins :msg "make the Runner lose [Click]" :effect (effect (lose :runner :click 1))}]}) (defcard "Localized Product Line" {:on-play {:prompt "Choose a card" :choices (req (cancellable (:deck corp) :sorted)) :async true :effect (effect (continue-ability (let [title (:title target) copies (filter #(= (:title %) title) (:deck corp))] {:prompt "How many copies?" :choices {:number (req (count copies))} :msg (msg "add " (quantify target "cop" "y" "ies") " of " title " to HQ") :effect (req (shuffle! state :corp :deck) (doseq [copy (take target copies)] (move state side copy :hand)))}) card nil))}}) (defcard "Manhunt" {:events [{:event :successful-run :interactive (req true) :trace {:req (req (first-event? state side :successful-run)) :base 2 :successful {:msg "give the Runner 1 tag" :async true :effect (effect (gain-tags eid 1))}}}]}) (defcard "Market Forces" (letfn [(credit-diff [state] (min (* 3 (count-tags state)) (get-in @state [:runner :credit])))] {:on-play {:req (req tagged) :msg (msg (let [c (credit-diff state)] (str "make the runner lose " c " [Credits], and gain " c " [Credits]"))) :async true :effect (req (let [c (credit-diff state)] (wait-for (lose-credits state :runner c) (gain-credits state :corp eid c))))}})) (defcard "Mass Commercialization" {:on-play {:msg (msg "gain " (* 2 (count (filter #(pos? (get-counters % :advancement)) (get-all-installed state)))) " [Credits]") :async true :effect (effect (gain-credits eid (* 2 (count (filter #(pos? (get-counters % :advancement)) (get-all-installed state))))))}}) (defcard "MCA Informant" {:on-play {:req (req (not-empty (filter #(has-subtype? % "Connection") (all-active-installed state :runner)))) :prompt "Choose a connection to host MCA Informant on" :choices {:card #(and (runner? %) (has-subtype? % "Connection") (installed? %))} :msg (msg "host it on " (card-str state target) ". The Runner has an additional tag") :effect (req (host state side (get-card state target) (assoc card :seen true :condition true)))} :constant-effects [{:type :tags :value 1}] :leave-play (req (system-msg state :corp "trashes MCA Informant")) :runner-abilities [{:label "Trash MCA Informant host" :cost [:click 1 :credit 2] :req (req (= :runner side)) :async true :effect (effect (system-msg :runner (str "spends [Click] and 2 [Credits] to trash " (card-str state (:host card)))) (trash :runner eid (get-card state (:host card)) nil))}]}) (defcard "PI:NAME:<NAME>END_PI BPI:NAME:<NAME>END_PI" {:on-play {:async true :req (req (pos? (count (:scored runner)))) :effect (effect (continue-ability {:prompt "Select an agenda in the runner's score area" :choices {:card #(and (agenda? %) (is-scored? state :runner %))} :effect (req (update! state side (assoc card :title (:title target) :abilities (ability-init (card-def target)))) (card-init state side (get-card state card) {:resolve-effect false :init-data true}) (update! state side (assoc (get-card state card) :title "Media Blitz")))} card nil))}}) (defcard "Medical Research Fundraiser" {:on-play {:msg "gain 8 [Credits]. The Runner gains 3 [Credits]" :async true :effect (req (wait-for (gain-credits state side 8) (gain-credits state :runner eid 3)))}}) (defcard "Midseason Replacements" {:on-play {:trace {:req (req (last-turn? state :runner :stole-agenda)) :base 6 :label "Trace 6 - Give the Runner X tags" :successful {:msg "give the Runner X tags" :async true :effect (effect (system-msg (str "gives the Runner " (- target (second targets)) " tags")) (gain-tags eid (- target (second targets))))}}}}) (defcard "PI:NAME:<NAME>END_PI" {:on-play {:prompt "Select a card to install from HQ" :choices {:card #(and (not (operation? %)) (corp? %) (in-hand? %))} :async true :effect (req (wait-for (corp-install state side target "New remote" nil) (let [installed-card async-result] (add-prop state side installed-card :advance-counter 3 {:placed true}) (register-turn-flag! state side card :can-rez (fn [state side card] (if (same-card? card installed-card) ((constantly false) (toast state :corp "Cannot rez due to Mushin No Shin." "warning")) true))) (register-turn-flag! state side card :can-score (fn [state side card] (if (same-card? card installed-card) ((constantly false) (toast state :corp "Cannot score due to Mushin No Shin." "warning")) true))) (effect-completed state side eid))))}}) (defcard "Mutate" {:on-play {:req (req (some #(and (ice? %) (rezzed? %)) (all-installed state :corp))) :prompt "Select a rezzed piece of ice to trash" :choices {:card #(and (ice? %) (rezzed? %))} :async true :effect (req (let [index (card-index state target) [revealed-cards r] (split-with (complement ice?) (get-in @state [:corp :deck])) titles (->> (conj (vec revealed-cards) (first r)) (filter identity) (map :title))] (wait-for (trash state :corp target nil) (shuffle! state :corp :deck) (system-msg state side (str "uses Mutate to trash " (:title target))) (wait-for (reveal state side revealed-cards) (system-msg state side (str "reveals " (clojure.string/join ", " titles) " from R&D")) (let [ice (first r) zone (zone->name (second (get-zone target)))] (if ice (do (system-msg state side (str "uses Mutate to install and rez " (:title ice) " from R&D at no cost")) (corp-install state side eid ice zone {:ignore-all-cost true :install-state :rezzed-no-cost :display-message false :index index})) (do (system-msg state side "does not find any ICE to install from R&D") (effect-completed state side eid))))))))}}) (defcard "NAPD Cordon" {:on-play {:trash-after-resolving false} :events [{:event :pre-steal-cost :effect (req (let [counter (get-counters target :advancement)] (steal-cost-bonus state side [:credit (+ 4 (* 2 counter))])))} {:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "Neural EMP" {:on-play {:req (req (last-turn? state :runner :made-run)) :msg "do 1 net damage" :async true :effect (effect (damage eid :net 1 {:card card}))}}) (defcard "Neurospike" {:on-play {:msg (msg "do " (:scored-agenda corp-reg 0) " net damage") :async true :effect (effect (damage eid :net (:scored-agenda corp-reg 0) {:card card}))}}) (defcard "NEXT Activation Command" {:on-play {:trash-after-resolving false} :constant-effects [{:type :ice-strength :value 2} {:type :prevent-ability :req (req (let [target-card (first targets) ability (second targets)] (and (not (has-subtype? target-card "Icebreaker")) (:break ability)))) :value true}] :events [{:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "O₂ Shortage" {:on-play {:async true :effect (req (if (empty? (:hand runner)) (do (gain state :corp :click 2) (system-msg state side "uses O₂ Shortage to gain [Click][Click]") (effect-completed state side eid)) (continue-ability state side {:optional {:waiting-prompt "Runner to decide whether or not to trash a card from their Grip" :prompt "Trash 1 random card from your Grip?" :player :runner :yes-ability {:async true :effect (effect (trash-cards :runner eid (take 1 (shuffle (:hand runner))) nil))} :no-ability {:msg "gain [Click][Click]" :effect (effect (gain :corp :click 2))}}} card nil)))}}) (defcard "Observe and Destroy" {:on-play {:additional-cost [:tag 1] :req (req (and (pos? (count-real-tags state)) (< (:credit runner) 6))) :prompt "Select an installed card to trash" :choices {:card #(and (runner? %) (installed? %))} :msg (msg "remove 1 Runner tag and trash " (card-str state target)) :async true :effect (effect (trash eid target nil))}}) (defcard "Oversight AI" {:on-play {:choices {:card #(and (ice? %) (not (rezzed? %)) (= (last (get-zone %)) :ices))} :msg (msg "rez " (card-str state target) " at no cost") :async true :effect (req (wait-for (rez state side target {:ignore-cost :all-costs :no-msg true}) (host state side (:card async-result) (assoc card :seen true :condition true)) (effect-completed state side eid)))} :events [{:event :subroutines-broken :condition :hosted :async true :req (req (and (same-card? target (:host card)) (empty? (remove :broken (:subroutines target))))) :msg (msg "trash itself and " (card-str state target)) :effect (effect (trash :corp eid target {:unpreventable true}))}]}) (defcard "Patch" {:on-play {:choices {:card #(and (ice? %) (rezzed? %))} :msg (msg "give +2 strength to " (card-str state target)) :effect (req (let [card (host state side target (assoc card :seen true :condition true))] (update-ice-strength state side (get-card state target))))} :constant-effects [{:type :ice-strength :req (req (same-card? target (:host card))) :value 2}]}) (defcard "Paywall Implementation" {:events [{:event :successful-run :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Peak Efficiency" {:on-play {:msg (msg "gain " (reduce (fn [c server] (+ c (count (filter (fn [ice] (:rezzed ice)) (:ices server))))) 0 (flatten (seq (:servers corp)))) " [Credits]") :async true :effect (effect (gain-credits eid (reduce (fn [c server] (+ c (count (filter (fn [ice] (:rezzed ice)) (:ices server))))) 0 (flatten (seq (:servers corp))))))}}) (defcard "Power Grid Overload" {:on-play {:trace {:base 2 :req (req (last-turn? state :runner :made-run)) :successful {:msg "trash 1 piece of hardware" :async true :effect (effect (continue-ability (let [max-cost (- target (second targets))] {:choices {:card #(and (hardware? %) (<= (:cost %) max-cost))} :msg (msg "trash " (:title target)) :effect (effect (trash eid target nil))}) card nil))}}}}) (defcard "Power Shutdown" {:on-play {:req (req (and (last-turn? state :runner :made-run) (not-empty (filter #(or (hardware? %) (program? %)) (all-active-installed state :runner))))) :prompt "Trash how many cards from the top R&D?" :choices {:number (req (count (:deck corp)))} :msg (msg "trash " target " cards from the top of R&D") :async true :effect (req (wait-for (mill state :corp :corp target) (continue-ability state :runner (let [n target] {:async true :prompt "Select a Program or piece of Hardware to trash" :choices {:card #(and (or (hardware? %) (program? %)) (<= (:cost %) n))} :msg (msg "trash " (:title target)) :effect (effect (trash eid target nil))}) card nil)))}}) (defcard "Precognition" {:on-play {:msg "rearrange the top 5 cards of R&D" :waiting-prompt "Corp to rearrange the top cards of R&D" :async true :effect (effect (continue-ability (let [from (take 5 (:deck corp))] (when (pos? (count from)) (reorder-choice :corp :runner from '() (count from) from))) card nil))}}) (defcard "Predictive Algorithm" {:events [{:event :pre-steal-cost :effect (effect (steal-cost-bonus [:credit 2]))}]}) (defcard "Predictive Planogram" {:on-play {:prompt "Choose one" :choices (req ["Gain 3 [Credits]" "Draw 3 cards" (when tagged "Gain 3 [Credits] and draw 3 cards")]) :msg (msg (string/lower-case target)) :async true :effect (req (case target "Gain 3 [Credits]" (gain-credits state :corp eid 3) "Draw 3 cards" (draw state :corp eid 3 nil) "Gain 3 [Credits] and draw 3 cards" (wait-for (gain-credits state :corp 3) (draw state :corp eid 3 nil)) ; else (effect-completed state side eid)))}}) (defcard "Preemptive Action" {:on-play {:rfg-instead-of-trashing true :async true :effect (effect (shuffle-into-rd-effect eid card 3 true))}}) (defcard "Priority Construction" (letfn [(install-card [chosen] {:prompt "Select a remote server" :choices (req (conj (vec (get-remote-names state)) "New remote")) :async true :effect (effect (corp-install eid (assoc chosen :advance-counter 3) target {:ignore-all-cost true}))})] {:on-play {:prompt "Choose a piece of ICE in HQ to install" :choices {:card #(and (in-hand? %) (corp? %) (ice? %))} :msg "install an ICE from HQ and place 3 advancements on it" :cancel-effect (req (effect-completed state side eid)) :async true :effect (effect (continue-ability (install-card target) card nil))}})) (defcard "Product Recall" {:on-play {:prompt "Select a rezzed asset or upgrade to trash" :choices {:card #(and (rezzed? %) (or (asset? %) (upgrade? %)))} :msg (msg "trash " (card-str state target) " and gain " (trash-cost state side target) " [Credits]") :async true :effect (req (wait-for (trash state side target {:unpreventable true}) (gain-credits state :corp eid (trash-cost state side target))))}}) (defcard "Psychographics" {:on-play {:req (req tagged) :prompt "Pay how many credits?" :choices {:number (req (count-tags state))} :async true :effect (req (let [c target] (if (can-pay? state side (assoc eid :source card :source-type :ability) card (:title card) :credit c) (let [new-eid (make-eid state {:source card :source-type :ability})] (wait-for (pay state :corp new-eid card :credit c) (when-let [payment-str (:msg async-result)] (system-msg state :corp payment-str)) (continue-ability state side {:msg (msg "place " (quantify c " advancement token") " on " (card-str state target)) :choices {:card can-be-advanced?} :effect (effect (add-prop target :advance-counter c {:placed true}))} card nil))) (effect-completed state side eid))))}}) (defcard "Psychokinesis" (letfn [(choose-card [state cards] (let [allowed-cards (filter #(some #{"New remote"} (installable-servers state %)) cards)] {:prompt "Select an agenda, asset, or upgrade to install" :choices (conj (vec allowed-cards) "None") :async true :effect (req (if (or (= target "None") (ice? target) (operation? target)) (do (system-msg state side "does not install an asset, agenda, or upgrade") (effect-completed state side eid)) (continue-ability state side (install-card target) card nil)))})) (install-card [chosen] {:prompt "Select a remote server" :choices (req (conj (vec (get-remote-names state)) "New remote")) :async true :effect (effect (corp-install eid chosen target nil))})] {:on-play {:req (req (pos? (count (:deck corp)))) :msg (msg "look at the top " (quantify (count (take 5 (:deck corp))) "card") " of R&D") :waiting-prompt "Corp to look at the top cards of R&D" :async true :effect (effect (continue-ability (let [top-5 (take 5 (:deck corp))] (choose-card state top-5)) card nil))}})) (defcard "Public Trail" {:on-play {:req (req (last-turn? state :runner :successful-run)) :player :runner :msg (msg "force the Runner to " (decapitalize target)) :prompt "Pick one" :choices (req ["Take 1 tag" (when (can-pay? state :runner (assoc eid :source card :source-type :ability) card (:title card) :credit 8) "Pay 8 [Credits]")]) :async true :effect (req (if (= target "Pay 8 [Credits]") (wait-for (pay state :runner card :credit 8) (system-msg state :runner (:msg async-result)) (effect-completed state side eid)) (gain-tags state :corp eid 1)))}}) (defcard "Punitive Counterstrike" {:on-play {:trace {:base 5 :successful {:async true :msg (msg "do " (:stole-agenda runner-reg-last 0) " meat damage") :effect (effect (damage eid :meat (:stole-agenda runner-reg-last 0) {:card card}))}}}}) (defcard "Reclamation Order" {:on-play {:prompt "Select a card from Archives" :show-discard true :choices {:card #(and (corp? %) (not= (:title %) "Reclamation Order") (in-discard? %))} :msg (msg "name " (:title target)) :async true :effect (req (let [title (:title target) cards (filter #(= title (:title %)) (:discard corp)) n (count cards)] (continue-ability state side {:prompt (str "Choose how many copies of " title " to reveal") :choices {:number (req n)} :msg (msg "reveal " (quantify target "cop" "y" "ies") " of " title " from Archives" (when (pos? target) (str " and add " (if (= 1 target) "it" "them") " to HQ"))) :async true :effect (req (wait-for (reveal state side cards) (doseq [c (->> cards (sort-by :seen) reverse (take target))] (move state side c :hand)) (effect-completed state side eid)))} card nil)))}}) (defcard "Recruiting Trip" (let [rthelp (fn rt [total left selected] (if (pos? left) {:prompt (str "Choose a Sysop (" (inc (- total left)) "/" total ")") :choices (req (cancellable (filter #(and (has-subtype? % "Sysop") (not-any? #{(:title %)} selected)) (:deck corp)) :sorted)) :msg (msg "put " (:title target) " into HQ") :async true :effect (req (move state side target :hand) (continue-ability state side (rt total (dec left) (cons (:title target) selected)) card nil))} {:effect (effect (shuffle! :corp :deck)) :msg (msg "shuffle R&D")}))] {:on-play {:prompt "How many Sysops?" :choices :credit :msg (msg "search for " target " Sysops") :async true :effect (effect (continue-ability (rthelp target target []) card nil))}})) (defcard "Red Level Clearance" (let [all [{:msg "gain 2 [Credits]" :async true :effect (effect (gain-credits eid 2))} {:msg "draw 2 cards" :async true :effect (effect (draw eid 2 nil))} {:msg "gain [Click]" :effect (effect (gain :click 1))} {:prompt "Choose a non-agenda to install" :msg "install a non-agenda from hand" :choices {:card #(and (not (agenda? %)) (not (operation? %)) (in-hand? %))} :async true :effect (effect (corp-install eid target nil nil))}] can-install? (fn [hand] (seq (remove #(or (agenda? %) (operation? %)) hand))) choice (fn choice [abis chose-once] {:prompt "Choose an ability to resolve" :choices (map #(capitalize (:msg %)) abis) :async true :effect (req (let [chosen (some #(when (= target (capitalize (:msg %))) %) abis)] (if (or (not= target "Install a non-agenda from hand") (and (= target "Install a non-agenda from hand") (can-install? (:hand corp)))) (wait-for (resolve-ability state side chosen card nil) (if (false? chose-once) (continue-ability state side (choice (remove #(= % chosen) abis) true) card nil) (effect-completed state side eid))) (continue-ability state side (choice abis chose-once) card nil))))})] {:on-play {:waiting-prompt "Corp to use Red Level Clearance" :async true :effect (effect (continue-ability (choice all false) card nil))}})) (defcard "Red Planet Couriers" {:on-play {:req (req (some #(can-be-advanced? %) (all-installed state :corp))) :prompt "Select an installed card that can be advanced" :choices {:card can-be-advanced?} :async true :effect (req (let [installed (get-all-installed state) total-adv (reduce + (map #(get-counters % :advancement) installed))] (doseq [c installed] (add-prop state side c :advance-counter (- (get-counters c :advancement)) {:placed true})) (add-prop state side target :advance-counter total-adv {:placed true}) (update-all-ice state side) (system-msg state side (str "uses Red Planet Couriers to move " total-adv " advancement tokens to " (card-str state target))) (effect-completed state side eid)))}}) (defcard "Replanting" (letfn [(replant [n] {:prompt "Select a card to install with Replanting" :async true :choices {:card #(and (corp? %) (not (operation? %)) (in-hand? %))} :effect (req (wait-for (corp-install state side target nil {:ignore-all-cost true}) (if (< n 2) (continue-ability state side (replant (inc n)) card nil) (effect-completed state side eid))))})] {:on-play {:prompt "Select an installed card to add to HQ" :choices {:card #(and (corp? %) (installed? %))} :msg (msg "add " (card-str state target) " to HQ, then install 2 cards ignoring all costs") :async true :effect (req (move state side target :hand) (continue-ability state side (replant 1) card nil))}})) (defcard "Restore" {:on-play {:prompt "Select a card in Archives to install & rez" :show-discard true :choices {:card #(and (corp? %) (not (operation? %)) (in-discard? %))} :async true :effect (req (wait-for (corp-install state side target nil {:install-state :rezzed}) (let [seen (assoc target :seen true)] (system-msg state side (str "uses Restore to " (corp-install-msg seen))) (let [leftover (filter #(= (:title target) (:title %)) (-> @state :corp :discard))] (when (seq leftover) (doseq [c leftover] (move state side c :rfg)) (system-msg state side (str "removes " (count leftover) " copies of " (:title target) " from the game")))) (effect-completed state side eid))))}}) (defcard "Restoring Face" {:on-play {:prompt "Select a Sysop, Executive or Clone to trash" :msg (msg "trash " (:title target) " to remove 2 bad publicity") :choices {:card #(or (has-subtype? % "Clone") (has-subtype? % "Executive") (has-subtype? % "Sysop"))} :async true :effect (req (wait-for (lose-bad-publicity state side 2) (wait-for (resolve-ability state side (when (facedown? target) {:async true :effect (effect (reveal eid target))}) card targets) (trash state side eid target nil))))}}) (defcard "Retribution" {:on-play {:req (req (and tagged (->> (all-installed state :runner) (filter #(or (hardware? %) (program? %))) not-empty))) :prompt "Choose a program or hardware to trash" :choices {:req (req (and (installed? target) (or (program? target) (hardware? target))))} :msg (msg "trash " (card-str state target)) :async true :effect (effect (trash eid target))}}) (defcard "Restructure" {:on-play {:msg "gain 15 [Credits]" :async true :effect (effect (gain-credits eid 15))}}) (defcard "Reuse" {:on-play {:prompt (msg "Select up to " (quantify (count (:hand corp)) "card") " in HQ to trash") :choices {:max (req (count (:hand corp))) :card #(and (corp? %) (in-hand? %))} :msg (msg (let [m (count targets)] (str "trash " (quantify m "card") " and gain " (* 2 m) " [Credits]"))) :async true :effect (req (wait-for (trash-cards state side targets {:unpreventable true}) (gain-credits state side eid (* 2 (count async-result)))))}}) (defcard "Reverse Infection" {:on-play {:prompt "Choose one:" :choices ["Purge virus counters" "Gain 2 [Credits]"] :async true :effect (req (if (= target "Gain 2 [Credits]") (wait-for (gain-credits state side 2) (system-msg state side "uses Reverse Infection to gain 2 [Credits]") (effect-completed state side eid)) (let [pre-purge-virus (number-of-virus-counters state)] (purge state side) (let [post-purge-virus (number-of-virus-counters state) num-virus-purged (- pre-purge-virus post-purge-virus) num-to-trash (quot num-virus-purged 3)] (wait-for (mill state :corp :runner num-to-trash) (system-msg state side (str "uses Reverse Infection to purge " (quantify num-virus-purged "virus counter") " and trash " (quantify num-to-trash "card") " from the top of the stack")) (effect-completed state side eid))))))}}) (defcard "Rework" {:on-play {:prompt "Select a card from HQ to shuffle into R&D" :choices {:card #(and (corp? %) (in-hand? %))} :msg "shuffle a card from HQ into R&D" :effect (effect (move target :deck) (shuffle! :deck))}}) (defcard "Riot Suppression" {:on-play {:rfg-instead-of-trashing true :optional {:req (req (last-turn? state :runner :trashed-card)) :waiting-prompt "Runner to decide if they will take 1 brain damage" :prompt "Take 1 brain damage to prevent having 3 fewer clicks next turn?" :player :runner :yes-ability {:async true :effect (effect (system-msg "suffers 1 brain damage to prevent losing 3[Click] to Riot Suppression") (damage eid :brain 1 {:card card}))} :no-ability {:msg "give the Runner 3 fewer [Click] next turn" :effect (req (swap! state update-in [:runner :extra-click-temp] (fnil #(- % 3) 0)))}}}}) (defcard "Rolling Brownout" {:on-play {:msg "increase the play cost of operations and events by 1 [Credits]"} :constant-effects [{:type :play-cost :value 1}] :events [{:event :play-event :once :per-turn :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}]}) (defcard "Rover Algorithm" {:on-play {:choices {:card #(and (ice? %) (rezzed? %))} :msg (msg "host it as a condition counter on " (card-str state target)) :effect (effect (host target (assoc card :installed true :seen true :condition true)) (update-ice-strength (get-card state target)))} :constant-effects [{:type :ice-strength :req (req (same-card? target (:host card))) :value (req (get-counters card :power))}] :events [{:event :pass-ice :condition :hosted :req (req (same-card? (:ice context) (:host card))) :msg (msg "add 1 power counter to itself") :effect (effect (add-counter card :power 1))}]}) (defcard "Sacrifice" {:on-play {:req (req (and (pos? (count-bad-pub state)) (some #(pos? (:agendapoints %)) (:scored corp)))) :additional-cost [:forfeit] :async true :effect (req (let [bp-lost (max 0 (min (:agendapoints (last (:rfg corp))) (count-bad-pub state)))] (system-msg state side (str "uses Sacrifice to lose " bp-lost " bad publicity and gain " bp-lost " [Credits]")) (if (pos? bp-lost) (wait-for (lose-bad-publicity state side bp-lost) (gain-credits state side eid bp-lost)) (effect-completed state side eid))))}}) (defcard "Salem's Hospitality" {:on-play {:prompt "Name a Runner card" :choices {:card-title (req (and (runner? target) (not (identity? target))))} :async true :effect (req (system-msg state side (str "uses Salem's Hospitality to reveal the Runner's Grip ( " (string/join ", " (map :title (sort-by :title (:hand runner)))) " ) and trash any copies of " target)) (let [cards (filter #(= target (:title %)) (:hand runner))] (wait-for (reveal state side cards) (trash-cards state side eid cards {:unpreventable true}))))}}) (defcard "Scapenet" {:on-play {:trace {:req (req (last-turn? state :runner :successful-run)) :base 7 :successful {:prompt "Choose an installed virtual or chip card to remove from game" :choices {:card #(and (installed? %) (or (has-subtype? % "Virtual") (has-subtype? % "Chip")))} :msg (msg "remove " (card-str state target) " from game") :async true :effect (effect (move :runner target :rfg) (effect-completed eid))}}}}) (defcard "Scarcity of Resources" {:on-play {:msg "increase the install cost of resources by 2"} :constant-effects [{:type :install-cost :req (req (resource? target)) :value 2}]}) (defcard "Scorched Earth" {:on-play {:req (req tagged) :msg "do 4 meat damage" :async true :effect (effect (damage eid :meat 4 {:card card}))}}) (defcard "SEA Source" {:on-play {:trace {:base 3 :req (req (last-turn? state :runner :successful-run)) :label "Trace 3 - Give the Runner 1 tag" :successful {:msg "give the Runner 1 tag" :async true :effect (effect (gain-tags :corp eid 1))}}}}) (defcard "Seamless Launch" {:on-play {:prompt "Select target" :req (req (some #(and (corp? %) (installed? %) (not (= :this-turn (installed? %)))) (all-installed state :corp))) :choices {:card #(and (corp? %) (installed? %) (not (= :this-turn (installed? %))))} :msg (msg "place 2 advancement tokens on " (card-str state target)) :async true :effect (effect (add-prop eid target :advance-counter 2 {:placed true}))}}) (defcard "Secure and Protect" {:on-play {:interactive (req true) :waiting-prompt "Corp to use Secure and Protect" :async true :effect (req (if (seq (filter ice? (:deck corp))) (continue-ability state side {:async true :prompt "Choose a piece of ice" :choices (req (filter ice? (:deck corp))) :effect (effect (continue-ability (let [chosen-ice target] {:async true :prompt (str "Select where to install " (:title chosen-ice)) :choices ["Archives" "R&D" "HQ"] :msg (msg "reveal " (:title chosen-ice) " and install it, paying 3 [Credit] less") :effect (req (wait-for (reveal state side chosen-ice) (shuffle! state side :deck) (corp-install state side eid chosen-ice target {:cost-bonus -3})))}) card nil))} card nil) (do (shuffle! state side :deck) (effect-completed state side eid))))}}) (defcard "Self-Growth Program" {:on-play {:req (req tagged) :prompt "Select two installed Runner cards" :choices {:card #(and (installed? %) (runner? %)) :max 2} :msg (msg (str "move " (string/join ", " (map :title targets)) " to the Runner's grip")) :effect (req (doseq [c targets] (move state :runner c :hand)))}}) (defcard "Service Outage" {:on-play {:msg "add a cost of 1 [Credit] for the Runner to make the first run each turn"} :constant-effects [{:type :run-additional-cost :req (req (no-event? state side :run)) :value [:credit 1]}]}) (defcard "Shipment from Kaguya" {:on-play {:choices {:max 2 :card #(and (corp? %) (installed? %) (can-be-advanced? %))} :msg (msg "place 1 advancement token on " (count targets) " cards") :effect (req (doseq [t targets] (add-prop state :corp t :advance-counter 1 {:placed true})))}}) (defcard "Shipment from MirrorMorph" (letfn [(shelper [n] (when (< n 3) {:async true :prompt "Select a card to install with Shipment from MirrorMorph" :choices {:card #(and (corp? %) (not (operation? %)) (in-hand? %))} :effect (req (wait-for (corp-install state side target nil nil) (continue-ability state side (shelper (inc n)) card nil)))}))] {:on-play {:async true :effect (effect (continue-ability (shelper 0) card nil))}})) (defcard "Shipment from SanSan" {:on-play {:choices ["0" "1" "2"] :prompt "How many advancement tokens?" :async true :effect (req (let [c (str->int target)] (continue-ability state side {:choices {:card can-be-advanced?} :msg (msg "place " c " advancement tokens on " (card-str state target)) :effect (effect (add-prop :corp target :advance-counter c {:placed true}))} card nil)))}}) (defcard "Shipment from PI:NAME:<NAME>END_PI" {:on-play {:req (req (not-last-turn? state :runner :successful-run)) :choices {:card #(and (corp? %) (installed? %))} :msg (msg "place 2 advancement tokens on " (card-str state target)) :effect (effect (add-prop target :advance-counter 2 {:placed true}))}}) (defcard "Shoot the Moon" (letfn [(rez-helper [ice] (when (seq ice) {:async true :effect (req (wait-for (rez state side (first ice) {:ignore-cost :all-costs}) (continue-ability state side (rez-helper (rest ice)) card nil)))}))] {:on-play {:req (req tagged) :choices {:card #(and (ice? %) (not (rezzed? %))) :max (req (min (count-tags state) (reduce (fn [c server] (+ c (count (filter #(not (:rezzed %)) (:ices server))))) 0 (flatten (seq (:servers corp))))))} :async true :effect (effect (continue-ability (rez-helper targets) card nil))}})) (defcard "Snatch and Grab" {:on-play {:trace {:base 3 :successful {:waiting-prompt "Corp to use Snatch and Grab" :msg "trash a connection" :choices {:card #(has-subtype? % "Connection")} :async true :effect (effect (continue-ability (let [c target] {:optional {:player :runner :waiting-prompt "Runner to decide if they will take 1 tag" :prompt (str "Take 1 tag to prevent " (:title c) " from being trashed?") :yes-ability {:async true :msg (msg "take 1 tag to prevent " (:title c) " from being trashed") :effect (effect (gain-tags :runner eid 1 {:unpreventable true}))} :no-ability {:async true :msg (msg "trash " (:title c)) :effect (effect (trash :corp eid c nil))}}}) card nil))}}}}) (defcard "Special Report" {:on-play {:prompt "Select any number of cards in HQ to shuffle into R&D" :choices {:max (req (count (:hand corp))) :card #(and (corp? %) (in-hand? %))} :msg (msg "shuffle " (count targets) " cards in HQ into R&D and draw " (count targets) " cards") :async true :effect (req (doseq [c targets] (move state side c :deck)) (shuffle! state side :deck) (draw state side eid (count targets) nil))}}) (defcard "Sprint" {:on-play {:async true :effect (req (wait-for (draw state side 3 nil) (system-msg state side (str "uses Sprint to draw " (quantify (count async-result) "card"))) (continue-ability state side {:prompt "Select 2 cards in HQ to shuffle" :choices {:max 2 :card #(and (corp? %) (in-hand? %))} :msg "shuffles 2 cards from HQ into R&D" :effect (req (doseq [c targets] (move state side c :deck)) (shuffle! state side :deck))} card nil)))}}) (defcard "Standard Procedure" {:on-play {:req (req (last-turn? state :runner :successful-run)) :prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :msg (msg "name " target ", revealing " (string/join ", " (map :title (:hand runner))) " in the Runner's Grip, and gains " (* 2 (count (filter #(is-type? % target) (:hand runner)))) " [Credits]") :async true :effect (req (wait-for (reveal state side (:hand runner)) (gain-credits state :corp eid (* 2 (count (filter #(is-type? % target) (:hand runner)))))))}}) (defcard "Stock Buy-Back" {:on-play {:msg (msg "gain " (* 3 (count (:scored runner))) " [Credits]") :async true :effect (effect (gain-credits eid (* 3 (count (:scored runner)))))}}) (defcard "Sub Boost" (let [new-sub {:label "[Sub Boost]: End the run"}] {:sub-effect {:label "End the run" :msg "end the run" :async true :effect (effect (end-run eid card))} :on-play {:choices {:card #(and (ice? %) (rezzed? %))} :msg (msg "make " (card-str state target) " gain Barrier and \"[Subroutine] End the run\"") :effect (req (add-extra-sub! state :corp (get-card state target) new-sub (:cid card)) (host state side (get-card state target) (assoc card :seen true :condition true)))} :constant-effects [{:type :gain-subtype :req (req (and (same-card? target (:host card)) (rezzed? target))) :value "Barrier"}] :leave-play (req (remove-extra-subs! state :corp (:host card) (:cid card))) :events [{:event :rez :req (req (same-card? (:card context) (:host card))) :effect (req (add-extra-sub! state :corp (get-card state (:card context)) new-sub (:cid card)))}]})) (defcard "Subcontract" (letfn [(sc [i sccard] {:prompt "Select an operation in HQ to play" :choices {:card #(and (corp? %) (operation? %) (in-hand? %))} :async true :msg (msg "play " (:title target)) :effect (req (wait-for (play-instant state side target nil) (if (and (not (get-in @state [:corp :register :terminal])) (< i 2)) (continue-ability state side (sc (inc i) sccard) sccard nil) (effect-completed state side eid))))})] {:on-play {:req (req tagged) :async true :effect (effect (continue-ability (sc 1 card) card nil))}})) (defcard "Subliminal Messaging" {:on-play {:msg "gain 1 [Credits]" :async true :effect (req (wait-for (gain-credits state side 1) (continue-ability state side {:once :per-turn :once-key :subliminal-messaging :msg "gain [Click]" :effect (effect (gain :corp :click 1))} card nil)))} :events [{:event :corp-phase-12 :location :discard :optional {:req (req (not-last-turn? state :runner :made-run)) :prompt "Add Subliminal Messaging to HQ?" :yes-ability {:msg "add Subliminal Messaging to HQ" :effect (effect (move card :hand))}}}]}) (defcard "Success" (letfn [(advance-n-times [state side eid card target n] (if (pos? n) (wait-for (advance state :corp (make-eid state {:source card}) (get-card state target) :no-cost) (advance-n-times state side eid card target (dec n))) (effect-completed state side eid)))] {:on-play {:additional-cost [:forfeit] :choices {:card can-be-advanced?} :msg (msg "advance " (card-str state target) " " (quantify (get-advancement-requirement (cost-target eid :forfeit)) "time")) :async true :effect (effect (advance-n-times eid card target (get-advancement-requirement (cost-target eid :forfeit))))}})) (defcard "Successful Demonstration" {:on-play {:req (req (last-turn? state :runner :unsuccessful-run)) :msg "gain 7 [Credits]" :async true :effect (effect (gain-credits eid 7))}}) (defcard "Sunset" (letfn [(sun [serv] {:prompt "Select two pieces of ICE to swap positions" :choices {:card #(and (= serv (get-zone %)) (ice? %)) :max 2} :async true :effect (req (if (= (count targets) 2) (do (swap-ice state side (first targets) (second targets)) (system-msg state side (str "uses Sunset to swap " (card-str state (first targets)) " with " (card-str state (second targets)))) (continue-ability state side (sun serv) card nil)) (do (system-msg state side "has finished rearranging ICE") (effect-completed state side eid))))})] {:on-play {:prompt "Choose a server" :choices (req servers) :msg (msg "rearrange ICE protecting " target) :async true :effect (req (let [serv (conj (server->zone state target) :ices)] (continue-ability state side (sun serv) card nil)))}})) (defcard "Surveillance Sweep" {:events [{:event :pre-init-trace :req (req run) :effect (req (swap! state assoc-in [:trace :player] :runner))}]}) (defcard "Sweeps Week" {:on-play {:msg (msg "gain " (count (:hand runner)) " [Credits]") :async true :effect (effect (gain-credits eid (count (:hand runner))))}}) (defcard "SYNC Rerouting" {:on-play {:trash-after-resolving false} :events [{:event :run :async true :msg (msg "force the Runner to " (decapitalize target)) :player :runner :prompt "Pay 4 [Credits] or take 1 tag?" :choices ["Pay 4 [Credits]" "Take 1 tag"] :effect (req (if (= target "Pay 4 [Credits]") (wait-for (pay state :runner card :credit 4) (system-msg state :runner (:msg async-result)) (effect-completed state side eid)) (gain-tags state :corp eid 1 nil)))} {:event :corp-turn-begins :async true :effect (effect (trash eid card nil))}]}) (defcard "Targeted Marketing" (let [gaincr {:req (req (= (:title (:card context)) (get-in card [:special :marketing-target]))) :async true :msg (msg "gain 10 [Credits] from " (:marketing-target card)) :effect (effect (gain-credits :corp eid 10))}] {:on-play {:prompt "Name a Runner card" :choices {:card-title (req (and (runner? target) (not (identity? target))))} :effect (effect (update! (assoc-in card [:special :marketing-target] target)) (system-msg (str "uses Targeted Marketing to name " target)))} :events [(assoc gaincr :event :runner-install) (assoc gaincr :event :play-event)]})) (defcard "The All-Seeing I" (let [trash-all-resources {:msg "trash all resources" :async true :effect (effect (trash-cards :corp eid (filter resource? (all-active-installed state :runner))))}] {:on-play {:req (req tagged) :async true :effect (effect (continue-ability (if (pos? (count-bad-pub state)) {:optional {:player :runner :prompt "Remove 1 bad publicity to prevent all resources from being trashed?" :yes-ability {:msg "remove 1 bad publicity, preventing all resources from being trashed" :async true :effect (effect (lose-bad-publicity eid 1))} :no-ability trash-all-resources}} trash-all-resources) card nil))}})) (defcard "Threat Assessment" {:on-play {:req (req (last-turn? state :runner :trashed-card)) :prompt "Select an installed Runner card" :choices {:card #(and (runner? %) (installed? %))} :rfg-instead-of-trashing true :async true :effect (effect (continue-ability (let [chosen target] {:player :runner :waiting-prompt "Runner to resolve Threat Assessment" :prompt (str "Add " (:title chosen) " to the top of the Stack or take 2 tags?") :choices [(str "Move " (:title chosen)) "Take 2 tags"] :async true :effect (req (if (= target "Take 2 tags") (do (system-msg state side "chooses to take 2 tags") (gain-tags state :runner eid 2)) (do (system-msg state side (str "chooses to move " (:title chosen) " to the Stack")) (move state :runner chosen :deck {:front true}) (effect-completed state side eid))))}) card nil))}}) (defcard "Threat Level Alpha" {:on-play {:trace {:base 1 :successful {:label "Give the Runner X tags" :async true :effect (req (let [tags (max 1 (count-tags state))] (gain-tags state :corp eid tags) (system-msg state side (str "uses Threat Level Alpha to give the Runner " (quantify tags "tag")))))}}}}) (defcard "Too Big to Fail" {:on-play {:req (req (< (:credit corp) 10)) :msg "gain 7 [Credits] and take 1 bad publicity" :async true :effect (req (wait-for (gain-credits state side 7) (gain-bad-publicity state :corp eid 1)))}}) (defcard "Traffic Accident" {:on-play {:req (req (<= 2 (count-tags state))) :msg "do 2 meat damage" :async true :effect (effect (damage eid :meat 2 {:card card}))}}) (defcard "Transparency Initiative" {:constant-effects [{:type :gain-subtype :req (req (and (same-card? target (:host card)) (rezzed? target))) :value "Public"}] :on-play {:choices {:card #(and (agenda? %) (installed? %) (not (faceup? %)))} :effect (req (let [target (update! state side (assoc target :seen true :rezzed true)) card (host state side target (assoc card :seen true :condition true))] (register-events state side card [{:event :advance :location :hosted :req (req (same-card? (:host card) target)) :async true :msg "gain 1 [Credit]" :effect (effect (gain-credits eid 1))}])))}}) (defcard "Trick of Light" {:on-play {:req (req (let [advanceable (some can-be-advanced? (get-all-installed state)) advanced (some #(get-counters % :advancement) (get-all-installed state))] (and advanceable advanced))) :choices {:card #(and (pos? (get-counters % :advancement)) (installed? %))} :async true :effect (effect (continue-ability (let [fr target] {:async true :prompt "Move how many advancement tokens?" :choices (take (inc (get-counters fr :advancement)) ["0" "1" "2"]) :effect (effect (continue-ability (let [c (str->int target)] {:prompt "Move to where?" :choices {:card #(and (not (same-card? fr %)) (can-be-advanced? %))} :msg (msg "move " c " advancement tokens from " (card-str state fr) " to " (card-str state target)) :effect (effect (add-prop :corp target :advance-counter c {:placed true}) (add-prop :corp fr :advance-counter (- c) {:placed true}))}) card nil))}) card nil))}}) (defcard "PI:NAME:<NAME>END_PI" {:on-play {:trace {:base 4 :req (req (:accessed-cards runner-reg-last)) :label "Trace 4 - Trash a program" :successful {:async true :effect (req (let [exceed (- target (second targets))] (continue-ability state side {:async true :prompt (str "Select a program with an install cost of no more than " exceed "[Credits]") :choices {:card #(and (program? %) (installed? %) (>= exceed (:cost %)))} :msg (msg "trash " (card-str state target)) :effect (effect (trash eid target nil))} card nil)))}}}}) (defcard "Ultraviolet Clearance" {:on-play {:async true :effect (req (wait-for (gain-credits state side 10) (wait-for (draw state side 4 nil) (continue-ability state side {:prompt "Choose a card in HQ to install" :choices {:card #(and (in-hand? %) (corp? %) (not (operation? %)))} :msg "gain 10 [Credits], draw 4 cards, and install 1 card from HQ" :cancel-effect (req (effect-completed state side eid)) :async true :effect (effect (corp-install eid target nil nil))} card nil))))}}) (defcard "Under the Bus" {:on-play {:req (req (and (last-turn? state :runner :accessed-cards) (not-empty (filter #(and (resource? %) (has-subtype? % "Connection")) (all-active-installed state :runner))))) :prompt "Choose a connection to trash" :choices {:card #(and (runner? %) (resource? %) (has-subtype? % "Connection") (installed? %))} :msg (msg "trash " (:title target) " and take 1 bad publicity") :async true :effect (req (wait-for (trash state side target nil) (gain-bad-publicity state :corp eid 1)))}}) (defcard "Violet Level Clearance" {:on-play {:msg "gain 8 [Credits] and draw 4 cards" :async true :effect (req (wait-for (gain-credits state side 8) (draw state side eid 4 nil)))}}) (defcard "Voter Intimidation" {:on-play {:psi {:req (req (seq (:scored runner))) :not-equal {:player :corp :async true :prompt "Select a resource to trash" :choices {:card #(and (installed? %) (resource? %))} :msg (msg "trash " (:title target)) :effect (effect (trash eid target nil))}}}}) (defcard "Wake Up Call" {:on-play {:rfg-instead-of-trashing true :req (req (last-turn? state :runner :trashed-card)) :prompt "Select a piece of hardware or non-virtual resource" :choices {:card #(or (hardware? %) (and (resource? %) (not (has-subtype? % "Virtual"))))} :async true :effect (effect (continue-ability (let [chosen target wake card] {:player :runner :waiting-prompt "Runner to resolve Wake Up Call" :prompt (str "Trash " (:title chosen) " or suffer 4 meat damage?") :choices [(str "Trash " (:title chosen)) "4 meat damage"] :async true :effect (req (if (= target "4 meat damage") (do (system-msg state side "chooses to suffer meat damage") (damage state side eid :meat 4 {:card wake :unboostable true})) (do (system-msg state side (str "chooses to trash " (:title chosen))) (trash state side eid chosen nil))))}) card nil))}}) (defcard "Wetwork Refit" (let [new-sub {:label "[Wetwork Refit] Do 1 brain damage"}] {:on-play {:choices {:card #(and (ice? %) (has-subtype? % "Bioroid") (rezzed? %))} :msg (msg "give " (card-str state target) " \"[Subroutine] Do 1 brain damage\" before all its other subroutines") :effect (req (add-extra-sub! state :corp target new-sub (:cid card) {:front true}) (host state side (get-card state target) (assoc card :seen true :condition true)))} :sub-effect (do-brain-damage 1) :leave-play (req (remove-extra-subs! state :corp (:host card) (:cid card))) :events [{:event :rez :req (req (same-card? (:card context) (:host card))) :effect (req (add-extra-sub! state :corp (get-card state (:card context)) new-sub (:cid card) {:front true}))}]})) (defcard "Witness Tampering" {:on-play {:msg "remove 2 bad publicity" :effect (effect (lose-bad-publicity 2))}})
[ { "context": " [{dashboard-id :id, :as dashboard} {:name \"Test Dashboard\"}]\n Card ", "end": 5058, "score": 0.5454035401344299, "start": 5054, "tag": "NAME", "value": "Test" }, { "context": "e! Dashboard dashboard-id\n :name \"Revert Test\"\n :description \"something\")\n (tes", "end": 6794, "score": 0.6025719046592712, "start": 6783, "tag": "NAME", "value": "Revert Test" }, { "context": " Dashboard state\"\n (is (= {:name \"Revert Test\"\n :description \"something\"\n", "end": 6921, "score": 0.6194671988487244, "start": 6915, "tag": "NAME", "value": "Revert" }, { "context": "vert-dashboard! nil dashboard-id (users/user->id :crowberto) serialized-dashboard)\n (is (= {:name", "end": 7222, "score": 0.7442294359207153, "start": 7218, "tag": "USERNAME", "value": "crow" } ]
c#-metabase/test/metabase/models/dashboard_test.clj
hanakhry/Crime_Admin
0
(ns metabase.models.dashboard-test (:require [clojure.test :refer :all] [metabase.api.common :as api] [metabase.automagic-dashboards.core :as magic] [metabase.models.card :refer [Card]] [metabase.models.collection :as collection :refer [Collection]] [metabase.models.dashboard :as dashboard :refer :all] [metabase.models.dashboard-card :as dashboard-card :refer [DashboardCard]] [metabase.models.dashboard-card-series :refer [DashboardCardSeries]] [metabase.models.database :refer [Database]] [metabase.models.interface :as mi] [metabase.models.permissions :as perms] [metabase.models.pulse :refer [Pulse]] [metabase.models.pulse-card :refer [PulseCard]] [metabase.models.table :refer [Table]] [metabase.models.user :as user] [metabase.test :as mt] [metabase.test.data :refer :all] [metabase.test.data.users :as users] [metabase.test.util :as tu] [metabase.util :as u] [toucan.db :as db] [toucan.util.test :as tt])) ;; ## Dashboard Revisions (deftest serialize-dashboard-test (tt/with-temp* [Dashboard [{dashboard-id :id :as dashboard} {:name "Test Dashboard"}] Card [{card-id :id}] Card [{series-id-1 :id}] Card [{series-id-2 :id}] DashboardCard [{dashcard-id :id} {:dashboard_id dashboard-id, :card_id card-id}] DashboardCardSeries [_ {:dashboardcard_id dashcard-id, :card_id series-id-1, :position 0}] DashboardCardSeries [_ {:dashboardcard_id dashcard-id, :card_id series-id-2, :position 1}]] (is (= {:name "Test Dashboard" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id true :card_id true :series true}]} (update (serialize-dashboard dashboard) :cards (fn [[{:keys [id card_id series], :as card}]] [(assoc card :id (= dashcard-id id) :card_id (= card-id card_id) :series (= [series-id-1 series-id-2] series))])))))) (deftest diff-dashboards-str-test (is (= "renamed it from \"Diff Test\" to \"Diff Test Changed\" and added a description." (#'dashboard/diff-dashboards-str nil {:name "Diff Test" :description nil :cards []} {:name "Diff Test Changed" :description "foobar" :cards []}))) (is (= "added a card." (#'dashboard/diff-dashboards-str nil {:name "Diff Test" :description nil :cards []} {:name "Diff Test" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id 1 :card_id 1 :series []}]}))) (is (= "rearranged the cards, modified the series on card 1 and added some series to card 2." (#'dashboard/diff-dashboards-str nil {:name "Diff Test" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id 1 :card_id 1 :series [5 6]} {:sizeX 2 :sizeY 2 :row 0 :col 0 :id 2 :card_id 2 :series []}]} {:name "Diff Test" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id 1 :card_id 1 :series [4 5]} {:sizeX 2 :sizeY 2 :row 2 :col 0 :id 2 :card_id 2 :series [3 4 5]}]})))) (deftest revert-dashboard!-test (tt/with-temp* [Dashboard [{dashboard-id :id, :as dashboard} {:name "Test Dashboard"}] Card [{card-id :id}] Card [{series-id-1 :id}] Card [{series-id-2 :id}] DashboardCard [{dashcard-id :id :as dashboard-card} {:dashboard_id dashboard-id, :card_id card-id}] DashboardCardSeries [_ {:dashboardcard_id dashcard-id, :card_id series-id-1, :position 0}] DashboardCardSeries [_ {:dashboardcard_id dashcard-id, :card_id series-id-2, :position 1}]] (let [check-ids (fn [[{:keys [id card_id series] :as card}]] [(assoc card :id (= dashcard-id id) :card_id (= card-id card_id) :series (= [series-id-1 series-id-2] series))]) serialized-dashboard (serialize-dashboard dashboard)] (testing "original state" (is (= {:name "Test Dashboard" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id true :card_id true :series true}]} (update serialized-dashboard :cards check-ids)))) (testing "delete the dashcard and modify the dash attributes" (dashboard-card/delete-dashboard-card! dashboard-card (users/user->id :rasta)) (db/update! Dashboard dashboard-id :name "Revert Test" :description "something") (testing "capture updated Dashboard state" (is (= {:name "Revert Test" :description "something" :cards []} (serialize-dashboard (Dashboard dashboard-id)))))) (testing "now do the reversion; state should return to original" (#'dashboard/revert-dashboard! nil dashboard-id (users/user->id :crowberto) serialized-dashboard) (is (= {:name "Test Dashboard" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id false :card_id true :series true}]} (update (serialize-dashboard (Dashboard dashboard-id)) :cards check-ids))))))) (deftest public-sharing-test (testing "test that a Dashboard's :public_uuid comes back if public sharing is enabled..." (tu/with-temporary-setting-values [enable-public-sharing true] (tt/with-temp Dashboard [dashboard {:public_uuid (str (java.util.UUID/randomUUID))}] (is (schema= u/uuid-regex (:public_uuid dashboard))))) (testing "...but if public sharing is *disabled* it should come back as `nil`" (tu/with-temporary-setting-values [enable-public-sharing false] (tt/with-temp Dashboard [dashboard {:public_uuid (str (java.util.UUID/randomUUID))}] (is (= nil (:public_uuid dashboard)))))))) (deftest post-update-test (tt/with-temp* [Dashboard [{dashboard-id :id} {:name "Lucky the Pigeon's Lucky Stuff"}] Card [{card-id :id}] Pulse [{pulse-id :id} {:dashboard_id dashboard-id}] DashboardCard [{dashcard-id :id} {:dashboard_id dashboard-id, :card_id card-id}] PulseCard [{pulse-card-id :id} {:pulse_id pulse-id, :card_id card-id, :dashboard_card_id dashcard-id}]] (testing "Pulse name updates" (db/update! Dashboard dashboard-id :name "Lucky's Close Shaves") (is (= "Lucky's Close Shaves" (db/select-one-field :name Pulse :id pulse-id)))) (testing "PulseCard syncing" (tt/with-temp Card [{new-card-id :id}] (add-dashcard! dashboard-id new-card-id) (db/update! Dashboard dashboard-id :name "Lucky's Close Shaves") (is (not (nil? (db/select-one PulseCard :card_id new-card-id)))))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Collections Permissions Tests | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn do-with-dash-in-collection [f] (tu/with-non-admin-groups-no-root-collection-perms (tt/with-temp* [Collection [collection] Dashboard [dash {:collection_id (u/the-id collection)}] Database [db {:engine :h2}] Table [table {:db_id (u/the-id db)}] Card [card {:dataset_query {:database (u/the-id db) :type :query :query {:source-table (u/the-id table)}}}] DashboardCard [_ {:dashboard_id (u/the-id dash), :card_id (u/the-id card)}]] (f db collection dash)))) (defmacro with-dash-in-collection "Execute `body` with a Dashboard in a Collection. Dashboard will contain one Card in a Database." {:style/indent 1} [[db-binding collection-binding dash-binding] & body] `(do-with-dash-in-collection (fn [~db-binding ~collection-binding ~dash-binding] ~@body))) (deftest perms-test (with-dash-in-collection [db collection dash] (testing (str "Check that if a Dashboard is in a Collection, someone who would not be able to see it under the old " "artifact-permissions regime will be able to see it if they have permissions for that Collection") (binding [api/*current-user-permissions-set* (atom #{(perms/collection-read-path collection)})] (is (= true (mi/can-read? dash))))) (testing (str "Check that if a Dashboard is in a Collection, someone who would otherwise be able to see it under " "the old artifact-permissions regime will *NOT* be able to see it if they don't have permissions for " "that Collection")) (binding [api/*current-user-permissions-set* (atom #{(perms/object-path (u/the-id db))})] (is (= false (mi/can-read? dash)))) (testing "Do we have *write* Permissions for a Dashboard if we have *write* Permissions for the Collection its in?" (binding [api/*current-user-permissions-set* (atom #{(perms/collection-readwrite-path collection)})] (mi/can-write? dash))))) (deftest transient-dashboards-test (testing "test that we save a transient dashboard" (tu/with-model-cleanup [Card Dashboard DashboardCard Collection] (let [rastas-personal-collection (collection/user->personal-collection (users/user->id :rasta))] (binding [api/*current-user-id* (users/user->id :rasta) api/*current-user-permissions-set* (-> :rasta users/user->id user/permissions-set atom)] (let [dashboard (magic/automagic-analysis (Table (id :venues)) {}) saved-dashboard (save-transient-dashboard! dashboard (u/the-id rastas-personal-collection))] (is (= (db/count DashboardCard :dashboard_id (u/the-id saved-dashboard)) (-> dashboard :ordered_cards count))))))))) (deftest validate-collection-namespace-test (mt/with-temp Collection [{collection-id :id} {:namespace "currency"}] (testing "Shouldn't be able to create a Dashboard in a non-normal Collection" (let [dashboard-name (mt/random-name)] (try (is (thrown-with-msg? clojure.lang.ExceptionInfo #"A Dashboard can only go in Collections in the \"default\" namespace" (db/insert! Dashboard (assoc (tt/with-temp-defaults Dashboard) :collection_id collection-id, :name dashboard-name)))) (finally (db/delete! Dashboard :name dashboard-name))))) (testing "Shouldn't be able to move a Dashboard to a non-normal Collection" (mt/with-temp Dashboard [{card-id :id}] (is (thrown-with-msg? clojure.lang.ExceptionInfo #"A Dashboard can only go in Collections in the \"default\" namespace" (db/update! Dashboard card-id {:collection_id collection-id}))))))) (deftest validate-parameters-test (testing "Should validate Dashboard :parameters when" (testing "creating" (is (thrown-with-msg? clojure.lang.ExceptionInfo #":parameters must be a sequence of maps with String :id keys" (mt/with-temp Dashboard [_ {:parameters {:a :b}}])))) (testing "updating" (mt/with-temp Dashboard [{:keys [id]} {:parameters []}] (is (thrown-with-msg? clojure.lang.ExceptionInfo #":parameters must be a sequence of maps with String :id keys" (db/update! Dashboard id :parameters [{:id 100}])))))))
81907
(ns metabase.models.dashboard-test (:require [clojure.test :refer :all] [metabase.api.common :as api] [metabase.automagic-dashboards.core :as magic] [metabase.models.card :refer [Card]] [metabase.models.collection :as collection :refer [Collection]] [metabase.models.dashboard :as dashboard :refer :all] [metabase.models.dashboard-card :as dashboard-card :refer [DashboardCard]] [metabase.models.dashboard-card-series :refer [DashboardCardSeries]] [metabase.models.database :refer [Database]] [metabase.models.interface :as mi] [metabase.models.permissions :as perms] [metabase.models.pulse :refer [Pulse]] [metabase.models.pulse-card :refer [PulseCard]] [metabase.models.table :refer [Table]] [metabase.models.user :as user] [metabase.test :as mt] [metabase.test.data :refer :all] [metabase.test.data.users :as users] [metabase.test.util :as tu] [metabase.util :as u] [toucan.db :as db] [toucan.util.test :as tt])) ;; ## Dashboard Revisions (deftest serialize-dashboard-test (tt/with-temp* [Dashboard [{dashboard-id :id :as dashboard} {:name "Test Dashboard"}] Card [{card-id :id}] Card [{series-id-1 :id}] Card [{series-id-2 :id}] DashboardCard [{dashcard-id :id} {:dashboard_id dashboard-id, :card_id card-id}] DashboardCardSeries [_ {:dashboardcard_id dashcard-id, :card_id series-id-1, :position 0}] DashboardCardSeries [_ {:dashboardcard_id dashcard-id, :card_id series-id-2, :position 1}]] (is (= {:name "Test Dashboard" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id true :card_id true :series true}]} (update (serialize-dashboard dashboard) :cards (fn [[{:keys [id card_id series], :as card}]] [(assoc card :id (= dashcard-id id) :card_id (= card-id card_id) :series (= [series-id-1 series-id-2] series))])))))) (deftest diff-dashboards-str-test (is (= "renamed it from \"Diff Test\" to \"Diff Test Changed\" and added a description." (#'dashboard/diff-dashboards-str nil {:name "Diff Test" :description nil :cards []} {:name "Diff Test Changed" :description "foobar" :cards []}))) (is (= "added a card." (#'dashboard/diff-dashboards-str nil {:name "Diff Test" :description nil :cards []} {:name "Diff Test" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id 1 :card_id 1 :series []}]}))) (is (= "rearranged the cards, modified the series on card 1 and added some series to card 2." (#'dashboard/diff-dashboards-str nil {:name "Diff Test" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id 1 :card_id 1 :series [5 6]} {:sizeX 2 :sizeY 2 :row 0 :col 0 :id 2 :card_id 2 :series []}]} {:name "Diff Test" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id 1 :card_id 1 :series [4 5]} {:sizeX 2 :sizeY 2 :row 2 :col 0 :id 2 :card_id 2 :series [3 4 5]}]})))) (deftest revert-dashboard!-test (tt/with-temp* [Dashboard [{dashboard-id :id, :as dashboard} {:name "<NAME> Dashboard"}] Card [{card-id :id}] Card [{series-id-1 :id}] Card [{series-id-2 :id}] DashboardCard [{dashcard-id :id :as dashboard-card} {:dashboard_id dashboard-id, :card_id card-id}] DashboardCardSeries [_ {:dashboardcard_id dashcard-id, :card_id series-id-1, :position 0}] DashboardCardSeries [_ {:dashboardcard_id dashcard-id, :card_id series-id-2, :position 1}]] (let [check-ids (fn [[{:keys [id card_id series] :as card}]] [(assoc card :id (= dashcard-id id) :card_id (= card-id card_id) :series (= [series-id-1 series-id-2] series))]) serialized-dashboard (serialize-dashboard dashboard)] (testing "original state" (is (= {:name "Test Dashboard" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id true :card_id true :series true}]} (update serialized-dashboard :cards check-ids)))) (testing "delete the dashcard and modify the dash attributes" (dashboard-card/delete-dashboard-card! dashboard-card (users/user->id :rasta)) (db/update! Dashboard dashboard-id :name "<NAME>" :description "something") (testing "capture updated Dashboard state" (is (= {:name "<NAME> Test" :description "something" :cards []} (serialize-dashboard (Dashboard dashboard-id)))))) (testing "now do the reversion; state should return to original" (#'dashboard/revert-dashboard! nil dashboard-id (users/user->id :crowberto) serialized-dashboard) (is (= {:name "Test Dashboard" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id false :card_id true :series true}]} (update (serialize-dashboard (Dashboard dashboard-id)) :cards check-ids))))))) (deftest public-sharing-test (testing "test that a Dashboard's :public_uuid comes back if public sharing is enabled..." (tu/with-temporary-setting-values [enable-public-sharing true] (tt/with-temp Dashboard [dashboard {:public_uuid (str (java.util.UUID/randomUUID))}] (is (schema= u/uuid-regex (:public_uuid dashboard))))) (testing "...but if public sharing is *disabled* it should come back as `nil`" (tu/with-temporary-setting-values [enable-public-sharing false] (tt/with-temp Dashboard [dashboard {:public_uuid (str (java.util.UUID/randomUUID))}] (is (= nil (:public_uuid dashboard)))))))) (deftest post-update-test (tt/with-temp* [Dashboard [{dashboard-id :id} {:name "Lucky the Pigeon's Lucky Stuff"}] Card [{card-id :id}] Pulse [{pulse-id :id} {:dashboard_id dashboard-id}] DashboardCard [{dashcard-id :id} {:dashboard_id dashboard-id, :card_id card-id}] PulseCard [{pulse-card-id :id} {:pulse_id pulse-id, :card_id card-id, :dashboard_card_id dashcard-id}]] (testing "Pulse name updates" (db/update! Dashboard dashboard-id :name "Lucky's Close Shaves") (is (= "Lucky's Close Shaves" (db/select-one-field :name Pulse :id pulse-id)))) (testing "PulseCard syncing" (tt/with-temp Card [{new-card-id :id}] (add-dashcard! dashboard-id new-card-id) (db/update! Dashboard dashboard-id :name "Lucky's Close Shaves") (is (not (nil? (db/select-one PulseCard :card_id new-card-id)))))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Collections Permissions Tests | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn do-with-dash-in-collection [f] (tu/with-non-admin-groups-no-root-collection-perms (tt/with-temp* [Collection [collection] Dashboard [dash {:collection_id (u/the-id collection)}] Database [db {:engine :h2}] Table [table {:db_id (u/the-id db)}] Card [card {:dataset_query {:database (u/the-id db) :type :query :query {:source-table (u/the-id table)}}}] DashboardCard [_ {:dashboard_id (u/the-id dash), :card_id (u/the-id card)}]] (f db collection dash)))) (defmacro with-dash-in-collection "Execute `body` with a Dashboard in a Collection. Dashboard will contain one Card in a Database." {:style/indent 1} [[db-binding collection-binding dash-binding] & body] `(do-with-dash-in-collection (fn [~db-binding ~collection-binding ~dash-binding] ~@body))) (deftest perms-test (with-dash-in-collection [db collection dash] (testing (str "Check that if a Dashboard is in a Collection, someone who would not be able to see it under the old " "artifact-permissions regime will be able to see it if they have permissions for that Collection") (binding [api/*current-user-permissions-set* (atom #{(perms/collection-read-path collection)})] (is (= true (mi/can-read? dash))))) (testing (str "Check that if a Dashboard is in a Collection, someone who would otherwise be able to see it under " "the old artifact-permissions regime will *NOT* be able to see it if they don't have permissions for " "that Collection")) (binding [api/*current-user-permissions-set* (atom #{(perms/object-path (u/the-id db))})] (is (= false (mi/can-read? dash)))) (testing "Do we have *write* Permissions for a Dashboard if we have *write* Permissions for the Collection its in?" (binding [api/*current-user-permissions-set* (atom #{(perms/collection-readwrite-path collection)})] (mi/can-write? dash))))) (deftest transient-dashboards-test (testing "test that we save a transient dashboard" (tu/with-model-cleanup [Card Dashboard DashboardCard Collection] (let [rastas-personal-collection (collection/user->personal-collection (users/user->id :rasta))] (binding [api/*current-user-id* (users/user->id :rasta) api/*current-user-permissions-set* (-> :rasta users/user->id user/permissions-set atom)] (let [dashboard (magic/automagic-analysis (Table (id :venues)) {}) saved-dashboard (save-transient-dashboard! dashboard (u/the-id rastas-personal-collection))] (is (= (db/count DashboardCard :dashboard_id (u/the-id saved-dashboard)) (-> dashboard :ordered_cards count))))))))) (deftest validate-collection-namespace-test (mt/with-temp Collection [{collection-id :id} {:namespace "currency"}] (testing "Shouldn't be able to create a Dashboard in a non-normal Collection" (let [dashboard-name (mt/random-name)] (try (is (thrown-with-msg? clojure.lang.ExceptionInfo #"A Dashboard can only go in Collections in the \"default\" namespace" (db/insert! Dashboard (assoc (tt/with-temp-defaults Dashboard) :collection_id collection-id, :name dashboard-name)))) (finally (db/delete! Dashboard :name dashboard-name))))) (testing "Shouldn't be able to move a Dashboard to a non-normal Collection" (mt/with-temp Dashboard [{card-id :id}] (is (thrown-with-msg? clojure.lang.ExceptionInfo #"A Dashboard can only go in Collections in the \"default\" namespace" (db/update! Dashboard card-id {:collection_id collection-id}))))))) (deftest validate-parameters-test (testing "Should validate Dashboard :parameters when" (testing "creating" (is (thrown-with-msg? clojure.lang.ExceptionInfo #":parameters must be a sequence of maps with String :id keys" (mt/with-temp Dashboard [_ {:parameters {:a :b}}])))) (testing "updating" (mt/with-temp Dashboard [{:keys [id]} {:parameters []}] (is (thrown-with-msg? clojure.lang.ExceptionInfo #":parameters must be a sequence of maps with String :id keys" (db/update! Dashboard id :parameters [{:id 100}])))))))
true
(ns metabase.models.dashboard-test (:require [clojure.test :refer :all] [metabase.api.common :as api] [metabase.automagic-dashboards.core :as magic] [metabase.models.card :refer [Card]] [metabase.models.collection :as collection :refer [Collection]] [metabase.models.dashboard :as dashboard :refer :all] [metabase.models.dashboard-card :as dashboard-card :refer [DashboardCard]] [metabase.models.dashboard-card-series :refer [DashboardCardSeries]] [metabase.models.database :refer [Database]] [metabase.models.interface :as mi] [metabase.models.permissions :as perms] [metabase.models.pulse :refer [Pulse]] [metabase.models.pulse-card :refer [PulseCard]] [metabase.models.table :refer [Table]] [metabase.models.user :as user] [metabase.test :as mt] [metabase.test.data :refer :all] [metabase.test.data.users :as users] [metabase.test.util :as tu] [metabase.util :as u] [toucan.db :as db] [toucan.util.test :as tt])) ;; ## Dashboard Revisions (deftest serialize-dashboard-test (tt/with-temp* [Dashboard [{dashboard-id :id :as dashboard} {:name "Test Dashboard"}] Card [{card-id :id}] Card [{series-id-1 :id}] Card [{series-id-2 :id}] DashboardCard [{dashcard-id :id} {:dashboard_id dashboard-id, :card_id card-id}] DashboardCardSeries [_ {:dashboardcard_id dashcard-id, :card_id series-id-1, :position 0}] DashboardCardSeries [_ {:dashboardcard_id dashcard-id, :card_id series-id-2, :position 1}]] (is (= {:name "Test Dashboard" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id true :card_id true :series true}]} (update (serialize-dashboard dashboard) :cards (fn [[{:keys [id card_id series], :as card}]] [(assoc card :id (= dashcard-id id) :card_id (= card-id card_id) :series (= [series-id-1 series-id-2] series))])))))) (deftest diff-dashboards-str-test (is (= "renamed it from \"Diff Test\" to \"Diff Test Changed\" and added a description." (#'dashboard/diff-dashboards-str nil {:name "Diff Test" :description nil :cards []} {:name "Diff Test Changed" :description "foobar" :cards []}))) (is (= "added a card." (#'dashboard/diff-dashboards-str nil {:name "Diff Test" :description nil :cards []} {:name "Diff Test" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id 1 :card_id 1 :series []}]}))) (is (= "rearranged the cards, modified the series on card 1 and added some series to card 2." (#'dashboard/diff-dashboards-str nil {:name "Diff Test" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id 1 :card_id 1 :series [5 6]} {:sizeX 2 :sizeY 2 :row 0 :col 0 :id 2 :card_id 2 :series []}]} {:name "Diff Test" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id 1 :card_id 1 :series [4 5]} {:sizeX 2 :sizeY 2 :row 2 :col 0 :id 2 :card_id 2 :series [3 4 5]}]})))) (deftest revert-dashboard!-test (tt/with-temp* [Dashboard [{dashboard-id :id, :as dashboard} {:name "PI:NAME:<NAME>END_PI Dashboard"}] Card [{card-id :id}] Card [{series-id-1 :id}] Card [{series-id-2 :id}] DashboardCard [{dashcard-id :id :as dashboard-card} {:dashboard_id dashboard-id, :card_id card-id}] DashboardCardSeries [_ {:dashboardcard_id dashcard-id, :card_id series-id-1, :position 0}] DashboardCardSeries [_ {:dashboardcard_id dashcard-id, :card_id series-id-2, :position 1}]] (let [check-ids (fn [[{:keys [id card_id series] :as card}]] [(assoc card :id (= dashcard-id id) :card_id (= card-id card_id) :series (= [series-id-1 series-id-2] series))]) serialized-dashboard (serialize-dashboard dashboard)] (testing "original state" (is (= {:name "Test Dashboard" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id true :card_id true :series true}]} (update serialized-dashboard :cards check-ids)))) (testing "delete the dashcard and modify the dash attributes" (dashboard-card/delete-dashboard-card! dashboard-card (users/user->id :rasta)) (db/update! Dashboard dashboard-id :name "PI:NAME:<NAME>END_PI" :description "something") (testing "capture updated Dashboard state" (is (= {:name "PI:NAME:<NAME>END_PI Test" :description "something" :cards []} (serialize-dashboard (Dashboard dashboard-id)))))) (testing "now do the reversion; state should return to original" (#'dashboard/revert-dashboard! nil dashboard-id (users/user->id :crowberto) serialized-dashboard) (is (= {:name "Test Dashboard" :description nil :cards [{:sizeX 2 :sizeY 2 :row 0 :col 0 :id false :card_id true :series true}]} (update (serialize-dashboard (Dashboard dashboard-id)) :cards check-ids))))))) (deftest public-sharing-test (testing "test that a Dashboard's :public_uuid comes back if public sharing is enabled..." (tu/with-temporary-setting-values [enable-public-sharing true] (tt/with-temp Dashboard [dashboard {:public_uuid (str (java.util.UUID/randomUUID))}] (is (schema= u/uuid-regex (:public_uuid dashboard))))) (testing "...but if public sharing is *disabled* it should come back as `nil`" (tu/with-temporary-setting-values [enable-public-sharing false] (tt/with-temp Dashboard [dashboard {:public_uuid (str (java.util.UUID/randomUUID))}] (is (= nil (:public_uuid dashboard)))))))) (deftest post-update-test (tt/with-temp* [Dashboard [{dashboard-id :id} {:name "Lucky the Pigeon's Lucky Stuff"}] Card [{card-id :id}] Pulse [{pulse-id :id} {:dashboard_id dashboard-id}] DashboardCard [{dashcard-id :id} {:dashboard_id dashboard-id, :card_id card-id}] PulseCard [{pulse-card-id :id} {:pulse_id pulse-id, :card_id card-id, :dashboard_card_id dashcard-id}]] (testing "Pulse name updates" (db/update! Dashboard dashboard-id :name "Lucky's Close Shaves") (is (= "Lucky's Close Shaves" (db/select-one-field :name Pulse :id pulse-id)))) (testing "PulseCard syncing" (tt/with-temp Card [{new-card-id :id}] (add-dashcard! dashboard-id new-card-id) (db/update! Dashboard dashboard-id :name "Lucky's Close Shaves") (is (not (nil? (db/select-one PulseCard :card_id new-card-id)))))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Collections Permissions Tests | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn do-with-dash-in-collection [f] (tu/with-non-admin-groups-no-root-collection-perms (tt/with-temp* [Collection [collection] Dashboard [dash {:collection_id (u/the-id collection)}] Database [db {:engine :h2}] Table [table {:db_id (u/the-id db)}] Card [card {:dataset_query {:database (u/the-id db) :type :query :query {:source-table (u/the-id table)}}}] DashboardCard [_ {:dashboard_id (u/the-id dash), :card_id (u/the-id card)}]] (f db collection dash)))) (defmacro with-dash-in-collection "Execute `body` with a Dashboard in a Collection. Dashboard will contain one Card in a Database." {:style/indent 1} [[db-binding collection-binding dash-binding] & body] `(do-with-dash-in-collection (fn [~db-binding ~collection-binding ~dash-binding] ~@body))) (deftest perms-test (with-dash-in-collection [db collection dash] (testing (str "Check that if a Dashboard is in a Collection, someone who would not be able to see it under the old " "artifact-permissions regime will be able to see it if they have permissions for that Collection") (binding [api/*current-user-permissions-set* (atom #{(perms/collection-read-path collection)})] (is (= true (mi/can-read? dash))))) (testing (str "Check that if a Dashboard is in a Collection, someone who would otherwise be able to see it under " "the old artifact-permissions regime will *NOT* be able to see it if they don't have permissions for " "that Collection")) (binding [api/*current-user-permissions-set* (atom #{(perms/object-path (u/the-id db))})] (is (= false (mi/can-read? dash)))) (testing "Do we have *write* Permissions for a Dashboard if we have *write* Permissions for the Collection its in?" (binding [api/*current-user-permissions-set* (atom #{(perms/collection-readwrite-path collection)})] (mi/can-write? dash))))) (deftest transient-dashboards-test (testing "test that we save a transient dashboard" (tu/with-model-cleanup [Card Dashboard DashboardCard Collection] (let [rastas-personal-collection (collection/user->personal-collection (users/user->id :rasta))] (binding [api/*current-user-id* (users/user->id :rasta) api/*current-user-permissions-set* (-> :rasta users/user->id user/permissions-set atom)] (let [dashboard (magic/automagic-analysis (Table (id :venues)) {}) saved-dashboard (save-transient-dashboard! dashboard (u/the-id rastas-personal-collection))] (is (= (db/count DashboardCard :dashboard_id (u/the-id saved-dashboard)) (-> dashboard :ordered_cards count))))))))) (deftest validate-collection-namespace-test (mt/with-temp Collection [{collection-id :id} {:namespace "currency"}] (testing "Shouldn't be able to create a Dashboard in a non-normal Collection" (let [dashboard-name (mt/random-name)] (try (is (thrown-with-msg? clojure.lang.ExceptionInfo #"A Dashboard can only go in Collections in the \"default\" namespace" (db/insert! Dashboard (assoc (tt/with-temp-defaults Dashboard) :collection_id collection-id, :name dashboard-name)))) (finally (db/delete! Dashboard :name dashboard-name))))) (testing "Shouldn't be able to move a Dashboard to a non-normal Collection" (mt/with-temp Dashboard [{card-id :id}] (is (thrown-with-msg? clojure.lang.ExceptionInfo #"A Dashboard can only go in Collections in the \"default\" namespace" (db/update! Dashboard card-id {:collection_id collection-id}))))))) (deftest validate-parameters-test (testing "Should validate Dashboard :parameters when" (testing "creating" (is (thrown-with-msg? clojure.lang.ExceptionInfo #":parameters must be a sequence of maps with String :id keys" (mt/with-temp Dashboard [_ {:parameters {:a :b}}])))) (testing "updating" (mt/with-temp Dashboard [{:keys [id]} {:parameters []}] (is (thrown-with-msg? clojure.lang.ExceptionInfo #":parameters must be a sequence of maps with String :id keys" (db/update! Dashboard id :parameters [{:id 100}])))))))
[ { "context": "l\" :type \"email\" :col-width \"col-6\" :placeholder \"pevita@gmail.com\"}\n :password {:label \"Password\" :type \"password", "end": 315, "score": 0.9999204277992249, "start": 299, "tag": "EMAIL", "value": "pevita@gmail.com" }, { "context": "eholder \"pevita@gmail.com\"}\n :password {:label \"Password\" :type \"password\" :col-width \"col-8\" :placeholder", "end": 348, "score": 0.9380483627319336, "start": 340, "tag": "PASSWORD", "value": "Password" } ]
src/client/ebtanas/ui/login.cljs
codxse/ebtanas-untangled
0
(ns ebtanas.ui.login (:require [om.next :as om :refer-macros [defui]] [om.dom :as dom] [untangled.client.core :as uc] [ebtanas.state.routes :refer [page-data]])) (defonce input-text-data {:email {:label "Email" :type "email" :col-width "col-6" :placeholder "pevita@gmail.com"} :password {:label "Password" :type "password" :col-width "col-8" :placeholder "***************"}}) (defui ^:once InputTextLogin static uc/InitialAppState (initial-state [this {:keys [label type col-width placeholder]}] {:label label :type type :col-width col-width :placeholder placeholder}) static om/Ident (ident [this {:keys [label]}] [:login-form/by-label label]) static om/IQuery (query [this] [:label :type :col-width :placeholder]) Object (render [this] (let [{:keys [label type col-width placeholder]} (om/props this)] (dom/div #js {:className "form-group"} (dom/div #js {:className "col-4"} (dom/label #js {:className "form-label"} label)) (dom/div #js {:className col-width} (dom/input #js {:className "form-input" :type type :placeholder placeholder})))))) (def input-text (om/factory InputTextLogin)) (defui ^:once Login static uc/InitialAppState (initial-state [this params] {:handler (get-in page-data [:login :handler]) :title (get-in page-data [:login :title]) :id 1 :label {:checkbox "Ingat saya" :submit "Masuk" :forgot-pwd "Lupa password?"} :txt-input-form [(uc/initial-state InputTextLogin (:email input-text-data)) (uc/initial-state InputTextLogin (:password input-text-data))]}) static om/IQuery (query [this] [:handler :id :title :label {:txt-input-form (om/get-query InputTextLogin)}]) Object (render [this] (let [{:keys [title txt-input-form] :as props} (om/props this)] (dom/section #js {:className "body section columns"} (dom/h2 nil title) (dom/div #js {:className "container"} (dom/div #js {:className "column col-6 centered"} (dom/form #js {:className "form-horizontal"} (input-text (txt-input-form 0)) (input-text (txt-input-form 1)) (dom/div #js {:className "form-group"} (dom/div #js {:className "col-4"}) (dom/label #js {:className "col-8"} (dom/label #js {:className "form-checkbox"} (dom/input #js {:type "checkbox"}) (dom/i #js {:className "form-icon"}) (get-in props [:label :checkbox])))) (dom/div #js {:className "form-group"} (dom/div #js {:className "col-4"}) (dom/div #js {:className "col-8"} (dom/button #js {:className "btn btn-primary" :type "submit"} (get-in props [:label :submit])) (dom/button #js {:className "btn btn-link disabled"} (get-in props [:label :forgot-pwd]))))))))))) (def login (om/factory Login))
48814
(ns ebtanas.ui.login (:require [om.next :as om :refer-macros [defui]] [om.dom :as dom] [untangled.client.core :as uc] [ebtanas.state.routes :refer [page-data]])) (defonce input-text-data {:email {:label "Email" :type "email" :col-width "col-6" :placeholder "<EMAIL>"} :password {:label "<PASSWORD>" :type "password" :col-width "col-8" :placeholder "***************"}}) (defui ^:once InputTextLogin static uc/InitialAppState (initial-state [this {:keys [label type col-width placeholder]}] {:label label :type type :col-width col-width :placeholder placeholder}) static om/Ident (ident [this {:keys [label]}] [:login-form/by-label label]) static om/IQuery (query [this] [:label :type :col-width :placeholder]) Object (render [this] (let [{:keys [label type col-width placeholder]} (om/props this)] (dom/div #js {:className "form-group"} (dom/div #js {:className "col-4"} (dom/label #js {:className "form-label"} label)) (dom/div #js {:className col-width} (dom/input #js {:className "form-input" :type type :placeholder placeholder})))))) (def input-text (om/factory InputTextLogin)) (defui ^:once Login static uc/InitialAppState (initial-state [this params] {:handler (get-in page-data [:login :handler]) :title (get-in page-data [:login :title]) :id 1 :label {:checkbox "Ingat saya" :submit "Masuk" :forgot-pwd "Lupa password?"} :txt-input-form [(uc/initial-state InputTextLogin (:email input-text-data)) (uc/initial-state InputTextLogin (:password input-text-data))]}) static om/IQuery (query [this] [:handler :id :title :label {:txt-input-form (om/get-query InputTextLogin)}]) Object (render [this] (let [{:keys [title txt-input-form] :as props} (om/props this)] (dom/section #js {:className "body section columns"} (dom/h2 nil title) (dom/div #js {:className "container"} (dom/div #js {:className "column col-6 centered"} (dom/form #js {:className "form-horizontal"} (input-text (txt-input-form 0)) (input-text (txt-input-form 1)) (dom/div #js {:className "form-group"} (dom/div #js {:className "col-4"}) (dom/label #js {:className "col-8"} (dom/label #js {:className "form-checkbox"} (dom/input #js {:type "checkbox"}) (dom/i #js {:className "form-icon"}) (get-in props [:label :checkbox])))) (dom/div #js {:className "form-group"} (dom/div #js {:className "col-4"}) (dom/div #js {:className "col-8"} (dom/button #js {:className "btn btn-primary" :type "submit"} (get-in props [:label :submit])) (dom/button #js {:className "btn btn-link disabled"} (get-in props [:label :forgot-pwd]))))))))))) (def login (om/factory Login))
true
(ns ebtanas.ui.login (:require [om.next :as om :refer-macros [defui]] [om.dom :as dom] [untangled.client.core :as uc] [ebtanas.state.routes :refer [page-data]])) (defonce input-text-data {:email {:label "Email" :type "email" :col-width "col-6" :placeholder "PI:EMAIL:<EMAIL>END_PI"} :password {:label "PI:PASSWORD:<PASSWORD>END_PI" :type "password" :col-width "col-8" :placeholder "***************"}}) (defui ^:once InputTextLogin static uc/InitialAppState (initial-state [this {:keys [label type col-width placeholder]}] {:label label :type type :col-width col-width :placeholder placeholder}) static om/Ident (ident [this {:keys [label]}] [:login-form/by-label label]) static om/IQuery (query [this] [:label :type :col-width :placeholder]) Object (render [this] (let [{:keys [label type col-width placeholder]} (om/props this)] (dom/div #js {:className "form-group"} (dom/div #js {:className "col-4"} (dom/label #js {:className "form-label"} label)) (dom/div #js {:className col-width} (dom/input #js {:className "form-input" :type type :placeholder placeholder})))))) (def input-text (om/factory InputTextLogin)) (defui ^:once Login static uc/InitialAppState (initial-state [this params] {:handler (get-in page-data [:login :handler]) :title (get-in page-data [:login :title]) :id 1 :label {:checkbox "Ingat saya" :submit "Masuk" :forgot-pwd "Lupa password?"} :txt-input-form [(uc/initial-state InputTextLogin (:email input-text-data)) (uc/initial-state InputTextLogin (:password input-text-data))]}) static om/IQuery (query [this] [:handler :id :title :label {:txt-input-form (om/get-query InputTextLogin)}]) Object (render [this] (let [{:keys [title txt-input-form] :as props} (om/props this)] (dom/section #js {:className "body section columns"} (dom/h2 nil title) (dom/div #js {:className "container"} (dom/div #js {:className "column col-6 centered"} (dom/form #js {:className "form-horizontal"} (input-text (txt-input-form 0)) (input-text (txt-input-form 1)) (dom/div #js {:className "form-group"} (dom/div #js {:className "col-4"}) (dom/label #js {:className "col-8"} (dom/label #js {:className "form-checkbox"} (dom/input #js {:type "checkbox"}) (dom/i #js {:className "form-icon"}) (get-in props [:label :checkbox])))) (dom/div #js {:className "form-group"} (dom/div #js {:className "col-4"}) (dom/div #js {:className "col-8"} (dom/button #js {:className "btn btn-primary" :type "submit"} (get-in props [:label :submit])) (dom/button #js {:className "btn btn-link disabled"} (get-in props [:label :forgot-pwd]))))))))))) (def login (om/factory Login))
[ { "context": "\n(def mock-ctx {:request {:params {:businessName \"Johnys Pizza\"\n :zipCodes \"323", "end": 279, "score": 0.9998736381530762, "start": 267, "tag": "NAME", "value": "Johnys Pizza" }, { "context": "ipCodes \"32345\"\n :businessName \"Johnys Pizza\"\n :startDate \"2013-02-02\"\n ", "end": 2075, "score": 0.9998705387115479, "start": 2063, "tag": "NAME", "value": "Johnys Pizza" }, { "context": "des \"32345\",\n :businessName \"Johnys Pizza\",\n :startDate \"2013-02-02\",\n", "end": 2735, "score": 0.9998762011528015, "start": 2723, "tag": "NAME", "value": "Johnys Pizza" }, { "context": "2345\",\n :businessName \"Johnys Pizza\",\n :startDate \"2013-02", "end": 3489, "score": 0.9998737573623657, "start": 3477, "tag": "NAME", "value": "Johnys Pizza" }, { "context": "2345\",\n :businessName \"Johnys Pizza\",\n :endDate \"2017-02-0", "end": 4259, "score": 0.9998793601989746, "start": 4247, "tag": "NAME", "value": "Johnys Pizza" }, { "context": "\"}}]},\n :params {:businessName \"Johnys Pizza\",\n :startDate \"2013-02", "end": 4985, "score": 0.9998635053634644, "start": 4973, "tag": "NAME", "value": "Johnys Pizza" }, { "context": " \"33137,22345\"\n :businessName \"McDonalds\"\n :endDate \"2015-03-03\"\n ", "end": 5613, "score": 0.999809205532074, "start": 5604, "tag": "NAME", "value": "McDonalds" }, { "context": " :businessName \"McDonalds\"\n :startD", "end": 5924, "score": 0.999798059463501, "start": 5915, "tag": "NAME", "value": "McDonalds" } ]
test/unit/fbi_api/handlers/inspections_test.clj
CodeforSouth/fbi-api
8
(ns unit.fbi-api.handlers.inspections-test (:require [clojure.test :refer :all] [fbi-api.handlers.inspections :refer :all])) ;; =========================== MOCK DATA =================================== (def mock-ctx {:request {:params {:businessName "Johnys Pizza" :zipCodes "32345" :districtCode "D3" :startDate "2013-02-02" :endDate "2017-02-01" :countyNumber "19" :perPage "1" :page "2"}}}) (def inspection-example {:county_name "Broward", :county_number 16, :location_address "8735 STIRLING RD", :noncritical_violations_before_2013 nil, :license_type_code "2010", :location_city "COOPER CITY", :business_name "FAMILY BAGELS OF LONG ISLAND", :inspection_date #inst "2016-07-07T04:00:00.000-00:00", :pda_status true, :license_number 1621404, :location_zipcode "33328", :critical_violations_before_2013 nil, :high_priority_violations 2, :inspection_visit_id 5807286, :inspection_number 2571280, :basic_violations 4, :license_id "6321820", :inspection_class "Food", :total_violations 11, :inspection_disposition "Inspection Completed - No Further Action", :district "D2", :intermediate_violations 5, :inspection_type "Food-Licensing Inspection", :violations [{:id 3, :count 1} {:id 9, :count 1} {:id 18, :count 1} {:id 23, :count 1} {:id 33, :count 1} {:id 43, :count 1} {:id 53, :count 1} {:id 54, :count 1}]}) ;; ================================ BEGIN TESTS ============================ (deftest processable?-test (testing "Given a request object, returns all params if all true." (is (= (processable? mock-ctx) [true {:valid-params {:zipCodes "32345" :businessName "Johnys Pizza" :startDate "2013-02-02" :endDate "2017-02-01" :countyNumber "19" :districtCode "D3" :perPage 1 :page 2}}]))) (testing "json error for county if county is invalid" (is (= [false {:errors-map {:errors [{:code 1, :title "Validation Error", :detail "Invalid format or value for parameter.", :source {:parameter "countyNumber"}}]}, :params {:zipCodes "32345", :businessName "Johnys Pizza", :startDate "2013-02-02", :endDate "2017-02-01", :districtCode "D3", :perPage 1, :page 2}}] (processable? (assoc-in mock-ctx [:request :params :countyNumber] "38h3fh__"))))) (testing "json error for district if district is invalid" (is (= [false {:errors-map {:errors [{:code 1, :title "Validation Error", :detail "Invalid format or value for parameter.", :source {:parameter "districtCode"}}]}, :params {:zipCodes "32345", :businessName "Johnys Pizza", :startDate "2013-02-02", :endDate "2017-02-01", :countyNumber "19", :perPage 1, :page 2}}] (processable? (assoc-in mock-ctx [:request :params :districtCode] "D9999"))))) (testing "json error for date if date is invalid" (is (= [false {:errors-map {:errors [{:code 1, :title "Validation Error", :detail "Invalid format or value for parameter.", :source {:parameter "startDate"}}]}, :params {:zipCodes "32345", :businessName "Johnys Pizza", :endDate "2017-02-01", :districtCode "D3", :countyNumber "19", :perPage 1, :page 2}}] (processable? (assoc-in mock-ctx [:request :params :startDate] "2015-03-a0"))))) (testing "json error for zipCodes if zipCode is invalid" (is (= [false {:errors-map {:errors [{:code 1, :title "Validation Error", :detail "Invalid format or value for parameter.", :source {:parameter "zipCodes"}}]}, :params {:businessName "Johnys Pizza", :startDate "2013-02-02", :endDate "2017-02-01", :districtCode "D3", :countyNumber "19", :perPage 1, :page 2}}] (processable? (assoc-in mock-ctx [:request :params :zipCodes] "33136,33435,0")))))) (deftest validate-inspections-params-test (testing "Given query params input, returns valid and invalid format/values." (is (= {:invalid {:startDate false} :valid {:zipCodes "33137,22345" :businessName "McDonalds" :endDate "2015-03-03" :districtCode nil :countyNumber nil :perPage 1 :page 2}} (validate-inspections-params {:zipCodes "33137,22345" :businessName "McDonalds" :startDate "2013-aa-22" :endDate "2015-03-03" :districtCode nil :countyNumber nil :perPage "1" :page "2"}))))) (deftest handle-unprocessable-test (testing "properly returns correct error object given a ctx")) (deftest format-params-test (testing "Given parameters, returns formatted params" (is (= {:zipCodes ["326015125"], :businessName "%MC%DON%", :startDate "2013-01-01", :endDate "2016-11-06", :districtCode nil, :countyNumber nil, :perPage 20, :page 0} (format-params {:zipCodes "326015125", :businessName "*MC*DON*", :startDate "2013-01-01", :endDate "2016-11-06", :districtCode nil, :countyNumber nil, :perPage 20, :page 0})))) (testing "given per page and page number, returns page multiplied by perpage" (is (= {:zipCodes ["326015125"], :businessName "%MC%DON%", :startDate "2013-01-01", :endDate "2016-11-06", :districtCode nil, :countyNumber nil, :perPage 10, :page 20} (format-params {:zipCodes "326015125", :businessName "*MC*DON*", :startDate "2013-01-01", :endDate "2016-11-06", :districtCode nil, :countyNumber nil, :perPage 10, :page 2}))))) (deftest format-inspection-test ;; TODO: test given full results, gets fully correctly formatted object ;; TODO: given empty, returns full object with nulls (let [data inspection-example] (testing "Basic data" (let [json (format-inspection data)] (is (= (:location_city json) "COOPER CITY")) (is (= (:id json) 5807286)) (is (= (:total_violations json) 11)))) (testing "Full data" (let [json (format-inspection data true)] (is (= (:location_city json) "COOPER CITY")) (is (= (count (:violations json)) 8)) (is (= (first (:violations json)) {:id 3, :count 1})) (is (= (:total_violations json) 11))))))
58767
(ns unit.fbi-api.handlers.inspections-test (:require [clojure.test :refer :all] [fbi-api.handlers.inspections :refer :all])) ;; =========================== MOCK DATA =================================== (def mock-ctx {:request {:params {:businessName "<NAME>" :zipCodes "32345" :districtCode "D3" :startDate "2013-02-02" :endDate "2017-02-01" :countyNumber "19" :perPage "1" :page "2"}}}) (def inspection-example {:county_name "Broward", :county_number 16, :location_address "8735 STIRLING RD", :noncritical_violations_before_2013 nil, :license_type_code "2010", :location_city "COOPER CITY", :business_name "FAMILY BAGELS OF LONG ISLAND", :inspection_date #inst "2016-07-07T04:00:00.000-00:00", :pda_status true, :license_number 1621404, :location_zipcode "33328", :critical_violations_before_2013 nil, :high_priority_violations 2, :inspection_visit_id 5807286, :inspection_number 2571280, :basic_violations 4, :license_id "6321820", :inspection_class "Food", :total_violations 11, :inspection_disposition "Inspection Completed - No Further Action", :district "D2", :intermediate_violations 5, :inspection_type "Food-Licensing Inspection", :violations [{:id 3, :count 1} {:id 9, :count 1} {:id 18, :count 1} {:id 23, :count 1} {:id 33, :count 1} {:id 43, :count 1} {:id 53, :count 1} {:id 54, :count 1}]}) ;; ================================ BEGIN TESTS ============================ (deftest processable?-test (testing "Given a request object, returns all params if all true." (is (= (processable? mock-ctx) [true {:valid-params {:zipCodes "32345" :businessName "<NAME>" :startDate "2013-02-02" :endDate "2017-02-01" :countyNumber "19" :districtCode "D3" :perPage 1 :page 2}}]))) (testing "json error for county if county is invalid" (is (= [false {:errors-map {:errors [{:code 1, :title "Validation Error", :detail "Invalid format or value for parameter.", :source {:parameter "countyNumber"}}]}, :params {:zipCodes "32345", :businessName "<NAME>", :startDate "2013-02-02", :endDate "2017-02-01", :districtCode "D3", :perPage 1, :page 2}}] (processable? (assoc-in mock-ctx [:request :params :countyNumber] "38h3fh__"))))) (testing "json error for district if district is invalid" (is (= [false {:errors-map {:errors [{:code 1, :title "Validation Error", :detail "Invalid format or value for parameter.", :source {:parameter "districtCode"}}]}, :params {:zipCodes "32345", :businessName "<NAME>", :startDate "2013-02-02", :endDate "2017-02-01", :countyNumber "19", :perPage 1, :page 2}}] (processable? (assoc-in mock-ctx [:request :params :districtCode] "D9999"))))) (testing "json error for date if date is invalid" (is (= [false {:errors-map {:errors [{:code 1, :title "Validation Error", :detail "Invalid format or value for parameter.", :source {:parameter "startDate"}}]}, :params {:zipCodes "32345", :businessName "<NAME>", :endDate "2017-02-01", :districtCode "D3", :countyNumber "19", :perPage 1, :page 2}}] (processable? (assoc-in mock-ctx [:request :params :startDate] "2015-03-a0"))))) (testing "json error for zipCodes if zipCode is invalid" (is (= [false {:errors-map {:errors [{:code 1, :title "Validation Error", :detail "Invalid format or value for parameter.", :source {:parameter "zipCodes"}}]}, :params {:businessName "<NAME>", :startDate "2013-02-02", :endDate "2017-02-01", :districtCode "D3", :countyNumber "19", :perPage 1, :page 2}}] (processable? (assoc-in mock-ctx [:request :params :zipCodes] "33136,33435,0")))))) (deftest validate-inspections-params-test (testing "Given query params input, returns valid and invalid format/values." (is (= {:invalid {:startDate false} :valid {:zipCodes "33137,22345" :businessName "<NAME>" :endDate "2015-03-03" :districtCode nil :countyNumber nil :perPage 1 :page 2}} (validate-inspections-params {:zipCodes "33137,22345" :businessName "<NAME>" :startDate "2013-aa-22" :endDate "2015-03-03" :districtCode nil :countyNumber nil :perPage "1" :page "2"}))))) (deftest handle-unprocessable-test (testing "properly returns correct error object given a ctx")) (deftest format-params-test (testing "Given parameters, returns formatted params" (is (= {:zipCodes ["326015125"], :businessName "%MC%DON%", :startDate "2013-01-01", :endDate "2016-11-06", :districtCode nil, :countyNumber nil, :perPage 20, :page 0} (format-params {:zipCodes "326015125", :businessName "*MC*DON*", :startDate "2013-01-01", :endDate "2016-11-06", :districtCode nil, :countyNumber nil, :perPage 20, :page 0})))) (testing "given per page and page number, returns page multiplied by perpage" (is (= {:zipCodes ["326015125"], :businessName "%MC%DON%", :startDate "2013-01-01", :endDate "2016-11-06", :districtCode nil, :countyNumber nil, :perPage 10, :page 20} (format-params {:zipCodes "326015125", :businessName "*MC*DON*", :startDate "2013-01-01", :endDate "2016-11-06", :districtCode nil, :countyNumber nil, :perPage 10, :page 2}))))) (deftest format-inspection-test ;; TODO: test given full results, gets fully correctly formatted object ;; TODO: given empty, returns full object with nulls (let [data inspection-example] (testing "Basic data" (let [json (format-inspection data)] (is (= (:location_city json) "COOPER CITY")) (is (= (:id json) 5807286)) (is (= (:total_violations json) 11)))) (testing "Full data" (let [json (format-inspection data true)] (is (= (:location_city json) "COOPER CITY")) (is (= (count (:violations json)) 8)) (is (= (first (:violations json)) {:id 3, :count 1})) (is (= (:total_violations json) 11))))))
true
(ns unit.fbi-api.handlers.inspections-test (:require [clojure.test :refer :all] [fbi-api.handlers.inspections :refer :all])) ;; =========================== MOCK DATA =================================== (def mock-ctx {:request {:params {:businessName "PI:NAME:<NAME>END_PI" :zipCodes "32345" :districtCode "D3" :startDate "2013-02-02" :endDate "2017-02-01" :countyNumber "19" :perPage "1" :page "2"}}}) (def inspection-example {:county_name "Broward", :county_number 16, :location_address "8735 STIRLING RD", :noncritical_violations_before_2013 nil, :license_type_code "2010", :location_city "COOPER CITY", :business_name "FAMILY BAGELS OF LONG ISLAND", :inspection_date #inst "2016-07-07T04:00:00.000-00:00", :pda_status true, :license_number 1621404, :location_zipcode "33328", :critical_violations_before_2013 nil, :high_priority_violations 2, :inspection_visit_id 5807286, :inspection_number 2571280, :basic_violations 4, :license_id "6321820", :inspection_class "Food", :total_violations 11, :inspection_disposition "Inspection Completed - No Further Action", :district "D2", :intermediate_violations 5, :inspection_type "Food-Licensing Inspection", :violations [{:id 3, :count 1} {:id 9, :count 1} {:id 18, :count 1} {:id 23, :count 1} {:id 33, :count 1} {:id 43, :count 1} {:id 53, :count 1} {:id 54, :count 1}]}) ;; ================================ BEGIN TESTS ============================ (deftest processable?-test (testing "Given a request object, returns all params if all true." (is (= (processable? mock-ctx) [true {:valid-params {:zipCodes "32345" :businessName "PI:NAME:<NAME>END_PI" :startDate "2013-02-02" :endDate "2017-02-01" :countyNumber "19" :districtCode "D3" :perPage 1 :page 2}}]))) (testing "json error for county if county is invalid" (is (= [false {:errors-map {:errors [{:code 1, :title "Validation Error", :detail "Invalid format or value for parameter.", :source {:parameter "countyNumber"}}]}, :params {:zipCodes "32345", :businessName "PI:NAME:<NAME>END_PI", :startDate "2013-02-02", :endDate "2017-02-01", :districtCode "D3", :perPage 1, :page 2}}] (processable? (assoc-in mock-ctx [:request :params :countyNumber] "38h3fh__"))))) (testing "json error for district if district is invalid" (is (= [false {:errors-map {:errors [{:code 1, :title "Validation Error", :detail "Invalid format or value for parameter.", :source {:parameter "districtCode"}}]}, :params {:zipCodes "32345", :businessName "PI:NAME:<NAME>END_PI", :startDate "2013-02-02", :endDate "2017-02-01", :countyNumber "19", :perPage 1, :page 2}}] (processable? (assoc-in mock-ctx [:request :params :districtCode] "D9999"))))) (testing "json error for date if date is invalid" (is (= [false {:errors-map {:errors [{:code 1, :title "Validation Error", :detail "Invalid format or value for parameter.", :source {:parameter "startDate"}}]}, :params {:zipCodes "32345", :businessName "PI:NAME:<NAME>END_PI", :endDate "2017-02-01", :districtCode "D3", :countyNumber "19", :perPage 1, :page 2}}] (processable? (assoc-in mock-ctx [:request :params :startDate] "2015-03-a0"))))) (testing "json error for zipCodes if zipCode is invalid" (is (= [false {:errors-map {:errors [{:code 1, :title "Validation Error", :detail "Invalid format or value for parameter.", :source {:parameter "zipCodes"}}]}, :params {:businessName "PI:NAME:<NAME>END_PI", :startDate "2013-02-02", :endDate "2017-02-01", :districtCode "D3", :countyNumber "19", :perPage 1, :page 2}}] (processable? (assoc-in mock-ctx [:request :params :zipCodes] "33136,33435,0")))))) (deftest validate-inspections-params-test (testing "Given query params input, returns valid and invalid format/values." (is (= {:invalid {:startDate false} :valid {:zipCodes "33137,22345" :businessName "PI:NAME:<NAME>END_PI" :endDate "2015-03-03" :districtCode nil :countyNumber nil :perPage 1 :page 2}} (validate-inspections-params {:zipCodes "33137,22345" :businessName "PI:NAME:<NAME>END_PI" :startDate "2013-aa-22" :endDate "2015-03-03" :districtCode nil :countyNumber nil :perPage "1" :page "2"}))))) (deftest handle-unprocessable-test (testing "properly returns correct error object given a ctx")) (deftest format-params-test (testing "Given parameters, returns formatted params" (is (= {:zipCodes ["326015125"], :businessName "%MC%DON%", :startDate "2013-01-01", :endDate "2016-11-06", :districtCode nil, :countyNumber nil, :perPage 20, :page 0} (format-params {:zipCodes "326015125", :businessName "*MC*DON*", :startDate "2013-01-01", :endDate "2016-11-06", :districtCode nil, :countyNumber nil, :perPage 20, :page 0})))) (testing "given per page and page number, returns page multiplied by perpage" (is (= {:zipCodes ["326015125"], :businessName "%MC%DON%", :startDate "2013-01-01", :endDate "2016-11-06", :districtCode nil, :countyNumber nil, :perPage 10, :page 20} (format-params {:zipCodes "326015125", :businessName "*MC*DON*", :startDate "2013-01-01", :endDate "2016-11-06", :districtCode nil, :countyNumber nil, :perPage 10, :page 2}))))) (deftest format-inspection-test ;; TODO: test given full results, gets fully correctly formatted object ;; TODO: given empty, returns full object with nulls (let [data inspection-example] (testing "Basic data" (let [json (format-inspection data)] (is (= (:location_city json) "COOPER CITY")) (is (= (:id json) 5807286)) (is (= (:total_violations json) 11)))) (testing "Full data" (let [json (format-inspection data true)] (is (= (:location_city json) "COOPER CITY")) (is (= (count (:violations json)) 8)) (is (= (first (:violations json)) {:id 3, :count 1})) (is (= (:total_violations json) 11))))))
[ { "context": "(def person\n {:first-name \"Kelly\"\n :last-name \"Keen\"\n :age 32\n :occupation \"", "end": 33, "score": 0.9997334480285645, "start": 28, "tag": "NAME", "value": "Kelly" }, { "context": "(def person\n {:first-name \"Kelly\"\n :last-name \"Keen\"\n :age 32\n :occupation \"Programmer\"})\n(printl", "end": 54, "score": 0.999738335609436, "start": 50, "tag": "NAME", "value": "Keen" } ]
clojure/maps_again.clj
scorphus/sparring
2
(def person {:first-name "Kelly" :last-name "Keen" :age 32 :occupation "Programmer"}) (println person) (println (keys person)) (println (vals person)) (println (get person :occupation)) (println (person :occupation)) (println (:occupation person)) (println (:favorite-color person "green")) (def person (assoc person :occupation "Pro Cyclist")) (def person (dissoc person :age)) (println person) (def company {:name "WidgetCo" :address {:street "123 Main St" :city "Springfield" :state "IL"}}) (println company) (println (get-in company [:address :city])) (def company (assoc-in company [:address :street] "303 Broadway")) (def company (assoc-in company [:address :country] "USA")) (println company)
36633
(def person {:first-name "<NAME>" :last-name "<NAME>" :age 32 :occupation "Programmer"}) (println person) (println (keys person)) (println (vals person)) (println (get person :occupation)) (println (person :occupation)) (println (:occupation person)) (println (:favorite-color person "green")) (def person (assoc person :occupation "Pro Cyclist")) (def person (dissoc person :age)) (println person) (def company {:name "WidgetCo" :address {:street "123 Main St" :city "Springfield" :state "IL"}}) (println company) (println (get-in company [:address :city])) (def company (assoc-in company [:address :street] "303 Broadway")) (def company (assoc-in company [:address :country] "USA")) (println company)
true
(def person {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age 32 :occupation "Programmer"}) (println person) (println (keys person)) (println (vals person)) (println (get person :occupation)) (println (person :occupation)) (println (:occupation person)) (println (:favorite-color person "green")) (def person (assoc person :occupation "Pro Cyclist")) (def person (dissoc person :age)) (println person) (def company {:name "WidgetCo" :address {:street "123 Main St" :city "Springfield" :state "IL"}}) (println company) (println (get-in company [:address :city])) (def company (assoc-in company [:address :street] "303 Broadway")) (def company (assoc-in company [:address :country] "USA")) (println company)
[ { "context": "-and-exit 1)))\n {:host (env :pdb-test-db-host \"127.0.0.1\")\n :port (env :pdb-test-db-port 5432)\n :u", "end": 1205, "score": 0.9997338056564331, "start": 1196, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "ort (env :pdb-test-db-port 5432)\n :user {:name user\n :password (env :pdb-test-db-user-pass", "end": 1270, "score": 0.9653491377830505, "start": 1266, "tag": "USERNAME", "value": "user" }, { "context": " :password (env :pdb-test-db-user-password \"pdb_test\")}\n :admin {:name admin\n :passwor", "end": 1334, "score": 0.9909974932670593, "start": 1326, "tag": "PASSWORD", "value": "pdb_test" }, { "context": " :password (env :pdb-test-db-admin-password \"pdb_test_admin\")}}))\n\n(def sample-db-config\n {:classname \"org.p", "end": 1434, "score": 0.9961155652999878, "start": 1420, "tag": "PASSWORD", "value": "pdb_test_admin" }, { "context": "stgresql\"\n :subname (env :puppetdb-dbsubname \"//127.0.0.1:5432/foo\")\n :user \"puppetdb\"\n :password \"xyzz", "end": 1580, "score": 0.9995577335357666, "start": 1571, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": ".0.1:5432/foo\")\n :user \"puppetdb\"\n :password \"xyzzy\"})\n\n(defn db-admin-config\n ([] (db-admin-config ", "end": 1631, "score": 0.9994314312934875, "start": 1626, "tag": "PASSWORD", "value": "xyzzy" } ]
test/puppetlabs/puppetdb/testutils/db.clj
senior/puppetdb
0
(ns puppetlabs.puppetdb.testutils.db (:require [clojure.java.jdbc :as sql] [clojure.string :as str] [environ.core :refer [env]] [puppetlabs.kitchensink.core :as kitchensink] [puppetlabs.puppetdb.config :as conf] [puppetlabs.puppetdb.jdbc :as jdbc] [puppetlabs.puppetdb.scf.migrate :refer [migrate!]] [puppetlabs.puppetdb.scf.storage-utils :as sutils] [puppetlabs.puppetdb.schema :refer [transform-data]] [puppetlabs.puppetdb.testutils :refer [pprint-str]] [puppetlabs.puppetdb.utils :refer [flush-and-exit]])) (defn valid-sql-id? [id] (re-matches #"[a-zA-Z][a-zA-Z0-9_]*" id)) (def test-env (let [user (env :pdb-test-db-user (env :puppetdb-dbuser "pdb_test")) admin (env :pdb-test-db-admin "pdb_test_admin")] ;; Since we're going to use these in raw SQL later (i.e. not via ?). (doseq [[who name] [[:user user] [:admin admin]]] (when-not (valid-sql-id? name) (binding [*out* *err*] (println (format "Invalid test %s name %s" who (pr-str name))) (flush)) (flush-and-exit 1))) {:host (env :pdb-test-db-host "127.0.0.1") :port (env :pdb-test-db-port 5432) :user {:name user :password (env :pdb-test-db-user-password "pdb_test")} :admin {:name admin :password (env :pdb-test-db-admin-password "pdb_test_admin")}})) (def sample-db-config {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname (env :puppetdb-dbsubname "//127.0.0.1:5432/foo") :user "puppetdb" :password "xyzzy"}) (defn db-admin-config ([] (db-admin-config "postgres")) ([database] {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname (format "//%s:%s/%s" (:host test-env) (:port test-env) database) :user (get-in test-env [:admin :name]) :password (get-in test-env [:admin :password])})) (defn db-user-config [database] {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname (format "//%s:%s/%s" (:host test-env) (:port test-env) database) :user (get-in test-env [:user :name]) :password (get-in test-env [:user :password])}) (defn subname->validated-db-name [subname] (let [sep (.lastIndexOf subname "/")] (assert (pos? sep)) (let [name (subs subname (inc sep))] (assert (valid-sql-id? name)) name))) (defn init-db [db read-only?] (jdbc/with-db-connection db (migrate! db)) (jdbc/pooled-datasource (assoc db :read-only? read-only?))) (defn drop-table! "Drops a table from the database. Expects to be called from within a db binding. Exercise extreme caution when calling this function!" [table-name] (jdbc/do-commands (format "DROP TABLE IF EXISTS %s CASCADE" table-name))) (defn drop-sequence! "Drops a sequence from the database. Expects to be called from within a db binding. Exercise extreme caution when calling this function!" [sequence-name] (jdbc/do-commands (format "DROP SEQUENCE IF EXISTS %s" sequence-name))) (defn drop-function! "Drops a function from the database. Expects to be called from within a db binding. Exercise extreme caution when calling this function!" [function-name] (jdbc/do-commands (format "DROP FUNCTION IF EXISTS %s CASCADE" function-name))) (defn clear-db-for-testing! "Completely clears the database specified by config (or the current database), dropping all puppetdb tables and other objects that exist within it. Expects to be called from within a db binding. You Exercise extreme caution when calling this function!" ([config] (jdbc/with-db-connection config (clear-db-for-testing!))) ([] (jdbc/do-commands "DROP SCHEMA IF EXISTS pdbtestschema CASCADE") (doseq [table-name (cons "test" (sutils/sql-current-connection-table-names))] (drop-table! table-name)) (doseq [sequence-name (cons "test" (sutils/sql-current-connection-sequence-names))] (drop-sequence! sequence-name)) (doseq [function-name (sutils/sql-current-connection-function-names)] (drop-function! function-name)))) (def ^:private pdb-test-id (env :pdb-test-id)) (def ^:private template-name (if pdb-test-id (let [name (str "pdb_test_" pdb-test-id "_template")] (assert (valid-sql-id? name)) name) "pdb_test_template")) (def ^:private template-created (atom false)) (defn- ensure-pdb-db-templates-exist [] (locking ensure-pdb-db-templates-exist (when-not @template-created (assert (valid-sql-id? template-name)) (.addShutdownHook (Runtime/getRuntime) (Thread. #(jdbc/with-db-connection (db-admin-config) (jdbc/do-commands-outside-txn (format "drop database if exists %s" template-name))))) (jdbc/with-db-connection (db-admin-config) (jdbc/do-commands-outside-txn (format "drop database if exists %s" template-name) (format "create database %s" template-name))) (jdbc/with-db-connection (db-admin-config template-name) (jdbc/do-commands-outside-txn "create extension if not exists pg_trgm" "create extension if not exists pgcrypto")) (let [cfg (db-user-config template-name)] (jdbc/with-db-connection cfg (migrate! cfg))) (reset! template-created true)))) (def ^:private test-db-counter (atom 0)) (defn create-temp-db [] "Creates a temporary test database. Prefer with-test-db, etc." (ensure-pdb-db-templates-exist) (let [n (swap! test-db-counter inc) db-name (if-not pdb-test-id (str "pdb_test_" n) (str "pdb_test_" pdb-test-id "_" n))] (assert (valid-sql-id? db-name)) (jdbc/with-db-connection (db-admin-config) (jdbc/do-commands-outside-txn (format "drop database if exists %s" db-name) (format "create database %s template %s" db-name template-name))) (db-user-config db-name))) (def ^:dynamic *db* nil) (defn- disconnect-db-user [db user] "Forcibly disconnects all connections from the specified user to the named db. Requires that the current DB session has sufficient authorization." (jdbc/query-to-vec [(str "select pg_terminate_backend (pg_stat_activity.pid)" " from pg_stat_activity" " where pg_stat_activity.datname = ?" " and pg_stat_activity.usename = ?") db user])) (defn- drop-test-db [db-config] (let [db-name (subname->validated-db-name (:subname db-config))] (jdbc/with-db-connection (db-admin-config) (jdbc/do-commands (format "alter database \"%s\" with connection limit 0" db-name))) (let [config (db-user-config "postgres")] (jdbc/with-db-connection config ;; We'll need this until we can upgrade bonecp (0.8.0 ;; appears to fix the problem). (disconnect-db-user db-name (:user config)))) (jdbc/with-db-connection (db-admin-config) (jdbc/do-commands-outside-txn (format "drop database if exists %s" db-name))))) (def preserve-test-db-on-failure (boolean (re-matches #"yes|true|1" (env :pdb-test-keep-db-on-fail "")))) (defn call-with-db-info-on-failure-or-drop "Calls (f), and then if there are no clojure.tests failures or errors, drops the database, otherwise displays its subname." [db-config f] (let [before (some-> clojure.test/*report-counters* deref)] (try (f) (finally (if-not preserve-test-db-on-failure (drop-test-db db-config) (let [after (some-> clojure.test/*report-counters* deref)] (if (and (= (:error before) (:error after)) (= (:fail before) (:fail after))) (drop-test-db db-config) (clojure.test/with-test-out (println "Leaving test database intact:" (:subname *db*)))))))))) (defmacro with-db-info-on-failure-or-drop "Evaluates body in the context of call-with-db-info-on-failure-or-drop." [db-config & body] `(call-with-db-info-on-failure-or-drop ~db-config (fn [] ~@body))) (defn call-with-test-db "Binds *db* to a clean, migrated test database, opens a connection to it, and calls (f). If there are no clojure.tests failures or errors, drops the database, otherwise displays its subname." [f] (binding [*db* (create-temp-db)] (with-db-info-on-failure-or-drop *db* (jdbc/with-db-connection *db* (with-redefs [sutils/db-metadata (delay (sutils/db-metadata-fn))] (f)))))) (defmacro with-test-db [& body] `(call-with-test-db (fn [] ~@body))) (defn call-with-test-dbs [n f] "Calls (f db-config ...) with n db-config arguments, each representing a database created and protected by with-test-db." (if (pos? n) (with-test-db (call-with-test-dbs (dec n) (partial f *db*))) (f))) (defn without-db-var "Binds the java.jdbc dtabase connection to nil. When running a unit test using `call-with-test-db`, jint/*db* will be bound. If the routes being tested don't explicitly bind the db connection, it will use one bound in call-with-test-db. This causes a problem at runtime that won't show up in the unit tests. This fixture can be used around route testing code to ensure that the route has it's own db connection." [f] (binding [jdbc/*db* nil] (f))) (defn defaulted-write-db-config "Defaults and converts `db-config` from the write database INI format to the internal write database format" [db-config] (transform-data conf/write-database-config-in conf/write-database-config-out db-config)) (defn defaulted-read-db-config "Defaults and converts `db-config` from the read-database INI format to the internal read database format" [db-config] (transform-data conf/database-config-in conf/database-config-out db-config)) (def antonym-data {"absence" "presence" "abundant" "scarce" "accept" "refuse" "accurate" "inaccurate" "admit" "deny" "advance" "retreat" "advantage" "disadvantage" "alive" "dead" "always" "never" "ancient" "modern" "answer" "question" "approval" "disapproval" "arrival" "departure" "artificial" "natural" "ascend" "descend" "blandness" "zest" "lethargy" "zest"}) (defn insert-entries [m] (jdbc/insert-multi! :test [:key :value] (seq m))) (defn call-with-antonym-test-database [function] (with-test-db (jdbc/with-db-transaction [] (jdbc/do-commands (sql/create-table-ddl :test [[:key "VARCHAR(256)" "PRIMARY KEY"] [:value "VARCHAR(256)" "NOT NULL"]])) (insert-entries antonym-data)) (function))) (def indexes-sql "SELECT U.usename AS user, ns.nspname AS schema, idx.indrelid :: REGCLASS AS table, i.relname AS index, idx.indisunique AS is_unique, idx.indisprimary AS is_primary, am.amname AS type, ARRAY( SELECT pg_get_indexdef(idx.indexrelid, k + 1, TRUE) FROM generate_subscripts(idx.indkey, 1) AS k ORDER BY k ) AS index_keys, (idx.indexprs IS NOT NULL) OR (idx.indkey::int[] @> array[0]) AS is_functional, idx.indpred IS NOT NULL AS is_partial FROM pg_index AS idx JOIN pg_class AS i ON i.oid = idx.indexrelid JOIN pg_am AS am ON i.relam = am.oid JOIN pg_namespace AS NS ON i.relnamespace = NS.OID JOIN pg_user AS U ON i.relowner = U.usesysid WHERE NOT nspname LIKE 'pg%';") (defn db->index-map "Converts the metadata columns from their database names/formats to something more natural to use in Clojure" [row] (-> row (update :table #(.getValue %)) (clojure.set/rename-keys {:is_unique :unique? :is_functional :functional? :is_primary :primary?}))) (defn query-indexes "Returns the list of all PuppetDB created indexes, sorted by table, then the name of the index" [db] (jdbc/with-db-connection db (let [indexes (sort-by (juxt :table :index_keys) (map db->index-map (jdbc/query-to-vec indexes-sql)))] (kitchensink/mapvals first (group-by (juxt :table :index_keys) indexes))))) (def table-column-sql "SELECT c.table_name, c.column_name, c.column_default, c.is_nullable, c.data_type, c.datetime_precision, c.numeric_precision, c.numeric_precision_radix, c.numeric_scale, c.character_maximum_length, c.character_octet_length FROM information_schema.tables t inner join information_schema.columns c on t.table_name = c.table_name where t.table_schema = 'public';") (defn db->table-map "Converts the metadata column names to something more natural in Clojure" [row] (clojure.set/rename-keys row {:is_nullable :nullable?})) (defn query-tables "Return a map, keyed by [<table-name> <column-name>] that contains each PuppetDB created table+column in the database" [db] (jdbc/with-db-connection db (let [tables (sort-by (juxt :table_name :column_name) (map db->table-map (jdbc/query-to-vec table-column-sql)))] (kitchensink/mapvals first (group-by (juxt :table_name :column_name) tables))))) (defn schema-info-map [db-props] {:indexes (query-indexes db-props) :tables (query-tables db-props)}) (defn diff' [left right] (let [[left-only right-only same] (clojure.data/diff left right)] (when (or left-only right-only) {:left-only left-only :right-only right-only :same same}))) (defn diff-schema-data [left right] (->> (concat (keys left) (keys right)) (into (sorted-set)) (keep (fn [data-map-key] (diff' (get left data-map-key) (get right data-map-key)))))) (defn diff-schema-maps [left right] (let [index-diff (diff-schema-data (:indexes left) (:indexes right)) table-diffs (diff-schema-data (:tables left) (:tables right))] {:index-diff (seq index-diff) :table-diff (seq table-diffs)})) (defn output-table-diffs [diff-list] (str/join "\n\n------------------------------\n\n" (map (fn [{:keys [left-only right-only same]}] (str "Left Only:\n" (pprint-str left-only) "\nRight Only:\n" (pprint-str right-only) "\nSame:\n" (pprint-str same))) diff-list)))
18257
(ns puppetlabs.puppetdb.testutils.db (:require [clojure.java.jdbc :as sql] [clojure.string :as str] [environ.core :refer [env]] [puppetlabs.kitchensink.core :as kitchensink] [puppetlabs.puppetdb.config :as conf] [puppetlabs.puppetdb.jdbc :as jdbc] [puppetlabs.puppetdb.scf.migrate :refer [migrate!]] [puppetlabs.puppetdb.scf.storage-utils :as sutils] [puppetlabs.puppetdb.schema :refer [transform-data]] [puppetlabs.puppetdb.testutils :refer [pprint-str]] [puppetlabs.puppetdb.utils :refer [flush-and-exit]])) (defn valid-sql-id? [id] (re-matches #"[a-zA-Z][a-zA-Z0-9_]*" id)) (def test-env (let [user (env :pdb-test-db-user (env :puppetdb-dbuser "pdb_test")) admin (env :pdb-test-db-admin "pdb_test_admin")] ;; Since we're going to use these in raw SQL later (i.e. not via ?). (doseq [[who name] [[:user user] [:admin admin]]] (when-not (valid-sql-id? name) (binding [*out* *err*] (println (format "Invalid test %s name %s" who (pr-str name))) (flush)) (flush-and-exit 1))) {:host (env :pdb-test-db-host "127.0.0.1") :port (env :pdb-test-db-port 5432) :user {:name user :password (env :pdb-test-db-user-password "<PASSWORD>")} :admin {:name admin :password (env :pdb-test-db-admin-password "<PASSWORD>")}})) (def sample-db-config {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname (env :puppetdb-dbsubname "//127.0.0.1:5432/foo") :user "puppetdb" :password "<PASSWORD>"}) (defn db-admin-config ([] (db-admin-config "postgres")) ([database] {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname (format "//%s:%s/%s" (:host test-env) (:port test-env) database) :user (get-in test-env [:admin :name]) :password (get-in test-env [:admin :password])})) (defn db-user-config [database] {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname (format "//%s:%s/%s" (:host test-env) (:port test-env) database) :user (get-in test-env [:user :name]) :password (get-in test-env [:user :password])}) (defn subname->validated-db-name [subname] (let [sep (.lastIndexOf subname "/")] (assert (pos? sep)) (let [name (subs subname (inc sep))] (assert (valid-sql-id? name)) name))) (defn init-db [db read-only?] (jdbc/with-db-connection db (migrate! db)) (jdbc/pooled-datasource (assoc db :read-only? read-only?))) (defn drop-table! "Drops a table from the database. Expects to be called from within a db binding. Exercise extreme caution when calling this function!" [table-name] (jdbc/do-commands (format "DROP TABLE IF EXISTS %s CASCADE" table-name))) (defn drop-sequence! "Drops a sequence from the database. Expects to be called from within a db binding. Exercise extreme caution when calling this function!" [sequence-name] (jdbc/do-commands (format "DROP SEQUENCE IF EXISTS %s" sequence-name))) (defn drop-function! "Drops a function from the database. Expects to be called from within a db binding. Exercise extreme caution when calling this function!" [function-name] (jdbc/do-commands (format "DROP FUNCTION IF EXISTS %s CASCADE" function-name))) (defn clear-db-for-testing! "Completely clears the database specified by config (or the current database), dropping all puppetdb tables and other objects that exist within it. Expects to be called from within a db binding. You Exercise extreme caution when calling this function!" ([config] (jdbc/with-db-connection config (clear-db-for-testing!))) ([] (jdbc/do-commands "DROP SCHEMA IF EXISTS pdbtestschema CASCADE") (doseq [table-name (cons "test" (sutils/sql-current-connection-table-names))] (drop-table! table-name)) (doseq [sequence-name (cons "test" (sutils/sql-current-connection-sequence-names))] (drop-sequence! sequence-name)) (doseq [function-name (sutils/sql-current-connection-function-names)] (drop-function! function-name)))) (def ^:private pdb-test-id (env :pdb-test-id)) (def ^:private template-name (if pdb-test-id (let [name (str "pdb_test_" pdb-test-id "_template")] (assert (valid-sql-id? name)) name) "pdb_test_template")) (def ^:private template-created (atom false)) (defn- ensure-pdb-db-templates-exist [] (locking ensure-pdb-db-templates-exist (when-not @template-created (assert (valid-sql-id? template-name)) (.addShutdownHook (Runtime/getRuntime) (Thread. #(jdbc/with-db-connection (db-admin-config) (jdbc/do-commands-outside-txn (format "drop database if exists %s" template-name))))) (jdbc/with-db-connection (db-admin-config) (jdbc/do-commands-outside-txn (format "drop database if exists %s" template-name) (format "create database %s" template-name))) (jdbc/with-db-connection (db-admin-config template-name) (jdbc/do-commands-outside-txn "create extension if not exists pg_trgm" "create extension if not exists pgcrypto")) (let [cfg (db-user-config template-name)] (jdbc/with-db-connection cfg (migrate! cfg))) (reset! template-created true)))) (def ^:private test-db-counter (atom 0)) (defn create-temp-db [] "Creates a temporary test database. Prefer with-test-db, etc." (ensure-pdb-db-templates-exist) (let [n (swap! test-db-counter inc) db-name (if-not pdb-test-id (str "pdb_test_" n) (str "pdb_test_" pdb-test-id "_" n))] (assert (valid-sql-id? db-name)) (jdbc/with-db-connection (db-admin-config) (jdbc/do-commands-outside-txn (format "drop database if exists %s" db-name) (format "create database %s template %s" db-name template-name))) (db-user-config db-name))) (def ^:dynamic *db* nil) (defn- disconnect-db-user [db user] "Forcibly disconnects all connections from the specified user to the named db. Requires that the current DB session has sufficient authorization." (jdbc/query-to-vec [(str "select pg_terminate_backend (pg_stat_activity.pid)" " from pg_stat_activity" " where pg_stat_activity.datname = ?" " and pg_stat_activity.usename = ?") db user])) (defn- drop-test-db [db-config] (let [db-name (subname->validated-db-name (:subname db-config))] (jdbc/with-db-connection (db-admin-config) (jdbc/do-commands (format "alter database \"%s\" with connection limit 0" db-name))) (let [config (db-user-config "postgres")] (jdbc/with-db-connection config ;; We'll need this until we can upgrade bonecp (0.8.0 ;; appears to fix the problem). (disconnect-db-user db-name (:user config)))) (jdbc/with-db-connection (db-admin-config) (jdbc/do-commands-outside-txn (format "drop database if exists %s" db-name))))) (def preserve-test-db-on-failure (boolean (re-matches #"yes|true|1" (env :pdb-test-keep-db-on-fail "")))) (defn call-with-db-info-on-failure-or-drop "Calls (f), and then if there are no clojure.tests failures or errors, drops the database, otherwise displays its subname." [db-config f] (let [before (some-> clojure.test/*report-counters* deref)] (try (f) (finally (if-not preserve-test-db-on-failure (drop-test-db db-config) (let [after (some-> clojure.test/*report-counters* deref)] (if (and (= (:error before) (:error after)) (= (:fail before) (:fail after))) (drop-test-db db-config) (clojure.test/with-test-out (println "Leaving test database intact:" (:subname *db*)))))))))) (defmacro with-db-info-on-failure-or-drop "Evaluates body in the context of call-with-db-info-on-failure-or-drop." [db-config & body] `(call-with-db-info-on-failure-or-drop ~db-config (fn [] ~@body))) (defn call-with-test-db "Binds *db* to a clean, migrated test database, opens a connection to it, and calls (f). If there are no clojure.tests failures or errors, drops the database, otherwise displays its subname." [f] (binding [*db* (create-temp-db)] (with-db-info-on-failure-or-drop *db* (jdbc/with-db-connection *db* (with-redefs [sutils/db-metadata (delay (sutils/db-metadata-fn))] (f)))))) (defmacro with-test-db [& body] `(call-with-test-db (fn [] ~@body))) (defn call-with-test-dbs [n f] "Calls (f db-config ...) with n db-config arguments, each representing a database created and protected by with-test-db." (if (pos? n) (with-test-db (call-with-test-dbs (dec n) (partial f *db*))) (f))) (defn without-db-var "Binds the java.jdbc dtabase connection to nil. When running a unit test using `call-with-test-db`, jint/*db* will be bound. If the routes being tested don't explicitly bind the db connection, it will use one bound in call-with-test-db. This causes a problem at runtime that won't show up in the unit tests. This fixture can be used around route testing code to ensure that the route has it's own db connection." [f] (binding [jdbc/*db* nil] (f))) (defn defaulted-write-db-config "Defaults and converts `db-config` from the write database INI format to the internal write database format" [db-config] (transform-data conf/write-database-config-in conf/write-database-config-out db-config)) (defn defaulted-read-db-config "Defaults and converts `db-config` from the read-database INI format to the internal read database format" [db-config] (transform-data conf/database-config-in conf/database-config-out db-config)) (def antonym-data {"absence" "presence" "abundant" "scarce" "accept" "refuse" "accurate" "inaccurate" "admit" "deny" "advance" "retreat" "advantage" "disadvantage" "alive" "dead" "always" "never" "ancient" "modern" "answer" "question" "approval" "disapproval" "arrival" "departure" "artificial" "natural" "ascend" "descend" "blandness" "zest" "lethargy" "zest"}) (defn insert-entries [m] (jdbc/insert-multi! :test [:key :value] (seq m))) (defn call-with-antonym-test-database [function] (with-test-db (jdbc/with-db-transaction [] (jdbc/do-commands (sql/create-table-ddl :test [[:key "VARCHAR(256)" "PRIMARY KEY"] [:value "VARCHAR(256)" "NOT NULL"]])) (insert-entries antonym-data)) (function))) (def indexes-sql "SELECT U.usename AS user, ns.nspname AS schema, idx.indrelid :: REGCLASS AS table, i.relname AS index, idx.indisunique AS is_unique, idx.indisprimary AS is_primary, am.amname AS type, ARRAY( SELECT pg_get_indexdef(idx.indexrelid, k + 1, TRUE) FROM generate_subscripts(idx.indkey, 1) AS k ORDER BY k ) AS index_keys, (idx.indexprs IS NOT NULL) OR (idx.indkey::int[] @> array[0]) AS is_functional, idx.indpred IS NOT NULL AS is_partial FROM pg_index AS idx JOIN pg_class AS i ON i.oid = idx.indexrelid JOIN pg_am AS am ON i.relam = am.oid JOIN pg_namespace AS NS ON i.relnamespace = NS.OID JOIN pg_user AS U ON i.relowner = U.usesysid WHERE NOT nspname LIKE 'pg%';") (defn db->index-map "Converts the metadata columns from their database names/formats to something more natural to use in Clojure" [row] (-> row (update :table #(.getValue %)) (clojure.set/rename-keys {:is_unique :unique? :is_functional :functional? :is_primary :primary?}))) (defn query-indexes "Returns the list of all PuppetDB created indexes, sorted by table, then the name of the index" [db] (jdbc/with-db-connection db (let [indexes (sort-by (juxt :table :index_keys) (map db->index-map (jdbc/query-to-vec indexes-sql)))] (kitchensink/mapvals first (group-by (juxt :table :index_keys) indexes))))) (def table-column-sql "SELECT c.table_name, c.column_name, c.column_default, c.is_nullable, c.data_type, c.datetime_precision, c.numeric_precision, c.numeric_precision_radix, c.numeric_scale, c.character_maximum_length, c.character_octet_length FROM information_schema.tables t inner join information_schema.columns c on t.table_name = c.table_name where t.table_schema = 'public';") (defn db->table-map "Converts the metadata column names to something more natural in Clojure" [row] (clojure.set/rename-keys row {:is_nullable :nullable?})) (defn query-tables "Return a map, keyed by [<table-name> <column-name>] that contains each PuppetDB created table+column in the database" [db] (jdbc/with-db-connection db (let [tables (sort-by (juxt :table_name :column_name) (map db->table-map (jdbc/query-to-vec table-column-sql)))] (kitchensink/mapvals first (group-by (juxt :table_name :column_name) tables))))) (defn schema-info-map [db-props] {:indexes (query-indexes db-props) :tables (query-tables db-props)}) (defn diff' [left right] (let [[left-only right-only same] (clojure.data/diff left right)] (when (or left-only right-only) {:left-only left-only :right-only right-only :same same}))) (defn diff-schema-data [left right] (->> (concat (keys left) (keys right)) (into (sorted-set)) (keep (fn [data-map-key] (diff' (get left data-map-key) (get right data-map-key)))))) (defn diff-schema-maps [left right] (let [index-diff (diff-schema-data (:indexes left) (:indexes right)) table-diffs (diff-schema-data (:tables left) (:tables right))] {:index-diff (seq index-diff) :table-diff (seq table-diffs)})) (defn output-table-diffs [diff-list] (str/join "\n\n------------------------------\n\n" (map (fn [{:keys [left-only right-only same]}] (str "Left Only:\n" (pprint-str left-only) "\nRight Only:\n" (pprint-str right-only) "\nSame:\n" (pprint-str same))) diff-list)))
true
(ns puppetlabs.puppetdb.testutils.db (:require [clojure.java.jdbc :as sql] [clojure.string :as str] [environ.core :refer [env]] [puppetlabs.kitchensink.core :as kitchensink] [puppetlabs.puppetdb.config :as conf] [puppetlabs.puppetdb.jdbc :as jdbc] [puppetlabs.puppetdb.scf.migrate :refer [migrate!]] [puppetlabs.puppetdb.scf.storage-utils :as sutils] [puppetlabs.puppetdb.schema :refer [transform-data]] [puppetlabs.puppetdb.testutils :refer [pprint-str]] [puppetlabs.puppetdb.utils :refer [flush-and-exit]])) (defn valid-sql-id? [id] (re-matches #"[a-zA-Z][a-zA-Z0-9_]*" id)) (def test-env (let [user (env :pdb-test-db-user (env :puppetdb-dbuser "pdb_test")) admin (env :pdb-test-db-admin "pdb_test_admin")] ;; Since we're going to use these in raw SQL later (i.e. not via ?). (doseq [[who name] [[:user user] [:admin admin]]] (when-not (valid-sql-id? name) (binding [*out* *err*] (println (format "Invalid test %s name %s" who (pr-str name))) (flush)) (flush-and-exit 1))) {:host (env :pdb-test-db-host "127.0.0.1") :port (env :pdb-test-db-port 5432) :user {:name user :password (env :pdb-test-db-user-password "PI:PASSWORD:<PASSWORD>END_PI")} :admin {:name admin :password (env :pdb-test-db-admin-password "PI:PASSWORD:<PASSWORD>END_PI")}})) (def sample-db-config {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname (env :puppetdb-dbsubname "//127.0.0.1:5432/foo") :user "puppetdb" :password "PI:PASSWORD:<PASSWORD>END_PI"}) (defn db-admin-config ([] (db-admin-config "postgres")) ([database] {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname (format "//%s:%s/%s" (:host test-env) (:port test-env) database) :user (get-in test-env [:admin :name]) :password (get-in test-env [:admin :password])})) (defn db-user-config [database] {:classname "org.postgresql.Driver" :subprotocol "postgresql" :subname (format "//%s:%s/%s" (:host test-env) (:port test-env) database) :user (get-in test-env [:user :name]) :password (get-in test-env [:user :password])}) (defn subname->validated-db-name [subname] (let [sep (.lastIndexOf subname "/")] (assert (pos? sep)) (let [name (subs subname (inc sep))] (assert (valid-sql-id? name)) name))) (defn init-db [db read-only?] (jdbc/with-db-connection db (migrate! db)) (jdbc/pooled-datasource (assoc db :read-only? read-only?))) (defn drop-table! "Drops a table from the database. Expects to be called from within a db binding. Exercise extreme caution when calling this function!" [table-name] (jdbc/do-commands (format "DROP TABLE IF EXISTS %s CASCADE" table-name))) (defn drop-sequence! "Drops a sequence from the database. Expects to be called from within a db binding. Exercise extreme caution when calling this function!" [sequence-name] (jdbc/do-commands (format "DROP SEQUENCE IF EXISTS %s" sequence-name))) (defn drop-function! "Drops a function from the database. Expects to be called from within a db binding. Exercise extreme caution when calling this function!" [function-name] (jdbc/do-commands (format "DROP FUNCTION IF EXISTS %s CASCADE" function-name))) (defn clear-db-for-testing! "Completely clears the database specified by config (or the current database), dropping all puppetdb tables and other objects that exist within it. Expects to be called from within a db binding. You Exercise extreme caution when calling this function!" ([config] (jdbc/with-db-connection config (clear-db-for-testing!))) ([] (jdbc/do-commands "DROP SCHEMA IF EXISTS pdbtestschema CASCADE") (doseq [table-name (cons "test" (sutils/sql-current-connection-table-names))] (drop-table! table-name)) (doseq [sequence-name (cons "test" (sutils/sql-current-connection-sequence-names))] (drop-sequence! sequence-name)) (doseq [function-name (sutils/sql-current-connection-function-names)] (drop-function! function-name)))) (def ^:private pdb-test-id (env :pdb-test-id)) (def ^:private template-name (if pdb-test-id (let [name (str "pdb_test_" pdb-test-id "_template")] (assert (valid-sql-id? name)) name) "pdb_test_template")) (def ^:private template-created (atom false)) (defn- ensure-pdb-db-templates-exist [] (locking ensure-pdb-db-templates-exist (when-not @template-created (assert (valid-sql-id? template-name)) (.addShutdownHook (Runtime/getRuntime) (Thread. #(jdbc/with-db-connection (db-admin-config) (jdbc/do-commands-outside-txn (format "drop database if exists %s" template-name))))) (jdbc/with-db-connection (db-admin-config) (jdbc/do-commands-outside-txn (format "drop database if exists %s" template-name) (format "create database %s" template-name))) (jdbc/with-db-connection (db-admin-config template-name) (jdbc/do-commands-outside-txn "create extension if not exists pg_trgm" "create extension if not exists pgcrypto")) (let [cfg (db-user-config template-name)] (jdbc/with-db-connection cfg (migrate! cfg))) (reset! template-created true)))) (def ^:private test-db-counter (atom 0)) (defn create-temp-db [] "Creates a temporary test database. Prefer with-test-db, etc." (ensure-pdb-db-templates-exist) (let [n (swap! test-db-counter inc) db-name (if-not pdb-test-id (str "pdb_test_" n) (str "pdb_test_" pdb-test-id "_" n))] (assert (valid-sql-id? db-name)) (jdbc/with-db-connection (db-admin-config) (jdbc/do-commands-outside-txn (format "drop database if exists %s" db-name) (format "create database %s template %s" db-name template-name))) (db-user-config db-name))) (def ^:dynamic *db* nil) (defn- disconnect-db-user [db user] "Forcibly disconnects all connections from the specified user to the named db. Requires that the current DB session has sufficient authorization." (jdbc/query-to-vec [(str "select pg_terminate_backend (pg_stat_activity.pid)" " from pg_stat_activity" " where pg_stat_activity.datname = ?" " and pg_stat_activity.usename = ?") db user])) (defn- drop-test-db [db-config] (let [db-name (subname->validated-db-name (:subname db-config))] (jdbc/with-db-connection (db-admin-config) (jdbc/do-commands (format "alter database \"%s\" with connection limit 0" db-name))) (let [config (db-user-config "postgres")] (jdbc/with-db-connection config ;; We'll need this until we can upgrade bonecp (0.8.0 ;; appears to fix the problem). (disconnect-db-user db-name (:user config)))) (jdbc/with-db-connection (db-admin-config) (jdbc/do-commands-outside-txn (format "drop database if exists %s" db-name))))) (def preserve-test-db-on-failure (boolean (re-matches #"yes|true|1" (env :pdb-test-keep-db-on-fail "")))) (defn call-with-db-info-on-failure-or-drop "Calls (f), and then if there are no clojure.tests failures or errors, drops the database, otherwise displays its subname." [db-config f] (let [before (some-> clojure.test/*report-counters* deref)] (try (f) (finally (if-not preserve-test-db-on-failure (drop-test-db db-config) (let [after (some-> clojure.test/*report-counters* deref)] (if (and (= (:error before) (:error after)) (= (:fail before) (:fail after))) (drop-test-db db-config) (clojure.test/with-test-out (println "Leaving test database intact:" (:subname *db*)))))))))) (defmacro with-db-info-on-failure-or-drop "Evaluates body in the context of call-with-db-info-on-failure-or-drop." [db-config & body] `(call-with-db-info-on-failure-or-drop ~db-config (fn [] ~@body))) (defn call-with-test-db "Binds *db* to a clean, migrated test database, opens a connection to it, and calls (f). If there are no clojure.tests failures or errors, drops the database, otherwise displays its subname." [f] (binding [*db* (create-temp-db)] (with-db-info-on-failure-or-drop *db* (jdbc/with-db-connection *db* (with-redefs [sutils/db-metadata (delay (sutils/db-metadata-fn))] (f)))))) (defmacro with-test-db [& body] `(call-with-test-db (fn [] ~@body))) (defn call-with-test-dbs [n f] "Calls (f db-config ...) with n db-config arguments, each representing a database created and protected by with-test-db." (if (pos? n) (with-test-db (call-with-test-dbs (dec n) (partial f *db*))) (f))) (defn without-db-var "Binds the java.jdbc dtabase connection to nil. When running a unit test using `call-with-test-db`, jint/*db* will be bound. If the routes being tested don't explicitly bind the db connection, it will use one bound in call-with-test-db. This causes a problem at runtime that won't show up in the unit tests. This fixture can be used around route testing code to ensure that the route has it's own db connection." [f] (binding [jdbc/*db* nil] (f))) (defn defaulted-write-db-config "Defaults and converts `db-config` from the write database INI format to the internal write database format" [db-config] (transform-data conf/write-database-config-in conf/write-database-config-out db-config)) (defn defaulted-read-db-config "Defaults and converts `db-config` from the read-database INI format to the internal read database format" [db-config] (transform-data conf/database-config-in conf/database-config-out db-config)) (def antonym-data {"absence" "presence" "abundant" "scarce" "accept" "refuse" "accurate" "inaccurate" "admit" "deny" "advance" "retreat" "advantage" "disadvantage" "alive" "dead" "always" "never" "ancient" "modern" "answer" "question" "approval" "disapproval" "arrival" "departure" "artificial" "natural" "ascend" "descend" "blandness" "zest" "lethargy" "zest"}) (defn insert-entries [m] (jdbc/insert-multi! :test [:key :value] (seq m))) (defn call-with-antonym-test-database [function] (with-test-db (jdbc/with-db-transaction [] (jdbc/do-commands (sql/create-table-ddl :test [[:key "VARCHAR(256)" "PRIMARY KEY"] [:value "VARCHAR(256)" "NOT NULL"]])) (insert-entries antonym-data)) (function))) (def indexes-sql "SELECT U.usename AS user, ns.nspname AS schema, idx.indrelid :: REGCLASS AS table, i.relname AS index, idx.indisunique AS is_unique, idx.indisprimary AS is_primary, am.amname AS type, ARRAY( SELECT pg_get_indexdef(idx.indexrelid, k + 1, TRUE) FROM generate_subscripts(idx.indkey, 1) AS k ORDER BY k ) AS index_keys, (idx.indexprs IS NOT NULL) OR (idx.indkey::int[] @> array[0]) AS is_functional, idx.indpred IS NOT NULL AS is_partial FROM pg_index AS idx JOIN pg_class AS i ON i.oid = idx.indexrelid JOIN pg_am AS am ON i.relam = am.oid JOIN pg_namespace AS NS ON i.relnamespace = NS.OID JOIN pg_user AS U ON i.relowner = U.usesysid WHERE NOT nspname LIKE 'pg%';") (defn db->index-map "Converts the metadata columns from their database names/formats to something more natural to use in Clojure" [row] (-> row (update :table #(.getValue %)) (clojure.set/rename-keys {:is_unique :unique? :is_functional :functional? :is_primary :primary?}))) (defn query-indexes "Returns the list of all PuppetDB created indexes, sorted by table, then the name of the index" [db] (jdbc/with-db-connection db (let [indexes (sort-by (juxt :table :index_keys) (map db->index-map (jdbc/query-to-vec indexes-sql)))] (kitchensink/mapvals first (group-by (juxt :table :index_keys) indexes))))) (def table-column-sql "SELECT c.table_name, c.column_name, c.column_default, c.is_nullable, c.data_type, c.datetime_precision, c.numeric_precision, c.numeric_precision_radix, c.numeric_scale, c.character_maximum_length, c.character_octet_length FROM information_schema.tables t inner join information_schema.columns c on t.table_name = c.table_name where t.table_schema = 'public';") (defn db->table-map "Converts the metadata column names to something more natural in Clojure" [row] (clojure.set/rename-keys row {:is_nullable :nullable?})) (defn query-tables "Return a map, keyed by [<table-name> <column-name>] that contains each PuppetDB created table+column in the database" [db] (jdbc/with-db-connection db (let [tables (sort-by (juxt :table_name :column_name) (map db->table-map (jdbc/query-to-vec table-column-sql)))] (kitchensink/mapvals first (group-by (juxt :table_name :column_name) tables))))) (defn schema-info-map [db-props] {:indexes (query-indexes db-props) :tables (query-tables db-props)}) (defn diff' [left right] (let [[left-only right-only same] (clojure.data/diff left right)] (when (or left-only right-only) {:left-only left-only :right-only right-only :same same}))) (defn diff-schema-data [left right] (->> (concat (keys left) (keys right)) (into (sorted-set)) (keep (fn [data-map-key] (diff' (get left data-map-key) (get right data-map-key)))))) (defn diff-schema-maps [left right] (let [index-diff (diff-schema-data (:indexes left) (:indexes right)) table-diffs (diff-schema-data (:tables left) (:tables right))] {:index-diff (seq index-diff) :table-diff (seq table-diffs)})) (defn output-table-diffs [diff-list] (str/join "\n\n------------------------------\n\n" (map (fn [{:keys [left-only right-only same]}] (str "Left Only:\n" (pprint-str left-only) "\nRight Only:\n" (pprint-str right-only) "\nSame:\n" (pprint-str same))) diff-list)))
[ { "context": "g developed for the CLASS Project\n;;\n;; Copyright: Roi Sucasas Font, Atos Research and Innovation, 2018.\n;;\n;; This c", "end": 167, "score": 0.9998156428337097, "start": 151, "tag": "NAME", "value": "Roi Sucasas Font" } ]
clojure old project/src/atos/class/logs/logs.clj
class-rotterdam/Rotterdam
0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; This code is being developed for the CLASS Project ;; ;; Copyright: Roi Sucasas Font, Atos Research and Innovation, 2018. ;; ;; This code is licensed under an Apache 2.0 license. Please, refer to the ;; LICENSE.TXT file for more information ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns atos.class.logs.logs (:require [clojure.tools.logging :as logging] [atos.class.config :as config])) ;; DEFINITION: use to check not nil (def ^:private not-nil? (complement nil?)) ;; FUNCTION: print-log (defn- print-log "prints log content on screen console" [debug-level txt] {:pre [(not-nil? debug-level) (not-nil? txt)]} (cond (= debug-level "DEBUG") (logging/debug txt) (= debug-level "INFO") (logging/info txt) (= debug-level "ERROR") (logging/error txt) (= debug-level "WARNING") (logging/warn txt) :else (logging/trace txt))) ;; FUNCTION: pr-log (defn- pr-log [l-type & txt] (print-log l-type (apply str config/get-log-message txt))) ;; FUNCTION: debug (defn debug [& txt] {:pre [(not-nil? txt)]} (apply pr-log "DEBUG" txt)) ;; FUNCTION: info (defn info [& txt] {:pre [(not-nil? txt)]} (apply pr-log "INFO" txt)) ;; FUNCTION: error (defn error [& txt] {:pre [(not-nil? txt)]} (apply pr-log "ERROR" txt)) ;; FUNCTION: warning (defn warning [& txt] {:pre [(not-nil? txt)]} (apply pr-log "WARNING" txt)) ;; FUNCTION: trace (defn trace [& txt] {:pre [(not-nil? txt)]} (apply pr-log "TRACE" txt)) ;; FUNCTION: create error map (defn get-error-stacktrace [e] (error "> Caught exception: [" (.getMessage e) "], stackTrace: \n " (clojure.string/join "\n " (map str (.getStackTrace e))))) ;; FUNCTION: create-map-error (defn create-map-error "creates a map with Exception info" [e] {:code "ERROR" :message (str "caught exception: " (.getMessage e)) :stacktrace (str "StackTrace: " (clojure.string/join "\n " (map str (.getStackTrace e)))) :response false}) ;; FUNCTION: (defn log-exception "creates a map with Exception info" [e] (error "ERROR: caught exception: " (.getMessage e) "\n stackTrace: " (clojure.string/join "\n " (map str (.getStackTrace e)))))
88547
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; This code is being developed for the CLASS Project ;; ;; Copyright: <NAME>, Atos Research and Innovation, 2018. ;; ;; This code is licensed under an Apache 2.0 license. Please, refer to the ;; LICENSE.TXT file for more information ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns atos.class.logs.logs (:require [clojure.tools.logging :as logging] [atos.class.config :as config])) ;; DEFINITION: use to check not nil (def ^:private not-nil? (complement nil?)) ;; FUNCTION: print-log (defn- print-log "prints log content on screen console" [debug-level txt] {:pre [(not-nil? debug-level) (not-nil? txt)]} (cond (= debug-level "DEBUG") (logging/debug txt) (= debug-level "INFO") (logging/info txt) (= debug-level "ERROR") (logging/error txt) (= debug-level "WARNING") (logging/warn txt) :else (logging/trace txt))) ;; FUNCTION: pr-log (defn- pr-log [l-type & txt] (print-log l-type (apply str config/get-log-message txt))) ;; FUNCTION: debug (defn debug [& txt] {:pre [(not-nil? txt)]} (apply pr-log "DEBUG" txt)) ;; FUNCTION: info (defn info [& txt] {:pre [(not-nil? txt)]} (apply pr-log "INFO" txt)) ;; FUNCTION: error (defn error [& txt] {:pre [(not-nil? txt)]} (apply pr-log "ERROR" txt)) ;; FUNCTION: warning (defn warning [& txt] {:pre [(not-nil? txt)]} (apply pr-log "WARNING" txt)) ;; FUNCTION: trace (defn trace [& txt] {:pre [(not-nil? txt)]} (apply pr-log "TRACE" txt)) ;; FUNCTION: create error map (defn get-error-stacktrace [e] (error "> Caught exception: [" (.getMessage e) "], stackTrace: \n " (clojure.string/join "\n " (map str (.getStackTrace e))))) ;; FUNCTION: create-map-error (defn create-map-error "creates a map with Exception info" [e] {:code "ERROR" :message (str "caught exception: " (.getMessage e)) :stacktrace (str "StackTrace: " (clojure.string/join "\n " (map str (.getStackTrace e)))) :response false}) ;; FUNCTION: (defn log-exception "creates a map with Exception info" [e] (error "ERROR: caught exception: " (.getMessage e) "\n stackTrace: " (clojure.string/join "\n " (map str (.getStackTrace e)))))
true
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; This code is being developed for the CLASS Project ;; ;; Copyright: PI:NAME:<NAME>END_PI, Atos Research and Innovation, 2018. ;; ;; This code is licensed under an Apache 2.0 license. Please, refer to the ;; LICENSE.TXT file for more information ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns atos.class.logs.logs (:require [clojure.tools.logging :as logging] [atos.class.config :as config])) ;; DEFINITION: use to check not nil (def ^:private not-nil? (complement nil?)) ;; FUNCTION: print-log (defn- print-log "prints log content on screen console" [debug-level txt] {:pre [(not-nil? debug-level) (not-nil? txt)]} (cond (= debug-level "DEBUG") (logging/debug txt) (= debug-level "INFO") (logging/info txt) (= debug-level "ERROR") (logging/error txt) (= debug-level "WARNING") (logging/warn txt) :else (logging/trace txt))) ;; FUNCTION: pr-log (defn- pr-log [l-type & txt] (print-log l-type (apply str config/get-log-message txt))) ;; FUNCTION: debug (defn debug [& txt] {:pre [(not-nil? txt)]} (apply pr-log "DEBUG" txt)) ;; FUNCTION: info (defn info [& txt] {:pre [(not-nil? txt)]} (apply pr-log "INFO" txt)) ;; FUNCTION: error (defn error [& txt] {:pre [(not-nil? txt)]} (apply pr-log "ERROR" txt)) ;; FUNCTION: warning (defn warning [& txt] {:pre [(not-nil? txt)]} (apply pr-log "WARNING" txt)) ;; FUNCTION: trace (defn trace [& txt] {:pre [(not-nil? txt)]} (apply pr-log "TRACE" txt)) ;; FUNCTION: create error map (defn get-error-stacktrace [e] (error "> Caught exception: [" (.getMessage e) "], stackTrace: \n " (clojure.string/join "\n " (map str (.getStackTrace e))))) ;; FUNCTION: create-map-error (defn create-map-error "creates a map with Exception info" [e] {:code "ERROR" :message (str "caught exception: " (.getMessage e)) :stacktrace (str "StackTrace: " (clojure.string/join "\n " (map str (.getStackTrace e)))) :response false}) ;; FUNCTION: (defn log-exception "creates a map with Exception info" [e] (error "ERROR: caught exception: " (.getMessage e) "\n stackTrace: " (clojure.string/join "\n " (map str (.getStackTrace e)))))
[ { "context": "; Copyright (c) 2006 Parth Malwankar\n; All rights reserved.\n;\n; A small script to gene", "end": 36, "score": 0.9998952746391296, "start": 21, "tag": "NAME", "value": "Parth Malwankar" }, { "context": "jure's core\n; functions. The script was written by Parth Malwankar. It\n; is included in VimClojure with his permissi", "end": 176, "score": 0.9998990893363953, "start": 161, "tag": "NAME", "value": "Parth Malwankar" }, { "context": " included in VimClojure with his permission.\n; -- Meikel Brandmeyer, 16 August 2008\n; Frankfurt am Main, Germany\n", "end": 253, "score": 0.9998943209648132, "start": 236, "tag": "NAME", "value": "Meikel Brandmeyer" } ]
bin/gen-completions.clj
vivrass/dotvim
0
; Copyright (c) 2006 Parth Malwankar ; All rights reserved. ; ; A small script to generate a dictionary of Clojure's core ; functions. The script was written by Parth Malwankar. It ; is included in VimClojure with his permission. ; -- Meikel Brandmeyer, 16 August 2008 ; Frankfurt am Main, Germany ; ; See also: http://en.wikibooks.org/wiki/Clojure_Programming ; (defmacro with-out-file [pathname & body] `(with-open stream# (new java.io.FileWriter ~pathname) (binding [*out* stream#] ~@body))) (def completions (keys (ns-publics (find-ns 'clojure)))) (with-out-file "clj-keys.txt" (doseq x completions (println x)))
114944
; Copyright (c) 2006 <NAME> ; All rights reserved. ; ; A small script to generate a dictionary of Clojure's core ; functions. The script was written by <NAME>. It ; is included in VimClojure with his permission. ; -- <NAME>, 16 August 2008 ; Frankfurt am Main, Germany ; ; See also: http://en.wikibooks.org/wiki/Clojure_Programming ; (defmacro with-out-file [pathname & body] `(with-open stream# (new java.io.FileWriter ~pathname) (binding [*out* stream#] ~@body))) (def completions (keys (ns-publics (find-ns 'clojure)))) (with-out-file "clj-keys.txt" (doseq x completions (println x)))
true
; Copyright (c) 2006 PI:NAME:<NAME>END_PI ; All rights reserved. ; ; A small script to generate a dictionary of Clojure's core ; functions. The script was written by PI:NAME:<NAME>END_PI. It ; is included in VimClojure with his permission. ; -- PI:NAME:<NAME>END_PI, 16 August 2008 ; Frankfurt am Main, Germany ; ; See also: http://en.wikibooks.org/wiki/Clojure_Programming ; (defmacro with-out-file [pathname & body] `(with-open stream# (new java.io.FileWriter ~pathname) (binding [*out* stream#] ~@body))) (def completions (keys (ns-publics (find-ns 'clojure)))) (with-out-file "clj-keys.txt" (doseq x completions (println x)))
[ { "context": "nder the License.\n;\n; Based on https://github.com/richhickey/clojure/blob/4bea7a529bb14b99d48758cfaf0d71af0997", "end": 619, "score": 0.9989837408065796, "start": 609, "tag": "USERNAME", "value": "richhickey" }, { "context": "lj\n; Original copyright notice\n;\n; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 764, "score": 0.9997003078460693, "start": 753, "tag": "NAME", "value": "Rich Hickey" } ]
src/main/clj/com/climate/shell.clj
aykuznetsova/lemur
21
;Copyright 2012 The Climate Corporation ; ;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. ; ; Based on https://github.com/richhickey/clojure/blob/4bea7a529bb14b99d48758cfaf0d71af0997f0ff/src/clj/clojure/java/shell.clj ; Original copyright notice ; ; 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 com.climate.shell (:use [clojure.java.io :only [as-file copy input-stream output-stream]]) (:import [java.io File InputStreamReader OutputStreamWriter])) (def ^{:dynamic true} *sh-dir* nil) (def ^{:dynamic true} *sh-env* nil) (def ENV (System/getenv)) (defn clj-main-jar "Returns the jar in which clojure.main exists." [] (-> (Class/forName "clojure.main") (.getClassLoader) (.getResource "clojure/main.class") (.getPath) (#(re-find #"file:(.*)!.*" %)) (last))) (defmacro with-sh-dir "Sets the directory for use with sh, see sh for details." {:added "1.2"} [dir & forms] `(binding [*sh-dir* ~dir] ~@forms)) (defmacro with-sh-env "Sets the environment for use with sh, see sh for details." {:added "1.2"} [env & forms] `(binding [*sh-env* ~env] ~@forms)) (defn- stream-seq "Takes an InputStream and returns a lazy seq of integers from the stream." [stream] (take-while #(>= % 0) (repeatedly #(.read stream)))) (defn- aconcat "Concatenates arrays of given type." [type & xs] (let [target (make-array type (apply + (map count xs)))] (loop [i 0 idx 0] (when-let [a (nth xs i nil)] (System/arraycopy a 0 target idx (count a)) (recur (inc i) (+ idx (count a))))) target)) (defn- parse-args [args] (let [default-opts {:out "UTF-8" :dir *sh-dir* :env *sh-env*} [cmd opts] (split-with string? args)] [cmd (merge default-opts (apply hash-map opts))])) (defn merge-env "Takes a map of environment settings and merges them with the SYSTEM ENVIRONMENT. Keys can be strings or keywords." [env] (merge {} ENV env)) (defn- as-env-string "Helper so that callers can pass a Clojure map for the :env to sh." [arg] (cond (nil? arg) nil (map? arg) (into-array String (map (fn [[k v]] (str (name k) "=" v)) arg)) true arg)) (defn- handle-stream "Based on opt, handle the given stream. See the :out option to (sh) for the meaning of opt. In the fn case, the fn should accept one arg, which will be the OutputStream. Run in a thread, and the return value is returned immediately in a future." [opt strm system-stream] (future (cond (= opt :bytes) (into-array Byte/TYPE (map byte (stream-seq strm))) (= opt :pass) (copy strm system-stream) (string? opt) (apply str (map char (stream-seq (InputStreamReader. strm opt)))) (fn? opt) (opt strm) (instance? File opt) (with-open [os (output-stream opt)] (copy strm os)) :default (copy strm opt)))) (defn sh "Passes the given strings to Runtime.exec() to launch a sub-process. Options are :in may be given followed by a String, InputStream or File specifying text to be fed to the sub-process's stdin. Does not close any streams except those it opens itself (on a File). :out may be given followed by :bytes, :pass, a File, a fn or a String. For... - String - it will be used as a character encoding name (for example \"UTF-8\" or \"ISO-8859-1\") to convert the sub-process's stdout to a String which is returned. - :bytes - the sub-process's stdout will be stored in a byte array and returned. - fn - it receives the stdout InputStream as an argument (the stream is closed automatically). The fn is run in a Thread, but sh blocks until the Thread completes. This can be used, for example, to filter the stream. - File - the output is written to the file. - :pass - the sub-process's stdout is passed to the main process stdout. Defaults to \"UTF-8\". :err same options as :out. Defaults to the same value as :out. :env override the process env with a map (or the underlying Java String[] if you are a masochist). :dir override the process dir with a String or java.io.File. You can bind :env or :dir for multiple operations using with-sh-env and with-sh-dir. sh returns a map of :exit => sub-process's exit code :out => sub-process's stdout (as byte[], String or InputStream) :err => sub-process's stderr (as byte[], String or InputStream) " {:added "1.2"} [& args] (let [[cmd opts] (parse-args args) proc (.exec (Runtime/getRuntime) (into-array cmd) (as-env-string (:env opts)) (as-file (:dir opts))) input-future (future (cond (string? (:in opts)) (with-open [osw (OutputStreamWriter. (.getOutputStream proc))] (.write osw (:in opts))) (nil? (:in opts)) (.close (.getOutputStream proc)) (instance? File (:in opts)) (with-open [is (input-stream (:in opts)) os (.getOutputStream proc)] (copy is os)) :default (with-open [os (.getOutputStream proc)] (copy (:in opts) os))))] (with-open [stdout (.getInputStream proc) stderr (.getErrorStream proc)] (let [out (handle-stream (:out opts) stdout System/out) err (handle-stream (get opts :err (:out opts)) stderr System/err) exit-code (.waitFor proc)] ;make sure input is done @input-future {:exit exit-code :out @out :err @err})))) (comment (println (sh "ls" "-l")) (println (sh "ls" "-l" "/no-such-thing")) (println (sh "sed" "s/[aeiou]/oo/g" :in "hello there\n")) (println (sh "cat" :in "x\u25bax\n")) (println (sh "echo" "x\u25bax")) (println (sh "echo" "x\u25bax" :out "ISO-8859-1")) ; reads 4 single-byte chars (println (sh "cat" "myimage.png" :out :bytes)) ; reads binary file into bytes[] (println (sh "cat" :in (as-file "/tmp/input") :out (as-file "/tmp/out") :err :pass)) )
121826
;Copyright 2012 The Climate Corporation ; ;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. ; ; Based on https://github.com/richhickey/clojure/blob/4bea7a529bb14b99d48758cfaf0d71af0997f0ff/src/clj/clojure/java/shell.clj ; Original copyright notice ; ; 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 com.climate.shell (:use [clojure.java.io :only [as-file copy input-stream output-stream]]) (:import [java.io File InputStreamReader OutputStreamWriter])) (def ^{:dynamic true} *sh-dir* nil) (def ^{:dynamic true} *sh-env* nil) (def ENV (System/getenv)) (defn clj-main-jar "Returns the jar in which clojure.main exists." [] (-> (Class/forName "clojure.main") (.getClassLoader) (.getResource "clojure/main.class") (.getPath) (#(re-find #"file:(.*)!.*" %)) (last))) (defmacro with-sh-dir "Sets the directory for use with sh, see sh for details." {:added "1.2"} [dir & forms] `(binding [*sh-dir* ~dir] ~@forms)) (defmacro with-sh-env "Sets the environment for use with sh, see sh for details." {:added "1.2"} [env & forms] `(binding [*sh-env* ~env] ~@forms)) (defn- stream-seq "Takes an InputStream and returns a lazy seq of integers from the stream." [stream] (take-while #(>= % 0) (repeatedly #(.read stream)))) (defn- aconcat "Concatenates arrays of given type." [type & xs] (let [target (make-array type (apply + (map count xs)))] (loop [i 0 idx 0] (when-let [a (nth xs i nil)] (System/arraycopy a 0 target idx (count a)) (recur (inc i) (+ idx (count a))))) target)) (defn- parse-args [args] (let [default-opts {:out "UTF-8" :dir *sh-dir* :env *sh-env*} [cmd opts] (split-with string? args)] [cmd (merge default-opts (apply hash-map opts))])) (defn merge-env "Takes a map of environment settings and merges them with the SYSTEM ENVIRONMENT. Keys can be strings or keywords." [env] (merge {} ENV env)) (defn- as-env-string "Helper so that callers can pass a Clojure map for the :env to sh." [arg] (cond (nil? arg) nil (map? arg) (into-array String (map (fn [[k v]] (str (name k) "=" v)) arg)) true arg)) (defn- handle-stream "Based on opt, handle the given stream. See the :out option to (sh) for the meaning of opt. In the fn case, the fn should accept one arg, which will be the OutputStream. Run in a thread, and the return value is returned immediately in a future." [opt strm system-stream] (future (cond (= opt :bytes) (into-array Byte/TYPE (map byte (stream-seq strm))) (= opt :pass) (copy strm system-stream) (string? opt) (apply str (map char (stream-seq (InputStreamReader. strm opt)))) (fn? opt) (opt strm) (instance? File opt) (with-open [os (output-stream opt)] (copy strm os)) :default (copy strm opt)))) (defn sh "Passes the given strings to Runtime.exec() to launch a sub-process. Options are :in may be given followed by a String, InputStream or File specifying text to be fed to the sub-process's stdin. Does not close any streams except those it opens itself (on a File). :out may be given followed by :bytes, :pass, a File, a fn or a String. For... - String - it will be used as a character encoding name (for example \"UTF-8\" or \"ISO-8859-1\") to convert the sub-process's stdout to a String which is returned. - :bytes - the sub-process's stdout will be stored in a byte array and returned. - fn - it receives the stdout InputStream as an argument (the stream is closed automatically). The fn is run in a Thread, but sh blocks until the Thread completes. This can be used, for example, to filter the stream. - File - the output is written to the file. - :pass - the sub-process's stdout is passed to the main process stdout. Defaults to \"UTF-8\". :err same options as :out. Defaults to the same value as :out. :env override the process env with a map (or the underlying Java String[] if you are a masochist). :dir override the process dir with a String or java.io.File. You can bind :env or :dir for multiple operations using with-sh-env and with-sh-dir. sh returns a map of :exit => sub-process's exit code :out => sub-process's stdout (as byte[], String or InputStream) :err => sub-process's stderr (as byte[], String or InputStream) " {:added "1.2"} [& args] (let [[cmd opts] (parse-args args) proc (.exec (Runtime/getRuntime) (into-array cmd) (as-env-string (:env opts)) (as-file (:dir opts))) input-future (future (cond (string? (:in opts)) (with-open [osw (OutputStreamWriter. (.getOutputStream proc))] (.write osw (:in opts))) (nil? (:in opts)) (.close (.getOutputStream proc)) (instance? File (:in opts)) (with-open [is (input-stream (:in opts)) os (.getOutputStream proc)] (copy is os)) :default (with-open [os (.getOutputStream proc)] (copy (:in opts) os))))] (with-open [stdout (.getInputStream proc) stderr (.getErrorStream proc)] (let [out (handle-stream (:out opts) stdout System/out) err (handle-stream (get opts :err (:out opts)) stderr System/err) exit-code (.waitFor proc)] ;make sure input is done @input-future {:exit exit-code :out @out :err @err})))) (comment (println (sh "ls" "-l")) (println (sh "ls" "-l" "/no-such-thing")) (println (sh "sed" "s/[aeiou]/oo/g" :in "hello there\n")) (println (sh "cat" :in "x\u25bax\n")) (println (sh "echo" "x\u25bax")) (println (sh "echo" "x\u25bax" :out "ISO-8859-1")) ; reads 4 single-byte chars (println (sh "cat" "myimage.png" :out :bytes)) ; reads binary file into bytes[] (println (sh "cat" :in (as-file "/tmp/input") :out (as-file "/tmp/out") :err :pass)) )
true
;Copyright 2012 The Climate Corporation ; ;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. ; ; Based on https://github.com/richhickey/clojure/blob/4bea7a529bb14b99d48758cfaf0d71af0997f0ff/src/clj/clojure/java/shell.clj ; Original copyright notice ; ; 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 com.climate.shell (:use [clojure.java.io :only [as-file copy input-stream output-stream]]) (:import [java.io File InputStreamReader OutputStreamWriter])) (def ^{:dynamic true} *sh-dir* nil) (def ^{:dynamic true} *sh-env* nil) (def ENV (System/getenv)) (defn clj-main-jar "Returns the jar in which clojure.main exists." [] (-> (Class/forName "clojure.main") (.getClassLoader) (.getResource "clojure/main.class") (.getPath) (#(re-find #"file:(.*)!.*" %)) (last))) (defmacro with-sh-dir "Sets the directory for use with sh, see sh for details." {:added "1.2"} [dir & forms] `(binding [*sh-dir* ~dir] ~@forms)) (defmacro with-sh-env "Sets the environment for use with sh, see sh for details." {:added "1.2"} [env & forms] `(binding [*sh-env* ~env] ~@forms)) (defn- stream-seq "Takes an InputStream and returns a lazy seq of integers from the stream." [stream] (take-while #(>= % 0) (repeatedly #(.read stream)))) (defn- aconcat "Concatenates arrays of given type." [type & xs] (let [target (make-array type (apply + (map count xs)))] (loop [i 0 idx 0] (when-let [a (nth xs i nil)] (System/arraycopy a 0 target idx (count a)) (recur (inc i) (+ idx (count a))))) target)) (defn- parse-args [args] (let [default-opts {:out "UTF-8" :dir *sh-dir* :env *sh-env*} [cmd opts] (split-with string? args)] [cmd (merge default-opts (apply hash-map opts))])) (defn merge-env "Takes a map of environment settings and merges them with the SYSTEM ENVIRONMENT. Keys can be strings or keywords." [env] (merge {} ENV env)) (defn- as-env-string "Helper so that callers can pass a Clojure map for the :env to sh." [arg] (cond (nil? arg) nil (map? arg) (into-array String (map (fn [[k v]] (str (name k) "=" v)) arg)) true arg)) (defn- handle-stream "Based on opt, handle the given stream. See the :out option to (sh) for the meaning of opt. In the fn case, the fn should accept one arg, which will be the OutputStream. Run in a thread, and the return value is returned immediately in a future." [opt strm system-stream] (future (cond (= opt :bytes) (into-array Byte/TYPE (map byte (stream-seq strm))) (= opt :pass) (copy strm system-stream) (string? opt) (apply str (map char (stream-seq (InputStreamReader. strm opt)))) (fn? opt) (opt strm) (instance? File opt) (with-open [os (output-stream opt)] (copy strm os)) :default (copy strm opt)))) (defn sh "Passes the given strings to Runtime.exec() to launch a sub-process. Options are :in may be given followed by a String, InputStream or File specifying text to be fed to the sub-process's stdin. Does not close any streams except those it opens itself (on a File). :out may be given followed by :bytes, :pass, a File, a fn or a String. For... - String - it will be used as a character encoding name (for example \"UTF-8\" or \"ISO-8859-1\") to convert the sub-process's stdout to a String which is returned. - :bytes - the sub-process's stdout will be stored in a byte array and returned. - fn - it receives the stdout InputStream as an argument (the stream is closed automatically). The fn is run in a Thread, but sh blocks until the Thread completes. This can be used, for example, to filter the stream. - File - the output is written to the file. - :pass - the sub-process's stdout is passed to the main process stdout. Defaults to \"UTF-8\". :err same options as :out. Defaults to the same value as :out. :env override the process env with a map (or the underlying Java String[] if you are a masochist). :dir override the process dir with a String or java.io.File. You can bind :env or :dir for multiple operations using with-sh-env and with-sh-dir. sh returns a map of :exit => sub-process's exit code :out => sub-process's stdout (as byte[], String or InputStream) :err => sub-process's stderr (as byte[], String or InputStream) " {:added "1.2"} [& args] (let [[cmd opts] (parse-args args) proc (.exec (Runtime/getRuntime) (into-array cmd) (as-env-string (:env opts)) (as-file (:dir opts))) input-future (future (cond (string? (:in opts)) (with-open [osw (OutputStreamWriter. (.getOutputStream proc))] (.write osw (:in opts))) (nil? (:in opts)) (.close (.getOutputStream proc)) (instance? File (:in opts)) (with-open [is (input-stream (:in opts)) os (.getOutputStream proc)] (copy is os)) :default (with-open [os (.getOutputStream proc)] (copy (:in opts) os))))] (with-open [stdout (.getInputStream proc) stderr (.getErrorStream proc)] (let [out (handle-stream (:out opts) stdout System/out) err (handle-stream (get opts :err (:out opts)) stderr System/err) exit-code (.waitFor proc)] ;make sure input is done @input-future {:exit exit-code :out @out :err @err})))) (comment (println (sh "ls" "-l")) (println (sh "ls" "-l" "/no-such-thing")) (println (sh "sed" "s/[aeiou]/oo/g" :in "hello there\n")) (println (sh "cat" :in "x\u25bax\n")) (println (sh "echo" "x\u25bax")) (println (sh "echo" "x\u25bax" :out "ISO-8859-1")) ; reads 4 single-byte chars (println (sh "cat" "myimage.png" :out :bytes)) ; reads binary file into bytes[] (println (sh "cat" :in (as-file "/tmp/input") :out (as-file "/tmp/out") :err :pass)) )
[ { "context": "name :winner_rating :loser_rating]))]\n (is (= \"Roger Federer\" (:winner_name (first history))))\n (is (= \"Gui", "end": 845, "score": 0.9998364448547363, "start": 832, "tag": "NAME", "value": "Roger Federer" }, { "context": "rer\" (:winner_name (first history))))\n (is (= \"Guido Pella\" (:loser_name (first history))))\n (is (= \"Marc", "end": 903, "score": 0.9998545050621033, "start": 892, "tag": "NAME", "value": "Guido Pella" }, { "context": "ella\" (:loser_name (first history))))\n (is (= \"Marcus Willis\" (:loser_name (ffirst (second history)))))\n (i", "end": 962, "score": 0.999849259853363, "start": 949, "tag": "NAME", "value": "Marcus Willis" }, { "context": "ser_name (ffirst (second history)))))\n (is (= \"Daniel Evans\" (:loser_name (ffirst (second (first (second hist", "end": 1030, "score": 0.9998505115509033, "start": 1018, "tag": "NAME", "value": "Daniel Evans" } ]
Chapter07/tests/packt-clj.chapter-7-tests/test/packt_clj/chapter_7_tests/activity_7_01_test.clj
transducer/The-Clojure-Workshop
55
(ns packt-clj.chapter-7-tests.activity-7-01-test (:require [packt-clj.chapter-7-tests.activity-7-01 :as act] [clojure.test :as t :refer [deftest is testing]] [clojure.java.io :as io] [packt-clj.chapter-7-tests.exercise-7-05 :as exo] [packt-clj.chapter-7-tests.exercise-7-03 :as exo-three])) (def matches (exo-three/elo-db (io/file (io/resource "match_scores_1991-2016_unindexed_csv.csv")) 35)) (def federer (exo-three/match-tree-by-player matches "roger-federer")) (deftest focus-history (let [history (act/focus-history federer "roger-federer" 4 2 #(select-keys % [:winner_name :loser_name :winner_rating :loser_rating]))] (is (= "Roger Federer" (:winner_name (first history)))) (is (= "Guido Pella" (:loser_name (first history)))) (is (= "Marcus Willis" (:loser_name (ffirst (second history))))) (is (= "Daniel Evans" (:loser_name (ffirst (second (first (second history)))))))))
30180
(ns packt-clj.chapter-7-tests.activity-7-01-test (:require [packt-clj.chapter-7-tests.activity-7-01 :as act] [clojure.test :as t :refer [deftest is testing]] [clojure.java.io :as io] [packt-clj.chapter-7-tests.exercise-7-05 :as exo] [packt-clj.chapter-7-tests.exercise-7-03 :as exo-three])) (def matches (exo-three/elo-db (io/file (io/resource "match_scores_1991-2016_unindexed_csv.csv")) 35)) (def federer (exo-three/match-tree-by-player matches "roger-federer")) (deftest focus-history (let [history (act/focus-history federer "roger-federer" 4 2 #(select-keys % [:winner_name :loser_name :winner_rating :loser_rating]))] (is (= "<NAME>" (:winner_name (first history)))) (is (= "<NAME>" (:loser_name (first history)))) (is (= "<NAME>" (:loser_name (ffirst (second history))))) (is (= "<NAME>" (:loser_name (ffirst (second (first (second history)))))))))
true
(ns packt-clj.chapter-7-tests.activity-7-01-test (:require [packt-clj.chapter-7-tests.activity-7-01 :as act] [clojure.test :as t :refer [deftest is testing]] [clojure.java.io :as io] [packt-clj.chapter-7-tests.exercise-7-05 :as exo] [packt-clj.chapter-7-tests.exercise-7-03 :as exo-three])) (def matches (exo-three/elo-db (io/file (io/resource "match_scores_1991-2016_unindexed_csv.csv")) 35)) (def federer (exo-three/match-tree-by-player matches "roger-federer")) (deftest focus-history (let [history (act/focus-history federer "roger-federer" 4 2 #(select-keys % [:winner_name :loser_name :winner_rating :loser_rating]))] (is (= "PI:NAME:<NAME>END_PI" (:winner_name (first history)))) (is (= "PI:NAME:<NAME>END_PI" (:loser_name (first history)))) (is (= "PI:NAME:<NAME>END_PI" (:loser_name (ffirst (second history))))) (is (= "PI:NAME:<NAME>END_PI" (:loser_name (ffirst (second (first (second history)))))))))
[ { "context": "\"\n (is (= \"base-url-195241/Observation?__token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA&__t=195312\"\n @(nav/token-url page-store", "end": 5451, "score": 0.9637441635131836, "start": 5419, "tag": "KEY", "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" }, { "context": "\"\n (is (= \"base-url-195241/Observation?__token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB&__t=195312\"\n @(nav/token-url\n ", "end": 5670, "score": 0.965183436870575, "start": 5638, "tag": "KEY", "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB" }, { "context": "tion?__token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB&__t=195312\"\n @(nav/token-url\n (reify ", "end": 5681, "score": 0.9269733428955078, "start": 5675, "tag": "PASSWORD", "value": "195312" }, { "context": " \"base-url-195241\" match\n {:token \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB\"}\n clauses-1\n 195312\n ", "end": 5899, "score": 0.969143807888031, "start": 5867, "tag": "KEY", "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB" } ]
modules/interaction/test/blaze/interaction/search/nav_test.clj
samply/blaze
50
(ns blaze.interaction.search.nav-test (:require [blaze.async.comp :as ac] [blaze.interaction.search.nav :as nav] [blaze.interaction.search.nav-spec] [blaze.page-store.protocols :as p] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [deftest is testing]] [cuerdas.core :as str])) (st/instrument) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def match {:data {:blaze/base-url "" :fhir.resource/type "Observation"} :path "/Observation"}) (deftest url-test (testing "url encoding of clauses" (testing "Observation code with URL" (is (= "base-url-110407/Observation?code=http%3A%2F%2Floinc.org%7C8480-6&__t=1" (nav/url "base-url-110407" match nil [["code" "http://loinc.org|8480-6"]] 1 nil))))) (testing "two clauses with the same code" (is (= "base-url-110421/Observation?combo-code-value-quantity=8480-6%24ge140&combo-code-value-quantity=8462-4%24ge90&__t=1" (nav/url "base-url-110421" match nil [["combo-code-value-quantity" "8480-6$ge140"] ["combo-code-value-quantity" "8462-4$ge90"]] 1 nil)))) (testing "with include-defs" (testing "empty" (is (= "base-url-110439/Observation?__t=1" (nav/url "base-url-110439" match {:include-defs {:direct {} :iterate {}}} nil 1 nil)))) (testing "one direct forward include param" (is (= "base-url-110542/Observation?_include=Observation%3Asubject&__t=1" (nav/url "base-url-110542" match {:include-defs {:direct {:forward {"Observation" [{:code "subject"}]}}}} nil 1 nil))) (testing "with target type" (is (= "base-url-110553/Observation?_include=Observation%3Asubject%3AGroup&__t=1" (nav/url "base-url-110553" match {:include-defs {:direct {:forward {"Observation" [{:code "subject" :target-type "Group"}]}}}} nil 1 nil))))) (testing "two direct forward include params" (is (= "base-url-110604/Observation?_include=MedicationStatement%3Amedication&_include=Medication%3Amanufacturer&__t=1" (nav/url "base-url-110604" match {:include-defs {:direct {:forward {"MedicationStatement" [{:code "medication"}] "Medication" [{:code "manufacturer"}]}}}} nil 1 nil)))) (testing "one iterate forward include param" (is (= "base-url-110614/Observation?_include%3Aiterate=Observation%3Asubject&__t=1" (nav/url "base-url-110614" match {:include-defs {:iterate {:forward {"Observation" [{:code "subject"}]}}}} nil 1 nil)))) (testing "one direct and one iterate forward include param" (is (= "base-url-110624/Observation?_include=MedicationStatement%3Amedication&_include%3Aiterate=Medication%3Amanufacturer&__t=1" (nav/url "base-url-110624" match {:include-defs {:direct {:forward {"MedicationStatement" [{:code "medication"}]}} :iterate {:forward {"Medication" [{:code "manufacturer"}]}}}} nil 1 nil)))) (testing "one direct reverse include param" (is (= "base-url-110635/Observation?_revinclude=Observation%3Asubject&__t=1" (nav/url "base-url-110635" match {:include-defs {:direct {:reverse {:any [{:source-type "Observation" :code "subject"}]}}}} nil 1 nil))) (testing "with target type" (is (= "base-url-110645/Observation?_revinclude=Observation%3Asubject%3AGroup&__t=1" (nav/url "base-url-110645" match {:include-defs {:direct {:reverse {"Group" [{:source-type "Observation" :code "subject"}]}}}} nil 1 nil))))) (testing "one iterate reverse include param" (is (= "base-url-110654/Observation?_revinclude%3Aiterate=Observation%3Asubject&__t=1" (nav/url "base-url-110654" match {:include-defs {:iterate {:reverse {:any [{:source-type "Observation" :code "subject"}]}}}} nil 1 nil)))))) (def clauses-1 [["foo" "bar"]]) (def page-store (reify p/PageStore (-put [_ clauses] (assert (= clauses-1 clauses)) (ac/completed-future (str/repeat "A" 32))))) (deftest token-url-test (testing "stores clauses and puts token into the query params" (is (= "base-url-195241/Observation?__token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA&__t=195312" @(nav/token-url page-store "base-url-195241" match {} clauses-1 195312 nil)))) (testing "reuses existing token" (is (= "base-url-195241/Observation?__token=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB&__t=195312" @(nav/token-url (reify p/PageStore (-put [_ _] (assert false))) "base-url-195241" match {:token "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB"} clauses-1 195312 nil)))))
41445
(ns blaze.interaction.search.nav-test (:require [blaze.async.comp :as ac] [blaze.interaction.search.nav :as nav] [blaze.interaction.search.nav-spec] [blaze.page-store.protocols :as p] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [deftest is testing]] [cuerdas.core :as str])) (st/instrument) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def match {:data {:blaze/base-url "" :fhir.resource/type "Observation"} :path "/Observation"}) (deftest url-test (testing "url encoding of clauses" (testing "Observation code with URL" (is (= "base-url-110407/Observation?code=http%3A%2F%2Floinc.org%7C8480-6&__t=1" (nav/url "base-url-110407" match nil [["code" "http://loinc.org|8480-6"]] 1 nil))))) (testing "two clauses with the same code" (is (= "base-url-110421/Observation?combo-code-value-quantity=8480-6%24ge140&combo-code-value-quantity=8462-4%24ge90&__t=1" (nav/url "base-url-110421" match nil [["combo-code-value-quantity" "8480-6$ge140"] ["combo-code-value-quantity" "8462-4$ge90"]] 1 nil)))) (testing "with include-defs" (testing "empty" (is (= "base-url-110439/Observation?__t=1" (nav/url "base-url-110439" match {:include-defs {:direct {} :iterate {}}} nil 1 nil)))) (testing "one direct forward include param" (is (= "base-url-110542/Observation?_include=Observation%3Asubject&__t=1" (nav/url "base-url-110542" match {:include-defs {:direct {:forward {"Observation" [{:code "subject"}]}}}} nil 1 nil))) (testing "with target type" (is (= "base-url-110553/Observation?_include=Observation%3Asubject%3AGroup&__t=1" (nav/url "base-url-110553" match {:include-defs {:direct {:forward {"Observation" [{:code "subject" :target-type "Group"}]}}}} nil 1 nil))))) (testing "two direct forward include params" (is (= "base-url-110604/Observation?_include=MedicationStatement%3Amedication&_include=Medication%3Amanufacturer&__t=1" (nav/url "base-url-110604" match {:include-defs {:direct {:forward {"MedicationStatement" [{:code "medication"}] "Medication" [{:code "manufacturer"}]}}}} nil 1 nil)))) (testing "one iterate forward include param" (is (= "base-url-110614/Observation?_include%3Aiterate=Observation%3Asubject&__t=1" (nav/url "base-url-110614" match {:include-defs {:iterate {:forward {"Observation" [{:code "subject"}]}}}} nil 1 nil)))) (testing "one direct and one iterate forward include param" (is (= "base-url-110624/Observation?_include=MedicationStatement%3Amedication&_include%3Aiterate=Medication%3Amanufacturer&__t=1" (nav/url "base-url-110624" match {:include-defs {:direct {:forward {"MedicationStatement" [{:code "medication"}]}} :iterate {:forward {"Medication" [{:code "manufacturer"}]}}}} nil 1 nil)))) (testing "one direct reverse include param" (is (= "base-url-110635/Observation?_revinclude=Observation%3Asubject&__t=1" (nav/url "base-url-110635" match {:include-defs {:direct {:reverse {:any [{:source-type "Observation" :code "subject"}]}}}} nil 1 nil))) (testing "with target type" (is (= "base-url-110645/Observation?_revinclude=Observation%3Asubject%3AGroup&__t=1" (nav/url "base-url-110645" match {:include-defs {:direct {:reverse {"Group" [{:source-type "Observation" :code "subject"}]}}}} nil 1 nil))))) (testing "one iterate reverse include param" (is (= "base-url-110654/Observation?_revinclude%3Aiterate=Observation%3Asubject&__t=1" (nav/url "base-url-110654" match {:include-defs {:iterate {:reverse {:any [{:source-type "Observation" :code "subject"}]}}}} nil 1 nil)))))) (def clauses-1 [["foo" "bar"]]) (def page-store (reify p/PageStore (-put [_ clauses] (assert (= clauses-1 clauses)) (ac/completed-future (str/repeat "A" 32))))) (deftest token-url-test (testing "stores clauses and puts token into the query params" (is (= "base-url-195241/Observation?__token=<KEY>&__t=195312" @(nav/token-url page-store "base-url-195241" match {} clauses-1 195312 nil)))) (testing "reuses existing token" (is (= "base-url-195241/Observation?__token=<KEY>&__t=<PASSWORD>" @(nav/token-url (reify p/PageStore (-put [_ _] (assert false))) "base-url-195241" match {:token "<KEY>"} clauses-1 195312 nil)))))
true
(ns blaze.interaction.search.nav-test (:require [blaze.async.comp :as ac] [blaze.interaction.search.nav :as nav] [blaze.interaction.search.nav-spec] [blaze.page-store.protocols :as p] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [deftest is testing]] [cuerdas.core :as str])) (st/instrument) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def match {:data {:blaze/base-url "" :fhir.resource/type "Observation"} :path "/Observation"}) (deftest url-test (testing "url encoding of clauses" (testing "Observation code with URL" (is (= "base-url-110407/Observation?code=http%3A%2F%2Floinc.org%7C8480-6&__t=1" (nav/url "base-url-110407" match nil [["code" "http://loinc.org|8480-6"]] 1 nil))))) (testing "two clauses with the same code" (is (= "base-url-110421/Observation?combo-code-value-quantity=8480-6%24ge140&combo-code-value-quantity=8462-4%24ge90&__t=1" (nav/url "base-url-110421" match nil [["combo-code-value-quantity" "8480-6$ge140"] ["combo-code-value-quantity" "8462-4$ge90"]] 1 nil)))) (testing "with include-defs" (testing "empty" (is (= "base-url-110439/Observation?__t=1" (nav/url "base-url-110439" match {:include-defs {:direct {} :iterate {}}} nil 1 nil)))) (testing "one direct forward include param" (is (= "base-url-110542/Observation?_include=Observation%3Asubject&__t=1" (nav/url "base-url-110542" match {:include-defs {:direct {:forward {"Observation" [{:code "subject"}]}}}} nil 1 nil))) (testing "with target type" (is (= "base-url-110553/Observation?_include=Observation%3Asubject%3AGroup&__t=1" (nav/url "base-url-110553" match {:include-defs {:direct {:forward {"Observation" [{:code "subject" :target-type "Group"}]}}}} nil 1 nil))))) (testing "two direct forward include params" (is (= "base-url-110604/Observation?_include=MedicationStatement%3Amedication&_include=Medication%3Amanufacturer&__t=1" (nav/url "base-url-110604" match {:include-defs {:direct {:forward {"MedicationStatement" [{:code "medication"}] "Medication" [{:code "manufacturer"}]}}}} nil 1 nil)))) (testing "one iterate forward include param" (is (= "base-url-110614/Observation?_include%3Aiterate=Observation%3Asubject&__t=1" (nav/url "base-url-110614" match {:include-defs {:iterate {:forward {"Observation" [{:code "subject"}]}}}} nil 1 nil)))) (testing "one direct and one iterate forward include param" (is (= "base-url-110624/Observation?_include=MedicationStatement%3Amedication&_include%3Aiterate=Medication%3Amanufacturer&__t=1" (nav/url "base-url-110624" match {:include-defs {:direct {:forward {"MedicationStatement" [{:code "medication"}]}} :iterate {:forward {"Medication" [{:code "manufacturer"}]}}}} nil 1 nil)))) (testing "one direct reverse include param" (is (= "base-url-110635/Observation?_revinclude=Observation%3Asubject&__t=1" (nav/url "base-url-110635" match {:include-defs {:direct {:reverse {:any [{:source-type "Observation" :code "subject"}]}}}} nil 1 nil))) (testing "with target type" (is (= "base-url-110645/Observation?_revinclude=Observation%3Asubject%3AGroup&__t=1" (nav/url "base-url-110645" match {:include-defs {:direct {:reverse {"Group" [{:source-type "Observation" :code "subject"}]}}}} nil 1 nil))))) (testing "one iterate reverse include param" (is (= "base-url-110654/Observation?_revinclude%3Aiterate=Observation%3Asubject&__t=1" (nav/url "base-url-110654" match {:include-defs {:iterate {:reverse {:any [{:source-type "Observation" :code "subject"}]}}}} nil 1 nil)))))) (def clauses-1 [["foo" "bar"]]) (def page-store (reify p/PageStore (-put [_ clauses] (assert (= clauses-1 clauses)) (ac/completed-future (str/repeat "A" 32))))) (deftest token-url-test (testing "stores clauses and puts token into the query params" (is (= "base-url-195241/Observation?__token=PI:KEY:<KEY>END_PI&__t=195312" @(nav/token-url page-store "base-url-195241" match {} clauses-1 195312 nil)))) (testing "reuses existing token" (is (= "base-url-195241/Observation?__token=PI:KEY:<KEY>END_PI&__t=PI:PASSWORD:<PASSWORD>END_PI" @(nav/token-url (reify p/PageStore (-put [_ _] (assert false))) "base-url-195241" match {:token "PI:KEY:<KEY>END_PI"} clauses-1 195312 nil)))))
[ { "context": "(ns\n ^{:author \"Zach Tellman\"\n :doc \"This namespace contains methods for co", "end": 29, "score": 0.9997984766960144, "start": 17, "tag": "NAME", "value": "Zach Tellman" } ]
src/manifold/time.clj
benmoss/manifold
0
(ns ^{:author "Zach Tellman" :doc "This namespace contains methods for converting units of time, with milliseconds as the base representation, and for deferring execution of functions to some time in the future. In practice, the methods here are not necessary to use Manifold effectively - `manifold.deferred/timeout` and `manifold.stream/periodically` are more directly useful - but they are available for anyone who should need them."} manifold.time (:require [manifold.utils :as utils] [clojure.string :as str]) (:import [java.util Calendar TimeZone] [java.util.concurrent Future Executor Executors TimeUnit ScheduledThreadPoolExecutor TimeoutException])) (defn nanoseconds "Converts nanoseconds -> milliseconds" [n] (/ n 1e6)) (defn microseconds "Converts microseconds -> milliseconds" [n] (/ n 1e3)) (defn milliseconds "Converts milliseconds -> milliseconds" [n] n) (defn seconds "Converts seconds -> milliseconds" [n] (* n 1e3)) (defn minutes "Converts minutes -> milliseconds" [n] (* n 6e4)) (defn hours "Converts hours -> milliseconds" [n] (* n 36e5)) (defn days "Converts days -> milliseconds" [n] (* n 864e5)) (defn hz "Converts frequency -> period in milliseconds" [n] (/ 1e3 n)) (let [intervals (partition 2 ["d" (days 1) "h" (hours 1) "m" (minutes 1) "s" (seconds 1)])] (defn format-duration "Takes a duration in milliseconds, and returns a formatted string describing the interval, i.e. '5d 3h 1m'" [n] (loop [s "", n n, intervals intervals] (if (empty? intervals) (if (empty? s) "0s" (str/trim s)) (let [[desc val] (first intervals)] (if (>= n val) (recur (str s (int (/ n val)) desc " ") (rem n val) (rest intervals)) (recur s n (rest intervals)))))))) (let [sorted-units [:millisecond Calendar/MILLISECOND :second Calendar/SECOND :minute Calendar/MINUTE :hour Calendar/HOUR :day Calendar/DAY_OF_YEAR :week Calendar/WEEK_OF_MONTH :month Calendar/MONTH] unit->calendar-unit (apply hash-map sorted-units) units (->> sorted-units (partition 2) (map first)) unit->cleared-fields (zipmap units (map #(->> (take % units) (map unit->calendar-unit)) (range (count units))))] (defn floor "Takes a `timestamp`, and rounds it down to the nearest even multiple of the `unit`. (floor 1001 :second) => 1000 (floor (seconds 61) :minute) => 60000 " [timestamp unit] (assert (contains? unit->calendar-unit unit)) (let [^Calendar cal (doto (Calendar/getInstance (TimeZone/getTimeZone "UTC")) (.setTimeInMillis timestamp))] (doseq [field (unit->cleared-fields unit)] (.set cal field 0)) (.getTimeInMillis cal))) (defn add "Takes a `timestamp`, and adds `value` multiples of `unit` to the value." [timestamp value unit] (assert (contains? unit->calendar-unit unit)) (let [^Calendar cal (doto (Calendar/getInstance (TimeZone/getTimeZone "UTC")) (.setTimeInMillis timestamp))] (.add cal (unit->calendar-unit unit) value) (.getTimeInMillis cal)))) ;;; (in-ns 'manifold.deferred) (clojure.core/declare success! error! deferred) (in-ns 'manifold.time) ;;; (let [scheduler (delay (ScheduledThreadPoolExecutor. 1 (utils/thread-factory (constantly "manifold-scheduler-queue")))) num-cores (.availableProcessors (Runtime/getRuntime)) cnt (atom 0) executor (delay (Executors/newFixedThreadPool num-cores (utils/thread-factory #(str "manifold-scheduler-" (swap! cnt inc)))))] (defn in "Schedules no-arg function `f` to be invoked in `interval` milliseconds. Returns a deferred representing the returned value of the function." [^double interval f] (let [d (manifold.deferred/deferred) f (fn [] (let [f (fn [] (try (manifold.deferred/success! d (f)) (catch Throwable e (manifold.deferred/error! d e))))] (.execute ^Executor @executor ^Runnable f)))] (.schedule ^ScheduledThreadPoolExecutor @scheduler ^Runnable f (long (* interval 1e3)) TimeUnit/MICROSECONDS) d)) (defn every "Schedules no-arg function `f` to be invoked every `period` milliseconds, after `initial-delay` milliseconds, which defaults to `0`. Returns a zero-argument function which, when invoked, cancels the repeated invocation. If the invocation of `f` ever throws an exception, repeated invocation is automatically cancelled." ([period f] (every period 0 f)) ([period initial-delay f] (let [future-ref (promise) f (fn [] (try (f) (catch Throwable e (let [^Future future @future-ref] (.cancel future false)) (throw e))))] (deliver future-ref (.scheduleAtFixedRate ^ScheduledThreadPoolExecutor @scheduler ^Runnable (fn [] (.execute ^Executor @executor ^Runnable f)) (long (* initial-delay 1e3)) (long (* period 1e3)) TimeUnit/MICROSECONDS)) (fn [] (let [^Future future @future-ref] (.cancel future false))))))) (defn at "Schedules no-arg function `f` to be invoked at `timestamp`, which is the milliseconds since the epoch. Returns a deferred representing the returned value of the function." [timestamp f] (in (max 0 (- timestamp (System/currentTimeMillis))) f))
122547
(ns ^{:author "<NAME>" :doc "This namespace contains methods for converting units of time, with milliseconds as the base representation, and for deferring execution of functions to some time in the future. In practice, the methods here are not necessary to use Manifold effectively - `manifold.deferred/timeout` and `manifold.stream/periodically` are more directly useful - but they are available for anyone who should need them."} manifold.time (:require [manifold.utils :as utils] [clojure.string :as str]) (:import [java.util Calendar TimeZone] [java.util.concurrent Future Executor Executors TimeUnit ScheduledThreadPoolExecutor TimeoutException])) (defn nanoseconds "Converts nanoseconds -> milliseconds" [n] (/ n 1e6)) (defn microseconds "Converts microseconds -> milliseconds" [n] (/ n 1e3)) (defn milliseconds "Converts milliseconds -> milliseconds" [n] n) (defn seconds "Converts seconds -> milliseconds" [n] (* n 1e3)) (defn minutes "Converts minutes -> milliseconds" [n] (* n 6e4)) (defn hours "Converts hours -> milliseconds" [n] (* n 36e5)) (defn days "Converts days -> milliseconds" [n] (* n 864e5)) (defn hz "Converts frequency -> period in milliseconds" [n] (/ 1e3 n)) (let [intervals (partition 2 ["d" (days 1) "h" (hours 1) "m" (minutes 1) "s" (seconds 1)])] (defn format-duration "Takes a duration in milliseconds, and returns a formatted string describing the interval, i.e. '5d 3h 1m'" [n] (loop [s "", n n, intervals intervals] (if (empty? intervals) (if (empty? s) "0s" (str/trim s)) (let [[desc val] (first intervals)] (if (>= n val) (recur (str s (int (/ n val)) desc " ") (rem n val) (rest intervals)) (recur s n (rest intervals)))))))) (let [sorted-units [:millisecond Calendar/MILLISECOND :second Calendar/SECOND :minute Calendar/MINUTE :hour Calendar/HOUR :day Calendar/DAY_OF_YEAR :week Calendar/WEEK_OF_MONTH :month Calendar/MONTH] unit->calendar-unit (apply hash-map sorted-units) units (->> sorted-units (partition 2) (map first)) unit->cleared-fields (zipmap units (map #(->> (take % units) (map unit->calendar-unit)) (range (count units))))] (defn floor "Takes a `timestamp`, and rounds it down to the nearest even multiple of the `unit`. (floor 1001 :second) => 1000 (floor (seconds 61) :minute) => 60000 " [timestamp unit] (assert (contains? unit->calendar-unit unit)) (let [^Calendar cal (doto (Calendar/getInstance (TimeZone/getTimeZone "UTC")) (.setTimeInMillis timestamp))] (doseq [field (unit->cleared-fields unit)] (.set cal field 0)) (.getTimeInMillis cal))) (defn add "Takes a `timestamp`, and adds `value` multiples of `unit` to the value." [timestamp value unit] (assert (contains? unit->calendar-unit unit)) (let [^Calendar cal (doto (Calendar/getInstance (TimeZone/getTimeZone "UTC")) (.setTimeInMillis timestamp))] (.add cal (unit->calendar-unit unit) value) (.getTimeInMillis cal)))) ;;; (in-ns 'manifold.deferred) (clojure.core/declare success! error! deferred) (in-ns 'manifold.time) ;;; (let [scheduler (delay (ScheduledThreadPoolExecutor. 1 (utils/thread-factory (constantly "manifold-scheduler-queue")))) num-cores (.availableProcessors (Runtime/getRuntime)) cnt (atom 0) executor (delay (Executors/newFixedThreadPool num-cores (utils/thread-factory #(str "manifold-scheduler-" (swap! cnt inc)))))] (defn in "Schedules no-arg function `f` to be invoked in `interval` milliseconds. Returns a deferred representing the returned value of the function." [^double interval f] (let [d (manifold.deferred/deferred) f (fn [] (let [f (fn [] (try (manifold.deferred/success! d (f)) (catch Throwable e (manifold.deferred/error! d e))))] (.execute ^Executor @executor ^Runnable f)))] (.schedule ^ScheduledThreadPoolExecutor @scheduler ^Runnable f (long (* interval 1e3)) TimeUnit/MICROSECONDS) d)) (defn every "Schedules no-arg function `f` to be invoked every `period` milliseconds, after `initial-delay` milliseconds, which defaults to `0`. Returns a zero-argument function which, when invoked, cancels the repeated invocation. If the invocation of `f` ever throws an exception, repeated invocation is automatically cancelled." ([period f] (every period 0 f)) ([period initial-delay f] (let [future-ref (promise) f (fn [] (try (f) (catch Throwable e (let [^Future future @future-ref] (.cancel future false)) (throw e))))] (deliver future-ref (.scheduleAtFixedRate ^ScheduledThreadPoolExecutor @scheduler ^Runnable (fn [] (.execute ^Executor @executor ^Runnable f)) (long (* initial-delay 1e3)) (long (* period 1e3)) TimeUnit/MICROSECONDS)) (fn [] (let [^Future future @future-ref] (.cancel future false))))))) (defn at "Schedules no-arg function `f` to be invoked at `timestamp`, which is the milliseconds since the epoch. Returns a deferred representing the returned value of the function." [timestamp f] (in (max 0 (- timestamp (System/currentTimeMillis))) f))
true
(ns ^{:author "PI:NAME:<NAME>END_PI" :doc "This namespace contains methods for converting units of time, with milliseconds as the base representation, and for deferring execution of functions to some time in the future. In practice, the methods here are not necessary to use Manifold effectively - `manifold.deferred/timeout` and `manifold.stream/periodically` are more directly useful - but they are available for anyone who should need them."} manifold.time (:require [manifold.utils :as utils] [clojure.string :as str]) (:import [java.util Calendar TimeZone] [java.util.concurrent Future Executor Executors TimeUnit ScheduledThreadPoolExecutor TimeoutException])) (defn nanoseconds "Converts nanoseconds -> milliseconds" [n] (/ n 1e6)) (defn microseconds "Converts microseconds -> milliseconds" [n] (/ n 1e3)) (defn milliseconds "Converts milliseconds -> milliseconds" [n] n) (defn seconds "Converts seconds -> milliseconds" [n] (* n 1e3)) (defn minutes "Converts minutes -> milliseconds" [n] (* n 6e4)) (defn hours "Converts hours -> milliseconds" [n] (* n 36e5)) (defn days "Converts days -> milliseconds" [n] (* n 864e5)) (defn hz "Converts frequency -> period in milliseconds" [n] (/ 1e3 n)) (let [intervals (partition 2 ["d" (days 1) "h" (hours 1) "m" (minutes 1) "s" (seconds 1)])] (defn format-duration "Takes a duration in milliseconds, and returns a formatted string describing the interval, i.e. '5d 3h 1m'" [n] (loop [s "", n n, intervals intervals] (if (empty? intervals) (if (empty? s) "0s" (str/trim s)) (let [[desc val] (first intervals)] (if (>= n val) (recur (str s (int (/ n val)) desc " ") (rem n val) (rest intervals)) (recur s n (rest intervals)))))))) (let [sorted-units [:millisecond Calendar/MILLISECOND :second Calendar/SECOND :minute Calendar/MINUTE :hour Calendar/HOUR :day Calendar/DAY_OF_YEAR :week Calendar/WEEK_OF_MONTH :month Calendar/MONTH] unit->calendar-unit (apply hash-map sorted-units) units (->> sorted-units (partition 2) (map first)) unit->cleared-fields (zipmap units (map #(->> (take % units) (map unit->calendar-unit)) (range (count units))))] (defn floor "Takes a `timestamp`, and rounds it down to the nearest even multiple of the `unit`. (floor 1001 :second) => 1000 (floor (seconds 61) :minute) => 60000 " [timestamp unit] (assert (contains? unit->calendar-unit unit)) (let [^Calendar cal (doto (Calendar/getInstance (TimeZone/getTimeZone "UTC")) (.setTimeInMillis timestamp))] (doseq [field (unit->cleared-fields unit)] (.set cal field 0)) (.getTimeInMillis cal))) (defn add "Takes a `timestamp`, and adds `value` multiples of `unit` to the value." [timestamp value unit] (assert (contains? unit->calendar-unit unit)) (let [^Calendar cal (doto (Calendar/getInstance (TimeZone/getTimeZone "UTC")) (.setTimeInMillis timestamp))] (.add cal (unit->calendar-unit unit) value) (.getTimeInMillis cal)))) ;;; (in-ns 'manifold.deferred) (clojure.core/declare success! error! deferred) (in-ns 'manifold.time) ;;; (let [scheduler (delay (ScheduledThreadPoolExecutor. 1 (utils/thread-factory (constantly "manifold-scheduler-queue")))) num-cores (.availableProcessors (Runtime/getRuntime)) cnt (atom 0) executor (delay (Executors/newFixedThreadPool num-cores (utils/thread-factory #(str "manifold-scheduler-" (swap! cnt inc)))))] (defn in "Schedules no-arg function `f` to be invoked in `interval` milliseconds. Returns a deferred representing the returned value of the function." [^double interval f] (let [d (manifold.deferred/deferred) f (fn [] (let [f (fn [] (try (manifold.deferred/success! d (f)) (catch Throwable e (manifold.deferred/error! d e))))] (.execute ^Executor @executor ^Runnable f)))] (.schedule ^ScheduledThreadPoolExecutor @scheduler ^Runnable f (long (* interval 1e3)) TimeUnit/MICROSECONDS) d)) (defn every "Schedules no-arg function `f` to be invoked every `period` milliseconds, after `initial-delay` milliseconds, which defaults to `0`. Returns a zero-argument function which, when invoked, cancels the repeated invocation. If the invocation of `f` ever throws an exception, repeated invocation is automatically cancelled." ([period f] (every period 0 f)) ([period initial-delay f] (let [future-ref (promise) f (fn [] (try (f) (catch Throwable e (let [^Future future @future-ref] (.cancel future false)) (throw e))))] (deliver future-ref (.scheduleAtFixedRate ^ScheduledThreadPoolExecutor @scheduler ^Runnable (fn [] (.execute ^Executor @executor ^Runnable f)) (long (* initial-delay 1e3)) (long (* period 1e3)) TimeUnit/MICROSECONDS)) (fn [] (let [^Future future @future-ref] (.cancel future false))))))) (defn at "Schedules no-arg function `f` to be invoked at `timestamp`, which is the milliseconds since the epoch. Returns a deferred representing the returned value of the function." [timestamp f] (in (max 0 (- timestamp (System/currentTimeMillis))) f))
[ { "context": ";; author: Mark W. Naylor\n;; file: chapter01.clj\n;; date: 2021-Jan-10\n(ns", "end": 25, "score": 0.999873161315918, "start": 11, "tag": "NAME", "value": "Mark W. Naylor" }, { "context": " :else (sum-of-squares y z)))\n\n\n;; Exercise 1.6. Alyssa P. Hacker doesn't see why if needs to be provided\n;; as a s", "end": 1366, "score": 0.9973013997077942, "start": 1350, "tag": "NAME", "value": "Alyssa P. Hacker" }, { "context": "edure in terms of cond?\" she asks. Alyssa's friend Eva Lu Ator\n;; claims this can indeed be done, and she define", "end": 1541, "score": 0.9338567852973938, "start": 1530, "tag": "NAME", "value": "Eva Lu Ator" }, { "context": "----\n;; BSD 3-Clause License\n\n;; Copyright © 2021, Mark W. Naylor\n;; All rights reserved.\n\n;; Redistribution and us", "end": 6895, "score": 0.9998397827148438, "start": 6881, "tag": "NAME", "value": "Mark W. Naylor" } ]
src/org/mark_naylor_1701/sicp/chapter01.clj
mark-naylor-1701/clojure-sicp
0
;; author: Mark W. Naylor ;; file: chapter01.clj ;; date: 2021-Jan-10 (ns org.mark-naylor-1701.sicp.chapter01) ;; Examples ;; Trivial, but used in later examples and exercises. (defn square "Return the result of a number muliplied by itself." [x] (* x x)) (defn sum-of-squares "" [x y] (+ (square x) (square y))) ;; Although defined in Math/abs, use this version to follow the text. (defn- abs "" [x] (cond (< x 0) (- x) :else x)) ;; Example 1.1.7: Square Roots by Newton's Method (def ^:private ^:dynamic *delta* 0.001) (defn- good-enough-1? [guess x] (< (abs (- (square guess) x)) *delta*)) (defn- average [x y] (/ (+ x y) 2.0)) (defn- improve [guess x] (average guess (/ x guess))) (defn- sqrt-iter-1 [guess x] (if (good-enough-1? guess x) guess (recur (improve guess x) x))) (defn sqrt-1 [x] (sqrt-iter-1 1.0 x)) ;; Exercise 1.2 Convert to prefix form (def ex-1_2 (/ (+ 5 4 (- 2 (- 3 (+ 6 4/5)))) (* 3 (- 6 2) (- 2 7)))) ;; Exercise 1.3 Define a procedure that takes three numbers and ;; returns the sum of the squares of the two larger numbers. (defn ex-1_3 "" [x y z] (cond (and (>= x z) (>= y z)) (sum-of-squares x y) (and (>= x y) (>= z y)) (sum-of-squares x z) :else (sum-of-squares y z))) ;; Exercise 1.6. Alyssa P. Hacker doesn't see why if needs to be provided ;; as a special form. "Why can't I just define it as an ordinary ;; procedure in terms of cond?" she asks. Alyssa's friend Eva Lu Ator ;; claims this can indeed be done, and she defines a new version of if:2 (defn new-if "" [predicate then-clause else-clause] (cond predicate then-clause :else else-clause)) ;; Eva demonstrates the program for Alyssa: (new-if (= 2 3) 0 5) ;; Because `new-if' is not a special form, the recursive call has to ;; made explicitly. Using recur fails in this case because the Clojure ;; compiler does not recognize as a proper tail-call.> (defn sqrt-iter-new-if [guess x] (new-if (good-enough-1? guess x) guess (sqrt-iter-new-if (improve guess x) x))) ;; Q: What happens if we run this? A: Stack blows up because else clause always evaluated. ;; Exercise 1.7. The good-enough? test used in computing square roots ;; will not be very effective finding the square roots of very small ;; numbers. Also, in real computers, arithmetic operations are always ;; performed with limited precision. This makes our test inadequate ;; for very large numbers. these statements, with examples showing how ;; the test fails for small and large numbers. An strategy for ;; implementing good-enough? is to watch how guess changes from one ;; iteration to next and to stop when the change is a very small ;; fraction of the guess. Design a square-root procedure uses this ;; kind of end test. Does this work better for small and large ;; numbers? (defn- good-enough-2? [guess x prior] (< (/ (abs (- guess prior)) guess) *delta*)) (defn- sqrt-iter-2 ([guess x] (sqrt-iter-2 guess x -1.0)) ([guess x prior] (if (good-enough-2? guess x prior) guess (recur (improve guess x) x guess)))) (defn sqrt-2 [x] (sqrt-iter-2 1.0 x -1.0)) ;; Exercise 1.8. Newton's method for cube roots is based on the fact ;; that if y is an approximation to the cube root of x, then a better ;; approximation is given by the value: ;; (x/y^2 + 2y) / 3 ;; Use this formula to implement a cube-root procedure analogous to ;; the square-root procedure. (In section 1.3.4 we will see how to ;; implement Newton's method in general as an abstraction of these ;; square- root and cube-root procedures.) (defn- cube "x raised to the 3rd power." [x] (* x x x)) (defn- cube-root-native "Cube root function using native Math/pow function." [x] (double (Math/pow x 1/3))) (defn- improve-cube [guess x] (let [guess (double guess) ] (/ (+ (/ x (square guess)) (* 2 guess)) 3))) (defn- good-enough-cube? [guess x] (< (abs (- (cube guess) x)) *delta*)) (defn- cube-root-iter [guess x] (if (good-enough-cube? guess x) guess (recur (improve-cube guess x) x))) (defn cube-root "" [x] (cube-root-iter 1 x)) ;;Exercise 1.10. The following procedure computes a mathematical function called Ackermann's function. ;; (define (A x y) ;; (cond ((= y 0) ) ;; ((= x 0) (* 2 y)) ;; ((= y 1) 2) ;; (else (A ;; (- x 1) ;; (A x (- y 1)))))) (defn A "Ackermann's function." [x y] (cond (zero? y) 0 (zero? x) (* 2 y) (= y 1) 2 :else (A (dec x) (A x (dec y))))) ;; What are the values of the following expressions? ;; (A 1 10) -> 1024 ;; (A 2 4) -> 65536 ;; (A 3 3) -> 65536 ;; Consider the following procedures, where A is the procedure defined above: ;; (define (f n) (A 0 n)) ;; (define (g n) (A 1 n)) ;; (define (h n) (A 2 n)) ;; (define (k n) (* 5 n n)) ;; Give concise mathematical definitions for the functions computed by the procedures f, g, and h for ;; positive integer values of n. For example, (k n) computes 5n2. (def f "Partially applied A on 0" (partial A 0)) (def g "Partially applied A on 1" (partial A 1)) (def h "Partially applied A on 2" (partial A 2)) (defn k [n] "Computes 5 * n^2" (* 5 n n)) ;; Define Fibonacci variants (defn fib "Recursive version." [x] (cond (zero? x) 0 (= x 1) 1 :else (+ (fib (dec x)) (fib (- x 2))))) (defn fib-iter "Iterative (tail recursive) version." [x] (letfn [(fib-iter [a b count] (cond (zero? count) b :else (recur (+ a b) a (dec count))))] (fib-iter 1 0 x))) ;; Exercise 1.11. A function f is defined by the rule that f(n) = n if ;; n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a ;; procedure that computes f by means of a recursive process. Write a ;; procedure that computes f by means of an iterative process. (defn ex1-11-recur [x] (cond (< x 3) x :else (+ (ex1-11-recur (- x 1)) (* 2 (ex1-11-recur (- x 2))) (* 3 (ex1-11-recur (- x 3)))))) ;; Solution found here: http://community.schemewiki.org/?sicp-ex-1.11 ;; (define (f n) ;; (define (f-i a b c count) ;; (cond ((< n 3) n) ;; ((<= count 0) a) ;; (else (f-i (+ a (* 2 b) (* 3 c)) a b (- count 1))))) ;; (f-i 2 1 0 (- n 2))) (defn ex1-11-iter [x] (letfn [(ex1-11-iter [a b c count] (cond (< x 3) x (<= count 0) a :else (recur (+ a (* 2 b) (* 3 c)) a b (dec count))))] (ex1-11-iter 2 1 0 (- x 2)))) ;; ------------------------------------------------------------------------------ ;; BSD 3-Clause License ;; Copyright © 2021, Mark W. Naylor ;; All rights reserved. ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; 1. Redistributions of source code must retain the above copyright notice, this ;; list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright notice, ;; this list of conditions and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; 3. Neither the name of the copyright holder nor the names of its ;; contributors may be used to endorse or promote products derived from ;; this software without specific prior written permission. ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30048
;; author: <NAME> ;; file: chapter01.clj ;; date: 2021-Jan-10 (ns org.mark-naylor-1701.sicp.chapter01) ;; Examples ;; Trivial, but used in later examples and exercises. (defn square "Return the result of a number muliplied by itself." [x] (* x x)) (defn sum-of-squares "" [x y] (+ (square x) (square y))) ;; Although defined in Math/abs, use this version to follow the text. (defn- abs "" [x] (cond (< x 0) (- x) :else x)) ;; Example 1.1.7: Square Roots by Newton's Method (def ^:private ^:dynamic *delta* 0.001) (defn- good-enough-1? [guess x] (< (abs (- (square guess) x)) *delta*)) (defn- average [x y] (/ (+ x y) 2.0)) (defn- improve [guess x] (average guess (/ x guess))) (defn- sqrt-iter-1 [guess x] (if (good-enough-1? guess x) guess (recur (improve guess x) x))) (defn sqrt-1 [x] (sqrt-iter-1 1.0 x)) ;; Exercise 1.2 Convert to prefix form (def ex-1_2 (/ (+ 5 4 (- 2 (- 3 (+ 6 4/5)))) (* 3 (- 6 2) (- 2 7)))) ;; Exercise 1.3 Define a procedure that takes three numbers and ;; returns the sum of the squares of the two larger numbers. (defn ex-1_3 "" [x y z] (cond (and (>= x z) (>= y z)) (sum-of-squares x y) (and (>= x y) (>= z y)) (sum-of-squares x z) :else (sum-of-squares y z))) ;; Exercise 1.6. <NAME> doesn't see why if needs to be provided ;; as a special form. "Why can't I just define it as an ordinary ;; procedure in terms of cond?" she asks. Alyssa's friend <NAME> ;; claims this can indeed be done, and she defines a new version of if:2 (defn new-if "" [predicate then-clause else-clause] (cond predicate then-clause :else else-clause)) ;; Eva demonstrates the program for Alyssa: (new-if (= 2 3) 0 5) ;; Because `new-if' is not a special form, the recursive call has to ;; made explicitly. Using recur fails in this case because the Clojure ;; compiler does not recognize as a proper tail-call.> (defn sqrt-iter-new-if [guess x] (new-if (good-enough-1? guess x) guess (sqrt-iter-new-if (improve guess x) x))) ;; Q: What happens if we run this? A: Stack blows up because else clause always evaluated. ;; Exercise 1.7. The good-enough? test used in computing square roots ;; will not be very effective finding the square roots of very small ;; numbers. Also, in real computers, arithmetic operations are always ;; performed with limited precision. This makes our test inadequate ;; for very large numbers. these statements, with examples showing how ;; the test fails for small and large numbers. An strategy for ;; implementing good-enough? is to watch how guess changes from one ;; iteration to next and to stop when the change is a very small ;; fraction of the guess. Design a square-root procedure uses this ;; kind of end test. Does this work better for small and large ;; numbers? (defn- good-enough-2? [guess x prior] (< (/ (abs (- guess prior)) guess) *delta*)) (defn- sqrt-iter-2 ([guess x] (sqrt-iter-2 guess x -1.0)) ([guess x prior] (if (good-enough-2? guess x prior) guess (recur (improve guess x) x guess)))) (defn sqrt-2 [x] (sqrt-iter-2 1.0 x -1.0)) ;; Exercise 1.8. Newton's method for cube roots is based on the fact ;; that if y is an approximation to the cube root of x, then a better ;; approximation is given by the value: ;; (x/y^2 + 2y) / 3 ;; Use this formula to implement a cube-root procedure analogous to ;; the square-root procedure. (In section 1.3.4 we will see how to ;; implement Newton's method in general as an abstraction of these ;; square- root and cube-root procedures.) (defn- cube "x raised to the 3rd power." [x] (* x x x)) (defn- cube-root-native "Cube root function using native Math/pow function." [x] (double (Math/pow x 1/3))) (defn- improve-cube [guess x] (let [guess (double guess) ] (/ (+ (/ x (square guess)) (* 2 guess)) 3))) (defn- good-enough-cube? [guess x] (< (abs (- (cube guess) x)) *delta*)) (defn- cube-root-iter [guess x] (if (good-enough-cube? guess x) guess (recur (improve-cube guess x) x))) (defn cube-root "" [x] (cube-root-iter 1 x)) ;;Exercise 1.10. The following procedure computes a mathematical function called Ackermann's function. ;; (define (A x y) ;; (cond ((= y 0) ) ;; ((= x 0) (* 2 y)) ;; ((= y 1) 2) ;; (else (A ;; (- x 1) ;; (A x (- y 1)))))) (defn A "Ackermann's function." [x y] (cond (zero? y) 0 (zero? x) (* 2 y) (= y 1) 2 :else (A (dec x) (A x (dec y))))) ;; What are the values of the following expressions? ;; (A 1 10) -> 1024 ;; (A 2 4) -> 65536 ;; (A 3 3) -> 65536 ;; Consider the following procedures, where A is the procedure defined above: ;; (define (f n) (A 0 n)) ;; (define (g n) (A 1 n)) ;; (define (h n) (A 2 n)) ;; (define (k n) (* 5 n n)) ;; Give concise mathematical definitions for the functions computed by the procedures f, g, and h for ;; positive integer values of n. For example, (k n) computes 5n2. (def f "Partially applied A on 0" (partial A 0)) (def g "Partially applied A on 1" (partial A 1)) (def h "Partially applied A on 2" (partial A 2)) (defn k [n] "Computes 5 * n^2" (* 5 n n)) ;; Define Fibonacci variants (defn fib "Recursive version." [x] (cond (zero? x) 0 (= x 1) 1 :else (+ (fib (dec x)) (fib (- x 2))))) (defn fib-iter "Iterative (tail recursive) version." [x] (letfn [(fib-iter [a b count] (cond (zero? count) b :else (recur (+ a b) a (dec count))))] (fib-iter 1 0 x))) ;; Exercise 1.11. A function f is defined by the rule that f(n) = n if ;; n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a ;; procedure that computes f by means of a recursive process. Write a ;; procedure that computes f by means of an iterative process. (defn ex1-11-recur [x] (cond (< x 3) x :else (+ (ex1-11-recur (- x 1)) (* 2 (ex1-11-recur (- x 2))) (* 3 (ex1-11-recur (- x 3)))))) ;; Solution found here: http://community.schemewiki.org/?sicp-ex-1.11 ;; (define (f n) ;; (define (f-i a b c count) ;; (cond ((< n 3) n) ;; ((<= count 0) a) ;; (else (f-i (+ a (* 2 b) (* 3 c)) a b (- count 1))))) ;; (f-i 2 1 0 (- n 2))) (defn ex1-11-iter [x] (letfn [(ex1-11-iter [a b c count] (cond (< x 3) x (<= count 0) a :else (recur (+ a (* 2 b) (* 3 c)) a b (dec count))))] (ex1-11-iter 2 1 0 (- x 2)))) ;; ------------------------------------------------------------------------------ ;; BSD 3-Clause License ;; Copyright © 2021, <NAME> ;; All rights reserved. ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; 1. Redistributions of source code must retain the above copyright notice, this ;; list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright notice, ;; this list of conditions and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; 3. Neither the name of the copyright holder nor the names of its ;; contributors may be used to endorse or promote products derived from ;; this software without specific prior written permission. ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
true
;; author: PI:NAME:<NAME>END_PI ;; file: chapter01.clj ;; date: 2021-Jan-10 (ns org.mark-naylor-1701.sicp.chapter01) ;; Examples ;; Trivial, but used in later examples and exercises. (defn square "Return the result of a number muliplied by itself." [x] (* x x)) (defn sum-of-squares "" [x y] (+ (square x) (square y))) ;; Although defined in Math/abs, use this version to follow the text. (defn- abs "" [x] (cond (< x 0) (- x) :else x)) ;; Example 1.1.7: Square Roots by Newton's Method (def ^:private ^:dynamic *delta* 0.001) (defn- good-enough-1? [guess x] (< (abs (- (square guess) x)) *delta*)) (defn- average [x y] (/ (+ x y) 2.0)) (defn- improve [guess x] (average guess (/ x guess))) (defn- sqrt-iter-1 [guess x] (if (good-enough-1? guess x) guess (recur (improve guess x) x))) (defn sqrt-1 [x] (sqrt-iter-1 1.0 x)) ;; Exercise 1.2 Convert to prefix form (def ex-1_2 (/ (+ 5 4 (- 2 (- 3 (+ 6 4/5)))) (* 3 (- 6 2) (- 2 7)))) ;; Exercise 1.3 Define a procedure that takes three numbers and ;; returns the sum of the squares of the two larger numbers. (defn ex-1_3 "" [x y z] (cond (and (>= x z) (>= y z)) (sum-of-squares x y) (and (>= x y) (>= z y)) (sum-of-squares x z) :else (sum-of-squares y z))) ;; Exercise 1.6. PI:NAME:<NAME>END_PI doesn't see why if needs to be provided ;; as a special form. "Why can't I just define it as an ordinary ;; procedure in terms of cond?" she asks. Alyssa's friend PI:NAME:<NAME>END_PI ;; claims this can indeed be done, and she defines a new version of if:2 (defn new-if "" [predicate then-clause else-clause] (cond predicate then-clause :else else-clause)) ;; Eva demonstrates the program for Alyssa: (new-if (= 2 3) 0 5) ;; Because `new-if' is not a special form, the recursive call has to ;; made explicitly. Using recur fails in this case because the Clojure ;; compiler does not recognize as a proper tail-call.> (defn sqrt-iter-new-if [guess x] (new-if (good-enough-1? guess x) guess (sqrt-iter-new-if (improve guess x) x))) ;; Q: What happens if we run this? A: Stack blows up because else clause always evaluated. ;; Exercise 1.7. The good-enough? test used in computing square roots ;; will not be very effective finding the square roots of very small ;; numbers. Also, in real computers, arithmetic operations are always ;; performed with limited precision. This makes our test inadequate ;; for very large numbers. these statements, with examples showing how ;; the test fails for small and large numbers. An strategy for ;; implementing good-enough? is to watch how guess changes from one ;; iteration to next and to stop when the change is a very small ;; fraction of the guess. Design a square-root procedure uses this ;; kind of end test. Does this work better for small and large ;; numbers? (defn- good-enough-2? [guess x prior] (< (/ (abs (- guess prior)) guess) *delta*)) (defn- sqrt-iter-2 ([guess x] (sqrt-iter-2 guess x -1.0)) ([guess x prior] (if (good-enough-2? guess x prior) guess (recur (improve guess x) x guess)))) (defn sqrt-2 [x] (sqrt-iter-2 1.0 x -1.0)) ;; Exercise 1.8. Newton's method for cube roots is based on the fact ;; that if y is an approximation to the cube root of x, then a better ;; approximation is given by the value: ;; (x/y^2 + 2y) / 3 ;; Use this formula to implement a cube-root procedure analogous to ;; the square-root procedure. (In section 1.3.4 we will see how to ;; implement Newton's method in general as an abstraction of these ;; square- root and cube-root procedures.) (defn- cube "x raised to the 3rd power." [x] (* x x x)) (defn- cube-root-native "Cube root function using native Math/pow function." [x] (double (Math/pow x 1/3))) (defn- improve-cube [guess x] (let [guess (double guess) ] (/ (+ (/ x (square guess)) (* 2 guess)) 3))) (defn- good-enough-cube? [guess x] (< (abs (- (cube guess) x)) *delta*)) (defn- cube-root-iter [guess x] (if (good-enough-cube? guess x) guess (recur (improve-cube guess x) x))) (defn cube-root "" [x] (cube-root-iter 1 x)) ;;Exercise 1.10. The following procedure computes a mathematical function called Ackermann's function. ;; (define (A x y) ;; (cond ((= y 0) ) ;; ((= x 0) (* 2 y)) ;; ((= y 1) 2) ;; (else (A ;; (- x 1) ;; (A x (- y 1)))))) (defn A "Ackermann's function." [x y] (cond (zero? y) 0 (zero? x) (* 2 y) (= y 1) 2 :else (A (dec x) (A x (dec y))))) ;; What are the values of the following expressions? ;; (A 1 10) -> 1024 ;; (A 2 4) -> 65536 ;; (A 3 3) -> 65536 ;; Consider the following procedures, where A is the procedure defined above: ;; (define (f n) (A 0 n)) ;; (define (g n) (A 1 n)) ;; (define (h n) (A 2 n)) ;; (define (k n) (* 5 n n)) ;; Give concise mathematical definitions for the functions computed by the procedures f, g, and h for ;; positive integer values of n. For example, (k n) computes 5n2. (def f "Partially applied A on 0" (partial A 0)) (def g "Partially applied A on 1" (partial A 1)) (def h "Partially applied A on 2" (partial A 2)) (defn k [n] "Computes 5 * n^2" (* 5 n n)) ;; Define Fibonacci variants (defn fib "Recursive version." [x] (cond (zero? x) 0 (= x 1) 1 :else (+ (fib (dec x)) (fib (- x 2))))) (defn fib-iter "Iterative (tail recursive) version." [x] (letfn [(fib-iter [a b count] (cond (zero? count) b :else (recur (+ a b) a (dec count))))] (fib-iter 1 0 x))) ;; Exercise 1.11. A function f is defined by the rule that f(n) = n if ;; n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a ;; procedure that computes f by means of a recursive process. Write a ;; procedure that computes f by means of an iterative process. (defn ex1-11-recur [x] (cond (< x 3) x :else (+ (ex1-11-recur (- x 1)) (* 2 (ex1-11-recur (- x 2))) (* 3 (ex1-11-recur (- x 3)))))) ;; Solution found here: http://community.schemewiki.org/?sicp-ex-1.11 ;; (define (f n) ;; (define (f-i a b c count) ;; (cond ((< n 3) n) ;; ((<= count 0) a) ;; (else (f-i (+ a (* 2 b) (* 3 c)) a b (- count 1))))) ;; (f-i 2 1 0 (- n 2))) (defn ex1-11-iter [x] (letfn [(ex1-11-iter [a b c count] (cond (< x 3) x (<= count 0) a :else (recur (+ a (* 2 b) (* 3 c)) a b (dec count))))] (ex1-11-iter 2 1 0 (- x 2)))) ;; ------------------------------------------------------------------------------ ;; BSD 3-Clause License ;; Copyright © 2021, PI:NAME:<NAME>END_PI ;; All rights reserved. ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; 1. Redistributions of source code must retain the above copyright notice, this ;; list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright notice, ;; this list of conditions and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; 3. Neither the name of the copyright holder nor the names of its ;; contributors may be used to endorse or promote products derived from ;; this software without specific prior written permission. ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[ { "context": ";; Copyright © 2015-2022 Esko Luontola\n;; This software is released under the Apache Lic", "end": 38, "score": 0.9998838901519775, "start": 25, "tag": "NAME", "value": "Esko Luontola" } ]
test/territory_bro/test/testutil.clj
3breadt/territory-bro
0
;; Copyright © 2015-2022 Esko Luontola ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.test.testutil (:require [clojure.test :refer :all] [territory-bro.commands :as commands] [territory-bro.events :as events] [territory-bro.infra.foreign-key :as foreign-key]) (:import (java.util.regex Pattern))) (defn re-equals [^String s] (re-pattern (str "^" (Pattern/quote s) "$"))) (defn re-contains [^String s] (re-pattern (Pattern/quote s))) (defmacro grab-exception [& body] `(try (let [result# (do ~@body)] (do-report {:type :fail :message "should have thrown an exception, but did not" :expected (seq (into [(symbol "grab-exception")] '~body)) :actual result#}) result#) (catch Throwable t# t#))) (def dummy-reference-checkers {:card-minimap-viewport (constantly true) :congregation (constantly true) :congregation-boundary (constantly true) :new (constantly true) :region (constantly true) :share (constantly true) :territory (constantly true) :user (constantly true) :user-or-anonymous (constantly true) :unsafe (constantly true)}) (defn validate-command [command] (binding [foreign-key/*reference-checkers* dummy-reference-checkers] (commands/validate-command command))) (defn validate-commands [commands] (doseq [command commands] (validate-command command)) commands) (defn apply-events [projection events] (reduce projection nil (events/validate-events events)))
92448
;; Copyright © 2015-2022 <NAME> ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.test.testutil (:require [clojure.test :refer :all] [territory-bro.commands :as commands] [territory-bro.events :as events] [territory-bro.infra.foreign-key :as foreign-key]) (:import (java.util.regex Pattern))) (defn re-equals [^String s] (re-pattern (str "^" (Pattern/quote s) "$"))) (defn re-contains [^String s] (re-pattern (Pattern/quote s))) (defmacro grab-exception [& body] `(try (let [result# (do ~@body)] (do-report {:type :fail :message "should have thrown an exception, but did not" :expected (seq (into [(symbol "grab-exception")] '~body)) :actual result#}) result#) (catch Throwable t# t#))) (def dummy-reference-checkers {:card-minimap-viewport (constantly true) :congregation (constantly true) :congregation-boundary (constantly true) :new (constantly true) :region (constantly true) :share (constantly true) :territory (constantly true) :user (constantly true) :user-or-anonymous (constantly true) :unsafe (constantly true)}) (defn validate-command [command] (binding [foreign-key/*reference-checkers* dummy-reference-checkers] (commands/validate-command command))) (defn validate-commands [commands] (doseq [command commands] (validate-command command)) commands) (defn apply-events [projection events] (reduce projection nil (events/validate-events events)))
true
;; Copyright © 2015-2022 PI:NAME:<NAME>END_PI ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns territory-bro.test.testutil (:require [clojure.test :refer :all] [territory-bro.commands :as commands] [territory-bro.events :as events] [territory-bro.infra.foreign-key :as foreign-key]) (:import (java.util.regex Pattern))) (defn re-equals [^String s] (re-pattern (str "^" (Pattern/quote s) "$"))) (defn re-contains [^String s] (re-pattern (Pattern/quote s))) (defmacro grab-exception [& body] `(try (let [result# (do ~@body)] (do-report {:type :fail :message "should have thrown an exception, but did not" :expected (seq (into [(symbol "grab-exception")] '~body)) :actual result#}) result#) (catch Throwable t# t#))) (def dummy-reference-checkers {:card-minimap-viewport (constantly true) :congregation (constantly true) :congregation-boundary (constantly true) :new (constantly true) :region (constantly true) :share (constantly true) :territory (constantly true) :user (constantly true) :user-or-anonymous (constantly true) :unsafe (constantly true)}) (defn validate-command [command] (binding [foreign-key/*reference-checkers* dummy-reference-checkers] (commands/validate-command command))) (defn validate-commands [commands] (doseq [command commands] (validate-command command)) commands) (defn apply-events [projection events] (reduce projection nil (events/validate-events events)))
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"Kristina Lisa Klinkner, John Alan McDonald\" :date \"2016-11-08\"\n :do", "end": 109, "score": 0.9998824596405029, "start": 87, "tag": "NAME", "value": "Kristina Lisa Klinkner" }, { "context": "n-on-boxed)\n(ns ^{:author \"Kristina Lisa Klinkner, John Alan McDonald\" :date \"2016-11-08\"\n :doc \"Iris data probabi", "end": 129, "score": 0.9998747706413269, "start": 111, "tag": "NAME", "value": "John Alan McDonald" } ]
src/test/clojure/taiga/test/classify/iris/mincount.clj
wahpenayo/taiga
4
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "Kristina Lisa Klinkner, John Alan McDonald" :date "2016-11-08" :doc "Iris data probability forest example." } taiga.test.classify.iris.mincount (:require [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.tree :as tree] [taiga.test.classify.data.defs :as defs] [taiga.test.classify.iris.record :as record] [taiga.test.classify.iris.iris :as iris])) ;; mvn -Dtest=taiga.test.classify.iris.mincount clojure:test > tests.txt ;;------------------------------------------------------------------------------ (def nss (str *ns*)) (test/deftest iris-mincount (z/reset-mersenne-twister-seeds) (let [options (iris/options) options (assoc options :mincount 15) false-negative-cost 999.0 false-positive-cost 1.0 ^clojure.lang.IFn$OD y (:ground-truth record/attributes) weight (fn weight ^double [datum] (if (== 1.0 (.invokePrim y datum)) false-negative-cost false-positive-cost)) options (assoc options :weight weight) predictors (into (sorted-map) (dissoc record/attributes :ground-truth :prediction)) forest (taiga/majority-vote-probability options) ^clojure.lang.IFn$OD prob (fn prob ^double [datum] (.invokePrim forest predictors datum)) threshold (/ false-positive-cost (+ false-negative-cost false-positive-cost)) yhat (fn yhat ^double [datum] (if (< (.invokePrim prob datum) threshold) 0.0 1.0))] (z/mapc #(tree/check-mincount options %) (taiga/terms forest)) (test/is (= (mapv taiga/node-height (taiga/terms forest)) [4 4 3 4 3 4 3 4 3 3 4 3 5 3 3 4 4 3 4 3 3 3 4 4 4 5 4 5 3 4 4 4 4 4 5 4 4 4 4 5 4 4 4 4 4 4 4 3 4 2 3 4 4 3 4 3 4 5 4 4 4 3 3 3 3 3 4 3 4 3 4 3 3 4 3 3 4 3 3 4 3 3 4 4 4 4 5 3 4 4 4 3 4 4 3 4 4 3 4 4 3 4 4 3 4 4 4 4 3 4 4 4 3 3 3 4 3 4 4 3 3 4 3 3 4 4 3 3 4 5 4 3 3 4 4 3 4 4 4 4 4 4 3 4 3 3 4 4 4 3 4 3 3 4 4 5 4 3 3 4 4 4 3 3 3 4 3 4 4 3 4 3 4 4 3 4 4 3 4 3 5 4 3 4 4 3 4 3 4 4 3 4 3 4 3 3 4 3 4 4 4 3 3 5 4 4 3 3 4 3 4 3 3 4 3 4 4 3 4 4 3 4 4 3 3 3 3 3 4 4 4 4 3 3 4 3 3 3 3 4 3 3 4 3 4 5 3 3 5 4 3 4 4 5 3 3 3 4 4 4 4 4 4 3 3 4 3 4 4 3 4 5 3 5 3 3 4 3 4 3 3 4 3 4 4 4 3 4 5 4 4 4 4 3 4 3 4 3 3 4 3 3 4 4 4 4 3 3 5 4 4 3 5 4 4 3 3 4 4 3 4 3 3 4 4 3 4 3 4 5 4 4 4 4 4 4 3 3 3 3 3 4 4 4 5 3 3 3 3 4 3 3 3 4 4 4 4 3 4 3 4 5 4 4 5 4 4 4 4 4 3 4 3 4 4 3 4 3 3 4 4 3 3 4 3 3 4 4 4 4 4 3 3 4 4 4 4 5 4 3 5 4 4 3 5 3 4 3 4 3 4 5 3 4 3 4 3 4 3 3 3 4 5 5 3 3 3 4 4 4 4 3 4 3 4 3 3 5 3 4 4 4 3 4 4 4 3 4 3 3 3 4 4 3 3 3 3 4 4 4 4 5 3 3 3 4 3 4 4 3 4 3 4 4 3 4 3 4 3 4 4 4 4 4 4 3 3 3 4 2 3 4 5 4 3 3 4 5 3 4 4 4 5 3 4 3 4 4 3 3 4 4] )) (test/is (= (mapv taiga/count-children (taiga/terms forest)) [7 7 5 7 5 7 5 7 5 5 7 5 9 7 5 7 7 5 7 5 5 5 7 7 7 9 7 9 5 7 7 7 7 7 11 7 7 9 7 9 7 7 7 7 7 7 7 5 7 3 5 7 7 5 7 7 9 9 7 7 7 5 5 5 5 5 7 5 7 5 7 5 5 9 5 5 7 5 5 7 5 5 7 7 7 7 9 5 7 7 7 5 7 7 5 7 7 5 7 7 7 7 7 5 7 7 7 7 7 7 7 7 5 5 5 7 5 7 7 5 5 7 7 5 7 7 5 5 7 9 7 5 7 7 7 5 7 7 7 7 7 7 5 9 7 5 7 7 7 5 7 5 5 7 7 9 7 5 5 7 7 7 5 5 5 7 5 7 7 5 7 5 7 7 5 7 7 5 7 5 9 9 5 7 7 5 7 5 7 9 5 7 5 7 5 5 7 5 7 7 7 5 5 9 7 7 5 7 7 5 7 5 5 7 5 7 7 5 7 7 7 7 7 5 5 5 5 7 7 7 7 9 5 5 7 5 5 5 5 7 5 5 9 5 7 9 5 5 9 7 5 7 7 9 7 5 5 7 7 7 7 7 7 5 5 7 5 7 7 5 9 9 5 9 5 5 7 5 7 5 5 7 5 7 7 7 5 7 9 7 7 9 7 5 7 5 7 5 5 7 5 5 7 7 7 7 5 5 9 7 7 5 9 7 7 5 5 7 7 5 7 5 5 7 7 5 7 5 7 9 7 7 7 7 7 9 5 5 5 5 5 9 7 7 9 5 5 5 5 7 5 5 5 7 7 7 7 5 7 5 7 9 7 7 9 7 7 7 7 7 5 7 5 7 7 5 7 5 5 7 7 5 5 7 5 5 7 7 7 7 7 5 5 7 9 7 7 9 9 5 9 7 7 5 9 5 7 5 7 5 7 9 5 7 5 9 5 7 5 5 5 7 9 9 5 5 5 7 7 9 7 5 7 5 7 5 5 9 5 7 7 7 5 7 7 7 5 7 5 5 5 7 7 5 5 5 5 7 7 7 7 9 5 5 5 7 7 7 7 5 7 5 7 7 5 7 5 7 5 7 7 7 7 7 7 7 5 5 7 3 5 9 9 7 5 5 7 9 5 7 7 7 9 5 9 5 7 7 5 5 7 7] )) (test/is (= (mapv taiga/count-leaves (taiga/terms forest)) [4 4 3 4 3 4 3 4 3 3 4 3 5 4 3 4 4 3 4 3 3 3 4 4 4 5 4 5 3 4 4 4 4 4 6 4 4 5 4 5 4 4 4 4 4 4 4 3 4 2 3 4 4 3 4 4 5 5 4 4 4 3 3 3 3 3 4 3 4 3 4 3 3 5 3 3 4 3 3 4 3 3 4 4 4 4 5 3 4 4 4 3 4 4 3 4 4 3 4 4 4 4 4 3 4 4 4 4 4 4 4 4 3 3 3 4 3 4 4 3 3 4 4 3 4 4 3 3 4 5 4 3 4 4 4 3 4 4 4 4 4 4 3 5 4 3 4 4 4 3 4 3 3 4 4 5 4 3 3 4 4 4 3 3 3 4 3 4 4 3 4 3 4 4 3 4 4 3 4 3 5 5 3 4 4 3 4 3 4 5 3 4 3 4 3 3 4 3 4 4 4 3 3 5 4 4 3 4 4 3 4 3 3 4 3 4 4 3 4 4 4 4 4 3 3 3 3 4 4 4 4 5 3 3 4 3 3 3 3 4 3 3 5 3 4 5 3 3 5 4 3 4 4 5 4 3 3 4 4 4 4 4 4 3 3 4 3 4 4 3 5 5 3 5 3 3 4 3 4 3 3 4 3 4 4 4 3 4 5 4 4 5 4 3 4 3 4 3 3 4 3 3 4 4 4 4 3 3 5 4 4 3 5 4 4 3 3 4 4 3 4 3 3 4 4 3 4 3 4 5 4 4 4 4 4 5 3 3 3 3 3 5 4 4 5 3 3 3 3 4 3 3 3 4 4 4 4 3 4 3 4 5 4 4 5 4 4 4 4 4 3 4 3 4 4 3 4 3 3 4 4 3 3 4 3 3 4 4 4 4 4 3 3 4 5 4 4 5 5 3 5 4 4 3 5 3 4 3 4 3 4 5 3 4 3 5 3 4 3 3 3 4 5 5 3 3 3 4 4 5 4 3 4 3 4 3 3 5 3 4 4 4 3 4 4 4 3 4 3 3 3 4 4 3 3 3 3 4 4 4 4 5 3 3 3 4 4 4 4 3 4 3 4 4 3 4 3 4 3 4 4 4 4 4 4 4 3 3 4 2 3 5 5 4 3 3 4 5 3 4 4 4 5 3 5 3 4 4 3 3 4 4 ] )) (defs/serialization-test nss options forest) (test/is (= [0 0 50 50] (defs/print-confusion y yhat (:data options)))))) ;;------------------------------------------------------------------------------
83898
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>, <NAME>" :date "2016-11-08" :doc "Iris data probability forest example." } taiga.test.classify.iris.mincount (:require [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.tree :as tree] [taiga.test.classify.data.defs :as defs] [taiga.test.classify.iris.record :as record] [taiga.test.classify.iris.iris :as iris])) ;; mvn -Dtest=taiga.test.classify.iris.mincount clojure:test > tests.txt ;;------------------------------------------------------------------------------ (def nss (str *ns*)) (test/deftest iris-mincount (z/reset-mersenne-twister-seeds) (let [options (iris/options) options (assoc options :mincount 15) false-negative-cost 999.0 false-positive-cost 1.0 ^clojure.lang.IFn$OD y (:ground-truth record/attributes) weight (fn weight ^double [datum] (if (== 1.0 (.invokePrim y datum)) false-negative-cost false-positive-cost)) options (assoc options :weight weight) predictors (into (sorted-map) (dissoc record/attributes :ground-truth :prediction)) forest (taiga/majority-vote-probability options) ^clojure.lang.IFn$OD prob (fn prob ^double [datum] (.invokePrim forest predictors datum)) threshold (/ false-positive-cost (+ false-negative-cost false-positive-cost)) yhat (fn yhat ^double [datum] (if (< (.invokePrim prob datum) threshold) 0.0 1.0))] (z/mapc #(tree/check-mincount options %) (taiga/terms forest)) (test/is (= (mapv taiga/node-height (taiga/terms forest)) [4 4 3 4 3 4 3 4 3 3 4 3 5 3 3 4 4 3 4 3 3 3 4 4 4 5 4 5 3 4 4 4 4 4 5 4 4 4 4 5 4 4 4 4 4 4 4 3 4 2 3 4 4 3 4 3 4 5 4 4 4 3 3 3 3 3 4 3 4 3 4 3 3 4 3 3 4 3 3 4 3 3 4 4 4 4 5 3 4 4 4 3 4 4 3 4 4 3 4 4 3 4 4 3 4 4 4 4 3 4 4 4 3 3 3 4 3 4 4 3 3 4 3 3 4 4 3 3 4 5 4 3 3 4 4 3 4 4 4 4 4 4 3 4 3 3 4 4 4 3 4 3 3 4 4 5 4 3 3 4 4 4 3 3 3 4 3 4 4 3 4 3 4 4 3 4 4 3 4 3 5 4 3 4 4 3 4 3 4 4 3 4 3 4 3 3 4 3 4 4 4 3 3 5 4 4 3 3 4 3 4 3 3 4 3 4 4 3 4 4 3 4 4 3 3 3 3 3 4 4 4 4 3 3 4 3 3 3 3 4 3 3 4 3 4 5 3 3 5 4 3 4 4 5 3 3 3 4 4 4 4 4 4 3 3 4 3 4 4 3 4 5 3 5 3 3 4 3 4 3 3 4 3 4 4 4 3 4 5 4 4 4 4 3 4 3 4 3 3 4 3 3 4 4 4 4 3 3 5 4 4 3 5 4 4 3 3 4 4 3 4 3 3 4 4 3 4 3 4 5 4 4 4 4 4 4 3 3 3 3 3 4 4 4 5 3 3 3 3 4 3 3 3 4 4 4 4 3 4 3 4 5 4 4 5 4 4 4 4 4 3 4 3 4 4 3 4 3 3 4 4 3 3 4 3 3 4 4 4 4 4 3 3 4 4 4 4 5 4 3 5 4 4 3 5 3 4 3 4 3 4 5 3 4 3 4 3 4 3 3 3 4 5 5 3 3 3 4 4 4 4 3 4 3 4 3 3 5 3 4 4 4 3 4 4 4 3 4 3 3 3 4 4 3 3 3 3 4 4 4 4 5 3 3 3 4 3 4 4 3 4 3 4 4 3 4 3 4 3 4 4 4 4 4 4 3 3 3 4 2 3 4 5 4 3 3 4 5 3 4 4 4 5 3 4 3 4 4 3 3 4 4] )) (test/is (= (mapv taiga/count-children (taiga/terms forest)) [7 7 5 7 5 7 5 7 5 5 7 5 9 7 5 7 7 5 7 5 5 5 7 7 7 9 7 9 5 7 7 7 7 7 11 7 7 9 7 9 7 7 7 7 7 7 7 5 7 3 5 7 7 5 7 7 9 9 7 7 7 5 5 5 5 5 7 5 7 5 7 5 5 9 5 5 7 5 5 7 5 5 7 7 7 7 9 5 7 7 7 5 7 7 5 7 7 5 7 7 7 7 7 5 7 7 7 7 7 7 7 7 5 5 5 7 5 7 7 5 5 7 7 5 7 7 5 5 7 9 7 5 7 7 7 5 7 7 7 7 7 7 5 9 7 5 7 7 7 5 7 5 5 7 7 9 7 5 5 7 7 7 5 5 5 7 5 7 7 5 7 5 7 7 5 7 7 5 7 5 9 9 5 7 7 5 7 5 7 9 5 7 5 7 5 5 7 5 7 7 7 5 5 9 7 7 5 7 7 5 7 5 5 7 5 7 7 5 7 7 7 7 7 5 5 5 5 7 7 7 7 9 5 5 7 5 5 5 5 7 5 5 9 5 7 9 5 5 9 7 5 7 7 9 7 5 5 7 7 7 7 7 7 5 5 7 5 7 7 5 9 9 5 9 5 5 7 5 7 5 5 7 5 7 7 7 5 7 9 7 7 9 7 5 7 5 7 5 5 7 5 5 7 7 7 7 5 5 9 7 7 5 9 7 7 5 5 7 7 5 7 5 5 7 7 5 7 5 7 9 7 7 7 7 7 9 5 5 5 5 5 9 7 7 9 5 5 5 5 7 5 5 5 7 7 7 7 5 7 5 7 9 7 7 9 7 7 7 7 7 5 7 5 7 7 5 7 5 5 7 7 5 5 7 5 5 7 7 7 7 7 5 5 7 9 7 7 9 9 5 9 7 7 5 9 5 7 5 7 5 7 9 5 7 5 9 5 7 5 5 5 7 9 9 5 5 5 7 7 9 7 5 7 5 7 5 5 9 5 7 7 7 5 7 7 7 5 7 5 5 5 7 7 5 5 5 5 7 7 7 7 9 5 5 5 7 7 7 7 5 7 5 7 7 5 7 5 7 5 7 7 7 7 7 7 7 5 5 7 3 5 9 9 7 5 5 7 9 5 7 7 7 9 5 9 5 7 7 5 5 7 7] )) (test/is (= (mapv taiga/count-leaves (taiga/terms forest)) [4 4 3 4 3 4 3 4 3 3 4 3 5 4 3 4 4 3 4 3 3 3 4 4 4 5 4 5 3 4 4 4 4 4 6 4 4 5 4 5 4 4 4 4 4 4 4 3 4 2 3 4 4 3 4 4 5 5 4 4 4 3 3 3 3 3 4 3 4 3 4 3 3 5 3 3 4 3 3 4 3 3 4 4 4 4 5 3 4 4 4 3 4 4 3 4 4 3 4 4 4 4 4 3 4 4 4 4 4 4 4 4 3 3 3 4 3 4 4 3 3 4 4 3 4 4 3 3 4 5 4 3 4 4 4 3 4 4 4 4 4 4 3 5 4 3 4 4 4 3 4 3 3 4 4 5 4 3 3 4 4 4 3 3 3 4 3 4 4 3 4 3 4 4 3 4 4 3 4 3 5 5 3 4 4 3 4 3 4 5 3 4 3 4 3 3 4 3 4 4 4 3 3 5 4 4 3 4 4 3 4 3 3 4 3 4 4 3 4 4 4 4 4 3 3 3 3 4 4 4 4 5 3 3 4 3 3 3 3 4 3 3 5 3 4 5 3 3 5 4 3 4 4 5 4 3 3 4 4 4 4 4 4 3 3 4 3 4 4 3 5 5 3 5 3 3 4 3 4 3 3 4 3 4 4 4 3 4 5 4 4 5 4 3 4 3 4 3 3 4 3 3 4 4 4 4 3 3 5 4 4 3 5 4 4 3 3 4 4 3 4 3 3 4 4 3 4 3 4 5 4 4 4 4 4 5 3 3 3 3 3 5 4 4 5 3 3 3 3 4 3 3 3 4 4 4 4 3 4 3 4 5 4 4 5 4 4 4 4 4 3 4 3 4 4 3 4 3 3 4 4 3 3 4 3 3 4 4 4 4 4 3 3 4 5 4 4 5 5 3 5 4 4 3 5 3 4 3 4 3 4 5 3 4 3 5 3 4 3 3 3 4 5 5 3 3 3 4 4 5 4 3 4 3 4 3 3 5 3 4 4 4 3 4 4 4 3 4 3 3 3 4 4 3 3 3 3 4 4 4 4 5 3 3 3 4 4 4 4 3 4 3 4 4 3 4 3 4 3 4 4 4 4 4 4 4 3 3 4 2 3 5 5 4 3 3 4 5 3 4 4 4 5 3 5 3 4 4 3 3 4 4 ] )) (defs/serialization-test nss options forest) (test/is (= [0 0 50 50] (defs/print-confusion y yhat (:data options)))))) ;;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI" :date "2016-11-08" :doc "Iris data probability forest example." } taiga.test.classify.iris.mincount (:require [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.tree :as tree] [taiga.test.classify.data.defs :as defs] [taiga.test.classify.iris.record :as record] [taiga.test.classify.iris.iris :as iris])) ;; mvn -Dtest=taiga.test.classify.iris.mincount clojure:test > tests.txt ;;------------------------------------------------------------------------------ (def nss (str *ns*)) (test/deftest iris-mincount (z/reset-mersenne-twister-seeds) (let [options (iris/options) options (assoc options :mincount 15) false-negative-cost 999.0 false-positive-cost 1.0 ^clojure.lang.IFn$OD y (:ground-truth record/attributes) weight (fn weight ^double [datum] (if (== 1.0 (.invokePrim y datum)) false-negative-cost false-positive-cost)) options (assoc options :weight weight) predictors (into (sorted-map) (dissoc record/attributes :ground-truth :prediction)) forest (taiga/majority-vote-probability options) ^clojure.lang.IFn$OD prob (fn prob ^double [datum] (.invokePrim forest predictors datum)) threshold (/ false-positive-cost (+ false-negative-cost false-positive-cost)) yhat (fn yhat ^double [datum] (if (< (.invokePrim prob datum) threshold) 0.0 1.0))] (z/mapc #(tree/check-mincount options %) (taiga/terms forest)) (test/is (= (mapv taiga/node-height (taiga/terms forest)) [4 4 3 4 3 4 3 4 3 3 4 3 5 3 3 4 4 3 4 3 3 3 4 4 4 5 4 5 3 4 4 4 4 4 5 4 4 4 4 5 4 4 4 4 4 4 4 3 4 2 3 4 4 3 4 3 4 5 4 4 4 3 3 3 3 3 4 3 4 3 4 3 3 4 3 3 4 3 3 4 3 3 4 4 4 4 5 3 4 4 4 3 4 4 3 4 4 3 4 4 3 4 4 3 4 4 4 4 3 4 4 4 3 3 3 4 3 4 4 3 3 4 3 3 4 4 3 3 4 5 4 3 3 4 4 3 4 4 4 4 4 4 3 4 3 3 4 4 4 3 4 3 3 4 4 5 4 3 3 4 4 4 3 3 3 4 3 4 4 3 4 3 4 4 3 4 4 3 4 3 5 4 3 4 4 3 4 3 4 4 3 4 3 4 3 3 4 3 4 4 4 3 3 5 4 4 3 3 4 3 4 3 3 4 3 4 4 3 4 4 3 4 4 3 3 3 3 3 4 4 4 4 3 3 4 3 3 3 3 4 3 3 4 3 4 5 3 3 5 4 3 4 4 5 3 3 3 4 4 4 4 4 4 3 3 4 3 4 4 3 4 5 3 5 3 3 4 3 4 3 3 4 3 4 4 4 3 4 5 4 4 4 4 3 4 3 4 3 3 4 3 3 4 4 4 4 3 3 5 4 4 3 5 4 4 3 3 4 4 3 4 3 3 4 4 3 4 3 4 5 4 4 4 4 4 4 3 3 3 3 3 4 4 4 5 3 3 3 3 4 3 3 3 4 4 4 4 3 4 3 4 5 4 4 5 4 4 4 4 4 3 4 3 4 4 3 4 3 3 4 4 3 3 4 3 3 4 4 4 4 4 3 3 4 4 4 4 5 4 3 5 4 4 3 5 3 4 3 4 3 4 5 3 4 3 4 3 4 3 3 3 4 5 5 3 3 3 4 4 4 4 3 4 3 4 3 3 5 3 4 4 4 3 4 4 4 3 4 3 3 3 4 4 3 3 3 3 4 4 4 4 5 3 3 3 4 3 4 4 3 4 3 4 4 3 4 3 4 3 4 4 4 4 4 4 3 3 3 4 2 3 4 5 4 3 3 4 5 3 4 4 4 5 3 4 3 4 4 3 3 4 4] )) (test/is (= (mapv taiga/count-children (taiga/terms forest)) [7 7 5 7 5 7 5 7 5 5 7 5 9 7 5 7 7 5 7 5 5 5 7 7 7 9 7 9 5 7 7 7 7 7 11 7 7 9 7 9 7 7 7 7 7 7 7 5 7 3 5 7 7 5 7 7 9 9 7 7 7 5 5 5 5 5 7 5 7 5 7 5 5 9 5 5 7 5 5 7 5 5 7 7 7 7 9 5 7 7 7 5 7 7 5 7 7 5 7 7 7 7 7 5 7 7 7 7 7 7 7 7 5 5 5 7 5 7 7 5 5 7 7 5 7 7 5 5 7 9 7 5 7 7 7 5 7 7 7 7 7 7 5 9 7 5 7 7 7 5 7 5 5 7 7 9 7 5 5 7 7 7 5 5 5 7 5 7 7 5 7 5 7 7 5 7 7 5 7 5 9 9 5 7 7 5 7 5 7 9 5 7 5 7 5 5 7 5 7 7 7 5 5 9 7 7 5 7 7 5 7 5 5 7 5 7 7 5 7 7 7 7 7 5 5 5 5 7 7 7 7 9 5 5 7 5 5 5 5 7 5 5 9 5 7 9 5 5 9 7 5 7 7 9 7 5 5 7 7 7 7 7 7 5 5 7 5 7 7 5 9 9 5 9 5 5 7 5 7 5 5 7 5 7 7 7 5 7 9 7 7 9 7 5 7 5 7 5 5 7 5 5 7 7 7 7 5 5 9 7 7 5 9 7 7 5 5 7 7 5 7 5 5 7 7 5 7 5 7 9 7 7 7 7 7 9 5 5 5 5 5 9 7 7 9 5 5 5 5 7 5 5 5 7 7 7 7 5 7 5 7 9 7 7 9 7 7 7 7 7 5 7 5 7 7 5 7 5 5 7 7 5 5 7 5 5 7 7 7 7 7 5 5 7 9 7 7 9 9 5 9 7 7 5 9 5 7 5 7 5 7 9 5 7 5 9 5 7 5 5 5 7 9 9 5 5 5 7 7 9 7 5 7 5 7 5 5 9 5 7 7 7 5 7 7 7 5 7 5 5 5 7 7 5 5 5 5 7 7 7 7 9 5 5 5 7 7 7 7 5 7 5 7 7 5 7 5 7 5 7 7 7 7 7 7 7 5 5 7 3 5 9 9 7 5 5 7 9 5 7 7 7 9 5 9 5 7 7 5 5 7 7] )) (test/is (= (mapv taiga/count-leaves (taiga/terms forest)) [4 4 3 4 3 4 3 4 3 3 4 3 5 4 3 4 4 3 4 3 3 3 4 4 4 5 4 5 3 4 4 4 4 4 6 4 4 5 4 5 4 4 4 4 4 4 4 3 4 2 3 4 4 3 4 4 5 5 4 4 4 3 3 3 3 3 4 3 4 3 4 3 3 5 3 3 4 3 3 4 3 3 4 4 4 4 5 3 4 4 4 3 4 4 3 4 4 3 4 4 4 4 4 3 4 4 4 4 4 4 4 4 3 3 3 4 3 4 4 3 3 4 4 3 4 4 3 3 4 5 4 3 4 4 4 3 4 4 4 4 4 4 3 5 4 3 4 4 4 3 4 3 3 4 4 5 4 3 3 4 4 4 3 3 3 4 3 4 4 3 4 3 4 4 3 4 4 3 4 3 5 5 3 4 4 3 4 3 4 5 3 4 3 4 3 3 4 3 4 4 4 3 3 5 4 4 3 4 4 3 4 3 3 4 3 4 4 3 4 4 4 4 4 3 3 3 3 4 4 4 4 5 3 3 4 3 3 3 3 4 3 3 5 3 4 5 3 3 5 4 3 4 4 5 4 3 3 4 4 4 4 4 4 3 3 4 3 4 4 3 5 5 3 5 3 3 4 3 4 3 3 4 3 4 4 4 3 4 5 4 4 5 4 3 4 3 4 3 3 4 3 3 4 4 4 4 3 3 5 4 4 3 5 4 4 3 3 4 4 3 4 3 3 4 4 3 4 3 4 5 4 4 4 4 4 5 3 3 3 3 3 5 4 4 5 3 3 3 3 4 3 3 3 4 4 4 4 3 4 3 4 5 4 4 5 4 4 4 4 4 3 4 3 4 4 3 4 3 3 4 4 3 3 4 3 3 4 4 4 4 4 3 3 4 5 4 4 5 5 3 5 4 4 3 5 3 4 3 4 3 4 5 3 4 3 5 3 4 3 3 3 4 5 5 3 3 3 4 4 5 4 3 4 3 4 3 3 5 3 4 4 4 3 4 4 4 3 4 3 3 3 4 4 3 3 3 3 4 4 4 4 5 3 3 3 4 4 4 4 3 4 3 4 4 3 4 3 4 3 4 4 4 4 4 4 4 3 3 4 2 3 5 5 4 3 3 4 5 3 4 4 4 5 3 5 3 4 4 3 3 4 4 ] )) (defs/serialization-test nss options forest) (test/is (= [0 0 50 50] (defs/print-confusion y yhat (:data options)))))) ;;------------------------------------------------------------------------------
[ { "context": "est test-create-user\n (if (user/get-user \"test_user42\")\n (user/delete-user (user/get-user \"te", "end": 811, "score": 0.992453932762146, "start": 800, "tag": "USERNAME", "value": "test_user42" }, { "context": "42\")\n (user/delete-user (user/get-user \"test_user42\")))\n (is (= \"test_user42\" (:name (user/c", "end": 870, "score": 0.9911653399467468, "start": 859, "tag": "USERNAME", "value": "test_user42" }, { "context": " (user/get-user \"test_user42\")))\n (is (= \"test_user42\" (:name (user/create-user \"test_user42\" \"123\" [\"", "end": 903, "score": 0.9898115992546082, "start": 892, "tag": "USERNAME", "value": "test_user42" }, { "context": " (is (= \"test_user42\" (:name (user/create-user \"test_user42\" \"123\" [\"user\"]))))\n (is (= \"test_user42@", "end": 943, "score": 0.9950704574584961, "start": 932, "tag": "USERNAME", "value": "test_user42" }, { "context": "42@somewhere\" (:name (user/create-user \"test_user42@somewhere\" \"123\" [\"user\"]))))\n (is (user", "end": 1041, "score": 0.7033187747001648, "start": 1040, "tag": "USERNAME", "value": "4" }, { "context": "23\" [\"user\"]))))\n (is (user/authenticate \"test_user42\" \"123\"))\n (is (user/authenticate \"test_us", "end": 1117, "score": 0.9958837628364563, "start": 1106, "tag": "USERNAME", "value": "test_user42" }, { "context": " \"123\"))\n (is (false? (user/authenticate \"test_user42\" \"1234\")))\n (is (= \"test_user42\" (:name (", "end": 1243, "score": 0.9958483576774597, "start": 1232, "tag": "USERNAME", "value": "test_user42" }, { "context": "enticate \"test_user42\" \"1234\")))\n (is (= \"test_user42\" (:name (user/set-password \"test_user42\" \"1234\"))", "end": 1283, "score": 0.9863346815109253, "start": 1272, "tag": "USERNAME", "value": "test_user42" }, { "context": " (is (= \"test_user42\" (:name (user/set-password \"test_user42\" \"1234\"))))\n (is (user/authenticate \"test", "end": 1323, "score": 0.9969528913497925, "start": 1312, "tag": "PASSWORD", "value": "test_user42" }, { "context": "_user42\" (:name (user/set-password \"test_user42\" \"1234\"))))\n (is (user/authenticate \"test_user42", "end": 1330, "score": 0.962599515914917, "start": 1326, "tag": "PASSWORD", "value": "1234" }, { "context": "er42\" \"1234\"))))\n (is (user/authenticate \"test_user42\" \"1234\"))\n (user/delete-user (user/get-us", "end": 1380, "score": 0.9960871934890747, "start": 1369, "tag": "USERNAME", "value": "test_user42" }, { "context": "234\"))\n (user/delete-user (user/get-user \"test_user42\"))\n (user/delete-user (user/get-user \"tes", "end": 1445, "score": 0.9952231645584106, "start": 1434, "tag": "USERNAME", "value": "test_user42" }, { "context": "portant\"]}\n :readers {:names [\"joe\"]}}]\n (with-test-db\n (do\n ", "end": 1640, "score": 0.9996230602264404, "start": 1637, "tag": "NAME", "value": "joe" } ]
test/joiner/test/core.clj
jalpedersen/couch-joiner
0
(ns joiner.test.core (:require [joiner.core :as core] [joiner.admin :as admin] [joiner.design :as design] [joiner.user :as user] [joiner.resource :as resource] [joiner.utils :as utils] [joiner.search :as search] [joiner.ring :as ring] [com.ashafa.clutch :as clutch] [com.ashafa.clutch.http-client :as http] [cheshire.core :as json] [joiner.main] :reload-all) (:use clojure.test)) (def testdb "joiner_testdb") (defmacro with-test-db [body] `(let [db# (clutch/get-database-with-db (core/authenticated-database testdb))] (try (~@body) (finally (clutch/delete-database-with-db db#))))) (deftest test-create-user (if (user/get-user "test_user42") (user/delete-user (user/get-user "test_user42"))) (is (= "test_user42" (:name (user/create-user "test_user42" "123" ["user"])))) (is (= "test_user42@somewhere" (:name (user/create-user "test_user42@somewhere" "123" ["user"])))) (is (user/authenticate "test_user42" "123")) (is (user/authenticate "test_user42@somewhere" "123")) (is (false? (user/authenticate "test_user42" "1234"))) (is (= "test_user42" (:name (user/set-password "test_user42" "1234")))) (is (user/authenticate "test_user42" "1234")) (user/delete-user (user/get-user "test_user42")) (user/delete-user (user/get-user "test_user42@somewhere"))) (deftest test-set-security (let [acl {:admins {:roles ["important"]} :readers {:names ["joe"]}}] (with-test-db (do (clutch/with-db (core/authenticated-database testdb) (is (:ok (admin/security acl))) (is (= acl (admin/security)))))))) (deftest test-util (with-test-db (do (is (= 1 (count (utils/uuids)))) (is (= 42 (count (utils/uuids 42))))))) (deftest test-error-handling (with-test-db (let [response (utils/catch-couchdb-exceptions (core/with-authenticated-db "_bad-name" (http/couchdb-request :get (core/authenticated-database testdb))))] (is (= 400 (:status response))) (let [json-resp (json/parse-string (:body response) true)] (is (= "illegal_database_name" (:error json-resp))))))) (deftest test-design (with-test-db (core/with-authenticated-db testdb (admin/security {:admins {:roles ["_admin"]} :readers {:roles ["_admin"]}}) (design/update-views "testing" "test-view") (is (= 1 (count (:views (clutch/get-document "_design/testing"))))) (design/update-views "testing" "test-view" "another-view") (is (= 2 (count (:views (clutch/get-document "_design/testing"))))))))
78819
(ns joiner.test.core (:require [joiner.core :as core] [joiner.admin :as admin] [joiner.design :as design] [joiner.user :as user] [joiner.resource :as resource] [joiner.utils :as utils] [joiner.search :as search] [joiner.ring :as ring] [com.ashafa.clutch :as clutch] [com.ashafa.clutch.http-client :as http] [cheshire.core :as json] [joiner.main] :reload-all) (:use clojure.test)) (def testdb "joiner_testdb") (defmacro with-test-db [body] `(let [db# (clutch/get-database-with-db (core/authenticated-database testdb))] (try (~@body) (finally (clutch/delete-database-with-db db#))))) (deftest test-create-user (if (user/get-user "test_user42") (user/delete-user (user/get-user "test_user42"))) (is (= "test_user42" (:name (user/create-user "test_user42" "123" ["user"])))) (is (= "test_user42@somewhere" (:name (user/create-user "test_user42@somewhere" "123" ["user"])))) (is (user/authenticate "test_user42" "123")) (is (user/authenticate "test_user42@somewhere" "123")) (is (false? (user/authenticate "test_user42" "1234"))) (is (= "test_user42" (:name (user/set-password "<PASSWORD>" "<PASSWORD>")))) (is (user/authenticate "test_user42" "1234")) (user/delete-user (user/get-user "test_user42")) (user/delete-user (user/get-user "test_user42@somewhere"))) (deftest test-set-security (let [acl {:admins {:roles ["important"]} :readers {:names ["<NAME>"]}}] (with-test-db (do (clutch/with-db (core/authenticated-database testdb) (is (:ok (admin/security acl))) (is (= acl (admin/security)))))))) (deftest test-util (with-test-db (do (is (= 1 (count (utils/uuids)))) (is (= 42 (count (utils/uuids 42))))))) (deftest test-error-handling (with-test-db (let [response (utils/catch-couchdb-exceptions (core/with-authenticated-db "_bad-name" (http/couchdb-request :get (core/authenticated-database testdb))))] (is (= 400 (:status response))) (let [json-resp (json/parse-string (:body response) true)] (is (= "illegal_database_name" (:error json-resp))))))) (deftest test-design (with-test-db (core/with-authenticated-db testdb (admin/security {:admins {:roles ["_admin"]} :readers {:roles ["_admin"]}}) (design/update-views "testing" "test-view") (is (= 1 (count (:views (clutch/get-document "_design/testing"))))) (design/update-views "testing" "test-view" "another-view") (is (= 2 (count (:views (clutch/get-document "_design/testing"))))))))
true
(ns joiner.test.core (:require [joiner.core :as core] [joiner.admin :as admin] [joiner.design :as design] [joiner.user :as user] [joiner.resource :as resource] [joiner.utils :as utils] [joiner.search :as search] [joiner.ring :as ring] [com.ashafa.clutch :as clutch] [com.ashafa.clutch.http-client :as http] [cheshire.core :as json] [joiner.main] :reload-all) (:use clojure.test)) (def testdb "joiner_testdb") (defmacro with-test-db [body] `(let [db# (clutch/get-database-with-db (core/authenticated-database testdb))] (try (~@body) (finally (clutch/delete-database-with-db db#))))) (deftest test-create-user (if (user/get-user "test_user42") (user/delete-user (user/get-user "test_user42"))) (is (= "test_user42" (:name (user/create-user "test_user42" "123" ["user"])))) (is (= "test_user42@somewhere" (:name (user/create-user "test_user42@somewhere" "123" ["user"])))) (is (user/authenticate "test_user42" "123")) (is (user/authenticate "test_user42@somewhere" "123")) (is (false? (user/authenticate "test_user42" "1234"))) (is (= "test_user42" (:name (user/set-password "PI:PASSWORD:<PASSWORD>END_PI" "PI:PASSWORD:<PASSWORD>END_PI")))) (is (user/authenticate "test_user42" "1234")) (user/delete-user (user/get-user "test_user42")) (user/delete-user (user/get-user "test_user42@somewhere"))) (deftest test-set-security (let [acl {:admins {:roles ["important"]} :readers {:names ["PI:NAME:<NAME>END_PI"]}}] (with-test-db (do (clutch/with-db (core/authenticated-database testdb) (is (:ok (admin/security acl))) (is (= acl (admin/security)))))))) (deftest test-util (with-test-db (do (is (= 1 (count (utils/uuids)))) (is (= 42 (count (utils/uuids 42))))))) (deftest test-error-handling (with-test-db (let [response (utils/catch-couchdb-exceptions (core/with-authenticated-db "_bad-name" (http/couchdb-request :get (core/authenticated-database testdb))))] (is (= 400 (:status response))) (let [json-resp (json/parse-string (:body response) true)] (is (= "illegal_database_name" (:error json-resp))))))) (deftest test-design (with-test-db (core/with-authenticated-db testdb (admin/security {:admins {:roles ["_admin"]} :readers {:roles ["_admin"]}}) (design/update-views "testing" "test-view") (is (= 1 (count (:views (clutch/get-document "_design/testing"))))) (design/update-views "testing" "test-view" "another-view") (is (= 2 (count (:views (clutch/get-document "_design/testing"))))))))
[ { "context": ";;;;;;;;;;;;;;;;;;;;;;;;\n;; core.async snippets\n;; Ed Sumitra\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n;; type the follow", "end": 66, "score": 0.9998669624328613, "start": 56, "tag": "NAME", "value": "Ed Sumitra" } ]
src/reagent_webapp/async.cljs
boston-clojure/reagent-webapp
3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; core.async snippets ;; Ed Sumitra ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; type the following in figwheel clojurescript repl ;; required libraries and macros (require '[cljs.core.async :as async]) (require-macros '[cljs.core.async.macros :refer [go go-loop]]) (enable-console-print!) ;;; ------------------------ ;;; minimal core.async intro ;;; ------------------------ ;; create a chan (def chan-atest (async/chan)) ;; put a message into the channel (go (async/>! chan-atest "hello bosclj 1")) ;; take a message from the channel (go (println (async/<! chan-atest))) ;; keep printing messages in channel (go-loop [] (println (async/<! chan-atest)) (recur)) ;;; -------------------------------- ;;; create a repl event subscription ;;; -------------------------------- (in-ns 'reagent-bosclj.events) (def chan-repl-logger (async/chan)) (async/sub *event-que* :new-ui-task chan-repl-logger) (go-loop [] (println "repl log:" (async/<! chan-repl-logger)) (recur))
116271
;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; core.async snippets ;; <NAME> ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; type the following in figwheel clojurescript repl ;; required libraries and macros (require '[cljs.core.async :as async]) (require-macros '[cljs.core.async.macros :refer [go go-loop]]) (enable-console-print!) ;;; ------------------------ ;;; minimal core.async intro ;;; ------------------------ ;; create a chan (def chan-atest (async/chan)) ;; put a message into the channel (go (async/>! chan-atest "hello bosclj 1")) ;; take a message from the channel (go (println (async/<! chan-atest))) ;; keep printing messages in channel (go-loop [] (println (async/<! chan-atest)) (recur)) ;;; -------------------------------- ;;; create a repl event subscription ;;; -------------------------------- (in-ns 'reagent-bosclj.events) (def chan-repl-logger (async/chan)) (async/sub *event-que* :new-ui-task chan-repl-logger) (go-loop [] (println "repl log:" (async/<! chan-repl-logger)) (recur))
true
;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; core.async snippets ;; PI:NAME:<NAME>END_PI ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; type the following in figwheel clojurescript repl ;; required libraries and macros (require '[cljs.core.async :as async]) (require-macros '[cljs.core.async.macros :refer [go go-loop]]) (enable-console-print!) ;;; ------------------------ ;;; minimal core.async intro ;;; ------------------------ ;; create a chan (def chan-atest (async/chan)) ;; put a message into the channel (go (async/>! chan-atest "hello bosclj 1")) ;; take a message from the channel (go (println (async/<! chan-atest))) ;; keep printing messages in channel (go-loop [] (println (async/<! chan-atest)) (recur)) ;;; -------------------------------- ;;; create a repl event subscription ;;; -------------------------------- (in-ns 'reagent-bosclj.events) (def chan-repl-logger (async/chan)) (async/sub *event-que* :new-ui-task chan-repl-logger) (go-loop [] (println "repl log:" (async/<! chan-repl-logger)) (recur))
[ { "context": "id3.basics-util :as util]\n ))\n\n(def cursor-key :b03-add-element-on-top)\n\n(def height 100)\n(def width 100)\n\n(defn example", "end": 191, "score": 0.9061684012413025, "start": 169, "tag": "KEY", "value": "b03-add-element-on-top" } ]
src/basics/rid3/b03_add_element_on_top.cljs
ryanechternacht/rid3
153
(ns rid3.b03-add-element-on-top (:require [reagent.core :as reagent] [rid3.core :as rid3 :refer [rid3->]] [rid3.basics-util :as util] )) (def cursor-key :b03-add-element-on-top) (def height 100) (def width 100) (defn example [app-state] (let [viz-ratom (reagent/cursor app-state [cursor-key])] (fn [app-state] [:div [:h4 "3) Add an element on top of another element: a circle on a rect"] [util/link-source (name cursor-key)] [rid3/viz {:id "b03" :ratom viz-ratom :svg {:did-mount (fn [node ratom] (rid3-> node {:height height :width width}))} :pieces [{:kind :elem :class "some-element" :tag "rect" :did-mount (fn [node ratom] (rid3-> node {:x 0 :y 0 :height height :width width :fill "lightgrey"}))} ;; You can add any number of elements. They are added in ;; order, which means this circle overlaid on top of the ;; rect above." {:kind :elem :class "some-element-on-top" :tag "circle" :did-mount (fn [node ratom] (rid3-> node {:cx (/ width 2) :cy (/ height 2) :r 20 :fill "green"}))} ]}]])))
40822
(ns rid3.b03-add-element-on-top (:require [reagent.core :as reagent] [rid3.core :as rid3 :refer [rid3->]] [rid3.basics-util :as util] )) (def cursor-key :<KEY>) (def height 100) (def width 100) (defn example [app-state] (let [viz-ratom (reagent/cursor app-state [cursor-key])] (fn [app-state] [:div [:h4 "3) Add an element on top of another element: a circle on a rect"] [util/link-source (name cursor-key)] [rid3/viz {:id "b03" :ratom viz-ratom :svg {:did-mount (fn [node ratom] (rid3-> node {:height height :width width}))} :pieces [{:kind :elem :class "some-element" :tag "rect" :did-mount (fn [node ratom] (rid3-> node {:x 0 :y 0 :height height :width width :fill "lightgrey"}))} ;; You can add any number of elements. They are added in ;; order, which means this circle overlaid on top of the ;; rect above." {:kind :elem :class "some-element-on-top" :tag "circle" :did-mount (fn [node ratom] (rid3-> node {:cx (/ width 2) :cy (/ height 2) :r 20 :fill "green"}))} ]}]])))
true
(ns rid3.b03-add-element-on-top (:require [reagent.core :as reagent] [rid3.core :as rid3 :refer [rid3->]] [rid3.basics-util :as util] )) (def cursor-key :PI:KEY:<KEY>END_PI) (def height 100) (def width 100) (defn example [app-state] (let [viz-ratom (reagent/cursor app-state [cursor-key])] (fn [app-state] [:div [:h4 "3) Add an element on top of another element: a circle on a rect"] [util/link-source (name cursor-key)] [rid3/viz {:id "b03" :ratom viz-ratom :svg {:did-mount (fn [node ratom] (rid3-> node {:height height :width width}))} :pieces [{:kind :elem :class "some-element" :tag "rect" :did-mount (fn [node ratom] (rid3-> node {:x 0 :y 0 :height height :width width :fill "lightgrey"}))} ;; You can add any number of elements. They are added in ;; order, which means this circle overlaid on top of the ;; rect above." {:kind :elem :class "some-element-on-top" :tag "circle" :did-mount (fn [node ratom] (rid3-> node {:cx (/ width 2) :cy (/ height 2) :r 20 :fill "green"}))} ]}]])))
[ { "context": " definition.\n(defn hie\n [person message]\n (str \"Hie, \" person \" : \" message))\n\n;; What does it look l", "end": 5570, "score": 0.8855299353599548, "start": 5567, "tag": "NAME", "value": "Hie" }, { "context": " [4]\n(defn hie [person message] (str \"Hie, \" person \" : \" message)) ; [5]\n;; Where:\n;; - [1", "end": 5759, "score": 0.8860898017883301, "start": 5756, "tag": "NAME", "value": "Hie" } ]
src/clojure_by_example/ex00_introduction.clj
paprbackwritr/clojure-by-example
0
(ns clojure-by-example.ex00-introduction) ;; IMPORTANT: ;; - The README file explains why this project exists. ;; - Begin in this "ex00..." file, and work through it step by step. ;; - Once you are done with "ex00...", open the next file and repeat. ;; - Keep going this way, until you have worked through all the files. ;; EX00: LESSON GOAL: ;; - A very quick intro to Clojure syntax, just to familiarize your ;; eyes with it. ;; ;; - Don't get stuck here! ;; - Run through it once, try evaluating expressions of interest ;; and move on to EX01. ;; - Your eyes and brain will adjust fairly quickly, as you ;; work through the examples to follow. ;; Clojure is a "Lisp" ;; - Lisp is short for List Processing ;; - It's just another way to design a programming language ;; (Ignore "But, Why?" for now... Just use it as it is, and try to ;; do something practical with it.) ;; Clojure code is composed of "expressions": ;; These literal values are Clojure "expressions" "hello" ; strings :hello ; keywords 'hello ; symbols 42 ; numbers 22/7 ; fractional numbers ;; "Built-in" functions are also "expressions" ;; - We will meet all of these again, very soon. + ; addition map ; map over a collection filter ; filter from a collection reduce ; transform a collection ;; Collection "literals" are expressions too: ;; - We will extensively use such "collection" data structures. [1 2 3 4 5] ; a vector {:a 1 :b 2} ; a hash-map #{1 2 3 4 5} ; a hash-set '(1 2 3 4 5) ; a list ;; Clojure code is also composed of expressions; ;; - we refer to them as "symbolic" expressions (or "s"-expression) (+ 1 2) ; an s-expression (+ (+ 1 2) (+ 1 2)) ; an s-expression of nested expressions (+ (+ (+ 1 2) (+ 1 2)) (+ (+ 1 2) (+ 1 2))) ; an even more nested s-expression ;; In fact, ALL Clojure code is just "expressions" ;; - And, all Clojure expressions evaluate to a value. ;; ;; - All literals evaluate to themselves. They are values. ;; (Hence "literal": a literal is what it is. :-D) ;; ;; - All collection literals also evaluate to themselves. ;; (A literal collection is what it is, too.) ;; ;; - All functions are values. ;; (More on this a little later) ;; ;; - All s-expressions, however deeply nested, finally evaluate ;; to a return value. Expressions evaluate to either a literal, ;; or a collection, or a function. ;; Clojure expression syntax rules: ;; ;; - Literals: ;; - Just write them down ;; ;; - Collection Literals: ;; - Just write them down too, but also ;; - make sure opening brackets are always matched by closing brackets ;; [1 2 3] is a well-formed vector representation ;; [1 2 3 is an "unbalanced" vector and will cause an error. ;; ;; - Symbolic expressions ("s-expressions"): ;; - Make sure the round parentheses close over the intended/required ;; sub-expressions ;; (+ 1 2) is a well-formed expression that will be evaluated ;; (+ 1 2 is an "unbalanced" s-expression and will cause an error. ;; Clojure Code Evaluation Rules: ;; ;; - To instruct Clojure to evaluate a list of expressions, ;; enclose the expressions in round parentheses. ;; - Recall: (+ 1 2) ;; ;; - The very first expression after an opening paren MUST be ;; a function. ;; - So: (1 2) will fail, because 1 is not a function ;; ;; - All expressions or sub-expressions that follow the first expression ;; will first be fully evaluated into values, and then passed to ;; the first expression as arguments. ;; - Recall: (+ (+ (+ 1 2) (+ 1 2)) ;; (+ (+ 1 2) (+ 1 2))) ;; ;; - You may mentally evaluate the above form "inside-out", like this: ;; - Evaluate the smallest and innermost expressions first, ;; - Mentally replace them with their return values ;; - Pass those values as arguments to the next higher expression ;; - Continue until you are left with a literal value. ;; ;; (+ (+ (+ 1 2) (+ 1 2)) ;; (+ (+ 1 2) (+ 1 2))) ;; ;; (+ (+ 3 3 ) ;; (+ 3 3 )) ;; ;; (+ 6 ;; 6) ;; ;; 12 ;; ;; - Keep this evaluation model in mind, when you read Clojure code, ;; to figure out how the code will evaluate. ;; ;; - To prevent evaluation, explicitly mark an expression as a list ;; '(1 2) put a single quote in front of an expression to tell Clojure ;; you don't want it to evaluate that expression. ;; ;; - To comment out in-line comment text, or even an expression, ;; place one or more semi-colons before the text/expression. ;; ;; - `#_` is a clean way to comment out multi-line s-expressions ;; Compare this: #_(+ 1 2 3 4 5 6) ;; With this: ;; (+ 1 2 ;; 3 4 ;; 5 6) ;; Why is Clojure a "List Processing" language? '(+ 1 2) ; Recall: this is a Clojure list, that Clojure evaluates ; as literal data. (+ 1 2) ; if we remove the single quote, Clojure treats the same list ; as an executable list, and tries to evaluate it as code. ;; More generally, Clojure code, like other lisps, is written ;; in terms of its own data structures. For example: ;; ;; Here is a function definition. (defn hie [person message] (str "Hie, " person " : " message)) ;; What does it look like? ;; - Let's flatten it into one line for illustrative purposes: ;;[1] [2] [3] [4] (defn hie [person message] (str "Hie, " person " : " message)) ; [5] ;; Where: ;; - [1] `defn` is a Clojure built-in primitive ;; - Notice, it's at the 1st position, and ;; - 2-4 are all arguments to defn ;; Further: ;; - [2] is a Clojure symbol, `hello`, which will name the function ;; - [3] is a Clojure vector of two named arguments ;; - [4] is a Clojure s-expression, and is treated as the body of ;; the function definition ;; - [5] the whole thing itself is a Clojure s-expression! ;; RECAP: ;; ;; - All Clojure code is a bunch of "expressions" ;; (literals, collections, s-expressions) ;; ;; - All Clojure expressions evaluate to a return value ;; ;; - All Clojure code is written in terms of its own data structures ;; ;; - All opening braces or parentheses must be matched by closing ;; braces or parentheses, to create legal Clojure expressions.
85549
(ns clojure-by-example.ex00-introduction) ;; IMPORTANT: ;; - The README file explains why this project exists. ;; - Begin in this "ex00..." file, and work through it step by step. ;; - Once you are done with "ex00...", open the next file and repeat. ;; - Keep going this way, until you have worked through all the files. ;; EX00: LESSON GOAL: ;; - A very quick intro to Clojure syntax, just to familiarize your ;; eyes with it. ;; ;; - Don't get stuck here! ;; - Run through it once, try evaluating expressions of interest ;; and move on to EX01. ;; - Your eyes and brain will adjust fairly quickly, as you ;; work through the examples to follow. ;; Clojure is a "Lisp" ;; - Lisp is short for List Processing ;; - It's just another way to design a programming language ;; (Ignore "But, Why?" for now... Just use it as it is, and try to ;; do something practical with it.) ;; Clojure code is composed of "expressions": ;; These literal values are Clojure "expressions" "hello" ; strings :hello ; keywords 'hello ; symbols 42 ; numbers 22/7 ; fractional numbers ;; "Built-in" functions are also "expressions" ;; - We will meet all of these again, very soon. + ; addition map ; map over a collection filter ; filter from a collection reduce ; transform a collection ;; Collection "literals" are expressions too: ;; - We will extensively use such "collection" data structures. [1 2 3 4 5] ; a vector {:a 1 :b 2} ; a hash-map #{1 2 3 4 5} ; a hash-set '(1 2 3 4 5) ; a list ;; Clojure code is also composed of expressions; ;; - we refer to them as "symbolic" expressions (or "s"-expression) (+ 1 2) ; an s-expression (+ (+ 1 2) (+ 1 2)) ; an s-expression of nested expressions (+ (+ (+ 1 2) (+ 1 2)) (+ (+ 1 2) (+ 1 2))) ; an even more nested s-expression ;; In fact, ALL Clojure code is just "expressions" ;; - And, all Clojure expressions evaluate to a value. ;; ;; - All literals evaluate to themselves. They are values. ;; (Hence "literal": a literal is what it is. :-D) ;; ;; - All collection literals also evaluate to themselves. ;; (A literal collection is what it is, too.) ;; ;; - All functions are values. ;; (More on this a little later) ;; ;; - All s-expressions, however deeply nested, finally evaluate ;; to a return value. Expressions evaluate to either a literal, ;; or a collection, or a function. ;; Clojure expression syntax rules: ;; ;; - Literals: ;; - Just write them down ;; ;; - Collection Literals: ;; - Just write them down too, but also ;; - make sure opening brackets are always matched by closing brackets ;; [1 2 3] is a well-formed vector representation ;; [1 2 3 is an "unbalanced" vector and will cause an error. ;; ;; - Symbolic expressions ("s-expressions"): ;; - Make sure the round parentheses close over the intended/required ;; sub-expressions ;; (+ 1 2) is a well-formed expression that will be evaluated ;; (+ 1 2 is an "unbalanced" s-expression and will cause an error. ;; Clojure Code Evaluation Rules: ;; ;; - To instruct Clojure to evaluate a list of expressions, ;; enclose the expressions in round parentheses. ;; - Recall: (+ 1 2) ;; ;; - The very first expression after an opening paren MUST be ;; a function. ;; - So: (1 2) will fail, because 1 is not a function ;; ;; - All expressions or sub-expressions that follow the first expression ;; will first be fully evaluated into values, and then passed to ;; the first expression as arguments. ;; - Recall: (+ (+ (+ 1 2) (+ 1 2)) ;; (+ (+ 1 2) (+ 1 2))) ;; ;; - You may mentally evaluate the above form "inside-out", like this: ;; - Evaluate the smallest and innermost expressions first, ;; - Mentally replace them with their return values ;; - Pass those values as arguments to the next higher expression ;; - Continue until you are left with a literal value. ;; ;; (+ (+ (+ 1 2) (+ 1 2)) ;; (+ (+ 1 2) (+ 1 2))) ;; ;; (+ (+ 3 3 ) ;; (+ 3 3 )) ;; ;; (+ 6 ;; 6) ;; ;; 12 ;; ;; - Keep this evaluation model in mind, when you read Clojure code, ;; to figure out how the code will evaluate. ;; ;; - To prevent evaluation, explicitly mark an expression as a list ;; '(1 2) put a single quote in front of an expression to tell Clojure ;; you don't want it to evaluate that expression. ;; ;; - To comment out in-line comment text, or even an expression, ;; place one or more semi-colons before the text/expression. ;; ;; - `#_` is a clean way to comment out multi-line s-expressions ;; Compare this: #_(+ 1 2 3 4 5 6) ;; With this: ;; (+ 1 2 ;; 3 4 ;; 5 6) ;; Why is Clojure a "List Processing" language? '(+ 1 2) ; Recall: this is a Clojure list, that Clojure evaluates ; as literal data. (+ 1 2) ; if we remove the single quote, Clojure treats the same list ; as an executable list, and tries to evaluate it as code. ;; More generally, Clojure code, like other lisps, is written ;; in terms of its own data structures. For example: ;; ;; Here is a function definition. (defn hie [person message] (str "<NAME>, " person " : " message)) ;; What does it look like? ;; - Let's flatten it into one line for illustrative purposes: ;;[1] [2] [3] [4] (defn hie [person message] (str "<NAME>, " person " : " message)) ; [5] ;; Where: ;; - [1] `defn` is a Clojure built-in primitive ;; - Notice, it's at the 1st position, and ;; - 2-4 are all arguments to defn ;; Further: ;; - [2] is a Clojure symbol, `hello`, which will name the function ;; - [3] is a Clojure vector of two named arguments ;; - [4] is a Clojure s-expression, and is treated as the body of ;; the function definition ;; - [5] the whole thing itself is a Clojure s-expression! ;; RECAP: ;; ;; - All Clojure code is a bunch of "expressions" ;; (literals, collections, s-expressions) ;; ;; - All Clojure expressions evaluate to a return value ;; ;; - All Clojure code is written in terms of its own data structures ;; ;; - All opening braces or parentheses must be matched by closing ;; braces or parentheses, to create legal Clojure expressions.
true
(ns clojure-by-example.ex00-introduction) ;; IMPORTANT: ;; - The README file explains why this project exists. ;; - Begin in this "ex00..." file, and work through it step by step. ;; - Once you are done with "ex00...", open the next file and repeat. ;; - Keep going this way, until you have worked through all the files. ;; EX00: LESSON GOAL: ;; - A very quick intro to Clojure syntax, just to familiarize your ;; eyes with it. ;; ;; - Don't get stuck here! ;; - Run through it once, try evaluating expressions of interest ;; and move on to EX01. ;; - Your eyes and brain will adjust fairly quickly, as you ;; work through the examples to follow. ;; Clojure is a "Lisp" ;; - Lisp is short for List Processing ;; - It's just another way to design a programming language ;; (Ignore "But, Why?" for now... Just use it as it is, and try to ;; do something practical with it.) ;; Clojure code is composed of "expressions": ;; These literal values are Clojure "expressions" "hello" ; strings :hello ; keywords 'hello ; symbols 42 ; numbers 22/7 ; fractional numbers ;; "Built-in" functions are also "expressions" ;; - We will meet all of these again, very soon. + ; addition map ; map over a collection filter ; filter from a collection reduce ; transform a collection ;; Collection "literals" are expressions too: ;; - We will extensively use such "collection" data structures. [1 2 3 4 5] ; a vector {:a 1 :b 2} ; a hash-map #{1 2 3 4 5} ; a hash-set '(1 2 3 4 5) ; a list ;; Clojure code is also composed of expressions; ;; - we refer to them as "symbolic" expressions (or "s"-expression) (+ 1 2) ; an s-expression (+ (+ 1 2) (+ 1 2)) ; an s-expression of nested expressions (+ (+ (+ 1 2) (+ 1 2)) (+ (+ 1 2) (+ 1 2))) ; an even more nested s-expression ;; In fact, ALL Clojure code is just "expressions" ;; - And, all Clojure expressions evaluate to a value. ;; ;; - All literals evaluate to themselves. They are values. ;; (Hence "literal": a literal is what it is. :-D) ;; ;; - All collection literals also evaluate to themselves. ;; (A literal collection is what it is, too.) ;; ;; - All functions are values. ;; (More on this a little later) ;; ;; - All s-expressions, however deeply nested, finally evaluate ;; to a return value. Expressions evaluate to either a literal, ;; or a collection, or a function. ;; Clojure expression syntax rules: ;; ;; - Literals: ;; - Just write them down ;; ;; - Collection Literals: ;; - Just write them down too, but also ;; - make sure opening brackets are always matched by closing brackets ;; [1 2 3] is a well-formed vector representation ;; [1 2 3 is an "unbalanced" vector and will cause an error. ;; ;; - Symbolic expressions ("s-expressions"): ;; - Make sure the round parentheses close over the intended/required ;; sub-expressions ;; (+ 1 2) is a well-formed expression that will be evaluated ;; (+ 1 2 is an "unbalanced" s-expression and will cause an error. ;; Clojure Code Evaluation Rules: ;; ;; - To instruct Clojure to evaluate a list of expressions, ;; enclose the expressions in round parentheses. ;; - Recall: (+ 1 2) ;; ;; - The very first expression after an opening paren MUST be ;; a function. ;; - So: (1 2) will fail, because 1 is not a function ;; ;; - All expressions or sub-expressions that follow the first expression ;; will first be fully evaluated into values, and then passed to ;; the first expression as arguments. ;; - Recall: (+ (+ (+ 1 2) (+ 1 2)) ;; (+ (+ 1 2) (+ 1 2))) ;; ;; - You may mentally evaluate the above form "inside-out", like this: ;; - Evaluate the smallest and innermost expressions first, ;; - Mentally replace them with their return values ;; - Pass those values as arguments to the next higher expression ;; - Continue until you are left with a literal value. ;; ;; (+ (+ (+ 1 2) (+ 1 2)) ;; (+ (+ 1 2) (+ 1 2))) ;; ;; (+ (+ 3 3 ) ;; (+ 3 3 )) ;; ;; (+ 6 ;; 6) ;; ;; 12 ;; ;; - Keep this evaluation model in mind, when you read Clojure code, ;; to figure out how the code will evaluate. ;; ;; - To prevent evaluation, explicitly mark an expression as a list ;; '(1 2) put a single quote in front of an expression to tell Clojure ;; you don't want it to evaluate that expression. ;; ;; - To comment out in-line comment text, or even an expression, ;; place one or more semi-colons before the text/expression. ;; ;; - `#_` is a clean way to comment out multi-line s-expressions ;; Compare this: #_(+ 1 2 3 4 5 6) ;; With this: ;; (+ 1 2 ;; 3 4 ;; 5 6) ;; Why is Clojure a "List Processing" language? '(+ 1 2) ; Recall: this is a Clojure list, that Clojure evaluates ; as literal data. (+ 1 2) ; if we remove the single quote, Clojure treats the same list ; as an executable list, and tries to evaluate it as code. ;; More generally, Clojure code, like other lisps, is written ;; in terms of its own data structures. For example: ;; ;; Here is a function definition. (defn hie [person message] (str "PI:NAME:<NAME>END_PI, " person " : " message)) ;; What does it look like? ;; - Let's flatten it into one line for illustrative purposes: ;;[1] [2] [3] [4] (defn hie [person message] (str "PI:NAME:<NAME>END_PI, " person " : " message)) ; [5] ;; Where: ;; - [1] `defn` is a Clojure built-in primitive ;; - Notice, it's at the 1st position, and ;; - 2-4 are all arguments to defn ;; Further: ;; - [2] is a Clojure symbol, `hello`, which will name the function ;; - [3] is a Clojure vector of two named arguments ;; - [4] is a Clojure s-expression, and is treated as the body of ;; the function definition ;; - [5] the whole thing itself is a Clojure s-expression! ;; RECAP: ;; ;; - All Clojure code is a bunch of "expressions" ;; (literals, collections, s-expressions) ;; ;; - All Clojure expressions evaluate to a return value ;; ;; - All Clojure code is written in terms of its own data structures ;; ;; - All opening braces or parentheses must be matched by closing ;; braces or parentheses, to create legal Clojure expressions.
[ { "context": "--------------------------------\n;; Copyright 2017 Greg Haskins\n;;\n;; SPDX-License-Identifier: Apache-2.0\n;;-----", "end": 110, "score": 0.9997881054878235, "start": 98, "tag": "NAME", "value": "Greg Haskins" } ]
examples/example02/client/cljs/src/example02/connection.cljs
simonmulser/fabric-chaintool
138
;;----------------------------------------------------------------------------- ;; Copyright 2017 Greg Haskins ;; ;; SPDX-License-Identifier: Apache-2.0 ;;----------------------------------------------------------------------------- (ns example02.connection (:require [fabric-sdk.core :as fabric] [fabric-sdk.channel :as fabric.channel] [fabric-sdk.eventhub :as fabric.eventhub] [fabric-sdk.user :as fabric.user] [promesa.core :as p :include-macros true])) (defn- set-state-store [client path] (-> (fabric/new-default-kv-store path) (p/then #(fabric/set-state-store client %)))) (defn- create-user [client identity] (let [config #js {:username (:principal identity) :mspid (:mspid identity) :cryptoContent #js {:privateKeyPEM (:privatekey identity) :signedCertPEM (:certificate identity)}}] (fabric/create-user client config))) (defn- connect-orderer [client channel config] (let [{:keys [ca hostname url]} (:orderer config) orderer (fabric/new-orderer client url #js {:pem ca :ssl-target-name-override hostname})] (fabric.channel/add-orderer channel orderer) orderer)) (defn- connect-peer [client channel config peercfg] (let [ca (-> config :ca :certificate) {:keys [api hostname]} peercfg peer (fabric/new-peer client api #js {:pem ca :ssl-target-name-override hostname :request-timeout 120000})] (fabric.channel/add-peer channel peer) peer)) (defn- connect-eventhub [client channel config] (let [ca (-> config :ca :certificate) {:keys [events hostname]} (-> config :peers first) eventhub (fabric/new-eventhub client)] (fabric.eventhub/set-peer-addr eventhub events #js {:pem ca :ssl-target-name-override hostname}) (fabric.eventhub/connect! eventhub) eventhub)) (defn connect! [{:keys [config id channelId] :as options}] (let [client (fabric/new-client) identity (:identity config)] (-> (set-state-store client ".hfc-kvstore") (p/then #(create-user client identity)) (p/then (fn [user] (let [channel (fabric.channel/new client channelId) orderer (connect-orderer client channel config) peers (->> config :peers (map #(connect-peer client channel config %))) eventhub (connect-eventhub client channel config)] (-> (fabric.channel/initialize channel) (p/then (fn [] {:client client :channel channel :orderer orderer :peers peers :eventhub eventhub :user user}))))))))) (defn disconnect! [{:keys [eventhub]}] (fabric.eventhub/disconnect! eventhub))
109585
;;----------------------------------------------------------------------------- ;; Copyright 2017 <NAME> ;; ;; SPDX-License-Identifier: Apache-2.0 ;;----------------------------------------------------------------------------- (ns example02.connection (:require [fabric-sdk.core :as fabric] [fabric-sdk.channel :as fabric.channel] [fabric-sdk.eventhub :as fabric.eventhub] [fabric-sdk.user :as fabric.user] [promesa.core :as p :include-macros true])) (defn- set-state-store [client path] (-> (fabric/new-default-kv-store path) (p/then #(fabric/set-state-store client %)))) (defn- create-user [client identity] (let [config #js {:username (:principal identity) :mspid (:mspid identity) :cryptoContent #js {:privateKeyPEM (:privatekey identity) :signedCertPEM (:certificate identity)}}] (fabric/create-user client config))) (defn- connect-orderer [client channel config] (let [{:keys [ca hostname url]} (:orderer config) orderer (fabric/new-orderer client url #js {:pem ca :ssl-target-name-override hostname})] (fabric.channel/add-orderer channel orderer) orderer)) (defn- connect-peer [client channel config peercfg] (let [ca (-> config :ca :certificate) {:keys [api hostname]} peercfg peer (fabric/new-peer client api #js {:pem ca :ssl-target-name-override hostname :request-timeout 120000})] (fabric.channel/add-peer channel peer) peer)) (defn- connect-eventhub [client channel config] (let [ca (-> config :ca :certificate) {:keys [events hostname]} (-> config :peers first) eventhub (fabric/new-eventhub client)] (fabric.eventhub/set-peer-addr eventhub events #js {:pem ca :ssl-target-name-override hostname}) (fabric.eventhub/connect! eventhub) eventhub)) (defn connect! [{:keys [config id channelId] :as options}] (let [client (fabric/new-client) identity (:identity config)] (-> (set-state-store client ".hfc-kvstore") (p/then #(create-user client identity)) (p/then (fn [user] (let [channel (fabric.channel/new client channelId) orderer (connect-orderer client channel config) peers (->> config :peers (map #(connect-peer client channel config %))) eventhub (connect-eventhub client channel config)] (-> (fabric.channel/initialize channel) (p/then (fn [] {:client client :channel channel :orderer orderer :peers peers :eventhub eventhub :user user}))))))))) (defn disconnect! [{:keys [eventhub]}] (fabric.eventhub/disconnect! eventhub))
true
;;----------------------------------------------------------------------------- ;; Copyright 2017 PI:NAME:<NAME>END_PI ;; ;; SPDX-License-Identifier: Apache-2.0 ;;----------------------------------------------------------------------------- (ns example02.connection (:require [fabric-sdk.core :as fabric] [fabric-sdk.channel :as fabric.channel] [fabric-sdk.eventhub :as fabric.eventhub] [fabric-sdk.user :as fabric.user] [promesa.core :as p :include-macros true])) (defn- set-state-store [client path] (-> (fabric/new-default-kv-store path) (p/then #(fabric/set-state-store client %)))) (defn- create-user [client identity] (let [config #js {:username (:principal identity) :mspid (:mspid identity) :cryptoContent #js {:privateKeyPEM (:privatekey identity) :signedCertPEM (:certificate identity)}}] (fabric/create-user client config))) (defn- connect-orderer [client channel config] (let [{:keys [ca hostname url]} (:orderer config) orderer (fabric/new-orderer client url #js {:pem ca :ssl-target-name-override hostname})] (fabric.channel/add-orderer channel orderer) orderer)) (defn- connect-peer [client channel config peercfg] (let [ca (-> config :ca :certificate) {:keys [api hostname]} peercfg peer (fabric/new-peer client api #js {:pem ca :ssl-target-name-override hostname :request-timeout 120000})] (fabric.channel/add-peer channel peer) peer)) (defn- connect-eventhub [client channel config] (let [ca (-> config :ca :certificate) {:keys [events hostname]} (-> config :peers first) eventhub (fabric/new-eventhub client)] (fabric.eventhub/set-peer-addr eventhub events #js {:pem ca :ssl-target-name-override hostname}) (fabric.eventhub/connect! eventhub) eventhub)) (defn connect! [{:keys [config id channelId] :as options}] (let [client (fabric/new-client) identity (:identity config)] (-> (set-state-store client ".hfc-kvstore") (p/then #(create-user client identity)) (p/then (fn [user] (let [channel (fabric.channel/new client channelId) orderer (connect-orderer client channel config) peers (->> config :peers (map #(connect-peer client channel config %))) eventhub (connect-eventhub client channel config)] (-> (fabric.channel/initialize channel) (p/then (fn [] {:client client :channel channel :orderer orderer :peers peers :eventhub eventhub :user user}))))))))) (defn disconnect! [{:keys [eventhub]}] (fabric.eventhub/disconnect! eventhub))
[ { "context": "test-\" user-id)\n :username (str \"username-load-test-\" user-id)\n :email-address (str ", "end": 1026, "score": 0.9994804263114929, "start": 1008, "tag": "USERNAME", "value": "username-load-test" }, { "context": " (assoc-in [:session :auth-provider-user-email] \"email@example.com\")))\n\n(defn stub-stonecutter-sign-in [request]\n (", "end": 2364, "score": 0.9999011754989624, "start": 2347, "tag": "EMAIL", "value": "email@example.com" } ]
dev/dev_helpers/stub_twitter_and_stonecutter.clj
d-cent/objective8
23
(ns dev-helpers.stub-twitter-and-stonecutter (:require [bidi.ring :refer [make-handler]] [clojure.tools.logging :as log] [ring.util.response :as response] [objective8.front-end.workflows.sign-up :refer [sign-up-workflow authorise]] [objective8.front-end.api.http :as http-api] [objective8.utils :as utils])) ;; Stub out twitter authentication workflow (def twitter-id (atom "twitter-FAKE_ID")) (def stonecutter-id (atom "d-cent-123123")) (defn stub-twitter-handler [request] (let [session (:session request)] (log/info "Stubbing twitter with fake twitter id: " @twitter-id) (-> (response/redirect (str utils/host-url "/sign-up")) (assoc :session (assoc session :auth-provider-user-id @twitter-id))))) (defn create-or-sign-in [{params :params :as request}] (let [user-id (:user-id params) user-map {:auth-provider-user-id (str "load-test-" user-id) :username (str "username-load-test-" user-id) :email-address (str "email-" user-id "@loadtest.com")} {status :status user :result :as find-result} (http-api/find-user-by-auth-provider-user-id (:auth-provider-user-id user-map))] (if (= status ::http-api/success) (authorise {:status 200} user) (let [{status :status user :result} (http-api/create-user user-map)] (if (= status ::http-api/success) (authorise {:status 200} user) (do (prn (str "Creating user failed: " status "\n params: " params "\n session: " (:session request))) {:status 500})))))) (def stub-twitter-workflow (make-handler ["/" {"create-or-sign-in" create-or-sign-in "twitter-sign-in" stub-twitter-handler}])) (def stub-twitter-auth-config {:allow-anon? true :workflows [stub-twitter-workflow sign-up-workflow] :login-uri "/sign-in"}) (defn stub-stonecutter-callback [request] (-> (response/redirect (str utils/host-url "/sign-up")) (assoc :session (:session request)) (assoc-in [:session :auth-provider-user-id] @stonecutter-id) (assoc-in [:session :auth-provider-user-email] "email@example.com"))) (defn stub-stonecutter-sign-in [request] (stub-stonecutter-callback request)) (def stub-stonecutter-workflow (make-handler ["/" {"d-cent-sign-in" stub-stonecutter-sign-in "d-cent-callback" stub-stonecutter-callback}])) (def stub-twitter-and-stonecutter-auth-config {:allow-anon? true :workflows [stub-twitter-workflow stub-stonecutter-workflow sign-up-workflow] :login-uri "/sign-in"})
72704
(ns dev-helpers.stub-twitter-and-stonecutter (:require [bidi.ring :refer [make-handler]] [clojure.tools.logging :as log] [ring.util.response :as response] [objective8.front-end.workflows.sign-up :refer [sign-up-workflow authorise]] [objective8.front-end.api.http :as http-api] [objective8.utils :as utils])) ;; Stub out twitter authentication workflow (def twitter-id (atom "twitter-FAKE_ID")) (def stonecutter-id (atom "d-cent-123123")) (defn stub-twitter-handler [request] (let [session (:session request)] (log/info "Stubbing twitter with fake twitter id: " @twitter-id) (-> (response/redirect (str utils/host-url "/sign-up")) (assoc :session (assoc session :auth-provider-user-id @twitter-id))))) (defn create-or-sign-in [{params :params :as request}] (let [user-id (:user-id params) user-map {:auth-provider-user-id (str "load-test-" user-id) :username (str "username-load-test-" user-id) :email-address (str "email-" user-id "@loadtest.com")} {status :status user :result :as find-result} (http-api/find-user-by-auth-provider-user-id (:auth-provider-user-id user-map))] (if (= status ::http-api/success) (authorise {:status 200} user) (let [{status :status user :result} (http-api/create-user user-map)] (if (= status ::http-api/success) (authorise {:status 200} user) (do (prn (str "Creating user failed: " status "\n params: " params "\n session: " (:session request))) {:status 500})))))) (def stub-twitter-workflow (make-handler ["/" {"create-or-sign-in" create-or-sign-in "twitter-sign-in" stub-twitter-handler}])) (def stub-twitter-auth-config {:allow-anon? true :workflows [stub-twitter-workflow sign-up-workflow] :login-uri "/sign-in"}) (defn stub-stonecutter-callback [request] (-> (response/redirect (str utils/host-url "/sign-up")) (assoc :session (:session request)) (assoc-in [:session :auth-provider-user-id] @stonecutter-id) (assoc-in [:session :auth-provider-user-email] "<EMAIL>"))) (defn stub-stonecutter-sign-in [request] (stub-stonecutter-callback request)) (def stub-stonecutter-workflow (make-handler ["/" {"d-cent-sign-in" stub-stonecutter-sign-in "d-cent-callback" stub-stonecutter-callback}])) (def stub-twitter-and-stonecutter-auth-config {:allow-anon? true :workflows [stub-twitter-workflow stub-stonecutter-workflow sign-up-workflow] :login-uri "/sign-in"})
true
(ns dev-helpers.stub-twitter-and-stonecutter (:require [bidi.ring :refer [make-handler]] [clojure.tools.logging :as log] [ring.util.response :as response] [objective8.front-end.workflows.sign-up :refer [sign-up-workflow authorise]] [objective8.front-end.api.http :as http-api] [objective8.utils :as utils])) ;; Stub out twitter authentication workflow (def twitter-id (atom "twitter-FAKE_ID")) (def stonecutter-id (atom "d-cent-123123")) (defn stub-twitter-handler [request] (let [session (:session request)] (log/info "Stubbing twitter with fake twitter id: " @twitter-id) (-> (response/redirect (str utils/host-url "/sign-up")) (assoc :session (assoc session :auth-provider-user-id @twitter-id))))) (defn create-or-sign-in [{params :params :as request}] (let [user-id (:user-id params) user-map {:auth-provider-user-id (str "load-test-" user-id) :username (str "username-load-test-" user-id) :email-address (str "email-" user-id "@loadtest.com")} {status :status user :result :as find-result} (http-api/find-user-by-auth-provider-user-id (:auth-provider-user-id user-map))] (if (= status ::http-api/success) (authorise {:status 200} user) (let [{status :status user :result} (http-api/create-user user-map)] (if (= status ::http-api/success) (authorise {:status 200} user) (do (prn (str "Creating user failed: " status "\n params: " params "\n session: " (:session request))) {:status 500})))))) (def stub-twitter-workflow (make-handler ["/" {"create-or-sign-in" create-or-sign-in "twitter-sign-in" stub-twitter-handler}])) (def stub-twitter-auth-config {:allow-anon? true :workflows [stub-twitter-workflow sign-up-workflow] :login-uri "/sign-in"}) (defn stub-stonecutter-callback [request] (-> (response/redirect (str utils/host-url "/sign-up")) (assoc :session (:session request)) (assoc-in [:session :auth-provider-user-id] @stonecutter-id) (assoc-in [:session :auth-provider-user-email] "PI:EMAIL:<EMAIL>END_PI"))) (defn stub-stonecutter-sign-in [request] (stub-stonecutter-callback request)) (def stub-stonecutter-workflow (make-handler ["/" {"d-cent-sign-in" stub-stonecutter-sign-in "d-cent-callback" stub-stonecutter-callback}])) (def stub-twitter-and-stonecutter-auth-config {:allow-anon? true :workflows [stub-twitter-workflow stub-stonecutter-workflow sign-up-workflow] :login-uri "/sign-in"})
[ { "context": " author {:id, :name, :email}.\"\n (is (= {:id \"id-01\"\n :name \"author\"\n :email \"a", "end": 738, "score": 0.6096539497375488, "start": 736, "tag": "USERNAME", "value": "01" }, { "context": "ail}.\"\n (is (= {:id \"id-01\"\n :name \"author\"\n :email \"author@clj.map\"} (seven-days", "end": 765, "score": 0.8137769103050232, "start": 759, "tag": "USERNAME", "value": "author" }, { "context": "1\"\n :name \"author\"\n :email \"author@clj.map\"} (seven-days-of-clojure.some-functions/author)))", "end": 801, "score": 0.9999110102653503, "start": 787, "tag": "EMAIL", "value": "author@clj.map" } ]
day6/tests.clj
joaopaulomoraes/7-days-of-clojure
8
(ns seven-days-of-clojure.tests (:require [clojure.test :refer :all] [seven-days-of-clojure.some-functions :refer :all])) (deftest one-test (testing "Should return 1." (is (= 1 (seven-days-of-clojure.some-functions/one))))) (deftest floating-point-test (testing "Should return 7.7." (is (= 7.7 (seven-days-of-clojure.some-functions/floating-point))))) (deftest language-test (testing "Should return Clojure." (is (= "Clojure" (seven-days-of-clojure.some-functions/language))))) (deftest is-bool-test (testing "Should return true." (is (= true (seven-days-of-clojure.some-functions/is-bool))))) (deftest author-test (testing "Shoud return an author {:id, :name, :email}." (is (= {:id "id-01" :name "author" :email "author@clj.map"} (seven-days-of-clojure.some-functions/author))))) (deftest paradigm-test (testing "Should return :fp." (is (= :fp (seven-days-of-clojure.some-functions/paradigm)))))
53787
(ns seven-days-of-clojure.tests (:require [clojure.test :refer :all] [seven-days-of-clojure.some-functions :refer :all])) (deftest one-test (testing "Should return 1." (is (= 1 (seven-days-of-clojure.some-functions/one))))) (deftest floating-point-test (testing "Should return 7.7." (is (= 7.7 (seven-days-of-clojure.some-functions/floating-point))))) (deftest language-test (testing "Should return Clojure." (is (= "Clojure" (seven-days-of-clojure.some-functions/language))))) (deftest is-bool-test (testing "Should return true." (is (= true (seven-days-of-clojure.some-functions/is-bool))))) (deftest author-test (testing "Shoud return an author {:id, :name, :email}." (is (= {:id "id-01" :name "author" :email "<EMAIL>"} (seven-days-of-clojure.some-functions/author))))) (deftest paradigm-test (testing "Should return :fp." (is (= :fp (seven-days-of-clojure.some-functions/paradigm)))))
true
(ns seven-days-of-clojure.tests (:require [clojure.test :refer :all] [seven-days-of-clojure.some-functions :refer :all])) (deftest one-test (testing "Should return 1." (is (= 1 (seven-days-of-clojure.some-functions/one))))) (deftest floating-point-test (testing "Should return 7.7." (is (= 7.7 (seven-days-of-clojure.some-functions/floating-point))))) (deftest language-test (testing "Should return Clojure." (is (= "Clojure" (seven-days-of-clojure.some-functions/language))))) (deftest is-bool-test (testing "Should return true." (is (= true (seven-days-of-clojure.some-functions/is-bool))))) (deftest author-test (testing "Shoud return an author {:id, :name, :email}." (is (= {:id "id-01" :name "author" :email "PI:EMAIL:<EMAIL>END_PI"} (seven-days-of-clojure.some-functions/author))))) (deftest paradigm-test (testing "Should return :fp." (is (= :fp (seven-days-of-clojure.some-functions/paradigm)))))
[ { "context": "\n [c/Menu\n [c/MenuItem {:name \"editorials\"\n :active (= @active-i", "end": 5162, "score": 0.7081933617591858, "start": 5156, "tag": "NAME", "value": "editor" }, { "context": "[c/Checkbox {:slider true}]]\n [c/TableCell \"John Lilki\"]\n [c/TableCell \"September 14, 2013\"]\n ", "end": 9704, "score": 0.9998614192008972, "start": 9694, "tag": "NAME", "value": "John Lilki" }, { "context": "leCell \"September 14, 2013\"]\n [c/TableCell \"jhlilk22@yahoo.com\"]\n [c/TableCell \"No\"]]\n [c/TableRow\n ", "end": 9788, "score": 0.9999317526817322, "start": 9770, "tag": "EMAIL", "value": "jhlilk22@yahoo.com" }, { "context": "[c/Checkbox {:slider true}]]\n [c/TableCell \"Jamie Harington\"]\n [c/TableCell \"January 11, 2014\"]\n ", "end": 9940, "score": 0.9998741149902344, "start": 9925, "tag": "NAME", "value": "Jamie Harington" }, { "context": "ableCell \"January 11, 2014\"]\n [c/TableCell \"jamieharingonton@yahoo.com\"]\n [c/TableCell \"Yes\"]]\n [c/TableRow\n ", "end": 10030, "score": 0.9999338984489441, "start": 10004, "tag": "EMAIL", "value": "jamieharingonton@yahoo.com" }, { "context": "[c/Checkbox {:slider true}]]\n [c/TableCell \"Jill Lewis\"]\n [c/TableCell \"May 11, 2014\"]\n [c/T", "end": 10178, "score": 0.9998638033866882, "start": 10168, "tag": "NAME", "value": "Jill Lewis" }, { "context": "[c/TableCell \"May 11, 2014\"]\n [c/TableCell \"jilsewris22@yahoo.com\"]\n [c/TableCell \"Yes\"]]]\n [c/TableFoote", "end": 10259, "score": 0.9999332427978516, "start": 10238, "tag": "EMAIL", "value": "jilsewris22@yahoo.com" } ]
dev/semantic_ui_reagent/collections.cljs
toyokumo/semantic-ui-reagent
2
(ns semantic-ui-reagent.collections (:require [reagent.core :as r] [semantic-ui-reagent.core :as c])) (defn Breadcrumb [] [:div.examples [c/Header {:as :h2} "Breadcrumb"] [:div.ex [c/Breadcrumb [c/BreadcrumbSection {:link true} "Home"] [c/BreadcrumbDivider {:icon "right angle"}] [c/BreadcrumbSection {:link true} "Store"] [c/BreadcrumbDivider {:icon "right angle"}] [c/BreadcrumbSection {:link true} "T-Shirt"]]] [:div.ex [c/Breadcrumb [c/BreadcrumbSection {:link true} "Home"] [c/BreadcrumbDivider "/"] [c/BreadcrumbSection {:link true} "Store"] [c/BreadcrumbDivider {:icon "right angle"}] [c/BreadcrumbSection {:active true} "Search for:" [:a {:href "#"} "paper towels"]]]]]) (defn Form [] (let [state (r/atom {})] (fn [] [:div.examples [c/Header {:as :h2} "Form"] [:div.ex [c/Form {:on-submit (fn [evt form] (.preventDefault evt) (reset! state (get (js->clj form) "formData")))} [c/FormGroup {:widths :equal} [c/FormInput {:label "Name" :name "name" :placeholder "Name"}] [c/FormSelect {:label "Gender" :name "Gender" :placeholder "Gender" :options [{:key "m" :text "Male" :value "male"} {:key "f" :text "Female" :value "female"}]}]] [c/FormSelect {:label "Products" :name "products" :placeholder "Search..." :search true :multiple true :options [{:key "hat" :text "Hat" :value "hat"} {:key "scarf" :text "Scarf" :value "scarf"} {:key "jacket" :text "Jacket" :value "jacket"} {:key "t_shirt" :text "T-Shirt" :value "t_shirt"} {:key "gloves" :text "Gloves" :value "gloves"} {:key "watch" :text "Watch" :value "watch"} {:key "belt" :text "Belt" :value "belt"} {:key "pants" :text "Pants" :value "pants"} {:key "shoes" :text "Shoes" :value "shoes"} {:key "socks" :text "Socks" :value "socks"}]}] [c/FormGroup {:widths 2} [c/FormField [:label "Plan"] [c/FormGroup {:inline true} [c/FormRadio {:label "A" :name "plan" :value "a"}] [c/FormRadio {:label "B" :name "plan" :value "a"}] [c/FormRadio {:label "C" :name "plan" :value "a"}]]] [c/FormField [:label "Shipping Options"] [c/FormGroup {:inline true} [c/FormCheckbox {:label "Expedite" :name "shippingOptions" :value "expedite"}] [c/FormCheckbox {:label "Gift Wrap" :name "shippingOptions" :value "giftWrap"}] [c/FormCheckbox {:label "C.O.D" :name "shippingOptions" :value "cod"}]]]] [c/FormTextArea {:name "details" :label "Details" :placeholder "Anything else we should know?" :rows 3}] [c/FormCheckbox {:name "terms" :label "I agree to the Terms and Conditions"}] [c/Button {:primary true :type :submit} "Submit"]] [:br]]]))) (defn Grid [] [:div.examples [c/Header {:as :h2} "Grid"] [:div.ex [c/Grid (for [i (range 16)] ^{:key i} [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/image.png"}]])]] [:div.ex [:span.title "Divided"] [c/Grid {:columns 3 :divided true} [c/GridRow [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]] [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]] [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]]] [c/GridRow [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]] [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]] [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]]]]] [:div.ex [:span.title "Celled"] [c/Grid {:celled true} [c/GridRow [c/GridColumn {:width 3} [c/Image {:src "http://semantic-ui.com/images/wireframe/image.png"}]] [c/GridColumn {:width 13} [c/Image {:src "http://semantic-ui.com/images/wireframe/centered-paragraph.png"}]]] [c/GridRow [c/GridColumn {:width 3} [c/Image {:src "http://semantic-ui.com/images/wireframe/image.png"}]] [c/GridColumn {:width 10} [c/Image {:src "http://semantic-ui.com/images/wireframe/paragraph.png"}]] [c/GridColumn {:width 3} [c/Image {:src "http://semantic-ui.com/images/wireframe/image.png"}]]]]]]) (defn Menu-1 [] (let [active-item (r/atom nil)] (fn [] (let [handle-item-click (fn [_ data] (reset! active-item (aget data "name")))] [:div.examples [c/Header {:as :h2} "Menu 1"] [:div.ex [:span.title "Simple Menu"] [c/Menu [c/MenuItem {:name "editorials" :active (= @active-item "editorials") :on-click handle-item-click}] [c/MenuItem {:name "reviews" :active (= @active-item "reviews") :on-click handle-item-click}] [c/MenuItem {:name "upcomingEvents" :active (= @active-item "upcomingEvents") :on-click handle-item-click}]]]])))) (defn Menu-2 [] (let [active-item (r/atom nil)] (fn [] (let [handle-item-click (fn [_ data] (reset! active-item (aget data "name")))] [:div.examples [c/Header {:as :h2} "Menu 2"] [:div.ex [:span.title "Menu Tabular"] [c/Menu {:tabular true} [c/MenuItem {:name "bio" :active (= @active-item "bio") :on-click handle-item-click}] [c/MenuItem {:name "photos" :active (= @active-item "photos") :on-click handle-item-click}]]]])))) (defn Menu-3 [] (let [active-item (r/atom nil)] (fn [] (let [handle-item-click (fn [_ data] (reset! active-item (aget data "name")))] [:div.examples [c/Header {:as :h2} "Menu 3"] [:div.ex [:span.title "Menu Vertical"] [c/Menu {:vertical true} [c/MenuItem {:name "inbox" :active (= @active-item "inbox") :on-click handle-item-click} [c/Label {:color :teal} "1"] "Inbox"] [c/MenuItem {:name "spam" :active (= @active-item "spam") :on-click handle-item-click} [c/Label "51"] "Spam"] [c/MenuItem {:name "updates" :active (= @active-item "updates") :on-click handle-item-click} [c/Label "1"] "Updates"] [c/MenuItem [c/Input {:icon "search" :placeholder "Search mail..."}]]]]])))) (defn Message [] [:div.examples [c/Header {:as :h2} "Message"] [:div.ex [c/Message [c/MessageHeader "Changes in Service"] [:p "We updated our privacy policy here to better service our customers. We recommend reviewing the changes."]]] [:div.ex [c/Message {:icon true} [c/Icon {:name "circle notched" :loading true}] [c/MessageContent [c/MessageHeader "Just one second"] "We are fetching that content for you."]]] [:div.ex [c/Message {:error true :header "There was some errors with your submission" :list ["You must include both a upper and lower case letters in your password." "You need to select your home country."]}]]]) (defn Table [] [:div.examples [c/Header {:as :h2} "Table"] [:div.ex [c/Table {:celled true :padded true} [c/TableHeader [c/TableRow [c/TableHeaderCell {:single-line true} "Evidence Rating"] [c/TableHeaderCell "Effect"] [c/TableHeaderCell "Efficacy"] [c/TableHeaderCell "Consensus"] [c/TableHeaderCell "Comments"]]] [c/TableBody [c/TableRow [c/TableCell [c/Header {:as :h2 :text-align :center} "A"]] [c/TableCell {:single-line true} "Power Output"] [c/TableCell [c/Rating {:icon :star :default-rating 3 :max-rating 3}]] [c/TableCell {:text-align :right} "80%" [:br] [:a {:href "#"} "18 studies"]] [c/TableCell "Creatine supplementation is the reference compound for increasing muscular creatine levels; there is\nvariability in this increase, however, with some nonresponders."]] [c/TableRow [c/TableCell [c/Header {:as :h2 :text-align :center} "A"]] [c/TableCell {:single-line true} "Weight"] [c/TableCell [c/Rating {:icon :star :default-rating 2 :max-rating 3}]] [c/TableCell {:text-align :right} "100%" [:br] [:a {:href "#"} "65 studies"]] [c/TableCell "Creatine is the reference compound for power improvement, with numbers from one meta-analysis to assess\npotency"]]]]] [:div.ex [c/Table {:compact true :celled true :definition true} [c/TableHeader [c/TableRow [c/TableHeaderCell] [c/TableHeaderCell "Name"] [c/TableHeaderCell "Registration Date"] [c/TableHeaderCell "E-mail address"] [c/TableHeaderCell "Premium Plan"]]] [c/TableBody [c/TableRow [c/TableCell {:collapsing true} [c/Checkbox {:slider true}]] [c/TableCell "John Lilki"] [c/TableCell "September 14, 2013"] [c/TableCell "jhlilk22@yahoo.com"] [c/TableCell "No"]] [c/TableRow [c/TableCell {:collapsing true} [c/Checkbox {:slider true}]] [c/TableCell "Jamie Harington"] [c/TableCell "January 11, 2014"] [c/TableCell "jamieharingonton@yahoo.com"] [c/TableCell "Yes"]] [c/TableRow [c/TableCell {:collapsing true} [c/Checkbox {:slider true}]] [c/TableCell "Jill Lewis"] [c/TableCell "May 11, 2014"] [c/TableCell "jilsewris22@yahoo.com"] [c/TableCell "Yes"]]] [c/TableFooter {:full-width true} [c/TableRow [c/TableHeaderCell] [c/TableHeaderCell {:col-span 4} [c/Button {:floated :right :icon true :label-position :left :primary true :size :small} [c/Icon {:name "user"}] "Add User"] [c/Button {:size :small} "Approve"] [c/Button {:disabled true :size :small} "Approve All"]]]]]]])
96295
(ns semantic-ui-reagent.collections (:require [reagent.core :as r] [semantic-ui-reagent.core :as c])) (defn Breadcrumb [] [:div.examples [c/Header {:as :h2} "Breadcrumb"] [:div.ex [c/Breadcrumb [c/BreadcrumbSection {:link true} "Home"] [c/BreadcrumbDivider {:icon "right angle"}] [c/BreadcrumbSection {:link true} "Store"] [c/BreadcrumbDivider {:icon "right angle"}] [c/BreadcrumbSection {:link true} "T-Shirt"]]] [:div.ex [c/Breadcrumb [c/BreadcrumbSection {:link true} "Home"] [c/BreadcrumbDivider "/"] [c/BreadcrumbSection {:link true} "Store"] [c/BreadcrumbDivider {:icon "right angle"}] [c/BreadcrumbSection {:active true} "Search for:" [:a {:href "#"} "paper towels"]]]]]) (defn Form [] (let [state (r/atom {})] (fn [] [:div.examples [c/Header {:as :h2} "Form"] [:div.ex [c/Form {:on-submit (fn [evt form] (.preventDefault evt) (reset! state (get (js->clj form) "formData")))} [c/FormGroup {:widths :equal} [c/FormInput {:label "Name" :name "name" :placeholder "Name"}] [c/FormSelect {:label "Gender" :name "Gender" :placeholder "Gender" :options [{:key "m" :text "Male" :value "male"} {:key "f" :text "Female" :value "female"}]}]] [c/FormSelect {:label "Products" :name "products" :placeholder "Search..." :search true :multiple true :options [{:key "hat" :text "Hat" :value "hat"} {:key "scarf" :text "Scarf" :value "scarf"} {:key "jacket" :text "Jacket" :value "jacket"} {:key "t_shirt" :text "T-Shirt" :value "t_shirt"} {:key "gloves" :text "Gloves" :value "gloves"} {:key "watch" :text "Watch" :value "watch"} {:key "belt" :text "Belt" :value "belt"} {:key "pants" :text "Pants" :value "pants"} {:key "shoes" :text "Shoes" :value "shoes"} {:key "socks" :text "Socks" :value "socks"}]}] [c/FormGroup {:widths 2} [c/FormField [:label "Plan"] [c/FormGroup {:inline true} [c/FormRadio {:label "A" :name "plan" :value "a"}] [c/FormRadio {:label "B" :name "plan" :value "a"}] [c/FormRadio {:label "C" :name "plan" :value "a"}]]] [c/FormField [:label "Shipping Options"] [c/FormGroup {:inline true} [c/FormCheckbox {:label "Expedite" :name "shippingOptions" :value "expedite"}] [c/FormCheckbox {:label "Gift Wrap" :name "shippingOptions" :value "giftWrap"}] [c/FormCheckbox {:label "C.O.D" :name "shippingOptions" :value "cod"}]]]] [c/FormTextArea {:name "details" :label "Details" :placeholder "Anything else we should know?" :rows 3}] [c/FormCheckbox {:name "terms" :label "I agree to the Terms and Conditions"}] [c/Button {:primary true :type :submit} "Submit"]] [:br]]]))) (defn Grid [] [:div.examples [c/Header {:as :h2} "Grid"] [:div.ex [c/Grid (for [i (range 16)] ^{:key i} [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/image.png"}]])]] [:div.ex [:span.title "Divided"] [c/Grid {:columns 3 :divided true} [c/GridRow [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]] [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]] [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]]] [c/GridRow [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]] [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]] [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]]]]] [:div.ex [:span.title "Celled"] [c/Grid {:celled true} [c/GridRow [c/GridColumn {:width 3} [c/Image {:src "http://semantic-ui.com/images/wireframe/image.png"}]] [c/GridColumn {:width 13} [c/Image {:src "http://semantic-ui.com/images/wireframe/centered-paragraph.png"}]]] [c/GridRow [c/GridColumn {:width 3} [c/Image {:src "http://semantic-ui.com/images/wireframe/image.png"}]] [c/GridColumn {:width 10} [c/Image {:src "http://semantic-ui.com/images/wireframe/paragraph.png"}]] [c/GridColumn {:width 3} [c/Image {:src "http://semantic-ui.com/images/wireframe/image.png"}]]]]]]) (defn Menu-1 [] (let [active-item (r/atom nil)] (fn [] (let [handle-item-click (fn [_ data] (reset! active-item (aget data "name")))] [:div.examples [c/Header {:as :h2} "Menu 1"] [:div.ex [:span.title "Simple Menu"] [c/Menu [c/MenuItem {:name "<NAME>ials" :active (= @active-item "editorials") :on-click handle-item-click}] [c/MenuItem {:name "reviews" :active (= @active-item "reviews") :on-click handle-item-click}] [c/MenuItem {:name "upcomingEvents" :active (= @active-item "upcomingEvents") :on-click handle-item-click}]]]])))) (defn Menu-2 [] (let [active-item (r/atom nil)] (fn [] (let [handle-item-click (fn [_ data] (reset! active-item (aget data "name")))] [:div.examples [c/Header {:as :h2} "Menu 2"] [:div.ex [:span.title "Menu Tabular"] [c/Menu {:tabular true} [c/MenuItem {:name "bio" :active (= @active-item "bio") :on-click handle-item-click}] [c/MenuItem {:name "photos" :active (= @active-item "photos") :on-click handle-item-click}]]]])))) (defn Menu-3 [] (let [active-item (r/atom nil)] (fn [] (let [handle-item-click (fn [_ data] (reset! active-item (aget data "name")))] [:div.examples [c/Header {:as :h2} "Menu 3"] [:div.ex [:span.title "Menu Vertical"] [c/Menu {:vertical true} [c/MenuItem {:name "inbox" :active (= @active-item "inbox") :on-click handle-item-click} [c/Label {:color :teal} "1"] "Inbox"] [c/MenuItem {:name "spam" :active (= @active-item "spam") :on-click handle-item-click} [c/Label "51"] "Spam"] [c/MenuItem {:name "updates" :active (= @active-item "updates") :on-click handle-item-click} [c/Label "1"] "Updates"] [c/MenuItem [c/Input {:icon "search" :placeholder "Search mail..."}]]]]])))) (defn Message [] [:div.examples [c/Header {:as :h2} "Message"] [:div.ex [c/Message [c/MessageHeader "Changes in Service"] [:p "We updated our privacy policy here to better service our customers. We recommend reviewing the changes."]]] [:div.ex [c/Message {:icon true} [c/Icon {:name "circle notched" :loading true}] [c/MessageContent [c/MessageHeader "Just one second"] "We are fetching that content for you."]]] [:div.ex [c/Message {:error true :header "There was some errors with your submission" :list ["You must include both a upper and lower case letters in your password." "You need to select your home country."]}]]]) (defn Table [] [:div.examples [c/Header {:as :h2} "Table"] [:div.ex [c/Table {:celled true :padded true} [c/TableHeader [c/TableRow [c/TableHeaderCell {:single-line true} "Evidence Rating"] [c/TableHeaderCell "Effect"] [c/TableHeaderCell "Efficacy"] [c/TableHeaderCell "Consensus"] [c/TableHeaderCell "Comments"]]] [c/TableBody [c/TableRow [c/TableCell [c/Header {:as :h2 :text-align :center} "A"]] [c/TableCell {:single-line true} "Power Output"] [c/TableCell [c/Rating {:icon :star :default-rating 3 :max-rating 3}]] [c/TableCell {:text-align :right} "80%" [:br] [:a {:href "#"} "18 studies"]] [c/TableCell "Creatine supplementation is the reference compound for increasing muscular creatine levels; there is\nvariability in this increase, however, with some nonresponders."]] [c/TableRow [c/TableCell [c/Header {:as :h2 :text-align :center} "A"]] [c/TableCell {:single-line true} "Weight"] [c/TableCell [c/Rating {:icon :star :default-rating 2 :max-rating 3}]] [c/TableCell {:text-align :right} "100%" [:br] [:a {:href "#"} "65 studies"]] [c/TableCell "Creatine is the reference compound for power improvement, with numbers from one meta-analysis to assess\npotency"]]]]] [:div.ex [c/Table {:compact true :celled true :definition true} [c/TableHeader [c/TableRow [c/TableHeaderCell] [c/TableHeaderCell "Name"] [c/TableHeaderCell "Registration Date"] [c/TableHeaderCell "E-mail address"] [c/TableHeaderCell "Premium Plan"]]] [c/TableBody [c/TableRow [c/TableCell {:collapsing true} [c/Checkbox {:slider true}]] [c/TableCell "<NAME>"] [c/TableCell "September 14, 2013"] [c/TableCell "<EMAIL>"] [c/TableCell "No"]] [c/TableRow [c/TableCell {:collapsing true} [c/Checkbox {:slider true}]] [c/TableCell "<NAME>"] [c/TableCell "January 11, 2014"] [c/TableCell "<EMAIL>"] [c/TableCell "Yes"]] [c/TableRow [c/TableCell {:collapsing true} [c/Checkbox {:slider true}]] [c/TableCell "<NAME>"] [c/TableCell "May 11, 2014"] [c/TableCell "<EMAIL>"] [c/TableCell "Yes"]]] [c/TableFooter {:full-width true} [c/TableRow [c/TableHeaderCell] [c/TableHeaderCell {:col-span 4} [c/Button {:floated :right :icon true :label-position :left :primary true :size :small} [c/Icon {:name "user"}] "Add User"] [c/Button {:size :small} "Approve"] [c/Button {:disabled true :size :small} "Approve All"]]]]]]])
true
(ns semantic-ui-reagent.collections (:require [reagent.core :as r] [semantic-ui-reagent.core :as c])) (defn Breadcrumb [] [:div.examples [c/Header {:as :h2} "Breadcrumb"] [:div.ex [c/Breadcrumb [c/BreadcrumbSection {:link true} "Home"] [c/BreadcrumbDivider {:icon "right angle"}] [c/BreadcrumbSection {:link true} "Store"] [c/BreadcrumbDivider {:icon "right angle"}] [c/BreadcrumbSection {:link true} "T-Shirt"]]] [:div.ex [c/Breadcrumb [c/BreadcrumbSection {:link true} "Home"] [c/BreadcrumbDivider "/"] [c/BreadcrumbSection {:link true} "Store"] [c/BreadcrumbDivider {:icon "right angle"}] [c/BreadcrumbSection {:active true} "Search for:" [:a {:href "#"} "paper towels"]]]]]) (defn Form [] (let [state (r/atom {})] (fn [] [:div.examples [c/Header {:as :h2} "Form"] [:div.ex [c/Form {:on-submit (fn [evt form] (.preventDefault evt) (reset! state (get (js->clj form) "formData")))} [c/FormGroup {:widths :equal} [c/FormInput {:label "Name" :name "name" :placeholder "Name"}] [c/FormSelect {:label "Gender" :name "Gender" :placeholder "Gender" :options [{:key "m" :text "Male" :value "male"} {:key "f" :text "Female" :value "female"}]}]] [c/FormSelect {:label "Products" :name "products" :placeholder "Search..." :search true :multiple true :options [{:key "hat" :text "Hat" :value "hat"} {:key "scarf" :text "Scarf" :value "scarf"} {:key "jacket" :text "Jacket" :value "jacket"} {:key "t_shirt" :text "T-Shirt" :value "t_shirt"} {:key "gloves" :text "Gloves" :value "gloves"} {:key "watch" :text "Watch" :value "watch"} {:key "belt" :text "Belt" :value "belt"} {:key "pants" :text "Pants" :value "pants"} {:key "shoes" :text "Shoes" :value "shoes"} {:key "socks" :text "Socks" :value "socks"}]}] [c/FormGroup {:widths 2} [c/FormField [:label "Plan"] [c/FormGroup {:inline true} [c/FormRadio {:label "A" :name "plan" :value "a"}] [c/FormRadio {:label "B" :name "plan" :value "a"}] [c/FormRadio {:label "C" :name "plan" :value "a"}]]] [c/FormField [:label "Shipping Options"] [c/FormGroup {:inline true} [c/FormCheckbox {:label "Expedite" :name "shippingOptions" :value "expedite"}] [c/FormCheckbox {:label "Gift Wrap" :name "shippingOptions" :value "giftWrap"}] [c/FormCheckbox {:label "C.O.D" :name "shippingOptions" :value "cod"}]]]] [c/FormTextArea {:name "details" :label "Details" :placeholder "Anything else we should know?" :rows 3}] [c/FormCheckbox {:name "terms" :label "I agree to the Terms and Conditions"}] [c/Button {:primary true :type :submit} "Submit"]] [:br]]]))) (defn Grid [] [:div.examples [c/Header {:as :h2} "Grid"] [:div.ex [c/Grid (for [i (range 16)] ^{:key i} [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/image.png"}]])]] [:div.ex [:span.title "Divided"] [c/Grid {:columns 3 :divided true} [c/GridRow [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]] [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]] [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]]] [c/GridRow [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]] [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]] [c/GridColumn [c/Image {:src "http://semantic-ui.com/images/wireframe/media-paragraph.png"}]]]]] [:div.ex [:span.title "Celled"] [c/Grid {:celled true} [c/GridRow [c/GridColumn {:width 3} [c/Image {:src "http://semantic-ui.com/images/wireframe/image.png"}]] [c/GridColumn {:width 13} [c/Image {:src "http://semantic-ui.com/images/wireframe/centered-paragraph.png"}]]] [c/GridRow [c/GridColumn {:width 3} [c/Image {:src "http://semantic-ui.com/images/wireframe/image.png"}]] [c/GridColumn {:width 10} [c/Image {:src "http://semantic-ui.com/images/wireframe/paragraph.png"}]] [c/GridColumn {:width 3} [c/Image {:src "http://semantic-ui.com/images/wireframe/image.png"}]]]]]]) (defn Menu-1 [] (let [active-item (r/atom nil)] (fn [] (let [handle-item-click (fn [_ data] (reset! active-item (aget data "name")))] [:div.examples [c/Header {:as :h2} "Menu 1"] [:div.ex [:span.title "Simple Menu"] [c/Menu [c/MenuItem {:name "PI:NAME:<NAME>END_PIials" :active (= @active-item "editorials") :on-click handle-item-click}] [c/MenuItem {:name "reviews" :active (= @active-item "reviews") :on-click handle-item-click}] [c/MenuItem {:name "upcomingEvents" :active (= @active-item "upcomingEvents") :on-click handle-item-click}]]]])))) (defn Menu-2 [] (let [active-item (r/atom nil)] (fn [] (let [handle-item-click (fn [_ data] (reset! active-item (aget data "name")))] [:div.examples [c/Header {:as :h2} "Menu 2"] [:div.ex [:span.title "Menu Tabular"] [c/Menu {:tabular true} [c/MenuItem {:name "bio" :active (= @active-item "bio") :on-click handle-item-click}] [c/MenuItem {:name "photos" :active (= @active-item "photos") :on-click handle-item-click}]]]])))) (defn Menu-3 [] (let [active-item (r/atom nil)] (fn [] (let [handle-item-click (fn [_ data] (reset! active-item (aget data "name")))] [:div.examples [c/Header {:as :h2} "Menu 3"] [:div.ex [:span.title "Menu Vertical"] [c/Menu {:vertical true} [c/MenuItem {:name "inbox" :active (= @active-item "inbox") :on-click handle-item-click} [c/Label {:color :teal} "1"] "Inbox"] [c/MenuItem {:name "spam" :active (= @active-item "spam") :on-click handle-item-click} [c/Label "51"] "Spam"] [c/MenuItem {:name "updates" :active (= @active-item "updates") :on-click handle-item-click} [c/Label "1"] "Updates"] [c/MenuItem [c/Input {:icon "search" :placeholder "Search mail..."}]]]]])))) (defn Message [] [:div.examples [c/Header {:as :h2} "Message"] [:div.ex [c/Message [c/MessageHeader "Changes in Service"] [:p "We updated our privacy policy here to better service our customers. We recommend reviewing the changes."]]] [:div.ex [c/Message {:icon true} [c/Icon {:name "circle notched" :loading true}] [c/MessageContent [c/MessageHeader "Just one second"] "We are fetching that content for you."]]] [:div.ex [c/Message {:error true :header "There was some errors with your submission" :list ["You must include both a upper and lower case letters in your password." "You need to select your home country."]}]]]) (defn Table [] [:div.examples [c/Header {:as :h2} "Table"] [:div.ex [c/Table {:celled true :padded true} [c/TableHeader [c/TableRow [c/TableHeaderCell {:single-line true} "Evidence Rating"] [c/TableHeaderCell "Effect"] [c/TableHeaderCell "Efficacy"] [c/TableHeaderCell "Consensus"] [c/TableHeaderCell "Comments"]]] [c/TableBody [c/TableRow [c/TableCell [c/Header {:as :h2 :text-align :center} "A"]] [c/TableCell {:single-line true} "Power Output"] [c/TableCell [c/Rating {:icon :star :default-rating 3 :max-rating 3}]] [c/TableCell {:text-align :right} "80%" [:br] [:a {:href "#"} "18 studies"]] [c/TableCell "Creatine supplementation is the reference compound for increasing muscular creatine levels; there is\nvariability in this increase, however, with some nonresponders."]] [c/TableRow [c/TableCell [c/Header {:as :h2 :text-align :center} "A"]] [c/TableCell {:single-line true} "Weight"] [c/TableCell [c/Rating {:icon :star :default-rating 2 :max-rating 3}]] [c/TableCell {:text-align :right} "100%" [:br] [:a {:href "#"} "65 studies"]] [c/TableCell "Creatine is the reference compound for power improvement, with numbers from one meta-analysis to assess\npotency"]]]]] [:div.ex [c/Table {:compact true :celled true :definition true} [c/TableHeader [c/TableRow [c/TableHeaderCell] [c/TableHeaderCell "Name"] [c/TableHeaderCell "Registration Date"] [c/TableHeaderCell "E-mail address"] [c/TableHeaderCell "Premium Plan"]]] [c/TableBody [c/TableRow [c/TableCell {:collapsing true} [c/Checkbox {:slider true}]] [c/TableCell "PI:NAME:<NAME>END_PI"] [c/TableCell "September 14, 2013"] [c/TableCell "PI:EMAIL:<EMAIL>END_PI"] [c/TableCell "No"]] [c/TableRow [c/TableCell {:collapsing true} [c/Checkbox {:slider true}]] [c/TableCell "PI:NAME:<NAME>END_PI"] [c/TableCell "January 11, 2014"] [c/TableCell "PI:EMAIL:<EMAIL>END_PI"] [c/TableCell "Yes"]] [c/TableRow [c/TableCell {:collapsing true} [c/Checkbox {:slider true}]] [c/TableCell "PI:NAME:<NAME>END_PI"] [c/TableCell "May 11, 2014"] [c/TableCell "PI:EMAIL:<EMAIL>END_PI"] [c/TableCell "Yes"]]] [c/TableFooter {:full-width true} [c/TableRow [c/TableHeaderCell] [c/TableHeaderCell {:col-span 4} [c/Button {:floated :right :icon true :label-position :left :primary true :size :small} [c/Icon {:name "user"}] "Add User"] [c/Button {:size :small} "Approve"] [c/Button {:disabled true :size :small} "Approve All"]]]]]]])
[ { "context": "d\"\r\n :for \"user-name\"} \"User Name\"]]\r\n (text-field {:class \"for", "end": 4217, "score": 0.8326089382171631, "start": 4208, "tag": "NAME", "value": "User Name" }, { "context": "\"true\"\r\n :placeholder \"User Name\"} \"user-name\")]\r\n [:div {:class \"for", "end": 4436, "score": 0.7954992055892944, "start": 4427, "tag": "NAME", "value": "User Name" }, { "context": "word-field\"}\r\n \"new-password\")\r\n [:div {:class \"form-restric", "end": 10822, "score": 0.948833703994751, "start": 10810, "tag": "PASSWORD", "value": "new-password" }, { "context": "\n :for \"password\"} \"Your Password\"]]\r\n (password-field {:class ", "end": 14693, "score": 0.8688544034957886, "start": 14680, "tag": "PASSWORD", "value": "Your Password" }, { "context": "ired \"true\"}\r\n \"password\")]\r\n [:div {:class \"button-bar-c", "end": 14866, "score": 0.7639421820640564, "start": 14858, "tag": "PASSWORD", "value": "password" } ]
src/clj/cwiki/layouts/admin.clj
clartaq/cwiki
3
;;; ;;; This namespace includes layouts normally available only to admin users. ;;; (ns cwiki.layouts.admin (:require [clojure.string :as s] [cwiki.layouts.base :as base] [cwiki.util.req-info :as ri] [cwiki.models.wiki-db :as db] [hiccup.form :refer [drop-down email-field form-to hidden-field password-field submit-button text-field]] [ring.util.anti-forgery :refer [anti-forgery-field]]) (:import (java.net URLDecoder URL))) ;;; ;;; Functions related to saving a seed page. ;;; (defn confirm-save-seed-page "Return a page stating that the file has been saved." [page-name file-name referer] (base/short-message-jump-in-history "Save Complete" (str "Page \"" page-name "\" has been saved to \"" file-name "\".") -2)) (defn compose-save-seed-page "Compose and return a page that allows the user to save a seed page." [req] (let [referer (get (:headers req) "referer") ;; First figure out if they are trying to export the Front Page or ;; a 'regular' page. file-name (.getFile (URL. referer)) page-title (if (= "/" file-name) "Front Page" (let [snip (.substring ^String referer (inc (s/last-index-of referer "/")))] (URLDecoder/decode snip "UTF-8"))) page-id (db/title->page-id page-title)] (if (nil? page-id) (base/short-message-return-to-referer "Page Name Translation Error" (str "There was a problem getting the page name from the referring URL: \"" referer "\".") referer) (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "save-seed-page"] (anti-forgery-field) (hidden-field "page-id" page-id) (hidden-field "referer" referer) [:p {:class "form-title"} "Save Seed Page"] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "filename"} (str "Save and overwrite existing seed page \"" page-title "\"?")]]] [:div {:class "button-bar-container"} (submit-button {:id "save-seed-button" :class "form-button button-bar-item"} "Save") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :autofocus "autofocus" :onclick "window.history.back();"}]])])))) ;; ;; Functions related to creating a new user. ;; (defn compose-user-already-exists-page "Return a page stating that the user already exists." [] (base/short-message "Can't Do That!" "A user with this name already exits.")) (defn confirm-creation-page [user-name referer] (base/short-message-return-to-referer "Creation Complete" (str "User \"" user-name "\" has been created") referer)) (defn create-user-page "Return a page with a form to gather information needed to create a new user." [req] (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "create-user"] (anti-forgery-field) (hidden-field "referer" (get (:headers req) "referer")) [:p {:class "form-title"} "Create A New User"] [:p "Enter information describing the new user."] base/required-field-hint [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "user-name"} "User Name"]] (text-field {:class "form-text-field" :autofocus "autofocus" :required "true" :placeholder "User Name"} "user-name")] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "password"} "Password"]] (password-field {:class "form-password-field" :required "true"} "password")] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "user-role"} "Role"]] (drop-down {:class "form-dropdown" :required "true"} "user-role" ["reader" "writer" "editor" "admin"] "reader")] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "recovery-email"} "Password Recovery email"]] (email-field {:class "form-email-field" :placeholder "email"} "recovery-email")] [:div {:class "button-bar-container"} (submit-button {:id "create-user-button" :class "form-button button-bar-item"} "Create") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :onclick "window.history.back();"}]])])) ;; ;; Functions related to editing the profile of an existing user. ;; (defn- no-users-to-edit-page "Return a page that displays a message that there are no suitable users to edit." [req] (base/short-message "Nothing to Do" "There are no suitable users to edit.")) (defn must-not-be-empty-page "Return a page informing the user that the field cannot be empty." [] (base/short-message "Can't Do That!" "The user name cannot be empty.")) (defn confirm-edits-page "Return a page that confirms the edits have been completed and then go to the page given." [new-name old-name referer] (base/short-message-return-to-referer "Changes Complete" (if (not= new-name old-name) (str "User \"" old-name "\" has been changed to \"" new-name "\"") (str "User \"" new-name "\" has been changed")) referer)) (defn select-user-to-edit-page "Return a form to obtain the name of the user to be edited." [req] (let [all-users (db/get-all-users) cleaned-users (disj all-users "CWiki")] (if (zero? (count cleaned-users)) (no-users-to-edit-page req) (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "select-profile"] (anti-forgery-field) (hidden-field "referer" (get (:headers req) "referer")) [:p {:class "form-title"} "Edit Profile"] base/required-field-hint [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "user-name"} "User Profile to Edit"]] (drop-down {:class "form-dropdown" :required "true" :autofocus "autofocus"} "user-name" cleaned-users)] [:div {class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "password"} "Your Password"]] (password-field {:class "form-password-field" :required "true"} "password")] [:div {:class "button-bar-container"} (submit-button {:id "select-user-button" :class "form-button button-bar-item"} "Select") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :onclick "window.history.back();"}]])])))) (defn edit-user-page "Handle editing the profile of an existing user." [req] (let [user-info (get-in req [:session :edit-user-info]) user-name (:user_name user-info) user-role (s/replace-first (:user_role user-info) ":" "") user-email (:user_email user-info)] (if (nil? user-info) (no-users-to-edit-page req) (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "edit-profile"] (anti-forgery-field) [:p {:class "form-title"} "Edit the Profile of An Existing User"] [:p (str "Make any modifications needed to " user-name "'s profile.")] base/required-field-hint [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "new-user-name"} "User Name"]] (text-field {:class "form-text-field" :autofocus "autofocus" :required "true" :value user-name} "new-user-name") [:div {:class "form-restrictions"} "The user name cannot be empty. Any new user name cannot match an existing user name. The comparison is case-insensitive."]] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "password"} "Password"]] (password-field {:class "form-password-field"} "new-password") [:div {:class "form-restrictions"} "To leave the password as is, leave the field blank."]] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "new-role"} "Role"]] (drop-down {:class "form-dropdown"} "new-role" ["reader" "writer" "editor" "admin"] user-role)] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "recovery-email"} "Password Recovery email"]] (email-field {:class "form-email-field" :value user-email} "new-email") [:div {:class "form-restrictions"} "To erase the email field, delete all of the text in the field and leave it blank."]] [:div {:class "button-bar-container"} (submit-button {:id "change-user-button" :class "form-button button-bar-item"} "Change") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :onclick "window.history.back();"}]])])))) ;; ;; Functions related to deleting a user. ;; (defn wrong-password-page "Compose and return a short page stating that the password checked does not match that of the current user." [req] (base/short-message "Wrong Password" "The password given does not match that of the current user.")) (defn cannot-find-user "Return a page saying that we cannot find the user now." [req] (base/short-message "Well, That's Weird!" "Now that user cannot be found.")) (defn- no-users-to-delete-page "Return a page that displays a message that there are no suitable users to delete." [req] (base/short-message "Nothing to Do" "There are no suitable users to delete.")) (defn confirm-deletion-page [user-name referer] (base/short-message-return-to-referer "Deletion Complete" (str "User \"" user-name "\" has been deleted") referer)) (defn delete-user-page "Return a form to obtain information about a user to be deleted." [req] (let [all-users (db/get-all-users) current-user (ri/req->user-name req) cleaned-users (disj all-users "CWiki" current-user)] (if (zero? (count cleaned-users)) (no-users-to-delete-page req) (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "delete-user"] (anti-forgery-field) (hidden-field "referer" (get (:headers req) "referer")) [:p {:class "form-title"} "Delete A User"] [:p base/warning-span "This action cannot be undone."] base/required-field-hint [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "user-name"} "User to Delete"]] (drop-down {:class "form-dropdown" :required "true"} "user-name" cleaned-users)] [:div {class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "password"} "Your Password"]] (password-field {:class "form-password-field" :required "true"} "password")] [:div {:class "button-bar-container"} (submit-button {:id "login-button" :class "form-button button-bar-item"} "Delete") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :autofocus "autofocus" :onclick "window.history.back();"}]])]))))
6303
;;; ;;; This namespace includes layouts normally available only to admin users. ;;; (ns cwiki.layouts.admin (:require [clojure.string :as s] [cwiki.layouts.base :as base] [cwiki.util.req-info :as ri] [cwiki.models.wiki-db :as db] [hiccup.form :refer [drop-down email-field form-to hidden-field password-field submit-button text-field]] [ring.util.anti-forgery :refer [anti-forgery-field]]) (:import (java.net URLDecoder URL))) ;;; ;;; Functions related to saving a seed page. ;;; (defn confirm-save-seed-page "Return a page stating that the file has been saved." [page-name file-name referer] (base/short-message-jump-in-history "Save Complete" (str "Page \"" page-name "\" has been saved to \"" file-name "\".") -2)) (defn compose-save-seed-page "Compose and return a page that allows the user to save a seed page." [req] (let [referer (get (:headers req) "referer") ;; First figure out if they are trying to export the Front Page or ;; a 'regular' page. file-name (.getFile (URL. referer)) page-title (if (= "/" file-name) "Front Page" (let [snip (.substring ^String referer (inc (s/last-index-of referer "/")))] (URLDecoder/decode snip "UTF-8"))) page-id (db/title->page-id page-title)] (if (nil? page-id) (base/short-message-return-to-referer "Page Name Translation Error" (str "There was a problem getting the page name from the referring URL: \"" referer "\".") referer) (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "save-seed-page"] (anti-forgery-field) (hidden-field "page-id" page-id) (hidden-field "referer" referer) [:p {:class "form-title"} "Save Seed Page"] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "filename"} (str "Save and overwrite existing seed page \"" page-title "\"?")]]] [:div {:class "button-bar-container"} (submit-button {:id "save-seed-button" :class "form-button button-bar-item"} "Save") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :autofocus "autofocus" :onclick "window.history.back();"}]])])))) ;; ;; Functions related to creating a new user. ;; (defn compose-user-already-exists-page "Return a page stating that the user already exists." [] (base/short-message "Can't Do That!" "A user with this name already exits.")) (defn confirm-creation-page [user-name referer] (base/short-message-return-to-referer "Creation Complete" (str "User \"" user-name "\" has been created") referer)) (defn create-user-page "Return a page with a form to gather information needed to create a new user." [req] (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "create-user"] (anti-forgery-field) (hidden-field "referer" (get (:headers req) "referer")) [:p {:class "form-title"} "Create A New User"] [:p "Enter information describing the new user."] base/required-field-hint [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "user-name"} "<NAME>"]] (text-field {:class "form-text-field" :autofocus "autofocus" :required "true" :placeholder "<NAME>"} "user-name")] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "password"} "Password"]] (password-field {:class "form-password-field" :required "true"} "password")] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "user-role"} "Role"]] (drop-down {:class "form-dropdown" :required "true"} "user-role" ["reader" "writer" "editor" "admin"] "reader")] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "recovery-email"} "Password Recovery email"]] (email-field {:class "form-email-field" :placeholder "email"} "recovery-email")] [:div {:class "button-bar-container"} (submit-button {:id "create-user-button" :class "form-button button-bar-item"} "Create") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :onclick "window.history.back();"}]])])) ;; ;; Functions related to editing the profile of an existing user. ;; (defn- no-users-to-edit-page "Return a page that displays a message that there are no suitable users to edit." [req] (base/short-message "Nothing to Do" "There are no suitable users to edit.")) (defn must-not-be-empty-page "Return a page informing the user that the field cannot be empty." [] (base/short-message "Can't Do That!" "The user name cannot be empty.")) (defn confirm-edits-page "Return a page that confirms the edits have been completed and then go to the page given." [new-name old-name referer] (base/short-message-return-to-referer "Changes Complete" (if (not= new-name old-name) (str "User \"" old-name "\" has been changed to \"" new-name "\"") (str "User \"" new-name "\" has been changed")) referer)) (defn select-user-to-edit-page "Return a form to obtain the name of the user to be edited." [req] (let [all-users (db/get-all-users) cleaned-users (disj all-users "CWiki")] (if (zero? (count cleaned-users)) (no-users-to-edit-page req) (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "select-profile"] (anti-forgery-field) (hidden-field "referer" (get (:headers req) "referer")) [:p {:class "form-title"} "Edit Profile"] base/required-field-hint [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "user-name"} "User Profile to Edit"]] (drop-down {:class "form-dropdown" :required "true" :autofocus "autofocus"} "user-name" cleaned-users)] [:div {class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "password"} "Your Password"]] (password-field {:class "form-password-field" :required "true"} "password")] [:div {:class "button-bar-container"} (submit-button {:id "select-user-button" :class "form-button button-bar-item"} "Select") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :onclick "window.history.back();"}]])])))) (defn edit-user-page "Handle editing the profile of an existing user." [req] (let [user-info (get-in req [:session :edit-user-info]) user-name (:user_name user-info) user-role (s/replace-first (:user_role user-info) ":" "") user-email (:user_email user-info)] (if (nil? user-info) (no-users-to-edit-page req) (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "edit-profile"] (anti-forgery-field) [:p {:class "form-title"} "Edit the Profile of An Existing User"] [:p (str "Make any modifications needed to " user-name "'s profile.")] base/required-field-hint [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "new-user-name"} "User Name"]] (text-field {:class "form-text-field" :autofocus "autofocus" :required "true" :value user-name} "new-user-name") [:div {:class "form-restrictions"} "The user name cannot be empty. Any new user name cannot match an existing user name. The comparison is case-insensitive."]] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "password"} "Password"]] (password-field {:class "form-password-field"} "<PASSWORD>") [:div {:class "form-restrictions"} "To leave the password as is, leave the field blank."]] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "new-role"} "Role"]] (drop-down {:class "form-dropdown"} "new-role" ["reader" "writer" "editor" "admin"] user-role)] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "recovery-email"} "Password Recovery email"]] (email-field {:class "form-email-field" :value user-email} "new-email") [:div {:class "form-restrictions"} "To erase the email field, delete all of the text in the field and leave it blank."]] [:div {:class "button-bar-container"} (submit-button {:id "change-user-button" :class "form-button button-bar-item"} "Change") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :onclick "window.history.back();"}]])])))) ;; ;; Functions related to deleting a user. ;; (defn wrong-password-page "Compose and return a short page stating that the password checked does not match that of the current user." [req] (base/short-message "Wrong Password" "The password given does not match that of the current user.")) (defn cannot-find-user "Return a page saying that we cannot find the user now." [req] (base/short-message "Well, That's Weird!" "Now that user cannot be found.")) (defn- no-users-to-delete-page "Return a page that displays a message that there are no suitable users to delete." [req] (base/short-message "Nothing to Do" "There are no suitable users to delete.")) (defn confirm-deletion-page [user-name referer] (base/short-message-return-to-referer "Deletion Complete" (str "User \"" user-name "\" has been deleted") referer)) (defn delete-user-page "Return a form to obtain information about a user to be deleted." [req] (let [all-users (db/get-all-users) current-user (ri/req->user-name req) cleaned-users (disj all-users "CWiki" current-user)] (if (zero? (count cleaned-users)) (no-users-to-delete-page req) (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "delete-user"] (anti-forgery-field) (hidden-field "referer" (get (:headers req) "referer")) [:p {:class "form-title"} "Delete A User"] [:p base/warning-span "This action cannot be undone."] base/required-field-hint [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "user-name"} "User to Delete"]] (drop-down {:class "form-dropdown" :required "true"} "user-name" cleaned-users)] [:div {class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "password"} "<PASSWORD>"]] (password-field {:class "form-password-field" :required "true"} "<PASSWORD>")] [:div {:class "button-bar-container"} (submit-button {:id "login-button" :class "form-button button-bar-item"} "Delete") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :autofocus "autofocus" :onclick "window.history.back();"}]])]))))
true
;;; ;;; This namespace includes layouts normally available only to admin users. ;;; (ns cwiki.layouts.admin (:require [clojure.string :as s] [cwiki.layouts.base :as base] [cwiki.util.req-info :as ri] [cwiki.models.wiki-db :as db] [hiccup.form :refer [drop-down email-field form-to hidden-field password-field submit-button text-field]] [ring.util.anti-forgery :refer [anti-forgery-field]]) (:import (java.net URLDecoder URL))) ;;; ;;; Functions related to saving a seed page. ;;; (defn confirm-save-seed-page "Return a page stating that the file has been saved." [page-name file-name referer] (base/short-message-jump-in-history "Save Complete" (str "Page \"" page-name "\" has been saved to \"" file-name "\".") -2)) (defn compose-save-seed-page "Compose and return a page that allows the user to save a seed page." [req] (let [referer (get (:headers req) "referer") ;; First figure out if they are trying to export the Front Page or ;; a 'regular' page. file-name (.getFile (URL. referer)) page-title (if (= "/" file-name) "Front Page" (let [snip (.substring ^String referer (inc (s/last-index-of referer "/")))] (URLDecoder/decode snip "UTF-8"))) page-id (db/title->page-id page-title)] (if (nil? page-id) (base/short-message-return-to-referer "Page Name Translation Error" (str "There was a problem getting the page name from the referring URL: \"" referer "\".") referer) (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "save-seed-page"] (anti-forgery-field) (hidden-field "page-id" page-id) (hidden-field "referer" referer) [:p {:class "form-title"} "Save Seed Page"] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "filename"} (str "Save and overwrite existing seed page \"" page-title "\"?")]]] [:div {:class "button-bar-container"} (submit-button {:id "save-seed-button" :class "form-button button-bar-item"} "Save") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :autofocus "autofocus" :onclick "window.history.back();"}]])])))) ;; ;; Functions related to creating a new user. ;; (defn compose-user-already-exists-page "Return a page stating that the user already exists." [] (base/short-message "Can't Do That!" "A user with this name already exits.")) (defn confirm-creation-page [user-name referer] (base/short-message-return-to-referer "Creation Complete" (str "User \"" user-name "\" has been created") referer)) (defn create-user-page "Return a page with a form to gather information needed to create a new user." [req] (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "create-user"] (anti-forgery-field) (hidden-field "referer" (get (:headers req) "referer")) [:p {:class "form-title"} "Create A New User"] [:p "Enter information describing the new user."] base/required-field-hint [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "user-name"} "PI:NAME:<NAME>END_PI"]] (text-field {:class "form-text-field" :autofocus "autofocus" :required "true" :placeholder "PI:NAME:<NAME>END_PI"} "user-name")] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "password"} "Password"]] (password-field {:class "form-password-field" :required "true"} "password")] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "user-role"} "Role"]] (drop-down {:class "form-dropdown" :required "true"} "user-role" ["reader" "writer" "editor" "admin"] "reader")] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "recovery-email"} "Password Recovery email"]] (email-field {:class "form-email-field" :placeholder "email"} "recovery-email")] [:div {:class "button-bar-container"} (submit-button {:id "create-user-button" :class "form-button button-bar-item"} "Create") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :onclick "window.history.back();"}]])])) ;; ;; Functions related to editing the profile of an existing user. ;; (defn- no-users-to-edit-page "Return a page that displays a message that there are no suitable users to edit." [req] (base/short-message "Nothing to Do" "There are no suitable users to edit.")) (defn must-not-be-empty-page "Return a page informing the user that the field cannot be empty." [] (base/short-message "Can't Do That!" "The user name cannot be empty.")) (defn confirm-edits-page "Return a page that confirms the edits have been completed and then go to the page given." [new-name old-name referer] (base/short-message-return-to-referer "Changes Complete" (if (not= new-name old-name) (str "User \"" old-name "\" has been changed to \"" new-name "\"") (str "User \"" new-name "\" has been changed")) referer)) (defn select-user-to-edit-page "Return a form to obtain the name of the user to be edited." [req] (let [all-users (db/get-all-users) cleaned-users (disj all-users "CWiki")] (if (zero? (count cleaned-users)) (no-users-to-edit-page req) (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "select-profile"] (anti-forgery-field) (hidden-field "referer" (get (:headers req) "referer")) [:p {:class "form-title"} "Edit Profile"] base/required-field-hint [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "user-name"} "User Profile to Edit"]] (drop-down {:class "form-dropdown" :required "true" :autofocus "autofocus"} "user-name" cleaned-users)] [:div {class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "password"} "Your Password"]] (password-field {:class "form-password-field" :required "true"} "password")] [:div {:class "button-bar-container"} (submit-button {:id "select-user-button" :class "form-button button-bar-item"} "Select") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :onclick "window.history.back();"}]])])))) (defn edit-user-page "Handle editing the profile of an existing user." [req] (let [user-info (get-in req [:session :edit-user-info]) user-name (:user_name user-info) user-role (s/replace-first (:user_role user-info) ":" "") user-email (:user_email user-info)] (if (nil? user-info) (no-users-to-edit-page req) (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "edit-profile"] (anti-forgery-field) [:p {:class "form-title"} "Edit the Profile of An Existing User"] [:p (str "Make any modifications needed to " user-name "'s profile.")] base/required-field-hint [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "new-user-name"} "User Name"]] (text-field {:class "form-text-field" :autofocus "autofocus" :required "true" :value user-name} "new-user-name") [:div {:class "form-restrictions"} "The user name cannot be empty. Any new user name cannot match an existing user name. The comparison is case-insensitive."]] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "password"} "Password"]] (password-field {:class "form-password-field"} "PI:PASSWORD:<PASSWORD>END_PI") [:div {:class "form-restrictions"} "To leave the password as is, leave the field blank."]] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "new-role"} "Role"]] (drop-down {:class "form-dropdown"} "new-role" ["reader" "writer" "editor" "admin"] user-role)] [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label" :for "recovery-email"} "Password Recovery email"]] (email-field {:class "form-email-field" :value user-email} "new-email") [:div {:class "form-restrictions"} "To erase the email field, delete all of the text in the field and leave it blank."]] [:div {:class "button-bar-container"} (submit-button {:id "change-user-button" :class "form-button button-bar-item"} "Change") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :onclick "window.history.back();"}]])])))) ;; ;; Functions related to deleting a user. ;; (defn wrong-password-page "Compose and return a short page stating that the password checked does not match that of the current user." [req] (base/short-message "Wrong Password" "The password given does not match that of the current user.")) (defn cannot-find-user "Return a page saying that we cannot find the user now." [req] (base/short-message "Well, That's Weird!" "Now that user cannot be found.")) (defn- no-users-to-delete-page "Return a page that displays a message that there are no suitable users to delete." [req] (base/short-message "Nothing to Do" "There are no suitable users to delete.")) (defn confirm-deletion-page [user-name referer] (base/short-message-return-to-referer "Deletion Complete" (str "User \"" user-name "\" has been deleted") referer)) (defn delete-user-page "Return a form to obtain information about a user to be deleted." [req] (let [all-users (db/get-all-users) current-user (ri/req->user-name req) cleaned-users (disj all-users "CWiki" current-user)] (if (zero? (count cleaned-users)) (no-users-to-delete-page req) (base/short-form-template [:div {:class "cwiki-form"} (form-to {:enctype "multipart/form-data" :autocomplete "off"} [:post "delete-user"] (anti-forgery-field) (hidden-field "referer" (get (:headers req) "referer")) [:p {:class "form-title"} "Delete A User"] [:p base/warning-span "This action cannot be undone."] base/required-field-hint [:div {:class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "user-name"} "User to Delete"]] (drop-down {:class "form-dropdown" :required "true"} "user-name" cleaned-users)] [:div {class "form-group"} [:div {:class "form-label-div"} [:label {:class "form-label required" :for "password"} "PI:PASSWORD:<PASSWORD>END_PI"]] (password-field {:class "form-password-field" :required "true"} "PI:PASSWORD:<PASSWORD>END_PI")] [:div {:class "button-bar-container"} (submit-button {:id "login-button" :class "form-button button-bar-item"} "Delete") [:input {:type "button" :name "cancel-button" :value "Cancel" :class "form-button button-bar-item" :autofocus "autofocus" :onclick "window.history.back();"}]])]))))
[ { "context": ")]\n [:updated (:date post)]\n [:author [:name \"Jon Woods\"]]\n [:link {:href (str \"http://jonoflayham.com\"", "end": 171, "score": 0.9996675848960876, "start": 162, "tag": "NAME", "value": "Jon Woods" } ]
src/blog_gen/rss.clj
jonoflayham/blog-gen
0
(ns blog-gen.rss (:require [clojure.data.xml :as xml])) (defn- entry [post] [:entry [:title (:title post)] [:updated (:date post)] [:author [:name "Jon Woods"]] [:link {:href (str "http://jonoflayham.com" (:path post))}] [:id (str "urn:jonoflayham-io:feed:post:" (:title post))] [:content {:type "html"} (:content post)]]) (defn atom-xml [posts] (let [sorted-posts (->> posts (sort-by :date) reverse)] (xml/emit-str (xml/sexp-as-element [:feed {:xmlns "http://www.w3.org/2005/Atom"} [:id "urn:jonoflayham-io:feed"] [:updated (-> posts first :date)] [:title {:type "text"} "Loose Typing"] [:link {:rel "self" :href "http://jonoflayham.com/atom.xml"}] (map entry posts)]))))
26346
(ns blog-gen.rss (:require [clojure.data.xml :as xml])) (defn- entry [post] [:entry [:title (:title post)] [:updated (:date post)] [:author [:name "<NAME>"]] [:link {:href (str "http://jonoflayham.com" (:path post))}] [:id (str "urn:jonoflayham-io:feed:post:" (:title post))] [:content {:type "html"} (:content post)]]) (defn atom-xml [posts] (let [sorted-posts (->> posts (sort-by :date) reverse)] (xml/emit-str (xml/sexp-as-element [:feed {:xmlns "http://www.w3.org/2005/Atom"} [:id "urn:jonoflayham-io:feed"] [:updated (-> posts first :date)] [:title {:type "text"} "Loose Typing"] [:link {:rel "self" :href "http://jonoflayham.com/atom.xml"}] (map entry posts)]))))
true
(ns blog-gen.rss (:require [clojure.data.xml :as xml])) (defn- entry [post] [:entry [:title (:title post)] [:updated (:date post)] [:author [:name "PI:NAME:<NAME>END_PI"]] [:link {:href (str "http://jonoflayham.com" (:path post))}] [:id (str "urn:jonoflayham-io:feed:post:" (:title post))] [:content {:type "html"} (:content post)]]) (defn atom-xml [posts] (let [sorted-posts (->> posts (sort-by :date) reverse)] (xml/emit-str (xml/sexp-as-element [:feed {:xmlns "http://www.w3.org/2005/Atom"} [:id "urn:jonoflayham-io:feed"] [:updated (-> posts first :date)] [:title {:type "text"} "Loose Typing"] [:link {:rel "self" :href "http://jonoflayham.com/atom.xml"}] (map entry posts)]))))
[ { "context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; Copyright 2015 Xebia B.V.\n;\n; Licensed under the Apache License, Version 2", "end": 107, "score": 0.9854002594947815, "start": 98, "tag": "NAME", "value": "Xebia B.V" } ]
src/test/clojure/com/xebia/visualreview/service/screenshot_test.clj
andstepanuk/VisualReview
290
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright 2015 Xebia B.V. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns com.xebia.visualreview.service.screenshot-test (:require [clojure.test :refer :all] [slingshot.test] [clojure.java.io :as io] [com.xebia.visualreview.service.screenshot :as s] [com.xebia.visualreview.service.screenshot.persistence :as sp] [com.xebia.visualreview.service.image :as i] [com.xebia.visualreview.test-util :refer :all] [com.xebia.visualreview.service.run :as run]) (:import [java.sql SQLException])) (deftest insert-screenshot (let [run-id 1 image-id 2 image-file (io/as-file (io/resource "tapir_hat.png")) insert-screenshot-fn #(s/insert-screenshot! {} 999 "myScreenshot" {:browser "chrome" :os "windows"} {:version "4.0"} image-file)] (is (thrown+-with-msg? service-exception? #"Could not store screenshot, run id 999 does not exist." (with-mock [run/get-run nil] (insert-screenshot-fn))) "Throws a service exception when given run-id does not exist") (is (thrown+-with-msg? service-exception? #"Could not store screenshot in database: Database error" (with-mock [run/get-run {:id run-id} i/insert-image! {:id image-id} sp/save-screenshot! (throw (SQLException. "Database error"))] (insert-screenshot-fn))) "throws a service exception when screenshot could not be stored in the database") (is (thrown+-with-msg? service-exception? #"Could not store screenshot in database: screenshot with name and properties already exists" (with-mock [run/get-run {:id run-id} i/insert-image! {:id image-id} sp/save-screenshot! (throw (slingshot-exception {:type :sql-exception :subtype ::sp/unique-constraint-violation :message "Duplicate thingy"}))] (insert-screenshot-fn)))))) (deftest get-screenshot-by-id (with-mock [sp/get-screenshot-by-id nil] (is (nil? (s/get-screenshot-by-id {} 999)) "Returns nil when retrieving a screenshot that does not exist")) (with-mock [sp/get-screenshot-by-id (throw (SQLException. "Database error"))] (is (thrown+-with-msg? service-exception? #"Could not retrieve screenshot with id 999: Database error" (s/get-screenshot-by-id {} 999)) "returns a service exception when an error occurs"))) (deftest get-screenshots-by-run-id (with-mock [sp/get-screenshots [{:id 1} {:id 2}]] (is (= [{:id 1} {:id 2}] (s/get-screenshots-by-run-id {} 123)) "Returns a list of screnshots from a run")) (with-mock [sp/get-screenshots (throw (SQLException. "An error occurred 1"))] (is (thrown+-with-msg? service-exception? #"Could not retrieve screenshots: An error occurred 1" (s/get-screenshots-by-run-id {} 123)))))
51595
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; 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 com.xebia.visualreview.service.screenshot-test (:require [clojure.test :refer :all] [slingshot.test] [clojure.java.io :as io] [com.xebia.visualreview.service.screenshot :as s] [com.xebia.visualreview.service.screenshot.persistence :as sp] [com.xebia.visualreview.service.image :as i] [com.xebia.visualreview.test-util :refer :all] [com.xebia.visualreview.service.run :as run]) (:import [java.sql SQLException])) (deftest insert-screenshot (let [run-id 1 image-id 2 image-file (io/as-file (io/resource "tapir_hat.png")) insert-screenshot-fn #(s/insert-screenshot! {} 999 "myScreenshot" {:browser "chrome" :os "windows"} {:version "4.0"} image-file)] (is (thrown+-with-msg? service-exception? #"Could not store screenshot, run id 999 does not exist." (with-mock [run/get-run nil] (insert-screenshot-fn))) "Throws a service exception when given run-id does not exist") (is (thrown+-with-msg? service-exception? #"Could not store screenshot in database: Database error" (with-mock [run/get-run {:id run-id} i/insert-image! {:id image-id} sp/save-screenshot! (throw (SQLException. "Database error"))] (insert-screenshot-fn))) "throws a service exception when screenshot could not be stored in the database") (is (thrown+-with-msg? service-exception? #"Could not store screenshot in database: screenshot with name and properties already exists" (with-mock [run/get-run {:id run-id} i/insert-image! {:id image-id} sp/save-screenshot! (throw (slingshot-exception {:type :sql-exception :subtype ::sp/unique-constraint-violation :message "Duplicate thingy"}))] (insert-screenshot-fn)))))) (deftest get-screenshot-by-id (with-mock [sp/get-screenshot-by-id nil] (is (nil? (s/get-screenshot-by-id {} 999)) "Returns nil when retrieving a screenshot that does not exist")) (with-mock [sp/get-screenshot-by-id (throw (SQLException. "Database error"))] (is (thrown+-with-msg? service-exception? #"Could not retrieve screenshot with id 999: Database error" (s/get-screenshot-by-id {} 999)) "returns a service exception when an error occurs"))) (deftest get-screenshots-by-run-id (with-mock [sp/get-screenshots [{:id 1} {:id 2}]] (is (= [{:id 1} {:id 2}] (s/get-screenshots-by-run-id {} 123)) "Returns a list of screnshots from a run")) (with-mock [sp/get-screenshots (throw (SQLException. "An error occurred 1"))] (is (thrown+-with-msg? service-exception? #"Could not retrieve screenshots: An error occurred 1" (s/get-screenshots-by-run-id {} 123)))))
true
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; 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 com.xebia.visualreview.service.screenshot-test (:require [clojure.test :refer :all] [slingshot.test] [clojure.java.io :as io] [com.xebia.visualreview.service.screenshot :as s] [com.xebia.visualreview.service.screenshot.persistence :as sp] [com.xebia.visualreview.service.image :as i] [com.xebia.visualreview.test-util :refer :all] [com.xebia.visualreview.service.run :as run]) (:import [java.sql SQLException])) (deftest insert-screenshot (let [run-id 1 image-id 2 image-file (io/as-file (io/resource "tapir_hat.png")) insert-screenshot-fn #(s/insert-screenshot! {} 999 "myScreenshot" {:browser "chrome" :os "windows"} {:version "4.0"} image-file)] (is (thrown+-with-msg? service-exception? #"Could not store screenshot, run id 999 does not exist." (with-mock [run/get-run nil] (insert-screenshot-fn))) "Throws a service exception when given run-id does not exist") (is (thrown+-with-msg? service-exception? #"Could not store screenshot in database: Database error" (with-mock [run/get-run {:id run-id} i/insert-image! {:id image-id} sp/save-screenshot! (throw (SQLException. "Database error"))] (insert-screenshot-fn))) "throws a service exception when screenshot could not be stored in the database") (is (thrown+-with-msg? service-exception? #"Could not store screenshot in database: screenshot with name and properties already exists" (with-mock [run/get-run {:id run-id} i/insert-image! {:id image-id} sp/save-screenshot! (throw (slingshot-exception {:type :sql-exception :subtype ::sp/unique-constraint-violation :message "Duplicate thingy"}))] (insert-screenshot-fn)))))) (deftest get-screenshot-by-id (with-mock [sp/get-screenshot-by-id nil] (is (nil? (s/get-screenshot-by-id {} 999)) "Returns nil when retrieving a screenshot that does not exist")) (with-mock [sp/get-screenshot-by-id (throw (SQLException. "Database error"))] (is (thrown+-with-msg? service-exception? #"Could not retrieve screenshot with id 999: Database error" (s/get-screenshot-by-id {} 999)) "returns a service exception when an error occurs"))) (deftest get-screenshots-by-run-id (with-mock [sp/get-screenshots [{:id 1} {:id 2}]] (is (= [{:id 1} {:id 2}] (s/get-screenshots-by-run-id {} 123)) "Returns a list of screnshots from a run")) (with-mock [sp/get-screenshots (throw (SQLException. "An error occurred 1"))] (is (thrown+-with-msg? service-exception? #"Could not retrieve screenshots: An error occurred 1" (s/get-screenshots-by-run-id {} 123)))))
[ { "context": "y\n;because the buffers are large.\n(ns ^{ :author \"Alex Seewald\" }\n philharmonia-samples.sampled-viola\n (:use [", "end": 198, "score": 0.9998720288276672, "start": 186, "tag": "NAME", "value": "Alex Seewald" } ]
data/test/clojure/87b86486660ebcf6344b6d638627f001276a14c3sampled_viola.clj
harshp8l/deep-learning-lang-detection
84
;the sense in making a file for each instrument is that people can include them in their own namespaces individually, which can be costly ;because the buffers are large. (ns ^{ :author "Alex Seewald" } philharmonia-samples.sampled-viola (:use [philharmonia-samples.sample-utils] [overtone.live])) (def viola-samples (path-to-described-samples (str sampleroot "/viola"))) (def defaults (array-map :note "67" :duration "025" :loudness "fortissimo" :style "arco-normal")) (def features (featureset [:note :duration :loudness :style] (keys viola-samples))) (def distance-maxes {:note 1 :duration 4 :loudness 3 :style 6}) (def ^:private tmp (play-gen viola-samples defaults features distance-maxes)) (def viola (:ugen tmp)) (def viola-inst (:effect tmp)) (def violai (:effect tmp))
120571
;the sense in making a file for each instrument is that people can include them in their own namespaces individually, which can be costly ;because the buffers are large. (ns ^{ :author "<NAME>" } philharmonia-samples.sampled-viola (:use [philharmonia-samples.sample-utils] [overtone.live])) (def viola-samples (path-to-described-samples (str sampleroot "/viola"))) (def defaults (array-map :note "67" :duration "025" :loudness "fortissimo" :style "arco-normal")) (def features (featureset [:note :duration :loudness :style] (keys viola-samples))) (def distance-maxes {:note 1 :duration 4 :loudness 3 :style 6}) (def ^:private tmp (play-gen viola-samples defaults features distance-maxes)) (def viola (:ugen tmp)) (def viola-inst (:effect tmp)) (def violai (:effect tmp))
true
;the sense in making a file for each instrument is that people can include them in their own namespaces individually, which can be costly ;because the buffers are large. (ns ^{ :author "PI:NAME:<NAME>END_PI" } philharmonia-samples.sampled-viola (:use [philharmonia-samples.sample-utils] [overtone.live])) (def viola-samples (path-to-described-samples (str sampleroot "/viola"))) (def defaults (array-map :note "67" :duration "025" :loudness "fortissimo" :style "arco-normal")) (def features (featureset [:note :duration :loudness :style] (keys viola-samples))) (def distance-maxes {:note 1 :duration 4 :loudness 3 :style 6}) (def ^:private tmp (play-gen viola-samples defaults features distance-maxes)) (def viola (:ugen tmp)) (def viola-inst (:effect tmp)) (def violai (:effect tmp))
[ { "context": ";; Copyright (c) 2014, Paul Mucur (http://mudge.name)\n;; Released under the Eclipse", "end": 33, "score": 0.9998564124107361, "start": 23, "tag": "NAME", "value": "Paul Mucur" } ]
data/train/clojure/2e9fb6d51bd33d36cfe4550e714e931660ab5f51reader.clj
harshp8l/deep-learning-lang-detection
84
;; Copyright (c) 2014, Paul Mucur (http://mudge.name) ;; Released under the Eclipse Public License: ;; http://www.eclipse.org/legal/epl-v10.html (ns php_clj.reader (:require [clojure.string :as s]) (:import [java.io ByteArrayInputStream BufferedInputStream])) (defn buffered-input-stream "Returns a BufferedInputStream for a string." [^String s] (-> s .getBytes ByteArrayInputStream. BufferedInputStream.)) (defn read-char "Reads a single character from a BufferedInputStream and returns it. Note that this mutates the given stream." [^BufferedInputStream stream] (-> stream .read char)) (defn read-str "Reads n bytes from a BufferedInputStream and returns them as a string. Note that this mutates the given stream." [^BufferedInputStream stream n] (let [selected-bytes (byte-array n)] (.read stream selected-bytes) (String. selected-bytes))) (defn read-until "Reads from the given stream until a specified character is found and returns the string up to that point (not including the delimiter). Note that this mutates the given stream." [reader delimiter] (loop [acc []] (let [c (read-char reader)] (if (= delimiter c) (s/join acc) (recur (conj acc c))))))
112965
;; Copyright (c) 2014, <NAME> (http://mudge.name) ;; Released under the Eclipse Public License: ;; http://www.eclipse.org/legal/epl-v10.html (ns php_clj.reader (:require [clojure.string :as s]) (:import [java.io ByteArrayInputStream BufferedInputStream])) (defn buffered-input-stream "Returns a BufferedInputStream for a string." [^String s] (-> s .getBytes ByteArrayInputStream. BufferedInputStream.)) (defn read-char "Reads a single character from a BufferedInputStream and returns it. Note that this mutates the given stream." [^BufferedInputStream stream] (-> stream .read char)) (defn read-str "Reads n bytes from a BufferedInputStream and returns them as a string. Note that this mutates the given stream." [^BufferedInputStream stream n] (let [selected-bytes (byte-array n)] (.read stream selected-bytes) (String. selected-bytes))) (defn read-until "Reads from the given stream until a specified character is found and returns the string up to that point (not including the delimiter). Note that this mutates the given stream." [reader delimiter] (loop [acc []] (let [c (read-char reader)] (if (= delimiter c) (s/join acc) (recur (conj acc c))))))
true
;; Copyright (c) 2014, PI:NAME:<NAME>END_PI (http://mudge.name) ;; Released under the Eclipse Public License: ;; http://www.eclipse.org/legal/epl-v10.html (ns php_clj.reader (:require [clojure.string :as s]) (:import [java.io ByteArrayInputStream BufferedInputStream])) (defn buffered-input-stream "Returns a BufferedInputStream for a string." [^String s] (-> s .getBytes ByteArrayInputStream. BufferedInputStream.)) (defn read-char "Reads a single character from a BufferedInputStream and returns it. Note that this mutates the given stream." [^BufferedInputStream stream] (-> stream .read char)) (defn read-str "Reads n bytes from a BufferedInputStream and returns them as a string. Note that this mutates the given stream." [^BufferedInputStream stream n] (let [selected-bytes (byte-array n)] (.read stream selected-bytes) (String. selected-bytes))) (defn read-until "Reads from the given stream until a specified character is found and returns the string up to that point (not including the delimiter). Note that this mutates the given stream." [reader delimiter] (loop [acc []] (let [c (read-char reader)] (if (= delimiter c) (s/join acc) (recur (conj acc c))))))
[ { "context": " around\n with orchestrate.io and thinking about ted dziuba's thoughts on\n REVAT (http://teddziuba.gith", "end": 131, "score": 0.5892882347106934, "start": 127, "tag": "NAME", "value": "ed d" } ]
src/orch/atom.clj
joegallo/orch
1
(ns orch.atom "this is just a little tech demo that i created while playing around with orchestrate.io and thinking about ted dziuba's thoughts on REVAT (http://teddziuba.github.io/2014/08/18/the-s-in-rest/) -- this is obviously not a fully-featured client, it's just a toy" (:refer-clojure :exclude [atom swap! reset!]) (:require [orch.api :as o])) (defrecord OAtom [collection key] clojure.lang.IDeref (deref [_] (o/get collection key))) ;; blergh... this was required to make oatoms print nicely at the repl ;; rather than throwing an exception (defmethod print-method OAtom [o ^java.io.Writer w] (.write w (str (format "#<%s@%x: " (.getSimpleName (class o)) (System/identityHashCode o)) (pr-str @o) ">"))) (defn atom "oatom constructor" ;; it doesn't take an initial value, because we're building an ;; object for representing a remote cell, and there might already be ;; a value there. ;; also we're not doing anything fancy like :metadata-map or validators [coll key] (->OAtom coll key)) (defn swap! "like clojure.core/swap!, but for oatoms" [oatom f & args] (loop [] (let [curr @oatom newval (apply f curr args)] (if-let [ret (o/put! (:collection oatom) (:key oatom) (:ref (meta curr)) newval)] ;; it worked, return the new newval ret ;; it failed, try again (recur))))) (defn reset! "like clojure.core/reset!, but for oatoms" [oatom newval] (o/put! (:collection oatom) (:key oatom) newval))
61488
(ns orch.atom "this is just a little tech demo that i created while playing around with orchestrate.io and thinking about t<NAME>ziuba's thoughts on REVAT (http://teddziuba.github.io/2014/08/18/the-s-in-rest/) -- this is obviously not a fully-featured client, it's just a toy" (:refer-clojure :exclude [atom swap! reset!]) (:require [orch.api :as o])) (defrecord OAtom [collection key] clojure.lang.IDeref (deref [_] (o/get collection key))) ;; blergh... this was required to make oatoms print nicely at the repl ;; rather than throwing an exception (defmethod print-method OAtom [o ^java.io.Writer w] (.write w (str (format "#<%s@%x: " (.getSimpleName (class o)) (System/identityHashCode o)) (pr-str @o) ">"))) (defn atom "oatom constructor" ;; it doesn't take an initial value, because we're building an ;; object for representing a remote cell, and there might already be ;; a value there. ;; also we're not doing anything fancy like :metadata-map or validators [coll key] (->OAtom coll key)) (defn swap! "like clojure.core/swap!, but for oatoms" [oatom f & args] (loop [] (let [curr @oatom newval (apply f curr args)] (if-let [ret (o/put! (:collection oatom) (:key oatom) (:ref (meta curr)) newval)] ;; it worked, return the new newval ret ;; it failed, try again (recur))))) (defn reset! "like clojure.core/reset!, but for oatoms" [oatom newval] (o/put! (:collection oatom) (:key oatom) newval))
true
(ns orch.atom "this is just a little tech demo that i created while playing around with orchestrate.io and thinking about tPI:NAME:<NAME>END_PIziuba's thoughts on REVAT (http://teddziuba.github.io/2014/08/18/the-s-in-rest/) -- this is obviously not a fully-featured client, it's just a toy" (:refer-clojure :exclude [atom swap! reset!]) (:require [orch.api :as o])) (defrecord OAtom [collection key] clojure.lang.IDeref (deref [_] (o/get collection key))) ;; blergh... this was required to make oatoms print nicely at the repl ;; rather than throwing an exception (defmethod print-method OAtom [o ^java.io.Writer w] (.write w (str (format "#<%s@%x: " (.getSimpleName (class o)) (System/identityHashCode o)) (pr-str @o) ">"))) (defn atom "oatom constructor" ;; it doesn't take an initial value, because we're building an ;; object for representing a remote cell, and there might already be ;; a value there. ;; also we're not doing anything fancy like :metadata-map or validators [coll key] (->OAtom coll key)) (defn swap! "like clojure.core/swap!, but for oatoms" [oatom f & args] (loop [] (let [curr @oatom newval (apply f curr args)] (if-let [ret (o/put! (:collection oatom) (:key oatom) (:ref (meta curr)) newval)] ;; it worked, return the new newval ret ;; it failed, try again (recur))))) (defn reset! "like clojure.core/reset!, but for oatoms" [oatom newval] (o/put! (:collection oatom) (:key oatom) newval))
[ { "context": " :password password\n :usern", "end": 1598, "score": 0.8631311655044556, "start": 1590, "tag": "PASSWORD", "value": "password" } ]
code/src/sixsq/nuvla/server/resources/user_username_password.clj
nuvla/server
6
(ns sixsq.nuvla.server.resources.user-username-password " Provides the functions necessary to create a `user` resource from a username, password, and other given information." (:require [sixsq.nuvla.server.resources.common.utils :as u] [sixsq.nuvla.server.resources.spec.user] [sixsq.nuvla.server.resources.spec.user-template-username-password :as spec-username-password] [sixsq.nuvla.server.resources.user-interface :as p] [sixsq.nuvla.server.resources.user-template-username-password :as username-password] [sixsq.nuvla.server.resources.user.password :as password-utils] [sixsq.nuvla.server.resources.user.utils :as user-utils])) ;; ;; multimethod for validation ;; (def create-validate-fn-username (u/create-spec-validation-fn ::spec-username-password/schema-create)) (defmethod p/create-validate-subtype username-password/registration-method [{resource :template :as create-document}] (user-utils/check-password-constraints resource) (create-validate-fn-username create-document)) ;; ;; transformation of template ;; (defmethod p/tpl->user username-password/registration-method [resource _request] [nil (-> resource password-utils/create-user-map (assoc :state "ACTIVE"))]) ;; ;; create/update all related resources ;; (defmethod p/post-user-add username-password/registration-method [{user-id :id :as _resource} {:keys [body] :as _request}] (try (let [{{:keys [password username]} :template} body] (user-utils/create-user-subresources user-id :password password :username username)) (catch Exception e (user-utils/delete-user user-id) (throw e))))
794
(ns sixsq.nuvla.server.resources.user-username-password " Provides the functions necessary to create a `user` resource from a username, password, and other given information." (:require [sixsq.nuvla.server.resources.common.utils :as u] [sixsq.nuvla.server.resources.spec.user] [sixsq.nuvla.server.resources.spec.user-template-username-password :as spec-username-password] [sixsq.nuvla.server.resources.user-interface :as p] [sixsq.nuvla.server.resources.user-template-username-password :as username-password] [sixsq.nuvla.server.resources.user.password :as password-utils] [sixsq.nuvla.server.resources.user.utils :as user-utils])) ;; ;; multimethod for validation ;; (def create-validate-fn-username (u/create-spec-validation-fn ::spec-username-password/schema-create)) (defmethod p/create-validate-subtype username-password/registration-method [{resource :template :as create-document}] (user-utils/check-password-constraints resource) (create-validate-fn-username create-document)) ;; ;; transformation of template ;; (defmethod p/tpl->user username-password/registration-method [resource _request] [nil (-> resource password-utils/create-user-map (assoc :state "ACTIVE"))]) ;; ;; create/update all related resources ;; (defmethod p/post-user-add username-password/registration-method [{user-id :id :as _resource} {:keys [body] :as _request}] (try (let [{{:keys [password username]} :template} body] (user-utils/create-user-subresources user-id :password <PASSWORD> :username username)) (catch Exception e (user-utils/delete-user user-id) (throw e))))
true
(ns sixsq.nuvla.server.resources.user-username-password " Provides the functions necessary to create a `user` resource from a username, password, and other given information." (:require [sixsq.nuvla.server.resources.common.utils :as u] [sixsq.nuvla.server.resources.spec.user] [sixsq.nuvla.server.resources.spec.user-template-username-password :as spec-username-password] [sixsq.nuvla.server.resources.user-interface :as p] [sixsq.nuvla.server.resources.user-template-username-password :as username-password] [sixsq.nuvla.server.resources.user.password :as password-utils] [sixsq.nuvla.server.resources.user.utils :as user-utils])) ;; ;; multimethod for validation ;; (def create-validate-fn-username (u/create-spec-validation-fn ::spec-username-password/schema-create)) (defmethod p/create-validate-subtype username-password/registration-method [{resource :template :as create-document}] (user-utils/check-password-constraints resource) (create-validate-fn-username create-document)) ;; ;; transformation of template ;; (defmethod p/tpl->user username-password/registration-method [resource _request] [nil (-> resource password-utils/create-user-map (assoc :state "ACTIVE"))]) ;; ;; create/update all related resources ;; (defmethod p/post-user-add username-password/registration-method [{user-id :id :as _resource} {:keys [body] :as _request}] (try (let [{{:keys [password username]} :template} body] (user-utils/create-user-subresources user-id :password PI:PASSWORD:<PASSWORD>END_PI :username username)) (catch Exception e (user-utils/delete-user user-id) (throw e))))
[ { "context": "id (ref/new 1755))\n (restaurant-name (ref/new \"Venezia\"))\n (customer-name (ref/new \"Jan Kowalski\")", "end": 2904, "score": 0.5629533529281616, "start": 2900, "tag": "NAME", "value": "Vene" }, { "context": "(ref/new \"Venezia\"))\n (customer-name (ref/new \"Jan Kowalski\"))\n (customer-phone (ref/new \"123\"))\n (conf", "end": 2952, "score": 0.9997912645339966, "start": 2940, "tag": "NAME", "value": "Jan Kowalski" } ]
example/index.clj
zyla/random-lisp
0
; Unit ; (Array Int) ; (-> [(Array a) (Array a)] (Array a)) ; (forall [a b c] (-> (-> [a] b) (-> [b] c) (-> [a] c))) (declare print : (forall [a] (-> [a] Unit))) ; print :: forall a. a -> Unit (declare concat : (-> [String String] String)) (declare array/concat : (forall [a] (-> [(Array a) (Array a)] (Array a)))) (declare int->string : (-> [Int] String)) (declare + : (-> [Int Int] Int)) (declare - : (-> [Int Int] Int)) (declare if : (forall [a] (-> [Boolean a a] a))) (declare false : Boolean) (declare true : Boolean) (declare not : (-> [Boolean] Boolean)) ; (f a b c) ; x ; "" ; 5 ; (fn [(a Int) (b Int)] (+ a b)) ; (do e1 e2 e3) ; (let [(a e1) (e e2)] ...) (declare dynamic/pure : (forall [a] (-> [a] (Dynamic a)))) (declare dynamic/bind : (forall [a b] (-> [(Dynamic a) (-> [a] (Dynamic b))] (Dynamic b)))) (declare dynamic/subscribe : (forall [a] (-> [(Dynamic a) (-> [a] Unit)] Unit))) (declare dynamic/read : (forall [a] (-> [(Dynamic a)] a))) (declare ref/new : (forall [a] (-> [a] (Dynamic a)))) (declare ref/write : (forall [a] (-> [(Dynamic a) (Dynamic a)] Unit))) (defn debug-subscribe [(name String) (dyn (Dynamic Int))] (dynamic/subscribe dyn (fn [(x Int)] (print (concat (concat name ": ") (int->string x)))))) (defn debug-subscribe-str [(name String) (dyn (Dynamic String))] (dynamic/subscribe dyn (fn [(x String)] (print (concat (concat name ": ") x))))) (declare ref/write-constant : (forall [a] (-> [(Dynamic a) a] Unit))) (def main (do (debug-subscribe "pure 5" (dynamic/pure 5)) (debug-subscribe "5 >>= (+1)" (dynamic/bind (dynamic/pure 5) (fn [(x Int)] (dynamic/pure (+ x 1))))) (let [ (count (ref/new 0)) (x (ref/new 0)) (y (ref/new 0)) ] (debug-subscribe "count" count) (debug-subscribe-str "x, y" (concat (int->string x) (concat ", " (int->string y)))) (debug-subscribe-str "x" (int->string x)) (ref/write x (+ x 1)) (ref/write y 5) (ref/write y 10) ) )) (defn test [] (let [(x (ref/new 0))] (ref/write-constant x (+ x 1))) ) (declare el : (-> [String (Array Prop) (-> [] Unit)] Unit)) (declare text : (-> [(Dynamic String)] Unit)) (declare on-click : (-> [(-> [] Unit)] Prop)) (declare on-input : (-> [(-> [String] Unit)] Prop)) (declare attr : (-> [String (Dynamic String)] Prop)) (declare attr-if : (-> [(Dynamic Boolean) String (Dynamic String)] Prop)) (declare render-in-body : (-> [(-> [] Unit)] Unit)) ; Hack, as we can't yet type an empty array (declare no-props : (Array Prop)) (defn text-input [(props (Array Prop)) (ref (Dynamic String))] (el "input" (array/concat props [(on-input (fn [(value String)] (ref/write ref value))) (attr "value" ref)]) (fn [] (do)))) (def order-example (fn [] (let [ (order-id (ref/new 1755)) (restaurant-name (ref/new "Venezia")) (customer-name (ref/new "Jan Kowalski")) (customer-phone (ref/new "123")) (confirmed (ref/new false)) (details-row (fn [(label String) (body (-> [] Unit))] (el "tr" no-props (fn [] (el "th" no-props (fn [] (text label))) (el "td" no-props body) )))) ] (render-in-body (fn [] (el "table" no-props (fn [] (details-row "Order id" (fn [] (text (int->string order-id)))) (details-row "Restaurant" (fn [] (text restaurant-name))) (details-row "Customer" (fn [] (text (concat (concat customer-name ", ") customer-phone)))) (details-row "Status" (fn [] (text (if confirmed "Confirmed" "Waiting")))) )) (el "div" no-props (fn [] (el "label" no-props (fn [] (text "Customer name: "))) (text-input no-props customer-name))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write customer-phone (concat customer-phone "7"))))] (fn [] (text "Change phone"))))) (el "div" no-props (fn [] (el "label" no-props (fn [] (text "Restaurant: "))) (text-input no-props restaurant-name))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write confirmed true))) (attr-if confirmed "disabled" "disabled") ] (fn [] (text "Confirm"))))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write confirmed false))) (attr-if (not confirmed) "disabled" "disabled") ] (fn [] (text "Unconfirm"))))) ))) )) (def counter-example (fn [] (let [ (count (ref/new 0)) ] (render-in-body (fn [] (el "h2" no-props (fn [] (text "Counter"))) (el "div" no-props (fn [] (text (int->string count)))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write count (+ count 1))))] (fn [] (text "Increment"))))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write count (- count 1))))] (fn [] (text "Decrement"))))) )) ))) (def main (order-example))
69343
; Unit ; (Array Int) ; (-> [(Array a) (Array a)] (Array a)) ; (forall [a b c] (-> (-> [a] b) (-> [b] c) (-> [a] c))) (declare print : (forall [a] (-> [a] Unit))) ; print :: forall a. a -> Unit (declare concat : (-> [String String] String)) (declare array/concat : (forall [a] (-> [(Array a) (Array a)] (Array a)))) (declare int->string : (-> [Int] String)) (declare + : (-> [Int Int] Int)) (declare - : (-> [Int Int] Int)) (declare if : (forall [a] (-> [Boolean a a] a))) (declare false : Boolean) (declare true : Boolean) (declare not : (-> [Boolean] Boolean)) ; (f a b c) ; x ; "" ; 5 ; (fn [(a Int) (b Int)] (+ a b)) ; (do e1 e2 e3) ; (let [(a e1) (e e2)] ...) (declare dynamic/pure : (forall [a] (-> [a] (Dynamic a)))) (declare dynamic/bind : (forall [a b] (-> [(Dynamic a) (-> [a] (Dynamic b))] (Dynamic b)))) (declare dynamic/subscribe : (forall [a] (-> [(Dynamic a) (-> [a] Unit)] Unit))) (declare dynamic/read : (forall [a] (-> [(Dynamic a)] a))) (declare ref/new : (forall [a] (-> [a] (Dynamic a)))) (declare ref/write : (forall [a] (-> [(Dynamic a) (Dynamic a)] Unit))) (defn debug-subscribe [(name String) (dyn (Dynamic Int))] (dynamic/subscribe dyn (fn [(x Int)] (print (concat (concat name ": ") (int->string x)))))) (defn debug-subscribe-str [(name String) (dyn (Dynamic String))] (dynamic/subscribe dyn (fn [(x String)] (print (concat (concat name ": ") x))))) (declare ref/write-constant : (forall [a] (-> [(Dynamic a) a] Unit))) (def main (do (debug-subscribe "pure 5" (dynamic/pure 5)) (debug-subscribe "5 >>= (+1)" (dynamic/bind (dynamic/pure 5) (fn [(x Int)] (dynamic/pure (+ x 1))))) (let [ (count (ref/new 0)) (x (ref/new 0)) (y (ref/new 0)) ] (debug-subscribe "count" count) (debug-subscribe-str "x, y" (concat (int->string x) (concat ", " (int->string y)))) (debug-subscribe-str "x" (int->string x)) (ref/write x (+ x 1)) (ref/write y 5) (ref/write y 10) ) )) (defn test [] (let [(x (ref/new 0))] (ref/write-constant x (+ x 1))) ) (declare el : (-> [String (Array Prop) (-> [] Unit)] Unit)) (declare text : (-> [(Dynamic String)] Unit)) (declare on-click : (-> [(-> [] Unit)] Prop)) (declare on-input : (-> [(-> [String] Unit)] Prop)) (declare attr : (-> [String (Dynamic String)] Prop)) (declare attr-if : (-> [(Dynamic Boolean) String (Dynamic String)] Prop)) (declare render-in-body : (-> [(-> [] Unit)] Unit)) ; Hack, as we can't yet type an empty array (declare no-props : (Array Prop)) (defn text-input [(props (Array Prop)) (ref (Dynamic String))] (el "input" (array/concat props [(on-input (fn [(value String)] (ref/write ref value))) (attr "value" ref)]) (fn [] (do)))) (def order-example (fn [] (let [ (order-id (ref/new 1755)) (restaurant-name (ref/new "<NAME>zia")) (customer-name (ref/new "<NAME>")) (customer-phone (ref/new "123")) (confirmed (ref/new false)) (details-row (fn [(label String) (body (-> [] Unit))] (el "tr" no-props (fn [] (el "th" no-props (fn [] (text label))) (el "td" no-props body) )))) ] (render-in-body (fn [] (el "table" no-props (fn [] (details-row "Order id" (fn [] (text (int->string order-id)))) (details-row "Restaurant" (fn [] (text restaurant-name))) (details-row "Customer" (fn [] (text (concat (concat customer-name ", ") customer-phone)))) (details-row "Status" (fn [] (text (if confirmed "Confirmed" "Waiting")))) )) (el "div" no-props (fn [] (el "label" no-props (fn [] (text "Customer name: "))) (text-input no-props customer-name))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write customer-phone (concat customer-phone "7"))))] (fn [] (text "Change phone"))))) (el "div" no-props (fn [] (el "label" no-props (fn [] (text "Restaurant: "))) (text-input no-props restaurant-name))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write confirmed true))) (attr-if confirmed "disabled" "disabled") ] (fn [] (text "Confirm"))))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write confirmed false))) (attr-if (not confirmed) "disabled" "disabled") ] (fn [] (text "Unconfirm"))))) ))) )) (def counter-example (fn [] (let [ (count (ref/new 0)) ] (render-in-body (fn [] (el "h2" no-props (fn [] (text "Counter"))) (el "div" no-props (fn [] (text (int->string count)))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write count (+ count 1))))] (fn [] (text "Increment"))))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write count (- count 1))))] (fn [] (text "Decrement"))))) )) ))) (def main (order-example))
true
; Unit ; (Array Int) ; (-> [(Array a) (Array a)] (Array a)) ; (forall [a b c] (-> (-> [a] b) (-> [b] c) (-> [a] c))) (declare print : (forall [a] (-> [a] Unit))) ; print :: forall a. a -> Unit (declare concat : (-> [String String] String)) (declare array/concat : (forall [a] (-> [(Array a) (Array a)] (Array a)))) (declare int->string : (-> [Int] String)) (declare + : (-> [Int Int] Int)) (declare - : (-> [Int Int] Int)) (declare if : (forall [a] (-> [Boolean a a] a))) (declare false : Boolean) (declare true : Boolean) (declare not : (-> [Boolean] Boolean)) ; (f a b c) ; x ; "" ; 5 ; (fn [(a Int) (b Int)] (+ a b)) ; (do e1 e2 e3) ; (let [(a e1) (e e2)] ...) (declare dynamic/pure : (forall [a] (-> [a] (Dynamic a)))) (declare dynamic/bind : (forall [a b] (-> [(Dynamic a) (-> [a] (Dynamic b))] (Dynamic b)))) (declare dynamic/subscribe : (forall [a] (-> [(Dynamic a) (-> [a] Unit)] Unit))) (declare dynamic/read : (forall [a] (-> [(Dynamic a)] a))) (declare ref/new : (forall [a] (-> [a] (Dynamic a)))) (declare ref/write : (forall [a] (-> [(Dynamic a) (Dynamic a)] Unit))) (defn debug-subscribe [(name String) (dyn (Dynamic Int))] (dynamic/subscribe dyn (fn [(x Int)] (print (concat (concat name ": ") (int->string x)))))) (defn debug-subscribe-str [(name String) (dyn (Dynamic String))] (dynamic/subscribe dyn (fn [(x String)] (print (concat (concat name ": ") x))))) (declare ref/write-constant : (forall [a] (-> [(Dynamic a) a] Unit))) (def main (do (debug-subscribe "pure 5" (dynamic/pure 5)) (debug-subscribe "5 >>= (+1)" (dynamic/bind (dynamic/pure 5) (fn [(x Int)] (dynamic/pure (+ x 1))))) (let [ (count (ref/new 0)) (x (ref/new 0)) (y (ref/new 0)) ] (debug-subscribe "count" count) (debug-subscribe-str "x, y" (concat (int->string x) (concat ", " (int->string y)))) (debug-subscribe-str "x" (int->string x)) (ref/write x (+ x 1)) (ref/write y 5) (ref/write y 10) ) )) (defn test [] (let [(x (ref/new 0))] (ref/write-constant x (+ x 1))) ) (declare el : (-> [String (Array Prop) (-> [] Unit)] Unit)) (declare text : (-> [(Dynamic String)] Unit)) (declare on-click : (-> [(-> [] Unit)] Prop)) (declare on-input : (-> [(-> [String] Unit)] Prop)) (declare attr : (-> [String (Dynamic String)] Prop)) (declare attr-if : (-> [(Dynamic Boolean) String (Dynamic String)] Prop)) (declare render-in-body : (-> [(-> [] Unit)] Unit)) ; Hack, as we can't yet type an empty array (declare no-props : (Array Prop)) (defn text-input [(props (Array Prop)) (ref (Dynamic String))] (el "input" (array/concat props [(on-input (fn [(value String)] (ref/write ref value))) (attr "value" ref)]) (fn [] (do)))) (def order-example (fn [] (let [ (order-id (ref/new 1755)) (restaurant-name (ref/new "PI:NAME:<NAME>END_PIzia")) (customer-name (ref/new "PI:NAME:<NAME>END_PI")) (customer-phone (ref/new "123")) (confirmed (ref/new false)) (details-row (fn [(label String) (body (-> [] Unit))] (el "tr" no-props (fn [] (el "th" no-props (fn [] (text label))) (el "td" no-props body) )))) ] (render-in-body (fn [] (el "table" no-props (fn [] (details-row "Order id" (fn [] (text (int->string order-id)))) (details-row "Restaurant" (fn [] (text restaurant-name))) (details-row "Customer" (fn [] (text (concat (concat customer-name ", ") customer-phone)))) (details-row "Status" (fn [] (text (if confirmed "Confirmed" "Waiting")))) )) (el "div" no-props (fn [] (el "label" no-props (fn [] (text "Customer name: "))) (text-input no-props customer-name))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write customer-phone (concat customer-phone "7"))))] (fn [] (text "Change phone"))))) (el "div" no-props (fn [] (el "label" no-props (fn [] (text "Restaurant: "))) (text-input no-props restaurant-name))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write confirmed true))) (attr-if confirmed "disabled" "disabled") ] (fn [] (text "Confirm"))))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write confirmed false))) (attr-if (not confirmed) "disabled" "disabled") ] (fn [] (text "Unconfirm"))))) ))) )) (def counter-example (fn [] (let [ (count (ref/new 0)) ] (render-in-body (fn [] (el "h2" no-props (fn [] (text "Counter"))) (el "div" no-props (fn [] (text (int->string count)))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write count (+ count 1))))] (fn [] (text "Increment"))))) (el "div" no-props (fn [] (el "button" [(on-click (fn [] (ref/write count (- count 1))))] (fn [] (text "Decrement"))))) )) ))) (def main (order-example))
[ { "context": "c\n :highlight/next inc})\n\n(def ex0-ui\n [\" Alan Kay\"\n \" J.C.R. Licklider\"\n \" John McCarthy\" ]", "end": 959, "score": 0.9998307228088379, "start": 951, "tag": "NAME", "value": "Alan Kay" }, { "context": "ext inc})\n\n(def ex0-ui\n [\" Alan Kay\"\n \" J.C.R. Licklider\"\n \" John McCarthy\" ])\n\n(def ex1-ui\n [\" Sma", "end": 984, "score": 0.9998852014541626, "start": 968, "tag": "NAME", "value": "J.C.R. Licklider" }, { "context": "i\n [\" Alan Kay\"\n \" J.C.R. Licklider\"\n \" John McCarthy\" ])\n\n(def ex1-ui\n [\" Smalltalk\"\n \" Lisp\"\n ", "end": 1006, "score": 0.9998379945755005, "start": 993, "tag": "NAME", "value": "John McCarthy" } ]
data/train/clojure/be613c8b04e8bba0c4673da41837613128e88702core.cljs
harshp8l/deep-learning-lang-detection
84
(ns extracting-processes.core (:use [promise_stream.pstream :only [mapd* filter* concat* reductions* zip* promise fmap]] [jayq.core :only [$ on text]]) (:require [clojure.string :as string] [promise_stream.pstream :as ps] [promise_stream.sources :as sources] [jayq.core :as jq])) (defn log [clj-value] (js/console.log (clj->js clj-value)) clj-value) (defn log-stream [stream] (mapd* log stream)) ; Pure data (def keycode->key {38 :up 40 :down 74 :j 75 :k 13 :enter}) (def key->action {:up :highlight/previous :down :highlight/next :j :highlight/next :k :highlight/previous :enter :select/current}) (def highlight-actions #{:highlight/previous :highlight/next}) (def select-actions #{:select/current}) (def highlight-action->offset {:highlight/previous dec :highlight/next inc}) (def ex0-ui [" Alan Kay" " J.C.R. Licklider" " John McCarthy" ]) (def ex1-ui [" Smalltalk" " Lisp" " Prolog" " ML" ]) (def first-state {:highlight 0 :selection nil}) ; Utility (defn remember-selection "Stores current highlight as selection when select events occur. Otherwise updates remembered highlight." [{:keys [highlight selection] :as mem} event] (if (= event :select/current) (assoc mem :selection highlight) (assoc mem :highlight event))) ; Pure stream processing (defn identify-key-actions [keydowns] (->> keydowns (mapd* #(aget % "which")) (mapd* keycode->key) (filter* (comp promise identity)) (mapd* key->action))) (defn mouseover->highlight [mouseover] (.index (jq/$ (.-target mouseover)))) (defn set-char [s i c] (str (.substring s 0 i) c (.substring s (inc i)))) (defn render-highlight [ui {highlight :highlight}] (update-in ui [highlight] #(set-char % 0 ">"))) (defn render-selection [[ui {selection :selection}]] (if selection (update-in ui [selection] #(set-char % 1 "*")) ui)) (defn rendering-actions [element rendered-ui] [[:dom/set-text element rendered-ui]]) (defmulti execute first) (defmethod execute :dom/set-text [[_ element content]] (text element content)) (defn execute-dom-transaction [transaction] (mapv execute transaction)) (defn of-type [desired-type] (fn [raw-event] (promise (= desired-type (aget raw-event "type"))))) (defn identify-events [raw-events] (let [keydowns (filter* (of-type "keydown") raw-events) mouseovers (filter* (of-type "mouseover") raw-events) mouseouts (filter* (of-type "mouseout") raw-events) clicks (filter* (of-type "click") raw-events) key-actions (identify-key-actions keydowns) key-selects (filter* (comp promise select-actions) key-actions) mouse-selects (mapd* (constantly :select/current) clicks) selects (concat* key-selects mouse-selects) highlight-moves (filter* (comp promise highlight-actions) key-actions) mouse-highlight-indexes (mapd* mouseover->highlight mouseovers) clears (mapd* (constantly :clear) mouseouts)] (concat* selects highlight-moves mouse-highlight-indexes clears))) (defn manage-state [number-of-rows identified-events] (let [highlight-moves (filter* (comp promise highlight-actions) identified-events) mouse-highlight-indexes (filter* (comp promise number?) identified-events) selects (filter* (comp promise #{:select/current}) identified-events) clears (filter* (comp promise #{:clear}) identified-events) highlight-index-offsets (mapd* highlight-action->offset highlight-moves) highlight-index-resets (mapd* constantly mouse-highlight-indexes) highlight-modifyers (concat* highlight-index-offsets highlight-index-resets) raw-highlight-indexes (reductions* (fmap (fn [v f] (f v))) (promise 0) highlight-modifyers) wrapped-highlight-indexes (mapd* #(mod % number-of-rows) raw-highlight-indexes) highlights-and-selects (concat* wrapped-highlight-indexes selects)] (reductions* (fmap remember-selection) (promise first-state) highlights-and-selects))) (defn plan-changes [element ui ui-states] (let [highlighted-uis (mapd* (partial render-highlight ui) ui-states) selected-uis (mapd* render-selection (zip* highlighted-uis ui-states)) rendered-uis (mapd* (partial string/join "\n") selected-uis)] (mapd* (partial rendering-actions element) rendered-uis))) (defn menu-logic [element ui events] (->> (manage-state (count ui) events) (plan-changes element ui))) (defn connect-to-dom [menu-logic element ui] (let [keydowns (sources/callback->promise-stream on element "keydown") mouseovers (sources/callback->promise-stream on ($ "li" element) "mouseover") mouseouts (sources/callback->promise-stream on ($ element) "mouseout") clicks (sources/callback->promise-stream on ($ "li" element) "click") raw-events (concat* keydowns mouseovers mouseouts clicks)] (->> raw-events identify-events (menu-logic element ui) (mapd* execute-dom-transaction)))) (defn create-menu [element ui] (execute-dom-transaction [[:dom/set-text element (string/join "\n" ui)]]) (connect-to-dom menu-logic element ui)) (create-menu ($ "#ex0") ex0-ui)
16582
(ns extracting-processes.core (:use [promise_stream.pstream :only [mapd* filter* concat* reductions* zip* promise fmap]] [jayq.core :only [$ on text]]) (:require [clojure.string :as string] [promise_stream.pstream :as ps] [promise_stream.sources :as sources] [jayq.core :as jq])) (defn log [clj-value] (js/console.log (clj->js clj-value)) clj-value) (defn log-stream [stream] (mapd* log stream)) ; Pure data (def keycode->key {38 :up 40 :down 74 :j 75 :k 13 :enter}) (def key->action {:up :highlight/previous :down :highlight/next :j :highlight/next :k :highlight/previous :enter :select/current}) (def highlight-actions #{:highlight/previous :highlight/next}) (def select-actions #{:select/current}) (def highlight-action->offset {:highlight/previous dec :highlight/next inc}) (def ex0-ui [" <NAME>" " <NAME>" " <NAME>" ]) (def ex1-ui [" Smalltalk" " Lisp" " Prolog" " ML" ]) (def first-state {:highlight 0 :selection nil}) ; Utility (defn remember-selection "Stores current highlight as selection when select events occur. Otherwise updates remembered highlight." [{:keys [highlight selection] :as mem} event] (if (= event :select/current) (assoc mem :selection highlight) (assoc mem :highlight event))) ; Pure stream processing (defn identify-key-actions [keydowns] (->> keydowns (mapd* #(aget % "which")) (mapd* keycode->key) (filter* (comp promise identity)) (mapd* key->action))) (defn mouseover->highlight [mouseover] (.index (jq/$ (.-target mouseover)))) (defn set-char [s i c] (str (.substring s 0 i) c (.substring s (inc i)))) (defn render-highlight [ui {highlight :highlight}] (update-in ui [highlight] #(set-char % 0 ">"))) (defn render-selection [[ui {selection :selection}]] (if selection (update-in ui [selection] #(set-char % 1 "*")) ui)) (defn rendering-actions [element rendered-ui] [[:dom/set-text element rendered-ui]]) (defmulti execute first) (defmethod execute :dom/set-text [[_ element content]] (text element content)) (defn execute-dom-transaction [transaction] (mapv execute transaction)) (defn of-type [desired-type] (fn [raw-event] (promise (= desired-type (aget raw-event "type"))))) (defn identify-events [raw-events] (let [keydowns (filter* (of-type "keydown") raw-events) mouseovers (filter* (of-type "mouseover") raw-events) mouseouts (filter* (of-type "mouseout") raw-events) clicks (filter* (of-type "click") raw-events) key-actions (identify-key-actions keydowns) key-selects (filter* (comp promise select-actions) key-actions) mouse-selects (mapd* (constantly :select/current) clicks) selects (concat* key-selects mouse-selects) highlight-moves (filter* (comp promise highlight-actions) key-actions) mouse-highlight-indexes (mapd* mouseover->highlight mouseovers) clears (mapd* (constantly :clear) mouseouts)] (concat* selects highlight-moves mouse-highlight-indexes clears))) (defn manage-state [number-of-rows identified-events] (let [highlight-moves (filter* (comp promise highlight-actions) identified-events) mouse-highlight-indexes (filter* (comp promise number?) identified-events) selects (filter* (comp promise #{:select/current}) identified-events) clears (filter* (comp promise #{:clear}) identified-events) highlight-index-offsets (mapd* highlight-action->offset highlight-moves) highlight-index-resets (mapd* constantly mouse-highlight-indexes) highlight-modifyers (concat* highlight-index-offsets highlight-index-resets) raw-highlight-indexes (reductions* (fmap (fn [v f] (f v))) (promise 0) highlight-modifyers) wrapped-highlight-indexes (mapd* #(mod % number-of-rows) raw-highlight-indexes) highlights-and-selects (concat* wrapped-highlight-indexes selects)] (reductions* (fmap remember-selection) (promise first-state) highlights-and-selects))) (defn plan-changes [element ui ui-states] (let [highlighted-uis (mapd* (partial render-highlight ui) ui-states) selected-uis (mapd* render-selection (zip* highlighted-uis ui-states)) rendered-uis (mapd* (partial string/join "\n") selected-uis)] (mapd* (partial rendering-actions element) rendered-uis))) (defn menu-logic [element ui events] (->> (manage-state (count ui) events) (plan-changes element ui))) (defn connect-to-dom [menu-logic element ui] (let [keydowns (sources/callback->promise-stream on element "keydown") mouseovers (sources/callback->promise-stream on ($ "li" element) "mouseover") mouseouts (sources/callback->promise-stream on ($ element) "mouseout") clicks (sources/callback->promise-stream on ($ "li" element) "click") raw-events (concat* keydowns mouseovers mouseouts clicks)] (->> raw-events identify-events (menu-logic element ui) (mapd* execute-dom-transaction)))) (defn create-menu [element ui] (execute-dom-transaction [[:dom/set-text element (string/join "\n" ui)]]) (connect-to-dom menu-logic element ui)) (create-menu ($ "#ex0") ex0-ui)
true
(ns extracting-processes.core (:use [promise_stream.pstream :only [mapd* filter* concat* reductions* zip* promise fmap]] [jayq.core :only [$ on text]]) (:require [clojure.string :as string] [promise_stream.pstream :as ps] [promise_stream.sources :as sources] [jayq.core :as jq])) (defn log [clj-value] (js/console.log (clj->js clj-value)) clj-value) (defn log-stream [stream] (mapd* log stream)) ; Pure data (def keycode->key {38 :up 40 :down 74 :j 75 :k 13 :enter}) (def key->action {:up :highlight/previous :down :highlight/next :j :highlight/next :k :highlight/previous :enter :select/current}) (def highlight-actions #{:highlight/previous :highlight/next}) (def select-actions #{:select/current}) (def highlight-action->offset {:highlight/previous dec :highlight/next inc}) (def ex0-ui [" PI:NAME:<NAME>END_PI" " PI:NAME:<NAME>END_PI" " PI:NAME:<NAME>END_PI" ]) (def ex1-ui [" Smalltalk" " Lisp" " Prolog" " ML" ]) (def first-state {:highlight 0 :selection nil}) ; Utility (defn remember-selection "Stores current highlight as selection when select events occur. Otherwise updates remembered highlight." [{:keys [highlight selection] :as mem} event] (if (= event :select/current) (assoc mem :selection highlight) (assoc mem :highlight event))) ; Pure stream processing (defn identify-key-actions [keydowns] (->> keydowns (mapd* #(aget % "which")) (mapd* keycode->key) (filter* (comp promise identity)) (mapd* key->action))) (defn mouseover->highlight [mouseover] (.index (jq/$ (.-target mouseover)))) (defn set-char [s i c] (str (.substring s 0 i) c (.substring s (inc i)))) (defn render-highlight [ui {highlight :highlight}] (update-in ui [highlight] #(set-char % 0 ">"))) (defn render-selection [[ui {selection :selection}]] (if selection (update-in ui [selection] #(set-char % 1 "*")) ui)) (defn rendering-actions [element rendered-ui] [[:dom/set-text element rendered-ui]]) (defmulti execute first) (defmethod execute :dom/set-text [[_ element content]] (text element content)) (defn execute-dom-transaction [transaction] (mapv execute transaction)) (defn of-type [desired-type] (fn [raw-event] (promise (= desired-type (aget raw-event "type"))))) (defn identify-events [raw-events] (let [keydowns (filter* (of-type "keydown") raw-events) mouseovers (filter* (of-type "mouseover") raw-events) mouseouts (filter* (of-type "mouseout") raw-events) clicks (filter* (of-type "click") raw-events) key-actions (identify-key-actions keydowns) key-selects (filter* (comp promise select-actions) key-actions) mouse-selects (mapd* (constantly :select/current) clicks) selects (concat* key-selects mouse-selects) highlight-moves (filter* (comp promise highlight-actions) key-actions) mouse-highlight-indexes (mapd* mouseover->highlight mouseovers) clears (mapd* (constantly :clear) mouseouts)] (concat* selects highlight-moves mouse-highlight-indexes clears))) (defn manage-state [number-of-rows identified-events] (let [highlight-moves (filter* (comp promise highlight-actions) identified-events) mouse-highlight-indexes (filter* (comp promise number?) identified-events) selects (filter* (comp promise #{:select/current}) identified-events) clears (filter* (comp promise #{:clear}) identified-events) highlight-index-offsets (mapd* highlight-action->offset highlight-moves) highlight-index-resets (mapd* constantly mouse-highlight-indexes) highlight-modifyers (concat* highlight-index-offsets highlight-index-resets) raw-highlight-indexes (reductions* (fmap (fn [v f] (f v))) (promise 0) highlight-modifyers) wrapped-highlight-indexes (mapd* #(mod % number-of-rows) raw-highlight-indexes) highlights-and-selects (concat* wrapped-highlight-indexes selects)] (reductions* (fmap remember-selection) (promise first-state) highlights-and-selects))) (defn plan-changes [element ui ui-states] (let [highlighted-uis (mapd* (partial render-highlight ui) ui-states) selected-uis (mapd* render-selection (zip* highlighted-uis ui-states)) rendered-uis (mapd* (partial string/join "\n") selected-uis)] (mapd* (partial rendering-actions element) rendered-uis))) (defn menu-logic [element ui events] (->> (manage-state (count ui) events) (plan-changes element ui))) (defn connect-to-dom [menu-logic element ui] (let [keydowns (sources/callback->promise-stream on element "keydown") mouseovers (sources/callback->promise-stream on ($ "li" element) "mouseover") mouseouts (sources/callback->promise-stream on ($ element) "mouseout") clicks (sources/callback->promise-stream on ($ "li" element) "click") raw-events (concat* keydowns mouseovers mouseouts clicks)] (->> raw-events identify-events (menu-logic element ui) (mapd* execute-dom-transaction)))) (defn create-menu [element ui] (execute-dom-transaction [[:dom/set-text element (string/join "\n" ui)]]) (connect-to-dom menu-logic element ui)) (create-menu ($ "#ex0") ex0-ui)
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9997965693473816, "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.9998168349266052, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/.jokerd/linter.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 benchmark.graph-benchmark) (def world) (ns clojure.set) (def map-invert) (ns com.sun.javafx.css.StyleManager) (def getInstance) (ns editor.atlas) (def ->texture-vtx) (def pos-uv-frag) (def pos-uv-vert) (ns editor.code.data) (def dest-buffer) (def dest-offset) (def length) (ns editor.collada-scene) (def ->vtx-pos-nrm-tex) (def model-id-fragment-shader) (def model-id-vertex-shader) (def shader-frag-pos-nrm-tex) (def shader-ver-pos-nrm-tex) (ns editor.collision-object) (def ->color-vtx) (def fragment-shader) (def shape-id-fragment-shader) (def shape-id-vertex-shader) (def vertex-shader) (ns editor.cubemap) (def ->normal-vtx) (def pos-norm-frag) (def pos-norm-vert) (ns editor.curve-view) (def ->color-vtx) (def line-fragment-shader) (def line-vertex-shader) (ns editor.font) (def ->DefoldVertex) (def ->DFVertex) (ns editor.gl) (def gl-context) (ns editor.gl.pass) (def render-passes) (def selection-passes) (ns editor.gl.shader) (defmacro defshader [name & body]) (ns editor.gui) (def ->color-vtx) (def ->color-vtx-vb) (def ->uv-color-vtx) (def color-vtx-put!) (def fragment-shader) (def gui-id-fragment-shader) (def gui-id-vertex-shader) (def line-fragment-shader) (def line-vertex-shader) (def uv-color-vtx-put!) (def vertex-shader) (ns editor.label) (def ->color-vtx) (def color-vtx-put!) (def fragment-shader) (def label-id-fragment-shader) (def label-id-vertex-shader) (def line-fragment-shader) (def line-vertex-shader) (def vertex-shader) (ns editor.particlefx) (def ->color-vtx) (def line-fragment-shader) (def line-id-fragment-shader) (def line-id-vertex-shader) (def line-vertex-shader) (ns editor.render) (def ->vtx-pos-col) (def shader-frag-outline) (def shader-frag-tex-tint) (def shader-ver-outline) (def shader-ver-tex-col) (ns editor.rulers) (def ->color-uv-vtx) (def color-uv-vtx-put!) (def tex-fragment-shader) (def tex-vertex-shader) (ns editor.scene-tools) (def ->pos-vtx) (def fragment-shader) (def vertex-shader) (ns editor.sprite) (def ->color-vtx) (def ->texture-vtx) (def fragment-shader) (def outline-fragment-shader) (def outline-vertex-shader) (def sprite-id-fragment-shader) (def sprite-id-vertex-shader) (def vertex-shader) (ns editor.spine) (def spine-id-fragment-shader) (def spine-id-vertex-shader) (ns editor.system) (def defold-engine-sha1) (ns editor.tile-map) (def ->color-vtx) (def ->pos-uv-vtx) (def color-vtx-put!) (def pos-color-frag) (def pos-color-vert) (def pos-uv-frag) (def pos-uv-vert) (def pos-uv-vtx-put!) (def tile-map-id-fragment-shader) (def tile-map-id-vertex-shader) (ns editor.tile-source) (def ->pos-color-vtx) (def ->pos-uv-vtx) (def pos-color-frag) (def pos-color-vert) (def pos-uv-frag) (def pos-uv-vert) (ns editor.ui) (def now) (ns javafx.application.Platform) (def exit) (ns javafx.scene.Cursor) (def DEFAULT) (def DISAPPEAR) (def HAND) (def TEXT) (ns Thread$State) (def TERMINATED) (ns joker.core) (def clojure.core.protocols.CollReduce) (def clojure.core.protocols.IKVReduce) (def editor.gl.vertex2.VertexBuffer) (def internal.node.NodeImpl) (def internal.node.NodeTypeRef) (def internal.node.ValueTypeRef) (def javafx.scene.control.Tab) (def javafx.scene.input.KeyCharacterCombination) (def javafx.scene.input.KeyCodeCombination) (def javafx.stage.Stage) (def javafx.stage.Window) (def org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) (def schema.core.Predicate) (def schema.utils.ValidationError) (defmacro defproject [& _]) (defmacro deftest [& shut-up]) (defmacro is [& quiet-please]) (defmacro testing [& yawn]) (defmacro use-fixtures [& _]) (ns util.profiler-test) (def threads)
80981
;; 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 benchmark.graph-benchmark) (def world) (ns clojure.set) (def map-invert) (ns com.sun.javafx.css.StyleManager) (def getInstance) (ns editor.atlas) (def ->texture-vtx) (def pos-uv-frag) (def pos-uv-vert) (ns editor.code.data) (def dest-buffer) (def dest-offset) (def length) (ns editor.collada-scene) (def ->vtx-pos-nrm-tex) (def model-id-fragment-shader) (def model-id-vertex-shader) (def shader-frag-pos-nrm-tex) (def shader-ver-pos-nrm-tex) (ns editor.collision-object) (def ->color-vtx) (def fragment-shader) (def shape-id-fragment-shader) (def shape-id-vertex-shader) (def vertex-shader) (ns editor.cubemap) (def ->normal-vtx) (def pos-norm-frag) (def pos-norm-vert) (ns editor.curve-view) (def ->color-vtx) (def line-fragment-shader) (def line-vertex-shader) (ns editor.font) (def ->DefoldVertex) (def ->DFVertex) (ns editor.gl) (def gl-context) (ns editor.gl.pass) (def render-passes) (def selection-passes) (ns editor.gl.shader) (defmacro defshader [name & body]) (ns editor.gui) (def ->color-vtx) (def ->color-vtx-vb) (def ->uv-color-vtx) (def color-vtx-put!) (def fragment-shader) (def gui-id-fragment-shader) (def gui-id-vertex-shader) (def line-fragment-shader) (def line-vertex-shader) (def uv-color-vtx-put!) (def vertex-shader) (ns editor.label) (def ->color-vtx) (def color-vtx-put!) (def fragment-shader) (def label-id-fragment-shader) (def label-id-vertex-shader) (def line-fragment-shader) (def line-vertex-shader) (def vertex-shader) (ns editor.particlefx) (def ->color-vtx) (def line-fragment-shader) (def line-id-fragment-shader) (def line-id-vertex-shader) (def line-vertex-shader) (ns editor.render) (def ->vtx-pos-col) (def shader-frag-outline) (def shader-frag-tex-tint) (def shader-ver-outline) (def shader-ver-tex-col) (ns editor.rulers) (def ->color-uv-vtx) (def color-uv-vtx-put!) (def tex-fragment-shader) (def tex-vertex-shader) (ns editor.scene-tools) (def ->pos-vtx) (def fragment-shader) (def vertex-shader) (ns editor.sprite) (def ->color-vtx) (def ->texture-vtx) (def fragment-shader) (def outline-fragment-shader) (def outline-vertex-shader) (def sprite-id-fragment-shader) (def sprite-id-vertex-shader) (def vertex-shader) (ns editor.spine) (def spine-id-fragment-shader) (def spine-id-vertex-shader) (ns editor.system) (def defold-engine-sha1) (ns editor.tile-map) (def ->color-vtx) (def ->pos-uv-vtx) (def color-vtx-put!) (def pos-color-frag) (def pos-color-vert) (def pos-uv-frag) (def pos-uv-vert) (def pos-uv-vtx-put!) (def tile-map-id-fragment-shader) (def tile-map-id-vertex-shader) (ns editor.tile-source) (def ->pos-color-vtx) (def ->pos-uv-vtx) (def pos-color-frag) (def pos-color-vert) (def pos-uv-frag) (def pos-uv-vert) (ns editor.ui) (def now) (ns javafx.application.Platform) (def exit) (ns javafx.scene.Cursor) (def DEFAULT) (def DISAPPEAR) (def HAND) (def TEXT) (ns Thread$State) (def TERMINATED) (ns joker.core) (def clojure.core.protocols.CollReduce) (def clojure.core.protocols.IKVReduce) (def editor.gl.vertex2.VertexBuffer) (def internal.node.NodeImpl) (def internal.node.NodeTypeRef) (def internal.node.ValueTypeRef) (def javafx.scene.control.Tab) (def javafx.scene.input.KeyCharacterCombination) (def javafx.scene.input.KeyCodeCombination) (def javafx.stage.Stage) (def javafx.stage.Window) (def org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) (def schema.core.Predicate) (def schema.utils.ValidationError) (defmacro defproject [& _]) (defmacro deftest [& shut-up]) (defmacro is [& quiet-please]) (defmacro testing [& yawn]) (defmacro use-fixtures [& _]) (ns util.profiler-test) (def threads)
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 benchmark.graph-benchmark) (def world) (ns clojure.set) (def map-invert) (ns com.sun.javafx.css.StyleManager) (def getInstance) (ns editor.atlas) (def ->texture-vtx) (def pos-uv-frag) (def pos-uv-vert) (ns editor.code.data) (def dest-buffer) (def dest-offset) (def length) (ns editor.collada-scene) (def ->vtx-pos-nrm-tex) (def model-id-fragment-shader) (def model-id-vertex-shader) (def shader-frag-pos-nrm-tex) (def shader-ver-pos-nrm-tex) (ns editor.collision-object) (def ->color-vtx) (def fragment-shader) (def shape-id-fragment-shader) (def shape-id-vertex-shader) (def vertex-shader) (ns editor.cubemap) (def ->normal-vtx) (def pos-norm-frag) (def pos-norm-vert) (ns editor.curve-view) (def ->color-vtx) (def line-fragment-shader) (def line-vertex-shader) (ns editor.font) (def ->DefoldVertex) (def ->DFVertex) (ns editor.gl) (def gl-context) (ns editor.gl.pass) (def render-passes) (def selection-passes) (ns editor.gl.shader) (defmacro defshader [name & body]) (ns editor.gui) (def ->color-vtx) (def ->color-vtx-vb) (def ->uv-color-vtx) (def color-vtx-put!) (def fragment-shader) (def gui-id-fragment-shader) (def gui-id-vertex-shader) (def line-fragment-shader) (def line-vertex-shader) (def uv-color-vtx-put!) (def vertex-shader) (ns editor.label) (def ->color-vtx) (def color-vtx-put!) (def fragment-shader) (def label-id-fragment-shader) (def label-id-vertex-shader) (def line-fragment-shader) (def line-vertex-shader) (def vertex-shader) (ns editor.particlefx) (def ->color-vtx) (def line-fragment-shader) (def line-id-fragment-shader) (def line-id-vertex-shader) (def line-vertex-shader) (ns editor.render) (def ->vtx-pos-col) (def shader-frag-outline) (def shader-frag-tex-tint) (def shader-ver-outline) (def shader-ver-tex-col) (ns editor.rulers) (def ->color-uv-vtx) (def color-uv-vtx-put!) (def tex-fragment-shader) (def tex-vertex-shader) (ns editor.scene-tools) (def ->pos-vtx) (def fragment-shader) (def vertex-shader) (ns editor.sprite) (def ->color-vtx) (def ->texture-vtx) (def fragment-shader) (def outline-fragment-shader) (def outline-vertex-shader) (def sprite-id-fragment-shader) (def sprite-id-vertex-shader) (def vertex-shader) (ns editor.spine) (def spine-id-fragment-shader) (def spine-id-vertex-shader) (ns editor.system) (def defold-engine-sha1) (ns editor.tile-map) (def ->color-vtx) (def ->pos-uv-vtx) (def color-vtx-put!) (def pos-color-frag) (def pos-color-vert) (def pos-uv-frag) (def pos-uv-vert) (def pos-uv-vtx-put!) (def tile-map-id-fragment-shader) (def tile-map-id-vertex-shader) (ns editor.tile-source) (def ->pos-color-vtx) (def ->pos-uv-vtx) (def pos-color-frag) (def pos-color-vert) (def pos-uv-frag) (def pos-uv-vert) (ns editor.ui) (def now) (ns javafx.application.Platform) (def exit) (ns javafx.scene.Cursor) (def DEFAULT) (def DISAPPEAR) (def HAND) (def TEXT) (ns Thread$State) (def TERMINATED) (ns joker.core) (def clojure.core.protocols.CollReduce) (def clojure.core.protocols.IKVReduce) (def editor.gl.vertex2.VertexBuffer) (def internal.node.NodeImpl) (def internal.node.NodeTypeRef) (def internal.node.ValueTypeRef) (def javafx.scene.control.Tab) (def javafx.scene.input.KeyCharacterCombination) (def javafx.scene.input.KeyCodeCombination) (def javafx.stage.Stage) (def javafx.stage.Window) (def org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) (def schema.core.Predicate) (def schema.utils.ValidationError) (defmacro defproject [& _]) (defmacro deftest [& shut-up]) (defmacro is [& quiet-please]) (defmacro testing [& yawn]) (defmacro use-fixtures [& _]) (ns util.profiler-test) (def threads)
[ { "context": " \"0.1.2\"]])\n\n\n;; Example from: https://github.com/boutros/matsu/blob/master/doc/example.clj\n;; Original cop", "end": 162, "score": 0.9973132014274597, "start": 155, "tag": "USERNAME", "value": "boutros" }, { "context": "pyright and license statement:\n;; Copyright © 2012 Petter Goksøyr Åsen\n;;\n;; Distributed under the Eclipse Public Licens", "end": 281, "score": 0.9998871088027954, "start": 262, "tag": "NAME", "value": "Petter Goksøyr Åsen" }, { "context": "--------------------------------\\n\")\n\n\n;; When was Jimi Hendrix born?\n(defquery hendrix []\n (select-distinct :bd", "end": 2228, "score": 0.9997830390930176, "start": 2216, "tag": "NAME", "value": "Jimi Hendrix" }, { "context": "[]\n (select-distinct :bday)\n (where [:dbpedia :Jimi_Hendrix] [:prop :dateOfBirth] :bday))\n\n(def req\n ", "end": 2306, "score": 0.9228905439376831, "start": 2303, "tag": "NAME", "value": "imi" }, { "context": "(select-distinct :bday)\n (where [:dbpedia :Jimi_Hendrix] [:prop :dateOfBirth] :bday))\n\n(def req\n (cli", "end": 2311, "score": 0.5842861533164978, "start": 2308, "tag": "NAME", "value": "end" }, { "context": "wn down node))\n;=> \"1942-11-27\"\n(println \"When was Jimi Hendrix born?\")\n(println (util/pprint (hendrix)))\n(printl", "end": 2599, "score": 0.9996698498725891, "start": 2587, "tag": "NAME", "value": "Jimi Hendrix" }, { "context": "; Find actors who acted in both movies directed by Kubrick and by Spielberg\n(defquery actors []\n (base (URI", "end": 4980, "score": 0.9963839650154114, "start": 4973, "tag": "NAME", "value": "Kubrick" }, { "context": "ho acted in both movies directed by Kubrick and by Spielberg\n(defquery actors []\n (base (URI. \"http://data.li", "end": 4997, "score": 0.9961993098258972, "start": 4988, "tag": "NAME", "value": "Spielberg" }, { "context": "inct :actorname)\n (where :dir1 [:director_name] \"Steven Spielberg\" \\.\n :dir2 [:director_name] \"Stanley Kubr", "end": 5158, "score": 0.9998846054077148, "start": 5142, "tag": "NAME", "value": "Steven Spielberg" }, { "context": "en Spielberg\" \\.\n :dir2 [:director_name] \"Stanley Kubrick\" \\.\n :dir1film [:director] :dir1 \\;\n ", "end": 5211, "score": 0.9998818635940552, "start": 5196, "tag": "NAME", "value": "Stanley Kubrick" }, { "context": " \"Find actors who acted in both movies directed by Kubrick and by Spielberg\")\n(println (util/pprint (actors)", "end": 5781, "score": 0.997731626033783, "start": 5774, "tag": "NAME", "value": "Kubrick" }, { "context": "ho acted in both movies directed by Kubrick and by Spielberg\")\n(println (util/pprint (actors)))\n(println (str ", "end": 5798, "score": 0.9991133213043213, "start": 5789, "tag": "NAME", "value": "Spielberg" }, { "context": "---------------------------------------\")\n\n; => (\"Wolf Kahler\" \"Slim Pickens\" \"Tom Cruise\" \"Arliss Howard\"\n; ", "end": 5961, "score": 0.999882698059082, "start": 5950, "tag": "NAME", "value": "Wolf Kahler" }, { "context": "-------------------------\")\n\n; => (\"Wolf Kahler\" \"Slim Pickens\" \"Tom Cruise\" \"Arliss Howard\"\n; \"Slim Picken", "end": 5976, "score": 0.9998883605003357, "start": 5964, "tag": "NAME", "value": "Slim Pickens" }, { "context": "----------\")\n\n; => (\"Wolf Kahler\" \"Slim Pickens\" \"Tom Cruise\" \"Arliss Howard\"\n; \"Slim Pickens\" \"Ben Johns", "end": 5989, "score": 0.9998847842216492, "start": 5979, "tag": "NAME", "value": "Tom Cruise" }, { "context": "\n; => (\"Wolf Kahler\" \"Slim Pickens\" \"Tom Cruise\" \"Arliss Howard\"\n; \"Slim Pickens\" \"Ben Johnson\" \"Scatman Cro", "end": 6005, "score": 0.9998842477798462, "start": 5992, "tag": "NAME", "value": "Arliss Howard" }, { "context": "lim Pickens\" \"Tom Cruise\" \"Arliss Howard\"\n; \"Slim Pickens\" \"Ben Johnson\" \"Scatman Crothers\" \"Philip Stone\")", "end": 6027, "score": 0.9998786449432373, "start": 6015, "tag": "NAME", "value": "Slim Pickens" }, { "context": "om Cruise\" \"Arliss Howard\"\n; \"Slim Pickens\" \"Ben Johnson\" \"Scatman Crothers\" \"Philip Stone\")\n", "end": 6041, "score": 0.9998835921287537, "start": 6030, "tag": "NAME", "value": "Ben Johnson" }, { "context": "liss Howard\"\n; \"Slim Pickens\" \"Ben Johnson\" \"Scatman Crothers\" \"Philip Stone\")\n", "end": 6060, "score": 0.9998930096626282, "start": 6044, "tag": "NAME", "value": "Scatman Crothers" }, { "context": " \"Slim Pickens\" \"Ben Johnson\" \"Scatman Crothers\" \"Philip Stone\")\n", "end": 6075, "score": 0.9998830556869507, "start": 6063, "tag": "NAME", "value": "Philip Stone" } ]
overview/Script26.clj
clarkparsia/semtech2014
1
#_(defdeps [[org.clojure/clojure "1.6.0"] [clj-http "0.6.3"] [cheshire "5.0.1"] [matsu "0.1.2"]]) ;; Example from: https://github.com/boutros/matsu/blob/master/doc/example.clj ;; Original copyright and license statement: ;; Copyright © 2012 Petter Goksøyr Åsen ;; ;; Distributed under the Eclipse Public License, the same as Clojure. ;; Example REPL session querying remote SPARQL endpoints (DBpedia & LinkedMDB) ;; ============================================================================ ;; Uses the following dependencies in addition to matsu: ;; ;; [clj-http "0.6.3"] ;; [cheshire "5.0.1"] (ns boutros.matsu.example (:refer-clojure :exclude [filter concat group-by max min count]) (:require [clj-http.client :as client] [boutros.matsu.sparql :refer :all] [boutros.matsu.core :refer [register-namespaces]] [boutros.matsu.util :as util] [clojure.xml :as xml] [clojure.zip :as zip :refer [down right left node children]] [cheshire.core :refer [parse-string]] [clojure.walk :refer [keywordize-keys]]) (:import java.net.URI)) ;; Convenience function to parse xml strings (defn zip-str [s] (zip/xml-zip (xml/parse (java.io.ByteArrayInputStream. (.getBytes s))))) ;; DBpedia sparql endpoint (def dbpedia "http://dbpedia.org/sparql") ;; some common prefixes (register-namespaces {:prop "<http://dbpedia.org/property/>" :dbpedia "<http://dbpedia.org/resource/>" :foaf "<http://xmlns.com/foaf/0.1/>" :rdfs "<http://www.w3.org/2000/01/rdf-schema#>"}) ;; Is the Amazon river longer than the Nile River? (defquery amazon-vs-nile [] (ask [:dbpedia :Amazon_River] [:prop :length] :amazon \. [:dbpedia :Nile] [:prop :length] :nile \. (filter :amazon > :nile))) ;; send HTTP request (def req (client/get dbpedia {:query-params {"query" (amazon-vs-nile)}})) (:body req) ; => "false" (println "Is the Amazon river longer than the Nile River?") (println (util/pprint (amazon-vs-nile))) (println (str "\n=> "(:body req))) (println "-----------------------------------------------\n") ;; When was Jimi Hendrix born? (defquery hendrix [] (select-distinct :bday) (where [:dbpedia :Jimi_Hendrix] [:prop :dateOfBirth] :bday)) (def req (client/get dbpedia {:query-params {"query" (hendrix)}})) ;; Dbpedia response format defaults to xml (def birthday (-> (zip-str (:body req)) down right down down down down node)) ;=> "1942-11-27" (println "When was Jimi Hendrix born?") (println (util/pprint (hendrix))) (println (str "\n=>" birthday "\n\n")) (println "-----------------------------------------------") ;; Don't like to parse XML? You can also ask for JSON if you prefer ;; Let's find Elvis' birthday this time (defquery elvis [] (select :bday) (where [:dbpedia :Elvis_Presley] [:prop :dateOfBirth] :bday)) (def req (client/get dbpedia {:query-params { "query" (elvis) "format" "application/sparql-results+json"}})) (def answer (parse-string (:body req))) (def answer-clean (->> answer keywordize-keys :results :bindings first :bday :value)) ; => "1935-01-08" (println "Let's find Elvis' birthday this time") (println (util/pprint (elvis))) (println (str "\n=>" answer-clean)) (println "-----------------------------------------------") ;; Let's try something a litle more involving: ;; Find movies starring actors born in Tokyo, ;; limit to 10, ordered by longest running time: (defquery movies [] (select-distinct :title) (where :p [:prop :birthPlace] [:dbpedia :Tokyo] \. :movie [:prop :starring] :p \; [:rdfs :label] :title \; [:prop :runtime] :runtime (filter (lang-matches (lang :title) "en"))) (order-by-desc :runtime) (limit 10)) (def req (client/get dbpedia {:query-params { "query" (movies) "format" "application/sparql-results+json"}})) (def answer (parse-string (:body req))) ;; Iterate over the bindings and get titles (def movie-list (for [movie (->> answer keywordize-keys :results :bindings)] (->> movie :title :value))) (println "Find movies starring actors born in Tokyo, limit to 10, ordered by longest running time:") (println (util/pprint (movies))) (println (str "\n=>" (pr-str movie-list))) (println "-----------------------------------------------") ; => ("Kamen Rider Decade: All Riders vs. Dai-Shocker" "Pokémon: Mewtwo Returns" ; "The Last Emperor" "Ran (film)""Keroro Gunso the Super Movie 3: Keroro vs. ; Keroro Great Sky Duel" "The Fall of Ako Castle" "Eijanaika (film)" ; "The Users (TV movie)" "Runin: Banished" "Swallowtail Butterfly (film)") ;; Speaking of movies, let's try the linked data version of IMDB: ;; LinkedMoveDatabase SPARQL endpoint (def linkedmdb "http://linkedmdb.org/sparql") ;; Find actors who acted in both movies directed by Kubrick and by Spielberg (defquery actors [] (base (URI. "http://data.linkedmdb.org/resource/movie/")) (select-distinct :actorname) (where :dir1 [:director_name] "Steven Spielberg" \. :dir2 [:director_name] "Stanley Kubrick" \. :dir1film [:director] :dir1 \; [:actor] :actor \. :dir2film [:director] :dir2 \; [:actor] :actor \. :actor [:actor_name] :actorname \.)) (def req (client/get linkedmdb {:accept "application/sparql-results+json" :query-params { "query" (actors)}})) (def answer (parse-string (:body req))) (def actor-list (for [actor (->> answer keywordize-keys :results :bindings)] (->> actor :actorname :value))) (println "Find actors who acted in both movies directed by Kubrick and by Spielberg") (println (util/pprint (actors))) (println (str "\n=>" (pr-str actor-list) "\n")) (println "-----------------------------------------------") ; => ("Wolf Kahler" "Slim Pickens" "Tom Cruise" "Arliss Howard" ; "Slim Pickens" "Ben Johnson" "Scatman Crothers" "Philip Stone")
16111
#_(defdeps [[org.clojure/clojure "1.6.0"] [clj-http "0.6.3"] [cheshire "5.0.1"] [matsu "0.1.2"]]) ;; Example from: https://github.com/boutros/matsu/blob/master/doc/example.clj ;; Original copyright and license statement: ;; Copyright © 2012 <NAME> ;; ;; Distributed under the Eclipse Public License, the same as Clojure. ;; Example REPL session querying remote SPARQL endpoints (DBpedia & LinkedMDB) ;; ============================================================================ ;; Uses the following dependencies in addition to matsu: ;; ;; [clj-http "0.6.3"] ;; [cheshire "5.0.1"] (ns boutros.matsu.example (:refer-clojure :exclude [filter concat group-by max min count]) (:require [clj-http.client :as client] [boutros.matsu.sparql :refer :all] [boutros.matsu.core :refer [register-namespaces]] [boutros.matsu.util :as util] [clojure.xml :as xml] [clojure.zip :as zip :refer [down right left node children]] [cheshire.core :refer [parse-string]] [clojure.walk :refer [keywordize-keys]]) (:import java.net.URI)) ;; Convenience function to parse xml strings (defn zip-str [s] (zip/xml-zip (xml/parse (java.io.ByteArrayInputStream. (.getBytes s))))) ;; DBpedia sparql endpoint (def dbpedia "http://dbpedia.org/sparql") ;; some common prefixes (register-namespaces {:prop "<http://dbpedia.org/property/>" :dbpedia "<http://dbpedia.org/resource/>" :foaf "<http://xmlns.com/foaf/0.1/>" :rdfs "<http://www.w3.org/2000/01/rdf-schema#>"}) ;; Is the Amazon river longer than the Nile River? (defquery amazon-vs-nile [] (ask [:dbpedia :Amazon_River] [:prop :length] :amazon \. [:dbpedia :Nile] [:prop :length] :nile \. (filter :amazon > :nile))) ;; send HTTP request (def req (client/get dbpedia {:query-params {"query" (amazon-vs-nile)}})) (:body req) ; => "false" (println "Is the Amazon river longer than the Nile River?") (println (util/pprint (amazon-vs-nile))) (println (str "\n=> "(:body req))) (println "-----------------------------------------------\n") ;; When was <NAME> born? (defquery hendrix [] (select-distinct :bday) (where [:dbpedia :J<NAME>_H<NAME>rix] [:prop :dateOfBirth] :bday)) (def req (client/get dbpedia {:query-params {"query" (hendrix)}})) ;; Dbpedia response format defaults to xml (def birthday (-> (zip-str (:body req)) down right down down down down node)) ;=> "1942-11-27" (println "When was <NAME> born?") (println (util/pprint (hendrix))) (println (str "\n=>" birthday "\n\n")) (println "-----------------------------------------------") ;; Don't like to parse XML? You can also ask for JSON if you prefer ;; Let's find Elvis' birthday this time (defquery elvis [] (select :bday) (where [:dbpedia :Elvis_Presley] [:prop :dateOfBirth] :bday)) (def req (client/get dbpedia {:query-params { "query" (elvis) "format" "application/sparql-results+json"}})) (def answer (parse-string (:body req))) (def answer-clean (->> answer keywordize-keys :results :bindings first :bday :value)) ; => "1935-01-08" (println "Let's find Elvis' birthday this time") (println (util/pprint (elvis))) (println (str "\n=>" answer-clean)) (println "-----------------------------------------------") ;; Let's try something a litle more involving: ;; Find movies starring actors born in Tokyo, ;; limit to 10, ordered by longest running time: (defquery movies [] (select-distinct :title) (where :p [:prop :birthPlace] [:dbpedia :Tokyo] \. :movie [:prop :starring] :p \; [:rdfs :label] :title \; [:prop :runtime] :runtime (filter (lang-matches (lang :title) "en"))) (order-by-desc :runtime) (limit 10)) (def req (client/get dbpedia {:query-params { "query" (movies) "format" "application/sparql-results+json"}})) (def answer (parse-string (:body req))) ;; Iterate over the bindings and get titles (def movie-list (for [movie (->> answer keywordize-keys :results :bindings)] (->> movie :title :value))) (println "Find movies starring actors born in Tokyo, limit to 10, ordered by longest running time:") (println (util/pprint (movies))) (println (str "\n=>" (pr-str movie-list))) (println "-----------------------------------------------") ; => ("Kamen Rider Decade: All Riders vs. Dai-Shocker" "Pokémon: Mewtwo Returns" ; "The Last Emperor" "Ran (film)""Keroro Gunso the Super Movie 3: Keroro vs. ; Keroro Great Sky Duel" "The Fall of Ako Castle" "Eijanaika (film)" ; "The Users (TV movie)" "Runin: Banished" "Swallowtail Butterfly (film)") ;; Speaking of movies, let's try the linked data version of IMDB: ;; LinkedMoveDatabase SPARQL endpoint (def linkedmdb "http://linkedmdb.org/sparql") ;; Find actors who acted in both movies directed by <NAME> and by <NAME> (defquery actors [] (base (URI. "http://data.linkedmdb.org/resource/movie/")) (select-distinct :actorname) (where :dir1 [:director_name] "<NAME>" \. :dir2 [:director_name] "<NAME>" \. :dir1film [:director] :dir1 \; [:actor] :actor \. :dir2film [:director] :dir2 \; [:actor] :actor \. :actor [:actor_name] :actorname \.)) (def req (client/get linkedmdb {:accept "application/sparql-results+json" :query-params { "query" (actors)}})) (def answer (parse-string (:body req))) (def actor-list (for [actor (->> answer keywordize-keys :results :bindings)] (->> actor :actorname :value))) (println "Find actors who acted in both movies directed by <NAME> and by <NAME>") (println (util/pprint (actors))) (println (str "\n=>" (pr-str actor-list) "\n")) (println "-----------------------------------------------") ; => ("<NAME>" "<NAME>" "<NAME>" "<NAME>" ; "<NAME>" "<NAME>" "<NAME>" "<NAME>")
true
#_(defdeps [[org.clojure/clojure "1.6.0"] [clj-http "0.6.3"] [cheshire "5.0.1"] [matsu "0.1.2"]]) ;; Example from: https://github.com/boutros/matsu/blob/master/doc/example.clj ;; Original copyright and license statement: ;; Copyright © 2012 PI:NAME:<NAME>END_PI ;; ;; Distributed under the Eclipse Public License, the same as Clojure. ;; Example REPL session querying remote SPARQL endpoints (DBpedia & LinkedMDB) ;; ============================================================================ ;; Uses the following dependencies in addition to matsu: ;; ;; [clj-http "0.6.3"] ;; [cheshire "5.0.1"] (ns boutros.matsu.example (:refer-clojure :exclude [filter concat group-by max min count]) (:require [clj-http.client :as client] [boutros.matsu.sparql :refer :all] [boutros.matsu.core :refer [register-namespaces]] [boutros.matsu.util :as util] [clojure.xml :as xml] [clojure.zip :as zip :refer [down right left node children]] [cheshire.core :refer [parse-string]] [clojure.walk :refer [keywordize-keys]]) (:import java.net.URI)) ;; Convenience function to parse xml strings (defn zip-str [s] (zip/xml-zip (xml/parse (java.io.ByteArrayInputStream. (.getBytes s))))) ;; DBpedia sparql endpoint (def dbpedia "http://dbpedia.org/sparql") ;; some common prefixes (register-namespaces {:prop "<http://dbpedia.org/property/>" :dbpedia "<http://dbpedia.org/resource/>" :foaf "<http://xmlns.com/foaf/0.1/>" :rdfs "<http://www.w3.org/2000/01/rdf-schema#>"}) ;; Is the Amazon river longer than the Nile River? (defquery amazon-vs-nile [] (ask [:dbpedia :Amazon_River] [:prop :length] :amazon \. [:dbpedia :Nile] [:prop :length] :nile \. (filter :amazon > :nile))) ;; send HTTP request (def req (client/get dbpedia {:query-params {"query" (amazon-vs-nile)}})) (:body req) ; => "false" (println "Is the Amazon river longer than the Nile River?") (println (util/pprint (amazon-vs-nile))) (println (str "\n=> "(:body req))) (println "-----------------------------------------------\n") ;; When was PI:NAME:<NAME>END_PI born? (defquery hendrix [] (select-distinct :bday) (where [:dbpedia :JPI:NAME:<NAME>END_PI_HPI:NAME:<NAME>END_PIrix] [:prop :dateOfBirth] :bday)) (def req (client/get dbpedia {:query-params {"query" (hendrix)}})) ;; Dbpedia response format defaults to xml (def birthday (-> (zip-str (:body req)) down right down down down down node)) ;=> "1942-11-27" (println "When was PI:NAME:<NAME>END_PI born?") (println (util/pprint (hendrix))) (println (str "\n=>" birthday "\n\n")) (println "-----------------------------------------------") ;; Don't like to parse XML? You can also ask for JSON if you prefer ;; Let's find Elvis' birthday this time (defquery elvis [] (select :bday) (where [:dbpedia :Elvis_Presley] [:prop :dateOfBirth] :bday)) (def req (client/get dbpedia {:query-params { "query" (elvis) "format" "application/sparql-results+json"}})) (def answer (parse-string (:body req))) (def answer-clean (->> answer keywordize-keys :results :bindings first :bday :value)) ; => "1935-01-08" (println "Let's find Elvis' birthday this time") (println (util/pprint (elvis))) (println (str "\n=>" answer-clean)) (println "-----------------------------------------------") ;; Let's try something a litle more involving: ;; Find movies starring actors born in Tokyo, ;; limit to 10, ordered by longest running time: (defquery movies [] (select-distinct :title) (where :p [:prop :birthPlace] [:dbpedia :Tokyo] \. :movie [:prop :starring] :p \; [:rdfs :label] :title \; [:prop :runtime] :runtime (filter (lang-matches (lang :title) "en"))) (order-by-desc :runtime) (limit 10)) (def req (client/get dbpedia {:query-params { "query" (movies) "format" "application/sparql-results+json"}})) (def answer (parse-string (:body req))) ;; Iterate over the bindings and get titles (def movie-list (for [movie (->> answer keywordize-keys :results :bindings)] (->> movie :title :value))) (println "Find movies starring actors born in Tokyo, limit to 10, ordered by longest running time:") (println (util/pprint (movies))) (println (str "\n=>" (pr-str movie-list))) (println "-----------------------------------------------") ; => ("Kamen Rider Decade: All Riders vs. Dai-Shocker" "Pokémon: Mewtwo Returns" ; "The Last Emperor" "Ran (film)""Keroro Gunso the Super Movie 3: Keroro vs. ; Keroro Great Sky Duel" "The Fall of Ako Castle" "Eijanaika (film)" ; "The Users (TV movie)" "Runin: Banished" "Swallowtail Butterfly (film)") ;; Speaking of movies, let's try the linked data version of IMDB: ;; LinkedMoveDatabase SPARQL endpoint (def linkedmdb "http://linkedmdb.org/sparql") ;; Find actors who acted in both movies directed by PI:NAME:<NAME>END_PI and by PI:NAME:<NAME>END_PI (defquery actors [] (base (URI. "http://data.linkedmdb.org/resource/movie/")) (select-distinct :actorname) (where :dir1 [:director_name] "PI:NAME:<NAME>END_PI" \. :dir2 [:director_name] "PI:NAME:<NAME>END_PI" \. :dir1film [:director] :dir1 \; [:actor] :actor \. :dir2film [:director] :dir2 \; [:actor] :actor \. :actor [:actor_name] :actorname \.)) (def req (client/get linkedmdb {:accept "application/sparql-results+json" :query-params { "query" (actors)}})) (def answer (parse-string (:body req))) (def actor-list (for [actor (->> answer keywordize-keys :results :bindings)] (->> actor :actorname :value))) (println "Find actors who acted in both movies directed by PI:NAME:<NAME>END_PI and by PI:NAME:<NAME>END_PI") (println (util/pprint (actors))) (println (str "\n=>" (pr-str actor-list) "\n")) (println "-----------------------------------------------") ; => ("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" ; "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>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.9998135566711426, "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.9998199343681335, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/src/clj/editor/analytics.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.analytics (:require [clojure.data.json :as json] [clojure.java.io :as io] [clojure.string :as string] [editor.connection-properties :refer [connection-properties]] [editor.system :as sys] [editor.url :as url] [service.log :as log]) (:import (clojure.lang PersistentQueue) (com.defold.editor Editor) (java.io File) (java.net HttpURLConnection MalformedURLException URL) (java.nio.charset StandardCharsets) (java.util UUID) (java.util.concurrent CancellationException))) (set! *warn-on-reflection* true) ;; Set this to true to see the events that get sent when testing. (defonce ^:private log-events? false) (defonce ^:private batch-size 16) (defonce ^:private cid-regex #"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") (defonce ^:private config-atom (atom nil)) (defonce ^:private event-queue-atom (atom PersistentQueue/EMPTY)) (defonce ^:private max-failed-send-attempts 5) (defonce ^:private payload-content-type "application/x-www-form-urlencoded; charset=UTF-8") (defonce ^:private shutdown-timeout 1000) (defonce ^:private uid-regex #"[0-9A-F]{16}") (defonce ^:private worker-atom (atom nil)) ;; ----------------------------------------------------------------------------- ;; Validation ;; ----------------------------------------------------------------------------- (defn- valid-analytics-url? [value] (and (string? value) (try (let [url (URL. value)] (and (nil? (.getQuery url)) (nil? (.getRef url)) (let [protocol (.getProtocol url)] (or (= "http" protocol) (= "https" protocol))))) (catch MalformedURLException _ false)))) (defn- valid-cid? [value] (and (string? value) (.matches (re-matcher cid-regex value)))) (defn- valid-uid? [value] (and (string? value) (.matches (re-matcher uid-regex value)))) (defn- valid-config? [config] (and (map? config) (= #{:cid :uid} (set (keys config))) (let [{:keys [cid uid]} config] (and (valid-cid? cid) (or (nil? uid) (valid-uid? uid)))))) (def ^:private valid-event? (every-pred map? (comp nil? :cd1) ; Custom Dimension 1 is reserved for the uid. (comp (every-pred string? not-empty) :t) (partial every? (every-pred (comp keyword? key) (comp string? val) (comp not-empty val))))) ;; ----------------------------------------------------------------------------- ;; Configuration ;; ----------------------------------------------------------------------------- (defn- make-config [] {:post [(valid-config? %)]} {:cid (str (UUID/randomUUID)) :uid nil}) (defn- config-file ^File [] (.toFile (.resolve (Editor/getSupportPath) ".defold-analytics"))) (defn- write-config-to-file! [{:keys [cid uid]} ^File config-file] {:pre [(valid-cid? cid) (or (nil? uid) (valid-uid? uid))]} (let [json (if (some? uid) {"cid" cid "uid" uid} {"cid" cid})] (with-open [writer (io/writer config-file)] (json/write json writer)))) (defn- write-config! [config] (let [config-file (config-file)] (try (write-config-to-file! config config-file) (catch Throwable error (log/warn :msg (str "Failed to write analytics config: " config-file) :exception error))))) (defn- read-config-from-file! [^File config-file] (with-open [reader (io/reader config-file)] (let [{cid "cid" uid "uid"} (json/read reader)] {:cid cid :uid uid}))) (defn- read-config! [invalidate-uid?] {:post [(valid-config? %)]} (let [config-file (config-file) config-from-file (try (when (.exists config-file) (read-config-from-file! config-file)) (catch Throwable error (log/warn :msg (str "Failed to read analytics config: " config-file) :exception error) nil)) config (if-not (valid-config? config-from-file) (make-config) (cond-> config-from-file (and invalidate-uid? (contains? config-from-file :uid)) (assoc :uid nil)))] (when (not= config-from-file config) (write-config! config)) config)) ;; ----------------------------------------------------------------------------- ;; Internals ;; ----------------------------------------------------------------------------- ;; Entries sent to Google Analytics must be both UTF-8 and URL Encoded. ;; See the "URL Encoding Values" section here for details: ;; https://developers.google.com/analytics/devguides/collection/protocol/v1/reference (def encode-string (partial url/encode url/x-www-form-urlencoded-safe-character? false StandardCharsets/UTF_8)) (defn- encode-key-value-pair ^String [[k v]] (str (encode-string (name k)) "=" (encode-string v))) (defn- event->line ^String [event {:keys [cid uid] :as _config}] {:pre [(valid-event? event) (valid-cid? cid) (or (nil? uid) (valid-uid? uid))]} (let [tid (str "tid=" (get-in connection-properties [:google-analytics :tid])) common-pairs (if (some? uid) ; NOTE: The uid is also supplied as Custom Dimension 1. ["v=1" tid (str "cid=" cid) (str "uid=" uid) (str "cd1=" uid)] ["v=1" tid (str "cid=" cid)]) pairs (into common-pairs (map encode-key-value-pair) event)] (string/join "&" pairs))) (defn- batch->payload ^bytes [batch] {:pre [(vector? batch) (not-empty batch)]} (let [text (string/join "\n" batch)] (.getBytes text StandardCharsets/UTF_8))) (defn- get-response-code! "Wrapper rebound to verify response from dev server in tests." [^HttpURLConnection connection] (.getResponseCode connection)) (defn- post! ^HttpURLConnection [^String url-string ^String content-type ^bytes payload] {:pre [(not-empty payload)]} (let [^HttpURLConnection connection (.openConnection (URL. url-string))] (doto connection (.setRequestMethod "POST") (.setDoOutput true) (.setFixedLengthStreamingMode (count payload)) (.setRequestProperty "Content-Type" content-type) (.connect)) (with-open [output-stream (.getOutputStream connection)] (.write output-stream payload)) connection)) (defn- ok-response-code? [^long response-code] (<= 200 response-code 299)) (defn- send-payload! [analytics-url ^bytes payload] (try (let [response-code (get-response-code! (post! analytics-url payload-content-type payload))] (if (ok-response-code? response-code) true (do (log/warn :msg (str "Analytics server sent non-OK response code " response-code)) false))) (catch Exception error (log/warn :msg "An exception was thrown when sending analytics data" :exception error) false))) (defn- pop-count [queue ^long count] (nth (iterate pop queue) count)) (defn- send-one-batch! "Sends one batch of events from the queue. Returns false if there were events on the queue that could not be sent. Otherwise removes the successfully sent events from the queue and returns true." [analytics-url] (let [event-queue @event-queue-atom batch (into [] (take batch-size) event-queue)] (if (empty? batch) true (if-not (send-payload! analytics-url (batch->payload batch)) false (do (swap! event-queue-atom pop-count (count batch)) true))))) (defn- send-remaining-batches! [analytics-url] (let [event-queue @event-queue-atom] (loop [event-queue event-queue] (when-some [batch (not-empty (into [] (take batch-size) event-queue))] (send-payload! analytics-url (batch->payload batch)) (recur (pop-count event-queue (count batch))))) (swap! event-queue-atom pop-count (count event-queue)) nil)) (declare shutdown!) (defn- start-worker! [analytics-url ^long send-interval] (let [stopped-atom (atom false) thread (future (try (loop [failed-send-attempts 0] (cond (>= failed-send-attempts max-failed-send-attempts) (do (log/warn :msg (str "Analytics shut down after " max-failed-send-attempts " failed send attempts")) (shutdown! 0) (reset! event-queue-atom PersistentQueue/EMPTY) nil) @stopped-atom (send-remaining-batches! analytics-url) :else (do (Thread/sleep send-interval) (if (send-one-batch! analytics-url) (recur 0) (recur (inc failed-send-attempts)))))) (catch CancellationException _ nil) (catch InterruptedException _ nil) (catch Throwable error (log/warn :msg "Abnormal worker thread termination" :exception error))))] {:stopped-atom stopped-atom :thread thread})) (defn- shutdown-worker! [{:keys [stopped-atom thread]} timeout-ms] (if-not (pos? timeout-ms) (future-cancel thread) (do ;; Try to shut down the worker thread gracefully, otherwise cancel the thread. (reset! stopped-atom true) (when (= ::timeout (deref thread timeout-ms ::timeout)) (future-cancel thread)))) nil) (declare enabled?) (defn- append-event! [event] (when-some [config @config-atom] (let [line (event->line event config)] (when (enabled?) (swap! event-queue-atom conj line)) (when log-events? (log/info :msg line))))) ;; ----------------------------------------------------------------------------- ;; Public interface ;; ----------------------------------------------------------------------------- (defn start! [^String analytics-url send-interval invalidate-uid?] {:pre [(valid-analytics-url? analytics-url)]} (reset! config-atom (read-config! invalidate-uid?)) (when (some? (sys/defold-version)) (swap! worker-atom (fn [started-worker] (when (some? started-worker) (shutdown-worker! started-worker 0)) (start-worker! analytics-url send-interval))))) (defn shutdown! ([] (shutdown! shutdown-timeout)) ([timeout-ms] (swap! worker-atom (fn [started-worker] (when (some? started-worker) (shutdown-worker! started-worker timeout-ms)))))) (defn enabled? [] (some? @worker-atom)) (defn set-uid! [^String uid] {:pre [(or (nil? uid) (valid-uid? uid))]} (swap! config-atom (fn [config] (let [config (or config (read-config! false)) updated-config (assoc config :uid uid)] (when (not= config updated-config) (write-config! updated-config)) updated-config)))) (defn track-event! ([^String category ^String action] (append-event! {:t "event" :ec category :ea action})) ([^String category ^String action ^String label] (append-event! {:t "event" :ec category :ea action :el label}))) (defn track-exception! [^Throwable exception] (append-event! {:t "exception" :exd (.getSimpleName (class exception))})) (defn track-screen! [^String screen-name] (if-some [version (sys/defold-version)] (append-event! {:t "screenview" :an "defold" :av version :cd screen-name}) (append-event! {:t "screenview" :an "defold" :cd screen-name})))
55513
;; 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.analytics (:require [clojure.data.json :as json] [clojure.java.io :as io] [clojure.string :as string] [editor.connection-properties :refer [connection-properties]] [editor.system :as sys] [editor.url :as url] [service.log :as log]) (:import (clojure.lang PersistentQueue) (com.defold.editor Editor) (java.io File) (java.net HttpURLConnection MalformedURLException URL) (java.nio.charset StandardCharsets) (java.util UUID) (java.util.concurrent CancellationException))) (set! *warn-on-reflection* true) ;; Set this to true to see the events that get sent when testing. (defonce ^:private log-events? false) (defonce ^:private batch-size 16) (defonce ^:private cid-regex #"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") (defonce ^:private config-atom (atom nil)) (defonce ^:private event-queue-atom (atom PersistentQueue/EMPTY)) (defonce ^:private max-failed-send-attempts 5) (defonce ^:private payload-content-type "application/x-www-form-urlencoded; charset=UTF-8") (defonce ^:private shutdown-timeout 1000) (defonce ^:private uid-regex #"[0-9A-F]{16}") (defonce ^:private worker-atom (atom nil)) ;; ----------------------------------------------------------------------------- ;; Validation ;; ----------------------------------------------------------------------------- (defn- valid-analytics-url? [value] (and (string? value) (try (let [url (URL. value)] (and (nil? (.getQuery url)) (nil? (.getRef url)) (let [protocol (.getProtocol url)] (or (= "http" protocol) (= "https" protocol))))) (catch MalformedURLException _ false)))) (defn- valid-cid? [value] (and (string? value) (.matches (re-matcher cid-regex value)))) (defn- valid-uid? [value] (and (string? value) (.matches (re-matcher uid-regex value)))) (defn- valid-config? [config] (and (map? config) (= #{:cid :uid} (set (keys config))) (let [{:keys [cid uid]} config] (and (valid-cid? cid) (or (nil? uid) (valid-uid? uid)))))) (def ^:private valid-event? (every-pred map? (comp nil? :cd1) ; Custom Dimension 1 is reserved for the uid. (comp (every-pred string? not-empty) :t) (partial every? (every-pred (comp keyword? key) (comp string? val) (comp not-empty val))))) ;; ----------------------------------------------------------------------------- ;; Configuration ;; ----------------------------------------------------------------------------- (defn- make-config [] {:post [(valid-config? %)]} {:cid (str (UUID/randomUUID)) :uid nil}) (defn- config-file ^File [] (.toFile (.resolve (Editor/getSupportPath) ".defold-analytics"))) (defn- write-config-to-file! [{:keys [cid uid]} ^File config-file] {:pre [(valid-cid? cid) (or (nil? uid) (valid-uid? uid))]} (let [json (if (some? uid) {"cid" cid "uid" uid} {"cid" cid})] (with-open [writer (io/writer config-file)] (json/write json writer)))) (defn- write-config! [config] (let [config-file (config-file)] (try (write-config-to-file! config config-file) (catch Throwable error (log/warn :msg (str "Failed to write analytics config: " config-file) :exception error))))) (defn- read-config-from-file! [^File config-file] (with-open [reader (io/reader config-file)] (let [{cid "cid" uid "uid"} (json/read reader)] {:cid cid :uid uid}))) (defn- read-config! [invalidate-uid?] {:post [(valid-config? %)]} (let [config-file (config-file) config-from-file (try (when (.exists config-file) (read-config-from-file! config-file)) (catch Throwable error (log/warn :msg (str "Failed to read analytics config: " config-file) :exception error) nil)) config (if-not (valid-config? config-from-file) (make-config) (cond-> config-from-file (and invalidate-uid? (contains? config-from-file :uid)) (assoc :uid nil)))] (when (not= config-from-file config) (write-config! config)) config)) ;; ----------------------------------------------------------------------------- ;; Internals ;; ----------------------------------------------------------------------------- ;; Entries sent to Google Analytics must be both UTF-8 and URL Encoded. ;; See the "URL Encoding Values" section here for details: ;; https://developers.google.com/analytics/devguides/collection/protocol/v1/reference (def encode-string (partial url/encode url/x-www-form-urlencoded-safe-character? false StandardCharsets/UTF_8)) (defn- encode-key-value-pair ^String [[k v]] (str (encode-string (name k)) "=" (encode-string v))) (defn- event->line ^String [event {:keys [cid uid] :as _config}] {:pre [(valid-event? event) (valid-cid? cid) (or (nil? uid) (valid-uid? uid))]} (let [tid (str "tid=" (get-in connection-properties [:google-analytics :tid])) common-pairs (if (some? uid) ; NOTE: The uid is also supplied as Custom Dimension 1. ["v=1" tid (str "cid=" cid) (str "uid=" uid) (str "cd1=" uid)] ["v=1" tid (str "cid=" cid)]) pairs (into common-pairs (map encode-key-value-pair) event)] (string/join "&" pairs))) (defn- batch->payload ^bytes [batch] {:pre [(vector? batch) (not-empty batch)]} (let [text (string/join "\n" batch)] (.getBytes text StandardCharsets/UTF_8))) (defn- get-response-code! "Wrapper rebound to verify response from dev server in tests." [^HttpURLConnection connection] (.getResponseCode connection)) (defn- post! ^HttpURLConnection [^String url-string ^String content-type ^bytes payload] {:pre [(not-empty payload)]} (let [^HttpURLConnection connection (.openConnection (URL. url-string))] (doto connection (.setRequestMethod "POST") (.setDoOutput true) (.setFixedLengthStreamingMode (count payload)) (.setRequestProperty "Content-Type" content-type) (.connect)) (with-open [output-stream (.getOutputStream connection)] (.write output-stream payload)) connection)) (defn- ok-response-code? [^long response-code] (<= 200 response-code 299)) (defn- send-payload! [analytics-url ^bytes payload] (try (let [response-code (get-response-code! (post! analytics-url payload-content-type payload))] (if (ok-response-code? response-code) true (do (log/warn :msg (str "Analytics server sent non-OK response code " response-code)) false))) (catch Exception error (log/warn :msg "An exception was thrown when sending analytics data" :exception error) false))) (defn- pop-count [queue ^long count] (nth (iterate pop queue) count)) (defn- send-one-batch! "Sends one batch of events from the queue. Returns false if there were events on the queue that could not be sent. Otherwise removes the successfully sent events from the queue and returns true." [analytics-url] (let [event-queue @event-queue-atom batch (into [] (take batch-size) event-queue)] (if (empty? batch) true (if-not (send-payload! analytics-url (batch->payload batch)) false (do (swap! event-queue-atom pop-count (count batch)) true))))) (defn- send-remaining-batches! [analytics-url] (let [event-queue @event-queue-atom] (loop [event-queue event-queue] (when-some [batch (not-empty (into [] (take batch-size) event-queue))] (send-payload! analytics-url (batch->payload batch)) (recur (pop-count event-queue (count batch))))) (swap! event-queue-atom pop-count (count event-queue)) nil)) (declare shutdown!) (defn- start-worker! [analytics-url ^long send-interval] (let [stopped-atom (atom false) thread (future (try (loop [failed-send-attempts 0] (cond (>= failed-send-attempts max-failed-send-attempts) (do (log/warn :msg (str "Analytics shut down after " max-failed-send-attempts " failed send attempts")) (shutdown! 0) (reset! event-queue-atom PersistentQueue/EMPTY) nil) @stopped-atom (send-remaining-batches! analytics-url) :else (do (Thread/sleep send-interval) (if (send-one-batch! analytics-url) (recur 0) (recur (inc failed-send-attempts)))))) (catch CancellationException _ nil) (catch InterruptedException _ nil) (catch Throwable error (log/warn :msg "Abnormal worker thread termination" :exception error))))] {:stopped-atom stopped-atom :thread thread})) (defn- shutdown-worker! [{:keys [stopped-atom thread]} timeout-ms] (if-not (pos? timeout-ms) (future-cancel thread) (do ;; Try to shut down the worker thread gracefully, otherwise cancel the thread. (reset! stopped-atom true) (when (= ::timeout (deref thread timeout-ms ::timeout)) (future-cancel thread)))) nil) (declare enabled?) (defn- append-event! [event] (when-some [config @config-atom] (let [line (event->line event config)] (when (enabled?) (swap! event-queue-atom conj line)) (when log-events? (log/info :msg line))))) ;; ----------------------------------------------------------------------------- ;; Public interface ;; ----------------------------------------------------------------------------- (defn start! [^String analytics-url send-interval invalidate-uid?] {:pre [(valid-analytics-url? analytics-url)]} (reset! config-atom (read-config! invalidate-uid?)) (when (some? (sys/defold-version)) (swap! worker-atom (fn [started-worker] (when (some? started-worker) (shutdown-worker! started-worker 0)) (start-worker! analytics-url send-interval))))) (defn shutdown! ([] (shutdown! shutdown-timeout)) ([timeout-ms] (swap! worker-atom (fn [started-worker] (when (some? started-worker) (shutdown-worker! started-worker timeout-ms)))))) (defn enabled? [] (some? @worker-atom)) (defn set-uid! [^String uid] {:pre [(or (nil? uid) (valid-uid? uid))]} (swap! config-atom (fn [config] (let [config (or config (read-config! false)) updated-config (assoc config :uid uid)] (when (not= config updated-config) (write-config! updated-config)) updated-config)))) (defn track-event! ([^String category ^String action] (append-event! {:t "event" :ec category :ea action})) ([^String category ^String action ^String label] (append-event! {:t "event" :ec category :ea action :el label}))) (defn track-exception! [^Throwable exception] (append-event! {:t "exception" :exd (.getSimpleName (class exception))})) (defn track-screen! [^String screen-name] (if-some [version (sys/defold-version)] (append-event! {:t "screenview" :an "defold" :av version :cd screen-name}) (append-event! {:t "screenview" :an "defold" :cd screen-name})))
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.analytics (:require [clojure.data.json :as json] [clojure.java.io :as io] [clojure.string :as string] [editor.connection-properties :refer [connection-properties]] [editor.system :as sys] [editor.url :as url] [service.log :as log]) (:import (clojure.lang PersistentQueue) (com.defold.editor Editor) (java.io File) (java.net HttpURLConnection MalformedURLException URL) (java.nio.charset StandardCharsets) (java.util UUID) (java.util.concurrent CancellationException))) (set! *warn-on-reflection* true) ;; Set this to true to see the events that get sent when testing. (defonce ^:private log-events? false) (defonce ^:private batch-size 16) (defonce ^:private cid-regex #"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") (defonce ^:private config-atom (atom nil)) (defonce ^:private event-queue-atom (atom PersistentQueue/EMPTY)) (defonce ^:private max-failed-send-attempts 5) (defonce ^:private payload-content-type "application/x-www-form-urlencoded; charset=UTF-8") (defonce ^:private shutdown-timeout 1000) (defonce ^:private uid-regex #"[0-9A-F]{16}") (defonce ^:private worker-atom (atom nil)) ;; ----------------------------------------------------------------------------- ;; Validation ;; ----------------------------------------------------------------------------- (defn- valid-analytics-url? [value] (and (string? value) (try (let [url (URL. value)] (and (nil? (.getQuery url)) (nil? (.getRef url)) (let [protocol (.getProtocol url)] (or (= "http" protocol) (= "https" protocol))))) (catch MalformedURLException _ false)))) (defn- valid-cid? [value] (and (string? value) (.matches (re-matcher cid-regex value)))) (defn- valid-uid? [value] (and (string? value) (.matches (re-matcher uid-regex value)))) (defn- valid-config? [config] (and (map? config) (= #{:cid :uid} (set (keys config))) (let [{:keys [cid uid]} config] (and (valid-cid? cid) (or (nil? uid) (valid-uid? uid)))))) (def ^:private valid-event? (every-pred map? (comp nil? :cd1) ; Custom Dimension 1 is reserved for the uid. (comp (every-pred string? not-empty) :t) (partial every? (every-pred (comp keyword? key) (comp string? val) (comp not-empty val))))) ;; ----------------------------------------------------------------------------- ;; Configuration ;; ----------------------------------------------------------------------------- (defn- make-config [] {:post [(valid-config? %)]} {:cid (str (UUID/randomUUID)) :uid nil}) (defn- config-file ^File [] (.toFile (.resolve (Editor/getSupportPath) ".defold-analytics"))) (defn- write-config-to-file! [{:keys [cid uid]} ^File config-file] {:pre [(valid-cid? cid) (or (nil? uid) (valid-uid? uid))]} (let [json (if (some? uid) {"cid" cid "uid" uid} {"cid" cid})] (with-open [writer (io/writer config-file)] (json/write json writer)))) (defn- write-config! [config] (let [config-file (config-file)] (try (write-config-to-file! config config-file) (catch Throwable error (log/warn :msg (str "Failed to write analytics config: " config-file) :exception error))))) (defn- read-config-from-file! [^File config-file] (with-open [reader (io/reader config-file)] (let [{cid "cid" uid "uid"} (json/read reader)] {:cid cid :uid uid}))) (defn- read-config! [invalidate-uid?] {:post [(valid-config? %)]} (let [config-file (config-file) config-from-file (try (when (.exists config-file) (read-config-from-file! config-file)) (catch Throwable error (log/warn :msg (str "Failed to read analytics config: " config-file) :exception error) nil)) config (if-not (valid-config? config-from-file) (make-config) (cond-> config-from-file (and invalidate-uid? (contains? config-from-file :uid)) (assoc :uid nil)))] (when (not= config-from-file config) (write-config! config)) config)) ;; ----------------------------------------------------------------------------- ;; Internals ;; ----------------------------------------------------------------------------- ;; Entries sent to Google Analytics must be both UTF-8 and URL Encoded. ;; See the "URL Encoding Values" section here for details: ;; https://developers.google.com/analytics/devguides/collection/protocol/v1/reference (def encode-string (partial url/encode url/x-www-form-urlencoded-safe-character? false StandardCharsets/UTF_8)) (defn- encode-key-value-pair ^String [[k v]] (str (encode-string (name k)) "=" (encode-string v))) (defn- event->line ^String [event {:keys [cid uid] :as _config}] {:pre [(valid-event? event) (valid-cid? cid) (or (nil? uid) (valid-uid? uid))]} (let [tid (str "tid=" (get-in connection-properties [:google-analytics :tid])) common-pairs (if (some? uid) ; NOTE: The uid is also supplied as Custom Dimension 1. ["v=1" tid (str "cid=" cid) (str "uid=" uid) (str "cd1=" uid)] ["v=1" tid (str "cid=" cid)]) pairs (into common-pairs (map encode-key-value-pair) event)] (string/join "&" pairs))) (defn- batch->payload ^bytes [batch] {:pre [(vector? batch) (not-empty batch)]} (let [text (string/join "\n" batch)] (.getBytes text StandardCharsets/UTF_8))) (defn- get-response-code! "Wrapper rebound to verify response from dev server in tests." [^HttpURLConnection connection] (.getResponseCode connection)) (defn- post! ^HttpURLConnection [^String url-string ^String content-type ^bytes payload] {:pre [(not-empty payload)]} (let [^HttpURLConnection connection (.openConnection (URL. url-string))] (doto connection (.setRequestMethod "POST") (.setDoOutput true) (.setFixedLengthStreamingMode (count payload)) (.setRequestProperty "Content-Type" content-type) (.connect)) (with-open [output-stream (.getOutputStream connection)] (.write output-stream payload)) connection)) (defn- ok-response-code? [^long response-code] (<= 200 response-code 299)) (defn- send-payload! [analytics-url ^bytes payload] (try (let [response-code (get-response-code! (post! analytics-url payload-content-type payload))] (if (ok-response-code? response-code) true (do (log/warn :msg (str "Analytics server sent non-OK response code " response-code)) false))) (catch Exception error (log/warn :msg "An exception was thrown when sending analytics data" :exception error) false))) (defn- pop-count [queue ^long count] (nth (iterate pop queue) count)) (defn- send-one-batch! "Sends one batch of events from the queue. Returns false if there were events on the queue that could not be sent. Otherwise removes the successfully sent events from the queue and returns true." [analytics-url] (let [event-queue @event-queue-atom batch (into [] (take batch-size) event-queue)] (if (empty? batch) true (if-not (send-payload! analytics-url (batch->payload batch)) false (do (swap! event-queue-atom pop-count (count batch)) true))))) (defn- send-remaining-batches! [analytics-url] (let [event-queue @event-queue-atom] (loop [event-queue event-queue] (when-some [batch (not-empty (into [] (take batch-size) event-queue))] (send-payload! analytics-url (batch->payload batch)) (recur (pop-count event-queue (count batch))))) (swap! event-queue-atom pop-count (count event-queue)) nil)) (declare shutdown!) (defn- start-worker! [analytics-url ^long send-interval] (let [stopped-atom (atom false) thread (future (try (loop [failed-send-attempts 0] (cond (>= failed-send-attempts max-failed-send-attempts) (do (log/warn :msg (str "Analytics shut down after " max-failed-send-attempts " failed send attempts")) (shutdown! 0) (reset! event-queue-atom PersistentQueue/EMPTY) nil) @stopped-atom (send-remaining-batches! analytics-url) :else (do (Thread/sleep send-interval) (if (send-one-batch! analytics-url) (recur 0) (recur (inc failed-send-attempts)))))) (catch CancellationException _ nil) (catch InterruptedException _ nil) (catch Throwable error (log/warn :msg "Abnormal worker thread termination" :exception error))))] {:stopped-atom stopped-atom :thread thread})) (defn- shutdown-worker! [{:keys [stopped-atom thread]} timeout-ms] (if-not (pos? timeout-ms) (future-cancel thread) (do ;; Try to shut down the worker thread gracefully, otherwise cancel the thread. (reset! stopped-atom true) (when (= ::timeout (deref thread timeout-ms ::timeout)) (future-cancel thread)))) nil) (declare enabled?) (defn- append-event! [event] (when-some [config @config-atom] (let [line (event->line event config)] (when (enabled?) (swap! event-queue-atom conj line)) (when log-events? (log/info :msg line))))) ;; ----------------------------------------------------------------------------- ;; Public interface ;; ----------------------------------------------------------------------------- (defn start! [^String analytics-url send-interval invalidate-uid?] {:pre [(valid-analytics-url? analytics-url)]} (reset! config-atom (read-config! invalidate-uid?)) (when (some? (sys/defold-version)) (swap! worker-atom (fn [started-worker] (when (some? started-worker) (shutdown-worker! started-worker 0)) (start-worker! analytics-url send-interval))))) (defn shutdown! ([] (shutdown! shutdown-timeout)) ([timeout-ms] (swap! worker-atom (fn [started-worker] (when (some? started-worker) (shutdown-worker! started-worker timeout-ms)))))) (defn enabled? [] (some? @worker-atom)) (defn set-uid! [^String uid] {:pre [(or (nil? uid) (valid-uid? uid))]} (swap! config-atom (fn [config] (let [config (or config (read-config! false)) updated-config (assoc config :uid uid)] (when (not= config updated-config) (write-config! updated-config)) updated-config)))) (defn track-event! ([^String category ^String action] (append-event! {:t "event" :ec category :ea action})) ([^String category ^String action ^String label] (append-event! {:t "event" :ec category :ea action :el label}))) (defn track-exception! [^Throwable exception] (append-event! {:t "exception" :exd (.getSimpleName (class exception))})) (defn track-screen! [^String screen-name] (if-some [version (sys/defold-version)] (append-event! {:t "screenview" :an "defold" :av version :cd screen-name}) (append-event! {:t "screenview" :an "defold" :cd screen-name})))
[ { "context": " Logic SAT\n; Examples: jabeh\n\n; Copyright (c) 2016 Burkhardt Renz, Marco Stephan, THM. All rights reserved.\n; The u", "end": 103, "score": 0.9998559951782227, "start": 89, "tag": "NAME", "value": "Burkhardt Renz" }, { "context": "mples: jabeh\n\n; Copyright (c) 2016 Burkhardt Renz, Marco Stephan, THM. All rights reserved.\n; The use and distribu", "end": 118, "score": 0.9998466372489929, "start": 105, "tag": "NAME", "value": "Marco Stephan" } ]
src/lwb/prop/examples/jabeh.clj
esb-lwb/lwb
22
; lwb Logic WorkBench -- Propositional Logic SAT ; Examples: jabeh ; Copyright (c) 2016 Burkhardt Renz, Marco Stephan, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.prop.examples.jabeh (:require [lwb.prop :refer :all]) (:require [lwb.prop.cardinality :refer (min-kof kof)]) (:require [lwb.prop.sat :refer (sat)]) (:require [clojure.core.matrix :refer (emap)]) (:require [clojure.string :as str])) (def u "A symbol for an unknown state of a cell in the puzzle" \.) ;; The puzzle is given by a map with the keys :col-holes, ;; :row-holes and :field ;; e.g. (comment (def p {:col-holes [2 2 1 2 1 1 1 2] :row-holes [1 1 2 1 2 2 2 1] :field [[u u u 2 u u u u] [u u u u 6 u u u] [u u u u u 5 u 7] [u u 4 u 7 u u u] [1 u u 4 6 8 u u] [u u u u u u u u] [u u u 1 u u 7 u] [u u u u u u u u]]}) ) ;; :col-holes is a vector of the number of holes in the columns ;; :row-holes is a vector of the number of holes in te rows ;; :field is the field with ;; u = an unknown state of the cell ;; a number = an arrow, decoding the direction at cell x as follows ;; 7 8 1 ;; 6 x 2 ;; 5 4 3 ;; The encoding of the puzzle in the propositional logic: ;; We represent each cell as an atomic proposition build from the ;; index of the cell by make-sym. ;; If the atom is true, there is a hole, false otherwise ;; The constraints are ;; - the number of true atoms in a row is given by the corresponding number in :row-holes, ;; - the number of true atoms in a columns is given by the corresponding number in :col-holes, ;; - the atom for a cell with an arrow is false, and ;; - in the direction of the arrow one of the corresponding atoms has to be true ;; Symbols representing the proposition that a cell ;; is a "hole" or not. ;; The symbols are good for puzzle with up to 100 rows ;; and 100 columns (defn- make-sym "Makes a symbol from an index [row, col]." [[row col]] (symbol (format "c%02d%02d" row col))) (defn- size "Size [row-count col-count] of a (well-formed) puzzle." [puzzle] [(count (:row-holes puzzle)) (count (:col-holes puzzle))]) ;; Generating a seq of clauses for the constraints on the rows (defn rows-cl "Seq of clauses for the rows: each row has exactly the number of holes given by the corresponding number in :row-holes." [puzzle] (let [[row-count col-count] (size puzzle) syms (map make-sym (for [r (range row-count) c (range col-count)] [r c])) sym-rows (partition col-count syms)] (mapcat kof (:row-holes puzzle) sym-rows))) ;; Generating a seq of clauses for the constraints on the columns (defn cols-cl "Seq of clauses for the columns: each column has exactly the number of holes given by the corresponding number in :col-holes." [puzzle] (let [[row-count col-count] (size puzzle) syms (map make-sym (for [c (range col-count) r (range row-count)] [r c])) sym-rows (partition row-count syms)] (mapcat kof (:col-holes puzzle) sym-rows))) ;; Generating a seq of clauses for the constraints given by arrows (defn- next-cell "Next cell at [r c] in the given direction." [puzzle direction [r c]] (let [[row-count col-count] (size puzzle) [r2 c2] (case direction 1 [(dec r) (inc c)] 2 [r (inc c)] 3 [(inc r) (inc c)] 4 [(inc r) c] 5 [(inc r) (dec c)] 6 [r (dec c)] 7 [(dec r) (dec c)] 8 [(dec r) c])] (cond (neg? r2) nil (neg? c2) nil (>= r2 row-count) nil (>= c2 col-count) nil :else [r2 c2]))) (defn- next-cells "All cells at [r c] in the given direction." [puzzle direction [r c]] (vec (drop 1 (take-while some? (iterate (partial next-cell puzzle direction) [r c]))))) (defn- arrow-cl "Seq of clause for the fact that there is at least one hole in the cells in the direction of the arrow at [r c]." [puzzle direction [r c]] (min-kof 1 (map make-sym (next-cells puzzle direction [r c])))) (defn- arrow-cell? "Checks whether [[_ _] value] is a cell with a value that's an arrow." [[[_ _] value]] (not= value u)) (defn- neg-sym "Clause that negates sym." [sym] (list (list 'or (list 'not sym)))) (defn- arrow-cl-complete "Seq of clauses for the arrow-cell itself and for the cells in its direction." [puzzle [[row col] value]] (let [sym (make-sym [row col]) neg (neg-sym sym)] (concat neg (arrow-cl puzzle value [row col])))) (defn arrows-cl "Seq of clauses for all arrows, i.e. a clause of a single literal, expressing that the cell with the arrow itself is not a hole together with the clause that there is a hole in the direction of the arrow." [puzzle] (let [[row-count col-count] (size puzzle) field (:field puzzle) cells (for [r (range row-count) c (range col-count)] [[r c] (get-in field [r c])]) arrow-cells (filter arrow-cell? cells)] (mapcat (partial arrow-cl-complete puzzle) arrow-cells))) ;; Combining a puzzle and the rules to a proposition (defn jabeh-prop "Generates the proposition for the given puzzle." [puzzle] (apply list 'and (concat (rows-cl puzzle) (cols-cl puzzle) (arrows-cl puzzle)))) (defn solve "Solve Jabeh puzzle." [puzzle] (-> puzzle (jabeh-prop) (sat))) ;; Constructing the solution with + for holes and - else (defn- prepare-solution "Prepares the solution from the sat solver to a matrix with + (a hole) and - (not a hole)." [puzzle solution] (let [[_ col-count] (size puzzle)] (->> solution (map identity) (sort) (map #(if (= (second %) true) \+ \-)) (partition col-count) (map vec)))) (defn- combine "Combines the given field with the prepared solution." [field prepared-sol] (let [map-fn (fn [a b] (if (= a \.) b a))] (emap map-fn field prepared-sol))) (defn solve-and-assoc "Solve and bind in field of the puzzle" [puzzle] (let [psol (prepare-solution puzzle (solve puzzle)) fsol (combine (:field puzzle) psol)] (assoc puzzle :field fsol))) ;; Pretty Printer, good for puzzle with up to 10 rows and columns (defn- print-cell [cell] (case cell 1 \u2197 2 \u2192 3 \u2198 4 \u2193 5 \u2199 6 \u2190 7 \u2196 8 \u2191 \- \u25cb \+ \u25cf \. )) (defn pretty-print "Pretty-printing jabeh." [puzzle] (let [[row-count col-count] (size puzzle)] (print "*** Jabeh\n") (print (str " | " (str/join " " (:col-holes puzzle)) "\n")) (print (str "--+" (str/join (repeat col-count "--")) "\n")) (doseq [row (range row-count) col (range col-count)] (if (zero? col) (print (str (nth (:row-holes puzzle) row) " | "))) (print (str (print-cell (get-in (:field puzzle) [row col])) " ")) (if (= (dec col-count) col) (print "\n"))))) (defn print-puzzle-and-solution [puzzle] (pretty-print puzzle) (pretty-print (solve-and-assoc puzzle))) ;; Examples (comment (defn test-puzzle [file] (print-puzzle-and-solution (load-file (str "resources/jabeh/" file ".edn")))) (test-puzzle "jabeh01") (test-puzzle "jabeh02") (test-puzzle "jabeh03") (test-puzzle "jabeh04") (test-puzzle "jabeh05") (test-puzzle "jabeh06") (test-puzzle "jabeh07") ;; Benchmarks ;; load, run, print (defn bench [puzzles] (time (do (run! test-puzzle puzzles) :done))) (dotimes [_ 10] (bench ["jabeh01" "jabeh02" "jabeh03" "jabeh04" "jabeh05" "jabeh06"])) ; => 260 msec )
52783
; lwb Logic WorkBench -- Propositional Logic SAT ; Examples: jabeh ; Copyright (c) 2016 <NAME>, <NAME>, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.prop.examples.jabeh (:require [lwb.prop :refer :all]) (:require [lwb.prop.cardinality :refer (min-kof kof)]) (:require [lwb.prop.sat :refer (sat)]) (:require [clojure.core.matrix :refer (emap)]) (:require [clojure.string :as str])) (def u "A symbol for an unknown state of a cell in the puzzle" \.) ;; The puzzle is given by a map with the keys :col-holes, ;; :row-holes and :field ;; e.g. (comment (def p {:col-holes [2 2 1 2 1 1 1 2] :row-holes [1 1 2 1 2 2 2 1] :field [[u u u 2 u u u u] [u u u u 6 u u u] [u u u u u 5 u 7] [u u 4 u 7 u u u] [1 u u 4 6 8 u u] [u u u u u u u u] [u u u 1 u u 7 u] [u u u u u u u u]]}) ) ;; :col-holes is a vector of the number of holes in the columns ;; :row-holes is a vector of the number of holes in te rows ;; :field is the field with ;; u = an unknown state of the cell ;; a number = an arrow, decoding the direction at cell x as follows ;; 7 8 1 ;; 6 x 2 ;; 5 4 3 ;; The encoding of the puzzle in the propositional logic: ;; We represent each cell as an atomic proposition build from the ;; index of the cell by make-sym. ;; If the atom is true, there is a hole, false otherwise ;; The constraints are ;; - the number of true atoms in a row is given by the corresponding number in :row-holes, ;; - the number of true atoms in a columns is given by the corresponding number in :col-holes, ;; - the atom for a cell with an arrow is false, and ;; - in the direction of the arrow one of the corresponding atoms has to be true ;; Symbols representing the proposition that a cell ;; is a "hole" or not. ;; The symbols are good for puzzle with up to 100 rows ;; and 100 columns (defn- make-sym "Makes a symbol from an index [row, col]." [[row col]] (symbol (format "c%02d%02d" row col))) (defn- size "Size [row-count col-count] of a (well-formed) puzzle." [puzzle] [(count (:row-holes puzzle)) (count (:col-holes puzzle))]) ;; Generating a seq of clauses for the constraints on the rows (defn rows-cl "Seq of clauses for the rows: each row has exactly the number of holes given by the corresponding number in :row-holes." [puzzle] (let [[row-count col-count] (size puzzle) syms (map make-sym (for [r (range row-count) c (range col-count)] [r c])) sym-rows (partition col-count syms)] (mapcat kof (:row-holes puzzle) sym-rows))) ;; Generating a seq of clauses for the constraints on the columns (defn cols-cl "Seq of clauses for the columns: each column has exactly the number of holes given by the corresponding number in :col-holes." [puzzle] (let [[row-count col-count] (size puzzle) syms (map make-sym (for [c (range col-count) r (range row-count)] [r c])) sym-rows (partition row-count syms)] (mapcat kof (:col-holes puzzle) sym-rows))) ;; Generating a seq of clauses for the constraints given by arrows (defn- next-cell "Next cell at [r c] in the given direction." [puzzle direction [r c]] (let [[row-count col-count] (size puzzle) [r2 c2] (case direction 1 [(dec r) (inc c)] 2 [r (inc c)] 3 [(inc r) (inc c)] 4 [(inc r) c] 5 [(inc r) (dec c)] 6 [r (dec c)] 7 [(dec r) (dec c)] 8 [(dec r) c])] (cond (neg? r2) nil (neg? c2) nil (>= r2 row-count) nil (>= c2 col-count) nil :else [r2 c2]))) (defn- next-cells "All cells at [r c] in the given direction." [puzzle direction [r c]] (vec (drop 1 (take-while some? (iterate (partial next-cell puzzle direction) [r c]))))) (defn- arrow-cl "Seq of clause for the fact that there is at least one hole in the cells in the direction of the arrow at [r c]." [puzzle direction [r c]] (min-kof 1 (map make-sym (next-cells puzzle direction [r c])))) (defn- arrow-cell? "Checks whether [[_ _] value] is a cell with a value that's an arrow." [[[_ _] value]] (not= value u)) (defn- neg-sym "Clause that negates sym." [sym] (list (list 'or (list 'not sym)))) (defn- arrow-cl-complete "Seq of clauses for the arrow-cell itself and for the cells in its direction." [puzzle [[row col] value]] (let [sym (make-sym [row col]) neg (neg-sym sym)] (concat neg (arrow-cl puzzle value [row col])))) (defn arrows-cl "Seq of clauses for all arrows, i.e. a clause of a single literal, expressing that the cell with the arrow itself is not a hole together with the clause that there is a hole in the direction of the arrow." [puzzle] (let [[row-count col-count] (size puzzle) field (:field puzzle) cells (for [r (range row-count) c (range col-count)] [[r c] (get-in field [r c])]) arrow-cells (filter arrow-cell? cells)] (mapcat (partial arrow-cl-complete puzzle) arrow-cells))) ;; Combining a puzzle and the rules to a proposition (defn jabeh-prop "Generates the proposition for the given puzzle." [puzzle] (apply list 'and (concat (rows-cl puzzle) (cols-cl puzzle) (arrows-cl puzzle)))) (defn solve "Solve Jabeh puzzle." [puzzle] (-> puzzle (jabeh-prop) (sat))) ;; Constructing the solution with + for holes and - else (defn- prepare-solution "Prepares the solution from the sat solver to a matrix with + (a hole) and - (not a hole)." [puzzle solution] (let [[_ col-count] (size puzzle)] (->> solution (map identity) (sort) (map #(if (= (second %) true) \+ \-)) (partition col-count) (map vec)))) (defn- combine "Combines the given field with the prepared solution." [field prepared-sol] (let [map-fn (fn [a b] (if (= a \.) b a))] (emap map-fn field prepared-sol))) (defn solve-and-assoc "Solve and bind in field of the puzzle" [puzzle] (let [psol (prepare-solution puzzle (solve puzzle)) fsol (combine (:field puzzle) psol)] (assoc puzzle :field fsol))) ;; Pretty Printer, good for puzzle with up to 10 rows and columns (defn- print-cell [cell] (case cell 1 \u2197 2 \u2192 3 \u2198 4 \u2193 5 \u2199 6 \u2190 7 \u2196 8 \u2191 \- \u25cb \+ \u25cf \. )) (defn pretty-print "Pretty-printing jabeh." [puzzle] (let [[row-count col-count] (size puzzle)] (print "*** Jabeh\n") (print (str " | " (str/join " " (:col-holes puzzle)) "\n")) (print (str "--+" (str/join (repeat col-count "--")) "\n")) (doseq [row (range row-count) col (range col-count)] (if (zero? col) (print (str (nth (:row-holes puzzle) row) " | "))) (print (str (print-cell (get-in (:field puzzle) [row col])) " ")) (if (= (dec col-count) col) (print "\n"))))) (defn print-puzzle-and-solution [puzzle] (pretty-print puzzle) (pretty-print (solve-and-assoc puzzle))) ;; Examples (comment (defn test-puzzle [file] (print-puzzle-and-solution (load-file (str "resources/jabeh/" file ".edn")))) (test-puzzle "jabeh01") (test-puzzle "jabeh02") (test-puzzle "jabeh03") (test-puzzle "jabeh04") (test-puzzle "jabeh05") (test-puzzle "jabeh06") (test-puzzle "jabeh07") ;; Benchmarks ;; load, run, print (defn bench [puzzles] (time (do (run! test-puzzle puzzles) :done))) (dotimes [_ 10] (bench ["jabeh01" "jabeh02" "jabeh03" "jabeh04" "jabeh05" "jabeh06"])) ; => 260 msec )
true
; lwb Logic WorkBench -- Propositional Logic SAT ; Examples: jabeh ; Copyright (c) 2016 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.prop.examples.jabeh (:require [lwb.prop :refer :all]) (:require [lwb.prop.cardinality :refer (min-kof kof)]) (:require [lwb.prop.sat :refer (sat)]) (:require [clojure.core.matrix :refer (emap)]) (:require [clojure.string :as str])) (def u "A symbol for an unknown state of a cell in the puzzle" \.) ;; The puzzle is given by a map with the keys :col-holes, ;; :row-holes and :field ;; e.g. (comment (def p {:col-holes [2 2 1 2 1 1 1 2] :row-holes [1 1 2 1 2 2 2 1] :field [[u u u 2 u u u u] [u u u u 6 u u u] [u u u u u 5 u 7] [u u 4 u 7 u u u] [1 u u 4 6 8 u u] [u u u u u u u u] [u u u 1 u u 7 u] [u u u u u u u u]]}) ) ;; :col-holes is a vector of the number of holes in the columns ;; :row-holes is a vector of the number of holes in te rows ;; :field is the field with ;; u = an unknown state of the cell ;; a number = an arrow, decoding the direction at cell x as follows ;; 7 8 1 ;; 6 x 2 ;; 5 4 3 ;; The encoding of the puzzle in the propositional logic: ;; We represent each cell as an atomic proposition build from the ;; index of the cell by make-sym. ;; If the atom is true, there is a hole, false otherwise ;; The constraints are ;; - the number of true atoms in a row is given by the corresponding number in :row-holes, ;; - the number of true atoms in a columns is given by the corresponding number in :col-holes, ;; - the atom for a cell with an arrow is false, and ;; - in the direction of the arrow one of the corresponding atoms has to be true ;; Symbols representing the proposition that a cell ;; is a "hole" or not. ;; The symbols are good for puzzle with up to 100 rows ;; and 100 columns (defn- make-sym "Makes a symbol from an index [row, col]." [[row col]] (symbol (format "c%02d%02d" row col))) (defn- size "Size [row-count col-count] of a (well-formed) puzzle." [puzzle] [(count (:row-holes puzzle)) (count (:col-holes puzzle))]) ;; Generating a seq of clauses for the constraints on the rows (defn rows-cl "Seq of clauses for the rows: each row has exactly the number of holes given by the corresponding number in :row-holes." [puzzle] (let [[row-count col-count] (size puzzle) syms (map make-sym (for [r (range row-count) c (range col-count)] [r c])) sym-rows (partition col-count syms)] (mapcat kof (:row-holes puzzle) sym-rows))) ;; Generating a seq of clauses for the constraints on the columns (defn cols-cl "Seq of clauses for the columns: each column has exactly the number of holes given by the corresponding number in :col-holes." [puzzle] (let [[row-count col-count] (size puzzle) syms (map make-sym (for [c (range col-count) r (range row-count)] [r c])) sym-rows (partition row-count syms)] (mapcat kof (:col-holes puzzle) sym-rows))) ;; Generating a seq of clauses for the constraints given by arrows (defn- next-cell "Next cell at [r c] in the given direction." [puzzle direction [r c]] (let [[row-count col-count] (size puzzle) [r2 c2] (case direction 1 [(dec r) (inc c)] 2 [r (inc c)] 3 [(inc r) (inc c)] 4 [(inc r) c] 5 [(inc r) (dec c)] 6 [r (dec c)] 7 [(dec r) (dec c)] 8 [(dec r) c])] (cond (neg? r2) nil (neg? c2) nil (>= r2 row-count) nil (>= c2 col-count) nil :else [r2 c2]))) (defn- next-cells "All cells at [r c] in the given direction." [puzzle direction [r c]] (vec (drop 1 (take-while some? (iterate (partial next-cell puzzle direction) [r c]))))) (defn- arrow-cl "Seq of clause for the fact that there is at least one hole in the cells in the direction of the arrow at [r c]." [puzzle direction [r c]] (min-kof 1 (map make-sym (next-cells puzzle direction [r c])))) (defn- arrow-cell? "Checks whether [[_ _] value] is a cell with a value that's an arrow." [[[_ _] value]] (not= value u)) (defn- neg-sym "Clause that negates sym." [sym] (list (list 'or (list 'not sym)))) (defn- arrow-cl-complete "Seq of clauses for the arrow-cell itself and for the cells in its direction." [puzzle [[row col] value]] (let [sym (make-sym [row col]) neg (neg-sym sym)] (concat neg (arrow-cl puzzle value [row col])))) (defn arrows-cl "Seq of clauses for all arrows, i.e. a clause of a single literal, expressing that the cell with the arrow itself is not a hole together with the clause that there is a hole in the direction of the arrow." [puzzle] (let [[row-count col-count] (size puzzle) field (:field puzzle) cells (for [r (range row-count) c (range col-count)] [[r c] (get-in field [r c])]) arrow-cells (filter arrow-cell? cells)] (mapcat (partial arrow-cl-complete puzzle) arrow-cells))) ;; Combining a puzzle and the rules to a proposition (defn jabeh-prop "Generates the proposition for the given puzzle." [puzzle] (apply list 'and (concat (rows-cl puzzle) (cols-cl puzzle) (arrows-cl puzzle)))) (defn solve "Solve Jabeh puzzle." [puzzle] (-> puzzle (jabeh-prop) (sat))) ;; Constructing the solution with + for holes and - else (defn- prepare-solution "Prepares the solution from the sat solver to a matrix with + (a hole) and - (not a hole)." [puzzle solution] (let [[_ col-count] (size puzzle)] (->> solution (map identity) (sort) (map #(if (= (second %) true) \+ \-)) (partition col-count) (map vec)))) (defn- combine "Combines the given field with the prepared solution." [field prepared-sol] (let [map-fn (fn [a b] (if (= a \.) b a))] (emap map-fn field prepared-sol))) (defn solve-and-assoc "Solve and bind in field of the puzzle" [puzzle] (let [psol (prepare-solution puzzle (solve puzzle)) fsol (combine (:field puzzle) psol)] (assoc puzzle :field fsol))) ;; Pretty Printer, good for puzzle with up to 10 rows and columns (defn- print-cell [cell] (case cell 1 \u2197 2 \u2192 3 \u2198 4 \u2193 5 \u2199 6 \u2190 7 \u2196 8 \u2191 \- \u25cb \+ \u25cf \. )) (defn pretty-print "Pretty-printing jabeh." [puzzle] (let [[row-count col-count] (size puzzle)] (print "*** Jabeh\n") (print (str " | " (str/join " " (:col-holes puzzle)) "\n")) (print (str "--+" (str/join (repeat col-count "--")) "\n")) (doseq [row (range row-count) col (range col-count)] (if (zero? col) (print (str (nth (:row-holes puzzle) row) " | "))) (print (str (print-cell (get-in (:field puzzle) [row col])) " ")) (if (= (dec col-count) col) (print "\n"))))) (defn print-puzzle-and-solution [puzzle] (pretty-print puzzle) (pretty-print (solve-and-assoc puzzle))) ;; Examples (comment (defn test-puzzle [file] (print-puzzle-and-solution (load-file (str "resources/jabeh/" file ".edn")))) (test-puzzle "jabeh01") (test-puzzle "jabeh02") (test-puzzle "jabeh03") (test-puzzle "jabeh04") (test-puzzle "jabeh05") (test-puzzle "jabeh06") (test-puzzle "jabeh07") ;; Benchmarks ;; load, run, print (defn bench [puzzles] (time (do (run! test-puzzle puzzles) :done))) (dotimes [_ 10] (bench ["jabeh01" "jabeh02" "jabeh03" "jabeh04" "jabeh05" "jabeh06"])) ; => 260 msec )
[ { "context": ";;;; Copyright 2015 Peter Stephens. All Rights Reserved.\r\n;;;;\r\n;;;; Licensed unde", "end": 36, "score": 0.9997657537460327, "start": 22, "tag": "NAME", "value": "Peter Stephens" } ]
src/common/normalizer/filesystem.cljs
pstephens/kingjames.bible
23
;;;; Copyright 2015 Peter Stephens. All Rights Reserved. ;;;; ;;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;;; you may not use this file except in compliance with the License. ;;;; You may obtain a copy of the License at ;;;; ;;;; http://www.apache.org/licenses/LICENSE-2.0 ;;;; ;;;; Unless required by applicable law or agreed to in writing, software ;;;; distributed under the License is distributed on an "AS IS" BASIS, ;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the License for the specific language governing permissions and ;;;; limitations under the License. (ns common.normalizer.filesystem (:require [cljs.nodejs :as nodejs])) (def node-fs (nodejs/require "fs")) (defprotocol FileSystem (read-text [fs path]) (write-text [fs path text])) (deftype NodeFs [] FileSystem (read-text [fs path] (.readFileSync node-fs path (js-obj "encoding" "utf8"))) (write-text [fs path text] (.writeFileSync node-fs path text (js-obj "encoding" "utf8"))))
51152
;;;; Copyright 2015 <NAME>. All Rights Reserved. ;;;; ;;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;;; you may not use this file except in compliance with the License. ;;;; You may obtain a copy of the License at ;;;; ;;;; http://www.apache.org/licenses/LICENSE-2.0 ;;;; ;;;; Unless required by applicable law or agreed to in writing, software ;;;; distributed under the License is distributed on an "AS IS" BASIS, ;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the License for the specific language governing permissions and ;;;; limitations under the License. (ns common.normalizer.filesystem (:require [cljs.nodejs :as nodejs])) (def node-fs (nodejs/require "fs")) (defprotocol FileSystem (read-text [fs path]) (write-text [fs path text])) (deftype NodeFs [] FileSystem (read-text [fs path] (.readFileSync node-fs path (js-obj "encoding" "utf8"))) (write-text [fs path text] (.writeFileSync node-fs path text (js-obj "encoding" "utf8"))))
true
;;;; Copyright 2015 PI:NAME:<NAME>END_PI. All Rights Reserved. ;;;; ;;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;;; you may not use this file except in compliance with the License. ;;;; You may obtain a copy of the License at ;;;; ;;;; http://www.apache.org/licenses/LICENSE-2.0 ;;;; ;;;; Unless required by applicable law or agreed to in writing, software ;;;; distributed under the License is distributed on an "AS IS" BASIS, ;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the License for the specific language governing permissions and ;;;; limitations under the License. (ns common.normalizer.filesystem (:require [cljs.nodejs :as nodejs])) (def node-fs (nodejs/require "fs")) (defprotocol FileSystem (read-text [fs path]) (write-text [fs path text])) (deftype NodeFs [] FileSystem (read-text [fs path] (.readFileSync node-fs path (js-obj "encoding" "utf8"))) (write-text [fs path text] (.writeFileSync node-fs path text (js-obj "encoding" "utf8"))))
[ { "context": "ckupSource\"\n :encrypted-passwd \"WIwn6jIUt2Rbc\"}}))\n\n(def desktop-minimal-settings\n #{:install-", "end": 4214, "score": 0.9981997609138489, "start": 4201, "tag": "PASSWORD", "value": "WIwn6jIUt2Rbc" }, { "context": "kturama {:app-download-url \"https://bitbucket.org/fakturamadev/fakturama-2/downloads/Fakturama_linux_x64_2.0.3.d", "end": 6029, "score": 0.9996331334114075, "start": 6017, "tag": "USERNAME", "value": "fakturamadev" }, { "context": "aws)\n {:tightvnc-server {:user-password \"test\"}\n :settings\n #{:install-xfce", "end": 6607, "score": 0.9994993209838867, "start": 6603, "tag": "PASSWORD", "value": "test" } ]
main/src/dda/pallet/dda_managed_vm/domain.clj
DomainDrivenArchitecture/dda-managed-vm
5
; 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-vm.domain (:require [clojure.set :as set] [schema.core :as s] [dda.config.commons.map-utils :as mu] [dda.config.commons.user-home :as user-home] [dda.pallet.commons.secret :as secret] [dda.pallet.dda-managed-vm.domain.user :as user] [dda.pallet.dda-managed-vm.domain.git :as git] [dda.pallet.dda-managed-vm.domain.serverspec :as serverspec] [dda.pallet.dda-managed-vm.domain.bookmark :as bookmark] [dda.pallet.dda-managed-vm.infra :as infra])) (def DdaVmUser {:user {:name s/Str :password secret/Secret (s/optional-key :email) s/Str (s/optional-key :git-credentials) git/GitCredentials (s/optional-key :git-signing-key) s/Str (s/optional-key :ssh) {:ssh-public-key secret/Secret :ssh-private-key secret/Secret} (s/optional-key :gpg) {:gpg-public-key secret/Secret :gpg-private-key secret/Secret :gpg-passphrase secret/Secret} (s/optional-key :desktop-wiki) git/Repositories (s/optional-key :credential-store) git/Repositories}}) (def DdaVmUserResolved (secret/create-resolved-schema DdaVmUser)) (def Bookmarks infra/Bookmarks) (def DdaVmDomainBookmarks {(s/optional-key :bookmarks) infra/Bookmarks}) (def DdaVmTargetType {:target-type (s/enum :virtualbox :remote-aws :plain)}) (def DdaVmDomainConfig "The convention configuration for managed vms crate." (merge DdaVmUser DdaVmDomainBookmarks DdaVmTargetType {:usage-type (s/enum :desktop-minimal :desktop-ide :desktop-base :desktop-office)})) (def DdaVmDomainResolvedConfig "The convention configuration for managed vms crate." (secret/create-resolved-schema DdaVmDomainConfig)) (def InfraResult {infra/facility infra/DdaVmConfig}) (s/defn ^:always-validate user-config [domain-config :- DdaVmDomainResolvedConfig] (let [{:keys [user]} domain-config] {(keyword (:name user)) (merge {:clear-password (:password user)} (user/authorized-keys user) (user/ssh-personal-key user) (user/gpg user))})) (s/defn ^:always-validate vm-git-config "Git repos for VM" [domain-config :- DdaVmDomainResolvedConfig] (let [{:keys [user]} domain-config {:keys [name email git-credentials git-signing-key desktop-wiki credential-store]} user] (git/vm-git-config name email git-credentials git-signing-key desktop-wiki credential-store))) (s/defn ^:always-validate vm-serverspec-config "serverspec for VM" [domain-config :- DdaVmDomainResolvedConfig] (serverspec/serverspec-prerequisits)) (s/defn ^:always-validate vm-backup-config "Managed vm crate default configuration" [domain-config :- DdaVmDomainResolvedConfig] (let [{:keys [user]} domain-config {:keys [name]} user user-home (user-home/user-home-dir name)] {:backup-name "dda-managed-vm" :script-path "/usr/local/lib/dda-backup/" :gens-stored-on-source-system 1 :elements [{:type :file-compressed :name "user-home" :backup-path [(str user-home ".ssh") (str user-home ".gnupg") (str user-home ".mozilla") (str user-home ".thunderbird")]}] :backup-user {:name "dataBackupSource" :encrypted-passwd "WIwn6jIUt2Rbc"}})) (def desktop-minimal-settings #{:install-os-analysis :install-bash-utils :remove-xubuntu-unused :remove-ubuntu-unused}) (def desktop-base-settings (set/union desktop-minimal-settings #{:install-open-jdk-11 :install-git :install-zip-utils :install-timesync :install-openvpn :install-openconnect :install-vpnc :install-lightning})) (def desktop-office-settings (set/union desktop-base-settings #{:install-libreoffice :install-spellchecking-de :install-diagram :install-keymgm :install-chromium :install-inkscape :install-telegram :install-remina :install-enigmail :install-redshift ;:install-pdf-chain })) (def desktop-ide-settings (set/union desktop-office-settings #{:install-open-jdk-8})) (s/defn ^:always-validate infra-configuration :- InfraResult "Managed vm crate default configuration" [domain-config :- DdaVmDomainResolvedConfig] (let [{:keys [user target-type usage-type]} domain-config {:keys [name]} user] {infra/facility (mu/deep-merge {:vm-user (keyword name) :bookmarks (bookmark/bookmarks domain-config)} (when (contains? user :desktop-wiki) {:settings #{:install-desktop-wiki :install-diagram}}) (when (contains? user :credential-store) {:credential-store (:credential-store user) :settings #{:install-gopass}}) (cond (= usage-type :desktop-minimal) {:settings desktop-minimal-settings} (= usage-type :desktop-base) {:settings desktop-base-settings} (= usage-type :desktop-ide) {:settings desktop-ide-settings} (= usage-type :desktop-office) {:fakturama {:app-download-url "https://bitbucket.org/fakturamadev/fakturama-2/downloads/Fakturama_linux_x64_2.0.3.deb" :doc-download-url "https://files.fakturama.info/release/v2.0.3/Handbuch-Fakturama_2.0.3.pdf"} :settings ;(set/union desktop-office-settings}) ;#{:install-audio})}) (cond (= target-type :virtualbox) {:settings #{:install-virtualbox-guest :remove-power-management :configure-no-swappiness}} (= target-type :remote-aws) {:tightvnc-server {:user-password "test"} :settings #{:install-xfce-desktop :configure-no-swappiness}} (= target-type :plain) {:settings #{}}))}))
50779
; 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-vm.domain (:require [clojure.set :as set] [schema.core :as s] [dda.config.commons.map-utils :as mu] [dda.config.commons.user-home :as user-home] [dda.pallet.commons.secret :as secret] [dda.pallet.dda-managed-vm.domain.user :as user] [dda.pallet.dda-managed-vm.domain.git :as git] [dda.pallet.dda-managed-vm.domain.serverspec :as serverspec] [dda.pallet.dda-managed-vm.domain.bookmark :as bookmark] [dda.pallet.dda-managed-vm.infra :as infra])) (def DdaVmUser {:user {:name s/Str :password secret/Secret (s/optional-key :email) s/Str (s/optional-key :git-credentials) git/GitCredentials (s/optional-key :git-signing-key) s/Str (s/optional-key :ssh) {:ssh-public-key secret/Secret :ssh-private-key secret/Secret} (s/optional-key :gpg) {:gpg-public-key secret/Secret :gpg-private-key secret/Secret :gpg-passphrase secret/Secret} (s/optional-key :desktop-wiki) git/Repositories (s/optional-key :credential-store) git/Repositories}}) (def DdaVmUserResolved (secret/create-resolved-schema DdaVmUser)) (def Bookmarks infra/Bookmarks) (def DdaVmDomainBookmarks {(s/optional-key :bookmarks) infra/Bookmarks}) (def DdaVmTargetType {:target-type (s/enum :virtualbox :remote-aws :plain)}) (def DdaVmDomainConfig "The convention configuration for managed vms crate." (merge DdaVmUser DdaVmDomainBookmarks DdaVmTargetType {:usage-type (s/enum :desktop-minimal :desktop-ide :desktop-base :desktop-office)})) (def DdaVmDomainResolvedConfig "The convention configuration for managed vms crate." (secret/create-resolved-schema DdaVmDomainConfig)) (def InfraResult {infra/facility infra/DdaVmConfig}) (s/defn ^:always-validate user-config [domain-config :- DdaVmDomainResolvedConfig] (let [{:keys [user]} domain-config] {(keyword (:name user)) (merge {:clear-password (:password user)} (user/authorized-keys user) (user/ssh-personal-key user) (user/gpg user))})) (s/defn ^:always-validate vm-git-config "Git repos for VM" [domain-config :- DdaVmDomainResolvedConfig] (let [{:keys [user]} domain-config {:keys [name email git-credentials git-signing-key desktop-wiki credential-store]} user] (git/vm-git-config name email git-credentials git-signing-key desktop-wiki credential-store))) (s/defn ^:always-validate vm-serverspec-config "serverspec for VM" [domain-config :- DdaVmDomainResolvedConfig] (serverspec/serverspec-prerequisits)) (s/defn ^:always-validate vm-backup-config "Managed vm crate default configuration" [domain-config :- DdaVmDomainResolvedConfig] (let [{:keys [user]} domain-config {:keys [name]} user user-home (user-home/user-home-dir name)] {:backup-name "dda-managed-vm" :script-path "/usr/local/lib/dda-backup/" :gens-stored-on-source-system 1 :elements [{:type :file-compressed :name "user-home" :backup-path [(str user-home ".ssh") (str user-home ".gnupg") (str user-home ".mozilla") (str user-home ".thunderbird")]}] :backup-user {:name "dataBackupSource" :encrypted-passwd "<PASSWORD>"}})) (def desktop-minimal-settings #{:install-os-analysis :install-bash-utils :remove-xubuntu-unused :remove-ubuntu-unused}) (def desktop-base-settings (set/union desktop-minimal-settings #{:install-open-jdk-11 :install-git :install-zip-utils :install-timesync :install-openvpn :install-openconnect :install-vpnc :install-lightning})) (def desktop-office-settings (set/union desktop-base-settings #{:install-libreoffice :install-spellchecking-de :install-diagram :install-keymgm :install-chromium :install-inkscape :install-telegram :install-remina :install-enigmail :install-redshift ;:install-pdf-chain })) (def desktop-ide-settings (set/union desktop-office-settings #{:install-open-jdk-8})) (s/defn ^:always-validate infra-configuration :- InfraResult "Managed vm crate default configuration" [domain-config :- DdaVmDomainResolvedConfig] (let [{:keys [user target-type usage-type]} domain-config {:keys [name]} user] {infra/facility (mu/deep-merge {:vm-user (keyword name) :bookmarks (bookmark/bookmarks domain-config)} (when (contains? user :desktop-wiki) {:settings #{:install-desktop-wiki :install-diagram}}) (when (contains? user :credential-store) {:credential-store (:credential-store user) :settings #{:install-gopass}}) (cond (= usage-type :desktop-minimal) {:settings desktop-minimal-settings} (= usage-type :desktop-base) {:settings desktop-base-settings} (= usage-type :desktop-ide) {:settings desktop-ide-settings} (= usage-type :desktop-office) {:fakturama {:app-download-url "https://bitbucket.org/fakturamadev/fakturama-2/downloads/Fakturama_linux_x64_2.0.3.deb" :doc-download-url "https://files.fakturama.info/release/v2.0.3/Handbuch-Fakturama_2.0.3.pdf"} :settings ;(set/union desktop-office-settings}) ;#{:install-audio})}) (cond (= target-type :virtualbox) {:settings #{:install-virtualbox-guest :remove-power-management :configure-no-swappiness}} (= target-type :remote-aws) {:tightvnc-server {:user-password "<PASSWORD>"} :settings #{:install-xfce-desktop :configure-no-swappiness}} (= target-type :plain) {:settings #{}}))}))
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-vm.domain (:require [clojure.set :as set] [schema.core :as s] [dda.config.commons.map-utils :as mu] [dda.config.commons.user-home :as user-home] [dda.pallet.commons.secret :as secret] [dda.pallet.dda-managed-vm.domain.user :as user] [dda.pallet.dda-managed-vm.domain.git :as git] [dda.pallet.dda-managed-vm.domain.serverspec :as serverspec] [dda.pallet.dda-managed-vm.domain.bookmark :as bookmark] [dda.pallet.dda-managed-vm.infra :as infra])) (def DdaVmUser {:user {:name s/Str :password secret/Secret (s/optional-key :email) s/Str (s/optional-key :git-credentials) git/GitCredentials (s/optional-key :git-signing-key) s/Str (s/optional-key :ssh) {:ssh-public-key secret/Secret :ssh-private-key secret/Secret} (s/optional-key :gpg) {:gpg-public-key secret/Secret :gpg-private-key secret/Secret :gpg-passphrase secret/Secret} (s/optional-key :desktop-wiki) git/Repositories (s/optional-key :credential-store) git/Repositories}}) (def DdaVmUserResolved (secret/create-resolved-schema DdaVmUser)) (def Bookmarks infra/Bookmarks) (def DdaVmDomainBookmarks {(s/optional-key :bookmarks) infra/Bookmarks}) (def DdaVmTargetType {:target-type (s/enum :virtualbox :remote-aws :plain)}) (def DdaVmDomainConfig "The convention configuration for managed vms crate." (merge DdaVmUser DdaVmDomainBookmarks DdaVmTargetType {:usage-type (s/enum :desktop-minimal :desktop-ide :desktop-base :desktop-office)})) (def DdaVmDomainResolvedConfig "The convention configuration for managed vms crate." (secret/create-resolved-schema DdaVmDomainConfig)) (def InfraResult {infra/facility infra/DdaVmConfig}) (s/defn ^:always-validate user-config [domain-config :- DdaVmDomainResolvedConfig] (let [{:keys [user]} domain-config] {(keyword (:name user)) (merge {:clear-password (:password user)} (user/authorized-keys user) (user/ssh-personal-key user) (user/gpg user))})) (s/defn ^:always-validate vm-git-config "Git repos for VM" [domain-config :- DdaVmDomainResolvedConfig] (let [{:keys [user]} domain-config {:keys [name email git-credentials git-signing-key desktop-wiki credential-store]} user] (git/vm-git-config name email git-credentials git-signing-key desktop-wiki credential-store))) (s/defn ^:always-validate vm-serverspec-config "serverspec for VM" [domain-config :- DdaVmDomainResolvedConfig] (serverspec/serverspec-prerequisits)) (s/defn ^:always-validate vm-backup-config "Managed vm crate default configuration" [domain-config :- DdaVmDomainResolvedConfig] (let [{:keys [user]} domain-config {:keys [name]} user user-home (user-home/user-home-dir name)] {:backup-name "dda-managed-vm" :script-path "/usr/local/lib/dda-backup/" :gens-stored-on-source-system 1 :elements [{:type :file-compressed :name "user-home" :backup-path [(str user-home ".ssh") (str user-home ".gnupg") (str user-home ".mozilla") (str user-home ".thunderbird")]}] :backup-user {:name "dataBackupSource" :encrypted-passwd "PI:PASSWORD:<PASSWORD>END_PI"}})) (def desktop-minimal-settings #{:install-os-analysis :install-bash-utils :remove-xubuntu-unused :remove-ubuntu-unused}) (def desktop-base-settings (set/union desktop-minimal-settings #{:install-open-jdk-11 :install-git :install-zip-utils :install-timesync :install-openvpn :install-openconnect :install-vpnc :install-lightning})) (def desktop-office-settings (set/union desktop-base-settings #{:install-libreoffice :install-spellchecking-de :install-diagram :install-keymgm :install-chromium :install-inkscape :install-telegram :install-remina :install-enigmail :install-redshift ;:install-pdf-chain })) (def desktop-ide-settings (set/union desktop-office-settings #{:install-open-jdk-8})) (s/defn ^:always-validate infra-configuration :- InfraResult "Managed vm crate default configuration" [domain-config :- DdaVmDomainResolvedConfig] (let [{:keys [user target-type usage-type]} domain-config {:keys [name]} user] {infra/facility (mu/deep-merge {:vm-user (keyword name) :bookmarks (bookmark/bookmarks domain-config)} (when (contains? user :desktop-wiki) {:settings #{:install-desktop-wiki :install-diagram}}) (when (contains? user :credential-store) {:credential-store (:credential-store user) :settings #{:install-gopass}}) (cond (= usage-type :desktop-minimal) {:settings desktop-minimal-settings} (= usage-type :desktop-base) {:settings desktop-base-settings} (= usage-type :desktop-ide) {:settings desktop-ide-settings} (= usage-type :desktop-office) {:fakturama {:app-download-url "https://bitbucket.org/fakturamadev/fakturama-2/downloads/Fakturama_linux_x64_2.0.3.deb" :doc-download-url "https://files.fakturama.info/release/v2.0.3/Handbuch-Fakturama_2.0.3.pdf"} :settings ;(set/union desktop-office-settings}) ;#{:install-audio})}) (cond (= target-type :virtualbox) {:settings #{:install-virtualbox-guest :remove-power-management :configure-no-swappiness}} (= target-type :remote-aws) {:tightvnc-server {:user-password "PI:PASSWORD:<PASSWORD>END_PI"} :settings #{:install-xfce-desktop :configure-no-swappiness}} (= target-type :plain) {:settings #{}}))}))
[ { "context": " :uname uname\n :pwd pwd}}}))\n(rf/reg-event-fx\n :join-org-signup-return\n (", "end": 2026, "score": 0.9985630512237549, "start": 2023, "tag": "PASSWORD", "value": "pwd" }, { "context": "{:error (= @bad-input& :uname)}\n [:label \"Full Name\"\n [:> ui/Input {:class \"borderless\"", "end": 5769, "score": 0.7093951106071472, "start": 5765, "tag": "NAME", "value": "Full" }, { "context": " :uname @uname\n ", "end": 7555, "score": 0.6348610520362854, "start": 7550, "tag": "USERNAME", "value": "uname" }, { "context": " :pwd @pwd\n ", "end": 7614, "score": 0.8759716153144836, "start": 7610, "tag": "PASSWORD", "value": "@pwd" } ]
src/cljs/app/vetd_app/common/pages/join_org_signup.cljs
jaydeesimon/vetd-app
98
(ns vetd-app.common.pages.join-org-signup (:require [vetd-app.ui :as ui] [vetd-app.util :as util] [reagent.core :as r] [re-frame.core :as rf] [clojure.string :as s])) ;; Events (rf/reg-event-fx :nav-join-org-signup (fn [_ [_ link-key]] {:nav {:path (str "/signup-by-invite/" link-key)} :analytics/track {:event "Signup Start" :props {:category "Accounts" :label "By Invite"}}})) (rf/reg-event-fx :route-join-org-signup (fn [{:keys [db]} [_ link-key]] {:db (assoc db :page :join-org-signup :page-params {:link-key link-key})})) (rf/reg-event-fx :join-org-signup.submit (fn [{:keys [db]} [_ {:keys [need-email? email uname pwd cpwd terms-agree] :as account} link-key]] (let [[bad-input message] ; TODO use validated-dispatch-fx (cond (not (re-matches #".+\s.+" uname)) [:uname "Please enter your full name (first & last)."] (and need-email? (not (util/valid-email-address? email))) [:email "Please enter a valid email address."] (< (count pwd) 8) [:pwd "Password must be at least 8 characters."] (not= pwd cpwd) [:cpwd "Password and Confirm Password must match."] (not terms-agree) [:terms-agree "You must agree to the Terms of Use in order to sign up."] :else nil)] (if bad-input {:db (assoc-in db [:page-params :bad-input] bad-input) :toast {:type "error" :title "Error" :message message}} {:dispatch [:join-org-signup account link-key]})))) (rf/reg-event-fx :join-org-signup (fn [{:keys [db]} [_ {:keys [email uname pwd] :as account} link-key]] {:ws-send {:ws (:ws db) :payload {:cmd :do-link-action :return {:handler :join-org-signup-return} :link-key link-key :email email :uname uname :pwd pwd}}})) (rf/reg-event-fx :join-org-signup-return (fn [{:keys [db]} [_ {:keys [cmd output-data] :as results}]] (if (= cmd :invite-user-to-org) (if (:user-creation-initiated-from-reusable-link? output-data) (if-not (:email-used? output-data) {:dispatch [:nav-login] :toast {:type "success" :title "Please check your email" :message (str "We've sent an email to " (:email output-data) " with a link to activate your account.")}} {:db (assoc-in db [:page-params :bad-input] :email) :toast {:type "error" :title "Error" :message "There is already an account with that email address."}}) {:toast {:type "success" ;; this is a vague "Joined!" because it could ;; be an org or a community :title "Joined!" :message (str "You accepted an invitation to join " (:org-name output-data))} :local-store {:session-token (:session-token output-data)} :dispatch-later [{:ms 100 :dispatch [:ws-get-session-user]} {:ms 1000 :dispatch [:nav-home true]} {:ms 1500 :dispatch [:do-fx {:analytics/track {:event "FRONTEND Signup Complete" :props {:category "Accounts" :label "By Explicit Invite"}}}]}]}) {:toast {:type "error" :title "Sorry, that invitation is invalid or has expired."} :dispatch [:nav-home]}))) ;; Subscriptions (rf/reg-sub :link-key :<- [:page-params] (fn [{:keys [link-key]}] link-key)) ;; this is set by the initial link read for :invite-user-to-org (rf/reg-sub :signup-by-link-org-name (fn [{:keys [signup-by-link-org-name]}] signup-by-link-org-name)) (rf/reg-sub :signup-by-link-need-email? (fn [{:keys [signup-by-link-need-email?]}] signup-by-link-need-email?)) ;; Components (defn c-page [] (let [email (r/atom "") ;; email is only requested if it's from a org invite reusable link (as opposed to email) uname (r/atom "") pwd (r/atom "") cpwd (r/atom "") bad-cpwd (r/atom false) terms-agree (r/atom false) bad-input& (rf/subscribe [:bad-input]) org-name& (rf/subscribe [:signup-by-link-org-name]) need-email?& (rf/subscribe [:signup-by-link-need-email?]) link-key& (rf/subscribe [:link-key])] (fn [] [:div.centerpiece [:a {:on-click #(rf/dispatch [:nav-login])} [:img.logo {:src "https://s3.amazonaws.com/vetd-logos/vetd.svg"}]] [:> ui/Header {:as "h2" :class "blue"} ;; BUG @org-name& will be blank if the page is refreshed, because the link read is invalid ;; TODO ;; show this if simply joining an org "Join " @org-name& " on Vetd" ;; show this if invite originated from inviting a non-existent org ;; to a community ;; "Join COMMUNITY on Vetd" ] [:> ui/Form {:style {:margin-top 25}} (when @need-email?& [:> ui/FormField {:error (= @bad-input& :email)} [:label "Work Email Address" [:> ui/Input {:class "borderless" :type "email" :spellCheck false :auto-focus true :on-invalid #(.preventDefault %) ; no type=email error message (we'll show our own) :on-change (fn [_ this] (reset! email (.-value this)))}]]]) [:> ui/FormField {:error (= @bad-input& :uname)} [:label "Full Name" [:> ui/Input {:class "borderless" :spellCheck false :auto-focus (not @need-email?&) :onChange (fn [_ this] (reset! uname (.-value this)))}]]] [:> ui/FormField {:error (= @bad-input& :pwd)} [:label "Password" [:> ui/Input {:class "borderless" :type "password" :onChange (fn [_ this] (reset! pwd (.-value this)))}]]] [:> ui/FormField {:error (or @bad-cpwd (= @bad-input& :cpwd))} [:label "Confirm Password"] [:> ui/Input {:class "borderless" :type "password" :on-blur #(when-not (= @cpwd @pwd) (reset! bad-cpwd true)) :on-change (fn [_ this] (reset! cpwd (.-value this)) (when (= @cpwd @pwd) (reset! bad-cpwd false)))}]] [:> ui/FormField {:error (= @bad-input& :terms-agree) :style {:margin "25px 0 20px 0"}} [:> ui/Checkbox {:label "I agree to the Terms Of Use" :onChange (fn [_ this] (reset! terms-agree (.-checked this)))}] [:a {:href "https://vetd.com/terms-of-use" :target "_blank"} " (read)"]] [:> ui/Button {:color "blue" :fluid true :on-click #(rf/dispatch [:join-org-signup.submit {:need-email? @need-email?& :email @email :uname @uname :pwd @pwd :cpwd @cpwd :terms-agree @terms-agree} @link-key&])} "Sign Up"]]])))
117172
(ns vetd-app.common.pages.join-org-signup (:require [vetd-app.ui :as ui] [vetd-app.util :as util] [reagent.core :as r] [re-frame.core :as rf] [clojure.string :as s])) ;; Events (rf/reg-event-fx :nav-join-org-signup (fn [_ [_ link-key]] {:nav {:path (str "/signup-by-invite/" link-key)} :analytics/track {:event "Signup Start" :props {:category "Accounts" :label "By Invite"}}})) (rf/reg-event-fx :route-join-org-signup (fn [{:keys [db]} [_ link-key]] {:db (assoc db :page :join-org-signup :page-params {:link-key link-key})})) (rf/reg-event-fx :join-org-signup.submit (fn [{:keys [db]} [_ {:keys [need-email? email uname pwd cpwd terms-agree] :as account} link-key]] (let [[bad-input message] ; TODO use validated-dispatch-fx (cond (not (re-matches #".+\s.+" uname)) [:uname "Please enter your full name (first & last)."] (and need-email? (not (util/valid-email-address? email))) [:email "Please enter a valid email address."] (< (count pwd) 8) [:pwd "Password must be at least 8 characters."] (not= pwd cpwd) [:cpwd "Password and Confirm Password must match."] (not terms-agree) [:terms-agree "You must agree to the Terms of Use in order to sign up."] :else nil)] (if bad-input {:db (assoc-in db [:page-params :bad-input] bad-input) :toast {:type "error" :title "Error" :message message}} {:dispatch [:join-org-signup account link-key]})))) (rf/reg-event-fx :join-org-signup (fn [{:keys [db]} [_ {:keys [email uname pwd] :as account} link-key]] {:ws-send {:ws (:ws db) :payload {:cmd :do-link-action :return {:handler :join-org-signup-return} :link-key link-key :email email :uname uname :pwd <PASSWORD>}}})) (rf/reg-event-fx :join-org-signup-return (fn [{:keys [db]} [_ {:keys [cmd output-data] :as results}]] (if (= cmd :invite-user-to-org) (if (:user-creation-initiated-from-reusable-link? output-data) (if-not (:email-used? output-data) {:dispatch [:nav-login] :toast {:type "success" :title "Please check your email" :message (str "We've sent an email to " (:email output-data) " with a link to activate your account.")}} {:db (assoc-in db [:page-params :bad-input] :email) :toast {:type "error" :title "Error" :message "There is already an account with that email address."}}) {:toast {:type "success" ;; this is a vague "Joined!" because it could ;; be an org or a community :title "Joined!" :message (str "You accepted an invitation to join " (:org-name output-data))} :local-store {:session-token (:session-token output-data)} :dispatch-later [{:ms 100 :dispatch [:ws-get-session-user]} {:ms 1000 :dispatch [:nav-home true]} {:ms 1500 :dispatch [:do-fx {:analytics/track {:event "FRONTEND Signup Complete" :props {:category "Accounts" :label "By Explicit Invite"}}}]}]}) {:toast {:type "error" :title "Sorry, that invitation is invalid or has expired."} :dispatch [:nav-home]}))) ;; Subscriptions (rf/reg-sub :link-key :<- [:page-params] (fn [{:keys [link-key]}] link-key)) ;; this is set by the initial link read for :invite-user-to-org (rf/reg-sub :signup-by-link-org-name (fn [{:keys [signup-by-link-org-name]}] signup-by-link-org-name)) (rf/reg-sub :signup-by-link-need-email? (fn [{:keys [signup-by-link-need-email?]}] signup-by-link-need-email?)) ;; Components (defn c-page [] (let [email (r/atom "") ;; email is only requested if it's from a org invite reusable link (as opposed to email) uname (r/atom "") pwd (r/atom "") cpwd (r/atom "") bad-cpwd (r/atom false) terms-agree (r/atom false) bad-input& (rf/subscribe [:bad-input]) org-name& (rf/subscribe [:signup-by-link-org-name]) need-email?& (rf/subscribe [:signup-by-link-need-email?]) link-key& (rf/subscribe [:link-key])] (fn [] [:div.centerpiece [:a {:on-click #(rf/dispatch [:nav-login])} [:img.logo {:src "https://s3.amazonaws.com/vetd-logos/vetd.svg"}]] [:> ui/Header {:as "h2" :class "blue"} ;; BUG @org-name& will be blank if the page is refreshed, because the link read is invalid ;; TODO ;; show this if simply joining an org "Join " @org-name& " on Vetd" ;; show this if invite originated from inviting a non-existent org ;; to a community ;; "Join COMMUNITY on Vetd" ] [:> ui/Form {:style {:margin-top 25}} (when @need-email?& [:> ui/FormField {:error (= @bad-input& :email)} [:label "Work Email Address" [:> ui/Input {:class "borderless" :type "email" :spellCheck false :auto-focus true :on-invalid #(.preventDefault %) ; no type=email error message (we'll show our own) :on-change (fn [_ this] (reset! email (.-value this)))}]]]) [:> ui/FormField {:error (= @bad-input& :uname)} [:label "<NAME> Name" [:> ui/Input {:class "borderless" :spellCheck false :auto-focus (not @need-email?&) :onChange (fn [_ this] (reset! uname (.-value this)))}]]] [:> ui/FormField {:error (= @bad-input& :pwd)} [:label "Password" [:> ui/Input {:class "borderless" :type "password" :onChange (fn [_ this] (reset! pwd (.-value this)))}]]] [:> ui/FormField {:error (or @bad-cpwd (= @bad-input& :cpwd))} [:label "Confirm Password"] [:> ui/Input {:class "borderless" :type "password" :on-blur #(when-not (= @cpwd @pwd) (reset! bad-cpwd true)) :on-change (fn [_ this] (reset! cpwd (.-value this)) (when (= @cpwd @pwd) (reset! bad-cpwd false)))}]] [:> ui/FormField {:error (= @bad-input& :terms-agree) :style {:margin "25px 0 20px 0"}} [:> ui/Checkbox {:label "I agree to the Terms Of Use" :onChange (fn [_ this] (reset! terms-agree (.-checked this)))}] [:a {:href "https://vetd.com/terms-of-use" :target "_blank"} " (read)"]] [:> ui/Button {:color "blue" :fluid true :on-click #(rf/dispatch [:join-org-signup.submit {:need-email? @need-email?& :email @email :uname @uname :pwd <PASSWORD> :cpwd @cpwd :terms-agree @terms-agree} @link-key&])} "Sign Up"]]])))
true
(ns vetd-app.common.pages.join-org-signup (:require [vetd-app.ui :as ui] [vetd-app.util :as util] [reagent.core :as r] [re-frame.core :as rf] [clojure.string :as s])) ;; Events (rf/reg-event-fx :nav-join-org-signup (fn [_ [_ link-key]] {:nav {:path (str "/signup-by-invite/" link-key)} :analytics/track {:event "Signup Start" :props {:category "Accounts" :label "By Invite"}}})) (rf/reg-event-fx :route-join-org-signup (fn [{:keys [db]} [_ link-key]] {:db (assoc db :page :join-org-signup :page-params {:link-key link-key})})) (rf/reg-event-fx :join-org-signup.submit (fn [{:keys [db]} [_ {:keys [need-email? email uname pwd cpwd terms-agree] :as account} link-key]] (let [[bad-input message] ; TODO use validated-dispatch-fx (cond (not (re-matches #".+\s.+" uname)) [:uname "Please enter your full name (first & last)."] (and need-email? (not (util/valid-email-address? email))) [:email "Please enter a valid email address."] (< (count pwd) 8) [:pwd "Password must be at least 8 characters."] (not= pwd cpwd) [:cpwd "Password and Confirm Password must match."] (not terms-agree) [:terms-agree "You must agree to the Terms of Use in order to sign up."] :else nil)] (if bad-input {:db (assoc-in db [:page-params :bad-input] bad-input) :toast {:type "error" :title "Error" :message message}} {:dispatch [:join-org-signup account link-key]})))) (rf/reg-event-fx :join-org-signup (fn [{:keys [db]} [_ {:keys [email uname pwd] :as account} link-key]] {:ws-send {:ws (:ws db) :payload {:cmd :do-link-action :return {:handler :join-org-signup-return} :link-key link-key :email email :uname uname :pwd PI:PASSWORD:<PASSWORD>END_PI}}})) (rf/reg-event-fx :join-org-signup-return (fn [{:keys [db]} [_ {:keys [cmd output-data] :as results}]] (if (= cmd :invite-user-to-org) (if (:user-creation-initiated-from-reusable-link? output-data) (if-not (:email-used? output-data) {:dispatch [:nav-login] :toast {:type "success" :title "Please check your email" :message (str "We've sent an email to " (:email output-data) " with a link to activate your account.")}} {:db (assoc-in db [:page-params :bad-input] :email) :toast {:type "error" :title "Error" :message "There is already an account with that email address."}}) {:toast {:type "success" ;; this is a vague "Joined!" because it could ;; be an org or a community :title "Joined!" :message (str "You accepted an invitation to join " (:org-name output-data))} :local-store {:session-token (:session-token output-data)} :dispatch-later [{:ms 100 :dispatch [:ws-get-session-user]} {:ms 1000 :dispatch [:nav-home true]} {:ms 1500 :dispatch [:do-fx {:analytics/track {:event "FRONTEND Signup Complete" :props {:category "Accounts" :label "By Explicit Invite"}}}]}]}) {:toast {:type "error" :title "Sorry, that invitation is invalid or has expired."} :dispatch [:nav-home]}))) ;; Subscriptions (rf/reg-sub :link-key :<- [:page-params] (fn [{:keys [link-key]}] link-key)) ;; this is set by the initial link read for :invite-user-to-org (rf/reg-sub :signup-by-link-org-name (fn [{:keys [signup-by-link-org-name]}] signup-by-link-org-name)) (rf/reg-sub :signup-by-link-need-email? (fn [{:keys [signup-by-link-need-email?]}] signup-by-link-need-email?)) ;; Components (defn c-page [] (let [email (r/atom "") ;; email is only requested if it's from a org invite reusable link (as opposed to email) uname (r/atom "") pwd (r/atom "") cpwd (r/atom "") bad-cpwd (r/atom false) terms-agree (r/atom false) bad-input& (rf/subscribe [:bad-input]) org-name& (rf/subscribe [:signup-by-link-org-name]) need-email?& (rf/subscribe [:signup-by-link-need-email?]) link-key& (rf/subscribe [:link-key])] (fn [] [:div.centerpiece [:a {:on-click #(rf/dispatch [:nav-login])} [:img.logo {:src "https://s3.amazonaws.com/vetd-logos/vetd.svg"}]] [:> ui/Header {:as "h2" :class "blue"} ;; BUG @org-name& will be blank if the page is refreshed, because the link read is invalid ;; TODO ;; show this if simply joining an org "Join " @org-name& " on Vetd" ;; show this if invite originated from inviting a non-existent org ;; to a community ;; "Join COMMUNITY on Vetd" ] [:> ui/Form {:style {:margin-top 25}} (when @need-email?& [:> ui/FormField {:error (= @bad-input& :email)} [:label "Work Email Address" [:> ui/Input {:class "borderless" :type "email" :spellCheck false :auto-focus true :on-invalid #(.preventDefault %) ; no type=email error message (we'll show our own) :on-change (fn [_ this] (reset! email (.-value this)))}]]]) [:> ui/FormField {:error (= @bad-input& :uname)} [:label "PI:NAME:<NAME>END_PI Name" [:> ui/Input {:class "borderless" :spellCheck false :auto-focus (not @need-email?&) :onChange (fn [_ this] (reset! uname (.-value this)))}]]] [:> ui/FormField {:error (= @bad-input& :pwd)} [:label "Password" [:> ui/Input {:class "borderless" :type "password" :onChange (fn [_ this] (reset! pwd (.-value this)))}]]] [:> ui/FormField {:error (or @bad-cpwd (= @bad-input& :cpwd))} [:label "Confirm Password"] [:> ui/Input {:class "borderless" :type "password" :on-blur #(when-not (= @cpwd @pwd) (reset! bad-cpwd true)) :on-change (fn [_ this] (reset! cpwd (.-value this)) (when (= @cpwd @pwd) (reset! bad-cpwd false)))}]] [:> ui/FormField {:error (= @bad-input& :terms-agree) :style {:margin "25px 0 20px 0"}} [:> ui/Checkbox {:label "I agree to the Terms Of Use" :onChange (fn [_ this] (reset! terms-agree (.-checked this)))}] [:a {:href "https://vetd.com/terms-of-use" :target "_blank"} " (read)"]] [:> ui/Button {:color "blue" :fluid true :on-click #(rf/dispatch [:join-org-signup.submit {:need-email? @need-email?& :email @email :uname @uname :pwd PI:PASSWORD:<PASSWORD>END_PI :cpwd @cpwd :terms-agree @terms-agree} @link-key&])} "Sign Up"]]])))
[ { "context": "TRUCTURES ####################\n;{\n;\"first-name\": \"Stojan\",\n;\"last-name\" : \"Jakotyc\",\n;\"age\":38,\n;\"phones\":", "end": 2237, "score": 0.9998208284378052, "start": 2231, "tag": "NAME", "value": "Stojan" }, { "context": "#####\n;{\n;\"first-name\": \"Stojan\",\n;\"last-name\" : \"Jakotyc\",\n;\"age\":38,\n;\"phones\": {\"home\"},\n;..............", "end": 2263, "score": 0.9997958540916443, "start": 2256, "tag": "NAME", "value": "Jakotyc" }, { "context": "......\n;}\n(def person {\n :first-name \"Stojan\"\n :last-name \"Jakotyc\"\n ", "end": 2369, "score": 0.9998270869255066, "start": 2363, "tag": "NAME", "value": "Stojan" }, { "context": " :first-name \"Stojan\"\n :last-name \"Jakotyc\"\n :age 38\n :phones", "end": 2404, "score": 0.9998184442520142, "start": 2397, "tag": "NAME", "value": "Jakotyc" }, { "context": "oobar\"}\n :client-params {\"name\" \"Manny\"}\n :accept :json})\n(http/", "end": 4543, "score": 0.9919514656066895, "start": 4538, "tag": "NAME", "value": "Manny" }, { "context": " OTHER THINGS ####################\n(frequencies [\"Mario\" \"Mario\" \"Luigi\" \"Mario\"])\n(partition 3 (range 12", "end": 6290, "score": 0.9303649663925171, "start": 6285, "tag": "NAME", "value": "Mario" }, { "context": "HINGS ####################\n(frequencies [\"Mario\" \"Mario\" \"Luigi\" \"Mario\"])\n(partition 3 (range 12))", "end": 6298, "score": 0.9958093166351318, "start": 6293, "tag": "NAME", "value": "Mario" }, { "context": "##################\n(frequencies [\"Mario\" \"Mario\" \"Luigi\" \"Mario\"])\n(partition 3 (range 12))", "end": 6306, "score": 0.999281644821167, "start": 6301, "tag": "NAME", "value": "Luigi" }, { "context": "##########\n(frequencies [\"Mario\" \"Mario\" \"Luigi\" \"Mario\"])\n(partition 3 (range 12))", "end": 6314, "score": 0.9989317655563354, "start": 6309, "tag": "NAME", "value": "Mario" } ]
clj/src/clj/code1.clj
jbalaty/reveal.js
0
(ns clj.code1 (:require [clj-http.client :as http]) (:require [hiccup.core :as hiccup]) (:require [clojure.core.async :as a :refer [>! <! >!! <!! go chan buffer close! thread go-loop alts! alts!! timeout]]) (:use clojure.repl) (:use clojure.pprint)) ;; ############## DATA TYPES #################### ; char \c ; strings "Hello sailor!" ; integer 31337 ; floating point 3.1415 ; booolean true ;nil nil ; symbols this-is-a-symbol ; keywords :this-is-a-keyword ::ns-keyword ; regular expressions #"^a.*z$" ;; ############## EVALUATION #################### (function params) ;; ############## Fuctions #################### ; var (def var 123) ; anonymous function (fn [] (println "First function")) ; shorthand for anonymous functions #(= 1 %) #(= 1 %1 %3) (filter #(= (rem % 2) 0) [1 2 3 4 5 6]) ; function in var (def func1 (fn [] (println "First function"))) (func) ; function in var (defn func2 "This is documentation string for function func2" [world] (println "Hello" world)) (func2 "World") (doc func2) (apropos #"func") (source println) (defn tax-amount ([amount] (tax-amount amount 35)) ([amount rate] (Math/round (double (* amount (/ rate 100)))))) ;; ############## DATA STRUCTURES #################### ; list - sequential (1 2 3) (list 1 2 3) ; vector - sequential, random access [1 2 3] [1 2 :three "four"] (vector 1 2 3) ; hashmap - associative {:a 1 :b 2 :c 3} (hash-map :a 1 :b 2 :c 3) {:a 1, :b 2, :c 3} {"a" 1 "b" 2 "c" 3} {[1 2] 1 "b" 2 "c" 3} ; set - order not guaranteed #{:a :b :c} (hash-set :a :b :c) ;; ############## CHANGES #################### (def hmap {:a 1 :b 2 :c 3}) (assoc hmap :b 4) (println hmap) (let [mhmap (assoc hmap :b 4)] (println mhmap)) ;; ############## COLLECTION ABSTRACTIONS #################### (first '(1 2 3)) (first [1 2 3]) (first {:a 1 :b 2 :c 3}) (first #{:a :b :c}) (first "abcd") (seq {:a 1 :b 2 :c 3}) (contains? {:a 1 :b 2 :c 3} :o) (contains? [1 2 3] 2) (contains? #{:a :b :c} :b) (#{:a :b :c} :b) (filter #{:a :c :t} [:a :a :b :d :c :g :t]) ;; ############## COMPLEX DATA STRUCTURES #################### ;{ ;"first-name": "Stojan", ;"last-name" : "Jakotyc", ;"age":38, ;"phones": {"home"}, ;.................... ;} (def person { :first-name "Stojan" :last-name "Jakotyc" :age 38 :phones {:home "111 111 111" :work "222 222 222" :secret "333 333 333"} :adresses [{ :street "Na hrebenech" :city "Praha" :zip "120 00" } { :street "Kafci hory" :city "Praha" :zip "120 00" }] }) (get person :age) (get person :phones) (:phones person) (first (get person :phones)) (rest (get person :phones)) (get-in person [:phones :work]) (get-in person [:phones :work2] "default") (assoc-in person [:phones :work2] "999 999 999") ;; ############## FUNCTIONAL PROGRAMMING #################### (defn make-adder [x] (fn [y] (+ x y))) (def add5 (make-adder 5)) (add5 10) (defn addxy [x y] (+ x y)) (addxy 1 3) (def add7 (partial addxy 7)) (add7 10) ; apply (vector [1 2 3]) (apply vector [1 2 3]) ;(vector 1 2 3) ; comp (def concat-and-reverse (comp (partial apply str) reverse str)) ;(def concat-and-reverse (apply str (reverse (str "hello" "clojuredocs")))) (concat-and-reverse "hello" "clojuredocs") ; threading macro (-> (str "hello" "clojuredocs") (reverse) (#(apply str %))) ;; ############## HOMOICONICITY AND MACROS #################### (map inc [1 2 3 4 5]) (defmacro infix "Use this macro when you pine for the notation of your childhood" [infixed] (list (second infixed) (first infixed) (last infixed))) (infix (2 + 3)) (macroexpand '(infix (1 + 1))) ;; ############## DESTRUCTURING #################### (def obj {:a 1 :b 2 :point [11 12] :d {:d1 1 :d2 2 :d3 3}}) (defn dest1 [{point :point}] (println point)) (dest1 obj) (defn dest2 [{[x y] :point :as whole-map}] (println x y whole-map)) (dest2 obj) (defn dest3 [[_ b _ & rest]] (println b rest)) (dest3 [1 2 3 4 5]) ;; ############## OBJECTS VS DATA #################### (def http-params {:headers {"X-API-Key", "foobar"} :client-params {"name" "Manny"} :accept :json}) (http/get "http://api.bileto.zone/status" http-params) (def resp (http/get "http://api.bileto.zone/status" http-params)) (:status resp) (select-keys resp [:status :body]) ;; ############## SYNTAX VS DATA #################### (hiccup/html [:ul (for [x (range 1 4)] [:li x])]) (defn generateLIs [number] (for [i (range 1 number)] [:li i [:span (str "Item #" i)]])) (hiccup/html [:ul (generateLIs 7)]) ;; ############## POLYMORPHISM #################### (defn convert [data] (cond (nil? data) "null" (string? data) (str "\"" data "\"") (keyword? data) (convert (name data)) :else (str data))) (convert nil) (defmulti convert2 class) (defmethod convert2 clojure.lang.Keyword [data] (convert (name data))) (defmethod convert2 java.lang.String [data] (str "\"" data "\"")) (defmethod convert2 nil [data] "null") (defmethod convert2 :default [data] (str data)) (convert2 123) (defmethod convert2 java.lang.Long [data] (str "Long " data)) ;; ############## CONCURRENCY AND STATE #################### ; CLJ + CLJS (def my-atom (atom 0)) (swap! my-atom inc) (add-watch my-atom :my-key (fn [key atom old-state new-state] (println "Key" key "Atom" atom "OldState" old-state "NewState" new-state))) (reset! a {:foo "bar"}) ; CLJ only ; refs ; agents ; software transactional memory (STM) ;; ############## Core.async #################### (def echo-chan (chan)) (go-loop (println (<! echo-chan))) (>!! echo-chan "ketchup") (thread (println (<!! echo-chan))) (>!! echo-chan "mustard") ;; ############## OTHER THINGS #################### (frequencies ["Mario" "Mario" "Luigi" "Mario"]) (partition 3 (range 12))
15359
(ns clj.code1 (:require [clj-http.client :as http]) (:require [hiccup.core :as hiccup]) (:require [clojure.core.async :as a :refer [>! <! >!! <!! go chan buffer close! thread go-loop alts! alts!! timeout]]) (:use clojure.repl) (:use clojure.pprint)) ;; ############## DATA TYPES #################### ; char \c ; strings "Hello sailor!" ; integer 31337 ; floating point 3.1415 ; booolean true ;nil nil ; symbols this-is-a-symbol ; keywords :this-is-a-keyword ::ns-keyword ; regular expressions #"^a.*z$" ;; ############## EVALUATION #################### (function params) ;; ############## Fuctions #################### ; var (def var 123) ; anonymous function (fn [] (println "First function")) ; shorthand for anonymous functions #(= 1 %) #(= 1 %1 %3) (filter #(= (rem % 2) 0) [1 2 3 4 5 6]) ; function in var (def func1 (fn [] (println "First function"))) (func) ; function in var (defn func2 "This is documentation string for function func2" [world] (println "Hello" world)) (func2 "World") (doc func2) (apropos #"func") (source println) (defn tax-amount ([amount] (tax-amount amount 35)) ([amount rate] (Math/round (double (* amount (/ rate 100)))))) ;; ############## DATA STRUCTURES #################### ; list - sequential (1 2 3) (list 1 2 3) ; vector - sequential, random access [1 2 3] [1 2 :three "four"] (vector 1 2 3) ; hashmap - associative {:a 1 :b 2 :c 3} (hash-map :a 1 :b 2 :c 3) {:a 1, :b 2, :c 3} {"a" 1 "b" 2 "c" 3} {[1 2] 1 "b" 2 "c" 3} ; set - order not guaranteed #{:a :b :c} (hash-set :a :b :c) ;; ############## CHANGES #################### (def hmap {:a 1 :b 2 :c 3}) (assoc hmap :b 4) (println hmap) (let [mhmap (assoc hmap :b 4)] (println mhmap)) ;; ############## COLLECTION ABSTRACTIONS #################### (first '(1 2 3)) (first [1 2 3]) (first {:a 1 :b 2 :c 3}) (first #{:a :b :c}) (first "abcd") (seq {:a 1 :b 2 :c 3}) (contains? {:a 1 :b 2 :c 3} :o) (contains? [1 2 3] 2) (contains? #{:a :b :c} :b) (#{:a :b :c} :b) (filter #{:a :c :t} [:a :a :b :d :c :g :t]) ;; ############## COMPLEX DATA STRUCTURES #################### ;{ ;"first-name": "<NAME>", ;"last-name" : "<NAME>", ;"age":38, ;"phones": {"home"}, ;.................... ;} (def person { :first-name "<NAME>" :last-name "<NAME>" :age 38 :phones {:home "111 111 111" :work "222 222 222" :secret "333 333 333"} :adresses [{ :street "Na hrebenech" :city "Praha" :zip "120 00" } { :street "Kafci hory" :city "Praha" :zip "120 00" }] }) (get person :age) (get person :phones) (:phones person) (first (get person :phones)) (rest (get person :phones)) (get-in person [:phones :work]) (get-in person [:phones :work2] "default") (assoc-in person [:phones :work2] "999 999 999") ;; ############## FUNCTIONAL PROGRAMMING #################### (defn make-adder [x] (fn [y] (+ x y))) (def add5 (make-adder 5)) (add5 10) (defn addxy [x y] (+ x y)) (addxy 1 3) (def add7 (partial addxy 7)) (add7 10) ; apply (vector [1 2 3]) (apply vector [1 2 3]) ;(vector 1 2 3) ; comp (def concat-and-reverse (comp (partial apply str) reverse str)) ;(def concat-and-reverse (apply str (reverse (str "hello" "clojuredocs")))) (concat-and-reverse "hello" "clojuredocs") ; threading macro (-> (str "hello" "clojuredocs") (reverse) (#(apply str %))) ;; ############## HOMOICONICITY AND MACROS #################### (map inc [1 2 3 4 5]) (defmacro infix "Use this macro when you pine for the notation of your childhood" [infixed] (list (second infixed) (first infixed) (last infixed))) (infix (2 + 3)) (macroexpand '(infix (1 + 1))) ;; ############## DESTRUCTURING #################### (def obj {:a 1 :b 2 :point [11 12] :d {:d1 1 :d2 2 :d3 3}}) (defn dest1 [{point :point}] (println point)) (dest1 obj) (defn dest2 [{[x y] :point :as whole-map}] (println x y whole-map)) (dest2 obj) (defn dest3 [[_ b _ & rest]] (println b rest)) (dest3 [1 2 3 4 5]) ;; ############## OBJECTS VS DATA #################### (def http-params {:headers {"X-API-Key", "foobar"} :client-params {"name" "<NAME>"} :accept :json}) (http/get "http://api.bileto.zone/status" http-params) (def resp (http/get "http://api.bileto.zone/status" http-params)) (:status resp) (select-keys resp [:status :body]) ;; ############## SYNTAX VS DATA #################### (hiccup/html [:ul (for [x (range 1 4)] [:li x])]) (defn generateLIs [number] (for [i (range 1 number)] [:li i [:span (str "Item #" i)]])) (hiccup/html [:ul (generateLIs 7)]) ;; ############## POLYMORPHISM #################### (defn convert [data] (cond (nil? data) "null" (string? data) (str "\"" data "\"") (keyword? data) (convert (name data)) :else (str data))) (convert nil) (defmulti convert2 class) (defmethod convert2 clojure.lang.Keyword [data] (convert (name data))) (defmethod convert2 java.lang.String [data] (str "\"" data "\"")) (defmethod convert2 nil [data] "null") (defmethod convert2 :default [data] (str data)) (convert2 123) (defmethod convert2 java.lang.Long [data] (str "Long " data)) ;; ############## CONCURRENCY AND STATE #################### ; CLJ + CLJS (def my-atom (atom 0)) (swap! my-atom inc) (add-watch my-atom :my-key (fn [key atom old-state new-state] (println "Key" key "Atom" atom "OldState" old-state "NewState" new-state))) (reset! a {:foo "bar"}) ; CLJ only ; refs ; agents ; software transactional memory (STM) ;; ############## Core.async #################### (def echo-chan (chan)) (go-loop (println (<! echo-chan))) (>!! echo-chan "ketchup") (thread (println (<!! echo-chan))) (>!! echo-chan "mustard") ;; ############## OTHER THINGS #################### (frequencies ["<NAME>" "<NAME>" "<NAME>" "<NAME>"]) (partition 3 (range 12))
true
(ns clj.code1 (:require [clj-http.client :as http]) (:require [hiccup.core :as hiccup]) (:require [clojure.core.async :as a :refer [>! <! >!! <!! go chan buffer close! thread go-loop alts! alts!! timeout]]) (:use clojure.repl) (:use clojure.pprint)) ;; ############## DATA TYPES #################### ; char \c ; strings "Hello sailor!" ; integer 31337 ; floating point 3.1415 ; booolean true ;nil nil ; symbols this-is-a-symbol ; keywords :this-is-a-keyword ::ns-keyword ; regular expressions #"^a.*z$" ;; ############## EVALUATION #################### (function params) ;; ############## Fuctions #################### ; var (def var 123) ; anonymous function (fn [] (println "First function")) ; shorthand for anonymous functions #(= 1 %) #(= 1 %1 %3) (filter #(= (rem % 2) 0) [1 2 3 4 5 6]) ; function in var (def func1 (fn [] (println "First function"))) (func) ; function in var (defn func2 "This is documentation string for function func2" [world] (println "Hello" world)) (func2 "World") (doc func2) (apropos #"func") (source println) (defn tax-amount ([amount] (tax-amount amount 35)) ([amount rate] (Math/round (double (* amount (/ rate 100)))))) ;; ############## DATA STRUCTURES #################### ; list - sequential (1 2 3) (list 1 2 3) ; vector - sequential, random access [1 2 3] [1 2 :three "four"] (vector 1 2 3) ; hashmap - associative {:a 1 :b 2 :c 3} (hash-map :a 1 :b 2 :c 3) {:a 1, :b 2, :c 3} {"a" 1 "b" 2 "c" 3} {[1 2] 1 "b" 2 "c" 3} ; set - order not guaranteed #{:a :b :c} (hash-set :a :b :c) ;; ############## CHANGES #################### (def hmap {:a 1 :b 2 :c 3}) (assoc hmap :b 4) (println hmap) (let [mhmap (assoc hmap :b 4)] (println mhmap)) ;; ############## COLLECTION ABSTRACTIONS #################### (first '(1 2 3)) (first [1 2 3]) (first {:a 1 :b 2 :c 3}) (first #{:a :b :c}) (first "abcd") (seq {:a 1 :b 2 :c 3}) (contains? {:a 1 :b 2 :c 3} :o) (contains? [1 2 3] 2) (contains? #{:a :b :c} :b) (#{:a :b :c} :b) (filter #{:a :c :t} [:a :a :b :d :c :g :t]) ;; ############## COMPLEX DATA STRUCTURES #################### ;{ ;"first-name": "PI:NAME:<NAME>END_PI", ;"last-name" : "PI:NAME:<NAME>END_PI", ;"age":38, ;"phones": {"home"}, ;.................... ;} (def person { :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :age 38 :phones {:home "111 111 111" :work "222 222 222" :secret "333 333 333"} :adresses [{ :street "Na hrebenech" :city "Praha" :zip "120 00" } { :street "Kafci hory" :city "Praha" :zip "120 00" }] }) (get person :age) (get person :phones) (:phones person) (first (get person :phones)) (rest (get person :phones)) (get-in person [:phones :work]) (get-in person [:phones :work2] "default") (assoc-in person [:phones :work2] "999 999 999") ;; ############## FUNCTIONAL PROGRAMMING #################### (defn make-adder [x] (fn [y] (+ x y))) (def add5 (make-adder 5)) (add5 10) (defn addxy [x y] (+ x y)) (addxy 1 3) (def add7 (partial addxy 7)) (add7 10) ; apply (vector [1 2 3]) (apply vector [1 2 3]) ;(vector 1 2 3) ; comp (def concat-and-reverse (comp (partial apply str) reverse str)) ;(def concat-and-reverse (apply str (reverse (str "hello" "clojuredocs")))) (concat-and-reverse "hello" "clojuredocs") ; threading macro (-> (str "hello" "clojuredocs") (reverse) (#(apply str %))) ;; ############## HOMOICONICITY AND MACROS #################### (map inc [1 2 3 4 5]) (defmacro infix "Use this macro when you pine for the notation of your childhood" [infixed] (list (second infixed) (first infixed) (last infixed))) (infix (2 + 3)) (macroexpand '(infix (1 + 1))) ;; ############## DESTRUCTURING #################### (def obj {:a 1 :b 2 :point [11 12] :d {:d1 1 :d2 2 :d3 3}}) (defn dest1 [{point :point}] (println point)) (dest1 obj) (defn dest2 [{[x y] :point :as whole-map}] (println x y whole-map)) (dest2 obj) (defn dest3 [[_ b _ & rest]] (println b rest)) (dest3 [1 2 3 4 5]) ;; ############## OBJECTS VS DATA #################### (def http-params {:headers {"X-API-Key", "foobar"} :client-params {"name" "PI:NAME:<NAME>END_PI"} :accept :json}) (http/get "http://api.bileto.zone/status" http-params) (def resp (http/get "http://api.bileto.zone/status" http-params)) (:status resp) (select-keys resp [:status :body]) ;; ############## SYNTAX VS DATA #################### (hiccup/html [:ul (for [x (range 1 4)] [:li x])]) (defn generateLIs [number] (for [i (range 1 number)] [:li i [:span (str "Item #" i)]])) (hiccup/html [:ul (generateLIs 7)]) ;; ############## POLYMORPHISM #################### (defn convert [data] (cond (nil? data) "null" (string? data) (str "\"" data "\"") (keyword? data) (convert (name data)) :else (str data))) (convert nil) (defmulti convert2 class) (defmethod convert2 clojure.lang.Keyword [data] (convert (name data))) (defmethod convert2 java.lang.String [data] (str "\"" data "\"")) (defmethod convert2 nil [data] "null") (defmethod convert2 :default [data] (str data)) (convert2 123) (defmethod convert2 java.lang.Long [data] (str "Long " data)) ;; ############## CONCURRENCY AND STATE #################### ; CLJ + CLJS (def my-atom (atom 0)) (swap! my-atom inc) (add-watch my-atom :my-key (fn [key atom old-state new-state] (println "Key" key "Atom" atom "OldState" old-state "NewState" new-state))) (reset! a {:foo "bar"}) ; CLJ only ; refs ; agents ; software transactional memory (STM) ;; ############## Core.async #################### (def echo-chan (chan)) (go-loop (println (<! echo-chan))) (>!! echo-chan "ketchup") (thread (println (<!! echo-chan))) (>!! echo-chan "mustard") ;; ############## OTHER THINGS #################### (frequencies ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) (partition 3 (range 12))
[ { "context": ";; Copyright (c) Stuart Sierra, 2012. All rights reserved. The use and\n;; distri", "end": 30, "score": 0.999853253364563, "start": 17, "tag": "NAME", "value": "Stuart Sierra" } ]
output/conjure_deps/toolsnamespace/v0v3v1/clojure/tools/namespace/file.clj
Olical/conjure-deps
4
;; Copyright (c) Stuart Sierra, 2012. All rights reserved. The use and ;; distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.file (:require [clojure.java.io :as io] [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.parse :as parse] [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.track :as track]) (:import (java.io PushbackReader))) (defn read-file-ns-decl "Attempts to read a (ns ...) declaration from file, and returns the unevaluated form. Returns nil if ns declaration cannot be found. read-opts is passed through to tools.reader/read." ([file] (read-file-ns-decl file nil)) ([file read-opts] (with-open [rdr (PushbackReader. (io/reader file))] (parse/read-ns-decl rdr read-opts)))) (defn file-with-extension? "Returns true if the java.io.File represents a file whose name ends with one of the Strings in extensions." {:added "0.3.0"} [^java.io.File file extensions] (and (.isFile file) (let [name (.getName file)] (some #(.endsWith name %) extensions)))) (def ^{:added "0.3.0"} clojure-extensions "File extensions for Clojure (JVM) files." (list ".clj" ".cljc")) (def ^{:added "0.3.0"} clojurescript-extensions "File extensions for ClojureScript files." (list ".cljs" ".cljc")) (defn clojure-file? "Returns true if the java.io.File represents a file which will be read by the Clojure (JVM) compiler." [^java.io.File file] (file-with-extension? file clojure-extensions)) (defn clojurescript-file? "Returns true if the java.io.File represents a file which will be read by the ClojureScript compiler." {:added "0.3.0"} [^java.io.File file] (file-with-extension? file clojurescript-extensions)) ;;; Dependency tracker (defn- files-and-deps [files read-opts] (reduce (fn [m file] (if-let [decl (read-file-ns-decl file read-opts)] (let [deps (parse/deps-from-ns-decl decl) name (parse/name-from-ns-decl decl)] (-> m (assoc-in [:depmap name] deps) (assoc-in [:filemap file] name))) m)) {} files)) (def ^:private merge-map (fnil merge {})) (defn add-files "Reads ns declarations from files; returns an updated dependency tracker with those files added. read-opts is passed through to tools.reader." ([tracker files] (add-files tracker files nil)) ([tracker files read-opts] (let [{:keys [depmap filemap]} (files-and-deps files read-opts)] (-> tracker (track/add depmap) (update-in [::filemap] merge-map filemap))))) (defn remove-files "Returns an updated dependency tracker with files removed. The files must have been previously added with add-files." [tracker files] (-> tracker (track/remove (keep (::filemap tracker {}) files)) (update-in [::filemap] #(apply dissoc % files))))
39531
;; Copyright (c) <NAME>, 2012. All rights reserved. The use and ;; distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.file (:require [clojure.java.io :as io] [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.parse :as parse] [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.track :as track]) (:import (java.io PushbackReader))) (defn read-file-ns-decl "Attempts to read a (ns ...) declaration from file, and returns the unevaluated form. Returns nil if ns declaration cannot be found. read-opts is passed through to tools.reader/read." ([file] (read-file-ns-decl file nil)) ([file read-opts] (with-open [rdr (PushbackReader. (io/reader file))] (parse/read-ns-decl rdr read-opts)))) (defn file-with-extension? "Returns true if the java.io.File represents a file whose name ends with one of the Strings in extensions." {:added "0.3.0"} [^java.io.File file extensions] (and (.isFile file) (let [name (.getName file)] (some #(.endsWith name %) extensions)))) (def ^{:added "0.3.0"} clojure-extensions "File extensions for Clojure (JVM) files." (list ".clj" ".cljc")) (def ^{:added "0.3.0"} clojurescript-extensions "File extensions for ClojureScript files." (list ".cljs" ".cljc")) (defn clojure-file? "Returns true if the java.io.File represents a file which will be read by the Clojure (JVM) compiler." [^java.io.File file] (file-with-extension? file clojure-extensions)) (defn clojurescript-file? "Returns true if the java.io.File represents a file which will be read by the ClojureScript compiler." {:added "0.3.0"} [^java.io.File file] (file-with-extension? file clojurescript-extensions)) ;;; Dependency tracker (defn- files-and-deps [files read-opts] (reduce (fn [m file] (if-let [decl (read-file-ns-decl file read-opts)] (let [deps (parse/deps-from-ns-decl decl) name (parse/name-from-ns-decl decl)] (-> m (assoc-in [:depmap name] deps) (assoc-in [:filemap file] name))) m)) {} files)) (def ^:private merge-map (fnil merge {})) (defn add-files "Reads ns declarations from files; returns an updated dependency tracker with those files added. read-opts is passed through to tools.reader." ([tracker files] (add-files tracker files nil)) ([tracker files read-opts] (let [{:keys [depmap filemap]} (files-and-deps files read-opts)] (-> tracker (track/add depmap) (update-in [::filemap] merge-map filemap))))) (defn remove-files "Returns an updated dependency tracker with files removed. The files must have been previously added with add-files." [tracker files] (-> tracker (track/remove (keep (::filemap tracker {}) files)) (update-in [::filemap] #(apply dissoc % files))))
true
;; Copyright (c) PI:NAME:<NAME>END_PI, 2012. All rights reserved. The use and ;; distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.file (:require [clojure.java.io :as io] [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.parse :as parse] [conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.track :as track]) (:import (java.io PushbackReader))) (defn read-file-ns-decl "Attempts to read a (ns ...) declaration from file, and returns the unevaluated form. Returns nil if ns declaration cannot be found. read-opts is passed through to tools.reader/read." ([file] (read-file-ns-decl file nil)) ([file read-opts] (with-open [rdr (PushbackReader. (io/reader file))] (parse/read-ns-decl rdr read-opts)))) (defn file-with-extension? "Returns true if the java.io.File represents a file whose name ends with one of the Strings in extensions." {:added "0.3.0"} [^java.io.File file extensions] (and (.isFile file) (let [name (.getName file)] (some #(.endsWith name %) extensions)))) (def ^{:added "0.3.0"} clojure-extensions "File extensions for Clojure (JVM) files." (list ".clj" ".cljc")) (def ^{:added "0.3.0"} clojurescript-extensions "File extensions for ClojureScript files." (list ".cljs" ".cljc")) (defn clojure-file? "Returns true if the java.io.File represents a file which will be read by the Clojure (JVM) compiler." [^java.io.File file] (file-with-extension? file clojure-extensions)) (defn clojurescript-file? "Returns true if the java.io.File represents a file which will be read by the ClojureScript compiler." {:added "0.3.0"} [^java.io.File file] (file-with-extension? file clojurescript-extensions)) ;;; Dependency tracker (defn- files-and-deps [files read-opts] (reduce (fn [m file] (if-let [decl (read-file-ns-decl file read-opts)] (let [deps (parse/deps-from-ns-decl decl) name (parse/name-from-ns-decl decl)] (-> m (assoc-in [:depmap name] deps) (assoc-in [:filemap file] name))) m)) {} files)) (def ^:private merge-map (fnil merge {})) (defn add-files "Reads ns declarations from files; returns an updated dependency tracker with those files added. read-opts is passed through to tools.reader." ([tracker files] (add-files tracker files nil)) ([tracker files read-opts] (let [{:keys [depmap filemap]} (files-and-deps files read-opts)] (-> tracker (track/add depmap) (update-in [::filemap] merge-map filemap))))) (defn remove-files "Returns an updated dependency tracker with files removed. The files must have been previously added with add-files." [tracker files] (-> tracker (track/remove (keep (::filemap tracker {}) files)) (update-in [::filemap] #(apply dissoc % files))))
[ { "context": "> % (.toLowerCase %) (.indexOf text) (> -1))\n [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zo", "end": 613, "score": 0.9998546242713928, "start": 608, "tag": "NAME", "value": "Alice" }, { "context": "LowerCase %) (.indexOf text) (> -1))\n [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n", "end": 620, "score": 0.9998257160186768, "start": 616, "tag": "NAME", "value": "Alan" }, { "context": "se %) (.indexOf text) (> -1))\n [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(def f", "end": 626, "score": 0.9998353719711304, "start": 623, "tag": "NAME", "value": "Bob" }, { "context": "(.indexOf text) (> -1))\n [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(def friends ", "end": 633, "score": 0.9998067617416382, "start": 629, "tag": "NAME", "value": "Beth" }, { "context": "Of text) (> -1))\n [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(def friends (atom ", "end": 639, "score": 0.9998345971107483, "start": 636, "tag": "NAME", "value": "Jim" }, { "context": "t) (> -1))\n [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(def friends (atom [\"Alice", "end": 646, "score": 0.9998104572296143, "start": 642, "tag": "NAME", "value": "Jane" }, { "context": "1))\n [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(def friends (atom [\"Alice\" \"Ala", "end": 652, "score": 0.9998048543930054, "start": 649, "tag": "NAME", "value": "Kim" }, { "context": " [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(def friends (atom [\"Alice\" \"Alan\" \"Bo", "end": 658, "score": 0.999700665473938, "start": 655, "tag": "NAME", "value": "Rob" }, { "context": "ce\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(def friends (atom [\"Alice\" \"Alan\" \"Bob\" \"Be", "end": 664, "score": 0.9983362555503845, "start": 661, "tag": "NAME", "value": "Zoe" }, { "context": "\"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(def friends (atom [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zo", "end": 696, "score": 0.999838650226593, "start": 691, "tag": "NAME", "value": "Alice" }, { "context": "Kim\" \"Rob\" \"Zoe\"]))\n\n(def friends (atom [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n", "end": 703, "score": 0.9997895359992981, "start": 699, "tag": "NAME", "value": "Alan" }, { "context": "ob\" \"Zoe\"]))\n\n(def friends (atom [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(defn ", "end": 709, "score": 0.9998453259468079, "start": 706, "tag": "NAME", "value": "Bob" }, { "context": "oe\"]))\n\n(def friends (atom [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(defn friend-", "end": 716, "score": 0.9998049736022949, "start": 712, "tag": "NAME", "value": "Beth" }, { "context": "\n(def friends (atom [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(defn friend-source", "end": 722, "score": 0.9998428821563721, "start": 719, "tag": "NAME", "value": "Jim" }, { "context": "friends (atom [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(defn friend-source-ajax [", "end": 729, "score": 0.9998244047164917, "start": 725, "tag": "NAME", "value": "Jane" }, { "context": " (atom [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(defn friend-source-ajax [text]\n", "end": 735, "score": 0.9998292922973633, "start": 732, "tag": "NAME", "value": "Kim" }, { "context": " [\"Alice\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(defn friend-source-ajax [text]\n (fil", "end": 741, "score": 0.9998160004615784, "start": 738, "tag": "NAME", "value": "Rob" }, { "context": "ce\" \"Alan\" \"Bob\" \"Beth\" \"Jim\" \"Jane\" \"Kim\" \"Rob\" \"Zoe\"]))\n\n(defn friend-source-ajax [text]\n (filter\n ", "end": 747, "score": 0.999624490737915, "start": 744, "tag": "NAME", "value": "Zoe" }, { "context": " page []\n (let [doc (atom {:person {:first-name \"John\"\n :age 35\n ", "end": 4073, "score": 0.9998506307601929, "start": 4069, "tag": "NAME", "value": "John" }, { "context": " :age 35\n :email \"foo@bar.baz\"}\n :weight 100\n ", "end": 4158, "score": 0.999860942363739, "start": 4147, "tag": "EMAIL", "value": "foo@bar.baz" } ]
resources/public/js/forms_example/view_one.cljs
pariyatti/reagent-playground
0
(ns forms-example.view-one (:require [json-html.core :refer [edn->hiccup]] [reagent.core :as reagent :refer [atom]] [reagent-forms.core :refer [bind-fields init-field value-of]])) (defn row [label input] [:div.row [:div.col-md-2 [:label label]] [:div.col-md-5 input]]) (defn radio [label name value] [:div.radio [:label [:input {:field :radio :name name :value value}] label]]) (defn input [label type id] (row label [:input.form-control {:field type :id id}])) (defn friend-source [text] (filter #(-> % (.toLowerCase %) (.indexOf text) (> -1)) ["Alice" "Alan" "Bob" "Beth" "Jim" "Jane" "Kim" "Rob" "Zoe"])) (def friends (atom ["Alice" "Alan" "Bob" "Beth" "Jim" "Jane" "Kim" "Rob" "Zoe"])) (defn friend-source-ajax [text] (filter #(-> % (.toLowerCase %) (.indexOf text) (> -1)) friends)) (def form-template [:div (input "first name" :text :person.first-name) [:div.row [:div.col-md-2] [:div.col-md-5 [:div.alert.alert-danger {:field :alert :id :errors.first-name}]]] (input "last name" :text :person.last-name) [:div.row [:div.col-md-2] [:div.col-md-5 [:div.alert.alert-success {:field :alert :id :person.last-name :event empty?} "last name is empty!"]]] [:div.row [:div.col-md-2 [:label "Age"]] [:div.col-md-5 [:div [:label [:input {:field :datepicker :id :age :date-format "yyyy/mm/dd" :inline true}]]]]] (input "email" :email :person.email) (row "comments" [:textarea.form-control {:field :textarea :id :comments}]) [:hr] (input "kg" :numeric :weight-kg) (input "lb" :numeric :weight-lb) [:hr] [:h3 "BMI Calculator"] (input "height" :numeric :height) (input "weight" :numeric :weight) (row "BMI" [:input.form-control {:field :numeric :fmt "%.2f" :id :bmi :disabled true}]) [:hr] (row "Best friend" [:div {:field :typeahead :id :ta :data-source friend-source :input-placeholder "Who's your best friend? You can pick only one" :input-class "form-control" :list-class "typeahead-list" :item-class "typeahead-item" :highlight-class "highlighted"}]) [:br] (row "isn't data binding lovely?" [:input {:field :checkbox :id :databinding.lovely}]) [:label {:field :label :preamble "The level of awesome: " :placeholder "N/A" :id :awesomeness}] [:input {:field :range :min 1 :max 10 :id :awesomeness}] [:h3 "option list"] [:div.form-group [:label "pick an option"] [:select.form-control {:field :list :id :many.options} [:option {:key :foo} "foo"] [:option {:key :bar} "bar"] [:option {:key :baz} "baz"]]] (radio "Option one is this and that—be sure to include why it's great" :foo :a) (radio "Option two can be something else and selecting it will deselect option one" :foo :b) [:h3 "multi-select buttons"] [:div.btn-group {:field :multi-select :id :every.position} [:button.btn.btn-default {:key :left} "Left"] [:button.btn.btn-default {:key :middle} "Middle"] [:button.btn.btn-default {:key :right} "Right"]] [:h3 "single-select buttons"] [:div.btn-group {:field :single-select :id :unique.position} [:button.btn.btn-default {:key :left} "Left"] [:button.btn.btn-default {:key :middle} "Middle"] [:button.btn.btn-default {:key :right} "Right"]] [:h3 "single-select list"] [:div.list-group {:field :single-select :id :pick-one} [:div.list-group-item {:key :foo} "foo"] [:div.list-group-item {:key :bar} "bar"] [:div.list-group-item {:key :baz} "baz"]] [:h3 "multi-select list"] [:ul.list-group {:field :multi-select :id :pick-a-few} [:li.list-group-item {:key :foo} "foo"] [:li.list-group-item {:key :bar} "bar"] [:li.list-group-item {:key :baz} "baz"]]]) (defn page [] (let [doc (atom {:person {:first-name "John" :age 35 :email "foo@bar.baz"} :weight 100 :height 200 :bmi 0.5 :comments "some interesting comments\non this subject" :radioselection :b :position [:left :right] :pick-one :bar :unique {:position :middle} :pick-a-few [:bar :baz] :many {:options :bar}})] (fn [] [:div [:div.page-header [:h1 "View One: Sample Form"]] [bind-fields form-template doc (fn [[id] value {:keys [weight-lb weight-kg] :as document}] (cond (= id :weight-lb) (assoc document :weight-kg (/ value 2.2046)) (= id :weight-kg) (assoc document :weight-lb (* value 2.2046)) :else nil)) (fn [[id] value {:keys [height weight] :as document}] (when (and (some #{id} [:height :weight]) weight height) (assoc document :bmi (/ weight (* height height)))))] [:button.btn.btn-default {:on-click #(if (empty? (get-in @doc [:person :first-name])) (swap! doc assoc-in [:errors :first-name]"first name is empty"))} "save"] [:hr] [:h1 "Document State"] [edn->hiccup @doc]]))) (reagent/render-component [page] (.getElementById js/document "app"))
34041
(ns forms-example.view-one (:require [json-html.core :refer [edn->hiccup]] [reagent.core :as reagent :refer [atom]] [reagent-forms.core :refer [bind-fields init-field value-of]])) (defn row [label input] [:div.row [:div.col-md-2 [:label label]] [:div.col-md-5 input]]) (defn radio [label name value] [:div.radio [:label [:input {:field :radio :name name :value value}] label]]) (defn input [label type id] (row label [:input.form-control {:field type :id id}])) (defn friend-source [text] (filter #(-> % (.toLowerCase %) (.indexOf text) (> -1)) ["<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"])) (def friends (atom ["<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"])) (defn friend-source-ajax [text] (filter #(-> % (.toLowerCase %) (.indexOf text) (> -1)) friends)) (def form-template [:div (input "first name" :text :person.first-name) [:div.row [:div.col-md-2] [:div.col-md-5 [:div.alert.alert-danger {:field :alert :id :errors.first-name}]]] (input "last name" :text :person.last-name) [:div.row [:div.col-md-2] [:div.col-md-5 [:div.alert.alert-success {:field :alert :id :person.last-name :event empty?} "last name is empty!"]]] [:div.row [:div.col-md-2 [:label "Age"]] [:div.col-md-5 [:div [:label [:input {:field :datepicker :id :age :date-format "yyyy/mm/dd" :inline true}]]]]] (input "email" :email :person.email) (row "comments" [:textarea.form-control {:field :textarea :id :comments}]) [:hr] (input "kg" :numeric :weight-kg) (input "lb" :numeric :weight-lb) [:hr] [:h3 "BMI Calculator"] (input "height" :numeric :height) (input "weight" :numeric :weight) (row "BMI" [:input.form-control {:field :numeric :fmt "%.2f" :id :bmi :disabled true}]) [:hr] (row "Best friend" [:div {:field :typeahead :id :ta :data-source friend-source :input-placeholder "Who's your best friend? You can pick only one" :input-class "form-control" :list-class "typeahead-list" :item-class "typeahead-item" :highlight-class "highlighted"}]) [:br] (row "isn't data binding lovely?" [:input {:field :checkbox :id :databinding.lovely}]) [:label {:field :label :preamble "The level of awesome: " :placeholder "N/A" :id :awesomeness}] [:input {:field :range :min 1 :max 10 :id :awesomeness}] [:h3 "option list"] [:div.form-group [:label "pick an option"] [:select.form-control {:field :list :id :many.options} [:option {:key :foo} "foo"] [:option {:key :bar} "bar"] [:option {:key :baz} "baz"]]] (radio "Option one is this and that—be sure to include why it's great" :foo :a) (radio "Option two can be something else and selecting it will deselect option one" :foo :b) [:h3 "multi-select buttons"] [:div.btn-group {:field :multi-select :id :every.position} [:button.btn.btn-default {:key :left} "Left"] [:button.btn.btn-default {:key :middle} "Middle"] [:button.btn.btn-default {:key :right} "Right"]] [:h3 "single-select buttons"] [:div.btn-group {:field :single-select :id :unique.position} [:button.btn.btn-default {:key :left} "Left"] [:button.btn.btn-default {:key :middle} "Middle"] [:button.btn.btn-default {:key :right} "Right"]] [:h3 "single-select list"] [:div.list-group {:field :single-select :id :pick-one} [:div.list-group-item {:key :foo} "foo"] [:div.list-group-item {:key :bar} "bar"] [:div.list-group-item {:key :baz} "baz"]] [:h3 "multi-select list"] [:ul.list-group {:field :multi-select :id :pick-a-few} [:li.list-group-item {:key :foo} "foo"] [:li.list-group-item {:key :bar} "bar"] [:li.list-group-item {:key :baz} "baz"]]]) (defn page [] (let [doc (atom {:person {:first-name "<NAME>" :age 35 :email "<EMAIL>"} :weight 100 :height 200 :bmi 0.5 :comments "some interesting comments\non this subject" :radioselection :b :position [:left :right] :pick-one :bar :unique {:position :middle} :pick-a-few [:bar :baz] :many {:options :bar}})] (fn [] [:div [:div.page-header [:h1 "View One: Sample Form"]] [bind-fields form-template doc (fn [[id] value {:keys [weight-lb weight-kg] :as document}] (cond (= id :weight-lb) (assoc document :weight-kg (/ value 2.2046)) (= id :weight-kg) (assoc document :weight-lb (* value 2.2046)) :else nil)) (fn [[id] value {:keys [height weight] :as document}] (when (and (some #{id} [:height :weight]) weight height) (assoc document :bmi (/ weight (* height height)))))] [:button.btn.btn-default {:on-click #(if (empty? (get-in @doc [:person :first-name])) (swap! doc assoc-in [:errors :first-name]"first name is empty"))} "save"] [:hr] [:h1 "Document State"] [edn->hiccup @doc]]))) (reagent/render-component [page] (.getElementById js/document "app"))
true
(ns forms-example.view-one (:require [json-html.core :refer [edn->hiccup]] [reagent.core :as reagent :refer [atom]] [reagent-forms.core :refer [bind-fields init-field value-of]])) (defn row [label input] [:div.row [:div.col-md-2 [:label label]] [:div.col-md-5 input]]) (defn radio [label name value] [:div.radio [:label [:input {:field :radio :name name :value value}] label]]) (defn input [label type id] (row label [:input.form-control {:field type :id id}])) (defn friend-source [text] (filter #(-> % (.toLowerCase %) (.indexOf text) (> -1)) ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI: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 friends (atom ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"])) (defn friend-source-ajax [text] (filter #(-> % (.toLowerCase %) (.indexOf text) (> -1)) friends)) (def form-template [:div (input "first name" :text :person.first-name) [:div.row [:div.col-md-2] [:div.col-md-5 [:div.alert.alert-danger {:field :alert :id :errors.first-name}]]] (input "last name" :text :person.last-name) [:div.row [:div.col-md-2] [:div.col-md-5 [:div.alert.alert-success {:field :alert :id :person.last-name :event empty?} "last name is empty!"]]] [:div.row [:div.col-md-2 [:label "Age"]] [:div.col-md-5 [:div [:label [:input {:field :datepicker :id :age :date-format "yyyy/mm/dd" :inline true}]]]]] (input "email" :email :person.email) (row "comments" [:textarea.form-control {:field :textarea :id :comments}]) [:hr] (input "kg" :numeric :weight-kg) (input "lb" :numeric :weight-lb) [:hr] [:h3 "BMI Calculator"] (input "height" :numeric :height) (input "weight" :numeric :weight) (row "BMI" [:input.form-control {:field :numeric :fmt "%.2f" :id :bmi :disabled true}]) [:hr] (row "Best friend" [:div {:field :typeahead :id :ta :data-source friend-source :input-placeholder "Who's your best friend? You can pick only one" :input-class "form-control" :list-class "typeahead-list" :item-class "typeahead-item" :highlight-class "highlighted"}]) [:br] (row "isn't data binding lovely?" [:input {:field :checkbox :id :databinding.lovely}]) [:label {:field :label :preamble "The level of awesome: " :placeholder "N/A" :id :awesomeness}] [:input {:field :range :min 1 :max 10 :id :awesomeness}] [:h3 "option list"] [:div.form-group [:label "pick an option"] [:select.form-control {:field :list :id :many.options} [:option {:key :foo} "foo"] [:option {:key :bar} "bar"] [:option {:key :baz} "baz"]]] (radio "Option one is this and that—be sure to include why it's great" :foo :a) (radio "Option two can be something else and selecting it will deselect option one" :foo :b) [:h3 "multi-select buttons"] [:div.btn-group {:field :multi-select :id :every.position} [:button.btn.btn-default {:key :left} "Left"] [:button.btn.btn-default {:key :middle} "Middle"] [:button.btn.btn-default {:key :right} "Right"]] [:h3 "single-select buttons"] [:div.btn-group {:field :single-select :id :unique.position} [:button.btn.btn-default {:key :left} "Left"] [:button.btn.btn-default {:key :middle} "Middle"] [:button.btn.btn-default {:key :right} "Right"]] [:h3 "single-select list"] [:div.list-group {:field :single-select :id :pick-one} [:div.list-group-item {:key :foo} "foo"] [:div.list-group-item {:key :bar} "bar"] [:div.list-group-item {:key :baz} "baz"]] [:h3 "multi-select list"] [:ul.list-group {:field :multi-select :id :pick-a-few} [:li.list-group-item {:key :foo} "foo"] [:li.list-group-item {:key :bar} "bar"] [:li.list-group-item {:key :baz} "baz"]]]) (defn page [] (let [doc (atom {:person {:first-name "PI:NAME:<NAME>END_PI" :age 35 :email "PI:EMAIL:<EMAIL>END_PI"} :weight 100 :height 200 :bmi 0.5 :comments "some interesting comments\non this subject" :radioselection :b :position [:left :right] :pick-one :bar :unique {:position :middle} :pick-a-few [:bar :baz] :many {:options :bar}})] (fn [] [:div [:div.page-header [:h1 "View One: Sample Form"]] [bind-fields form-template doc (fn [[id] value {:keys [weight-lb weight-kg] :as document}] (cond (= id :weight-lb) (assoc document :weight-kg (/ value 2.2046)) (= id :weight-kg) (assoc document :weight-lb (* value 2.2046)) :else nil)) (fn [[id] value {:keys [height weight] :as document}] (when (and (some #{id} [:height :weight]) weight height) (assoc document :bmi (/ weight (* height height)))))] [:button.btn.btn-default {:on-click #(if (empty? (get-in @doc [:person :first-name])) (swap! doc assoc-in [:errors :first-name]"first name is empty"))} "save"] [:hr] [:h1 "Document State"] [edn->hiccup @doc]]))) (reagent/render-component [page] (.getElementById js/document "app"))
[ { "context": "create {:user-email email\n :password password\n :user-name (str \"extractor-\" (str ", "end": 198, "score": 0.9974759817123413, "start": 190, "tag": "PASSWORD", "value": "password" }, { "context": "run -m kulu-backend.scripts.add-extractor-user dev sam@harris.org chomsky\n;;\n(defn -main [& args]\n (System/setProp", "end": 427, "score": 0.9999064803123474, "start": 413, "tag": "EMAIL", "value": "sam@harris.org" }, { "context": "kend.scripts.add-extractor-user dev sam@harris.org chomsky\n;;\n(defn -main [& args]\n (System/setProperty \"no", "end": 435, "score": 0.7628629207611084, "start": 428, "tag": "USERNAME", "value": "chomsky" } ]
src/kulu_backend/scripts/add_extractor_user.clj
vkrmis/kulu-backend
3
(ns kulu-backend.scripts.add-extractor-user (:require [kulu-backend.organizations.model :as org])) (defn create [email password] (org/create {:user-email email :password password :user-name (str "extractor-" (str (java.util.UUID/randomUUID))) :organization-name "transcribers"})) ;; ;; how to run: ;; ;; $ lein run -m kulu-backend.scripts.add-extractor-user dev sam@harris.org chomsky ;; (defn -main [& args] (System/setProperty "nomad.env" (first args)) (create (second args) (first (rest (rest args)))) (System/exit 0))
122242
(ns kulu-backend.scripts.add-extractor-user (:require [kulu-backend.organizations.model :as org])) (defn create [email password] (org/create {:user-email email :password <PASSWORD> :user-name (str "extractor-" (str (java.util.UUID/randomUUID))) :organization-name "transcribers"})) ;; ;; how to run: ;; ;; $ lein run -m kulu-backend.scripts.add-extractor-user dev <EMAIL> chomsky ;; (defn -main [& args] (System/setProperty "nomad.env" (first args)) (create (second args) (first (rest (rest args)))) (System/exit 0))
true
(ns kulu-backend.scripts.add-extractor-user (:require [kulu-backend.organizations.model :as org])) (defn create [email password] (org/create {:user-email email :password PI:PASSWORD:<PASSWORD>END_PI :user-name (str "extractor-" (str (java.util.UUID/randomUUID))) :organization-name "transcribers"})) ;; ;; how to run: ;; ;; $ lein run -m kulu-backend.scripts.add-extractor-user dev PI:EMAIL:<EMAIL>END_PI chomsky ;; (defn -main [& args] (System/setProperty "nomad.env" (first args)) (create (second args) (first (rest (rest args)))) (System/exit 0))
[ { "context": " :primary-contact (rand-nth [\"John Smith 715 642-2111\"\n ", "end": 2406, "score": 0.9998643398284912, "start": 2396, "tag": "NAME", "value": "John Smith" }, { "context": " \"John Smith 715 642-2222\"\n ", "end": 2487, "score": 0.9998599290847778, "start": 2477, "tag": "NAME", "value": "John Smith" }, { "context": " \"John Smith 715 642-2333\"])\n :contr", "end": 2568, "score": 0.999863862991333, "start": 2558, "tag": "NAME", "value": "John Smith" } ]
PROJECTNAMESPACE.PROJECTNAME/src/PROJECTNAMESPACE/PROJECTNAME/frontend/devcards/components.cljs
armincerf/clojure-template
1
(ns PROJECTNAMESPACE.PROJECTNAME.frontend.devcards.components (:require [reagent.core :as r] [PROJECTNAMESPACE.PROJECTNAME.frontend.dashboard.components :as components] [PROJECTNAMESPACE.PROJECTNAME.frontend.uikit.table :as table] [devcards.core :refer [defcard-rg]])) (defcard-rg breadcrumb [:div {:style {:background "#424242" :padding "1rem"}} [components/breadcrumb [{:label "dealers" :href "#"} {:label "dealer 1" :href "#"}]]]) (defcard-rg table-test [:div [:h1 "Customer List"] [table/table {:columns [{:column-key :error :column-name "Error" :render-fn (fn [row v] (let [[icon-class icon-color] (case v "ok" ["fa-check-circle" "#00e676"] "warn" ["fa-exclamation-circle" "#ffea00"] "severe" ["fa-stop-circle" "#ff1744"] nil)] [:span {:style {:color icon-color :font-size "1.5rem"}} [:i.fas {:class icon-class}]])) :render-only #{:sort :filter}} {:column-key :company-name :column-name "Company Name"} {:column-key :location :column-name "Location"} {:column-key :primary-contact :column-name "Primary Contact"} {:column-key :contract :column-name "Contract"} {:column-key :records :column-name "Records"}] :rows (map-indexed (fn [idx] {:id idx :error (rand-nth ["ok" "warn" "severe"]) :company-name (rand-nth ["Big bobs windows" "Little bobs doors" "Fat stans fencing"]) :location (rand-nth ["111 Main St, City of Town, USA" "222 Main St, City of Town, USA" "333 Main St, City of Town, USA"]) :primary-contact (rand-nth ["John Smith 715 642-2111" "John Smith 715 642-2222" "John Smith 715 642-2333"]) :contract (rand-nth ["Yes" "No"]) :records "View Status"}) (range 20))}]])
3207
(ns PROJECTNAMESPACE.PROJECTNAME.frontend.devcards.components (:require [reagent.core :as r] [PROJECTNAMESPACE.PROJECTNAME.frontend.dashboard.components :as components] [PROJECTNAMESPACE.PROJECTNAME.frontend.uikit.table :as table] [devcards.core :refer [defcard-rg]])) (defcard-rg breadcrumb [:div {:style {:background "#424242" :padding "1rem"}} [components/breadcrumb [{:label "dealers" :href "#"} {:label "dealer 1" :href "#"}]]]) (defcard-rg table-test [:div [:h1 "Customer List"] [table/table {:columns [{:column-key :error :column-name "Error" :render-fn (fn [row v] (let [[icon-class icon-color] (case v "ok" ["fa-check-circle" "#00e676"] "warn" ["fa-exclamation-circle" "#ffea00"] "severe" ["fa-stop-circle" "#ff1744"] nil)] [:span {:style {:color icon-color :font-size "1.5rem"}} [:i.fas {:class icon-class}]])) :render-only #{:sort :filter}} {:column-key :company-name :column-name "Company Name"} {:column-key :location :column-name "Location"} {:column-key :primary-contact :column-name "Primary Contact"} {:column-key :contract :column-name "Contract"} {:column-key :records :column-name "Records"}] :rows (map-indexed (fn [idx] {:id idx :error (rand-nth ["ok" "warn" "severe"]) :company-name (rand-nth ["Big bobs windows" "Little bobs doors" "Fat stans fencing"]) :location (rand-nth ["111 Main St, City of Town, USA" "222 Main St, City of Town, USA" "333 Main St, City of Town, USA"]) :primary-contact (rand-nth ["<NAME> 715 642-2111" "<NAME> 715 642-2222" "<NAME> 715 642-2333"]) :contract (rand-nth ["Yes" "No"]) :records "View Status"}) (range 20))}]])
true
(ns PROJECTNAMESPACE.PROJECTNAME.frontend.devcards.components (:require [reagent.core :as r] [PROJECTNAMESPACE.PROJECTNAME.frontend.dashboard.components :as components] [PROJECTNAMESPACE.PROJECTNAME.frontend.uikit.table :as table] [devcards.core :refer [defcard-rg]])) (defcard-rg breadcrumb [:div {:style {:background "#424242" :padding "1rem"}} [components/breadcrumb [{:label "dealers" :href "#"} {:label "dealer 1" :href "#"}]]]) (defcard-rg table-test [:div [:h1 "Customer List"] [table/table {:columns [{:column-key :error :column-name "Error" :render-fn (fn [row v] (let [[icon-class icon-color] (case v "ok" ["fa-check-circle" "#00e676"] "warn" ["fa-exclamation-circle" "#ffea00"] "severe" ["fa-stop-circle" "#ff1744"] nil)] [:span {:style {:color icon-color :font-size "1.5rem"}} [:i.fas {:class icon-class}]])) :render-only #{:sort :filter}} {:column-key :company-name :column-name "Company Name"} {:column-key :location :column-name "Location"} {:column-key :primary-contact :column-name "Primary Contact"} {:column-key :contract :column-name "Contract"} {:column-key :records :column-name "Records"}] :rows (map-indexed (fn [idx] {:id idx :error (rand-nth ["ok" "warn" "severe"]) :company-name (rand-nth ["Big bobs windows" "Little bobs doors" "Fat stans fencing"]) :location (rand-nth ["111 Main St, City of Town, USA" "222 Main St, City of Town, USA" "333 Main St, City of Town, USA"]) :primary-contact (rand-nth ["PI:NAME:<NAME>END_PI 715 642-2111" "PI:NAME:<NAME>END_PI 715 642-2222" "PI:NAME:<NAME>END_PI 715 642-2333"]) :contract (rand-nth ["Yes" "No"]) :records "View Status"}) (range 20))}]])
[ { "context": " ;;\n;; Author: Jon Anthony ", "end": 1839, "score": 0.999825656414032, "start": 1828, "tag": "NAME", "value": "Jon Anthony" } ]
src/aerial/utils/math.clj
jsa-aerial/aerial.utils
5
;;--------------------------------------------------------------------------;; ;; ;; ;; U T I L S . M A T H ;; ;; ;; ;; 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 aerial.utils.math "Various math functions that don't quite have enough totality to have their own home namespace just yet." (:require [clojure.math.numeric-tower :as math] [aerial.utils.coll :refer [transpose reducem take-until]])) ;;; ----------------------------------------------------------------- ;;; Various ancillary math/arithmetic stuff. (defn div "Integer division. Return [q r], such that floor(n / d) * q + r = q" [n d] (let [q (math/floor (/ n d))] [q (rem n d)])) (defn sum "Return the sum of the numbers in COLL. If COLL is a map, return the sum of the (presumed all numbers) in (vals coll). For function F versions, return the sum x in COLL (f x) or sum x in COLL1, y in COLL2 (f x y) or sum x1 in C1, x2 in C2, ... xn in Cn (f x1 ... xn). By default, summation proceeds on the results of F applied over the _cross product_ of the collections. If summation should proceed over the collections in parallel, the first \"coll\" given should be the special keyword :||. If given this causes F to be applied to the elements of colls as stepped in parallel: f(coll1[i] coll2[i] .. colln[i]), i in [0 .. (count smallest-given-coll)]. Examples: (sum + [1 2 3] [1 2 3]) => 36 ; sum of all [1 2 3] X [1 2 3] pairwise sums (sum + :|| [1 2 3] [1 2 3]) => 12 ; sum of [(+ 1 1) (+ 2 2) (+ 3 3)] (sum (fn[x y] (* x (log2 y))) :|| [1 2 3] [1 2 3]) => 6.754887502163469 " ([coll] (let [vs (if (map? coll) (vals coll) coll)] (apply +' vs))) ([f coll] (reducem f +' coll)) ([f coll1 coll2 & colls] (let [colls (cons coll2 colls)] (apply reducem f +' coll1 colls)))) (defn cumsum "Cumulative sum of values in COLL. If COLL is a map, return the cumulative sum of the (presumed all numbers) in (vals coll). For function F versions, return the cumulative sum of x in COLL (f x) or the cumulative sum of x1 in COLL1, x2 in COLL2, ... xn in COLLn (f x1 ... xn). The cumulative sum is the seq of partial sums across COLL treated as a vector for each (i (range (count COLL))), effectively: [(coll 0) (sum (subvec coll 0 2)) .. (sum (subvec coll 0 (count coll)))] Except actual computational time is linear. " ([coll] (let [cv (vec (if (map? coll) (vals coll) coll)) c0 (cv 0)] (first (reduce (fn[[v s] x] (let [s (+ s x)] [(conj v s) s])) [[c0] c0] (rest cv))))) ([f coll] (cumsum (map f coll))) ([f coll1 coll2 & colls] (cumsum (apply map f coll1 coll2 colls)))) (defn prod "Return the product of the numbers in COLL. If COLL is a map, return the product of the (presumed all numbers) in (vals coll). For function F versions, return the product of x in COLL (f x) or prod x in COLL1, y in COLL2 (f x y) or prod x1 in C1, x2 in C2, ... xn in Cn (f x1 ... xn). By default, multiplication proceeds on the results of F applied over the _cross product_ of the collections. If multiplication should proceed over the collections in parallel, the first \"coll\" given should be the special keyword :||. If given, this causes F to be applied to the elements of colls as stepped in parallel: f(coll1[i] coll2[i] .. colln[i]), i in [0 .. (count smallest-coll)]. Examples: (prod + [1 2 3] [1 2 3]) => 172800 ; product of all [1 2 3] X [1 2 3] pairwise sums (prod + :|| [1 2 3] [1 2 3]) => 48 ; product of [(+ 1 1) (+ 2 2) (+ 3 3)] " ([coll] (let [vs (if (map? coll) (vals coll) coll)] (apply *' vs))) ([f coll] (reducem f *' coll)) ([f coll1 coll2 & colls] (let [colls (cons coll2 colls)] (apply reducem f *' coll1 colls)))) (defn sqr "Square x, i.e., returns (* x x)" [x] (*' x x)) (defn logb "Return the log to the base b _function_ of x" [b] (let [lnb (Math/log b)] (fn[x] (/ (Math/log x) lnb)))) (defn log "Return the natural log of x" [x] (Math/log x)) (defn ln "Return the natural log of x" [x] (Math/log x)) (def ^{:doc "Named version of (logb 2). Important enough to have a named top level function" :arglists '([x])} log2 (logb 2)) (def ^{:doc "Named version of (logb 10). Important enough to have a named top level function" :arglists '([x])} log10 (logb 10)) (defn logistic "Compute logistic of X (a number which will be cast as a double. Returns 1.0 / (1.0 + e^-x) = e^x / (e^x + 1.0) " [x] (let [ex (math/expt Math/E (double x))] (/ ex (+ ex 1.0)))) (defn logit "Compute the log odds of P an element of interval [0..1]. LOGFN is the logarithmic function to use and defaults to log2, log base 2. Other directly available log functions are ln (or simply log) and log10; for any other base see logb which can generate a log function of base b. Returns logfn (p / (1 - p)), the inverse of logistic. " [p & {:keys [logfn] :or {logfn log2}}] (logfn (/ p (- 1 p)))) (defn primes "RHickey paste.lisp.org with some fixes by jsa. Returns a list of all primes from 2 to n. Wicked fast!" [n] (if (< n 2) () (let [n (long n)] (let [root (long (Math/round (Math/floor (Math/sqrt n))))] (loop [i (long 3) a (int-array (inc n)) result (list 2)] (if (> i n) (reverse result) (recur (+ i (long 2)) (if (<= i root) (loop [arr a inc (+ i i) j (* i i)] (if (> j n) arr (recur (do (aset arr j (long 1)) arr) inc (+ j inc)))) a) (if (zero? (aget a i)) (conj result i) result)))))))) (def +prime-set+ (atom (primes 1000))) (defn prime-factors "Return the prime factorization of num as a seq of pairs [p n], where p is a prime and n is the number of times it is a factor. Ex: (prime-factors 510) => [[2 1] [3 1] [5 1] [17 1]] " [num] (if (< num 2) num (do (when (> num (last @+prime-set+)) (swap! +prime-set+ (fn[_](primes (+ num (long (/ num 2))))))) (loop [ps (take-until #(> % num) @+prime-set+) factors []] (if (empty? ps) factors (let [pf (loop [n num cnt 0] (let [f (first ps) [q r] (div n f)] (if (not= 0 r) (when (> cnt 0) [f cnt]) (recur q (inc cnt)))))] (recur (rest ps) (if pf (conj factors pf) factors)))))))) ;;; ----------------------------------------------------------------- ;;; Simple vector stuff. dot product, norm, distances, and such. Is ;;; all this stuff in Incanter?? (defn dot [v1 v2] (double (reduce + 0.0 (map * v1 v2)))) (defn norm [v] (math/sqrt (dot v v))) (defn vhat [v] (let [n (norm v)] (vec (map #(/ % n) v)))) (defn cos-vangle [v1 v2] (dot (vhat v1) (vhat v2))) (defn vangle-dist [v1 v2] (math/abs (dec (cos-vangle v1 v2)))) (defn vecdist [v1 v2] (let [v (map - v1 v2)] (math/sqrt (dot v v)))) (defn vecmean ([v1 v2] (map #(/ (+ %1 %2) 2) v1 v2)) ([vs] (let [d (count vs)] (map (fn[xs] (/ (apply + xs) d)) (transpose vs)))))
82622
;;--------------------------------------------------------------------------;; ;; ;; ;; U T I L S . M A T H ;; ;; ;; ;; 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 aerial.utils.math "Various math functions that don't quite have enough totality to have their own home namespace just yet." (:require [clojure.math.numeric-tower :as math] [aerial.utils.coll :refer [transpose reducem take-until]])) ;;; ----------------------------------------------------------------- ;;; Various ancillary math/arithmetic stuff. (defn div "Integer division. Return [q r], such that floor(n / d) * q + r = q" [n d] (let [q (math/floor (/ n d))] [q (rem n d)])) (defn sum "Return the sum of the numbers in COLL. If COLL is a map, return the sum of the (presumed all numbers) in (vals coll). For function F versions, return the sum x in COLL (f x) or sum x in COLL1, y in COLL2 (f x y) or sum x1 in C1, x2 in C2, ... xn in Cn (f x1 ... xn). By default, summation proceeds on the results of F applied over the _cross product_ of the collections. If summation should proceed over the collections in parallel, the first \"coll\" given should be the special keyword :||. If given this causes F to be applied to the elements of colls as stepped in parallel: f(coll1[i] coll2[i] .. colln[i]), i in [0 .. (count smallest-given-coll)]. Examples: (sum + [1 2 3] [1 2 3]) => 36 ; sum of all [1 2 3] X [1 2 3] pairwise sums (sum + :|| [1 2 3] [1 2 3]) => 12 ; sum of [(+ 1 1) (+ 2 2) (+ 3 3)] (sum (fn[x y] (* x (log2 y))) :|| [1 2 3] [1 2 3]) => 6.754887502163469 " ([coll] (let [vs (if (map? coll) (vals coll) coll)] (apply +' vs))) ([f coll] (reducem f +' coll)) ([f coll1 coll2 & colls] (let [colls (cons coll2 colls)] (apply reducem f +' coll1 colls)))) (defn cumsum "Cumulative sum of values in COLL. If COLL is a map, return the cumulative sum of the (presumed all numbers) in (vals coll). For function F versions, return the cumulative sum of x in COLL (f x) or the cumulative sum of x1 in COLL1, x2 in COLL2, ... xn in COLLn (f x1 ... xn). The cumulative sum is the seq of partial sums across COLL treated as a vector for each (i (range (count COLL))), effectively: [(coll 0) (sum (subvec coll 0 2)) .. (sum (subvec coll 0 (count coll)))] Except actual computational time is linear. " ([coll] (let [cv (vec (if (map? coll) (vals coll) coll)) c0 (cv 0)] (first (reduce (fn[[v s] x] (let [s (+ s x)] [(conj v s) s])) [[c0] c0] (rest cv))))) ([f coll] (cumsum (map f coll))) ([f coll1 coll2 & colls] (cumsum (apply map f coll1 coll2 colls)))) (defn prod "Return the product of the numbers in COLL. If COLL is a map, return the product of the (presumed all numbers) in (vals coll). For function F versions, return the product of x in COLL (f x) or prod x in COLL1, y in COLL2 (f x y) or prod x1 in C1, x2 in C2, ... xn in Cn (f x1 ... xn). By default, multiplication proceeds on the results of F applied over the _cross product_ of the collections. If multiplication should proceed over the collections in parallel, the first \"coll\" given should be the special keyword :||. If given, this causes F to be applied to the elements of colls as stepped in parallel: f(coll1[i] coll2[i] .. colln[i]), i in [0 .. (count smallest-coll)]. Examples: (prod + [1 2 3] [1 2 3]) => 172800 ; product of all [1 2 3] X [1 2 3] pairwise sums (prod + :|| [1 2 3] [1 2 3]) => 48 ; product of [(+ 1 1) (+ 2 2) (+ 3 3)] " ([coll] (let [vs (if (map? coll) (vals coll) coll)] (apply *' vs))) ([f coll] (reducem f *' coll)) ([f coll1 coll2 & colls] (let [colls (cons coll2 colls)] (apply reducem f *' coll1 colls)))) (defn sqr "Square x, i.e., returns (* x x)" [x] (*' x x)) (defn logb "Return the log to the base b _function_ of x" [b] (let [lnb (Math/log b)] (fn[x] (/ (Math/log x) lnb)))) (defn log "Return the natural log of x" [x] (Math/log x)) (defn ln "Return the natural log of x" [x] (Math/log x)) (def ^{:doc "Named version of (logb 2). Important enough to have a named top level function" :arglists '([x])} log2 (logb 2)) (def ^{:doc "Named version of (logb 10). Important enough to have a named top level function" :arglists '([x])} log10 (logb 10)) (defn logistic "Compute logistic of X (a number which will be cast as a double. Returns 1.0 / (1.0 + e^-x) = e^x / (e^x + 1.0) " [x] (let [ex (math/expt Math/E (double x))] (/ ex (+ ex 1.0)))) (defn logit "Compute the log odds of P an element of interval [0..1]. LOGFN is the logarithmic function to use and defaults to log2, log base 2. Other directly available log functions are ln (or simply log) and log10; for any other base see logb which can generate a log function of base b. Returns logfn (p / (1 - p)), the inverse of logistic. " [p & {:keys [logfn] :or {logfn log2}}] (logfn (/ p (- 1 p)))) (defn primes "RHickey paste.lisp.org with some fixes by jsa. Returns a list of all primes from 2 to n. Wicked fast!" [n] (if (< n 2) () (let [n (long n)] (let [root (long (Math/round (Math/floor (Math/sqrt n))))] (loop [i (long 3) a (int-array (inc n)) result (list 2)] (if (> i n) (reverse result) (recur (+ i (long 2)) (if (<= i root) (loop [arr a inc (+ i i) j (* i i)] (if (> j n) arr (recur (do (aset arr j (long 1)) arr) inc (+ j inc)))) a) (if (zero? (aget a i)) (conj result i) result)))))))) (def +prime-set+ (atom (primes 1000))) (defn prime-factors "Return the prime factorization of num as a seq of pairs [p n], where p is a prime and n is the number of times it is a factor. Ex: (prime-factors 510) => [[2 1] [3 1] [5 1] [17 1]] " [num] (if (< num 2) num (do (when (> num (last @+prime-set+)) (swap! +prime-set+ (fn[_](primes (+ num (long (/ num 2))))))) (loop [ps (take-until #(> % num) @+prime-set+) factors []] (if (empty? ps) factors (let [pf (loop [n num cnt 0] (let [f (first ps) [q r] (div n f)] (if (not= 0 r) (when (> cnt 0) [f cnt]) (recur q (inc cnt)))))] (recur (rest ps) (if pf (conj factors pf) factors)))))))) ;;; ----------------------------------------------------------------- ;;; Simple vector stuff. dot product, norm, distances, and such. Is ;;; all this stuff in Incanter?? (defn dot [v1 v2] (double (reduce + 0.0 (map * v1 v2)))) (defn norm [v] (math/sqrt (dot v v))) (defn vhat [v] (let [n (norm v)] (vec (map #(/ % n) v)))) (defn cos-vangle [v1 v2] (dot (vhat v1) (vhat v2))) (defn vangle-dist [v1 v2] (math/abs (dec (cos-vangle v1 v2)))) (defn vecdist [v1 v2] (let [v (map - v1 v2)] (math/sqrt (dot v v)))) (defn vecmean ([v1 v2] (map #(/ (+ %1 %2) 2) v1 v2)) ([vs] (let [d (count vs)] (map (fn[xs] (/ (apply + xs) d)) (transpose vs)))))
true
;;--------------------------------------------------------------------------;; ;; ;; ;; U T I L S . M A T H ;; ;; ;; ;; 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 aerial.utils.math "Various math functions that don't quite have enough totality to have their own home namespace just yet." (:require [clojure.math.numeric-tower :as math] [aerial.utils.coll :refer [transpose reducem take-until]])) ;;; ----------------------------------------------------------------- ;;; Various ancillary math/arithmetic stuff. (defn div "Integer division. Return [q r], such that floor(n / d) * q + r = q" [n d] (let [q (math/floor (/ n d))] [q (rem n d)])) (defn sum "Return the sum of the numbers in COLL. If COLL is a map, return the sum of the (presumed all numbers) in (vals coll). For function F versions, return the sum x in COLL (f x) or sum x in COLL1, y in COLL2 (f x y) or sum x1 in C1, x2 in C2, ... xn in Cn (f x1 ... xn). By default, summation proceeds on the results of F applied over the _cross product_ of the collections. If summation should proceed over the collections in parallel, the first \"coll\" given should be the special keyword :||. If given this causes F to be applied to the elements of colls as stepped in parallel: f(coll1[i] coll2[i] .. colln[i]), i in [0 .. (count smallest-given-coll)]. Examples: (sum + [1 2 3] [1 2 3]) => 36 ; sum of all [1 2 3] X [1 2 3] pairwise sums (sum + :|| [1 2 3] [1 2 3]) => 12 ; sum of [(+ 1 1) (+ 2 2) (+ 3 3)] (sum (fn[x y] (* x (log2 y))) :|| [1 2 3] [1 2 3]) => 6.754887502163469 " ([coll] (let [vs (if (map? coll) (vals coll) coll)] (apply +' vs))) ([f coll] (reducem f +' coll)) ([f coll1 coll2 & colls] (let [colls (cons coll2 colls)] (apply reducem f +' coll1 colls)))) (defn cumsum "Cumulative sum of values in COLL. If COLL is a map, return the cumulative sum of the (presumed all numbers) in (vals coll). For function F versions, return the cumulative sum of x in COLL (f x) or the cumulative sum of x1 in COLL1, x2 in COLL2, ... xn in COLLn (f x1 ... xn). The cumulative sum is the seq of partial sums across COLL treated as a vector for each (i (range (count COLL))), effectively: [(coll 0) (sum (subvec coll 0 2)) .. (sum (subvec coll 0 (count coll)))] Except actual computational time is linear. " ([coll] (let [cv (vec (if (map? coll) (vals coll) coll)) c0 (cv 0)] (first (reduce (fn[[v s] x] (let [s (+ s x)] [(conj v s) s])) [[c0] c0] (rest cv))))) ([f coll] (cumsum (map f coll))) ([f coll1 coll2 & colls] (cumsum (apply map f coll1 coll2 colls)))) (defn prod "Return the product of the numbers in COLL. If COLL is a map, return the product of the (presumed all numbers) in (vals coll). For function F versions, return the product of x in COLL (f x) or prod x in COLL1, y in COLL2 (f x y) or prod x1 in C1, x2 in C2, ... xn in Cn (f x1 ... xn). By default, multiplication proceeds on the results of F applied over the _cross product_ of the collections. If multiplication should proceed over the collections in parallel, the first \"coll\" given should be the special keyword :||. If given, this causes F to be applied to the elements of colls as stepped in parallel: f(coll1[i] coll2[i] .. colln[i]), i in [0 .. (count smallest-coll)]. Examples: (prod + [1 2 3] [1 2 3]) => 172800 ; product of all [1 2 3] X [1 2 3] pairwise sums (prod + :|| [1 2 3] [1 2 3]) => 48 ; product of [(+ 1 1) (+ 2 2) (+ 3 3)] " ([coll] (let [vs (if (map? coll) (vals coll) coll)] (apply *' vs))) ([f coll] (reducem f *' coll)) ([f coll1 coll2 & colls] (let [colls (cons coll2 colls)] (apply reducem f *' coll1 colls)))) (defn sqr "Square x, i.e., returns (* x x)" [x] (*' x x)) (defn logb "Return the log to the base b _function_ of x" [b] (let [lnb (Math/log b)] (fn[x] (/ (Math/log x) lnb)))) (defn log "Return the natural log of x" [x] (Math/log x)) (defn ln "Return the natural log of x" [x] (Math/log x)) (def ^{:doc "Named version of (logb 2). Important enough to have a named top level function" :arglists '([x])} log2 (logb 2)) (def ^{:doc "Named version of (logb 10). Important enough to have a named top level function" :arglists '([x])} log10 (logb 10)) (defn logistic "Compute logistic of X (a number which will be cast as a double. Returns 1.0 / (1.0 + e^-x) = e^x / (e^x + 1.0) " [x] (let [ex (math/expt Math/E (double x))] (/ ex (+ ex 1.0)))) (defn logit "Compute the log odds of P an element of interval [0..1]. LOGFN is the logarithmic function to use and defaults to log2, log base 2. Other directly available log functions are ln (or simply log) and log10; for any other base see logb which can generate a log function of base b. Returns logfn (p / (1 - p)), the inverse of logistic. " [p & {:keys [logfn] :or {logfn log2}}] (logfn (/ p (- 1 p)))) (defn primes "RHickey paste.lisp.org with some fixes by jsa. Returns a list of all primes from 2 to n. Wicked fast!" [n] (if (< n 2) () (let [n (long n)] (let [root (long (Math/round (Math/floor (Math/sqrt n))))] (loop [i (long 3) a (int-array (inc n)) result (list 2)] (if (> i n) (reverse result) (recur (+ i (long 2)) (if (<= i root) (loop [arr a inc (+ i i) j (* i i)] (if (> j n) arr (recur (do (aset arr j (long 1)) arr) inc (+ j inc)))) a) (if (zero? (aget a i)) (conj result i) result)))))))) (def +prime-set+ (atom (primes 1000))) (defn prime-factors "Return the prime factorization of num as a seq of pairs [p n], where p is a prime and n is the number of times it is a factor. Ex: (prime-factors 510) => [[2 1] [3 1] [5 1] [17 1]] " [num] (if (< num 2) num (do (when (> num (last @+prime-set+)) (swap! +prime-set+ (fn[_](primes (+ num (long (/ num 2))))))) (loop [ps (take-until #(> % num) @+prime-set+) factors []] (if (empty? ps) factors (let [pf (loop [n num cnt 0] (let [f (first ps) [q r] (div n f)] (if (not= 0 r) (when (> cnt 0) [f cnt]) (recur q (inc cnt)))))] (recur (rest ps) (if pf (conj factors pf) factors)))))))) ;;; ----------------------------------------------------------------- ;;; Simple vector stuff. dot product, norm, distances, and such. Is ;;; all this stuff in Incanter?? (defn dot [v1 v2] (double (reduce + 0.0 (map * v1 v2)))) (defn norm [v] (math/sqrt (dot v v))) (defn vhat [v] (let [n (norm v)] (vec (map #(/ % n) v)))) (defn cos-vangle [v1 v2] (dot (vhat v1) (vhat v2))) (defn vangle-dist [v1 v2] (math/abs (dec (cos-vangle v1 v2)))) (defn vecdist [v1 v2] (let [v (map - v1 v2)] (math/sqrt (dot v v)))) (defn vecmean ([v1 v2] (map #(/ (+ %1 %2) 2) v1 v2)) ([vs] (let [d (count vs)] (map (fn[xs] (/ (apply + xs) d)) (transpose vs)))))
[ { "context": "s\n ^{:doc \"AST dumper diagnostic tool.\", :author \"Sean Dawson\"}\n nanoweave.diagnostics.ast-dumper\n (:require\n ", "end": 63, "score": 0.9998567700386047, "start": 52, "tag": "NAME", "value": "Sean Dawson" } ]
src/nanoweave/diagnostics/ast_dumper.clj
NoxHarmonium/nanoweave
0
(ns ^{:doc "AST dumper diagnostic tool.", :author "Sean Dawson"} nanoweave.diagnostics.ast-dumper (:require [rhizome.viz :as r] [nanoweave.utils :refer [read-json-with-doubles]] [nanoweave.transformers.file-transformer :as transformer] [clojure.pprint :as pp]) (:import (nanoweave.ast.literals StringLit FloatLit BoolLit NilLit ArrayLit))) (defn- primative-lit? [val] (or (instance? StringLit val) (instance? FloatLit val) (instance? BoolLit val))) (defn- decend-map? [map] (not (primative-lit? map))) (defn- decend? [val] (or (and (map? val) (decend-map? val)) (vector? val))) (defn- decend [val] (if (map? val) (vals val) (seq val))) (defn- describe-node [node] {:label (if (map? node) (cond (primative-lit? node) (:value node) :else (type node)) (cond (instance? java.lang.String node) node :else (type node)))}) (defn- describe-edge [src, dest] {:label (cond (map? src) (first (map (fn [[k _]] k) (filter (fn [[_ v]] (= v dest)) src))) (vector? src) (.indexOf src dest))}) (defn- ast-map-to-graphviz [ast filename] (pp/pprint ast) (r/save-tree decend? decend ast :filename filename :node->descriptor describe-node :edge->descriptor describe-edge)) ; No-op (defn- process-ast [ast _] ast) (defn dump-ast-as-graphviz "Takes an input file and a nanoweave definition and outputs a graphical representation of the AST in PNG format to the output file" [input-file output-file nweave-file] (let [input (read-json-with-doubles (slurp input-file)) nweave (slurp nweave-file) output (transformer/transform input nweave process-ast)] (ast-map-to-graphviz output output-file) ; For some reason rhizome keeps the app open (System/exit 0)))
18501
(ns ^{:doc "AST dumper diagnostic tool.", :author "<NAME>"} nanoweave.diagnostics.ast-dumper (:require [rhizome.viz :as r] [nanoweave.utils :refer [read-json-with-doubles]] [nanoweave.transformers.file-transformer :as transformer] [clojure.pprint :as pp]) (:import (nanoweave.ast.literals StringLit FloatLit BoolLit NilLit ArrayLit))) (defn- primative-lit? [val] (or (instance? StringLit val) (instance? FloatLit val) (instance? BoolLit val))) (defn- decend-map? [map] (not (primative-lit? map))) (defn- decend? [val] (or (and (map? val) (decend-map? val)) (vector? val))) (defn- decend [val] (if (map? val) (vals val) (seq val))) (defn- describe-node [node] {:label (if (map? node) (cond (primative-lit? node) (:value node) :else (type node)) (cond (instance? java.lang.String node) node :else (type node)))}) (defn- describe-edge [src, dest] {:label (cond (map? src) (first (map (fn [[k _]] k) (filter (fn [[_ v]] (= v dest)) src))) (vector? src) (.indexOf src dest))}) (defn- ast-map-to-graphviz [ast filename] (pp/pprint ast) (r/save-tree decend? decend ast :filename filename :node->descriptor describe-node :edge->descriptor describe-edge)) ; No-op (defn- process-ast [ast _] ast) (defn dump-ast-as-graphviz "Takes an input file and a nanoweave definition and outputs a graphical representation of the AST in PNG format to the output file" [input-file output-file nweave-file] (let [input (read-json-with-doubles (slurp input-file)) nweave (slurp nweave-file) output (transformer/transform input nweave process-ast)] (ast-map-to-graphviz output output-file) ; For some reason rhizome keeps the app open (System/exit 0)))
true
(ns ^{:doc "AST dumper diagnostic tool.", :author "PI:NAME:<NAME>END_PI"} nanoweave.diagnostics.ast-dumper (:require [rhizome.viz :as r] [nanoweave.utils :refer [read-json-with-doubles]] [nanoweave.transformers.file-transformer :as transformer] [clojure.pprint :as pp]) (:import (nanoweave.ast.literals StringLit FloatLit BoolLit NilLit ArrayLit))) (defn- primative-lit? [val] (or (instance? StringLit val) (instance? FloatLit val) (instance? BoolLit val))) (defn- decend-map? [map] (not (primative-lit? map))) (defn- decend? [val] (or (and (map? val) (decend-map? val)) (vector? val))) (defn- decend [val] (if (map? val) (vals val) (seq val))) (defn- describe-node [node] {:label (if (map? node) (cond (primative-lit? node) (:value node) :else (type node)) (cond (instance? java.lang.String node) node :else (type node)))}) (defn- describe-edge [src, dest] {:label (cond (map? src) (first (map (fn [[k _]] k) (filter (fn [[_ v]] (= v dest)) src))) (vector? src) (.indexOf src dest))}) (defn- ast-map-to-graphviz [ast filename] (pp/pprint ast) (r/save-tree decend? decend ast :filename filename :node->descriptor describe-node :edge->descriptor describe-edge)) ; No-op (defn- process-ast [ast _] ast) (defn dump-ast-as-graphviz "Takes an input file and a nanoweave definition and outputs a graphical representation of the AST in PNG format to the output file" [input-file output-file nweave-file] (let [input (read-json-with-doubles (slurp input-file)) nweave (slurp nweave-file) output (transformer/transform input nweave process-ast)] (ast-map-to-graphviz output output-file) ; For some reason rhizome keeps the app open (System/exit 0)))
[ { "context": "License\n\nFor js-joda software\n\nCopyright (c) 2016, Philipp Thürwächter & Pattrick Hüper\n \nAll rights reserved.\n \nRedistr", "end": 1737, "score": 0.9998714327812195, "start": 1718, "tag": "NAME", "value": "Philipp Thürwächter" }, { "context": "oftware\n\nCopyright (c) 2016, Philipp Thürwächter & Pattrick Hüper\n \nAll rights reserved.\n \nRedistribution and use i", "end": 1754, "score": 0.9998754858970642, "start": 1740, "tag": "NAME", "value": "Pattrick Hüper" } ]
src/cljs/wkok/buy2let/legal/opensource/bsd.cljs
wkok/re-frame-buy2let
0
(ns wkok.buy2let.legal.opensource.bsd) (def bsd-3 {:name "BSD 3-Clause License" :text " BSD 3-Clause License Copyright (c) [year], [fullname] All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."}) (def bsd {:name "BSD License" :text " BSD License For js-joda software Copyright (c) 2016, Philipp Thürwächter & Pattrick Hüper 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. * Neither the name of js-joda nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."})
104806
(ns wkok.buy2let.legal.opensource.bsd) (def bsd-3 {:name "BSD 3-Clause License" :text " BSD 3-Clause License Copyright (c) [year], [fullname] All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."}) (def bsd {:name "BSD License" :text " BSD License For js-joda software Copyright (c) 2016, <NAME> & <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. * Neither the name of js-joda nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."})
true
(ns wkok.buy2let.legal.opensource.bsd) (def bsd-3 {:name "BSD 3-Clause License" :text " BSD 3-Clause License Copyright (c) [year], [fullname] All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."}) (def bsd {:name "BSD License" :text " BSD License For js-joda software Copyright (c) 2016, PI:NAME:<NAME>END_PI & 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. * Neither the name of js-joda nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."})
[ { "context": "thod nvpm]\n (let [m (assoc nvpm\n :user user\n :pwd password\n :signature ", "end": 196, "score": 0.9677543044090271, "start": 192, "tag": "USERNAME", "value": "user" }, { "context": "assoc nvpm\n :user user\n :pwd password\n :signature key\n :version v", "end": 222, "score": 0.9990173578262329, "start": 214, "tag": "PASSWORD", "value": "password" }, { "context": "serid user\n :x-paypal-security-password password\n :x-paypal-security-signature key\n ", "end": 550, "score": 0.9990594983100891, "start": 542, "tag": "PASSWORD", "value": "password" } ]
src/zutil/paypal.clj
zakwilson/zutil-clj
5
(ns zutil.paypal (:refer-clojure :exclude [get]) (:use clj-http.client zutil.web)) (defn make-paypal-query [user password key version method nvpm] (let [m (assoc nvpm :user user :pwd password :signature key :version version) q (str "method=" method "&" (map->query m))] q)) (defn make-adaptivepayments-query [user password key version method appid nvpm] (let [m (assoc nvpm :x-paypal-security-userid user :x-paypal-security-password password :x-paypal-security-signature key :x-paypal-service-version version :x-paypal-application-id appid :x-paypal-request-data-format "nv" :x-paypal-response-data-format "nv") q (str "method=" method "&" (map->query m))] q))
92804
(ns zutil.paypal (:refer-clojure :exclude [get]) (:use clj-http.client zutil.web)) (defn make-paypal-query [user password key version method nvpm] (let [m (assoc nvpm :user user :pwd <PASSWORD> :signature key :version version) q (str "method=" method "&" (map->query m))] q)) (defn make-adaptivepayments-query [user password key version method appid nvpm] (let [m (assoc nvpm :x-paypal-security-userid user :x-paypal-security-password <PASSWORD> :x-paypal-security-signature key :x-paypal-service-version version :x-paypal-application-id appid :x-paypal-request-data-format "nv" :x-paypal-response-data-format "nv") q (str "method=" method "&" (map->query m))] q))
true
(ns zutil.paypal (:refer-clojure :exclude [get]) (:use clj-http.client zutil.web)) (defn make-paypal-query [user password key version method nvpm] (let [m (assoc nvpm :user user :pwd PI:PASSWORD:<PASSWORD>END_PI :signature key :version version) q (str "method=" method "&" (map->query m))] q)) (defn make-adaptivepayments-query [user password key version method appid nvpm] (let [m (assoc nvpm :x-paypal-security-userid user :x-paypal-security-password PI:PASSWORD:<PASSWORD>END_PI :x-paypal-security-signature key :x-paypal-service-version version :x-paypal-application-id appid :x-paypal-request-data-format "nv" :x-paypal-response-data-format "nv") q (str "method=" method "&" (map->query m))] q))
[ { "context": ")\n \"Hello joe\" \"Hello $name$\" {\"name\" \"joe\"}\n 'foo-baz 'foo-$name$ {\"name\" \"baz\"}", "end": 877, "score": 0.9591983556747437, "start": 874, "tag": "NAME", "value": "joe" } ]
src/me/zzp/sqlet/id.clj
redraiment/sqlet
1
(ns me.zzp.sqlet.id "标识(identifier)相关函数 包括:symbol、keyword、namespace" (:require [clojure [string :as cs] [test :refer [are]]])) (defn ns? "是否为Clojure命名空间对象" [o] (instance? clojure.lang.Namespace o)) (defn id? "字符串或符号或关键字或命名空间" [o] (or (string? o) (symbol? o) (keyword? o) (ns? o))) (def symbolf "symbol + format" (comp symbol format)) (def keywordf "keyword + format" (comp keyword format)) (def nsf "namespace + format" (comp the-ns symbolf)) (defn id "提取tag的字符串名字" [o] (cond (keyword? o) (name o) (ns? o) (str (ns-name o)) :else (str o))) (def placeholder #"\$([-_0-9a-zA-Z]+)\$") (defn interpolate "类似字符串插值 用 smap 中的映射替换目标中 /$[-_0-9a-zA-Z]+$/ 形式的占位符" {:test #(are [expected id smap] (= expected (interpolate smap id)) "Hello joe" "Hello $name$" {"name" "joe"} 'foo-baz 'foo-$name$ {"name" "baz"} :foo-baz :foo-$name$ {"name" "baz"})} [smap o] (let [name (id o)] (cond (and (symbol? o) (re-matches placeholder name)) (smap (cs/replace name #"\$" "")) (id? o) ((cond (symbol? o) symbol (keyword? o) keyword (ns? o) nsf :else identity) (cs/replace name placeholder (comp str smap second))) :else o)))
41992
(ns me.zzp.sqlet.id "标识(identifier)相关函数 包括:symbol、keyword、namespace" (:require [clojure [string :as cs] [test :refer [are]]])) (defn ns? "是否为Clojure命名空间对象" [o] (instance? clojure.lang.Namespace o)) (defn id? "字符串或符号或关键字或命名空间" [o] (or (string? o) (symbol? o) (keyword? o) (ns? o))) (def symbolf "symbol + format" (comp symbol format)) (def keywordf "keyword + format" (comp keyword format)) (def nsf "namespace + format" (comp the-ns symbolf)) (defn id "提取tag的字符串名字" [o] (cond (keyword? o) (name o) (ns? o) (str (ns-name o)) :else (str o))) (def placeholder #"\$([-_0-9a-zA-Z]+)\$") (defn interpolate "类似字符串插值 用 smap 中的映射替换目标中 /$[-_0-9a-zA-Z]+$/ 形式的占位符" {:test #(are [expected id smap] (= expected (interpolate smap id)) "Hello joe" "Hello $name$" {"name" "<NAME>"} 'foo-baz 'foo-$name$ {"name" "baz"} :foo-baz :foo-$name$ {"name" "baz"})} [smap o] (let [name (id o)] (cond (and (symbol? o) (re-matches placeholder name)) (smap (cs/replace name #"\$" "")) (id? o) ((cond (symbol? o) symbol (keyword? o) keyword (ns? o) nsf :else identity) (cs/replace name placeholder (comp str smap second))) :else o)))
true
(ns me.zzp.sqlet.id "标识(identifier)相关函数 包括:symbol、keyword、namespace" (:require [clojure [string :as cs] [test :refer [are]]])) (defn ns? "是否为Clojure命名空间对象" [o] (instance? clojure.lang.Namespace o)) (defn id? "字符串或符号或关键字或命名空间" [o] (or (string? o) (symbol? o) (keyword? o) (ns? o))) (def symbolf "symbol + format" (comp symbol format)) (def keywordf "keyword + format" (comp keyword format)) (def nsf "namespace + format" (comp the-ns symbolf)) (defn id "提取tag的字符串名字" [o] (cond (keyword? o) (name o) (ns? o) (str (ns-name o)) :else (str o))) (def placeholder #"\$([-_0-9a-zA-Z]+)\$") (defn interpolate "类似字符串插值 用 smap 中的映射替换目标中 /$[-_0-9a-zA-Z]+$/ 形式的占位符" {:test #(are [expected id smap] (= expected (interpolate smap id)) "Hello joe" "Hello $name$" {"name" "PI:NAME:<NAME>END_PI"} 'foo-baz 'foo-$name$ {"name" "baz"} :foo-baz :foo-$name$ {"name" "baz"})} [smap o] (let [name (id o)] (cond (and (symbol? o) (re-matches placeholder name)) (smap (cs/replace name #"\$" "")) (id? o) ((cond (symbol? o) symbol (keyword? o) keyword (ns? o) nsf :else identity) (cs/replace name placeholder (comp str smap second))) :else o)))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998111128807068, "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.9998236298561096, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/test/editor/gl/vertex_test.clj
cmarincia/defold
0
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 Ragnar Svensson, Christian Murray ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns editor.gl.vertex-test (:require [clojure.test :refer :all] [support.test-support :refer [array=]] [editor.buffers :as b] [editor.gl.vertex :as v]) (:import [com.google.protobuf ByteString])) (defn- contents-of [vb] (let [bb (.asReadOnlyBuffer (.buffer vb)) arr (byte-array (.limit bb))] (.rewind bb) (.get bb arr) arr)) (defn- print-buffer [b cols] (let [fmt (clojure.string/join " " (repeat cols "%02X ")) rows (partition cols (seq (contents-of b)))] (doseq [r rows] (println (apply format fmt r))))) (v/defvertex one-d-position-only (vec1.byte location)) (v/defvertex two-d-position (vec2.byte position)) (v/defvertex two-d-position-short (vec2.short position)) (v/defvertex short-byte-byte (vec2.byte bite) (vec2.short shorty) (vec1.byte nibble)) (v/defvertex short-short :interleaved (vec1.short u) (vec1.short v)) (v/defvertex short-short-chunky :chunked (vec1.short u) (vec1.short v)) (deftest vertex-contains-correct-data (let [vertex-buffer (->one-d-position-only 1)] (conj! vertex-buffer [42]) (testing "what goes in comes out" (is (= [42] (get vertex-buffer 0))) (is (= 1 (count vertex-buffer))) (is (array= (byte-array [42]) (contents-of vertex-buffer)))) (testing "once made persistent, the data is still there" (let [final (persistent! vertex-buffer)] (is (= [42] (get final 0))) (is (= 1 (count final))) (is (array= (byte-array [42]) (contents-of final))))))) (defn- laid-out-as [def into-seq expected-vec] (let [ctor (symbol (str "->" (:name def))) dims (reduce + (map second (:attributes def))) buf ((ns-resolve 'editor.gl.vertex-test ctor) (/ (count into-seq) dims))] (doseq [x (partition dims into-seq)] (conj! buf x)) (array= (byte-array expected-vec) (contents-of buf)))) (deftest memory-layouts (is (laid-out-as one-d-position-only (range 10) [0 1 2 3 4 5 6 7 8 9])) (is (laid-out-as two-d-position (range 20) [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19])) (is (laid-out-as two-d-position-short (range 20) [0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10 0 11 0 12 0 13 0 14 0 15 0 16 0 17 0 18 0 19 0])) (is (laid-out-as short-byte-byte (interleave (range 0x10 0x18) (range 0x20 0x28) (range 0x100 0x108) (range 0x200 0x208) (map unchecked-byte (range 0x80 0x88))) [;byte byte short short byte 0x10 0x20 0x00 0x01 0x00 0x02 0x80 0x11 0x21 0x01 0x01 0x01 0x02 0x81 0x12 0x22 0x02 0x01 0x02 0x02 0x82 0x13 0x23 0x03 0x01 0x03 0x02 0x83 0x14 0x24 0x04 0x01 0x04 0x02 0x84 0x15 0x25 0x05 0x01 0x05 0x02 0x85 0x16 0x26 0x06 0x01 0x06 0x02 0x86 0x17 0x27 0x07 0x01 0x07 0x02 0x87])) (is (laid-out-as short-short (interleave (range 0x188 0x190) (map unchecked-short (range 0x9000 0x9002))) [;short ;short 0x88 0x01 0x00 0x90 ;; u0 v0 0x89 0x01 0x01 0x90 ;; u1 v1 ])) (is (laid-out-as short-short-chunky (interleave (range 0x188 0x190) (map unchecked-short (range 0x9000 0x9002))) [0x88 0x01 0x89 0x01 ;; u0 u1 0x00 0x90 0x01 0x90 ;; v0 v1 ]))) (deftest attributes-compiled-correctly (is (= [['location 1 'byte]] (:attributes one-d-position-only)))) (v/defvertex four-d-position-and-2d-texture (vec4.float position) (vec2.float texcoord)) (deftest four-two-vertex-contains-correct-data (let [vertex-buffer (->four-d-position-and-2d-texture 2) vertex-1 [100.0 101.0 102.0 103.0 150.0 151.0] vertex-2 [200.0 201.0 202.0 203.0 250.0 251.0]] (conj! vertex-buffer vertex-1) (is (= 1 (count vertex-buffer))) (conj! vertex-buffer vertex-2) (is (= 2 (count vertex-buffer))) (is (= vertex-1 (get vertex-buffer 0))) (is (= vertex-2 (get vertex-buffer 1))))) (deftest byte-pack (testing "returns a ByteString containing contents before current position" (are [expected vertex-buffer] (array= (byte-array expected) (.toByteArray (b/byte-pack vertex-buffer))) [0 0 0 0] (reduce conj! (->two-d-position 2) []) [1 2 0 0] (reduce conj! (->two-d-position 2) [[1 2]]) [1 2 3 4] (reduce conj! (->two-d-position 2) [[1 2] [3 4]]) [0 0 0 0] (persistent! (reduce conj! (->two-d-position 2) [])) [1 2 0 0] (persistent! (reduce conj! (->two-d-position 2) [[1 2]])) [1 2 3 4] (persistent! (reduce conj! (->two-d-position 2) [[1 2] [3 4]])))) (testing "multiple calls to byte-pack return the same value" (are [vertex-buffer] (let [vertex-buffer-val vertex-buffer byte-string1 (b/byte-pack vertex-buffer-val) byte-string2 (b/byte-pack vertex-buffer-val)] (array= (.toByteArray byte-string1) (.toByteArray byte-string2))) (reduce conj! (->two-d-position 2) []) (reduce conj! (->two-d-position 2) [[1 2]]) (reduce conj! (->two-d-position 2) [[1 2] [3 4]]) (persistent! (reduce conj! (->two-d-position 2) [])) (persistent! (reduce conj! (->two-d-position 2) [[1 2]])) (persistent! (reduce conj! (->two-d-position 2) [[1 2] [3 4]])))))
113439
;; 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.gl.vertex-test (:require [clojure.test :refer :all] [support.test-support :refer [array=]] [editor.buffers :as b] [editor.gl.vertex :as v]) (:import [com.google.protobuf ByteString])) (defn- contents-of [vb] (let [bb (.asReadOnlyBuffer (.buffer vb)) arr (byte-array (.limit bb))] (.rewind bb) (.get bb arr) arr)) (defn- print-buffer [b cols] (let [fmt (clojure.string/join " " (repeat cols "%02X ")) rows (partition cols (seq (contents-of b)))] (doseq [r rows] (println (apply format fmt r))))) (v/defvertex one-d-position-only (vec1.byte location)) (v/defvertex two-d-position (vec2.byte position)) (v/defvertex two-d-position-short (vec2.short position)) (v/defvertex short-byte-byte (vec2.byte bite) (vec2.short shorty) (vec1.byte nibble)) (v/defvertex short-short :interleaved (vec1.short u) (vec1.short v)) (v/defvertex short-short-chunky :chunked (vec1.short u) (vec1.short v)) (deftest vertex-contains-correct-data (let [vertex-buffer (->one-d-position-only 1)] (conj! vertex-buffer [42]) (testing "what goes in comes out" (is (= [42] (get vertex-buffer 0))) (is (= 1 (count vertex-buffer))) (is (array= (byte-array [42]) (contents-of vertex-buffer)))) (testing "once made persistent, the data is still there" (let [final (persistent! vertex-buffer)] (is (= [42] (get final 0))) (is (= 1 (count final))) (is (array= (byte-array [42]) (contents-of final))))))) (defn- laid-out-as [def into-seq expected-vec] (let [ctor (symbol (str "->" (:name def))) dims (reduce + (map second (:attributes def))) buf ((ns-resolve 'editor.gl.vertex-test ctor) (/ (count into-seq) dims))] (doseq [x (partition dims into-seq)] (conj! buf x)) (array= (byte-array expected-vec) (contents-of buf)))) (deftest memory-layouts (is (laid-out-as one-d-position-only (range 10) [0 1 2 3 4 5 6 7 8 9])) (is (laid-out-as two-d-position (range 20) [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19])) (is (laid-out-as two-d-position-short (range 20) [0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10 0 11 0 12 0 13 0 14 0 15 0 16 0 17 0 18 0 19 0])) (is (laid-out-as short-byte-byte (interleave (range 0x10 0x18) (range 0x20 0x28) (range 0x100 0x108) (range 0x200 0x208) (map unchecked-byte (range 0x80 0x88))) [;byte byte short short byte 0x10 0x20 0x00 0x01 0x00 0x02 0x80 0x11 0x21 0x01 0x01 0x01 0x02 0x81 0x12 0x22 0x02 0x01 0x02 0x02 0x82 0x13 0x23 0x03 0x01 0x03 0x02 0x83 0x14 0x24 0x04 0x01 0x04 0x02 0x84 0x15 0x25 0x05 0x01 0x05 0x02 0x85 0x16 0x26 0x06 0x01 0x06 0x02 0x86 0x17 0x27 0x07 0x01 0x07 0x02 0x87])) (is (laid-out-as short-short (interleave (range 0x188 0x190) (map unchecked-short (range 0x9000 0x9002))) [;short ;short 0x88 0x01 0x00 0x90 ;; u0 v0 0x89 0x01 0x01 0x90 ;; u1 v1 ])) (is (laid-out-as short-short-chunky (interleave (range 0x188 0x190) (map unchecked-short (range 0x9000 0x9002))) [0x88 0x01 0x89 0x01 ;; u0 u1 0x00 0x90 0x01 0x90 ;; v0 v1 ]))) (deftest attributes-compiled-correctly (is (= [['location 1 'byte]] (:attributes one-d-position-only)))) (v/defvertex four-d-position-and-2d-texture (vec4.float position) (vec2.float texcoord)) (deftest four-two-vertex-contains-correct-data (let [vertex-buffer (->four-d-position-and-2d-texture 2) vertex-1 [100.0 101.0 102.0 103.0 150.0 151.0] vertex-2 [200.0 201.0 202.0 203.0 250.0 251.0]] (conj! vertex-buffer vertex-1) (is (= 1 (count vertex-buffer))) (conj! vertex-buffer vertex-2) (is (= 2 (count vertex-buffer))) (is (= vertex-1 (get vertex-buffer 0))) (is (= vertex-2 (get vertex-buffer 1))))) (deftest byte-pack (testing "returns a ByteString containing contents before current position" (are [expected vertex-buffer] (array= (byte-array expected) (.toByteArray (b/byte-pack vertex-buffer))) [0 0 0 0] (reduce conj! (->two-d-position 2) []) [1 2 0 0] (reduce conj! (->two-d-position 2) [[1 2]]) [1 2 3 4] (reduce conj! (->two-d-position 2) [[1 2] [3 4]]) [0 0 0 0] (persistent! (reduce conj! (->two-d-position 2) [])) [1 2 0 0] (persistent! (reduce conj! (->two-d-position 2) [[1 2]])) [1 2 3 4] (persistent! (reduce conj! (->two-d-position 2) [[1 2] [3 4]])))) (testing "multiple calls to byte-pack return the same value" (are [vertex-buffer] (let [vertex-buffer-val vertex-buffer byte-string1 (b/byte-pack vertex-buffer-val) byte-string2 (b/byte-pack vertex-buffer-val)] (array= (.toByteArray byte-string1) (.toByteArray byte-string2))) (reduce conj! (->two-d-position 2) []) (reduce conj! (->two-d-position 2) [[1 2]]) (reduce conj! (->two-d-position 2) [[1 2] [3 4]]) (persistent! (reduce conj! (->two-d-position 2) [])) (persistent! (reduce conj! (->two-d-position 2) [[1 2]])) (persistent! (reduce conj! (->two-d-position 2) [[1 2] [3 4]])))))
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.gl.vertex-test (:require [clojure.test :refer :all] [support.test-support :refer [array=]] [editor.buffers :as b] [editor.gl.vertex :as v]) (:import [com.google.protobuf ByteString])) (defn- contents-of [vb] (let [bb (.asReadOnlyBuffer (.buffer vb)) arr (byte-array (.limit bb))] (.rewind bb) (.get bb arr) arr)) (defn- print-buffer [b cols] (let [fmt (clojure.string/join " " (repeat cols "%02X ")) rows (partition cols (seq (contents-of b)))] (doseq [r rows] (println (apply format fmt r))))) (v/defvertex one-d-position-only (vec1.byte location)) (v/defvertex two-d-position (vec2.byte position)) (v/defvertex two-d-position-short (vec2.short position)) (v/defvertex short-byte-byte (vec2.byte bite) (vec2.short shorty) (vec1.byte nibble)) (v/defvertex short-short :interleaved (vec1.short u) (vec1.short v)) (v/defvertex short-short-chunky :chunked (vec1.short u) (vec1.short v)) (deftest vertex-contains-correct-data (let [vertex-buffer (->one-d-position-only 1)] (conj! vertex-buffer [42]) (testing "what goes in comes out" (is (= [42] (get vertex-buffer 0))) (is (= 1 (count vertex-buffer))) (is (array= (byte-array [42]) (contents-of vertex-buffer)))) (testing "once made persistent, the data is still there" (let [final (persistent! vertex-buffer)] (is (= [42] (get final 0))) (is (= 1 (count final))) (is (array= (byte-array [42]) (contents-of final))))))) (defn- laid-out-as [def into-seq expected-vec] (let [ctor (symbol (str "->" (:name def))) dims (reduce + (map second (:attributes def))) buf ((ns-resolve 'editor.gl.vertex-test ctor) (/ (count into-seq) dims))] (doseq [x (partition dims into-seq)] (conj! buf x)) (array= (byte-array expected-vec) (contents-of buf)))) (deftest memory-layouts (is (laid-out-as one-d-position-only (range 10) [0 1 2 3 4 5 6 7 8 9])) (is (laid-out-as two-d-position (range 20) [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19])) (is (laid-out-as two-d-position-short (range 20) [0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10 0 11 0 12 0 13 0 14 0 15 0 16 0 17 0 18 0 19 0])) (is (laid-out-as short-byte-byte (interleave (range 0x10 0x18) (range 0x20 0x28) (range 0x100 0x108) (range 0x200 0x208) (map unchecked-byte (range 0x80 0x88))) [;byte byte short short byte 0x10 0x20 0x00 0x01 0x00 0x02 0x80 0x11 0x21 0x01 0x01 0x01 0x02 0x81 0x12 0x22 0x02 0x01 0x02 0x02 0x82 0x13 0x23 0x03 0x01 0x03 0x02 0x83 0x14 0x24 0x04 0x01 0x04 0x02 0x84 0x15 0x25 0x05 0x01 0x05 0x02 0x85 0x16 0x26 0x06 0x01 0x06 0x02 0x86 0x17 0x27 0x07 0x01 0x07 0x02 0x87])) (is (laid-out-as short-short (interleave (range 0x188 0x190) (map unchecked-short (range 0x9000 0x9002))) [;short ;short 0x88 0x01 0x00 0x90 ;; u0 v0 0x89 0x01 0x01 0x90 ;; u1 v1 ])) (is (laid-out-as short-short-chunky (interleave (range 0x188 0x190) (map unchecked-short (range 0x9000 0x9002))) [0x88 0x01 0x89 0x01 ;; u0 u1 0x00 0x90 0x01 0x90 ;; v0 v1 ]))) (deftest attributes-compiled-correctly (is (= [['location 1 'byte]] (:attributes one-d-position-only)))) (v/defvertex four-d-position-and-2d-texture (vec4.float position) (vec2.float texcoord)) (deftest four-two-vertex-contains-correct-data (let [vertex-buffer (->four-d-position-and-2d-texture 2) vertex-1 [100.0 101.0 102.0 103.0 150.0 151.0] vertex-2 [200.0 201.0 202.0 203.0 250.0 251.0]] (conj! vertex-buffer vertex-1) (is (= 1 (count vertex-buffer))) (conj! vertex-buffer vertex-2) (is (= 2 (count vertex-buffer))) (is (= vertex-1 (get vertex-buffer 0))) (is (= vertex-2 (get vertex-buffer 1))))) (deftest byte-pack (testing "returns a ByteString containing contents before current position" (are [expected vertex-buffer] (array= (byte-array expected) (.toByteArray (b/byte-pack vertex-buffer))) [0 0 0 0] (reduce conj! (->two-d-position 2) []) [1 2 0 0] (reduce conj! (->two-d-position 2) [[1 2]]) [1 2 3 4] (reduce conj! (->two-d-position 2) [[1 2] [3 4]]) [0 0 0 0] (persistent! (reduce conj! (->two-d-position 2) [])) [1 2 0 0] (persistent! (reduce conj! (->two-d-position 2) [[1 2]])) [1 2 3 4] (persistent! (reduce conj! (->two-d-position 2) [[1 2] [3 4]])))) (testing "multiple calls to byte-pack return the same value" (are [vertex-buffer] (let [vertex-buffer-val vertex-buffer byte-string1 (b/byte-pack vertex-buffer-val) byte-string2 (b/byte-pack vertex-buffer-val)] (array= (.toByteArray byte-string1) (.toByteArray byte-string2))) (reduce conj! (->two-d-position 2) []) (reduce conj! (->two-d-position 2) [[1 2]]) (reduce conj! (->two-d-position 2) [[1 2] [3 4]]) (persistent! (reduce conj! (->two-d-position 2) [])) (persistent! (reduce conj! (->two-d-position 2) [[1 2]])) (persistent! (reduce conj! (->two-d-position 2) [[1 2] [3 4]])))))
[ { "context": "(ns\n #^{:author \"Matt Revelle\"\n :doc \"OAuth client library for Clojure.\"}", "end": 32, "score": 0.9998887181282043, "start": 20, "tag": "NAME", "value": "Matt Revelle" } ]
src/oauth/signature.clj
mpenet/clj-oauth
3
(ns #^{:author "Matt Revelle" :doc "OAuth client library for Clojure."} oauth.signature (:require [oauth.digest :as digest] [clojure.string :refer [join]])) (declare rand-str base-string sign url-encode oauth-params) (defn- named? [a] (instance? clojure.lang.Named a)) (defn as-str [a] (if (named? a) (name a) (str a))) (def secure-random (java.security.SecureRandom/getInstance "SHA1PRNG")) (defn rand-str "Random string for OAuth requests." [length] (. (new BigInteger (int (* 5 length)) ^java.util.Random secure-random) toString 32)) (def signature-methods {:hmac-sha1 "HMAC-SHA1" :plaintext "PLAINTEXT"}) (defn url-form-encode [params] (join "&" (map (fn [[k v]] (str (url-encode (as-str k)) "=" (url-encode (as-str v)))) params ))) (defn base-string ([method base-url c t params] (base-string method base-url (assoc params :oauth_consumer_key (:key c) :oauth_token (:token t) :oauth_signature_method (or (params :oauth_signature_method) (signature-methods (:signature-method c))) :oauth_version "1.0"))) ([method base-url params] (join "&" [method (url-encode base-url) (url-encode (url-form-encode (sort params)))]))) (defmulti sign "Sign a base string for authentication." {:arglists '([consumer base-string & [token-secret]])} (fn [c & r] (:signature-method c))) (defmethod sign :hmac-sha1 [c base-string & [token-secret]] (let [key (str (url-encode (:secret c)) "&" (url-encode (or token-secret "")))] (digest/hmac key base-string))) (defmethod sign :plaintext [c base-string & [token-secret]] (str (url-encode (:secret c)) "&" (url-encode (or token-secret "")))) (defn verify [sig c base-string & [token-secret]] (let [token-secret (url-encode (or token-secret ""))] (= sig (sign c base-string token-secret)))) (defn url-encode "The java.net.URLEncoder class encodes for application/x-www-form-urlencoded, but OAuth requires RFC 3986 encoding." [s] (-> (java.net.URLEncoder/encode s "UTF-8") (.replace "+" "%20") (.replace "*" "%2A") (.replace "%7E" "~"))) (defn url-decode "The java.net.URLEncoder class encodes for application/x-www-form-urlencoded, but OAuth requires RFC 3986 encoding." [s] (java.net.URLDecoder/decode s "UTF-8")) (defn oauth-params "Build a map of parameters needed for OAuth requests." ([consumer] {:oauth_consumer_key (:key consumer) :oauth_signature_method (signature-methods (:signature-method consumer)) :oauth_timestamp (int (/ (System/currentTimeMillis) 1000)) :oauth_nonce (rand-str 30) :oauth_version "1.0"}) ([consumer token] (assoc (oauth-params consumer) :oauth_token token)) ([consumer token verifier] (assoc (oauth-params consumer token) :oauth_verifier (str verifier))))
124708
(ns #^{:author "<NAME>" :doc "OAuth client library for Clojure."} oauth.signature (:require [oauth.digest :as digest] [clojure.string :refer [join]])) (declare rand-str base-string sign url-encode oauth-params) (defn- named? [a] (instance? clojure.lang.Named a)) (defn as-str [a] (if (named? a) (name a) (str a))) (def secure-random (java.security.SecureRandom/getInstance "SHA1PRNG")) (defn rand-str "Random string for OAuth requests." [length] (. (new BigInteger (int (* 5 length)) ^java.util.Random secure-random) toString 32)) (def signature-methods {:hmac-sha1 "HMAC-SHA1" :plaintext "PLAINTEXT"}) (defn url-form-encode [params] (join "&" (map (fn [[k v]] (str (url-encode (as-str k)) "=" (url-encode (as-str v)))) params ))) (defn base-string ([method base-url c t params] (base-string method base-url (assoc params :oauth_consumer_key (:key c) :oauth_token (:token t) :oauth_signature_method (or (params :oauth_signature_method) (signature-methods (:signature-method c))) :oauth_version "1.0"))) ([method base-url params] (join "&" [method (url-encode base-url) (url-encode (url-form-encode (sort params)))]))) (defmulti sign "Sign a base string for authentication." {:arglists '([consumer base-string & [token-secret]])} (fn [c & r] (:signature-method c))) (defmethod sign :hmac-sha1 [c base-string & [token-secret]] (let [key (str (url-encode (:secret c)) "&" (url-encode (or token-secret "")))] (digest/hmac key base-string))) (defmethod sign :plaintext [c base-string & [token-secret]] (str (url-encode (:secret c)) "&" (url-encode (or token-secret "")))) (defn verify [sig c base-string & [token-secret]] (let [token-secret (url-encode (or token-secret ""))] (= sig (sign c base-string token-secret)))) (defn url-encode "The java.net.URLEncoder class encodes for application/x-www-form-urlencoded, but OAuth requires RFC 3986 encoding." [s] (-> (java.net.URLEncoder/encode s "UTF-8") (.replace "+" "%20") (.replace "*" "%2A") (.replace "%7E" "~"))) (defn url-decode "The java.net.URLEncoder class encodes for application/x-www-form-urlencoded, but OAuth requires RFC 3986 encoding." [s] (java.net.URLDecoder/decode s "UTF-8")) (defn oauth-params "Build a map of parameters needed for OAuth requests." ([consumer] {:oauth_consumer_key (:key consumer) :oauth_signature_method (signature-methods (:signature-method consumer)) :oauth_timestamp (int (/ (System/currentTimeMillis) 1000)) :oauth_nonce (rand-str 30) :oauth_version "1.0"}) ([consumer token] (assoc (oauth-params consumer) :oauth_token token)) ([consumer token verifier] (assoc (oauth-params consumer token) :oauth_verifier (str verifier))))
true
(ns #^{:author "PI:NAME:<NAME>END_PI" :doc "OAuth client library for Clojure."} oauth.signature (:require [oauth.digest :as digest] [clojure.string :refer [join]])) (declare rand-str base-string sign url-encode oauth-params) (defn- named? [a] (instance? clojure.lang.Named a)) (defn as-str [a] (if (named? a) (name a) (str a))) (def secure-random (java.security.SecureRandom/getInstance "SHA1PRNG")) (defn rand-str "Random string for OAuth requests." [length] (. (new BigInteger (int (* 5 length)) ^java.util.Random secure-random) toString 32)) (def signature-methods {:hmac-sha1 "HMAC-SHA1" :plaintext "PLAINTEXT"}) (defn url-form-encode [params] (join "&" (map (fn [[k v]] (str (url-encode (as-str k)) "=" (url-encode (as-str v)))) params ))) (defn base-string ([method base-url c t params] (base-string method base-url (assoc params :oauth_consumer_key (:key c) :oauth_token (:token t) :oauth_signature_method (or (params :oauth_signature_method) (signature-methods (:signature-method c))) :oauth_version "1.0"))) ([method base-url params] (join "&" [method (url-encode base-url) (url-encode (url-form-encode (sort params)))]))) (defmulti sign "Sign a base string for authentication." {:arglists '([consumer base-string & [token-secret]])} (fn [c & r] (:signature-method c))) (defmethod sign :hmac-sha1 [c base-string & [token-secret]] (let [key (str (url-encode (:secret c)) "&" (url-encode (or token-secret "")))] (digest/hmac key base-string))) (defmethod sign :plaintext [c base-string & [token-secret]] (str (url-encode (:secret c)) "&" (url-encode (or token-secret "")))) (defn verify [sig c base-string & [token-secret]] (let [token-secret (url-encode (or token-secret ""))] (= sig (sign c base-string token-secret)))) (defn url-encode "The java.net.URLEncoder class encodes for application/x-www-form-urlencoded, but OAuth requires RFC 3986 encoding." [s] (-> (java.net.URLEncoder/encode s "UTF-8") (.replace "+" "%20") (.replace "*" "%2A") (.replace "%7E" "~"))) (defn url-decode "The java.net.URLEncoder class encodes for application/x-www-form-urlencoded, but OAuth requires RFC 3986 encoding." [s] (java.net.URLDecoder/decode s "UTF-8")) (defn oauth-params "Build a map of parameters needed for OAuth requests." ([consumer] {:oauth_consumer_key (:key consumer) :oauth_signature_method (signature-methods (:signature-method consumer)) :oauth_timestamp (int (/ (System/currentTimeMillis) 1000)) :oauth_nonce (rand-str 30) :oauth_version "1.0"}) ([consumer token] (assoc (oauth-params consumer) :oauth_token token)) ([consumer token verifier] (assoc (oauth-params consumer token) :oauth_verifier (str verifier))))
[ { "context": "ogging.clj -- delegated logging for Clojure\n\n;; by Alex Taggart\n;; July 27, 2009\n\n;; Copyright (c) Alex Taggart, ", "end": 68, "score": 0.9998823404312134, "start": 56, "tag": "NAME", "value": "Alex Taggart" }, { "context": "by Alex Taggart\n;; July 27, 2009\n\n;; Copyright (c) Alex Taggart, July 2009. All rights reserved. The use\n;; and ", "end": 116, "score": 0.9998638033866882, "start": 104, "tag": "NAME", "value": "Alex Taggart" }, { "context": "any other, from this software.\n(ns\n ^{:author\n \"Alex Taggart, with contributions and suggestions by Chris Dean", "end": 589, "score": 0.9998851418495178, "start": 577, "tag": "NAME", "value": "Alex Taggart" }, { "context": "lex Taggart, with contributions and suggestions by Chris Dean, Phil\n Hagelberg, Richard Newman, and Timothy Pr", "end": 639, "score": 0.9998553395271301, "start": 629, "tag": "NAME", "value": "Chris Dean" }, { "context": " with contributions and suggestions by Chris Dean, Phil\n Hagelberg, Richard Newman, and Timothy Pratley\",\n :doc\n ", "end": 657, "score": 0.999873161315918, "start": 641, "tag": "NAME", "value": "Phil\n Hagelberg" }, { "context": "s and suggestions by Chris Dean, Phil\n Hagelberg, Richard Newman, and Timothy Pratley\",\n :doc\n \"Logging macros", "end": 673, "score": 0.9998488426208496, "start": 659, "tag": "NAME", "value": "Richard Newman" }, { "context": " Chris Dean, Phil\n Hagelberg, Richard Newman, and Timothy Pratley\",\n :doc\n \"Logging macros which delegate to a ", "end": 694, "score": 0.9998707175254822, "start": 679, "tag": "NAME", "value": "Timothy Pratley" } ]
data/clojure/306d96740f5db73924b9bb61f4af3c74_logging.clj
maxim5/code-inspector
5
;;; logging.clj -- delegated logging for Clojure ;; by Alex Taggart ;; July 27, 2009 ;; Copyright (c) Alex Taggart, July 2009. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns ^{:author "Alex Taggart, with contributions and suggestions by Chris Dean, Phil Hagelberg, Richard Newman, and Timothy Pratley", :doc "Logging macros which delegate to a specific logging implementation. At runtime a specific implementation is selected from, in order, Apache commons-logging, slf4j, log4j, and finally java.util.logging. Logging levels are specified by clojure keywords corresponding to the values used in log4j and commons-logging: :trace, :debug, :info, :warn, :error, :fatal Logging occurs with the log macro, or the level-specific convenience macros, which write either directly or via an agent. See log* for more details regarding direct vs agent logging. The log macros will not evaluate their 'message' unless the specific logging level is in effect. Alternately, you can use the spy macro when you have code that needs to be evaluated, and also want to output the code and its result to the log. Unless otherwise specified, the current namespace (as identified by *ns*) will be used as the log-ns (similar to how the java class name is usually used). Note: your log configuration should display the name that was passed to the logging implementation, and not perform stack-inspection, otherwise you'll see some ugly and unhelpful text in your logs. Use the enabled? macro to write conditional code against the logging level (beyond simply whether or not to call log, which is handled automatically). You can redirect all java writes of System.out and System.err to the log system by calling log-capture!. To bind *out* and *err* to the log system invoke with-logs. In both cases a log-ns (e.g., \"com.example.captured\") must be specified in order to namespace the output. For those new to using a java logging library, the following is a very basic configuration for log4j. Place it in a file called \"log4j.properties\" and place that file (and the log4j JAR) on the classpath. log4j.rootLogger=WARN, A1 log4j.logger.user=DEBUG log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%d %-5p %c: %m%n The above will print messages to the console for :debug or higher if one is in the user namespace, and :warn or higher in all other namespaces."} clojure.contrib.logging [:use [clojure.pprint :only [code-dispatch pprint with-pprint-dispatch]]]) (defprotocol Log "The protocol through which macros will interact with an underlying logging implementation. Implementations should at least support the six specified logging levels if they wish to benefit from the level-specific macros." (impl-enabled? [log level] "Implementation-specific check if a particular level is enabled. End-users should not need to call this.") (impl-write! [log level throwable message] "Implementation-specific write of a log message. End-users should not need to call this.")) (defprotocol LogFactory "The protocol through which macros will obtain an instance satisfying Log as well as providing information about the particular implementation being used. Implementations should be bound to *log-factory* in order to be picked up by this library." (impl-name [factory] "Returns some text identifying the underlying implementation.") (impl-get-log [factory log-ns] "Returns an implementation-specific Log by namespace. End-users should not need to call this.")) (def ^{:doc "The default agent used for performing logging when direct logging is disabled. See log* for details."} *logging-agent* (agent nil :error-mode :continue)) (def ^{:doc "The set of levels that will require using an agent when logging from within a running transaction. Defaults to #{:info :warn}. See log* for details."} *tx-agent-levels* #{:info :warn}) (def ^{:doc "Overrides the default rules for choosing between logging directly or via an agent. Defaults to nil. See log* for details."} *force* nil) (defn log* "Attempts to log a message, either directly or via an agent; does not check if the level is enabled. For performance reasons, an agent will only be used when invoked within a running transaction, and only for logging levels specified by *tx-agent-levels*. This allows those entries to only be written once the transaction commits, and are discarded if it is retried or aborted. As corollary, other levels (e.g., :debug, :error) will be written even from failed transactions though at the cost of repeat messages during retries. One can override the above by setting *force* to :direct or :agent; all subsequent writes will be direct or via an agent, respectively." [log level throwable message] (if (cond (nil? *force*) (and (clojure.lang.LockingTransaction/isRunning) (*tx-agent-levels* level)) (= *force* :agent) true (= *force* :direct) false) (send-off *logging-agent* (fn [_#] (impl-write! log level throwable message))) (impl-write! log level throwable message))) (declare *log-factory*) ; default LogFactory instance for calling impl-get-log (defmacro log "Evaluates and logs a message only if the specified level is enabled. See log* for more details." ([level message] `(log ~level nil ~message)) ([level throwable message] `(log ~*ns* ~level ~throwable ~message)) ([log-ns level throwable message] `(log *log-factory* ~log-ns ~level ~throwable ~message)) ([log-factory log-ns level throwable message] `(let [log# (impl-get-log ~log-factory ~log-ns)] (if (impl-enabled? log# ~level) (log* log# ~level ~throwable ~message))))) (defmacro logp "Logs a message using print style args. Can optionally take a throwable as its second arg. See level-specific macros, e.g., debug." {:arglists '([level message & more] [level throwable message & more])} [level x & more] (if (or (instance? String x) (nil? more)) ; optimize for common case `(log ~level (print-str ~x ~@more)) `(let [log# (impl-get-log *log-factory* ~*ns*)] (if (impl-enabled? log# ~level) (if (instance? Throwable ~x) ; type check only when enabled (log* log# ~level ~x (print-str ~@more)) (log* log# ~level (print-str ~x ~@more))))))) (defmacro logf "Logs a message using a format string and args. Can optionally take a throwable as its second arg. See level-specific macros, e.g., debugf." {:arglists '([level fmt & fmt-args] [level throwable fmt & fmt-args])} [level x & more] (if (or (instance? String x) (nil? more)) ; optimize for common case `(log ~level (format ~x ~@more)) `(let [log# (impl-get-log *log-factory* ~*ns*)] (if (impl-enabled? log# ~level) (if (instance? Throwable ~x) ; type check only when enabled (log* log# ~level ~x (format ~(first more) ~@(next more))) (log* log# ~level (format ~x ~@more))))))) (defmacro enabled? "Returns true if the specific logging level is enabled. Use of this function should only be necessary if one needs to execute alternate code paths beyond whether the log should be written to." ([level] `(enabled? ~level ~*ns*)) ([level log-ns] `(impl-enabled? (impl-get-log *log-factory* ~log-ns) ~level))) (defmacro spy "Evaluates expr and writes the form and its result to the log. Returns the result of expr. Defaults to debug log level." ([expr] `(spy :debug ~expr)) ([level expr] `(let [a# ~expr] (log ~level (let [s# (with-out-str (with-pprint-dispatch code-dispatch ; need a better way (pprint '~expr) (print "=> ") (pprint a#)))] (.substring s# 0 (dec (count s#))))) ; trim off the trailing newline a#))) (defn log-stream "Creates a PrintStream that will output to the log at the specified level." [level log-ns] (let [log (impl-get-log *log-factory* log-ns)] (java.io.PrintStream. (proxy [java.io.ByteArrayOutputStream] [] (flush [] ; deal with reflection in proxy-super (let [^java.io.ByteArrayOutputStream this this] (proxy-super flush) (let [message (.trim (.toString this))] (proxy-super reset) (if (> (.length message) 0) (log* log level nil message)))))) true))) (let [orig (atom nil) ; holds original System.out and System.err monitor (Object.)] ; sync monitor for calling setOut/setErr (defn log-capture! "Captures System.out and System.err, piping all writes of those streams to the log. If unspecified, levels default to :info and :error, respectively. The specified log-ns value will be used to namespace all log entries. Note: use with-logs to redirect output of *out* or *err*. Warning: if the logging implementation is configured to output to System.out (as is the default with java.util.logging) then using this function will result in StackOverflowException when writing to the log." ; Implementation Notes: ; - only set orig when nil to preserve original out/err ; - no enabled? check before making streams since that may change later ([log-ns] (log-capture! log-ns :info :error)) ([log-ns out-level err-level] (locking monitor (compare-and-set! orig nil [System/out System/err]) (System/setOut (log-stream out-level log-ns)) (System/setErr (log-stream err-level log-ns))))) (defn log-uncapture! "Restores System.out and System.err to their original values." [] (locking monitor (when-let [[out err :as v] @orig] (swap! orig (constantly nil)) (System/setOut out) (System/setErr err))))) (defmacro with-logs "Evaluates exprs in a context in which *out* and *err* write to the log. The specified log-ns value will be used to namespace all log entries. By default *out* and *err* write to :info and :error, respectively." {:arglists '([log-ns & body] [[log-ns out-level err-level] & body])} [arg & body] ; Implementation Notes: ; - no enabled? check before making writers since that may change later (let [[log-ns out-level err-level] (if (vector? arg) arg [arg :info :error])] (if (and log-ns (seq body)) `(binding [*out* (java.io.OutputStreamWriter. (log-stream ~out-level ~log-ns)) *err* (java.io.OutputStreamWriter. (log-stream ~err-level ~log-ns))] ~@body)))) ;; level-specific macros (defmacro trace "Trace level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :trace ~@args)) (defmacro debug "Debug level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :debug ~@args)) (defmacro info "Info level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :info ~@args)) (defmacro warn "Warn level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :warn ~@args)) (defmacro error "Error level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :error ~@args)) (defmacro fatal "Fatal level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :fatal ~@args)) (defmacro tracef "Trace level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :trace ~@args)) (defmacro debugf "Debug level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :debug ~@args)) (defmacro infof "Info level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :info ~@args)) (defmacro warnf "Warn level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :warn ~@args)) (defmacro errorf "Error level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :error ~@args)) (defmacro fatalf "Fatal level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :fatal ~@args)) ;; Implementations of Log and LogFactory protocols: (defn commons-logging "Returns a commons-logging-based implementation of the LogFactory protocol, or nil if not available. End-users should not need to call this." [] (try (Class/forName "org.apache.commons.logging.Log") (eval '(do (extend-type org.apache.commons.logging.Log Log (impl-enabled? [log# level#] (condp = level# :trace (.isTraceEnabled log#) :debug (.isDebugEnabled log#) :info (.isInfoEnabled log#) :warn (.isWarnEnabled log#) :error (.isErrorEnabled log#) :fatal (.isFatalEnabled log#) (throw (IllegalArgumentException. (str level#))))) (impl-write! [log# level# e# msg#] (condp = level# :trace (.trace log# msg# e#) :debug (.debug log# msg# e#) :info (.info log# msg# e#) :warn (.warn log# msg# e#) :error (.error log# msg# e#) :fatal (.fatal log# msg# e#) (throw (IllegalArgumentException. (str level#)))))) (reify LogFactory (impl-name [_#] "org.apache.commons.logging") (impl-get-log [_# log-ns#] (org.apache.commons.logging.LogFactory/getLog (str log-ns#)))))) (catch Exception e nil))) (defn slf4j-logging "Returns a SLF4J-based implementation of the LogFactory protocol, or nil if not available. End-users should not need to call this." [] (try (Class/forName "org.slf4j.Logger") (eval '(do (extend-type org.slf4j.Logger Log (impl-enabled? [log# level#] (condp = level# :trace (.isTraceEnabled log#) :debug (.isDebugEnabled log#) :info (.isInfoEnabled log#) :warn (.isWarnEnabled log#) :error (.isErrorEnabled log#) :fatal (.isErrorEnabled log#) (throw (IllegalArgumentException. (str level#))))) (impl-write! [^org.slf4j.Logger log# level# ^Throwable e# msg#] (let [^String msg# (str msg#)] (condp = level# :trace (.trace log# msg# e#) :debug (.debug log# msg# e#) :info (.info log# msg# e#) :warn (.warn log# msg# e#) :error (.error log# msg# e#) :fatal (.error log# msg# e#) (throw (IllegalArgumentException. (str level#))))))) (reify LogFactory (impl-name [_#] "org.slf4j") (impl-get-log [_# log-ns#] (org.slf4j.LoggerFactory/getLogger ^String (str log-ns#)))))) (catch Exception e nil))) (defn log4j-logging "Returns a log4j-based implementation of the LogFactory protocol, or nil if not available. End-users should not need to call this." [] (try (Class/forName "org.apache.log4j.Logger") (eval '(let [levels# {: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}] (extend-type org.apache.log4j.Logger Log (impl-enabled? [log# level#] (.isEnabledFor log# (or (levels# level#) (throw (IllegalArgumentException. (str level#)))))) (impl-write! [log# level# e# msg#] (let [level# (or (levels# level#) (throw (IllegalArgumentException. (str level#))))] (if-not e# (.log log# level# msg#) (.log log# level# msg# e#))))) (reify LogFactory (impl-name [_#] "org.apache.log4j") (impl-get-log [_# log-ns#] (org.apache.log4j.Logger/getLogger ^String (str log-ns#)))))) (catch Exception e nil))) (defn java-util-logging "Returns a java.util.logging-based implementation of the LogFactory protocol, or nil if not available. End-users should not need to call this." [] (try (Class/forName "java.util.logging.Logger") (eval '(let [levels# {:trace java.util.logging.Level/FINEST :debug java.util.logging.Level/FINE :info java.util.logging.Level/INFO :warn java.util.logging.Level/WARNING :error java.util.logging.Level/SEVERE :fatal java.util.logging.Level/SEVERE}] (extend-type java.util.logging.Logger Log (impl-enabled? [log# level#] (.isLoggable log# (or (levels# level#) (throw (IllegalArgumentException. (str level#)))))) (impl-write! [log# level# ^Throwable e# msg#] (let [^java.util.logging.Level level# (or (levels# level#) (throw (IllegalArgumentException. (str level#)))) ^String msg# (str msg#)] (if e# (.log log# level# msg# e#) (.log log# level# msg#))))) (reify LogFactory (impl-name [_#] "java.util.logging") (impl-get-log [_# log-ns#] (java.util.logging.Logger/getLogger (str log-ns#)))))) (catch Exception e nil))) (defn find-factory "Returns the first LogFactory found that is available from commons-logging, slf4j-logging, log4j-logging, or java-util-logging. End-users should not need to call this." [] (or (commons-logging) (slf4j-logging) (log4j-logging) (java-util-logging) (throw ; this should never happen in 1.5+ (RuntimeException. "Valid logging implementation could not be found.")))) (def ^{:doc "An instance satisfying the LogFactory protocol. Used internally when needing to obtain an instance satisfying the Log protocol. Defaults to the value returned from find-factory. Can be rebound to provide alternate logging implementations"} *log-factory* (find-factory))
76471
;;; logging.clj -- delegated logging for Clojure ;; by <NAME> ;; July 27, 2009 ;; Copyright (c) <NAME>, July 2009. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns ^{:author "<NAME>, with contributions and suggestions by <NAME>, <NAME>, <NAME>, and <NAME>", :doc "Logging macros which delegate to a specific logging implementation. At runtime a specific implementation is selected from, in order, Apache commons-logging, slf4j, log4j, and finally java.util.logging. Logging levels are specified by clojure keywords corresponding to the values used in log4j and commons-logging: :trace, :debug, :info, :warn, :error, :fatal Logging occurs with the log macro, or the level-specific convenience macros, which write either directly or via an agent. See log* for more details regarding direct vs agent logging. The log macros will not evaluate their 'message' unless the specific logging level is in effect. Alternately, you can use the spy macro when you have code that needs to be evaluated, and also want to output the code and its result to the log. Unless otherwise specified, the current namespace (as identified by *ns*) will be used as the log-ns (similar to how the java class name is usually used). Note: your log configuration should display the name that was passed to the logging implementation, and not perform stack-inspection, otherwise you'll see some ugly and unhelpful text in your logs. Use the enabled? macro to write conditional code against the logging level (beyond simply whether or not to call log, which is handled automatically). You can redirect all java writes of System.out and System.err to the log system by calling log-capture!. To bind *out* and *err* to the log system invoke with-logs. In both cases a log-ns (e.g., \"com.example.captured\") must be specified in order to namespace the output. For those new to using a java logging library, the following is a very basic configuration for log4j. Place it in a file called \"log4j.properties\" and place that file (and the log4j JAR) on the classpath. log4j.rootLogger=WARN, A1 log4j.logger.user=DEBUG log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%d %-5p %c: %m%n The above will print messages to the console for :debug or higher if one is in the user namespace, and :warn or higher in all other namespaces."} clojure.contrib.logging [:use [clojure.pprint :only [code-dispatch pprint with-pprint-dispatch]]]) (defprotocol Log "The protocol through which macros will interact with an underlying logging implementation. Implementations should at least support the six specified logging levels if they wish to benefit from the level-specific macros." (impl-enabled? [log level] "Implementation-specific check if a particular level is enabled. End-users should not need to call this.") (impl-write! [log level throwable message] "Implementation-specific write of a log message. End-users should not need to call this.")) (defprotocol LogFactory "The protocol through which macros will obtain an instance satisfying Log as well as providing information about the particular implementation being used. Implementations should be bound to *log-factory* in order to be picked up by this library." (impl-name [factory] "Returns some text identifying the underlying implementation.") (impl-get-log [factory log-ns] "Returns an implementation-specific Log by namespace. End-users should not need to call this.")) (def ^{:doc "The default agent used for performing logging when direct logging is disabled. See log* for details."} *logging-agent* (agent nil :error-mode :continue)) (def ^{:doc "The set of levels that will require using an agent when logging from within a running transaction. Defaults to #{:info :warn}. See log* for details."} *tx-agent-levels* #{:info :warn}) (def ^{:doc "Overrides the default rules for choosing between logging directly or via an agent. Defaults to nil. See log* for details."} *force* nil) (defn log* "Attempts to log a message, either directly or via an agent; does not check if the level is enabled. For performance reasons, an agent will only be used when invoked within a running transaction, and only for logging levels specified by *tx-agent-levels*. This allows those entries to only be written once the transaction commits, and are discarded if it is retried or aborted. As corollary, other levels (e.g., :debug, :error) will be written even from failed transactions though at the cost of repeat messages during retries. One can override the above by setting *force* to :direct or :agent; all subsequent writes will be direct or via an agent, respectively." [log level throwable message] (if (cond (nil? *force*) (and (clojure.lang.LockingTransaction/isRunning) (*tx-agent-levels* level)) (= *force* :agent) true (= *force* :direct) false) (send-off *logging-agent* (fn [_#] (impl-write! log level throwable message))) (impl-write! log level throwable message))) (declare *log-factory*) ; default LogFactory instance for calling impl-get-log (defmacro log "Evaluates and logs a message only if the specified level is enabled. See log* for more details." ([level message] `(log ~level nil ~message)) ([level throwable message] `(log ~*ns* ~level ~throwable ~message)) ([log-ns level throwable message] `(log *log-factory* ~log-ns ~level ~throwable ~message)) ([log-factory log-ns level throwable message] `(let [log# (impl-get-log ~log-factory ~log-ns)] (if (impl-enabled? log# ~level) (log* log# ~level ~throwable ~message))))) (defmacro logp "Logs a message using print style args. Can optionally take a throwable as its second arg. See level-specific macros, e.g., debug." {:arglists '([level message & more] [level throwable message & more])} [level x & more] (if (or (instance? String x) (nil? more)) ; optimize for common case `(log ~level (print-str ~x ~@more)) `(let [log# (impl-get-log *log-factory* ~*ns*)] (if (impl-enabled? log# ~level) (if (instance? Throwable ~x) ; type check only when enabled (log* log# ~level ~x (print-str ~@more)) (log* log# ~level (print-str ~x ~@more))))))) (defmacro logf "Logs a message using a format string and args. Can optionally take a throwable as its second arg. See level-specific macros, e.g., debugf." {:arglists '([level fmt & fmt-args] [level throwable fmt & fmt-args])} [level x & more] (if (or (instance? String x) (nil? more)) ; optimize for common case `(log ~level (format ~x ~@more)) `(let [log# (impl-get-log *log-factory* ~*ns*)] (if (impl-enabled? log# ~level) (if (instance? Throwable ~x) ; type check only when enabled (log* log# ~level ~x (format ~(first more) ~@(next more))) (log* log# ~level (format ~x ~@more))))))) (defmacro enabled? "Returns true if the specific logging level is enabled. Use of this function should only be necessary if one needs to execute alternate code paths beyond whether the log should be written to." ([level] `(enabled? ~level ~*ns*)) ([level log-ns] `(impl-enabled? (impl-get-log *log-factory* ~log-ns) ~level))) (defmacro spy "Evaluates expr and writes the form and its result to the log. Returns the result of expr. Defaults to debug log level." ([expr] `(spy :debug ~expr)) ([level expr] `(let [a# ~expr] (log ~level (let [s# (with-out-str (with-pprint-dispatch code-dispatch ; need a better way (pprint '~expr) (print "=> ") (pprint a#)))] (.substring s# 0 (dec (count s#))))) ; trim off the trailing newline a#))) (defn log-stream "Creates a PrintStream that will output to the log at the specified level." [level log-ns] (let [log (impl-get-log *log-factory* log-ns)] (java.io.PrintStream. (proxy [java.io.ByteArrayOutputStream] [] (flush [] ; deal with reflection in proxy-super (let [^java.io.ByteArrayOutputStream this this] (proxy-super flush) (let [message (.trim (.toString this))] (proxy-super reset) (if (> (.length message) 0) (log* log level nil message)))))) true))) (let [orig (atom nil) ; holds original System.out and System.err monitor (Object.)] ; sync monitor for calling setOut/setErr (defn log-capture! "Captures System.out and System.err, piping all writes of those streams to the log. If unspecified, levels default to :info and :error, respectively. The specified log-ns value will be used to namespace all log entries. Note: use with-logs to redirect output of *out* or *err*. Warning: if the logging implementation is configured to output to System.out (as is the default with java.util.logging) then using this function will result in StackOverflowException when writing to the log." ; Implementation Notes: ; - only set orig when nil to preserve original out/err ; - no enabled? check before making streams since that may change later ([log-ns] (log-capture! log-ns :info :error)) ([log-ns out-level err-level] (locking monitor (compare-and-set! orig nil [System/out System/err]) (System/setOut (log-stream out-level log-ns)) (System/setErr (log-stream err-level log-ns))))) (defn log-uncapture! "Restores System.out and System.err to their original values." [] (locking monitor (when-let [[out err :as v] @orig] (swap! orig (constantly nil)) (System/setOut out) (System/setErr err))))) (defmacro with-logs "Evaluates exprs in a context in which *out* and *err* write to the log. The specified log-ns value will be used to namespace all log entries. By default *out* and *err* write to :info and :error, respectively." {:arglists '([log-ns & body] [[log-ns out-level err-level] & body])} [arg & body] ; Implementation Notes: ; - no enabled? check before making writers since that may change later (let [[log-ns out-level err-level] (if (vector? arg) arg [arg :info :error])] (if (and log-ns (seq body)) `(binding [*out* (java.io.OutputStreamWriter. (log-stream ~out-level ~log-ns)) *err* (java.io.OutputStreamWriter. (log-stream ~err-level ~log-ns))] ~@body)))) ;; level-specific macros (defmacro trace "Trace level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :trace ~@args)) (defmacro debug "Debug level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :debug ~@args)) (defmacro info "Info level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :info ~@args)) (defmacro warn "Warn level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :warn ~@args)) (defmacro error "Error level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :error ~@args)) (defmacro fatal "Fatal level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :fatal ~@args)) (defmacro tracef "Trace level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :trace ~@args)) (defmacro debugf "Debug level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :debug ~@args)) (defmacro infof "Info level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :info ~@args)) (defmacro warnf "Warn level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :warn ~@args)) (defmacro errorf "Error level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :error ~@args)) (defmacro fatalf "Fatal level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :fatal ~@args)) ;; Implementations of Log and LogFactory protocols: (defn commons-logging "Returns a commons-logging-based implementation of the LogFactory protocol, or nil if not available. End-users should not need to call this." [] (try (Class/forName "org.apache.commons.logging.Log") (eval '(do (extend-type org.apache.commons.logging.Log Log (impl-enabled? [log# level#] (condp = level# :trace (.isTraceEnabled log#) :debug (.isDebugEnabled log#) :info (.isInfoEnabled log#) :warn (.isWarnEnabled log#) :error (.isErrorEnabled log#) :fatal (.isFatalEnabled log#) (throw (IllegalArgumentException. (str level#))))) (impl-write! [log# level# e# msg#] (condp = level# :trace (.trace log# msg# e#) :debug (.debug log# msg# e#) :info (.info log# msg# e#) :warn (.warn log# msg# e#) :error (.error log# msg# e#) :fatal (.fatal log# msg# e#) (throw (IllegalArgumentException. (str level#)))))) (reify LogFactory (impl-name [_#] "org.apache.commons.logging") (impl-get-log [_# log-ns#] (org.apache.commons.logging.LogFactory/getLog (str log-ns#)))))) (catch Exception e nil))) (defn slf4j-logging "Returns a SLF4J-based implementation of the LogFactory protocol, or nil if not available. End-users should not need to call this." [] (try (Class/forName "org.slf4j.Logger") (eval '(do (extend-type org.slf4j.Logger Log (impl-enabled? [log# level#] (condp = level# :trace (.isTraceEnabled log#) :debug (.isDebugEnabled log#) :info (.isInfoEnabled log#) :warn (.isWarnEnabled log#) :error (.isErrorEnabled log#) :fatal (.isErrorEnabled log#) (throw (IllegalArgumentException. (str level#))))) (impl-write! [^org.slf4j.Logger log# level# ^Throwable e# msg#] (let [^String msg# (str msg#)] (condp = level# :trace (.trace log# msg# e#) :debug (.debug log# msg# e#) :info (.info log# msg# e#) :warn (.warn log# msg# e#) :error (.error log# msg# e#) :fatal (.error log# msg# e#) (throw (IllegalArgumentException. (str level#))))))) (reify LogFactory (impl-name [_#] "org.slf4j") (impl-get-log [_# log-ns#] (org.slf4j.LoggerFactory/getLogger ^String (str log-ns#)))))) (catch Exception e nil))) (defn log4j-logging "Returns a log4j-based implementation of the LogFactory protocol, or nil if not available. End-users should not need to call this." [] (try (Class/forName "org.apache.log4j.Logger") (eval '(let [levels# {: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}] (extend-type org.apache.log4j.Logger Log (impl-enabled? [log# level#] (.isEnabledFor log# (or (levels# level#) (throw (IllegalArgumentException. (str level#)))))) (impl-write! [log# level# e# msg#] (let [level# (or (levels# level#) (throw (IllegalArgumentException. (str level#))))] (if-not e# (.log log# level# msg#) (.log log# level# msg# e#))))) (reify LogFactory (impl-name [_#] "org.apache.log4j") (impl-get-log [_# log-ns#] (org.apache.log4j.Logger/getLogger ^String (str log-ns#)))))) (catch Exception e nil))) (defn java-util-logging "Returns a java.util.logging-based implementation of the LogFactory protocol, or nil if not available. End-users should not need to call this." [] (try (Class/forName "java.util.logging.Logger") (eval '(let [levels# {:trace java.util.logging.Level/FINEST :debug java.util.logging.Level/FINE :info java.util.logging.Level/INFO :warn java.util.logging.Level/WARNING :error java.util.logging.Level/SEVERE :fatal java.util.logging.Level/SEVERE}] (extend-type java.util.logging.Logger Log (impl-enabled? [log# level#] (.isLoggable log# (or (levels# level#) (throw (IllegalArgumentException. (str level#)))))) (impl-write! [log# level# ^Throwable e# msg#] (let [^java.util.logging.Level level# (or (levels# level#) (throw (IllegalArgumentException. (str level#)))) ^String msg# (str msg#)] (if e# (.log log# level# msg# e#) (.log log# level# msg#))))) (reify LogFactory (impl-name [_#] "java.util.logging") (impl-get-log [_# log-ns#] (java.util.logging.Logger/getLogger (str log-ns#)))))) (catch Exception e nil))) (defn find-factory "Returns the first LogFactory found that is available from commons-logging, slf4j-logging, log4j-logging, or java-util-logging. End-users should not need to call this." [] (or (commons-logging) (slf4j-logging) (log4j-logging) (java-util-logging) (throw ; this should never happen in 1.5+ (RuntimeException. "Valid logging implementation could not be found.")))) (def ^{:doc "An instance satisfying the LogFactory protocol. Used internally when needing to obtain an instance satisfying the Log protocol. Defaults to the value returned from find-factory. Can be rebound to provide alternate logging implementations"} *log-factory* (find-factory))
true
;;; logging.clj -- delegated logging for Clojure ;; by PI:NAME:<NAME>END_PI ;; July 27, 2009 ;; Copyright (c) PI:NAME:<NAME>END_PI, July 2009. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns ^{:author "PI:NAME:<NAME>END_PI, with contributions and suggestions by PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and PI:NAME:<NAME>END_PI", :doc "Logging macros which delegate to a specific logging implementation. At runtime a specific implementation is selected from, in order, Apache commons-logging, slf4j, log4j, and finally java.util.logging. Logging levels are specified by clojure keywords corresponding to the values used in log4j and commons-logging: :trace, :debug, :info, :warn, :error, :fatal Logging occurs with the log macro, or the level-specific convenience macros, which write either directly or via an agent. See log* for more details regarding direct vs agent logging. The log macros will not evaluate their 'message' unless the specific logging level is in effect. Alternately, you can use the spy macro when you have code that needs to be evaluated, and also want to output the code and its result to the log. Unless otherwise specified, the current namespace (as identified by *ns*) will be used as the log-ns (similar to how the java class name is usually used). Note: your log configuration should display the name that was passed to the logging implementation, and not perform stack-inspection, otherwise you'll see some ugly and unhelpful text in your logs. Use the enabled? macro to write conditional code against the logging level (beyond simply whether or not to call log, which is handled automatically). You can redirect all java writes of System.out and System.err to the log system by calling log-capture!. To bind *out* and *err* to the log system invoke with-logs. In both cases a log-ns (e.g., \"com.example.captured\") must be specified in order to namespace the output. For those new to using a java logging library, the following is a very basic configuration for log4j. Place it in a file called \"log4j.properties\" and place that file (and the log4j JAR) on the classpath. log4j.rootLogger=WARN, A1 log4j.logger.user=DEBUG log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%d %-5p %c: %m%n The above will print messages to the console for :debug or higher if one is in the user namespace, and :warn or higher in all other namespaces."} clojure.contrib.logging [:use [clojure.pprint :only [code-dispatch pprint with-pprint-dispatch]]]) (defprotocol Log "The protocol through which macros will interact with an underlying logging implementation. Implementations should at least support the six specified logging levels if they wish to benefit from the level-specific macros." (impl-enabled? [log level] "Implementation-specific check if a particular level is enabled. End-users should not need to call this.") (impl-write! [log level throwable message] "Implementation-specific write of a log message. End-users should not need to call this.")) (defprotocol LogFactory "The protocol through which macros will obtain an instance satisfying Log as well as providing information about the particular implementation being used. Implementations should be bound to *log-factory* in order to be picked up by this library." (impl-name [factory] "Returns some text identifying the underlying implementation.") (impl-get-log [factory log-ns] "Returns an implementation-specific Log by namespace. End-users should not need to call this.")) (def ^{:doc "The default agent used for performing logging when direct logging is disabled. See log* for details."} *logging-agent* (agent nil :error-mode :continue)) (def ^{:doc "The set of levels that will require using an agent when logging from within a running transaction. Defaults to #{:info :warn}. See log* for details."} *tx-agent-levels* #{:info :warn}) (def ^{:doc "Overrides the default rules for choosing between logging directly or via an agent. Defaults to nil. See log* for details."} *force* nil) (defn log* "Attempts to log a message, either directly or via an agent; does not check if the level is enabled. For performance reasons, an agent will only be used when invoked within a running transaction, and only for logging levels specified by *tx-agent-levels*. This allows those entries to only be written once the transaction commits, and are discarded if it is retried or aborted. As corollary, other levels (e.g., :debug, :error) will be written even from failed transactions though at the cost of repeat messages during retries. One can override the above by setting *force* to :direct or :agent; all subsequent writes will be direct or via an agent, respectively." [log level throwable message] (if (cond (nil? *force*) (and (clojure.lang.LockingTransaction/isRunning) (*tx-agent-levels* level)) (= *force* :agent) true (= *force* :direct) false) (send-off *logging-agent* (fn [_#] (impl-write! log level throwable message))) (impl-write! log level throwable message))) (declare *log-factory*) ; default LogFactory instance for calling impl-get-log (defmacro log "Evaluates and logs a message only if the specified level is enabled. See log* for more details." ([level message] `(log ~level nil ~message)) ([level throwable message] `(log ~*ns* ~level ~throwable ~message)) ([log-ns level throwable message] `(log *log-factory* ~log-ns ~level ~throwable ~message)) ([log-factory log-ns level throwable message] `(let [log# (impl-get-log ~log-factory ~log-ns)] (if (impl-enabled? log# ~level) (log* log# ~level ~throwable ~message))))) (defmacro logp "Logs a message using print style args. Can optionally take a throwable as its second arg. See level-specific macros, e.g., debug." {:arglists '([level message & more] [level throwable message & more])} [level x & more] (if (or (instance? String x) (nil? more)) ; optimize for common case `(log ~level (print-str ~x ~@more)) `(let [log# (impl-get-log *log-factory* ~*ns*)] (if (impl-enabled? log# ~level) (if (instance? Throwable ~x) ; type check only when enabled (log* log# ~level ~x (print-str ~@more)) (log* log# ~level (print-str ~x ~@more))))))) (defmacro logf "Logs a message using a format string and args. Can optionally take a throwable as its second arg. See level-specific macros, e.g., debugf." {:arglists '([level fmt & fmt-args] [level throwable fmt & fmt-args])} [level x & more] (if (or (instance? String x) (nil? more)) ; optimize for common case `(log ~level (format ~x ~@more)) `(let [log# (impl-get-log *log-factory* ~*ns*)] (if (impl-enabled? log# ~level) (if (instance? Throwable ~x) ; type check only when enabled (log* log# ~level ~x (format ~(first more) ~@(next more))) (log* log# ~level (format ~x ~@more))))))) (defmacro enabled? "Returns true if the specific logging level is enabled. Use of this function should only be necessary if one needs to execute alternate code paths beyond whether the log should be written to." ([level] `(enabled? ~level ~*ns*)) ([level log-ns] `(impl-enabled? (impl-get-log *log-factory* ~log-ns) ~level))) (defmacro spy "Evaluates expr and writes the form and its result to the log. Returns the result of expr. Defaults to debug log level." ([expr] `(spy :debug ~expr)) ([level expr] `(let [a# ~expr] (log ~level (let [s# (with-out-str (with-pprint-dispatch code-dispatch ; need a better way (pprint '~expr) (print "=> ") (pprint a#)))] (.substring s# 0 (dec (count s#))))) ; trim off the trailing newline a#))) (defn log-stream "Creates a PrintStream that will output to the log at the specified level." [level log-ns] (let [log (impl-get-log *log-factory* log-ns)] (java.io.PrintStream. (proxy [java.io.ByteArrayOutputStream] [] (flush [] ; deal with reflection in proxy-super (let [^java.io.ByteArrayOutputStream this this] (proxy-super flush) (let [message (.trim (.toString this))] (proxy-super reset) (if (> (.length message) 0) (log* log level nil message)))))) true))) (let [orig (atom nil) ; holds original System.out and System.err monitor (Object.)] ; sync monitor for calling setOut/setErr (defn log-capture! "Captures System.out and System.err, piping all writes of those streams to the log. If unspecified, levels default to :info and :error, respectively. The specified log-ns value will be used to namespace all log entries. Note: use with-logs to redirect output of *out* or *err*. Warning: if the logging implementation is configured to output to System.out (as is the default with java.util.logging) then using this function will result in StackOverflowException when writing to the log." ; Implementation Notes: ; - only set orig when nil to preserve original out/err ; - no enabled? check before making streams since that may change later ([log-ns] (log-capture! log-ns :info :error)) ([log-ns out-level err-level] (locking monitor (compare-and-set! orig nil [System/out System/err]) (System/setOut (log-stream out-level log-ns)) (System/setErr (log-stream err-level log-ns))))) (defn log-uncapture! "Restores System.out and System.err to their original values." [] (locking monitor (when-let [[out err :as v] @orig] (swap! orig (constantly nil)) (System/setOut out) (System/setErr err))))) (defmacro with-logs "Evaluates exprs in a context in which *out* and *err* write to the log. The specified log-ns value will be used to namespace all log entries. By default *out* and *err* write to :info and :error, respectively." {:arglists '([log-ns & body] [[log-ns out-level err-level] & body])} [arg & body] ; Implementation Notes: ; - no enabled? check before making writers since that may change later (let [[log-ns out-level err-level] (if (vector? arg) arg [arg :info :error])] (if (and log-ns (seq body)) `(binding [*out* (java.io.OutputStreamWriter. (log-stream ~out-level ~log-ns)) *err* (java.io.OutputStreamWriter. (log-stream ~err-level ~log-ns))] ~@body)))) ;; level-specific macros (defmacro trace "Trace level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :trace ~@args)) (defmacro debug "Debug level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :debug ~@args)) (defmacro info "Info level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :info ~@args)) (defmacro warn "Warn level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :warn ~@args)) (defmacro error "Error level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :error ~@args)) (defmacro fatal "Fatal level logging using print-style args." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :fatal ~@args)) (defmacro tracef "Trace level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :trace ~@args)) (defmacro debugf "Debug level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :debug ~@args)) (defmacro infof "Info level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :info ~@args)) (defmacro warnf "Warn level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :warn ~@args)) (defmacro errorf "Error level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :error ~@args)) (defmacro fatalf "Fatal level logging using format." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :fatal ~@args)) ;; Implementations of Log and LogFactory protocols: (defn commons-logging "Returns a commons-logging-based implementation of the LogFactory protocol, or nil if not available. End-users should not need to call this." [] (try (Class/forName "org.apache.commons.logging.Log") (eval '(do (extend-type org.apache.commons.logging.Log Log (impl-enabled? [log# level#] (condp = level# :trace (.isTraceEnabled log#) :debug (.isDebugEnabled log#) :info (.isInfoEnabled log#) :warn (.isWarnEnabled log#) :error (.isErrorEnabled log#) :fatal (.isFatalEnabled log#) (throw (IllegalArgumentException. (str level#))))) (impl-write! [log# level# e# msg#] (condp = level# :trace (.trace log# msg# e#) :debug (.debug log# msg# e#) :info (.info log# msg# e#) :warn (.warn log# msg# e#) :error (.error log# msg# e#) :fatal (.fatal log# msg# e#) (throw (IllegalArgumentException. (str level#)))))) (reify LogFactory (impl-name [_#] "org.apache.commons.logging") (impl-get-log [_# log-ns#] (org.apache.commons.logging.LogFactory/getLog (str log-ns#)))))) (catch Exception e nil))) (defn slf4j-logging "Returns a SLF4J-based implementation of the LogFactory protocol, or nil if not available. End-users should not need to call this." [] (try (Class/forName "org.slf4j.Logger") (eval '(do (extend-type org.slf4j.Logger Log (impl-enabled? [log# level#] (condp = level# :trace (.isTraceEnabled log#) :debug (.isDebugEnabled log#) :info (.isInfoEnabled log#) :warn (.isWarnEnabled log#) :error (.isErrorEnabled log#) :fatal (.isErrorEnabled log#) (throw (IllegalArgumentException. (str level#))))) (impl-write! [^org.slf4j.Logger log# level# ^Throwable e# msg#] (let [^String msg# (str msg#)] (condp = level# :trace (.trace log# msg# e#) :debug (.debug log# msg# e#) :info (.info log# msg# e#) :warn (.warn log# msg# e#) :error (.error log# msg# e#) :fatal (.error log# msg# e#) (throw (IllegalArgumentException. (str level#))))))) (reify LogFactory (impl-name [_#] "org.slf4j") (impl-get-log [_# log-ns#] (org.slf4j.LoggerFactory/getLogger ^String (str log-ns#)))))) (catch Exception e nil))) (defn log4j-logging "Returns a log4j-based implementation of the LogFactory protocol, or nil if not available. End-users should not need to call this." [] (try (Class/forName "org.apache.log4j.Logger") (eval '(let [levels# {: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}] (extend-type org.apache.log4j.Logger Log (impl-enabled? [log# level#] (.isEnabledFor log# (or (levels# level#) (throw (IllegalArgumentException. (str level#)))))) (impl-write! [log# level# e# msg#] (let [level# (or (levels# level#) (throw (IllegalArgumentException. (str level#))))] (if-not e# (.log log# level# msg#) (.log log# level# msg# e#))))) (reify LogFactory (impl-name [_#] "org.apache.log4j") (impl-get-log [_# log-ns#] (org.apache.log4j.Logger/getLogger ^String (str log-ns#)))))) (catch Exception e nil))) (defn java-util-logging "Returns a java.util.logging-based implementation of the LogFactory protocol, or nil if not available. End-users should not need to call this." [] (try (Class/forName "java.util.logging.Logger") (eval '(let [levels# {:trace java.util.logging.Level/FINEST :debug java.util.logging.Level/FINE :info java.util.logging.Level/INFO :warn java.util.logging.Level/WARNING :error java.util.logging.Level/SEVERE :fatal java.util.logging.Level/SEVERE}] (extend-type java.util.logging.Logger Log (impl-enabled? [log# level#] (.isLoggable log# (or (levels# level#) (throw (IllegalArgumentException. (str level#)))))) (impl-write! [log# level# ^Throwable e# msg#] (let [^java.util.logging.Level level# (or (levels# level#) (throw (IllegalArgumentException. (str level#)))) ^String msg# (str msg#)] (if e# (.log log# level# msg# e#) (.log log# level# msg#))))) (reify LogFactory (impl-name [_#] "java.util.logging") (impl-get-log [_# log-ns#] (java.util.logging.Logger/getLogger (str log-ns#)))))) (catch Exception e nil))) (defn find-factory "Returns the first LogFactory found that is available from commons-logging, slf4j-logging, log4j-logging, or java-util-logging. End-users should not need to call this." [] (or (commons-logging) (slf4j-logging) (log4j-logging) (java-util-logging) (throw ; this should never happen in 1.5+ (RuntimeException. "Valid logging implementation could not be found.")))) (def ^{:doc "An instance satisfying the LogFactory protocol. Used internally when needing to obtain an instance satisfying the Log protocol. Defaults to the value returned from find-factory. Can be rebound to provide alternate logging implementations"} *log-factory* (find-factory))
[ { "context": "eTagAuto\"\n :key \"imageTagAuto\"\n :searchText (:tag val", "end": 1613, "score": 0.5855410099029541, "start": 1601, "tag": "KEY", "value": "imageTagAuto" } ]
ch16/swarmpit/src/cljs/swarmpit/component/service/form_settings.cljs
vincestorm/Docker-on-Amazon-Web-Services
0
(ns swarmpit.component.service.form-settings (:require [material.component :as comp] [material.component.form :as form] [swarmpit.component.state :as state] [swarmpit.component.service.form-ports :as ports] [swarmpit.component.parser :refer [parse-int]] [swarmpit.ajax :as ajax] [swarmpit.routes :as routes] [rum.core :as rum] [clojure.string :as str])) (enable-console-print!) (def form-value-cursor (conj state/form-value-cursor :settings)) (def form-state-cursor (conj state/form-state-cursor :settings)) (def form-mode-style {:display "flex" :marginTop "14px"}) (def form-image-style {:color "rgb(117, 117, 117)"}) (defn- form-image [value] (form/comp "IMAGE" (comp/vtext-field {:name "image" :key "image" :required true :disabled true :underlineShow false :inputStyle form-image-style :value value}))) (defn- form-image-tag [value tags] "For update services there is no port preload" (form/comp "IMAGE TAG" (comp/autocomplete {:name "image-tag" :key "image-tag" :searchText (:tag value) :onUpdateInput (fn [v] (state/update-value [:repository :tag] v form-value-cursor)) :dataSource tags}))) (defn- form-image-tag-preloaded [value tags] "Preload ports for services created via swarmpit" (form/comp "IMAGE TAG" (comp/autocomplete {:name "imageTagAuto" :key "imageTagAuto" :searchText (:tag value) :onUpdateInput (fn [v] (state/update-value [:repository :tag] v form-value-cursor)) :onNewRequest (fn [_] (ports/load-suggestable-ports value)) :dataSource tags}))) (defn- form-name [value update-form?] (form/comp "SERVICE NAME" (comp/vtext-field {:name "service-name" :key "service-name" :required true :disabled update-form? :value value :onChange (fn [_ v] (state/update-value [:serviceName] v form-value-cursor))}))) (defn- form-mode [value update-form?] (form/comp "MODE" (comp/radio-button-group {:name "mode" :key "mode" :style form-mode-style :valueSelected value :onChange (fn [_ v] (state/update-value [:mode] v form-value-cursor))} (comp/radio-button {:name "replicated-mode" :key "replicated-mode" :disabled update-form? :label "Replicated" :value "replicated"}) (comp/radio-button {:name "global-mode" :key "global-mode" :disabled update-form? :label "Global" :value "global"})))) (defn- form-replicas [value] (form/comp "REPLICAS" (comp/vtext-field {:name "replicas" :key "replicas" :required true :type "number" :min 0 :value (str value) :onChange (fn [_ v] (state/update-value [:replicas] (parse-int v) form-value-cursor))}))) (defn- form-command [value] (form/comp "COMMAND" (comp/vtext-field {:name "command" :key "command" :required false :value value :onChange (fn [_ v] (state/update-value [:command] (when (< 0 (count v)) (str/split v #" ")) form-value-cursor))}))) (defn tags-handler [repository] (ajax/get (routes/path-for-backend :repository-tags) {:params {:repository repository} :on-success (fn [{:keys [response]}] (state/update-value [:tags] response form-state-cursor)) :on-error (fn [_])})) (rum/defc form < rum/reactive [update-form?] (let [{:keys [repository serviceName mode replicas command]} (state/react form-value-cursor) {:keys [tags]} (state/react form-state-cursor)] [:div.form-edit (form/form {:onValid #(state/update-value [:valid?] true form-state-cursor) :onInvalid #(state/update-value [:valid?] false form-state-cursor)} (form-image (:name repository)) (if update-form? (form-image-tag repository tags) (form-image-tag-preloaded repository tags)) (form-name serviceName update-form?) (form-mode mode update-form?) (when (= "replicated" mode) (form-replicas replicas)) (form-command (str/join " " command)))]))
15433
(ns swarmpit.component.service.form-settings (:require [material.component :as comp] [material.component.form :as form] [swarmpit.component.state :as state] [swarmpit.component.service.form-ports :as ports] [swarmpit.component.parser :refer [parse-int]] [swarmpit.ajax :as ajax] [swarmpit.routes :as routes] [rum.core :as rum] [clojure.string :as str])) (enable-console-print!) (def form-value-cursor (conj state/form-value-cursor :settings)) (def form-state-cursor (conj state/form-state-cursor :settings)) (def form-mode-style {:display "flex" :marginTop "14px"}) (def form-image-style {:color "rgb(117, 117, 117)"}) (defn- form-image [value] (form/comp "IMAGE" (comp/vtext-field {:name "image" :key "image" :required true :disabled true :underlineShow false :inputStyle form-image-style :value value}))) (defn- form-image-tag [value tags] "For update services there is no port preload" (form/comp "IMAGE TAG" (comp/autocomplete {:name "image-tag" :key "image-tag" :searchText (:tag value) :onUpdateInput (fn [v] (state/update-value [:repository :tag] v form-value-cursor)) :dataSource tags}))) (defn- form-image-tag-preloaded [value tags] "Preload ports for services created via swarmpit" (form/comp "IMAGE TAG" (comp/autocomplete {:name "imageTagAuto" :key "<KEY>" :searchText (:tag value) :onUpdateInput (fn [v] (state/update-value [:repository :tag] v form-value-cursor)) :onNewRequest (fn [_] (ports/load-suggestable-ports value)) :dataSource tags}))) (defn- form-name [value update-form?] (form/comp "SERVICE NAME" (comp/vtext-field {:name "service-name" :key "service-name" :required true :disabled update-form? :value value :onChange (fn [_ v] (state/update-value [:serviceName] v form-value-cursor))}))) (defn- form-mode [value update-form?] (form/comp "MODE" (comp/radio-button-group {:name "mode" :key "mode" :style form-mode-style :valueSelected value :onChange (fn [_ v] (state/update-value [:mode] v form-value-cursor))} (comp/radio-button {:name "replicated-mode" :key "replicated-mode" :disabled update-form? :label "Replicated" :value "replicated"}) (comp/radio-button {:name "global-mode" :key "global-mode" :disabled update-form? :label "Global" :value "global"})))) (defn- form-replicas [value] (form/comp "REPLICAS" (comp/vtext-field {:name "replicas" :key "replicas" :required true :type "number" :min 0 :value (str value) :onChange (fn [_ v] (state/update-value [:replicas] (parse-int v) form-value-cursor))}))) (defn- form-command [value] (form/comp "COMMAND" (comp/vtext-field {:name "command" :key "command" :required false :value value :onChange (fn [_ v] (state/update-value [:command] (when (< 0 (count v)) (str/split v #" ")) form-value-cursor))}))) (defn tags-handler [repository] (ajax/get (routes/path-for-backend :repository-tags) {:params {:repository repository} :on-success (fn [{:keys [response]}] (state/update-value [:tags] response form-state-cursor)) :on-error (fn [_])})) (rum/defc form < rum/reactive [update-form?] (let [{:keys [repository serviceName mode replicas command]} (state/react form-value-cursor) {:keys [tags]} (state/react form-state-cursor)] [:div.form-edit (form/form {:onValid #(state/update-value [:valid?] true form-state-cursor) :onInvalid #(state/update-value [:valid?] false form-state-cursor)} (form-image (:name repository)) (if update-form? (form-image-tag repository tags) (form-image-tag-preloaded repository tags)) (form-name serviceName update-form?) (form-mode mode update-form?) (when (= "replicated" mode) (form-replicas replicas)) (form-command (str/join " " command)))]))
true
(ns swarmpit.component.service.form-settings (:require [material.component :as comp] [material.component.form :as form] [swarmpit.component.state :as state] [swarmpit.component.service.form-ports :as ports] [swarmpit.component.parser :refer [parse-int]] [swarmpit.ajax :as ajax] [swarmpit.routes :as routes] [rum.core :as rum] [clojure.string :as str])) (enable-console-print!) (def form-value-cursor (conj state/form-value-cursor :settings)) (def form-state-cursor (conj state/form-state-cursor :settings)) (def form-mode-style {:display "flex" :marginTop "14px"}) (def form-image-style {:color "rgb(117, 117, 117)"}) (defn- form-image [value] (form/comp "IMAGE" (comp/vtext-field {:name "image" :key "image" :required true :disabled true :underlineShow false :inputStyle form-image-style :value value}))) (defn- form-image-tag [value tags] "For update services there is no port preload" (form/comp "IMAGE TAG" (comp/autocomplete {:name "image-tag" :key "image-tag" :searchText (:tag value) :onUpdateInput (fn [v] (state/update-value [:repository :tag] v form-value-cursor)) :dataSource tags}))) (defn- form-image-tag-preloaded [value tags] "Preload ports for services created via swarmpit" (form/comp "IMAGE TAG" (comp/autocomplete {:name "imageTagAuto" :key "PI:KEY:<KEY>END_PI" :searchText (:tag value) :onUpdateInput (fn [v] (state/update-value [:repository :tag] v form-value-cursor)) :onNewRequest (fn [_] (ports/load-suggestable-ports value)) :dataSource tags}))) (defn- form-name [value update-form?] (form/comp "SERVICE NAME" (comp/vtext-field {:name "service-name" :key "service-name" :required true :disabled update-form? :value value :onChange (fn [_ v] (state/update-value [:serviceName] v form-value-cursor))}))) (defn- form-mode [value update-form?] (form/comp "MODE" (comp/radio-button-group {:name "mode" :key "mode" :style form-mode-style :valueSelected value :onChange (fn [_ v] (state/update-value [:mode] v form-value-cursor))} (comp/radio-button {:name "replicated-mode" :key "replicated-mode" :disabled update-form? :label "Replicated" :value "replicated"}) (comp/radio-button {:name "global-mode" :key "global-mode" :disabled update-form? :label "Global" :value "global"})))) (defn- form-replicas [value] (form/comp "REPLICAS" (comp/vtext-field {:name "replicas" :key "replicas" :required true :type "number" :min 0 :value (str value) :onChange (fn [_ v] (state/update-value [:replicas] (parse-int v) form-value-cursor))}))) (defn- form-command [value] (form/comp "COMMAND" (comp/vtext-field {:name "command" :key "command" :required false :value value :onChange (fn [_ v] (state/update-value [:command] (when (< 0 (count v)) (str/split v #" ")) form-value-cursor))}))) (defn tags-handler [repository] (ajax/get (routes/path-for-backend :repository-tags) {:params {:repository repository} :on-success (fn [{:keys [response]}] (state/update-value [:tags] response form-state-cursor)) :on-error (fn [_])})) (rum/defc form < rum/reactive [update-form?] (let [{:keys [repository serviceName mode replicas command]} (state/react form-value-cursor) {:keys [tags]} (state/react form-state-cursor)] [:div.form-edit (form/form {:onValid #(state/update-value [:valid?] true form-state-cursor) :onInvalid #(state/update-value [:valid?] false form-state-cursor)} (form-image (:name repository)) (if update-form? (form-image-tag repository tags) (form-image-tag-preloaded repository tags)) (form-name serviceName update-form?) (form-mode mode update-form?) (when (= "replicated" mode) (form-replicas replicas)) (form-command (str/join " " command)))]))
[ { "context": "mal super permutation\"\n :url \"https://github.com/deltam/clj-superpermutation\"\n :license {:name \"MIT Lice", "end": 131, "score": 0.9995574355125427, "start": 125, "tag": "USERNAME", "value": "deltam" }, { "context": "l \"none\"\n :year 2019\n :key \"mit\"}\n :dependencies [[org.clojure/clojure \"1.10.0\"]", "end": 254, "score": 0.9828067421913147, "start": 251, "tag": "KEY", "value": "mit" } ]
project.clj
deltam/clj-superpermutation
0
(defproject clj-superpermutation "0.1.0-SNAPSHOT" :description "Find minimal super permutation" :url "https://github.com/deltam/clj-superpermutation" :license {:name "MIT License" :url "none" :year 2019 :key "mit"} :dependencies [[org.clojure/clojure "1.10.0"] [org.clojure/math.combinatorics "0.1.5"] [org.clojure/core.async "0.4.490"]] :repl-options {:init-ns superperm.core})
7778
(defproject clj-superpermutation "0.1.0-SNAPSHOT" :description "Find minimal super permutation" :url "https://github.com/deltam/clj-superpermutation" :license {:name "MIT License" :url "none" :year 2019 :key "<KEY>"} :dependencies [[org.clojure/clojure "1.10.0"] [org.clojure/math.combinatorics "0.1.5"] [org.clojure/core.async "0.4.490"]] :repl-options {:init-ns superperm.core})
true
(defproject clj-superpermutation "0.1.0-SNAPSHOT" :description "Find minimal super permutation" :url "https://github.com/deltam/clj-superpermutation" :license {:name "MIT License" :url "none" :year 2019 :key "PI:KEY:<KEY>END_PI"} :dependencies [[org.clojure/clojure "1.10.0"] [org.clojure/math.combinatorics "0.1.5"] [org.clojure/core.async "0.4.490"]] :repl-options {:init-ns superperm.core})
[ { "context": "ome? val)\n {:from \"admin@helpinghands.com\"\n :to (:to tx-dat", "end": 1862, "score": 0.9999252557754517, "start": 1840, "tag": "EMAIL", "value": "admin@helpinghands.com" }, { "context": " :ssl true\n :user \"admin@helpinghands.com\"\n :pass \"resetme\"}\n ", "end": 2276, "score": 0.999911367893219, "start": 2254, "tag": "EMAIL", "value": "admin@helpinghands.com" }, { "context": "dmin@helpinghands.com\"\n :pass \"resetme\"}\n msg)]\n ;; send email\n ", "end": 2312, "score": 0.9989743232727051, "start": 2305, "tag": "PASSWORD", "value": "resetme" } ]
Chapter10/helping-hands-alert/src/clj/helping_hands/alert/core.clj
ryanorsinger/Microservices-with-Clojure
37
(ns helping-hands.alert.core "Initializes Helping Hands Alert Service" (:require [cheshire.core :as jp] [clojure.string :as s] [postal.core :as postal] [helping-hands.alert.persistence :as p] [io.pedestal.interceptor.chain :as chain]) (:import [java.io IOException] [java.util UUID])) ;; -------------------------------- ;; Validation Interceptors ;; -------------------------------- (defn- prepare-valid-context "Applies validation logic and returns the resulting context" [context] (let [params (-> context :request :form-params)] (if (and (not (empty? params)) (not (empty? (:to params))) (not (empty? (:body params)))) (let [to-val (map s/trim (s/split (:to params) #","))] (assoc context :tx-data (assoc params :to to-val))) (chain/terminate (assoc context :response {:status 400 :body "Both to and body are required"}))))) (def validate {:name ::validate :enter (fn [context] (if-let [params (-> context :request :form-params)] ;; validate and return a context with tx-data ;; or terminated interceptor chain (prepare-valid-context context) (chain/terminate (assoc context :response {:status 400 :body "Invalid parameters"})))) :error (fn [context ex-info] (assoc context :response {:status 500 :body (.getMessage ex-info)}))}) ;; -------------------------------- ;; Business Logic Interceptors ;; -------------------------------- (def send-email {:name ::send-email :enter (fn [context] (let [tx-data (:tx-data context) msg (into {} (filter (comp some? val) {:from "admin@helpinghands.com" :to (:to tx-data) :cc (:cc tx-data) :subject (:subject tx-data) :body (:body tx-data)})) result (postal/send-message {:host "smtp.gmail.com" :port 465 :ssl true :user "admin@helpinghands.com" :pass "resetme"} msg)] ;; send email (assoc context :response {:status 200 :body (jp/generate-string result)}))) :error (fn [context ex-info] (assoc context :response {:status 500 :body (.getMessage ex-info)}))}) (def send-sms {:name ::send-sms :enter (fn [context] (let [tx-data (:tx-data context)] ;; TODO ;; Send SMS (assoc context :response {:status 200 :body "SUCCESS"}))) :error (fn [context ex-info] (assoc context :response {:status 500 :body (.getMessage ex-info)}))})
62934
(ns helping-hands.alert.core "Initializes Helping Hands Alert Service" (:require [cheshire.core :as jp] [clojure.string :as s] [postal.core :as postal] [helping-hands.alert.persistence :as p] [io.pedestal.interceptor.chain :as chain]) (:import [java.io IOException] [java.util UUID])) ;; -------------------------------- ;; Validation Interceptors ;; -------------------------------- (defn- prepare-valid-context "Applies validation logic and returns the resulting context" [context] (let [params (-> context :request :form-params)] (if (and (not (empty? params)) (not (empty? (:to params))) (not (empty? (:body params)))) (let [to-val (map s/trim (s/split (:to params) #","))] (assoc context :tx-data (assoc params :to to-val))) (chain/terminate (assoc context :response {:status 400 :body "Both to and body are required"}))))) (def validate {:name ::validate :enter (fn [context] (if-let [params (-> context :request :form-params)] ;; validate and return a context with tx-data ;; or terminated interceptor chain (prepare-valid-context context) (chain/terminate (assoc context :response {:status 400 :body "Invalid parameters"})))) :error (fn [context ex-info] (assoc context :response {:status 500 :body (.getMessage ex-info)}))}) ;; -------------------------------- ;; Business Logic Interceptors ;; -------------------------------- (def send-email {:name ::send-email :enter (fn [context] (let [tx-data (:tx-data context) msg (into {} (filter (comp some? val) {:from "<EMAIL>" :to (:to tx-data) :cc (:cc tx-data) :subject (:subject tx-data) :body (:body tx-data)})) result (postal/send-message {:host "smtp.gmail.com" :port 465 :ssl true :user "<EMAIL>" :pass "<PASSWORD>"} msg)] ;; send email (assoc context :response {:status 200 :body (jp/generate-string result)}))) :error (fn [context ex-info] (assoc context :response {:status 500 :body (.getMessage ex-info)}))}) (def send-sms {:name ::send-sms :enter (fn [context] (let [tx-data (:tx-data context)] ;; TODO ;; Send SMS (assoc context :response {:status 200 :body "SUCCESS"}))) :error (fn [context ex-info] (assoc context :response {:status 500 :body (.getMessage ex-info)}))})
true
(ns helping-hands.alert.core "Initializes Helping Hands Alert Service" (:require [cheshire.core :as jp] [clojure.string :as s] [postal.core :as postal] [helping-hands.alert.persistence :as p] [io.pedestal.interceptor.chain :as chain]) (:import [java.io IOException] [java.util UUID])) ;; -------------------------------- ;; Validation Interceptors ;; -------------------------------- (defn- prepare-valid-context "Applies validation logic and returns the resulting context" [context] (let [params (-> context :request :form-params)] (if (and (not (empty? params)) (not (empty? (:to params))) (not (empty? (:body params)))) (let [to-val (map s/trim (s/split (:to params) #","))] (assoc context :tx-data (assoc params :to to-val))) (chain/terminate (assoc context :response {:status 400 :body "Both to and body are required"}))))) (def validate {:name ::validate :enter (fn [context] (if-let [params (-> context :request :form-params)] ;; validate and return a context with tx-data ;; or terminated interceptor chain (prepare-valid-context context) (chain/terminate (assoc context :response {:status 400 :body "Invalid parameters"})))) :error (fn [context ex-info] (assoc context :response {:status 500 :body (.getMessage ex-info)}))}) ;; -------------------------------- ;; Business Logic Interceptors ;; -------------------------------- (def send-email {:name ::send-email :enter (fn [context] (let [tx-data (:tx-data context) msg (into {} (filter (comp some? val) {:from "PI:EMAIL:<EMAIL>END_PI" :to (:to tx-data) :cc (:cc tx-data) :subject (:subject tx-data) :body (:body tx-data)})) result (postal/send-message {:host "smtp.gmail.com" :port 465 :ssl true :user "PI:EMAIL:<EMAIL>END_PI" :pass "PI:PASSWORD:<PASSWORD>END_PI"} msg)] ;; send email (assoc context :response {:status 200 :body (jp/generate-string result)}))) :error (fn [context ex-info] (assoc context :response {:status 500 :body (.getMessage ex-info)}))}) (def send-sms {:name ::send-sms :enter (fn [context] (let [tx-data (:tx-data context)] ;; TODO ;; Send SMS (assoc context :response {:status 200 :body "SUCCESS"}))) :error (fn [context ex-info] (assoc context :response {:status 500 :body (.getMessage ex-info)}))})
[ { "context": " :username \"postgres\"\n :password ", "end": 600, "score": 0.9941633343696594, "start": 592, "tag": "USERNAME", "value": "postgres" }, { "context": " :password \"postgres\"}))\n\n(def lacinia-schema (l/schema db-spec))\n\n(de", "end": 668, "score": 0.9995170831680298, "start": 660, "tag": "PASSWORD", "value": "postgres" } ]
clojure/pedestal/src/server.clj
graphqlize/graphqlize-demo
11
(ns server (:require [hikari-cp.core :as hikari] [io.pedestal.http :as server] [com.walmartlabs.lacinia.pedestal :as lacinia-pedestal] [graphqlize.lacinia.core :as l])) (def db-spec (hikari/make-datasource {:adapter "postgresql" :database-name "sakila" :server-name "localhost" :port-number 5432 :maximum-pool-size 1 :username "postgres" :password "postgres"})) (def lacinia-schema (l/schema db-spec)) (def service (assoc (lacinia-pedestal/service-map lacinia-schema {:graphiql true :port 8080}) ::server/resource-path "/static")) (defonce runnable-service (server/create-server service)) (.addShutdownHook (Runtime/getRuntime) (Thread. (fn [] (server/stop runnable-service) (.close db-spec)))) (defn -main [] (server/start runnable-service))
114463
(ns server (:require [hikari-cp.core :as hikari] [io.pedestal.http :as server] [com.walmartlabs.lacinia.pedestal :as lacinia-pedestal] [graphqlize.lacinia.core :as l])) (def db-spec (hikari/make-datasource {:adapter "postgresql" :database-name "sakila" :server-name "localhost" :port-number 5432 :maximum-pool-size 1 :username "postgres" :password "<PASSWORD>"})) (def lacinia-schema (l/schema db-spec)) (def service (assoc (lacinia-pedestal/service-map lacinia-schema {:graphiql true :port 8080}) ::server/resource-path "/static")) (defonce runnable-service (server/create-server service)) (.addShutdownHook (Runtime/getRuntime) (Thread. (fn [] (server/stop runnable-service) (.close db-spec)))) (defn -main [] (server/start runnable-service))
true
(ns server (:require [hikari-cp.core :as hikari] [io.pedestal.http :as server] [com.walmartlabs.lacinia.pedestal :as lacinia-pedestal] [graphqlize.lacinia.core :as l])) (def db-spec (hikari/make-datasource {:adapter "postgresql" :database-name "sakila" :server-name "localhost" :port-number 5432 :maximum-pool-size 1 :username "postgres" :password "PI:PASSWORD:<PASSWORD>END_PI"})) (def lacinia-schema (l/schema db-spec)) (def service (assoc (lacinia-pedestal/service-map lacinia-schema {:graphiql true :port 8080}) ::server/resource-path "/static")) (defonce runnable-service (server/create-server service)) (.addShutdownHook (Runtime/getRuntime) (Thread. (fn [] (server/stop runnable-service) (.close db-spec)))) (defn -main [] (server/start runnable-service))
[ { "context": "015\n :user \"test-user\"\n :authdb \"te", "end": 1688, "score": 0.9991963505744934, "start": 1679, "tag": "USERNAME", "value": "test-user" }, { "context": "db\"\n :pass \"test-passwd\"\n :dbname \"te", "end": 1806, "score": 0.998927891254425, "start": 1795, "tag": "PASSWORD", "value": "test-passwd" }, { "context": "010\n :user \"test-user\"\n :authdb \"te", "end": 2333, "score": 0.9995040893554688, "start": 2324, "tag": "USERNAME", "value": "test-user" }, { "context": "db\"\n :pass \"test-passwd\"\n :dbname \"te", "end": 2451, "score": 0.999416172504425, "start": 2440, "tag": "PASSWORD", "value": "test-passwd" }, { "context": "010\n :user \"test-user\"\n :authdb \"te", "end": 2986, "score": 0.9993742108345032, "start": 2977, "tag": "USERNAME", "value": "test-user" }, { "context": "db\"\n :pass \"test-passwd\"\n :dbname \"te", "end": 3104, "score": 0.9994179606437683, "start": 3093, "tag": "PASSWORD", "value": "test-passwd" }, { "context": " :user \"test-user\"\n ", "end": 3799, "score": 0.9994990825653076, "start": 3790, "tag": "USERNAME", "value": "test-user" }, { "context": " :pass \"test-passwd\"\n ", "end": 3977, "score": 0.9992842674255371, "start": 3966, "tag": "PASSWORD", "value": "test-passwd" }, { "context": " :user \"test-user\"\n ", "end": 5246, "score": 0.999489963054657, "start": 5237, "tag": "USERNAME", "value": "test-user" }, { "context": " :pass \"test-passwd\"\n ", "end": 5417, "score": 0.9987579584121704, "start": 5413, "tag": "PASSWORD", "value": "test" }, { "context": " :user \"test-user\"\n ", "end": 6703, "score": 0.9994683861732483, "start": 6694, "tag": "USERNAME", "value": "test-user" }, { "context": " :pass \"test-passwd\"\n ", "end": 6881, "score": 0.9994084239006042, "start": 6870, "tag": "PASSWORD", "value": "test-passwd" }, { "context": " :user \"test-user\"\n ", "end": 8128, "score": 0.9995338320732117, "start": 8119, "tag": "USERNAME", "value": "test-user" }, { "context": " :pass \"test-passwd\"\n ", "end": 8292, "score": 0.9994155764579773, "start": 8281, "tag": "PASSWORD", "value": "test-passwd" }, { "context": "alse\n :password \"changeme\"\n :tunnel-host \"loc", "end": 10724, "score": 0.9994305968284607, "start": 10716, "tag": "PASSWORD", "value": "changeme" }, { "context": "ost\"\n :tunnel-pass \"BOGUS-BOGUS\"\n :port 5432", "end": 10838, "score": 0.9994564056396484, "start": 10827, "tag": "PASSWORD", "value": "BOGUS-BOGUS" } ]
c#-metabase/modules/drivers/mongo/test/metabase/driver/mongo/util_test.clj
hanakhry/Crime_Admin
0
(ns metabase.driver.mongo.util-test (:require [clojure.test :refer :all] [metabase.driver.mongo.util :as mongo-util] [metabase.driver.util :as driver.u] [metabase.test :as mt]) (:import [com.mongodb DB MongoClient MongoClientException MongoClientOptions$Builder ReadPreference ServerAddress])) (defn- connect-mongo [opts] (let [connection-info (#'mongo-util/details->mongo-connection-info (#'mongo-util/normalize-details opts))] (#'mongo-util/connect connection-info))) (def connect-passthrough (fn [{map-type :type}] map-type)) (def srv-passthrough (fn [_] {:type :srv})) (deftest fqdn?-test (testing "test hostname is fqdn" (is (= true (#'mongo-util/fqdn? "db.mongo.com"))) (is (= true (#'mongo-util/fqdn? "replica-01.db.mongo.com"))) (is (= false (#'mongo-util/fqdn? "localhost"))) (is (= false (#'mongo-util/fqdn? "localhost.localdomain"))))) (deftest srv-conn-str-test (testing "test srv connection string" (is (= "mongodb+srv://test-user:test-pass@test-host.place.com/authdb" (#'mongo-util/srv-conn-str "test-user" "test-pass" "test-host.place.com" "authdb"))))) (deftest srv-toggle-test (testing "test that srv toggle works" (is (= :srv (with-redefs [mongo-util/srv-connection-info srv-passthrough mongo-util/connect connect-passthrough] (let [host "my.fake.domain" opts {:host host :port 1015 :user "test-user" :authdb "test-authdb" :pass "test-passwd" :dbname "test-dbname" :ssl true :additional-options "" :use-srv true}] (connect-mongo opts))))) (is (= :normal (with-redefs [mongo-util/connect connect-passthrough] (let [host "localhost" opts {:host host :port 1010 :user "test-user" :authdb "test-authdb" :pass "test-passwd" :dbname "test-dbname" :ssl true :additional-options "" :use-srv false}] (connect-mongo opts))))) (is (= :normal (with-redefs [mongo-util/connect connect-passthrough] (let [host "localhost.domain" opts {:host host :port 1010 :user "test-user" :authdb "test-authdb" :pass "test-passwd" :dbname "test-dbname" :ssl true :additional-options ""}] (connect-mongo opts))))))) (deftest srv-connection-properties-test (testing "test that connection properties when using srv" (is (= "No SRV record available for host fake.fqdn.com" (try (let [host "fake.fqdn.com" opts {:host host :port 1015 :user "test-user" :authdb "test-authdb" :pass "test-passwd" :dbname "test-dbname" :ssl true :additional-options "" :use-srv true} [^MongoClient mongo-client ^DB db] (connect-mongo opts) ^ServerAddress mongo-addr (-> mongo-client (.getAllAddress) first) mongo-host (-> mongo-addr .getHost) mongo-port (-> mongo-addr .getPort)] [mongo-host mongo-port]) (catch MongoClientException e (.getMessage e))))) (is (= "Using DNS SRV requires a FQDN for host" (try (let [host "host1" opts {:host host :port 1015 :user "test-user" :authdb "test-authdb" :pass "test-passwd" :dbname "test-dbname" :ssl true :additional-options "" :use-srv true} [^MongoClient mongo-client ^DB db] (connect-mongo opts) ^ServerAddress mongo-addr (-> mongo-client (.getAllAddress) first) mongo-host (-> mongo-addr .getHost) mongo-port (-> mongo-addr .getPort)] [mongo-host mongo-port]) (catch Exception e (.getMessage e))))) (is (= "Unable to look up SRV record for host fake.fqdn.org" (try (let [host "fake.fqdn.org" opts {:host host :port 1015 :user "test-user" :authdb "test-authdb" :pass "test-passwd" :dbname "test-dbname" :ssl true :additional-options "" :use-srv true} [^MongoClient mongo-client ^DB db] (connect-mongo opts) ^ServerAddress mongo-addr (-> mongo-client (.getAllAddress) first) mongo-host (-> mongo-addr .getHost) mongo-port (-> mongo-addr .getPort)] [mongo-host mongo-port]) (catch MongoClientException e (.getMessage e))))) (testing "test host and port are correct for both srv and normal" (let [host "localhost" opts {:host host :port 1010 :user "test-user" :authdb "test-authdb" :pass "test-passwd" :dbname "test-dbname" :ssl true :additional-options ""} [^MongoClient mongo-client ^DB db] (connect-mongo opts) ^ServerAddress mongo-addr (-> mongo-client (.getAllAddress) first) mongo-host (-> mongo-addr .getHost) mongo-port (-> mongo-addr .getPort)] (is (= "localhost" mongo-host)) (is (= 1010 mongo-port)))))) (defn- connection-options-builder ^MongoClientOptions$Builder [& args] (apply #'mongo-util/connection-options-builder args)) (deftest additional-connection-options-test (testing "test that people can specify additional connection options like `?readPreference=nearest`" (is (= (ReadPreference/nearest) (.getReadPreference (-> (connection-options-builder :additional-options "readPreference=nearest") .build)))) (is (= (ReadPreference/secondaryPreferred) (.getReadPreference (-> (connection-options-builder :additional-options "readPreference=secondaryPreferred") .build)))) (testing "make sure we can specify multiple options" (let [opts (-> (connection-options-builder :additional-options "readPreference=secondary&replicaSet=test") .build)] (is (= "test" (.getRequiredReplicaSetName opts))) (is (= (ReadPreference/secondary) (.getReadPreference opts))))) (testing "make sure that invalid additional options throw an Exception" (is (thrown-with-msg? IllegalArgumentException #"No match for read preference of ternary" (-> (connection-options-builder :additional-options "readPreference=ternary") .build)))))) (deftest test-ssh-connection (testing "Gets an error when it can't connect to mongo via ssh tunnel" (mt/test-driver :mongo (is (thrown? java.net.ConnectException (try (let [engine :mongo details {:ssl false :password "changeme" :tunnel-host "localhost" :tunnel-pass "BOGUS-BOGUS" :port 5432 :dbname "test" :host "localhost" :tunnel-enabled true ;; we want to use a bogus port here on purpose - ;; so that locally, it gets a ConnectionRefused, ;; and in CI it does too. Apache's SSHD library ;; doesn't wrap every exception in an SshdException :tunnel-port 21212 :tunnel-user "bogus"}] (driver.u/can-connect-with-details? engine details :throw-exceptions)) (catch Throwable e (loop [^Throwable e e] (or (when (instance? java.net.ConnectException e) (throw e)) (some-> (.getCause e) recur))))))))))
79613
(ns metabase.driver.mongo.util-test (:require [clojure.test :refer :all] [metabase.driver.mongo.util :as mongo-util] [metabase.driver.util :as driver.u] [metabase.test :as mt]) (:import [com.mongodb DB MongoClient MongoClientException MongoClientOptions$Builder ReadPreference ServerAddress])) (defn- connect-mongo [opts] (let [connection-info (#'mongo-util/details->mongo-connection-info (#'mongo-util/normalize-details opts))] (#'mongo-util/connect connection-info))) (def connect-passthrough (fn [{map-type :type}] map-type)) (def srv-passthrough (fn [_] {:type :srv})) (deftest fqdn?-test (testing "test hostname is fqdn" (is (= true (#'mongo-util/fqdn? "db.mongo.com"))) (is (= true (#'mongo-util/fqdn? "replica-01.db.mongo.com"))) (is (= false (#'mongo-util/fqdn? "localhost"))) (is (= false (#'mongo-util/fqdn? "localhost.localdomain"))))) (deftest srv-conn-str-test (testing "test srv connection string" (is (= "mongodb+srv://test-user:test-pass@test-host.place.com/authdb" (#'mongo-util/srv-conn-str "test-user" "test-pass" "test-host.place.com" "authdb"))))) (deftest srv-toggle-test (testing "test that srv toggle works" (is (= :srv (with-redefs [mongo-util/srv-connection-info srv-passthrough mongo-util/connect connect-passthrough] (let [host "my.fake.domain" opts {:host host :port 1015 :user "test-user" :authdb "test-authdb" :pass "<PASSWORD>" :dbname "test-dbname" :ssl true :additional-options "" :use-srv true}] (connect-mongo opts))))) (is (= :normal (with-redefs [mongo-util/connect connect-passthrough] (let [host "localhost" opts {:host host :port 1010 :user "test-user" :authdb "test-authdb" :pass "<PASSWORD>" :dbname "test-dbname" :ssl true :additional-options "" :use-srv false}] (connect-mongo opts))))) (is (= :normal (with-redefs [mongo-util/connect connect-passthrough] (let [host "localhost.domain" opts {:host host :port 1010 :user "test-user" :authdb "test-authdb" :pass "<PASSWORD>" :dbname "test-dbname" :ssl true :additional-options ""}] (connect-mongo opts))))))) (deftest srv-connection-properties-test (testing "test that connection properties when using srv" (is (= "No SRV record available for host fake.fqdn.com" (try (let [host "fake.fqdn.com" opts {:host host :port 1015 :user "test-user" :authdb "test-authdb" :pass "<PASSWORD>" :dbname "test-dbname" :ssl true :additional-options "" :use-srv true} [^MongoClient mongo-client ^DB db] (connect-mongo opts) ^ServerAddress mongo-addr (-> mongo-client (.getAllAddress) first) mongo-host (-> mongo-addr .getHost) mongo-port (-> mongo-addr .getPort)] [mongo-host mongo-port]) (catch MongoClientException e (.getMessage e))))) (is (= "Using DNS SRV requires a FQDN for host" (try (let [host "host1" opts {:host host :port 1015 :user "test-user" :authdb "test-authdb" :pass "<PASSWORD>-passwd" :dbname "test-dbname" :ssl true :additional-options "" :use-srv true} [^MongoClient mongo-client ^DB db] (connect-mongo opts) ^ServerAddress mongo-addr (-> mongo-client (.getAllAddress) first) mongo-host (-> mongo-addr .getHost) mongo-port (-> mongo-addr .getPort)] [mongo-host mongo-port]) (catch Exception e (.getMessage e))))) (is (= "Unable to look up SRV record for host fake.fqdn.org" (try (let [host "fake.fqdn.org" opts {:host host :port 1015 :user "test-user" :authdb "test-authdb" :pass "<PASSWORD>" :dbname "test-dbname" :ssl true :additional-options "" :use-srv true} [^MongoClient mongo-client ^DB db] (connect-mongo opts) ^ServerAddress mongo-addr (-> mongo-client (.getAllAddress) first) mongo-host (-> mongo-addr .getHost) mongo-port (-> mongo-addr .getPort)] [mongo-host mongo-port]) (catch MongoClientException e (.getMessage e))))) (testing "test host and port are correct for both srv and normal" (let [host "localhost" opts {:host host :port 1010 :user "test-user" :authdb "test-authdb" :pass "<PASSWORD>" :dbname "test-dbname" :ssl true :additional-options ""} [^MongoClient mongo-client ^DB db] (connect-mongo opts) ^ServerAddress mongo-addr (-> mongo-client (.getAllAddress) first) mongo-host (-> mongo-addr .getHost) mongo-port (-> mongo-addr .getPort)] (is (= "localhost" mongo-host)) (is (= 1010 mongo-port)))))) (defn- connection-options-builder ^MongoClientOptions$Builder [& args] (apply #'mongo-util/connection-options-builder args)) (deftest additional-connection-options-test (testing "test that people can specify additional connection options like `?readPreference=nearest`" (is (= (ReadPreference/nearest) (.getReadPreference (-> (connection-options-builder :additional-options "readPreference=nearest") .build)))) (is (= (ReadPreference/secondaryPreferred) (.getReadPreference (-> (connection-options-builder :additional-options "readPreference=secondaryPreferred") .build)))) (testing "make sure we can specify multiple options" (let [opts (-> (connection-options-builder :additional-options "readPreference=secondary&replicaSet=test") .build)] (is (= "test" (.getRequiredReplicaSetName opts))) (is (= (ReadPreference/secondary) (.getReadPreference opts))))) (testing "make sure that invalid additional options throw an Exception" (is (thrown-with-msg? IllegalArgumentException #"No match for read preference of ternary" (-> (connection-options-builder :additional-options "readPreference=ternary") .build)))))) (deftest test-ssh-connection (testing "Gets an error when it can't connect to mongo via ssh tunnel" (mt/test-driver :mongo (is (thrown? java.net.ConnectException (try (let [engine :mongo details {:ssl false :password "<PASSWORD>" :tunnel-host "localhost" :tunnel-pass "<PASSWORD>" :port 5432 :dbname "test" :host "localhost" :tunnel-enabled true ;; we want to use a bogus port here on purpose - ;; so that locally, it gets a ConnectionRefused, ;; and in CI it does too. Apache's SSHD library ;; doesn't wrap every exception in an SshdException :tunnel-port 21212 :tunnel-user "bogus"}] (driver.u/can-connect-with-details? engine details :throw-exceptions)) (catch Throwable e (loop [^Throwable e e] (or (when (instance? java.net.ConnectException e) (throw e)) (some-> (.getCause e) recur))))))))))
true
(ns metabase.driver.mongo.util-test (:require [clojure.test :refer :all] [metabase.driver.mongo.util :as mongo-util] [metabase.driver.util :as driver.u] [metabase.test :as mt]) (:import [com.mongodb DB MongoClient MongoClientException MongoClientOptions$Builder ReadPreference ServerAddress])) (defn- connect-mongo [opts] (let [connection-info (#'mongo-util/details->mongo-connection-info (#'mongo-util/normalize-details opts))] (#'mongo-util/connect connection-info))) (def connect-passthrough (fn [{map-type :type}] map-type)) (def srv-passthrough (fn [_] {:type :srv})) (deftest fqdn?-test (testing "test hostname is fqdn" (is (= true (#'mongo-util/fqdn? "db.mongo.com"))) (is (= true (#'mongo-util/fqdn? "replica-01.db.mongo.com"))) (is (= false (#'mongo-util/fqdn? "localhost"))) (is (= false (#'mongo-util/fqdn? "localhost.localdomain"))))) (deftest srv-conn-str-test (testing "test srv connection string" (is (= "mongodb+srv://test-user:test-pass@test-host.place.com/authdb" (#'mongo-util/srv-conn-str "test-user" "test-pass" "test-host.place.com" "authdb"))))) (deftest srv-toggle-test (testing "test that srv toggle works" (is (= :srv (with-redefs [mongo-util/srv-connection-info srv-passthrough mongo-util/connect connect-passthrough] (let [host "my.fake.domain" opts {:host host :port 1015 :user "test-user" :authdb "test-authdb" :pass "PI:PASSWORD:<PASSWORD>END_PI" :dbname "test-dbname" :ssl true :additional-options "" :use-srv true}] (connect-mongo opts))))) (is (= :normal (with-redefs [mongo-util/connect connect-passthrough] (let [host "localhost" opts {:host host :port 1010 :user "test-user" :authdb "test-authdb" :pass "PI:PASSWORD:<PASSWORD>END_PI" :dbname "test-dbname" :ssl true :additional-options "" :use-srv false}] (connect-mongo opts))))) (is (= :normal (with-redefs [mongo-util/connect connect-passthrough] (let [host "localhost.domain" opts {:host host :port 1010 :user "test-user" :authdb "test-authdb" :pass "PI:PASSWORD:<PASSWORD>END_PI" :dbname "test-dbname" :ssl true :additional-options ""}] (connect-mongo opts))))))) (deftest srv-connection-properties-test (testing "test that connection properties when using srv" (is (= "No SRV record available for host fake.fqdn.com" (try (let [host "fake.fqdn.com" opts {:host host :port 1015 :user "test-user" :authdb "test-authdb" :pass "PI:PASSWORD:<PASSWORD>END_PI" :dbname "test-dbname" :ssl true :additional-options "" :use-srv true} [^MongoClient mongo-client ^DB db] (connect-mongo opts) ^ServerAddress mongo-addr (-> mongo-client (.getAllAddress) first) mongo-host (-> mongo-addr .getHost) mongo-port (-> mongo-addr .getPort)] [mongo-host mongo-port]) (catch MongoClientException e (.getMessage e))))) (is (= "Using DNS SRV requires a FQDN for host" (try (let [host "host1" opts {:host host :port 1015 :user "test-user" :authdb "test-authdb" :pass "PI:PASSWORD:<PASSWORD>END_PI-passwd" :dbname "test-dbname" :ssl true :additional-options "" :use-srv true} [^MongoClient mongo-client ^DB db] (connect-mongo opts) ^ServerAddress mongo-addr (-> mongo-client (.getAllAddress) first) mongo-host (-> mongo-addr .getHost) mongo-port (-> mongo-addr .getPort)] [mongo-host mongo-port]) (catch Exception e (.getMessage e))))) (is (= "Unable to look up SRV record for host fake.fqdn.org" (try (let [host "fake.fqdn.org" opts {:host host :port 1015 :user "test-user" :authdb "test-authdb" :pass "PI:PASSWORD:<PASSWORD>END_PI" :dbname "test-dbname" :ssl true :additional-options "" :use-srv true} [^MongoClient mongo-client ^DB db] (connect-mongo opts) ^ServerAddress mongo-addr (-> mongo-client (.getAllAddress) first) mongo-host (-> mongo-addr .getHost) mongo-port (-> mongo-addr .getPort)] [mongo-host mongo-port]) (catch MongoClientException e (.getMessage e))))) (testing "test host and port are correct for both srv and normal" (let [host "localhost" opts {:host host :port 1010 :user "test-user" :authdb "test-authdb" :pass "PI:PASSWORD:<PASSWORD>END_PI" :dbname "test-dbname" :ssl true :additional-options ""} [^MongoClient mongo-client ^DB db] (connect-mongo opts) ^ServerAddress mongo-addr (-> mongo-client (.getAllAddress) first) mongo-host (-> mongo-addr .getHost) mongo-port (-> mongo-addr .getPort)] (is (= "localhost" mongo-host)) (is (= 1010 mongo-port)))))) (defn- connection-options-builder ^MongoClientOptions$Builder [& args] (apply #'mongo-util/connection-options-builder args)) (deftest additional-connection-options-test (testing "test that people can specify additional connection options like `?readPreference=nearest`" (is (= (ReadPreference/nearest) (.getReadPreference (-> (connection-options-builder :additional-options "readPreference=nearest") .build)))) (is (= (ReadPreference/secondaryPreferred) (.getReadPreference (-> (connection-options-builder :additional-options "readPreference=secondaryPreferred") .build)))) (testing "make sure we can specify multiple options" (let [opts (-> (connection-options-builder :additional-options "readPreference=secondary&replicaSet=test") .build)] (is (= "test" (.getRequiredReplicaSetName opts))) (is (= (ReadPreference/secondary) (.getReadPreference opts))))) (testing "make sure that invalid additional options throw an Exception" (is (thrown-with-msg? IllegalArgumentException #"No match for read preference of ternary" (-> (connection-options-builder :additional-options "readPreference=ternary") .build)))))) (deftest test-ssh-connection (testing "Gets an error when it can't connect to mongo via ssh tunnel" (mt/test-driver :mongo (is (thrown? java.net.ConnectException (try (let [engine :mongo details {:ssl false :password "PI:PASSWORD:<PASSWORD>END_PI" :tunnel-host "localhost" :tunnel-pass "PI:PASSWORD:<PASSWORD>END_PI" :port 5432 :dbname "test" :host "localhost" :tunnel-enabled true ;; we want to use a bogus port here on purpose - ;; so that locally, it gets a ConnectionRefused, ;; and in CI it does too. Apache's SSHD library ;; doesn't wrap every exception in an SshdException :tunnel-port 21212 :tunnel-user "bogus"}] (driver.u/can-connect-with-details? engine details :throw-exceptions)) (catch Throwable e (loop [^Throwable e e] (or (when (instance? java.net.ConnectException e) (throw e)) (some-> (.getCause e) recur))))))))))
[ { "context": "#########\n\n(ns cljfind.findsettings\n #^{:author \"Cary Clark\",\n :doc \"Defines the settings for a given fin", "end": 296, "score": 0.9998405575752258, "start": 286, "tag": "NAME", "value": "Cary Clark" } ]
clojure/cljfind/src/cljfind/findsettings.clj
clarkcb/xfind
0
;;; ############################################################################ ;;; ;;; findsettings.clj ;;; ;;; Defines the settings for a given find instance ;;; ;;; ############################################################################ (ns cljfind.findsettings #^{:author "Cary Clark", :doc "Defines the settings for a given find instance"} (:use [clojure.set :only (union)] [clojure.string :as str :only (split)] [cljfind.filetypes :only (from-name)])) (defrecord FindSettings [ archivesonly debug excludehidden includearchives in-archiveextensions in-archivefilepatterns in-dirpatterns in-extensions in-filepatterns in-filetypes listdirs listfiles out-archiveextensions out-archivefilepatterns out-dirpatterns out-extensions out-filepatterns out-filetypes paths printusage printversion recursive verbose ]) (def DEFAULT-SETTINGS (->FindSettings false ; archivesonly false ; debug true ; excludehidden false ; includearchives #{} ; in-archiveextensions #{} ; in-archivefilepatterns #{} ; in-dirpatterns #{} ; in-extensions #{} ; in-filepatterns #{} ; in-filetypes false ; listdirs false ; listfiles #{} ; out-archiveextensions #{} ; out-archivefilepatterns #{} ; out-dirpatterns #{} ; out-extensions #{} ; out-filepatterns #{} ; out-filetypes #{} ; paths false ; printusage false ; printversion true ; recursive false ; verbose )) (defn add-element [x coll] (conj coll x)) (defn add-extensions [settings exts extname] (if (empty? exts) settings (add-extensions (update-in settings [extname] #(add-element (first exts) %)) (rest exts) extname))) (defn add-extension [settings ext extname] (let [t (type ext)] (cond (= t (type [])) (add-extensions settings ext extname) :else (add-extensions settings (str/split ext #",") extname)))) (defn add-filetypes [settings types typesname] (if (empty? types) settings (add-filetypes (update-in settings [typesname] #(add-element (from-name (first types)) %)) (rest types) typesname))) (defn add-filetype [settings typ typesname] (let [t (type typ)] (cond (= t (type [])) (add-filetypes settings typ typesname) :else (add-filetypes settings (str/split typ #",") typesname)))) (defn add-paths [settings paths] (if (empty? paths) settings (add-paths (update-in settings [:paths] #(add-element (first paths) %)) (rest paths)))) (defn add-path [settings path] (let [t (type path)] (cond (= t (type [])) (add-paths settings path) :else (add-paths settings [path])))) (defn add-patterns [settings pats patname] (if (empty? pats) settings (add-patterns (update-in settings [patname] #(add-element (re-pattern (first pats)) %)) (rest pats) patname))) (defn add-pattern [settings p patname] (let [t (type p)] (cond (= t (type [])) (add-patterns settings p patname) :else (add-patterns settings [p] patname)))) (defn set-num [settings n numname] (let [t (type n)] (cond (= t java.lang.Long) (assoc settings numname n) :else (assoc settings numname (read-string n))))) (defn set-archivesonly [settings b] (let [with-archivesonly (assoc settings :archivesonly b)] (if b (assoc with-archivesonly :includearchives true) with-archivesonly))) (defn set-debug [settings b] (let [with-debug (assoc settings :debug true)] (if b (assoc with-debug :verbose true) with-debug)))
110636
;;; ############################################################################ ;;; ;;; findsettings.clj ;;; ;;; Defines the settings for a given find instance ;;; ;;; ############################################################################ (ns cljfind.findsettings #^{:author "<NAME>", :doc "Defines the settings for a given find instance"} (:use [clojure.set :only (union)] [clojure.string :as str :only (split)] [cljfind.filetypes :only (from-name)])) (defrecord FindSettings [ archivesonly debug excludehidden includearchives in-archiveextensions in-archivefilepatterns in-dirpatterns in-extensions in-filepatterns in-filetypes listdirs listfiles out-archiveextensions out-archivefilepatterns out-dirpatterns out-extensions out-filepatterns out-filetypes paths printusage printversion recursive verbose ]) (def DEFAULT-SETTINGS (->FindSettings false ; archivesonly false ; debug true ; excludehidden false ; includearchives #{} ; in-archiveextensions #{} ; in-archivefilepatterns #{} ; in-dirpatterns #{} ; in-extensions #{} ; in-filepatterns #{} ; in-filetypes false ; listdirs false ; listfiles #{} ; out-archiveextensions #{} ; out-archivefilepatterns #{} ; out-dirpatterns #{} ; out-extensions #{} ; out-filepatterns #{} ; out-filetypes #{} ; paths false ; printusage false ; printversion true ; recursive false ; verbose )) (defn add-element [x coll] (conj coll x)) (defn add-extensions [settings exts extname] (if (empty? exts) settings (add-extensions (update-in settings [extname] #(add-element (first exts) %)) (rest exts) extname))) (defn add-extension [settings ext extname] (let [t (type ext)] (cond (= t (type [])) (add-extensions settings ext extname) :else (add-extensions settings (str/split ext #",") extname)))) (defn add-filetypes [settings types typesname] (if (empty? types) settings (add-filetypes (update-in settings [typesname] #(add-element (from-name (first types)) %)) (rest types) typesname))) (defn add-filetype [settings typ typesname] (let [t (type typ)] (cond (= t (type [])) (add-filetypes settings typ typesname) :else (add-filetypes settings (str/split typ #",") typesname)))) (defn add-paths [settings paths] (if (empty? paths) settings (add-paths (update-in settings [:paths] #(add-element (first paths) %)) (rest paths)))) (defn add-path [settings path] (let [t (type path)] (cond (= t (type [])) (add-paths settings path) :else (add-paths settings [path])))) (defn add-patterns [settings pats patname] (if (empty? pats) settings (add-patterns (update-in settings [patname] #(add-element (re-pattern (first pats)) %)) (rest pats) patname))) (defn add-pattern [settings p patname] (let [t (type p)] (cond (= t (type [])) (add-patterns settings p patname) :else (add-patterns settings [p] patname)))) (defn set-num [settings n numname] (let [t (type n)] (cond (= t java.lang.Long) (assoc settings numname n) :else (assoc settings numname (read-string n))))) (defn set-archivesonly [settings b] (let [with-archivesonly (assoc settings :archivesonly b)] (if b (assoc with-archivesonly :includearchives true) with-archivesonly))) (defn set-debug [settings b] (let [with-debug (assoc settings :debug true)] (if b (assoc with-debug :verbose true) with-debug)))
true
;;; ############################################################################ ;;; ;;; findsettings.clj ;;; ;;; Defines the settings for a given find instance ;;; ;;; ############################################################################ (ns cljfind.findsettings #^{:author "PI:NAME:<NAME>END_PI", :doc "Defines the settings for a given find instance"} (:use [clojure.set :only (union)] [clojure.string :as str :only (split)] [cljfind.filetypes :only (from-name)])) (defrecord FindSettings [ archivesonly debug excludehidden includearchives in-archiveextensions in-archivefilepatterns in-dirpatterns in-extensions in-filepatterns in-filetypes listdirs listfiles out-archiveextensions out-archivefilepatterns out-dirpatterns out-extensions out-filepatterns out-filetypes paths printusage printversion recursive verbose ]) (def DEFAULT-SETTINGS (->FindSettings false ; archivesonly false ; debug true ; excludehidden false ; includearchives #{} ; in-archiveextensions #{} ; in-archivefilepatterns #{} ; in-dirpatterns #{} ; in-extensions #{} ; in-filepatterns #{} ; in-filetypes false ; listdirs false ; listfiles #{} ; out-archiveextensions #{} ; out-archivefilepatterns #{} ; out-dirpatterns #{} ; out-extensions #{} ; out-filepatterns #{} ; out-filetypes #{} ; paths false ; printusage false ; printversion true ; recursive false ; verbose )) (defn add-element [x coll] (conj coll x)) (defn add-extensions [settings exts extname] (if (empty? exts) settings (add-extensions (update-in settings [extname] #(add-element (first exts) %)) (rest exts) extname))) (defn add-extension [settings ext extname] (let [t (type ext)] (cond (= t (type [])) (add-extensions settings ext extname) :else (add-extensions settings (str/split ext #",") extname)))) (defn add-filetypes [settings types typesname] (if (empty? types) settings (add-filetypes (update-in settings [typesname] #(add-element (from-name (first types)) %)) (rest types) typesname))) (defn add-filetype [settings typ typesname] (let [t (type typ)] (cond (= t (type [])) (add-filetypes settings typ typesname) :else (add-filetypes settings (str/split typ #",") typesname)))) (defn add-paths [settings paths] (if (empty? paths) settings (add-paths (update-in settings [:paths] #(add-element (first paths) %)) (rest paths)))) (defn add-path [settings path] (let [t (type path)] (cond (= t (type [])) (add-paths settings path) :else (add-paths settings [path])))) (defn add-patterns [settings pats patname] (if (empty? pats) settings (add-patterns (update-in settings [patname] #(add-element (re-pattern (first pats)) %)) (rest pats) patname))) (defn add-pattern [settings p patname] (let [t (type p)] (cond (= t (type [])) (add-patterns settings p patname) :else (add-patterns settings [p] patname)))) (defn set-num [settings n numname] (let [t (type n)] (cond (= t java.lang.Long) (assoc settings numname n) :else (assoc settings numname (read-string n))))) (defn set-archivesonly [settings b] (let [with-archivesonly (assoc settings :archivesonly b)] (if b (assoc with-archivesonly :includearchives true) with-archivesonly))) (defn set-debug [settings b] (let [with-debug (assoc settings :debug true)] (if b (assoc with-debug :verbose true) with-debug)))
[ { "context": ";;; Copyright 2013 Mitchell Kember. Subject to the MIT License.\n\n(ns mini-pinions.ve", "end": 34, "score": 0.999890923500061, "start": 19, "tag": "NAME", "value": "Mitchell Kember" } ]
src/mini_pinions/vector.clj
mk12/mini-pinions
1
;;; Copyright 2013 Mitchell Kember. Subject to the MIT License. (ns mini-pinions.vector "Provides essential Euclidean vector operations." (:import java.lang.Math)) ;;; These functions are elegant, but very, very inefficient. That being said, ;;; "We should forget about small efficiencies, say about 97% of the time: ;;; premature optimization is the root of all evil" (Donald Knuth). ;;; UPDATE: I have made it slightly more efficient in case the vectors are ;;; slowing things down. It seems that graphics is the bottleneck, but I am ;;; going to leave it implemented like this. (defn make [x y] [^float x ^float y]) (def zero (make 0 0)) (defn x [v] (v 0)) (defn y [v] (v 1)) (defn add [[x1 y1] [x2 y2]] [(+ x1 x2) (+ y1 y2)]) (defn sub [[x1 y1] [x2 y2]] [(- x1 x2) (- y1 y2)]) (defn scale [k [x y]] [(* x k) (* y k)]) (defn div [k [x y]] [(/ x k) (/ y k)]) (defn dot [[x1 y1] [x2 y2]] (+ (* x1 x2) (* y1 y2))) (defn norm-sq [v] (dot v v)) (defn norm [v] (Math/sqrt (norm-sq v))) (defn normalize [v] (div (norm v) v)) (defn negate [v] (scale -1 v))
112876
;;; Copyright 2013 <NAME>. Subject to the MIT License. (ns mini-pinions.vector "Provides essential Euclidean vector operations." (:import java.lang.Math)) ;;; These functions are elegant, but very, very inefficient. That being said, ;;; "We should forget about small efficiencies, say about 97% of the time: ;;; premature optimization is the root of all evil" (Donald Knuth). ;;; UPDATE: I have made it slightly more efficient in case the vectors are ;;; slowing things down. It seems that graphics is the bottleneck, but I am ;;; going to leave it implemented like this. (defn make [x y] [^float x ^float y]) (def zero (make 0 0)) (defn x [v] (v 0)) (defn y [v] (v 1)) (defn add [[x1 y1] [x2 y2]] [(+ x1 x2) (+ y1 y2)]) (defn sub [[x1 y1] [x2 y2]] [(- x1 x2) (- y1 y2)]) (defn scale [k [x y]] [(* x k) (* y k)]) (defn div [k [x y]] [(/ x k) (/ y k)]) (defn dot [[x1 y1] [x2 y2]] (+ (* x1 x2) (* y1 y2))) (defn norm-sq [v] (dot v v)) (defn norm [v] (Math/sqrt (norm-sq v))) (defn normalize [v] (div (norm v) v)) (defn negate [v] (scale -1 v))
true
;;; Copyright 2013 PI:NAME:<NAME>END_PI. Subject to the MIT License. (ns mini-pinions.vector "Provides essential Euclidean vector operations." (:import java.lang.Math)) ;;; These functions are elegant, but very, very inefficient. That being said, ;;; "We should forget about small efficiencies, say about 97% of the time: ;;; premature optimization is the root of all evil" (Donald Knuth). ;;; UPDATE: I have made it slightly more efficient in case the vectors are ;;; slowing things down. It seems that graphics is the bottleneck, but I am ;;; going to leave it implemented like this. (defn make [x y] [^float x ^float y]) (def zero (make 0 0)) (defn x [v] (v 0)) (defn y [v] (v 1)) (defn add [[x1 y1] [x2 y2]] [(+ x1 x2) (+ y1 y2)]) (defn sub [[x1 y1] [x2 y2]] [(- x1 x2) (- y1 y2)]) (defn scale [k [x y]] [(* x k) (* y k)]) (defn div [k [x y]] [(/ x k) (/ y k)]) (defn dot [[x1 y1] [x2 y2]] (+ (* x1 x2) (* y1 y2))) (defn norm-sq [v] (dot v v)) (defn norm [v] (Math/sqrt (norm-sq v))) (defn normalize [v] (div (norm v) v)) (defn negate [v] (scale -1 v))
[ { "context": "(let [;; Create User\n user {\"user/name\" \"Karen Smith\"\n \"user/email\" \"smithka@testing.co", "end": 7848, "score": 0.9994227886199951, "start": 7837, "tag": "NAME", "value": "Karen Smith" }, { "context": "name\" \"Karen Smith\"\n \"user/email\" \"smithka@testing.com\"\n \"user/username\" \"smithk\"\n ", "end": 7899, "score": 0.9999290108680725, "start": 7880, "tag": "EMAIL", "value": "smithka@testing.com" }, { "context": "hka@testing.com\"\n \"user/username\" \"smithk\"\n \"user/password\" \"insecure\"}\n ", "end": 7940, "score": 0.9992691278457642, "start": 7934, "tag": "USERNAME", "value": "smithk" }, { "context": "ername\" \"smithk\"\n \"user/password\" \"insecure\"}\n req (-> (rtucore/req-w-std-hdrs rumet", "end": 7983, "score": 0.9953968524932861, "start": 7975, "tag": "PASSWORD", "value": "insecure" }, { "context": "tion\n fuelstation {\"fpfuelstation/name\" \"Joe's\"\n \"fpfuelstation/street\" \"1", "end": 10475, "score": 0.9994561076164246, "start": 10470, "tag": "NAME", "value": "Joe's" }, { "context": "tion\n fuelstation {\"fpfuelstation/name\" \"Andy's\"\n \"fpfuelstation/street\" \"1", "end": 12046, "score": 0.9994326233863831, "start": 12040, "tag": "NAME", "value": "Andy's" }, { "context": "tion\n fuelstation {\"fpfuelstation/name\" \"Ed's\"\n \"fpfuelstation/street\" \"1", "end": 13613, "score": 0.9995819330215454, "start": 13609, "tag": "NAME", "value": "Ed's" } ]
test/pe_fp_rest/resource/price_stream/price_stream_res_test.clj
evanspa/pe-gasjot-rest
0
(ns pe-fp-rest.resource.price-stream.price-stream-res-test (:require [clojure.test :refer :all] [clojure.data.json :as json] [clj-time.core :as t] [clj-time.coerce :as c] [clojure.tools.logging :as log] [compojure.core :refer [defroutes ANY]] [ring.middleware.cookies :refer [wrap-cookies]] [compojure.handler :as handler] [ring.mock.request :as mock] [pe-fp-rest.resource.vehicle.vehicles-res :as vehsres] [pe-fp-rest.resource.vehicle.version.vehicles-res-v001] [pe-fp-rest.resource.fuelstation.fuelstations-res :as fssres] [pe-fp-rest.resource.fuelstation.version.fuelstations-res-v001] [pe-fp-rest.resource.fplog.fplogs-res :as fplogsres] [pe-fp-rest.resource.fplog.version.fplogs-res-v001] [pe-fp-rest.resource.fplog.fplog-res :as fplogres] [pe-fp-rest.resource.fplog.version.fplog-res-v001] [pe-fp-rest.resource.price-stream.price-stream-res :as pricestreamres] [pe-fp-rest.resource.price-stream.version.price-stream-res-v001] [pe-fp-rest.meta :as meta] [pe-fp-core.core :as fpcore] [pe-rest-testutils.core :as rtucore] [pe-core-utils.core :as ucore] [pe-rest-utils.core :as rucore] [pe-jdbc-utils.core :as jcore] [pe-rest-utils.meta :as rumeta] [pe-user-core.core :as usercore] [pe-user-rest.meta :as usermeta] [pe-user-rest.resource.users-res :as userres] [pe-fp-rest.test-utils :refer [fpmt-subtype-prefix fp-auth-scheme fp-auth-scheme-param-name base-url fphdr-auth-token fphdr-error-mask fphdr-establish-session entity-uri-prefix fphdr-establish-session fphdr-if-unmodified-since fphdr-if-modified-since users-uri-template vehicles-uri-template fuelstations-uri-template fplogs-uri-template fplog-uri-template price-stream-uri-template db-spec fixture-maker users-route empty-embedded-resources-fn empty-links-fn err-notification-mustache-template err-subject err-from-email err-to-email]])) (defroutes routes users-route (ANY price-stream-uri-template [] (pricestreamres/price-stream-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask base-url entity-uri-prefix err-notification-mustache-template err-subject err-from-email err-to-email 50)) (ANY vehicles-uri-template [user-id] (vehsres/vehicles-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask fp-auth-scheme fp-auth-scheme-param-name base-url entity-uri-prefix (Long. user-id) empty-embedded-resources-fn empty-links-fn err-notification-mustache-template err-subject err-from-email err-to-email)) (ANY fuelstations-uri-template [user-id] (fssres/fuelstations-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask fp-auth-scheme fp-auth-scheme-param-name base-url entity-uri-prefix (Long. user-id) empty-embedded-resources-fn empty-links-fn err-notification-mustache-template err-subject err-from-email err-to-email)) (ANY fplogs-uri-template [user-id] (fplogsres/fplogs-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask fp-auth-scheme fp-auth-scheme-param-name base-url entity-uri-prefix (Long. user-id) empty-embedded-resources-fn empty-links-fn err-notification-mustache-template err-subject err-from-email err-to-email)) (ANY fplog-uri-template [user-id fplog-id] (fplogres/fplog-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask fp-auth-scheme fp-auth-scheme-param-name base-url entity-uri-prefix (Long. user-id) (Long. fplog-id) empty-embedded-resources-fn empty-links-fn fphdr-if-unmodified-since fphdr-if-modified-since err-notification-mustache-template err-subject err-from-email err-to-email))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Middleware-decorated app ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def app (-> routes (handler/api) (wrap-cookies))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Fixtures ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (use-fixtures :each (fixture-maker)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; The Tests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftest integration-tests-1 (testing "Fetch price event stream" (let [;; Create User user {"user/name" "Karen Smith" "user/email" "smithka@testing.com" "user/username" "smithk" "user/password" "insecure"} req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (usermeta/mt-subtype-user fpmt-subtype-prefix) usermeta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post users-uri-template) (rtucore/header fphdr-establish-session "true") (mock/body (json/write-str user)) (mock/content-type (rucore/content-type rumeta/mt-type (usermeta/mt-subtype-user fpmt-subtype-prefix) usermeta/v001 "json" "UTF-8"))) resp (app req) hdrs (:headers resp) user-location-str (get hdrs "location") resp-user-id-str (rtucore/last-url-part user-location-str) auth-token (get hdrs fphdr-auth-token) ;; Create Vehicle vehicle {"fpvehicle/name" "Mazda CX-9" "fpvehicle/default-octane" 87} req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-vehicle fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-vehicles)) (mock/body (json/write-str vehicle)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-vehicle fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token))) resp (app req) veh-300zx-location-str (get (:headers resp) "location") ;; Create Sacramento, CA fuel station fuelstation {"fpfuelstation/name" "Joe's" "fpfuelstation/street" "101 Main Street" "fpfuelstation/city" "Charlotte" "fpfuelstation/state" "NC" "fpfuelstation/zip" "28277" "fpfuelstation/longitude" -121.4944 "fpfuelstation/latitude" 38.581572} fuelstations-uri (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-fuelstations) req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post fuelstations-uri) (mock/body (json/write-str fuelstation)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token))) resp (app req) hdrs (:headers resp) fs-ca-location-str (get hdrs "location") ;; Create Albany, NY fuel station fuelstation {"fpfuelstation/name" "Andy's" "fpfuelstation/street" "101 Main Street" "fpfuelstation/city" "Albany" "fpfuelstation/state" "NY" "fpfuelstation/zip" "12207" "fpfuelstation/longitude" -73.756232 "fpfuelstation/latitude" 42.652579} fuelstations-uri (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-fuelstations) req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post fuelstations-uri) (mock/body (json/write-str fuelstation)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token))) resp (app req) hdrs (:headers resp) fs-ny-location-str (get hdrs "location") ;; Create Houston, TX fuelstation fuelstation {"fpfuelstation/name" "Ed's" "fpfuelstation/street" "103 Main Street" "fpfuelstation/city" "Providence" "fpfuelstation/state" "NC" "fpfuelstation/zip" "28278" "fpfuelstation/longitude" -95.369803 "fpfuelstation/latitude" 29.760} req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-fuelstations)) (mock/body (json/write-str fuelstation)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token))) resp (app req) hdrs (:headers resp) fs-tx-location-str (get hdrs "location")] (letfn [(new-fplog [fs purchased-at gallon-price octane] (let [fplog {"fplog/vehicle" veh-300zx-location-str "fplog/fuelstation" fs "fplog/purchased-at" (c/to-long purchased-at) "fplog/got-car-wash" true "fplog/car-wash-per-gal-discount" 0.08 "fplog/num-gallons" 14.3 "fplog/octane" octane "fplog/is-diesel" false "fplog/odometer" 15518 "fplog/gallon-price" gallon-price} fplogs-uri (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-fuelpurchase-logs) req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-fplog fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post fplogs-uri) (mock/body (json/write-str fplog)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-fplog fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token)))] (app req)))] (let [t1 (t/now)] (new-fplog fs-ca-location-str t1 4.99 87) (new-fplog fs-tx-location-str t1 2.19 87) (new-fplog fs-ny-location-str t1 3.39 87)) (let [price-stream-filter {"price-stream-filter/fs-latitude" 42.814 "price-stream-filter/fs-longitude" -73.939 "price-stream-filter/fs-distance-within" 10000000 "price-stream-filter/max-results" 20 "price-stream-filter/sort-by" [["f.gallon_price" "asc"] ["distance" "asc"] ["f.purchased_at" "desc"]]} price-stream-uri (str base-url entity-uri-prefix meta/pathcomp-price-stream) req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-price-stream fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post price-stream-uri) (mock/body (json/write-str price-stream-filter)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-price-stream fpmt-subtype-prefix) meta/v001 "json" "UTF-8"))) resp (app req)] (testing "status code" (is (= 200 (:status resp)))) (let [hdrs (:headers resp) resp-body-stream (:body resp) pct (rucore/parse-media-type (get hdrs "Content-Type")) charset (get rumeta/char-sets (:charset pct)) price-stream (rucore/read-res pct resp-body-stream charset)] (is (not (nil? price-stream))) (let [price-events (get price-stream "price-event-stream")] (is (= 3 (count price-events))) (let [[event-1 event-2 event-3] price-events] (is (= 2.19 (get event-1 "price-event/price"))) (is (= 87 (get event-1 "price-event/octane"))) (is (= false (get event-1 "price-event/is-diesel"))) (is (= 29.760 (get event-1 "price-event/fs-latitude"))) (is (= -95.369803 (get event-1 "price-event/fs-longitude"))) (is (= 3.39 (get event-2 "price-event/price"))) (is (= 4.99 (get event-3 "price-event/price")))))))))))
78622
(ns pe-fp-rest.resource.price-stream.price-stream-res-test (:require [clojure.test :refer :all] [clojure.data.json :as json] [clj-time.core :as t] [clj-time.coerce :as c] [clojure.tools.logging :as log] [compojure.core :refer [defroutes ANY]] [ring.middleware.cookies :refer [wrap-cookies]] [compojure.handler :as handler] [ring.mock.request :as mock] [pe-fp-rest.resource.vehicle.vehicles-res :as vehsres] [pe-fp-rest.resource.vehicle.version.vehicles-res-v001] [pe-fp-rest.resource.fuelstation.fuelstations-res :as fssres] [pe-fp-rest.resource.fuelstation.version.fuelstations-res-v001] [pe-fp-rest.resource.fplog.fplogs-res :as fplogsres] [pe-fp-rest.resource.fplog.version.fplogs-res-v001] [pe-fp-rest.resource.fplog.fplog-res :as fplogres] [pe-fp-rest.resource.fplog.version.fplog-res-v001] [pe-fp-rest.resource.price-stream.price-stream-res :as pricestreamres] [pe-fp-rest.resource.price-stream.version.price-stream-res-v001] [pe-fp-rest.meta :as meta] [pe-fp-core.core :as fpcore] [pe-rest-testutils.core :as rtucore] [pe-core-utils.core :as ucore] [pe-rest-utils.core :as rucore] [pe-jdbc-utils.core :as jcore] [pe-rest-utils.meta :as rumeta] [pe-user-core.core :as usercore] [pe-user-rest.meta :as usermeta] [pe-user-rest.resource.users-res :as userres] [pe-fp-rest.test-utils :refer [fpmt-subtype-prefix fp-auth-scheme fp-auth-scheme-param-name base-url fphdr-auth-token fphdr-error-mask fphdr-establish-session entity-uri-prefix fphdr-establish-session fphdr-if-unmodified-since fphdr-if-modified-since users-uri-template vehicles-uri-template fuelstations-uri-template fplogs-uri-template fplog-uri-template price-stream-uri-template db-spec fixture-maker users-route empty-embedded-resources-fn empty-links-fn err-notification-mustache-template err-subject err-from-email err-to-email]])) (defroutes routes users-route (ANY price-stream-uri-template [] (pricestreamres/price-stream-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask base-url entity-uri-prefix err-notification-mustache-template err-subject err-from-email err-to-email 50)) (ANY vehicles-uri-template [user-id] (vehsres/vehicles-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask fp-auth-scheme fp-auth-scheme-param-name base-url entity-uri-prefix (Long. user-id) empty-embedded-resources-fn empty-links-fn err-notification-mustache-template err-subject err-from-email err-to-email)) (ANY fuelstations-uri-template [user-id] (fssres/fuelstations-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask fp-auth-scheme fp-auth-scheme-param-name base-url entity-uri-prefix (Long. user-id) empty-embedded-resources-fn empty-links-fn err-notification-mustache-template err-subject err-from-email err-to-email)) (ANY fplogs-uri-template [user-id] (fplogsres/fplogs-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask fp-auth-scheme fp-auth-scheme-param-name base-url entity-uri-prefix (Long. user-id) empty-embedded-resources-fn empty-links-fn err-notification-mustache-template err-subject err-from-email err-to-email)) (ANY fplog-uri-template [user-id fplog-id] (fplogres/fplog-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask fp-auth-scheme fp-auth-scheme-param-name base-url entity-uri-prefix (Long. user-id) (Long. fplog-id) empty-embedded-resources-fn empty-links-fn fphdr-if-unmodified-since fphdr-if-modified-since err-notification-mustache-template err-subject err-from-email err-to-email))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Middleware-decorated app ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def app (-> routes (handler/api) (wrap-cookies))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Fixtures ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (use-fixtures :each (fixture-maker)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; The Tests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftest integration-tests-1 (testing "Fetch price event stream" (let [;; Create User user {"user/name" "<NAME>" "user/email" "<EMAIL>" "user/username" "smithk" "user/password" "<PASSWORD>"} req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (usermeta/mt-subtype-user fpmt-subtype-prefix) usermeta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post users-uri-template) (rtucore/header fphdr-establish-session "true") (mock/body (json/write-str user)) (mock/content-type (rucore/content-type rumeta/mt-type (usermeta/mt-subtype-user fpmt-subtype-prefix) usermeta/v001 "json" "UTF-8"))) resp (app req) hdrs (:headers resp) user-location-str (get hdrs "location") resp-user-id-str (rtucore/last-url-part user-location-str) auth-token (get hdrs fphdr-auth-token) ;; Create Vehicle vehicle {"fpvehicle/name" "Mazda CX-9" "fpvehicle/default-octane" 87} req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-vehicle fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-vehicles)) (mock/body (json/write-str vehicle)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-vehicle fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token))) resp (app req) veh-300zx-location-str (get (:headers resp) "location") ;; Create Sacramento, CA fuel station fuelstation {"fpfuelstation/name" "<NAME>" "fpfuelstation/street" "101 Main Street" "fpfuelstation/city" "Charlotte" "fpfuelstation/state" "NC" "fpfuelstation/zip" "28277" "fpfuelstation/longitude" -121.4944 "fpfuelstation/latitude" 38.581572} fuelstations-uri (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-fuelstations) req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post fuelstations-uri) (mock/body (json/write-str fuelstation)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token))) resp (app req) hdrs (:headers resp) fs-ca-location-str (get hdrs "location") ;; Create Albany, NY fuel station fuelstation {"fpfuelstation/name" "<NAME>" "fpfuelstation/street" "101 Main Street" "fpfuelstation/city" "Albany" "fpfuelstation/state" "NY" "fpfuelstation/zip" "12207" "fpfuelstation/longitude" -73.756232 "fpfuelstation/latitude" 42.652579} fuelstations-uri (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-fuelstations) req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post fuelstations-uri) (mock/body (json/write-str fuelstation)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token))) resp (app req) hdrs (:headers resp) fs-ny-location-str (get hdrs "location") ;; Create Houston, TX fuelstation fuelstation {"fpfuelstation/name" "<NAME>" "fpfuelstation/street" "103 Main Street" "fpfuelstation/city" "Providence" "fpfuelstation/state" "NC" "fpfuelstation/zip" "28278" "fpfuelstation/longitude" -95.369803 "fpfuelstation/latitude" 29.760} req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-fuelstations)) (mock/body (json/write-str fuelstation)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token))) resp (app req) hdrs (:headers resp) fs-tx-location-str (get hdrs "location")] (letfn [(new-fplog [fs purchased-at gallon-price octane] (let [fplog {"fplog/vehicle" veh-300zx-location-str "fplog/fuelstation" fs "fplog/purchased-at" (c/to-long purchased-at) "fplog/got-car-wash" true "fplog/car-wash-per-gal-discount" 0.08 "fplog/num-gallons" 14.3 "fplog/octane" octane "fplog/is-diesel" false "fplog/odometer" 15518 "fplog/gallon-price" gallon-price} fplogs-uri (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-fuelpurchase-logs) req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-fplog fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post fplogs-uri) (mock/body (json/write-str fplog)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-fplog fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token)))] (app req)))] (let [t1 (t/now)] (new-fplog fs-ca-location-str t1 4.99 87) (new-fplog fs-tx-location-str t1 2.19 87) (new-fplog fs-ny-location-str t1 3.39 87)) (let [price-stream-filter {"price-stream-filter/fs-latitude" 42.814 "price-stream-filter/fs-longitude" -73.939 "price-stream-filter/fs-distance-within" 10000000 "price-stream-filter/max-results" 20 "price-stream-filter/sort-by" [["f.gallon_price" "asc"] ["distance" "asc"] ["f.purchased_at" "desc"]]} price-stream-uri (str base-url entity-uri-prefix meta/pathcomp-price-stream) req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-price-stream fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post price-stream-uri) (mock/body (json/write-str price-stream-filter)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-price-stream fpmt-subtype-prefix) meta/v001 "json" "UTF-8"))) resp (app req)] (testing "status code" (is (= 200 (:status resp)))) (let [hdrs (:headers resp) resp-body-stream (:body resp) pct (rucore/parse-media-type (get hdrs "Content-Type")) charset (get rumeta/char-sets (:charset pct)) price-stream (rucore/read-res pct resp-body-stream charset)] (is (not (nil? price-stream))) (let [price-events (get price-stream "price-event-stream")] (is (= 3 (count price-events))) (let [[event-1 event-2 event-3] price-events] (is (= 2.19 (get event-1 "price-event/price"))) (is (= 87 (get event-1 "price-event/octane"))) (is (= false (get event-1 "price-event/is-diesel"))) (is (= 29.760 (get event-1 "price-event/fs-latitude"))) (is (= -95.369803 (get event-1 "price-event/fs-longitude"))) (is (= 3.39 (get event-2 "price-event/price"))) (is (= 4.99 (get event-3 "price-event/price")))))))))))
true
(ns pe-fp-rest.resource.price-stream.price-stream-res-test (:require [clojure.test :refer :all] [clojure.data.json :as json] [clj-time.core :as t] [clj-time.coerce :as c] [clojure.tools.logging :as log] [compojure.core :refer [defroutes ANY]] [ring.middleware.cookies :refer [wrap-cookies]] [compojure.handler :as handler] [ring.mock.request :as mock] [pe-fp-rest.resource.vehicle.vehicles-res :as vehsres] [pe-fp-rest.resource.vehicle.version.vehicles-res-v001] [pe-fp-rest.resource.fuelstation.fuelstations-res :as fssres] [pe-fp-rest.resource.fuelstation.version.fuelstations-res-v001] [pe-fp-rest.resource.fplog.fplogs-res :as fplogsres] [pe-fp-rest.resource.fplog.version.fplogs-res-v001] [pe-fp-rest.resource.fplog.fplog-res :as fplogres] [pe-fp-rest.resource.fplog.version.fplog-res-v001] [pe-fp-rest.resource.price-stream.price-stream-res :as pricestreamres] [pe-fp-rest.resource.price-stream.version.price-stream-res-v001] [pe-fp-rest.meta :as meta] [pe-fp-core.core :as fpcore] [pe-rest-testutils.core :as rtucore] [pe-core-utils.core :as ucore] [pe-rest-utils.core :as rucore] [pe-jdbc-utils.core :as jcore] [pe-rest-utils.meta :as rumeta] [pe-user-core.core :as usercore] [pe-user-rest.meta :as usermeta] [pe-user-rest.resource.users-res :as userres] [pe-fp-rest.test-utils :refer [fpmt-subtype-prefix fp-auth-scheme fp-auth-scheme-param-name base-url fphdr-auth-token fphdr-error-mask fphdr-establish-session entity-uri-prefix fphdr-establish-session fphdr-if-unmodified-since fphdr-if-modified-since users-uri-template vehicles-uri-template fuelstations-uri-template fplogs-uri-template fplog-uri-template price-stream-uri-template db-spec fixture-maker users-route empty-embedded-resources-fn empty-links-fn err-notification-mustache-template err-subject err-from-email err-to-email]])) (defroutes routes users-route (ANY price-stream-uri-template [] (pricestreamres/price-stream-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask base-url entity-uri-prefix err-notification-mustache-template err-subject err-from-email err-to-email 50)) (ANY vehicles-uri-template [user-id] (vehsres/vehicles-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask fp-auth-scheme fp-auth-scheme-param-name base-url entity-uri-prefix (Long. user-id) empty-embedded-resources-fn empty-links-fn err-notification-mustache-template err-subject err-from-email err-to-email)) (ANY fuelstations-uri-template [user-id] (fssres/fuelstations-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask fp-auth-scheme fp-auth-scheme-param-name base-url entity-uri-prefix (Long. user-id) empty-embedded-resources-fn empty-links-fn err-notification-mustache-template err-subject err-from-email err-to-email)) (ANY fplogs-uri-template [user-id] (fplogsres/fplogs-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask fp-auth-scheme fp-auth-scheme-param-name base-url entity-uri-prefix (Long. user-id) empty-embedded-resources-fn empty-links-fn err-notification-mustache-template err-subject err-from-email err-to-email)) (ANY fplog-uri-template [user-id fplog-id] (fplogres/fplog-res db-spec fpmt-subtype-prefix fphdr-auth-token fphdr-error-mask fp-auth-scheme fp-auth-scheme-param-name base-url entity-uri-prefix (Long. user-id) (Long. fplog-id) empty-embedded-resources-fn empty-links-fn fphdr-if-unmodified-since fphdr-if-modified-since err-notification-mustache-template err-subject err-from-email err-to-email))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Middleware-decorated app ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def app (-> routes (handler/api) (wrap-cookies))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Fixtures ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (use-fixtures :each (fixture-maker)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; The Tests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftest integration-tests-1 (testing "Fetch price event stream" (let [;; Create User user {"user/name" "PI:NAME:<NAME>END_PI" "user/email" "PI:EMAIL:<EMAIL>END_PI" "user/username" "smithk" "user/password" "PI:PASSWORD:<PASSWORD>END_PI"} req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (usermeta/mt-subtype-user fpmt-subtype-prefix) usermeta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post users-uri-template) (rtucore/header fphdr-establish-session "true") (mock/body (json/write-str user)) (mock/content-type (rucore/content-type rumeta/mt-type (usermeta/mt-subtype-user fpmt-subtype-prefix) usermeta/v001 "json" "UTF-8"))) resp (app req) hdrs (:headers resp) user-location-str (get hdrs "location") resp-user-id-str (rtucore/last-url-part user-location-str) auth-token (get hdrs fphdr-auth-token) ;; Create Vehicle vehicle {"fpvehicle/name" "Mazda CX-9" "fpvehicle/default-octane" 87} req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-vehicle fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-vehicles)) (mock/body (json/write-str vehicle)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-vehicle fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token))) resp (app req) veh-300zx-location-str (get (:headers resp) "location") ;; Create Sacramento, CA fuel station fuelstation {"fpfuelstation/name" "PI:NAME:<NAME>END_PI" "fpfuelstation/street" "101 Main Street" "fpfuelstation/city" "Charlotte" "fpfuelstation/state" "NC" "fpfuelstation/zip" "28277" "fpfuelstation/longitude" -121.4944 "fpfuelstation/latitude" 38.581572} fuelstations-uri (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-fuelstations) req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post fuelstations-uri) (mock/body (json/write-str fuelstation)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token))) resp (app req) hdrs (:headers resp) fs-ca-location-str (get hdrs "location") ;; Create Albany, NY fuel station fuelstation {"fpfuelstation/name" "PI:NAME:<NAME>END_PI" "fpfuelstation/street" "101 Main Street" "fpfuelstation/city" "Albany" "fpfuelstation/state" "NY" "fpfuelstation/zip" "12207" "fpfuelstation/longitude" -73.756232 "fpfuelstation/latitude" 42.652579} fuelstations-uri (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-fuelstations) req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post fuelstations-uri) (mock/body (json/write-str fuelstation)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token))) resp (app req) hdrs (:headers resp) fs-ny-location-str (get hdrs "location") ;; Create Houston, TX fuelstation fuelstation {"fpfuelstation/name" "PI:NAME:<NAME>END_PI" "fpfuelstation/street" "103 Main Street" "fpfuelstation/city" "Providence" "fpfuelstation/state" "NC" "fpfuelstation/zip" "28278" "fpfuelstation/longitude" -95.369803 "fpfuelstation/latitude" 29.760} req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-fuelstations)) (mock/body (json/write-str fuelstation)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-fuelstation fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token))) resp (app req) hdrs (:headers resp) fs-tx-location-str (get hdrs "location")] (letfn [(new-fplog [fs purchased-at gallon-price octane] (let [fplog {"fplog/vehicle" veh-300zx-location-str "fplog/fuelstation" fs "fplog/purchased-at" (c/to-long purchased-at) "fplog/got-car-wash" true "fplog/car-wash-per-gal-discount" 0.08 "fplog/num-gallons" 14.3 "fplog/octane" octane "fplog/is-diesel" false "fplog/odometer" 15518 "fplog/gallon-price" gallon-price} fplogs-uri (str base-url entity-uri-prefix usermeta/pathcomp-users "/" resp-user-id-str "/" meta/pathcomp-fuelpurchase-logs) req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-fplog fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post fplogs-uri) (mock/body (json/write-str fplog)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-fplog fpmt-subtype-prefix) meta/v001 "json" "UTF-8")) (rtucore/header "Authorization" (rtucore/authorization-req-hdr-val fp-auth-scheme fp-auth-scheme-param-name auth-token)))] (app req)))] (let [t1 (t/now)] (new-fplog fs-ca-location-str t1 4.99 87) (new-fplog fs-tx-location-str t1 2.19 87) (new-fplog fs-ny-location-str t1 3.39 87)) (let [price-stream-filter {"price-stream-filter/fs-latitude" 42.814 "price-stream-filter/fs-longitude" -73.939 "price-stream-filter/fs-distance-within" 10000000 "price-stream-filter/max-results" 20 "price-stream-filter/sort-by" [["f.gallon_price" "asc"] ["distance" "asc"] ["f.purchased_at" "desc"]]} price-stream-uri (str base-url entity-uri-prefix meta/pathcomp-price-stream) req (-> (rtucore/req-w-std-hdrs rumeta/mt-type (meta/mt-subtype-price-stream fpmt-subtype-prefix) meta/v001 "UTF-8;q=1,ISO-8859-1;q=0" "json" "en-US" :post price-stream-uri) (mock/body (json/write-str price-stream-filter)) (mock/content-type (rucore/content-type rumeta/mt-type (meta/mt-subtype-price-stream fpmt-subtype-prefix) meta/v001 "json" "UTF-8"))) resp (app req)] (testing "status code" (is (= 200 (:status resp)))) (let [hdrs (:headers resp) resp-body-stream (:body resp) pct (rucore/parse-media-type (get hdrs "Content-Type")) charset (get rumeta/char-sets (:charset pct)) price-stream (rucore/read-res pct resp-body-stream charset)] (is (not (nil? price-stream))) (let [price-events (get price-stream "price-event-stream")] (is (= 3 (count price-events))) (let [[event-1 event-2 event-3] price-events] (is (= 2.19 (get event-1 "price-event/price"))) (is (= 87 (get event-1 "price-event/octane"))) (is (= false (get event-1 "price-event/is-diesel"))) (is (= 29.760 (get event-1 "price-event/fs-latitude"))) (is (= -95.369803 (get event-1 "price-event/fs-longitude"))) (is (= 3.39 (get event-2 "price-event/price"))) (is (= 4.99 (get event-3 "price-event/price")))))))))))
[ { "context": "; Copyright 2018-2021 Rahul De\n;\n; Use of this source code is governed by an MIT", "end": 30, "score": 0.9998619556427002, "start": 22, "tag": "NAME", "value": "Rahul De" }, { "context": " :password db-password}}\n :xtdb/tx-log ", "end": 2392, "score": 0.945151150226593, "start": 2381, "tag": "PASSWORD", "value": "db-password" } ]
common/src/common/system.clj
bob-cd/bob
88
; Copyright 2018-2021 Rahul De ; ; Use of this source code is governed by an MIT-style ; license that can be found in the LICENSE file or at ; https://opensource.org/licenses/MIT. (ns common.system (:require [com.stuartsierra.component :as component] [environ.core :as env] [taoensso.timbre :as log] [failjure.core :as f] [xtdb.api :as xt] [langohr.core :as rmq] [langohr.channel :as lch] [langohr.queue :as lq] [langohr.exchange :as le] [langohr.consumers :as lc]) (:import [java.net ConnectException] [xtdb.api IXtdb])) (defn int-from-env [key default] (try (Integer/parseInt (get env/env key (str default))) (catch Exception _ default))) (defonce storage-url (:bob-storage-url env/env "jdbc:postgresql://localhost:5432/bob")) (defonce storage-user (:bob-storage-user env/env "bob")) (defonce storage-password (:bob-storage-password env/env "bob")) (defonce queue-url (:bob-queue-url env/env "amqp://localhost:5672")) (defonce queue-user (:bob-queue-user env/env "guest")) (defonce queue-password (:bob-queue-password env/env "guest")) (defonce connection-retry-attempts (int-from-env :bob-connection-retry-attempts 10)) (defonce connection-retry-delay (int-from-env :bob-connection-retry-delay 2000)) (defn try-connect ([conn-fn] (try-connect conn-fn connection-retry-attempts)) ([conn-fn n] (if (= n 0) (throw (ConnectException. "Cannot connect to system")) (let [res (f/try* (conn-fn))] (if (f/failed? res) (do (log/warnf "Connection failed with %s, retrying %d" (f/message res) n) (Thread/sleep connection-retry-delay) (recur conn-fn (dec n))) res))))) (defprotocol IDatabase (db-client [this])) (defrecord Database [db-url db-user db-password] component/Lifecycle (start [this] (log/info "Connecting to DB") (assoc this :client (try-connect #(xt/start-node {:xtdb.jdbc/connection-pool {:dialect {:xtdb/module 'xtdb.jdbc.psql/->dialect} :db-spec {:jdbcUrl db-url :user db-user :password db-password}} :xtdb/tx-log {:xtdb/module 'xtdb.jdbc/->tx-log :connection-pool :xtdb.jdbc/connection-pool} :xtdb/document-store {:xtdb/module 'xtdb.jdbc/->document-store :connection-pool :xtdb.jdbc/connection-pool}})))) (stop [this] (log/info "Disconnecting DB") (.close ^IXtdb (:client this)) (assoc this :client nil)) IDatabase (db-client [this] (:client this))) (defn fanout? [conf ex] (= "fanout" (get-in conf [:exchanges ex :type]))) (defprotocol IQueue (queue-chan [this])) (defrecord Queue [queue-url queue-user queue-password conf] component/Lifecycle (start [this] (let [conn (try-connect #(rmq/connect {:uri queue-url :username queue-user :password queue-password})) chan (lch/open conn)] (log/infof "Connected on channel id: %d" (.getChannelNumber chan)) (doseq [[ex props] (:exchanges conf)] (log/infof "Declared exchange %s" ex) (le/declare chan ex (:type props) (select-keys props [:durable]))) (doseq [[queue props] (:queues conf)] (log/infof "Declared queue %s" queue) (lq/declare chan queue props)) (doseq [[queue ex] (:bindings conf)] (log/infof "Bound %s -> %s" queue ex) (lq/bind chan queue ex (if (fanout? conf ex) {} {:routing-key queue}))) (doseq [[queue subscriber] (:subscriptions conf)] (log/infof "Subscribed to %s" queue) (lc/subscribe chan queue subscriber {:auto-ack true})) (assoc this :conn conn :chan chan))) (stop [this] (log/info "Disconnecting queue") (rmq/close (:conn this)) (assoc this :conn nil :chan nil)) IQueue (queue-chan [this] (:chan this))) (defn db ([] (Database. storage-url storage-user storage-password)) ([url user password] (Database. url user password))) (defn queue ([conf] (Queue. queue-url queue-user queue-password conf)) ([url user password conf] (Queue. url user password conf)))
65431
; Copyright 2018-2021 <NAME> ; ; Use of this source code is governed by an MIT-style ; license that can be found in the LICENSE file or at ; https://opensource.org/licenses/MIT. (ns common.system (:require [com.stuartsierra.component :as component] [environ.core :as env] [taoensso.timbre :as log] [failjure.core :as f] [xtdb.api :as xt] [langohr.core :as rmq] [langohr.channel :as lch] [langohr.queue :as lq] [langohr.exchange :as le] [langohr.consumers :as lc]) (:import [java.net ConnectException] [xtdb.api IXtdb])) (defn int-from-env [key default] (try (Integer/parseInt (get env/env key (str default))) (catch Exception _ default))) (defonce storage-url (:bob-storage-url env/env "jdbc:postgresql://localhost:5432/bob")) (defonce storage-user (:bob-storage-user env/env "bob")) (defonce storage-password (:bob-storage-password env/env "bob")) (defonce queue-url (:bob-queue-url env/env "amqp://localhost:5672")) (defonce queue-user (:bob-queue-user env/env "guest")) (defonce queue-password (:bob-queue-password env/env "guest")) (defonce connection-retry-attempts (int-from-env :bob-connection-retry-attempts 10)) (defonce connection-retry-delay (int-from-env :bob-connection-retry-delay 2000)) (defn try-connect ([conn-fn] (try-connect conn-fn connection-retry-attempts)) ([conn-fn n] (if (= n 0) (throw (ConnectException. "Cannot connect to system")) (let [res (f/try* (conn-fn))] (if (f/failed? res) (do (log/warnf "Connection failed with %s, retrying %d" (f/message res) n) (Thread/sleep connection-retry-delay) (recur conn-fn (dec n))) res))))) (defprotocol IDatabase (db-client [this])) (defrecord Database [db-url db-user db-password] component/Lifecycle (start [this] (log/info "Connecting to DB") (assoc this :client (try-connect #(xt/start-node {:xtdb.jdbc/connection-pool {:dialect {:xtdb/module 'xtdb.jdbc.psql/->dialect} :db-spec {:jdbcUrl db-url :user db-user :password <PASSWORD>}} :xtdb/tx-log {:xtdb/module 'xtdb.jdbc/->tx-log :connection-pool :xtdb.jdbc/connection-pool} :xtdb/document-store {:xtdb/module 'xtdb.jdbc/->document-store :connection-pool :xtdb.jdbc/connection-pool}})))) (stop [this] (log/info "Disconnecting DB") (.close ^IXtdb (:client this)) (assoc this :client nil)) IDatabase (db-client [this] (:client this))) (defn fanout? [conf ex] (= "fanout" (get-in conf [:exchanges ex :type]))) (defprotocol IQueue (queue-chan [this])) (defrecord Queue [queue-url queue-user queue-password conf] component/Lifecycle (start [this] (let [conn (try-connect #(rmq/connect {:uri queue-url :username queue-user :password queue-password})) chan (lch/open conn)] (log/infof "Connected on channel id: %d" (.getChannelNumber chan)) (doseq [[ex props] (:exchanges conf)] (log/infof "Declared exchange %s" ex) (le/declare chan ex (:type props) (select-keys props [:durable]))) (doseq [[queue props] (:queues conf)] (log/infof "Declared queue %s" queue) (lq/declare chan queue props)) (doseq [[queue ex] (:bindings conf)] (log/infof "Bound %s -> %s" queue ex) (lq/bind chan queue ex (if (fanout? conf ex) {} {:routing-key queue}))) (doseq [[queue subscriber] (:subscriptions conf)] (log/infof "Subscribed to %s" queue) (lc/subscribe chan queue subscriber {:auto-ack true})) (assoc this :conn conn :chan chan))) (stop [this] (log/info "Disconnecting queue") (rmq/close (:conn this)) (assoc this :conn nil :chan nil)) IQueue (queue-chan [this] (:chan this))) (defn db ([] (Database. storage-url storage-user storage-password)) ([url user password] (Database. url user password))) (defn queue ([conf] (Queue. queue-url queue-user queue-password conf)) ([url user password conf] (Queue. url user password conf)))
true
; Copyright 2018-2021 PI:NAME:<NAME>END_PI ; ; Use of this source code is governed by an MIT-style ; license that can be found in the LICENSE file or at ; https://opensource.org/licenses/MIT. (ns common.system (:require [com.stuartsierra.component :as component] [environ.core :as env] [taoensso.timbre :as log] [failjure.core :as f] [xtdb.api :as xt] [langohr.core :as rmq] [langohr.channel :as lch] [langohr.queue :as lq] [langohr.exchange :as le] [langohr.consumers :as lc]) (:import [java.net ConnectException] [xtdb.api IXtdb])) (defn int-from-env [key default] (try (Integer/parseInt (get env/env key (str default))) (catch Exception _ default))) (defonce storage-url (:bob-storage-url env/env "jdbc:postgresql://localhost:5432/bob")) (defonce storage-user (:bob-storage-user env/env "bob")) (defonce storage-password (:bob-storage-password env/env "bob")) (defonce queue-url (:bob-queue-url env/env "amqp://localhost:5672")) (defonce queue-user (:bob-queue-user env/env "guest")) (defonce queue-password (:bob-queue-password env/env "guest")) (defonce connection-retry-attempts (int-from-env :bob-connection-retry-attempts 10)) (defonce connection-retry-delay (int-from-env :bob-connection-retry-delay 2000)) (defn try-connect ([conn-fn] (try-connect conn-fn connection-retry-attempts)) ([conn-fn n] (if (= n 0) (throw (ConnectException. "Cannot connect to system")) (let [res (f/try* (conn-fn))] (if (f/failed? res) (do (log/warnf "Connection failed with %s, retrying %d" (f/message res) n) (Thread/sleep connection-retry-delay) (recur conn-fn (dec n))) res))))) (defprotocol IDatabase (db-client [this])) (defrecord Database [db-url db-user db-password] component/Lifecycle (start [this] (log/info "Connecting to DB") (assoc this :client (try-connect #(xt/start-node {:xtdb.jdbc/connection-pool {:dialect {:xtdb/module 'xtdb.jdbc.psql/->dialect} :db-spec {:jdbcUrl db-url :user db-user :password PI:PASSWORD:<PASSWORD>END_PI}} :xtdb/tx-log {:xtdb/module 'xtdb.jdbc/->tx-log :connection-pool :xtdb.jdbc/connection-pool} :xtdb/document-store {:xtdb/module 'xtdb.jdbc/->document-store :connection-pool :xtdb.jdbc/connection-pool}})))) (stop [this] (log/info "Disconnecting DB") (.close ^IXtdb (:client this)) (assoc this :client nil)) IDatabase (db-client [this] (:client this))) (defn fanout? [conf ex] (= "fanout" (get-in conf [:exchanges ex :type]))) (defprotocol IQueue (queue-chan [this])) (defrecord Queue [queue-url queue-user queue-password conf] component/Lifecycle (start [this] (let [conn (try-connect #(rmq/connect {:uri queue-url :username queue-user :password queue-password})) chan (lch/open conn)] (log/infof "Connected on channel id: %d" (.getChannelNumber chan)) (doseq [[ex props] (:exchanges conf)] (log/infof "Declared exchange %s" ex) (le/declare chan ex (:type props) (select-keys props [:durable]))) (doseq [[queue props] (:queues conf)] (log/infof "Declared queue %s" queue) (lq/declare chan queue props)) (doseq [[queue ex] (:bindings conf)] (log/infof "Bound %s -> %s" queue ex) (lq/bind chan queue ex (if (fanout? conf ex) {} {:routing-key queue}))) (doseq [[queue subscriber] (:subscriptions conf)] (log/infof "Subscribed to %s" queue) (lc/subscribe chan queue subscriber {:auto-ack true})) (assoc this :conn conn :chan chan))) (stop [this] (log/info "Disconnecting queue") (rmq/close (:conn this)) (assoc this :conn nil :chan nil)) IQueue (queue-chan [this] (:chan this))) (defn db ([] (Database. storage-url storage-user storage-password)) ([url user password] (Database. url user password))) (defn queue ([conf] (Queue. queue-url queue-user queue-password conf)) ([url user password conf] (Queue. url user password conf)))
[ { "context": " :user \"sa\"\n :password \"\"})\n\n(def accounts [\n [\"admin\" \"not admin\"]\n [\"mario\" \"ariom\"]\n [\"luigi\" \"mar", "end": 246, "score": 0.8917853832244873, "start": 241, "tag": "USERNAME", "value": "admin" }, { "context": "\"\"})\n\n(def accounts [\n [\"admin\" \"not admin\"]\n [\"mario\" \"ariom\"]\n [\"luigi\" \"mario\"]\n [\"another user ju", "end": 270, "score": 0.9860377311706543, "start": 265, "tag": "USERNAME", "value": "mario" }, { "context": "ef accounts [\n [\"admin\" \"not admin\"]\n [\"mario\" \"ariom\"]\n [\"luigi\" \"mario\"]\n [\"another user just becau", "end": 278, "score": 0.9807360172271729, "start": 273, "tag": "USERNAME", "value": "ariom" }, { "context": "[\n [\"admin\" \"not admin\"]\n [\"mario\" \"ariom\"]\n [\"luigi\" \"mario\"]\n [\"another user just because\" \"without", "end": 290, "score": 0.9940551519393921, "start": 285, "tag": "USERNAME", "value": "luigi" }, { "context": "min\" \"not admin\"]\n [\"mario\" \"ariom\"]\n [\"luigi\" \"mario\"]\n [\"another user just because\" \"without a passw", "end": 298, "score": 0.7154822945594788, "start": 293, "tag": "USERNAME", "value": "mario" }, { "context": " \"varchar(32)\" :primary :key]\n [:password \"varchar(32)\"]]))\n (doseq [[username password] accounts]\n ", "end": 532, "score": 0.9968811869621277, "start": 522, "tag": "PASSWORD", "value": "varchar(32" }, { "context": "(j/insert! db :users {:username username :password password})))\n\n(defn layout[^String username, ^String passw", "end": 642, "score": 0.947090208530426, "start": 634, "tag": "PASSWORD", "value": "password" }, { "context": " \"<label>username<input type=\\\"text\\\" name=\\\"username\\\"></label>\"\n \"<label>password<input type", "end": 2037, "score": 0.9922318458557129, "start": 2029, "tag": "USERNAME", "value": "username" }, { "context": " \\\"select username from users where username = '\\\" username \\\"' and password = '\\\" password \\\"';\\\")</code></d", "end": 2370, "score": 0.970600426197052, "start": 2362, "tag": "USERNAME", "value": "username" }, { "context": "e>\\\"select username from users where username = '\" username \"' and password = '\" password \"';\\\"</code></dd>\"\n", "end": 2549, "score": 0.9871487021446228, "start": 2541, "tag": "USERNAME", "value": "username" }, { "context": "tr \"select username from users where username = '\" username \"' and password = '\" password \"';\"))\n\n(defn login", "end": 3049, "score": 0.8483224511146545, "start": 3041, "tag": "USERNAME", "value": "username" }, { "context": "rname [request]\n (or\n (get (:params request) \"username\")\n \"\"))\n(defn post-password [request]\n (or\n ", "end": 3291, "score": 0.9895426034927368, "start": 3283, "tag": "USERNAME", "value": "username" } ]
src/sqlilab/core.clj
caligin/sqlilab
0
(ns sqlilab.core (:require [clojure.java.jdbc :as j]) (:import (java.net URLEncoder))) (def db { :classname "org.h2.Driver" :subprotocol "h2:mem" :subname "lab;DB_CLOSE_DELAY=-1" :user "sa" :password ""}) (def accounts [ ["admin" "not admin"] ["mario" "ariom"] ["luigi" "mario"] ["another user just because" "without a password!"]]) (defn populate-db [db accounts] (j/db-do-commands db (j/create-table-ddl :users [ [:username "varchar(32)" :primary :key] [:password "varchar(32)"]])) (doseq [[username password] accounts] (j/insert! db :users {:username username :password password}))) (defn layout[^String username, ^String password, usernames] (apply str "<!DOCTYPE html>" "<html>" "<head>" "<style>" "body {" " font-family: sans;" " background-color: lightblue;" "}" "dt {" " font-weight: bold;" "}" "</style>" "</head>" "<body>" "<h1>SQLi Lab</h1>" "<h3>SQL injection - what?</h3>" "<p>" "Injection attacks happen when data interpolated in a string of a language happens to be meaningful for the language itself.<br>" "SQL queries are commonly handled as strings with placeholders that are expected to be replaced by data (e.g. an username) " "but when the interpolation is handled unsafely it is possible to slip in more valid SQL, subverting the meaning of the original query.<br>" "The login form below implement such a vulnerability. You will be considered logged in if the query (shown below) matches at " "least an username-password combination: try to write some SQL in the fields and see what happens! The interpolated string is" "shown too to help visualizing what's going on on the server.<br>" "<a href=\"https://www.owasp.org/index.php/SQL_Injection\">Read more about SQLi from OWASP</a>" "</p>" "<form action=\"/\" method=\"POST\">" "<label>username<input type=\"text\" name=\"username\"></label>" "<label>password<input type=\"text\" name=\"password\"></label>" "<input type=\"submit\" value=\"login\">" "</form>" "<dl class=\"queries\">" "<dt>query string interpolation (clojure)</dt>" "<dd><code>(str \"select username from users where username = '\" username \"' and password = '\" password \"';\")</code></dd>" "<dt>interpolated query string</dt>" "<dd><code>\"select username from users where username = '" username "' and password = '" password "';\"</code></dd>" "<dt>results (" (count usernames) ")</dt><dd>" "<dl class=\"users\">" (apply str (map (fn [username] (apply str "<dt>user</dt><dd>" username "</dd>")) usernames)) "</dl>" "</dd>" "</dl>" "</body>" "</html>" )) (defn interpolate-query [username password] (str "select username from users where username = '" username "' and password = '" password "';")) (defn login [db username password] (map (fn [row] (:username row)) (j/query db (interpolate-query username password)))) (defn post-username [request] (or (get (:params request) "username") "")) (defn post-password [request] (or (get (:params request) "password") "")) (defn make-main-page-handler [db] (fn [request] { :status 200 :headers {"Content-Type" "text/html"} :body (layout (post-username request) (post-password request) (login db (post-username request) (post-password request)))}))
38573
(ns sqlilab.core (:require [clojure.java.jdbc :as j]) (:import (java.net URLEncoder))) (def db { :classname "org.h2.Driver" :subprotocol "h2:mem" :subname "lab;DB_CLOSE_DELAY=-1" :user "sa" :password ""}) (def accounts [ ["admin" "not admin"] ["mario" "ariom"] ["luigi" "mario"] ["another user just because" "without a password!"]]) (defn populate-db [db accounts] (j/db-do-commands db (j/create-table-ddl :users [ [:username "varchar(32)" :primary :key] [:password "<PASSWORD>)"]])) (doseq [[username password] accounts] (j/insert! db :users {:username username :password <PASSWORD>}))) (defn layout[^String username, ^String password, usernames] (apply str "<!DOCTYPE html>" "<html>" "<head>" "<style>" "body {" " font-family: sans;" " background-color: lightblue;" "}" "dt {" " font-weight: bold;" "}" "</style>" "</head>" "<body>" "<h1>SQLi Lab</h1>" "<h3>SQL injection - what?</h3>" "<p>" "Injection attacks happen when data interpolated in a string of a language happens to be meaningful for the language itself.<br>" "SQL queries are commonly handled as strings with placeholders that are expected to be replaced by data (e.g. an username) " "but when the interpolation is handled unsafely it is possible to slip in more valid SQL, subverting the meaning of the original query.<br>" "The login form below implement such a vulnerability. You will be considered logged in if the query (shown below) matches at " "least an username-password combination: try to write some SQL in the fields and see what happens! The interpolated string is" "shown too to help visualizing what's going on on the server.<br>" "<a href=\"https://www.owasp.org/index.php/SQL_Injection\">Read more about SQLi from OWASP</a>" "</p>" "<form action=\"/\" method=\"POST\">" "<label>username<input type=\"text\" name=\"username\"></label>" "<label>password<input type=\"text\" name=\"password\"></label>" "<input type=\"submit\" value=\"login\">" "</form>" "<dl class=\"queries\">" "<dt>query string interpolation (clojure)</dt>" "<dd><code>(str \"select username from users where username = '\" username \"' and password = '\" password \"';\")</code></dd>" "<dt>interpolated query string</dt>" "<dd><code>\"select username from users where username = '" username "' and password = '" password "';\"</code></dd>" "<dt>results (" (count usernames) ")</dt><dd>" "<dl class=\"users\">" (apply str (map (fn [username] (apply str "<dt>user</dt><dd>" username "</dd>")) usernames)) "</dl>" "</dd>" "</dl>" "</body>" "</html>" )) (defn interpolate-query [username password] (str "select username from users where username = '" username "' and password = '" password "';")) (defn login [db username password] (map (fn [row] (:username row)) (j/query db (interpolate-query username password)))) (defn post-username [request] (or (get (:params request) "username") "")) (defn post-password [request] (or (get (:params request) "password") "")) (defn make-main-page-handler [db] (fn [request] { :status 200 :headers {"Content-Type" "text/html"} :body (layout (post-username request) (post-password request) (login db (post-username request) (post-password request)))}))
true
(ns sqlilab.core (:require [clojure.java.jdbc :as j]) (:import (java.net URLEncoder))) (def db { :classname "org.h2.Driver" :subprotocol "h2:mem" :subname "lab;DB_CLOSE_DELAY=-1" :user "sa" :password ""}) (def accounts [ ["admin" "not admin"] ["mario" "ariom"] ["luigi" "mario"] ["another user just because" "without a password!"]]) (defn populate-db [db accounts] (j/db-do-commands db (j/create-table-ddl :users [ [:username "varchar(32)" :primary :key] [:password "PI:PASSWORD:<PASSWORD>END_PI)"]])) (doseq [[username password] accounts] (j/insert! db :users {:username username :password PI:PASSWORD:<PASSWORD>END_PI}))) (defn layout[^String username, ^String password, usernames] (apply str "<!DOCTYPE html>" "<html>" "<head>" "<style>" "body {" " font-family: sans;" " background-color: lightblue;" "}" "dt {" " font-weight: bold;" "}" "</style>" "</head>" "<body>" "<h1>SQLi Lab</h1>" "<h3>SQL injection - what?</h3>" "<p>" "Injection attacks happen when data interpolated in a string of a language happens to be meaningful for the language itself.<br>" "SQL queries are commonly handled as strings with placeholders that are expected to be replaced by data (e.g. an username) " "but when the interpolation is handled unsafely it is possible to slip in more valid SQL, subverting the meaning of the original query.<br>" "The login form below implement such a vulnerability. You will be considered logged in if the query (shown below) matches at " "least an username-password combination: try to write some SQL in the fields and see what happens! The interpolated string is" "shown too to help visualizing what's going on on the server.<br>" "<a href=\"https://www.owasp.org/index.php/SQL_Injection\">Read more about SQLi from OWASP</a>" "</p>" "<form action=\"/\" method=\"POST\">" "<label>username<input type=\"text\" name=\"username\"></label>" "<label>password<input type=\"text\" name=\"password\"></label>" "<input type=\"submit\" value=\"login\">" "</form>" "<dl class=\"queries\">" "<dt>query string interpolation (clojure)</dt>" "<dd><code>(str \"select username from users where username = '\" username \"' and password = '\" password \"';\")</code></dd>" "<dt>interpolated query string</dt>" "<dd><code>\"select username from users where username = '" username "' and password = '" password "';\"</code></dd>" "<dt>results (" (count usernames) ")</dt><dd>" "<dl class=\"users\">" (apply str (map (fn [username] (apply str "<dt>user</dt><dd>" username "</dd>")) usernames)) "</dl>" "</dd>" "</dl>" "</body>" "</html>" )) (defn interpolate-query [username password] (str "select username from users where username = '" username "' and password = '" password "';")) (defn login [db username password] (map (fn [row] (:username row)) (j/query db (interpolate-query username password)))) (defn post-username [request] (or (get (:params request) "username") "")) (defn post-password [request] (or (get (:params request) "password") "")) (defn make-main-page-handler [db] (fn [request] { :status 200 :headers {"Content-Type" "text/html"} :body (layout (post-username request) (post-password request) (login db (post-username request) (post-password request)))}))
[ { "context": "circle excitation tension loss))\"\n contributor \"Roger Allen\"))\n\n(defexamples membrane-hexagon\n (:mouse\n \"U", "end": 797, "score": 0.9998852610588074, "start": 786, "tag": "NAME", "value": "Roger Allen" }, { "context": "exagon excitation tension loss))\"\n contributor \"Roger Allen\"))\n", "end": 1484, "score": 0.9998811483383179, "start": 1473, "tag": "NAME", "value": "Roger Allen" } ]
src/overtone/sc/examples/membrane.clj
ABaldwinHunter/overtone
3,870
(ns overtone.sc.examples.membrane (:use [overtone.sc.machinery defexample] [overtone.sc ugens envelope])) (defexamples membrane-circle (:mouse "Use mouse button, X and Y locations to play a drum." "The mouse button drives the excitation input of the membrane. The mouse X location drives the tension and the Mouse Y location controls the loss parameter. From the .schelp file. Click and enjoy." rate :kr [] " (let [excitation (* (env-gen:kr (perc) (mouse-button:kr 0 1 0) 1.0 0.0 0.1 0) (pink-noise)) tension (mouse-x 0.01 0.1) loss (mouse-y 0.999999 0.999 EXP)] (membrane-circle excitation tension loss))" contributor "Roger Allen")) (defexamples membrane-hexagon (:mouse "Use mouse button, X and Y locations to play a drum." "The mouse button drives the excitation input of the membrane. The mouse X location drives the tension and the Mouse Y location controls the loss parameter. From the .schelp file. Click and enjoy." rate :kr [] " (let [excitation (* (env-gen:kr (perc) (mouse-button:kr 0 1 0) 1.0 0.0 0.1 0) (pink-noise)) tension (mouse-x 0.01 0.1) loss (mouse-y 0.999999 0.999 EXP)] (membrane-hexagon excitation tension loss))" contributor "Roger Allen"))
90483
(ns overtone.sc.examples.membrane (:use [overtone.sc.machinery defexample] [overtone.sc ugens envelope])) (defexamples membrane-circle (:mouse "Use mouse button, X and Y locations to play a drum." "The mouse button drives the excitation input of the membrane. The mouse X location drives the tension and the Mouse Y location controls the loss parameter. From the .schelp file. Click and enjoy." rate :kr [] " (let [excitation (* (env-gen:kr (perc) (mouse-button:kr 0 1 0) 1.0 0.0 0.1 0) (pink-noise)) tension (mouse-x 0.01 0.1) loss (mouse-y 0.999999 0.999 EXP)] (membrane-circle excitation tension loss))" contributor "<NAME>")) (defexamples membrane-hexagon (:mouse "Use mouse button, X and Y locations to play a drum." "The mouse button drives the excitation input of the membrane. The mouse X location drives the tension and the Mouse Y location controls the loss parameter. From the .schelp file. Click and enjoy." rate :kr [] " (let [excitation (* (env-gen:kr (perc) (mouse-button:kr 0 1 0) 1.0 0.0 0.1 0) (pink-noise)) tension (mouse-x 0.01 0.1) loss (mouse-y 0.999999 0.999 EXP)] (membrane-hexagon excitation tension loss))" contributor "<NAME>"))
true
(ns overtone.sc.examples.membrane (:use [overtone.sc.machinery defexample] [overtone.sc ugens envelope])) (defexamples membrane-circle (:mouse "Use mouse button, X and Y locations to play a drum." "The mouse button drives the excitation input of the membrane. The mouse X location drives the tension and the Mouse Y location controls the loss parameter. From the .schelp file. Click and enjoy." rate :kr [] " (let [excitation (* (env-gen:kr (perc) (mouse-button:kr 0 1 0) 1.0 0.0 0.1 0) (pink-noise)) tension (mouse-x 0.01 0.1) loss (mouse-y 0.999999 0.999 EXP)] (membrane-circle excitation tension loss))" contributor "PI:NAME:<NAME>END_PI")) (defexamples membrane-hexagon (:mouse "Use mouse button, X and Y locations to play a drum." "The mouse button drives the excitation input of the membrane. The mouse X location drives the tension and the Mouse Y location controls the loss parameter. From the .schelp file. Click and enjoy." rate :kr [] " (let [excitation (* (env-gen:kr (perc) (mouse-button:kr 0 1 0) 1.0 0.0 0.1 0) (pink-noise)) tension (mouse-x 0.01 0.1) loss (mouse-y 0.999999 0.999 EXP)] (membrane-hexagon excitation tension loss))" contributor "PI:NAME:<NAME>END_PI"))
[ { "context": "rnative multimethod implementations.\"\n {:author \"palisades dot lakes at gmail dot com\"\n :since \"2017-08-30\"\n :version \"2017-08-31\"}", "end": 293, "score": 0.9053258895874023, "start": 257, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/scripts/clojure/palisades/lakes/multix/diameter/bench2.clj
palisades-lakes/multimethod-experiments
5
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.multix.diameter.bench2 "Use criterium for alternative multimethod implementations." {:author "palisades dot lakes at gmail dot com" :since "2017-08-30" :version "2017-08-31"} (:require [palisades.lakes.bench.prng :as prng] [palisades.lakes.bench.generators :as g] [palisades.lakes.bench.core :as bench] [palisades.lakes.multix.diameter.defs :as defs])) ;;---------------------------------------------------------------- (bench/bench [g/Sets defs/r2] #_[prng/objects defs/r7] [#_defs/instanceof defs/instancefn defs/nohierarchy defs/dynafun defs/dynalin #_defs/instanceof #_defs/nohierarchy #_defs/dynafun] {:samples 256}) ;;---------------------------------------------------------------- (shutdown-agents) (System/exit 0)
18402
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.multix.diameter.bench2 "Use criterium for alternative multimethod implementations." {:author "<EMAIL>" :since "2017-08-30" :version "2017-08-31"} (:require [palisades.lakes.bench.prng :as prng] [palisades.lakes.bench.generators :as g] [palisades.lakes.bench.core :as bench] [palisades.lakes.multix.diameter.defs :as defs])) ;;---------------------------------------------------------------- (bench/bench [g/Sets defs/r2] #_[prng/objects defs/r7] [#_defs/instanceof defs/instancefn defs/nohierarchy defs/dynafun defs/dynalin #_defs/instanceof #_defs/nohierarchy #_defs/dynafun] {:samples 256}) ;;---------------------------------------------------------------- (shutdown-agents) (System/exit 0)
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.multix.diameter.bench2 "Use criterium for alternative multimethod implementations." {:author "PI:EMAIL:<EMAIL>END_PI" :since "2017-08-30" :version "2017-08-31"} (:require [palisades.lakes.bench.prng :as prng] [palisades.lakes.bench.generators :as g] [palisades.lakes.bench.core :as bench] [palisades.lakes.multix.diameter.defs :as defs])) ;;---------------------------------------------------------------- (bench/bench [g/Sets defs/r2] #_[prng/objects defs/r7] [#_defs/instanceof defs/instancefn defs/nohierarchy defs/dynafun defs/dynalin #_defs/instanceof #_defs/nohierarchy #_defs/dynafun] {:samples 256}) ;;---------------------------------------------------------------- (shutdown-agents) (System/exit 0)
[ { "context": ":updated \"Päivitetty\",\n :name \"Nimi\",\n :reported \"Ilmoitettu\",\n :type ", "end": 7532, "score": 0.9086786508560181, "start": 7528, "tag": "NAME", "value": "Nimi" }, { "context": "rjaudu salasanalla\",\n :password \"Salasana\",\n :logout \"Kirjaudu ulos\",\n ", "end": 15747, "score": 0.9986567497253418, "start": 15739, "tag": "PASSWORD", "value": "Salasana" }, { "context": " \"Kirjaudu ulos\",\n :username \"Sähköposti / käyttäjätunnus\",\n :login-help\n \"Jos ole", "end": 15834, "score": 0.9949929714202881, "start": 15824, "tag": "USERNAME", "value": "Sähköposti" }, { "context": "u ulos\",\n :username \"Sähköposti / käyttäjätunnus\",\n :login-help\n \"Jos olet jo LIPAS-käyttä", "end": 15851, "score": 0.8967071175575256, "start": 15837, "tag": "PASSWORD", "value": "käyttäjätunnus" }, { "context": "myös roskapostin!\",\n :username-example \"paavo.paivittaja@kunta.fi\",\n :forgot-password? \"Unohtuiko salasana", "end": 16562, "score": 0.9999032616615295, "start": 16537, "tag": "EMAIL", "value": "paavo.paivittaja@kunta.fi" }, { "context": "aivittaja@kunta.fi\",\n :forgot-password? \"Unohtuiko salasana?\"},\n :lipas.ice-stadium.conditions\n {:open-", "end": 16612, "score": 0.9649803042411804, "start": 16594, "tag": "PASSWORD", "value": "Unohtuiko salasana" }, { "context": " \"Omistaja\",\n :marketing-name \"Markkinointinimi\"},\n :status\n {:active \"", "end": 20478, "score": 0.9994810819625854, "start": 20462, "tag": "NAME", "value": "Markkinointinimi" }, { "context": ",\n :reset-password\n {:change-password \"Vaihda salasana\",\n :enter-new-password \"Syötä uusi salasana", "end": 24216, "score": 0.9992938041687012, "start": 24201, "tag": "PASSWORD", "value": "Vaihda salasana" }, { "context": " \"Vaihda salasana\",\n :enter-new-password \"Syötä uusi salasana\",\n :get-new-link \"Tilaa uusi vaihtoli", "end": 24266, "score": 0.9991880059242249, "start": 24247, "tag": "PASSWORD", "value": "Syötä uusi salasana" }, { "context": " \"Käyttäjää ei löydy.\",\n :username-conflict \"Käyttäjätunnus on jo käytössä\"},\n :reminders\n {:descriptio", "end": 26340, "score": 0.9639628529548645, "start": 26326, "tag": "USERNAME", "value": "Käyttäjätunnus" }, { "context": "aviin kuntiin:\",\n :password \"Salasana\",\n :lastname \"Sukunimi\",\n ", "end": 40094, "score": 0.9990994334220886, "start": 40086, "tag": "PASSWORD", "value": "Salasana" }, { "context": " \"Salasana\",\n :lastname \"Sukunimi\",\n :save-report \"Tallenna rapor", "end": 40138, "score": 0.9976657629013062, "start": 40130, "tag": "NAME", "value": "Sukunimi" }, { "context": "ikkiin kuntiin\",\n :username \"Käyttäjätunnus\",\n :history \"Historia\",\n ", "end": 40374, "score": 0.9973430633544922, "start": 40360, "tag": "USERNAME", "value": "Käyttäjätunnus" }, { "context": "detyt oikeudet\",\n :email-example \"kalle.kayttaja@kunta.fi\",\n :permission-to-portal-sites\n \"Sinulla ", "end": 40737, "score": 0.9999262094497681, "start": 40714, "tag": "EMAIL", "value": "kalle.kayttaja@kunta.fi" }, { "context": "nergiankulutus\",\n :firstname \"Etunimi\",\n :save-search \"Tallenna haku\"", "end": 41028, "score": 0.9913511872291565, "start": 41021, "tag": "NAME", "value": "Etunimi" }, { "context": "yttöoikeuksia.\",\n :username-example \"tane12\",\n :permission-to-types\n \"Sinulla on käyt", "end": 41258, "score": 0.9992685317993164, "start": 41252, "tag": "USERNAME", "value": "tane12" }, { "context": " :hall \"Hall\",\n :women \"Kvinnor\",\n :total-short \"Totalt\",\n :done ", "end": 45657, "score": 0.5942487716674805, "start": 45651, "tag": "NAME", "value": "vinnor" }, { "context": ":updated \"Uppdaterad\",\n :name \"Namn\",\n :reported \"Rapporterad\",\n :type ", "end": 45779, "score": 0.9995072484016418, "start": 45775, "tag": "NAME", "value": "Namn" }, { "context": ":feb \"Februari\",\n :nov \"November\",\n :may \"Maj\",\n :mar \"Mars\",\n :dec \"December\",\n :a", "end": 47505, "score": 0.7141718864440918, "start": 47502, "tag": "NAME", "value": "Maj" }, { "context": "re \"här\",\n :login-with-password \"Logga in med lösenord\",\n :password \"Lösenord\",\n :l", "end": 52340, "score": 0.9144662022590637, "start": 52319, "tag": "PASSWORD", "value": "Logga in med lösenord" }, { "context": "ga in med lösenord\",\n :password \"Lösenord\",\n :logout \"Logga ut\",\n :u", "end": 52380, "score": 0.9992088675498962, "start": 52372, "tag": "PASSWORD", "value": "Lösenord" }, { "context": " \"Logga ut\",\n :username \"E-post / användarnamn\",\n :login-help\n \"Om du har", "end": 52458, "score": 0.575913667678833, "start": 52454, "tag": "USERNAME", "value": "post" }, { "context": " \"Logga ut\",\n :username \"E-post / användarnamn\",\n :login-help\n \"Om du har ett användarna", "end": 52473, "score": 0.9720335006713867, "start": 52461, "tag": "USERNAME", "value": "användarnamn" }, { "context": " Kolla också spam!\",\n :username-example \"paavo.paivittaja@kunta.fi\",\n :forgot-password? \"Glömt ditt lösenor", "end": 53072, "score": 0.9999167919158936, "start": 53047, "tag": "EMAIL", "value": "paavo.paivittaja@kunta.fi" }, { "context": "aivittaja@kunta.fi\",\n :forgot-password? \"Glömt ditt lösenord?\"},\n :map.demographics\n {:headline \"Befol", "end": 53123, "score": 0.9026309251785278, "start": 53104, "tag": "PASSWORD", "value": "Glömt ditt lösenord" }, { "context": " \"Webbsida\",\n :name \"Namn på finska\",\n :reservations-link \"Bokningar\",\n", "end": 54697, "score": 0.5839873552322388, "start": 54693, "tag": "NAME", "value": "Namn" }, { "context": " \"Webbsida\",\n :name \"Namn på finska\",\n :reservations-link \"Bokningar\",\n :cons", "end": 54707, "score": 0.7383908033370972, "start": 54701, "tag": "NAME", "value": "finska" }, { "context": "ner \"Ägare\",\n :marketing-name \"Varumärkesnamn\"},\n :status\n {:active \"", "end": 55508, "score": 0.9974055290222168, "start": 55494, "tag": "NAME", "value": "Varumärkesnamn" }, { "context": "\"},\n :reset-password\n {:change-password \"Ändra lösenord\",\n :enter-new-password \"Skriv ett ny lösenord", "end": 58648, "score": 0.9993418455123901, "start": 58634, "tag": "PASSWORD", "value": "Ändra lösenord" }, { "context": "rd \"Ändra lösenord\",\n :enter-new-password \"Skriv ett ny lösenord\",\n :get-new-link \"Bestella ny återställ", "end": 58698, "score": 0.9988864064216614, "start": 58677, "tag": "PASSWORD", "value": "Skriv ett ny lösenord" }, { "context": "Användare hittas inte.\",\n :username-conflict \"Användarnamnet redan används\"},\n :reminders\n {", "end": 60758, "score": 0.8755640983581543, "start": 60756, "tag": "USERNAME", "value": "An" }, { "context": "vändare hittas inte.\",\n :username-conflict \"Användarnamnet redan används\"},\n :reminders\n {:des", "end": 60762, "score": 0.5899250507354736, "start": 60758, "tag": "NAME", "value": "vänd" }, { "context": "are hittas inte.\",\n :username-conflict \"Användarnamnet redan används\"},\n :reminders\n {:descript", "end": 60767, "score": 0.5341821312904358, "start": 60762, "tag": "USERNAME", "value": "arnam" }, { "context": "ittas inte.\",\n :username-conflict \"Användarnamnet redan används\"},\n :reminders\n {:description", "end": 60770, "score": 0.5949706435203552, "start": 60767, "tag": "NAME", "value": "net" }, { "context": "um \"Samkommun\",\n :other \"Annat\",\n :company-ltd \"Företag\",\n :c", "end": 72051, "score": 0.5438128113746643, "start": 72048, "tag": "NAME", "value": "nat" }, { "context": "r kommunerna:\",\n :password \"Lösenord\",\n :lastname \"Efternamn\",\n ", "end": 73484, "score": 0.9978154897689819, "start": 73476, "tag": "PASSWORD", "value": "Lösenord" }, { "context": " \"Lösenord\",\n :lastname \"Efternamn\",\n :save-report \"Spara raportm", "end": 73530, "score": 0.9995449781417847, "start": 73521, "tag": "NAME", "value": "Efternamn" }, { "context": "alla kommuner\",\n :username \"Användarnamn\",\n :history \"Historia\",\n ", "end": 73769, "score": 0.9996727108955383, "start": 73757, "tag": "USERNAME", "value": "Användarnamn" }, { "context": "a rättigheter\",\n :email-example \"epost@exempel.fi\",\n :permission-to-portal-sites\n \"Du har r", "end": 74114, "score": 0.9999294281005859, "start": 74098, "tag": "EMAIL", "value": "epost@exempel.fi" }, { "context": " konfirmerats\",\n :username-example \"tane12\",\n :permission-to-types\n \"Du har rättighe", "end": 74602, "score": 0.999568521976471, "start": 74596, "tag": "USERNAME", "value": "tane12" }, { "context": " :updated \"Updated\",\n :name \"Name\",\n :reported \"Reported\",\n :type ", "end": 81423, "score": 0.9806036353111267, "start": 81419, "tag": "NAME", "value": "Name" }, { "context": "c link to {1}\",\n :users \"Users\"},\n :lipas.ice-stadium.refrigeration\n {:hea", "end": 84039, "score": 0.8267011046409607, "start": 84034, "tag": "USERNAME", "value": "Users" }, { "context": "e \"here\",\n :login-with-password \"Login with password\",\n :password \"Pass", "end": 89157, "score": 0.5600706934928894, "start": 89152, "tag": "PASSWORD", "value": "Login" }, { "context": " \"here\",\n :login-with-password \"Login with password\",\n :password \"Password\",\n :l", "end": 89171, "score": 0.5823754072189331, "start": 89163, "tag": "PASSWORD", "value": "password" }, { "context": "ogin with password\",\n :password \"Password\",\n :logout \"Log out\",\n :us", "end": 89211, "score": 0.9983747005462646, "start": 89203, "tag": "PASSWORD", "value": "Password" }, { "context": " \"Log out\",\n :username \"Email / Username\",\n :login-help\n \"If you are al", "end": 89287, "score": 0.8411678075790405, "start": 89282, "tag": "USERNAME", "value": "Email" }, { "context": "dered \"Password\",\n :username-example \"paavo.paivittaja@kunta.fi\",\n :forgot-password? \"Forgot password?\"}", "end": 89736, "score": 0.9998977184295654, "start": 89711, "tag": "EMAIL", "value": "paavo.paivittaja@kunta.fi" }, { "context": "ally to the Excursionmap.fi service, maintained by Metsähallitus.\nI agree to update in the Lipas service any chang", "end": 96675, "score": 0.5528894066810608, "start": 96662, "tag": "USERNAME", "value": "Metsähallitus" }, { "context": "\"},\n :reset-password\n {:change-password \"Change password\",\n :enter-new-password \"Enter new password\",\n", "end": 97010, "score": 0.9976303577423096, "start": 96995, "tag": "PASSWORD", "value": "Change password" }, { "context": "d \"Change password\",\n :enter-new-password \"Enter new password\",\n :get-new-link \"Get new reset link\",\n", "end": 97057, "score": 0.9963417053222656, "start": 97039, "tag": "PASSWORD", "value": "Enter new password" }, { "context": " \"User not found.\",\n :username-conflict \"Username is already in use\"},\n :reminders\n {:description\n \"", "end": 98982, "score": 0.8568465113639832, "start": 98963, "tag": "USERNAME", "value": "Username is already" }, { "context": " \"Watch\",\n :video-description\n \"Pihjalalinna Areena - An Energy Efficient Ice Stadium\"},\n :lipas.l", "end": 101481, "score": 0.9998776912689209, "start": 101462, "tag": "NAME", "value": "Pihjalalinna Areena" }, { "context": "lowing cities:\",\n :password \"Password\",\n :lastname \"Last name\",\n ", "end": 111962, "score": 0.9894687533378601, "start": 111954, "tag": "PASSWORD", "value": "Password" }, { "context": " to all cities\",\n :username \"Username\",\n :history \"History\",\n ", "end": 112213, "score": 0.9995529651641846, "start": 112205, "tag": "USERNAME", "value": "Username" }, { "context": "ed permissions\",\n :email-example \"email@example.com\",\n :permission-to-portal-sites\n \"You have", "end": 112533, "score": 0.9999095797538757, "start": 112516, "tag": "EMAIL", "value": "email@example.com" }, { "context": "to any sites.\",\n :username-example \"tane12\",\n :permission-to-types \"You have permi", "end": 113040, "score": 0.9996104836463928, "start": 113034, "tag": "USERNAME", "value": "tane12" } ]
webapp/src/cljc/lipas/i18n/generated.cljc
lipas-liikuntapaikat/lipas
49
(ns lipas.i18n.generated) ;; From csv ;; (def dicts {:fi {:analysis {:headline "Analyysityökalu (beta)" :description "Analyysityökalulla voi arvioida liikuntaolosuhteiden tarjontaa ja saavutettavuutta vertailemalla liikuntapaikan etäisyyttä ja matkustusaikoja suhteessa muihin liikuntapaikkoihin, väestöön sekä oppilaitoksiin." :description2 "Väestöaineistona käytetään Tilastokeskuksen 250x250m ja 1x1km ruutuaineistoja, joista selviää kussakin ruudussa olevan väestön jakauma kolmessa ikäryhmässä (0-14, 15-65, 65-)." :description3 "Matka-aikojen laskeminen eri kulkutavoilla (kävellen, polkupyörällä, autolla) perustuu avoimeen OpenStreetMap-aineistoon ja OSRM-työkaluun." :description4 "Oppilaitosten nimi- ja sijaintitiedot perustuvat Tilastokeskuksen avoimeen aineistoon. Varhaiskasvatusyksiköiden nimi- ja sijaintitiedoissa käytetään LIKES:n keräämää ja luovuttamaa aineistoa." :add-new "Lisää uusi" :distance "Etäisyys" :travel-time "Matka-aika" :zones "Korit" :zone "Kori" :schools "Koulut" :daycare "Varhaiskasvatusyksikkö" :elementary-school "Peruskoulu" :high-school "Lukio" :elementary-and-high-school "Perus- ja lukioasteen koulu" :special-school "Erityiskoulu" :population "Väestö" :direct "Linnuntietä" :by-foot "Kävellen" :by-car "Autolla" :by-bicycle "Polkupyörällä" :analysis-buffer "Analyysialue" :filter-types "Suodata tyypin mukaan" :settings "Asetukset" :settings-map "Kartalla näkyvät kohteet" :settings-zones "Etäisyydet ja matka-ajat" :settings-help "Analyysialue määräytyy suurimman etäisyyskorin mukaan. Myöskään matka-aikoja ei lasketa tämän alueen ulkopuolelta."} :sport {:description "LIPAS tarjoaa ajantasaisen tiedon Suomen julkisista liikuntapaikoista ja virkistyskohteista avoimessa tietokannassa.", :headline "Liikuntapaikat", :open-interfaces "Avoimet rajapinnat", :up-to-date-information "Ajantasainen tieto Suomen liikuntapaikoista", :updating-tools "Päivitystyökalut tiedontuottajille"}, :confirm {:discard-changes? "Tahdotko kumota tekemäsi muutokset?", :headline "Varmistus", :no "Ei", :press-again-to-delete "Varmista painamalla uudestaan", :resurrect? "Tahdotko palauttaa liikuntapaikan aktiiviseksi?", :save-basic-data? "Haluatko tallentaa perustiedot?", :yes "Kyllä"}, :lipas.swimming-pool.saunas {:accessible? "Esteetön", :add-sauna "Lisää sauna", :edit-sauna "Muokkaa saunaa", :headline "Saunat", :men? "Miehet", :women? "Naiset"}, :slide-structures {:concrete "Betoni", :hardened-plastic "Lujitemuovi", :steel "Teräs"}, :lipas.swimming-pool.conditions {:open-days-in-year "Aukiolopäivät vuodessa", :open-hours-mon "Maanantaisin", :headline "Aukiolo", :open-hours-wed "Keskiviikkoisin", :open-hours-thu "Torstaisin", :open-hours-fri "Perjantaisin", :open-hours-tue "Tiistaisin", :open-hours-sun "Sunnuntaisin", :daily-open-hours "Aukiolotunnit päivässä", :open-hours-sat "Lauantaisin"}, :lipas.ice-stadium.ventilation {:dryer-duty-type "Ilmankuivauksen käyttötapa", :dryer-type "Ilmankuivaustapa", :headline "Hallin ilmanvaihto", :heat-pump-type "Lämpöpumpputyyppi", :heat-recovery-efficiency "Lämmöntalteenoton hyötysuhde %", :heat-recovery-type "Lämmöntalteenoton tyyppi"}, :swim {:description "Uimahalliportaali sisältää hallien perus- ja energiankulutustietoja sekä ohjeita energiatehokkuuden parantamiseen.", :latest-updates "Viimeksi päivitetyt tiedot", :headline "Uimahalli​portaali", :basic-data-of-halls "Uimahallien perustiedot", :updating-basic-data "Perustietojen päivitys", :edit "Uimahalli​portaali", :entering-energy-data "Energiankulutustietojen syöttäminen", :list "Hallien tiedot", :visualizations "Hallien vertailu"}, :home-page {:description "Etusivu", :headline "Etusivu"}, :ice-energy {:description "Ajantasaisen tietopaketin löydät Jääkiekkoliiton sivuilta.", :energy-calculator "Jäähallin energialaskuri", :finhockey-link "Siirry Jääkiekkoliiton sivuille", :headline "Energia​info"}, :filtering-methods {:activated-carbon "Aktiivihiili", :coal "Hiili", :membrane-filtration "Kalvosuodatus", :multi-layer-filtering "Monikerrossuodatus", :open-sand "Avohiekka", :other "Muu", :precipitation "Saostus", :pressure-sand "Painehiekka"}, :open-data {:description "Linkit ja ohjeet rajapintojen käyttöön.", :headline "Avoin data", :rest "REST", :wms-wfs "WMS & WFS"}, :lipas.swimming-pool.pool {:accessibility "Saavutettavuus", :outdoor-pool? "Ulkoallas"}, :pool-types {:multipurpose-pool "Monitoimiallas", :whirlpool-bath "Poreallas", :main-pool "Pääallas", :therapy-pool "Terapia-allas", :fitness-pool "Kuntouintiallas", :diving-pool "Hyppyallas", :childrens-pool "Lastenallas", :paddling-pool "Kahluuallas", :cold-pool "Kylmäallas", :other-pool "Muu allas", :teaching-pool "Opetusallas"}, :lipas.ice-stadium.envelope {:base-floor-structure "Alapohjan laatan rakenne", :headline "Vaipan rakenne", :insulated-ceiling? "Yläpohja lämpöeristetty", :insulated-exterior? "Ulkoseinä lämpöeristetty", :low-emissivity-coating? "Yläpohjassa matalaemissiiviteettipinnoite (heijastus/säteily)"}, :disclaimer {:headline "HUOMIO!", :test-version "Tämä on LIPAS-sovelluksen testiversio ja tarkoitettu koekäyttöön. Muutokset eivät tallennu oikeaan Lipakseen."}, :admin {:private-foundation "Yksityinen / säätiö", :city-other "Kunta / muu", :unknown "Ei tietoa", :municipal-consortium "Kuntayhtymä", :private-company "Yksityinen / yritys", :private-association "Yksityinen / yhdistys", :other "Muu", :city-technical-services "Kunta / tekninen toimi", :city-sports "Kunta / liikuntatoimi", :state "Valtio", :city-education "Kunta / opetustoimi"}, :accessibility {:lift "Allasnostin", :low-rise-stairs "Loivat portaat", :mobile-lift "Siirrettävä allasnostin", :slope "Luiska"}, :general {:description "Kuvaus", :hall "Halli", :women "Naiset", :total-short "Yht.", :done "Valmis", :updated "Päivitetty", :name "Nimi", :reported "Ilmoitettu", :type "Tyyppi", :last-modified "Muokattu viimeksi", :here "tästä", :event "Tapahtuma", :structure "Rakenne", :general-info "Yleiset tiedot", :comment "Kommentti", :measures "Mitat", :men "Miehet"}, :dryer-duty-types {:automatic "Automaattinen", :manual "Manuaali"}, :swim-energy {:description "Ajantasaisen tietopaketin löydät UKTY:n ja SUH:n sivuilta.", :headline "Energia​info", :headline-short "Info", :suh-link "Siirry SUH:n sivuille", :ukty-link "Siirry UKTY:n sivuille"}, :time {:two-years-ago "2 vuotta sitten", :date "Päivämäärä", :hour "Tunti", :this-month "Tässä kuussa", :time "Aika", :less-than-hour-ago "Alle tunti sitten", :start "Alkoi", :this-week "Tällä viikolla", :today "Tänään", :month "Kuukausi", :long-time-ago "Kauan sitten", :year "Vuosi", :just-a-moment-ago "Hetki sitten", :yesterday "Eilen", :three-years-ago "3 vuotta sitten", :end "Päättyi", :this-year "Tänä vuonna", :last-year "Viime vuonna"}, :ice-resurfacer-fuels {:LPG "Nestekaasu", :electicity "Sähkö", :gasoline "Bensiini", :natural-gas "Maakaasu", :propane "Propaani"}, :ice-rinks {:headline "Hallien tiedot"}, :month {:sep "Syyskuu", :jan "Tammikuu", :jun "Kesäkuu", :oct "Lokakuu", :jul "Heinäkuu", :apr "Huhtikuu", :feb "Helmikuu", :nov "Marraskuu", :may "Toukokuu", :mar "Maaliskuu", :dec "Joulukuu", :aug "Elokuu"}, :type {:name "Liikuntapaikkatyyppi", :main-category "Pääryhmä", :sub-category "Alaryhmä", :type-code "Tyyppikoodi"}, :duration {:hour "tuntia", :month "kuukautta", :years "vuotta", :years-short "v"}, :size-categories {:competition "Kilpahalli < 3000 hlö", :large "Suurhalli > 3000 hlö", :small "Pieni kilpahalli > 500 hlö"}, :lipas.admin {:access-all-sites "Sinulla on pääkäyttäjän oikeudet. Voit muokata kaikkia liikuntapaikkoja.", :confirm-magic-link "Haluatko varmasti lähettää taikalinkin käyttäjälle {1}?", :headline "Admin", :magic-link "Taikalinkki", :select-magic-link-template "Valitse saatekirje", :send-magic-link "Taikalinkki käyttäjälle {1}", :users "Käyttäjät"}, :lipas.ice-stadium.refrigeration {:headline "Kylmätekniikka", :refrigerant-solution-amount-l "Rataliuoksen määrä (l)", :individual-metering? "Alamittaroitu", :original? "Alkuperäinen", :refrigerant "Kylmäaine", :refrigerant-solution "Rataliuos", :condensate-energy-main-targets "Lauhdelämmön pääkäyttökohde", :power-kw "Kylmäkoneen sähköteho (kW)", :condensate-energy-recycling? "Lauhde-energia hyötykäytetty", :refrigerant-amount-kg "Kylmäaineen määrä (kg)"}, :lipas.building {:headline "Rakennus", :total-volume-m3 "Bruttotilavuus m³", :staff-count "Henkilökunnan lukumäärä", :piled? "Paalutettu", :heat-sections? "Allastila on jaettu lämpötilaosioihin", :total-ice-area-m2 "Jääpinta-ala m²", :main-construction-materials "Päärakennusmateriaalit", :main-designers "Pääsuunnittelijat", :total-pool-room-area-m2 "Allashuoneen pinta-ala m²", :heat-source "Lämmönlähde", :total-surface-area-m2 "Bruttopinta-ala m² (kokonaisala)", :total-water-area-m2 "Vesipinta-ala m²", :ceiling-structures "Yläpohjan rakenteet", :supporting-structures "Kantavat rakenteet", :seating-capacity "Katsomokapasiteetti"}, :heat-pump-types {:air-source "Ilmalämpöpumppu", :air-water-source "Ilma-vesilämpöpumppu", :exhaust-air-source "Poistoilmalämpöpumppu", :ground-source "Maalämpöpumppu", :none "Ei lämpöpumppua"}, :search {:table-view "Näytä hakutulokset taulukossa", :headline "Haku", :results-count "{1} hakutulosta", :placeholder "Etsi...", :retkikartta-filter "Retkikartta.fi-kohteet", :harrastuspassi-filter "Harrastuspassi.fi-kohteet", :filters "Rajaa hakua", :search-more "Hae lisää...", :page-size "Näytä kerralla", :search "Hae", :permissions-filter "Näytä kohteet joita voin muokata", :display-closest-first "Näytä lähimmät kohteet ensin", :list-view "Näytä hakutulokset listana", :pagination "Tulokset {1}-{2}", :school-use-filter "Koulujen liikuntapaikat", :clear-filters "Poista rajaukset"}, :map.tools {:drawing-tooltip "Piirtotyökalu valittu", :drawing-hole-tooltip "Reikäpiirtotyökalu valittu", :edit-tool "Muokkaustyökalu", :importing-tooltip "Tuontityökalu valittu", :deleting-tooltip "Poistotyökalu valittu", :splitting-tooltip "Katkaisutyökalu valittu"}, :partners {:headline "Kehittä​misessä mukana"}, :actions {:duplicate "Kopioi", :resurrect "Palauta", :select-year "Valitse vuosi", :select-owners "Valitse omistajat", :select-admins "Valitse ylläpitäjät", :select-tool "Valitse työkalu", :save-draft "Tallenna luonnos", :redo "Tee uudelleen", :open-main-menu "Avaa päävalikko", :back-to-listing "Takaisin listaukseen", :filter-surface-materials "Rajaa pintamateriaalit", :browse "siirry", :select-type "Valitse tyyppi", :edit "Muokkaa", :filter-construction-year "Rajaa rakennusvuodet", :submit "Lähetä", :choose-energy "Valitse energia", :delete "Poista", :browse-to-map "Siirry kartalle", :save "Tallenna", :close "Sulje", :filter-area-m2 "Rajaa liikuntapinta-ala m²", :show-account-menu "Avaa käyttäjävalikko", :fill-required-fields "Täytä pakolliset kentät", :undo "Kumoa", :browse-to-portal "Siirry portaaliin", :download-excel "Lataa Excel", :fill-data "Täytä tiedot", :select-statuses "Liikuntapaikan tila", :select-cities "Valitse kunnat", :select-hint "Valitse...", :discard "Kumoa", :more "Lisää...", :cancel "Peruuta", :select-columns "Valitse tietokentät", :add "Lisää", :show-all-years "Näytä kaikki vuodet", :download "Lataa", :select-hall "Valitse halli", :clear-selections "Poista valinnat", :select "Valitse", :select-types "Valitse tyypit"}, :dimensions {:area-m2 "Pinta-ala m²", :depth-max-m "Syvyys max m", :depth-min-m "Syvyys min m", :length-m "Pituus m", :surface-area-m2 "Pinta-ala m²", :volume-m3 "Tilavuus m³", :width-m "Leveys m"}, :login {:headline "Kirjaudu", :login-here "täältä", :login-with-password "Kirjaudu salasanalla", :password "Salasana", :logout "Kirjaudu ulos", :username "Sähköposti / käyttäjätunnus", :login-help "Jos olet jo LIPAS-käyttäjä, voit tilata suoran sisäänkirjautumislinkin sähköpostiisi", :login "Kirjaudu", :magic-link-help "Jos olet jo LIPAS-käyttäjä, voit tilata suoran sisäänkirjautumislinkin sähköpostiisi. Linkkiä käyttämällä sinun ei tarvitse muistaa salasanaasi.", :order-magic-link "Lähetä linkki sähköpostiini", :login-with-magic-link "Kirjaudu sähköpostilla", :bad-credentials "Käyttäjätunnus tai salasana ei kelpaa", :magic-link-ordered "Linkki on lähetetty ja sen pitäisi saapua sähköpostiisi parin minuutin sisällä. Tarkistathan myös roskapostin!", :username-example "paavo.paivittaja@kunta.fi", :forgot-password? "Unohtuiko salasana?"}, :lipas.ice-stadium.conditions {:open-months "Aukiolokuukaudet vuodessa", :headline "Käyttöolosuhteet", :ice-resurfacer-fuel "Jäänhoitokoneen polttoaine", :stand-temperature-c "Katsomon tavoiteltu keskilämpötila ottelun aikana", :ice-average-thickness-mm "Jään keskipaksuus mm", :air-humidity-min "Ilman suhteellinen kosteus % min", :daily-maintenances-weekends "Jäähoitokerrat viikonlppuina", :air-humidity-max "Ilman suhteellinen kosteus % max", :daily-maintenances-week-days "Jäähoitokerrat arkipäivinä", :maintenance-water-temperature-c "Jäähoitoveden lämpötila (tavoite +40)", :ice-surface-temperature-c "Jään pinnan lämpötila", :weekly-maintenances "Jäänhoitokerrat viikossa", :skating-area-temperature-c "Luistelualueen lämpötila 1 m korkeudella", :daily-open-hours "Käyttötunnit päivässä", :average-water-consumption-l "Keskimääräinen jäänhoitoon käytetty veden määrä (per ajo)"}, :map.demographics {:headline "Analyysityökalu", :tooltip "Analyysityökalu", :helper-text "Valitse liikuntapaikka kartalta tai lisää uusi analysoitava kohde ", :copyright1 "Väestötiedoissa käytetään Tilastokeskuksen vuoden 2019", :copyright2 "1x1 km ruutuaineistoa", :copyright3 "lisenssillä" :copyright4 ", sekä vuoden 2020 250x250m ruutuaineistoa suljetulla lisenssillä."}, :lipas.swimming-pool.slides {:add-slide "Lisää liukumäki", :edit-slide "Muokkaa liukumäkeä", :headline "Liukumäet"}, :notifications {:get-failed "Tietojen hakeminen epäonnistui.", :save-failed "Tallennus epäonnistui", :save-success "Tallennus onnistui" :ie (str "Internet Explorer ei ole tuettu selain. " "Suosittelemme käyttämään toista selainta, " "esim. Chrome, Firefox tai Edge.")}, :lipas.swimming-pool.energy-saving {:filter-rinse-water-heat-recovery? "Suodattimien huuhteluveden lämmöntalteenotto", :headline "Energian​säästö​toimet", :shower-water-heat-recovery? "Suihkuveden lämmöntalteenotto"}, :ice-form {:headline "Nestekaasu", :headline-short "Sähkö", :select-rink "Nestekaasu"}, :restricted {:login-or-register "Kirjaudu sisään tai rekisteröidy"}, :lipas.ice-stadium.rinks {:add-rink "Lisää rata", :edit-rink "Muokkaa rataa", :headline "Radat"}, :lipas.sports-site {:properties "Lisätiedot", :delete-tooltip "Poista liikuntapaikka...", :headline "Liikuntapaikka", :new-site-of-type "Uusi {1}", :address "Osoite", :new-site "Uusi liikuntapaikka", :phone-number "Puhelinnumero", :admin "Ylläpitäjä", :surface-materials "Pintamateriaalit", :www "Web-sivu", :name "Nimi suomeksi", :reservations-link "Tilavaraukset", :construction-year "Rakennus​vuosi", :type "Tyyppi", :delete "Poista {1}", :renovation-years "Perus​korjaus​vuodet", :name-localized-se "Nimi ruotsiksi", :status "Liikuntapaikan tila", :id "LIPAS-ID", :details-in-portal "Näytä kaikki lisätiedot", :comment "Lisätieto", :ownership "Omistus", :name-short "Nimi", :basic-data "Perustiedot", :delete-reason "Poiston syy", :event-date "Muokattu", :email-public "Sähköposti (julkinen)", :add-new "Lisää liikuntapaikka", :contact "Yhteystiedot", :owner "Omistaja", :marketing-name "Markkinointinimi"}, :status {:active "Toiminnassa", :planned "Suunniteltu" :incorrect-data "Väärä tieto", :out-of-service-permanently "Poistettu käytöstä pysyvästi", :out-of-service-temporarily "Poistettu käytöstä väliaikaisesti"}, :register {:headline "Rekisteröidy", :link "Rekisteröidy" :thank-you-for-registering "Kiitos rekisteröitymisestä! Saat sähköpostiisi viestin kun sinulle on myönnetty käyttöoikeudet."}, :map.address-search {:title "Etsi osoite", :tooltip "Etsi osoite"}, :ice-comparison {:headline "Hallien vertailu"}, :lipas.visitors {:headline "Kävijämäärät", :monthly-visitors-in-year "Kuukausittaiset kävijämäärät vuonna {1}", :not-reported "Ei kävijämäärätietoja", :not-reported-monthly "Ei kuukausitason tietoja", :spectators-count "Katsojamäärä", :total-count "Käyttäjämäärä"}, :lipas.energy-stats {:headline "Hallien energiankulutus vuonna {1}", :energy-reported-for "Sähkön-, lämmön- ja vedenkulutus ilmoitettu vuodelta {1}", :report "Ilmoita lukemat", :disclaimer "*Perustuu ilmoitettuihin kulutuksiin vuonna {1}", :reported "Ilmoitettu {1}", :cold-mwh "Kylmä MWh", :hall-missing? "Puuttuvatko hallisi tiedot kuvasta?", :not-reported "Ei tietoa {1}", :water-m3 "Vesi m³", :electricity-mwh "Sähkö MWh", :heat-mwh "Lämpö MWh", :energy-mwh "Sähkö + lämpö MWh"}, :map.basemap {:copyright "© Maanmittauslaitos", :maastokartta "Maastokartta", :ortokuva "Ilmakuva", :taustakartta "Taustakartta"}, :map.overlay {:tooltip "Muut karttatasot" :mml-kiinteisto "Kiinteistörajat" :light-traffic "Kevyen liikenteen väylät" :retkikartta-snowmobile-tracks "Metsähallituksen moottorikelkkaurat"} :lipas.swimming-pool.pools {:add-pool "Lisää allas", :edit-pool "Muokkaa allasta", :headline "Altaat", :structure "Rakenne"}, :condensate-energy-targets {:hall-heating "Hallin lämmitys", :maintenance-water-heating "Jäänhoitoveden lämmitys", :other-space-heating "Muun tilan lämmitys", :service-water-heating "Käyttöveden lämmitys", :snow-melting "Lumensulatus", :track-heating "Ratapohjan lämmitys"}, :refrigerants {:CO2 "CO2 (hiilidioksidi)", :R134A "R134A", :R22 "R22", :R404A "R404A", :R407A "R407A", :R407C "R407C", :R717 "R717"}, :harrastuspassi {:disclaimer "Kun ”saa julkaista Harrastuspassissa” – ruutu on rastitettu, liikuntapaikan tiedot siirretään automaattisesti Harrastuspassi-palveluun. Sitoudun päivittämään liikuntapaikan tietojen muutokset viipymättä Lippaaseen. Paikan hallinnoijalla on vastuu tietojen oikeellisuudesta ja paikan turvallisuudesta. Tiedot näkyvät Harrastuspassissa vain, mikäli kunnalla on sopimus Harrastuspassin käytöstä Harrastuspassin palveluntuottajan kanssa."} :retkikartta {:disclaimer "Kun ”Saa julkaista Retkikartassa” -ruutu on rastitettu, luontoliikuntapaikan tiedot siirretään automaattisesti Metsähallituksen ylläpitämään Retkikartta.fi -karttapalveluun kerran vuorokaudessa. Sitoudun päivittämään luontoliikuntapaikan tietojen muutokset viipymättä Lippaaseen. Paikan hallinnoijalla on vastuu tietojen oikeellisuudesta, paikan turvallisuudesta, palautteisiin vastaamisesta ja mahdollisista yksityisteihin liittyvistä kustannuksista."}, :reset-password {:change-password "Vaihda salasana", :enter-new-password "Syötä uusi salasana", :get-new-link "Tilaa uusi vaihtolinkki", :headline "Unohtuiko salasana?", :helper-text "Lähetämme salasanan vaihtolinkin sinulle sähköpostitse.", :password-helper-text "Salasanassa on oltava vähintään 6 merkkiä", :reset-link-sent "Linkki lähetetty! Tarkista sähköpostisi.", :reset-success "Salasana vaihdettu! Kirjaudu sisään uudella salasanalla."}, :reports {:contacts "Yhteys​tiedot", :download-as-excel "Luo raportti", :select-fields "Valitse raportin kentät", :selected-fields "Valitut kentät", :shortcuts "Pikavalinnat", :tooltip "Luo Excel-raportti hakutuloksista"}, :heat-sources {:district-heating "Kaukolämpö", :private-power-station "Oma voimalaitos"}, :map.import {:headline "Tuo geometriat", :geoJSON "Tuo .json-tiedosto, joka sisältää GeoJSON FeatureCollection -objektin. Lähtöaineiston pitää olla WGS84-koordinaatistossa.", :gpx "Lähtöaineiston pitää olla WGS84-koordinaatistossa.", :supported-formats "Tuetut tiedostomuodot ovat {1}", :replace-existing? "Korvaa nykyiset geometriat", :select-encoding "Valitse merkistö", :tab-header "Tuo tiedostosta", :kml "Lähtöaineiston pitää olla WGS84 koordinaatistossa.", :shapefile "Tuo .shp-, .dbf- ja .prj-tiedostot pakattuna .zip-muotoon.", :import-selected "Tuo valitut", :tooltip "Tuo geometriat tiedostosta", :unknown-format "Tuntematon tiedostopääte '{1}'"}, :error {:email-conflict "Sähköpostiosoite on jo käytössä", :email-not-found "Sähköpostiosoitetta ei ole rekisteröity.", :invalid-form "Korjaa punaisella merkityt kohdat", :no-data "Ei tietoja", :reset-token-expired "Salasanan vaihto epäonnistui. Linkki on vanhentunut.", :unknown "Tuntematon virhe tapahtui. :/", :user-not-found "Käyttäjää ei löydy.", :username-conflict "Käyttäjätunnus on jo käytössä"}, :reminders {:description "Viesti lähetetään sähköpostiisi valittuna ajankohtana", :after-one-month "Kuukauden kuluttua", :placeholder "Muista tarkistaa liikuntapaikka \"{1}\" {2}", :select-date "Valitse päivämäärä", :tomorrow "Huomenna", :title "Lisää muistutus", :after-six-months "Puolen vuoden kuluttua", :in-a-year "Vuoden kuluttua", :message "Viesti", :in-a-week "Viikon kuluttua"}, :units {:days-in-year "päivää vuodessa", :hours-per-day "tuntia päivässä", :pcs "kpl", :percent "%", :person "hlö", :times-per-day "kertaa päivässä", :times-per-week "kertaa viikossa"}, :lipas.energy-consumption {:contains-other-buildings? "Energialukemat sisältävät myös muita rakennuksia tai tiloja", :headline "Energian​kulutus", :yearly "Vuositasolla*", :report "Ilmoita lukemat", :electricity "Sähköenergia MWh", :headline-year "Lukemat vuonna {1}", :monthly? "Haluan ilmoittaa energiankulutuksen kuukausitasolla", :reported-for-year "Vuoden {1} energiankulutus ilmoitettu", :monthly "Kuukausitasolla", :operating-hours "Käyttötunnit", :not-reported "Ei energiankulutustietoja", :not-reported-monthly "Ei kuukausikulutustietoja", :heat "Lämpöenergia (ostettu) MWh", :cold "Kylmäenergia (ostettu) MWh", :comment "Kommentti", :water "Vesi m³", :monthly-readings-in-year "Kuukausikulutukset vuonna {1}"}, :ice {:description "Jäähalliportaali sisältää hallien perus- ja energiankulutustietoja sekä ohjeita energiatehokkuuden parantamiseen.", :large "Suurhalli > 3000 hlö", :competition "Kilpahalli < 3000 hlö", :headline "Jäähalli​portaali", :video "Video", :comparison "Hallien vertailu", :size-category "Kokoluokitus", :basic-data-of-halls "Jäähallien perustiedot", :updating-basic-data "Perustietojen päivitys", :entering-energy-data "Energiankulutustietojen syöttäminen", :small "Pieni kilpahalli > 500 hlö", :watch "Katso", :video-description "Pihlajalinna Areena on energiatehokas jäähalli"}, :lipas.location {:address "Katuosoite", :city "Kunta", :city-code "Kuntanumero", :headline "Sijainti", :neighborhood "Kuntaosa", :postal-code "Postinumero", :postal-office "Postitoimipaikka"}, :lipas.user.permissions {:admin? "Admin", :all-cities? "Oikeus kaikkiin kuntiin", :all-types? "Oikeus kaikkiin tyyppeihin", :cities "Kunnat", :sports-sites "Liikuntapaikat", :types "Tyypit"}, :help {:headline "Ohjeet", :permissions-help "Jos haluat lisää käyttöoikeuksia, ota yhteyttä ", :permissions-help-body "Haluan käyttöoikeudet seuraaviin liikuntapaikkoihin:", :permissions-help-subject "Haluan lisää käyttöoikeuksia"}, :ceiling-structures {:concrete "Betoni", :double-t-beam "TT-laatta", :glass "Lasi", :hollow-core-slab "Ontelolaatta", :solid-rock "Kallio", :steel "Teräs", :wood "Puu"}, :data-users {:data-user? "Käytätkö LIPAS-dataa?", :email-body "Mukavaa että hyödynnät LIPAS-dataa! Kirjoita tähän kuka olet ja miten hyödynnät Lipasta. Käytätkö mahdollisesti jotain rajapinnoistamme?", :email-subject "Mekin käytämme LIPAS-dataa", :headline "Lipasta hyödyntävät", :tell-us "Kerro siitä meille"}, :lipas.swimming-pool.facilities {:showers-men-count "Miesten suihkut lkm", :lockers-men-count "Miesten pukukaapit lkm", :headline "Muut palvelut", :platforms-5m-count "5 m hyppypaikkojen lkm", :kiosk? "Kioski / kahvio", :hydro-neck-massage-spots-count "Niskahierontapisteiden lkm", :lockers-unisex-count "Unisex pukukaapit lkm", :platforms-10m-count "10 m hyppypaikkojen lkm", :hydro-massage-spots-count "Muiden hierontapisteiden lkm", :lockers-women-count "Naisten pukukaapit lkm", :platforms-7.5m-count "7.5 m hyppypaikkojen lkm", :gym? "Kuntosali", :showers-unisex-count "Unisex suihkut lkm", :platforms-1m-count "1 m hyppypaikkojen lkm", :showers-women-count "Naisten suihkut lkm", :platforms-3m-count "3 m hyppypaikkojen lkm"}, :sauna-types {:infrared-sauna "Infrapunasauna", :other-sauna "Muu sauna", :sauna "Sauna", :steam-sauna "Höyrysauna"}, :stats-metrics {:investments "Investoinnit", :net-costs "Nettokustannukset", :operating-expenses "Käyttökustannukset", :operating-incomes "Käyttötuotot", :subsidies "Kunnan myöntämät avustukset"}, :refrigerant-solutions {:CO2 "CO2", :H2ONH3 "H2O/NH3", :cacl "CaCl", :ethanol-water "Etanoli-vesi", :ethylene-glycol "Etyleeniglykoli", :freezium "Freezium", :water-glycol "Vesi-glykoli"}, :user {:headline "Oma sivu", :admin-page-link "Siirry admin-sivulle", :promo1-link "Näytä TEAviisari-kohteet jotka voin päivittää", :swimming-pools-link "Uimahallit", :promo-headline "Ajankohtaista", :front-page-link "Siirry etusivulle", :promo1-text "Opetus- ja kulttuuriministeriö pyytää kuntia täydentämään erityisesti sisäliikuntapaikkojen rakennusvuosien ja peruskorjausvuosien tiedot. Tieto on tärkeää mm. liikuntapaikkojen korjausvelkaa arvioitaessa.", :ice-stadiums-link "Jäähallit", :greeting "Hei {1} {2}!", :promo1-topic "Kiitos että käytät Lipas.fi-palvelua!"}, :building-materials {:brick "Tiili", :concrete "Betoni", :solid-rock "Kallio", :steel "Teräs", :wood "Puu"}, :stats {:disclaimer-headline "Tietolähde" :general-disclaimer-1 "Lipas.fi – Suomen liikuntapaikat, ulkoilureitit ja virkistysalueet: Nimeä 4.0 Kansainvälinen (CC BY 4.0)." :general-disclaimer-2 "Voit vapaasti käyttää, kopioida, jakaa ja muokata aineistoa. Aineistolähteeseen tulee viitata esimerkiksi näin: Liikuntapaikat: Lipas.fi Jyväskylän yliopisto, otospäivä. Lisätietoja Creative Commons. https://creativecommons.org/licenses/by/4.0/deed.fi" :general-disclaimer-3 "Huomaa, että Lipas-tietokannan tiedot perustuvat kuntien ja muiden liikuntapaikkojen omistajien Lipas-tietokantaan syöttämiin tietoihin sekä Jyväskylän yliopiston Lipas-ylläpitäjien tuottamaan aineistoon. Tietojen kattavuutta, virheettömyyttä, ajantasaisuutta ja yhdenmukaisuutta ei voida taata. Lipas.fi –tilastot -osiossa tilastojen laskenta perustuu tietokantaan tallennettuihin tietoihin. Mahdolliset puuttuvat tiedot vaikuttavat laskelmiin." :finance-disclaimer "Aineistolähde: Tilastokeskus avoimet tilastoaineistot. Huomaa, että kunnat vastaavat itse virallisten taloustietojensa tallentamisesta Tilastokeskuksen tietokantaan Tilastokeskuksen ohjeiden perusteella. Tietojen yhdenmukaisuudesta tai aikasarjojen jatkuvuudesta ei voida antaa takeita." :description "Kuntien viralliset tilinpäätöstiedot liikunta- ja nuorisotoimien osalta. Kunta voi seurata omaa menokehitystään ja vertailla sitä muihin kuntiin.", :filter-types "Rajaa tyypit", :length-km-sum "Liikuntareittien pituus km yhteensä", :headline "Tilastot", :select-years "Valitse vuodet", :browse-to "Siirry tilastoihin", :select-issuer "Valitse myöntäjä", :select-unit "Valitse yksikkö", :bullet3 "Avustukset", :finance-stats "Talous​tiedot", :select-city "Valitse kunta", :area-m2-min "Liikuntapinta-ala m² min", :filter-cities "Rajaa kunnat", :select-metrics "Valitse suureet", :area-m2-count "Liikuntapinta-ala m² ilmoitettu lkm", :show-ranking "Näytä ranking", :age-structure-stats "Rakennus​vuodet", :subsidies-count "Avustusten lkm", :area-m2-sum "Liikuntapinta-ala m² yhteensä", :select-metric "Valitse suure", :bullet2 "Liikuntapaikkatilastot", :area-m2-max "Liikuntapinta-ala m² max", :select-grouping "Ryhmittely", :select-city-service "Valitse toimi", :region "Alue", :show-comparison "Näytä vertailu", :length-km-avg "Liikuntareitin pituus km keskiarvo", :sports-sites-count "Liikuntapaikkojen lkm", :length-km-min "Liikuntareitin pituus km min", :country-avg "(maan keskiarvo)", :length-km-count "Liikuntareitin pituus ilmoitettu lkm", :population "Asukasluku", :sports-stats "Liikunta​paikat", :select-cities "Valitse kunnat", :subsidies "Avustukset", :select-interval "Valitse aikaväli", :bullet1 "Liikunta- ja nuorisotoimen taloustiedot", :area-m2-avg "Liikuntapinta-ala m² keskiarvo", :age-structure "Liikunta​paikkojen rakennus​vuodet", :length-km-max "Liikuntareitin pituus km max", :total-amount-1000e "Yht. (1000 €)", :city-stats "Kunta​tilastot"}, :pool-structures {:concrete "Betoni", :hardened-plastic "Lujitemuovi", :steel "Teräs"}, :map {:retkikartta-checkbox-reminder "Muista myös valita \"Saa julkaista Retkikartta.fi -palvelussa\" ruksi seuraavan vaiheen lisätiedoissa.\"", :zoom-to-user "Kohdista sijaintiini", :remove "Poista", :modify-polygon "Muokkaa aluetta", :draw-polygon "Lisää alue", :retkikartta-problems-warning "Korjaa kartalle merkityt ongelmat, jos haluat, että kohde siirtyy Retkikartalle.", :edit-later-hint "Voit muokata geometriaa myös myöhemmin", :center-map-to-site "Kohdista kartta liikuntapaikkaan", :draw-hole "Lisää reikä", :split-linestring "Katkaise reittiosa", :delete-vertices-hint "Yksittäisiä pisteitä voi poistaa pitämällä alt-näppäintä pohjassa ja klikkaamalla pistettä.", :calculate-route-length "Laske reitin pituus automaattisesti", :remove-polygon "Poista alue", :modify-linestring "Muokkaa reittiä", :download-gpx "Lataa GPX", :add-to-map "Lisää kartalle", :bounding-box-filter "Hae kartan alueelta", :remove-linestring "Poista reittiosa", :draw-geoms "Piirrä", :confirm-remove "Haluatko varmasti poistaa valitun geometrian?", :draw "Lisää kartalle", :draw-linestring "Lisää reittiosa", :modify "Voit raahata pistettä kartalla", :zoom-to-site "Kohdista kartta liikuntapaikkaan", :kink "Muuta reitin kulkua niin, että reittiosa ei risteä itsensä kanssa. Voit tarvittaessa katkaista reitin useampaan osaan.", :zoom-closer "Kartta täytyy zoomata lähemmäs"}, :supporting-structures {:brick "Tiili", :concrete "Betoni", :concrete-beam "Betonipalkki", :concrete-pillar "Betonipilari", :solid-rock "Kallio", :steel "Teräs", :wood "Puu"}, :owner {:unknown "Ei tietoa", :municipal-consortium "Kuntayhtymä", :other "Muu", :company-ltd "Yritys", :city "Kunta", :state "Valtio", :registered-association "Rekisteröity yhdistys", :foundation "Säätiö", :city-main-owner "Kuntaenemmistöinen yritys"}, :menu {:frontpage "Etusivu", :headline "LIPAS", :jyu "Jyväskylän yliopisto", :main-menu "Päävalikko"}, :dryer-types {:cooling-coil "Jäähdytyspatteri", :munters "Muntters", :none "Ei ilmankuivausta"}, :physical-units {:mm "mm", :hour "h", :m3 "m³", :m "m", :temperature-c "Lämpötila °C", :l "l", :mwh "MWh", :m2 "m²", :celsius "°C"}, :lipas.swimming-pool.water-treatment {:activated-carbon? "Aktiivihiili", :filtering-methods "Suodatustapa", :headline "Vedenkäsittely", :ozonation? "Otsonointi", :uv-treatment? "UV-käsittely"}, :statuses {:edited "{1} (muokattu)"}, :lipas.user {:email "Sähköposti", :permissions "Käyttöoikeudet", :permissions-example "Oikeus päivittää Jyväskylän jäähallien tietoja.", :saved-searches "Tallennetut haut", :report-energy-and-visitors "Ilmoita energia- ja kävijämäärätiedot", :permission-to-cities "Sinulla on käyttöoikeus seuraaviin kuntiin:", :password "Salasana", :lastname "Sukunimi", :save-report "Tallenna raporttipohja", :sports-sites "Omat kohteet", :permission-to-all-cities "Sinulla on käyttöoikeus kaikkiin kuntiin", :username "Käyttäjätunnus", :history "Historia", :saved-reports "Tallennetut raporttipohjat", :contact-info "Yhteystiedot", :permission-to-all-types "Sinulla on käyttöoikeus kaikkiin liikuntapaikkatyyppeihin", :requested-permissions "Pyydetyt oikeudet", :email-example "kalle.kayttaja@kunta.fi", :permission-to-portal-sites "Sinulla on käyttöoikeus seuraaviin yksittäisiin liikuntapaikkoihin:", :permissions-help "Kerro, mitä tietoja haluat päivittää Lipaksessa", :report-energy-consumption "Ilmoita energiankulutus", :firstname "Etunimi", :save-search "Tallenna haku", :view-basic-info "Tarkista perustiedot", :no-permissions "Sinulle ei ole vielä myönnetty käyttöoikeuksia.", :username-example "tane12", :permission-to-types "Sinulla on käyttöoikeus seuraaviin liikuntapaikkatyyppeihin:"}, :heat-recovery-types {:liquid-circulation "Nestekierto", :plate-heat-exchanger "Levysiirrin", :thermal-wheel "Pyörivä"}}, :se {:sport {:description "LIPAS är en landsomfattande databas för offentliga finländska idrottsplatser.", :headline "Idrottsanläggningar", :open-interfaces "Öppna gränssnitt", :up-to-date-information "Aktuell data om finska idrottsanläggningar", :updating-tools "Uppdateringsverktyg"}, :confirm {:discard-changes? "Vill du förkasta ändringar?", :headline "Bekräftelse", :no "Nej", :press-again-to-delete "Klicka igen för att radera", :resurrect? "Vill du spara grunddata?", :save-basic-data? "Vill du spara grunddata?", :yes "Ja"}, :lipas.swimming-pool.saunas {:accessible? "Tillgängligt", :add-sauna "Lägg till en bastu", :edit-sauna "Redigera bastun", :headline "Bastur", :men? "Män", :women? "Kvinnor"}, :slide-structures {:concrete "Betong", :hardened-plastic "Öppna gränssnitt", :steel "Stål"}, :lipas.swimming-pool.conditions {:open-days-in-year "Fredagar", :open-hours-mon "Måndagar", :headline "Öppettider", :open-hours-wed "Onsdagar", :open-hours-thu "Torsdagar", :open-hours-fri "Fredagar", :open-hours-tue "Tisdagar", :open-hours-sun "Söndagar", :daily-open-hours "Dagliga öppettider", :open-hours-sat "Lördagar"}, :lipas.ice-stadium.ventilation {:dryer-duty-type "Gatuadress", :dryer-type "Kommun", :heat-pump-type "Gatuadress", :heat-recovery-efficiency "Kommun", :heat-recovery-type "Gatuadress"}, :swim {:basic-data-of-halls "Simhallsportal", :edit "Simhallsportal", :entering-energy-data "Datum", :headline "Simhallsportal", :latest-updates "Timme", :list "Energi information", :updating-basic-data "Information", :visualizations "Energi information"}, :home-page {:description "LIPAS-system innehåller information av idrottsanläggningar, idrottsrutter och friluftsregioner. Data är öppen CC4.0 International.", :headline "Startsida"}, :ice-energy {:finhockey-link "El", :headline "Bensin"}, :filtering-methods {:activated-carbon "Kol", :coal "Kol", :membrane-filtration "Annat", :open-sand "Annat", :other "Annat", :precipitation "Beskrivning", :pressure-sand "Kommentar"}, :open-data {:description "Länkar och information om gränssnitten", :headline "Öppna data", :rest "REST", :wms-wfs "WMS & WFS"}, :lipas.swimming-pool.pool {:accessibility "Tillgänglighet", :outdoor-pool? "Utomhus simbassäng"}, :pool-types {:multipurpose-pool "Allaktivitetsbassäng", :whirlpool-bath "Bubbelbad", :main-pool "Huvudsbassäng", :therapy-pool "Terapibassäng", :fitness-pool "Konditionsbassäng", :diving-pool "Hoppbassäng", :childrens-pool "Barnbassäng", :paddling-pool "Plaskdamm", :cold-pool "Kallbassäng", :other-pool "Annan bassäng", :teaching-pool "Undervisningsbassäng"}, :disclaimer {:headline "OBS!", :test-version "Automatisk"}, :admin {:private-foundation "Privat / stiftelse", :city-other "Kommun / annat", :unknown "Okänt", :municipal-consortium "Samkommun", :private-company "Privat / företag", :private-association "Privat / förening", :other "Annat", :city-technical-services "Kommun / teknisk väsende", :city-sports "Kommun/ idrottsväsende", :state "Stat", :city-education "Kommun / utbildingsväsende"}, :accessibility {:lift "Lyft i bassängen", :slope "Ramp"}, :general {:description "Beskrivning", :hall "Hall", :women "Kvinnor", :total-short "Totalt", :done "Färdig", :updated "Uppdaterad", :name "Namn", :reported "Rapporterad", :type "Typ", :last-modified "Senaste redigerad", :here "här", :event "Händelse", :structure "Struktur", :general-info "Allmänna uppgifter", :comment "Kommentar", :measures "Mått", :men "Män"}, :dryer-duty-types {:automatic "Automatisk", :manual "Manual"}, :swim-energy {:description "Information", :headline "Energi information", :headline-short "Information", :suh-link "Datum", :ukty-link "Slutade"}, :time {:two-years-ago "För 2 år sedan", :date "Datum", :hour "Timme", :this-month "Den här månaden", :time "Tid", :less-than-hour-ago "För mindre än en timme sedan", :start "Började", :this-week "Den här veckan", :today "I dag", :month "Månad", :long-time-ago "För länge sedan", :year "År", :just-a-moment-ago "För en stund sedan", :yesterday "I går", :three-years-ago "För 3 år sedan", :end "Slutade", :this-year "Det här året", :last-year "Förra året"}, :ice-resurfacer-fuels {:LPG "El", :electicity "El", :gasoline "Bensin", :natural-gas "Naturgas", :propane "Propan"}, :ice-rinks {:headline "Du har admin rättigheter."}, :month {:sep "September", :jan "Januari", :jun "Juni", :oct "Oktober", :jul "Juli", :apr "April", :feb "Februari", :nov "November", :may "Maj", :mar "Mars", :dec "December", :aug "Augusti"}, :type {:name "Idrottsanläggningstyp", :main-category "Huvudkategori", :sub-category "Underkategori", :type-code "Typkod"}, :duration {:hour "timmar", :month "månader", :years "år", :years-short "år"}, :size-categories {:large "Betong"}, :lipas.admin {:access-all-sites "Du har admin rättigheter.", :confirm-magic-link "Är du säker på att du vill skicka magic link till {1}?", :headline "Admin", :magic-link "Magic link", :select-magic-link-template "Välj brev", :send-magic-link "Skicka magic link till användare", :users "Användare"}, :lipas.building {:headline "Byggnad", :total-volume-m3 "Areal av vatten m²", :staff-count "Antalet personal", :heat-sections? "Antalet personal", :total-ice-area-m2 "Areal av is m²", :main-designers "Antalet personal", :total-pool-room-area-m2 "Areal av vatten m²", :total-water-area-m2 "Areal av vatten m²", :ceiling-structures "Byggnad", :supporting-structures "Areal av is m²", :seating-capacity "Antalet personal"}, :search {:table-view "Visa resultaten i tabellen", :headline "Sökning", :results-count "{1} resultat", :placeholder "Sök...", :retkikartta-filter "Retkikartta.fi-platser", :filters "Filtrera sökning", :search-more "Sök mer...", :page-size "Visa", :search "Sök", :permissions-filter "Visa platser som jag kan redigera", :display-closest-first "Visa närmaste platser först", :list-view "Visa resultaten i listan", :pagination "Resultaten {1}-{2}", :school-use-filter "Idrottsanläggningar nära skolor", :clear-filters "Avmarkera filter"}, :map.tools {:drawing-tooltip "Ritningsverktyg vald", :drawing-hole-tooltip "Hålverktyg vald", :edit-tool "Redigeringsverktyg", :importing-tooltip "Importeringsverktyg vald", :deleting-tooltip "Borttagningsverktyg vald", :splitting-tooltip "Klippningsverktyg vald"}, :partners {:headline "Tillsammans med"}, :actions {:duplicate "Kopiera", :resurrect "Öppna huvudmeny", :select-year "Välj år", :select-owners "Välj ägare", :select-admins "Välj administratörer", :select-tool "Välj verktyg", :save-draft "Spara utkast", :redo "Gör igen", :open-main-menu "Öppna huvudmeny", :back-to-listing "Till listan", :filter-surface-materials "Avgränsa enligt ytmaterial", :browse "flytta dig", :select-type "Välj typ", :edit "Redigera", :filter-construction-year "Avgränsa enligt byggnadsår", :submit "Skicka", :choose-energy "Välj energi", :delete "Radera", :browse-to-map "Flytta dig till kartan", :save "Spara", :close "Stäng", :filter-area-m2 "Avgränsa enligt areal m²", :show-account-menu "Öppna kontomeny", :fill-required-fields "Fyll i obligatoriska fält", :undo "Ångra", :browse-to-portal "Flytta dig till portalen", :download-excel "Ladda ner Excel", :fill-data "Fyll i informationen", :select-statuses "Status", :select-cities "Välj kommuner", :select-hint "Välj...", :discard "Förkasta", :more "Mer...", :cancel "Avbryta", :select-columns "Välj datafält", :add "Tillägg ", :show-all-years "Visa alla år", :download "Ladda ner", :select-hall "Välj hall", :clear-selections "Ta bort val", :select "Välj", :select-types "Välj typer"}, :dimensions {:area-m2 "Areal m²", :depth-max-m "Djup max m", :depth-min-m "Djup min m", :length-m "Längd m", :surface-area-m2 "Areal m²", :volume-m3 "Volym m3", :width-m "Bredd m"}, :login {:headline "Logga in", :login-here "här", :login-with-password "Logga in med lösenord", :password "Lösenord", :logout "Logga ut", :username "E-post / användarnamn", :login-help "Om du har ett användarnamn till LIPAS, du kan också logga in med e-post", :login "Logga in", :magic-link-help "Om du har ett användarnamn till LIPAS, du kan beställa en logga in-länk till din e-post.", :order-magic-link "Skicka länken till min e-post", :login-with-magic-link "Logga in med e-post", :bad-credentials "Lösenord eller användarnamn är felaktigt", :magic-link-ordered "Länken har skickats och den är snart i din e-post. Kolla också spam!", :username-example "paavo.paivittaja@kunta.fi", :forgot-password? "Glömt ditt lösenord?"}, :map.demographics {:headline "Befolkning", :tooltip "Visa befolkning", :helper-text "Välj idrottsanläggning på kartan.", :copyright1 "Befolkningsinformation: Statistikcentralen 2019 årets", :copyright2 "1 km * 1 km data", :copyright3 "licens"}, :lipas.swimming-pool.slides {:add-slide "Lägg till en rutschbana", :edit-slide "Redigera rutschbanan", :headline "Rutschbanor"}, :notifications {:get-failed "Datasökning misslyckades.", :save-failed "Sparningen misslyckades", :save-success "Sparningen lyckades" :ie (str "Internet Explorer stöds inte. Vi rekommenderar du använder t.ex. Chrome, Firefox eller Edge.")}, :lipas.swimming-pool.energy-saving {:filter-rinse-water-heat-recovery? "Gym", :headline "Andra tjänster", :shower-water-heat-recovery? "Gym"}, :ice-form {:headline "Naturgas", :headline-short "El", :select-rink "Bensin"}, :restricted {:login-or-register "Logga in eller registrera dig"}, :lipas.sports-site {:properties "Ytterligare information", :delete-tooltip "Ta bort idrottsanläggningen...", :headline "Idrottsanläggning", :new-site-of-type "Ny {1}", :address "Adress", :new-site "Ny idrottsplats", :phone-number "Telefonnummer", :admin "Administratör", :surface-materials "Ytmaterial", :www "Webbsida", :name "Namn på finska", :reservations-link "Bokningar", :construction-year "Byggår", :type "Typ", :delete "Ta bort {1}", :renovation-years "Renoveringsår", :name-localized-se "Namn på svenska", :status "Status", :id "LIPAS-ID", :details-in-portal "Visa alla ytterligare information", :comment "Ytterligare information", :ownership "Ägare", :name-short "Namn", :basic-data "Grunddata", :delete-reason "Orsak", :event-date "Redigerad", :email-public "E-post (publik)", :add-new "Lägg till en idrottsanläggning", :contact "Kontaktinformation", :owner "Ägare", :marketing-name "Varumärkesnamn"}, :status {:active "Aktiv", :planned "Planerad" :incorrect-data "Fel information", :out-of-service-permanently "Permanent ur funktion", :out-of-service-temporarily "Tillfälligt ur funktion"}, :register {:headline "Registrera", :link "Registrera här" :thank-you-for-registering "Tack för registrering! Du vill få e-posten snart."}, :map.address-search {:title "Sök address", :tooltip "Sök address"}, :ice-comparison {:headline "Jämförelse av hallar"}, :lipas.visitors {:headline "Användare", :not-reported "Glömt lösenordet?", :not-reported-monthly "Lösenord eller användarnamn är felaktigt", :spectators-count "Glömt ditt lösenord?", :total-count "Lösenord eller användarnamn är felaktigt"}, :lipas.energy-stats {:headline "Värme MWh", :energy-reported-for "Värme MWh", :disclaimer "El MWh", :reported "Vatten m³", :cold-mwh "El + värme MWh", :hall-missing? "Vatten m³", :not-reported "Vatten m³", :water-m3 "Vatten m³", :electricity-mwh "El MWh", :heat-mwh "Värme MWh", :energy-mwh "El + värme MWh"}, :map.basemap {:copyright "© Lantmäteriverket", :maastokartta "Terrängkarta", :ortokuva "Flygfoto", :taustakartta "Bakgrundskarta"}, :lipas.swimming-pool.pools {:add-pool "Lägg till en bassäng", :edit-pool "Redigera bassängen", :headline "Bassänger", :structure "Struktur"}, :condensate-energy-targets {:service-water-heating "Nej", :snow-melting "Vill du förkasta ändringar?", :track-heating "Vill du förkasta ändringar?"}, :refrigerants {:CO2 "CO2 (koldioxid)", :R134A "R134A", :R22 "R22", :R404A "R404A", :R407A "R407A", :R407C "R407C", :R717 "R717"}, :harrastuspassi {:disclaimer "När du kryssat för rutan ”Kan visas på Harrastuspassi.fi” flyttas uppgifterna om idrottsanläggningen automatiskt till Harrastuspassi.fi. Jag förbinder mig att uppdatera ändringar i uppgifterna om idrottsanläggningen utan dröjsmål i Lipas. Anläggningens administratör ansvarar för uppgifternas riktighet och anläggningens säkerhet. Uppgifterna visas i Harrastuspassi.fi om kommunen har kontrakt med Harrastuspassi.fi administratör för att använda Harrastuspassi.fi."} :retkikartta {:disclaimer "När du kryssat för rutan ”Kan visas på Utflyktskarta.fi” flyttas uppgifterna om naturutflyktsmålet automatiskt till karttjänsten Utflyktskarta.fi som Forststyrelsen administrerar. Uppgifter överförs till karttjänsten en gång i dygnet. Jag förbinder mig att uppdatera ändringar i uppgifterna om naturutflyktsmålet utan dröjsmål i Lipas. Utflyktsmålets administratör ansvarar för uppgifternas riktighet och utflyktsmålets säkerhet samt för svar på respons och för eventuella kostnader i samband med privata vägar."}, :reset-password {:change-password "Ändra lösenord", :enter-new-password "Skriv ett ny lösenord", :get-new-link "Bestella ny återställningslänk", :headline "Glömt lösenordet?", :helper-text "Vi ska skicka en återställningslänk till din e-post.", :password-helper-text "Lösenordet måste innehålla minst 6 tecken.", :reset-link-sent "Länken har skickats! Kolla din e-post.", :reset-success "Lösenordet har ändrats! Logga in med ditt nya lösenord."}, :reports {:contacts "Kontaktuppgifter", :download-as-excel "Skapa Excel", :select-fields "Välj fält för rapport", :selected-fields "Vald fält", :shortcuts "Genvägar", :tooltip "Skapa Excel-rapport från resultaten"}, :heat-sources {:district-heating "Om du behöver ytterligare användarrättigheter, kontakt ", :private-power-station "Hjälp"}, :map.import {:headline "Importera geometri", :geoJSON "Laddar upp .json file som innehåller GeoJSON FeatureCollect object. Koordinater måste vara i WGS84 koordinatsystem.", :gpx "Utgångsmaterial måste vara i WGS84 koordinatsystem.", :supported-formats "Filformat som passar är {1}", :replace-existing? "Ersätt gammal geometri", :select-encoding "Välj teckenuppsättning", :tab-header "Importera från filen", :kml "Utgångsmaterial måste vara i WGS84 koordinatsystem.", :shapefile "Importera .shp .dbf och .prj filer i packade .zip filen.", :import-selected "Importera valda", :tooltip "Importera geometrier från filen", :unknown-format "Okänt filformat '{1}'"}, :error {:email-conflict "E-post är redan registrerad", :email-not-found "E-post är inte registrerad", :invalid-form "Korrigera röda fält", :no-data "Ingen information", :reset-token-expired "Lösenordet har inte ändrats. Länken har utgått.", :unknown "Ett okänt fel uppstod. :/", :user-not-found "Användare hittas inte.", :username-conflict "Användarnamnet redan används"}, :reminders {:description "Meddelandet ska skickas till din e-post på vald tid.", :after-one-month "Om en månad", :placeholder "Kom ihåg att kolla idrottsanläggningen \"{1}\" {2}", :select-date "Välj datum", :tomorrow "I morgon", :title "Lägg till en påminnelse", :after-six-months "Om halv år", :in-a-year "Om ett år", :message "Meddelande", :in-a-week "Om en vecka"}, :units {:days-in-year "dagar per år", :hours-per-day "timmar per dag", :pcs "st", :percent "%", :person "pers.", :times-per-day "gånger per dag", :times-per-week "gånger per vecka"}, :lipas.energy-consumption {:cold "Kommentar", :comment "Kommentar", :monthly? "Vatten m³", :operating-hours "Vatten m³", :report "El MWh", :reported-for-year "Vatten m³", :water "Vatten m³", :yearly "El MWh"}, :ice {:description "Stor tävlingshall > 3000", :large "Stor tävlingshall > 3000", :competition "Tävlingsishall < 3000 person", :headline "Ishallsportal", :video "Video", :comparison "Jämförelse av hallar", :size-category "Storlek kategori", :basic-data-of-halls "Grunddata av ishallar", :updating-basic-data "Uppdatering av grunddata", :entering-energy-data "Ishallsportal", :small "Liten tävlingshall > 500 person", :watch "Titta", :video-description "Titta"}, :lipas.location {:address "Gatuadress", :city "Kommun", :city-code "Kommunkod", :headline "Position", :neighborhood "Kommundel", :postal-code "Postnummer", :postal-office "Postkontor"}, :lipas.user.permissions {:admin? "Admin", :all-cities? "Rättighet till alla kommuner", :all-types? "Rättighet till alla typer", :cities "Kommuner", :sports-sites "Idrottsanläggning", :types "Typer"}, :help {:headline "Hjälp", :permissions-help "Om du behöver ytterligare användarrättigheter, kontakt ", :permissions-help-body "Jag behöver användarrättigheter till följande platser:", :permissions-help-subject "Jag behöver mera användarrättigheter"}, :ceiling-structures {:concrete "Betong", :double-t-beam "TT-bricka", :glass "Glas", :hollow-core-slab "Häll", :solid-rock "Häll", :steel "Stål", :wood "Trä"}, :data-users {:data-user? "Använder du LIPAS-data?", :email-body "Vi använder också LIPAS-data", :email-subject "Vi använder också LIPAS-data", :headline "Några som använder LIPAS-data", :tell-us "Berättä om det för oss"}, :lipas.swimming-pool.facilities {:showers-men-count "Antalet duschar för män", :lockers-men-count "Antalet omklädningsskåp för män", :headline "Andra tjänster", :platforms-5m-count "Antalet 5 m hopplatser", :kiosk? "Kiosk / café", :hydro-neck-massage-spots-count "Antal av nackemassagepunkter", :lockers-unisex-count "Antalet unisex omklädningsskåp", :platforms-10m-count "Antalet 10 m hopplatser", :hydro-massage-spots-count "Antal av andra massagepunkter", :lockers-women-count "Antalet omklädningsskåp för kvinnor", :platforms-7.5m-count "Antalet 7.5 m hopplatser", :gym? "Gym", :showers-unisex-count "Antalet unisex duschar", :platforms-1m-count "Antalet 1 m hopplatser", :showers-women-count "Antalet duschar för kvinnor", :platforms-3m-count "Antalet 3 m hopplatser"}, :sauna-types {:infrared-sauna "Infraröd bastu", :other-sauna "Annan bastu", :sauna "Bastu", :steam-sauna "Ångbastu"}, :stats-metrics {:investments "Investeringar", :net-costs "Nettokostnader", :operating-expenses "Driftskostnader", :operating-incomes "Driftsintäkter", :subsidies "Understöd och bidrag från kommunen"}, :refrigerant-solutions {:CO2 "CO2", :H2ONH3 "H2O/NH3", :cacl "CaCl", :ethanol-water "Freezium", :ethylene-glycol "R134A", :freezium "Freezium", :water-glycol "R134A"}, :user {:headline "Mitt konto", :admin-page-link "Gå till adminsidan", :promo1-link "Visa gymnastiksaler som jag kan uppdatera", :swimming-pools-link "Simhallsportal", :promo-headline "Aktuellt", :front-page-link "Gå till framsidan", :promo1-text "Undervisnings- och kulturministeriet önskar att kommuner kompletterar information om byggnadsår och renoveringår om idrottsplatser inomhus. Informationen är viktig för utvärdering av renoveringsskuld i idrottsplatser.", :ice-stadiums-link "Ishallsportal", :greeting "Hej {1} {2} !", :promo1-topic "Tack för att du använder Lipas.fi!"}, :building-materials {:brick "Tegel", :concrete "Betong", :solid-rock "Häll", :steel "Stål", :wood "Trä"}, :stats {:disclaimer-headline "Datakälla" :general-disclaimer-1 "Lipas.fi idrottsanläggningar, friluftsleder och friluftsområden i Finland: Erkännande 4.0 Internationell (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/deed.sv" :general-disclaimer-2 "Du har tillstånd att dela, kopiera och vidaredistribuera materialet oavsett medium eller format, bearbeta, remixa, transformera, och bygg vidare på materialet, för alla ändamål, även kommersiellt. Du måste ge ett korrekt erkännande om du använder Lipas-data, till exempel “Idrottsplatser: Lipas.fi, Jyväskylä Universitet, datum/år”." :general-disclaimer-3 "Observera, att Lipas.fi data är uppdaterat av kommuner och andra ägare av idrottsplatser samt Lipas.fi administratörer i Jyväskylä Universitet. Omfattning, riktighet eller enhetlighet kan inte garanteras. I Lipas.fi statistik är material baserat på data i Lipas.fi databas. Återstående information kan påverka beräkningar." :finance-disclaimer "Ekonomiska uppgifter av kommuners idrotts- och ungdomsväsende: Statistikcentralen öppen data. Materialet har laddats ner från Statistikcentralens gränssnittstjänst 2001-2019 med licensen CC BY 4.0. Observera, att kommunerna ansvarar själva för att uppdatera sina ekonomiska uppgifter i Statistikcentralens databas. Enhetlighet och jämförbarhet mellan åren eller kommunerna kan inte garanteras." :description "Ekonomiska uppgifter om idrotts- och ungdomsväsende. Kommunen kan observera hur kostnader utvecklas över tid.", :filter-types "Välj typer", :length-km-sum "Idrottsrutters totalt längd ", :headline "Statistik", :select-years "Välj år", :browse-to "Gå till statistiken", :select-issuer "Välj understödare", :select-unit "Välj måttenhet", :bullet3 "Bidrag", :finance-stats "Ekonomiska uppgifter", :select-city "Välj kommun", :area-m2-min "Minimum idrottsareal m²", :filter-cities "Välj kommuner", :select-metrics "Välj storheter", :area-m2-count "Antal av platser med idrottsareal information", :show-ranking "Visa rankning", :age-structure-stats "Byggnadsår", :subsidies-count "Antal av bidrag", :area-m2-sum "Totalt idrottsareal m²", :select-metric "Välj storhet", :bullet2 "Statistiken om idrottsanläggningar", :area-m2-max "Maximum idrottsareal m²", :select-grouping "Gruppering", :select-city-service "Välj administratör", :region "Region", :show-comparison "Visa jämförelse", :length-km-avg "Medeltal av idrottsruttens längd", :sports-sites-count "Antal av idrottsanläggningar", :length-km-min "Minimum idrottsruttens längd", :country-avg "(medeltal för hela landet)", :length-km-count "Antal av idrottsrutter med längd information", :population "Folkmängd", :sports-stats "Idrottsanläggningar", :select-cities "Välj kommuner", :subsidies "Bidrag", :select-interval "Välj intervall", :bullet1 "Ekonomiska uppgifter om idrotts- och ungdomsväsende", :area-m2-avg "Medeltal av idrottsareal m²", :age-structure "Byggnadsår av idrottsanläggningar", :length-km-max "Maximum idrottsruttens längd", :total-amount-1000e "Totalt (1000 €)", :city-stats "Kommunstatistik"}, :pool-structures {:concrete "Betong", :hardened-plastic "Barnbassäng", :steel "Stål"}, :map {:retkikartta-checkbox-reminder "Välj också igen \"Kan visas i Retkikartta.fi - service\" i följande steg i ytterligare information.", :zoom-to-user "Zooma in till min position", :remove "Ta bort", :modify-polygon "Modifera området", :draw-polygon "Lägg till område", :retkikartta-problems-warning "Korrigera problem som är märkta på kartan för att visa i Retkikartta.fi.", :edit-later-hint "Du kan modifera geometrin också senare", :center-map-to-site "Fokusera kartan på platsen", :draw-hole "Lägg till hål", :split-linestring "Klippa ruttdel", :delete-vertices-hint "För att ta bort en punkt, tryck och håll alt-knappen och klicka på punkten", :calculate-route-length "Räkna ut längden", :remove-polygon "Ta bort område", :modify-linestring "Modifera rutten", :download-gpx "Ladda ner GPX", :add-to-map "Lägg till på karta", :bounding-box-filter "Sök i området", :remove-linestring "Ta bort ruttdel", :draw-geoms "Rita", :confirm-remove "Är du säker att du vill ta bort geometrin?", :draw "Lägg till på karta", :draw-linestring "Lägg till ruttdel", :modify "Du kan dra punkten på kartan", :zoom-to-site "Zooma in till sportplats", :kink "Korrigera så att ruttdelen inte korsar själv", :zoom-closer "Zooma in"}, :supporting-structures {:brick "Tegel", :concrete "Betong", :concrete-beam "Häll", :concrete-pillar "Stål", :solid-rock "Häll", :steel "Stål", :wood "Trä"}, :owner {:unknown "Ingen information", :municipal-consortium "Samkommun", :other "Annat", :company-ltd "Företag", :city "Kommun", :state "Stat", :registered-association "Registrerad förening", :foundation "Stiftelse", :city-main-owner "Företag med kommun som majoritetsägare"}, :menu {:frontpage "Framsidan", :headline "LIPAS", :jyu "Jyväskylä universitet", :main-menu "Huvudmeny"}, :dryer-types {:cooling-coil "timmar", :munters "månader", :none "timmar"}, :physical-units {:mm "mm", :hour "h", :m3 "m³", :m "m", :temperature-c "Temperatur °C", :l "l", :mwh "MWh", :m2 "m²", :celsius "°C"}, :lipas.swimming-pool.water-treatment {:filtering-methods "E-post", :headline "Kontaktuppgifter", :ozonation? "E-post", :uv-treatment? "Kontaktuppgifter"}, :statuses {:edited "{1} (redigerad)"}, :lipas.user {:email "E-post", :permissions "Rättigheter", :permissions-example "Rätt att uppdatera Jyväskylä ishallen.", :saved-searches "Sparad sök", :report-energy-and-visitors "Spara raportmodellen", :permission-to-cities "Du har rättighet att uppdatera de här kommunerna:", :password "Lösenord", :lastname "Efternamn", :save-report "Spara raportmodellen", :sports-sites "Egna platser", :permission-to-all-cities "Du har rättighet att uppdatera alla kommuner", :username "Användarnamn", :history "Historia", :saved-reports "Sparad raportmodeller", :contact-info "Kontaktuppgifter", :permission-to-all-types "Du har rättighet att uppdatera alla typer", :requested-permissions "Begärda rättigheter", :email-example "epost@exempel.fi", :permission-to-portal-sites "Du har rättighet att uppdatera de här platserna:", :permissions-help "Skriv vad du vill uppdatera i Lipas", :report-energy-consumption "Begärda rättigheter", :firstname "Förnamn", :save-search "Spara söket", :view-basic-info "Kolla ut grunddata", :no-permissions "Användarnamn till Lipas har inte ännu konfirmerats", :username-example "tane12", :permission-to-types "Du har rättighet att uppdatera de här typerna:"}, :heat-recovery-types {:thermal-wheel "Hjälp"}}, :en {:analysis {:headline "Analysis tool (beta)" :add-new "Add new" :distance "Distance" :travel-time "Travel time" :zones "Baskets" :zone "Basket" :schools "Schools" :daycare "Early childhood education" :elementary-school "Elementary school" :high-school "High school" :elementary-and-high-school "Elementary and high school" :special-school "Special education school" :direct "Beeline" :by-foot "By foot" :by-car "By car" :by-bicycle "By bicycle" :population "Population" :analysis-buffer "Analysis buffer" :filter-types "Filter by type" :settings "Settings" :settings-map "What's visible on map" :settings-zones "Distances and travel times" :settings-help "Note: analysis area will be determined by the maximum distance defined here. Travel times are not calculated outside the maximum distance."} :sport {:description "LIPAS is the national database of sport facilities and their conditions in Finland.", :headline "Sports Faclities", :open-interfaces "Open data and APIs", :up-to-date-information "Up-to-date information about sports facilities", :updating-tools "Tools for data maintainers"}, :confirm {:discard-changes? "Do you want to discard all changes?", :headline "Confirmation", :no "No", :press-again-to-delete "Press again to delete", :resurrect? "Are you sure you want to resurrect this sports facility?", :save-basic-data? "Do you want to save general information?", :yes "Yes"}, :lipas.swimming-pool.saunas {:accessible? "Accessible", :add-sauna "Add sauna", :edit-sauna "Edit sauna", :headline "Saunas", :men? "Men", :women? "Women"}, :slide-structures {:concrete "Concrete", :hardened-plastic "Hardened plastic", :steel "Steel"}, :lipas.swimming-pool.conditions {:open-days-in-year "Open days in year", :open-hours-mon "Mondays", :headline "Open hours", :open-hours-wed "Wednesdays", :open-hours-thu "Thursdays", :open-hours-fri "Fridays", :open-hours-tue "Tuesdays", :open-hours-sun "Sundays", :daily-open-hours "Daily open hours", :open-hours-sat "Saturdays"}, :lipas.ice-stadium.ventilation {:dryer-duty-type "Dryer duty type", :dryer-type "Dryer type", :headline "Ventilation", :heat-pump-type "Heat pump type", :heat-recovery-efficiency "Heat recovery efficiency", :heat-recovery-type "Heat recovery type"}, :swim {:description "Swimming pools portal contains data about indoor swimming pools energy consumption and related factors.", :latest-updates "Latest updates", :headline "Swimming pools", :basic-data-of-halls "General information about building and facilities", :updating-basic-data "Updating general information", :edit "Report consumption", :entering-energy-data "Reporing energy consumption", :list "Pools list", :visualizations "Comparison"}, :home-page {:description "LIPAS system has information on sport facilities, routes and recreational areas and economy. The content is open data under the CC4.0 International licence.", :headline "Front page"}, :ice-energy {:description "Up-to-date information can be found from Finhockey association web-site.", :energy-calculator "Ice stadium energy concumption calculator", :finhockey-link "Browse to Finhockey web-site", :headline "Energy Info"}, :filtering-methods {:activated-carbon "Activated carbon", :coal "Coal", :membrane-filtration "Membrane filtration", :multi-layer-filtering "Multi-layer filtering", :open-sand "Open sand", :other "Other", :precipitation "Precipitation", :pressure-sand "Pressure sand"}, :open-data {:description "Interface links and instructions", :headline "Open Data", :rest "REST", :wms-wfs "WMS & WFS"}, :lipas.swimming-pool.pool {:accessibility "Accessibility", :outdoor-pool? "Outdoor pool"}, :pool-types {:multipurpose-pool "Multi-purpose pool", :whirlpool-bath "Whirlpool bath", :main-pool "Main pool", :therapy-pool "Therapy pool", :fitness-pool "Fitness pool", :diving-pool "Diving pool", :childrens-pool "Childrens pool", :paddling-pool "Paddling pool", :cold-pool "Cold pool", :other-pool "Other pool", :teaching-pool "Teaching pool"}, :lipas.ice-stadium.envelope {:base-floor-structure "Base floor structure", :headline "Envelope structure", :insulated-ceiling? "Insulated ceiling", :insulated-exterior? "Insulated exterior", :low-emissivity-coating? "Low emissivity coating"}, :disclaimer {:headline "NOTICE!", :test-version "This is LIPAS TEST-ENVIRONMENT. Changes made here don't affect the production system."}, :admin {:private-foundation "Private / foundation", :city-other "City / other", :unknown "Unknown", :municipal-consortium "Municipal consortium", :private-company "Private / company", :private-association "Private / association", :other "Other", :city-technical-services "City / technical services", :city-sports "City / sports", :state "State", :city-education "City / education"}, :accessibility {:lift "Pool lift", :low-rise-stairs "Low rise stairs", :mobile-lift "Mobile pool lift", :slope "Slope"}, :general {:description "Description", :hall "Hall", :women "Women", :total-short "Total", :done "Done", :updated "Updated", :name "Name", :reported "Reported", :type "Type", :last-modified "Last modified", :here "here", :event "Event", :structure "Structure", :general-info "General information", :comment "Comment", :measures "Measures", :men "Men"}, :dryer-duty-types {:automatic "Automatic", :manual "Manual"}, :swim-energy {:description "Up-to-date information can be found from UKTY and SUH web-sites.", :headline "Energy info", :headline-short "Info", :suh-link "Browse to SUH web-site", :ukty-link "Browse to UKTY web-site"}, :time {:two-years-ago "2 years ago", :date "Date", :hour "Hour", :this-month "This month", :time "Time", :less-than-hour-ago "Less than an hour ago", :start "Started", :this-week "This week", :today "Today", :month "Month", :long-time-ago "Long time ago", :year "Year", :just-a-moment-ago "Just a moment ago", :yesterday "Yesterday", :three-years-ago "3 years ago", :end "Ended", :this-year "This year", :last-year "Last year"}, :ice-resurfacer-fuels {:LPG "LPG", :electicity "Electricity", :gasoline "Gasoline", :natural-gas "Natural gas", :propane "Propane"}, :ice-rinks {:headline "Venue details"}, :month {:sep "September", :jan "January", :jun "June", :oct "October", :jul "July", :apr "April", :feb "February", :nov "November", :may "May", :mar "March", :dec "December", :aug "August"}, :type {:name "Type", :main-category "Main category", :sub-category "Sub category", :type-code "Type code"}, :duration {:hour "hours", :month "months", :years "years", :years-short "y"}, :size-categories {:competition "Competition < 3000 persons", :large "Large > 3000 persons", :small "Small > 500 persons"}, :lipas.admin {:access-all-sites "You have admin permissions.", :confirm-magic-link "Are you sure you want to send magic link to {1}?", :headline "Admin", :magic-link "Magic Link", :select-magic-link-template "Select letter", :send-magic-link "Send magic link to {1}", :users "Users"}, :lipas.ice-stadium.refrigeration {:headline "Refrigeration", :refrigerant-solution-amount-l "Refrigerant solution amount (l)", :individual-metering? "Individual metering", :original? "Original", :refrigerant "Refrigerant", :refrigerant-solution "Refrigerant solution", :condensate-energy-main-targets "Condensate energy main target", :power-kw "Power (kW)", :condensate-energy-recycling? "Condensate energy recycling", :refrigerant-amount-kg "Refrigerant amount (kg)"}, :lipas.building {:headline "Building", :total-volume-m3 "Volume m³", :staff-count "Staff count", :piled? "Piled", :heat-sections? "Pool room is divided to heat sections?", :total-ice-area-m2 "Ice surface area m²", :main-construction-materials "Main construction materials", :main-designers "Main designers", :total-pool-room-area-m2 "Pool room area m²", :heat-source "Heat source", :total-surface-area-m2 "Area m²", :total-water-area-m2 "Water surface area m²", :ceiling-structures "Ceiling structures", :supporting-structures "Supporting structures", :seating-capacity "Seating capacity"}, :heat-pump-types {:air-source "Air source heat pump", :air-water-source "Air-water source heat pump", :exhaust-air-source "Exhaust air source heat pump", :ground-source "Ground source heat pump", :none "None"}, :search {:table-view "Table view", :headline "Search", :results-count "{1} results", :placeholder "Search...", :retkikartta-filter "Retkikartta.fi", :filters "Filters", :search-more "Search more...", :page-size "Page size", :search "Search", :permissions-filter "Show only sites that I can edit", :display-closest-first "Display nearest first", :list-view "List view", :pagination "Results {1}-{2}", :school-use-filter "Used by schools", :clear-filters "Clear filters"}, :map.tools {:drawing-tooltip "Draw tool selected", :drawing-hole-tooltip "Draw hole tool selected", :edit-tool "Edit tool", :importing-tooltip "Import tool selected", :deleting-tooltip "Delete tool selected", :splitting-tooltip "Split tool selected"}, :partners {:headline "In association with"}, :actions {:duplicate "Duplicate", :resurrect "Resurrect", :select-year "Select year", :select-owners "Select owners", :select-admins "Select administrators", :select-tool "Select tool", :save-draft "Save draft", :redo "Redo", :open-main-menu "Open main menu", :back-to-listing "Back to list view", :filter-surface-materials "Filter surface materials", :browse "Browse", :select-type "Select types", :edit "Edit", :filter-construction-year "Filter construction years", :submit "Submit", :choose-energy "Choose energy", :delete "Delete", :browse-to-map "Go to map view", :save "Save", :close "Close", :filter-area-m2 "Filter area m²", :show-account-menu "Open account menu", :fill-required-fields "Please fill all required fields", :undo "Undo", :browse-to-portal "Enter portal", :download-excel "Download Excel", :fill-data "Fill", :select-statuses "Status", :select-cities "Select cities", :select-hint "Select...", :discard "Discard", :more "More...", :cancel "Cancel", :select-columns "Select fields", :add "Add", :show-all-years "Show all years", :download "Download", :select-hall "Select hall", :clear-selections "Clear", :select "Select", :select-types "Select types"}, :dimensions {:area-m2 "Area m²", :depth-max-m "Depth max m", :depth-min-m "Depth min m", :length-m "Length m", :surface-area-m2 "Surface area m²", :volume-m3 "Volume m³", :width-m "Width m"}, :login {:headline "Login", :login-here "here", :login-with-password "Login with password", :password "Password", :logout "Log out", :username "Email / Username", :login-help "If you are already a LIPAS-user you can login using just your email address.", :login "Login", :magic-link-help "Order login link", :order-magic-link "Order login link", :login-with-magic-link "Login with email", :bad-credentials "Wrong username or password", :magic-link-ordered "Password", :username-example "paavo.paivittaja@kunta.fi", :forgot-password? "Forgot password?"}, :lipas.ice-stadium.conditions {:open-months "Open months in year", :headline "Conditions", :ice-resurfacer-fuel "Ice resurfacer fuel", :stand-temperature-c "Stand temperature (during match)", :ice-average-thickness-mm "Average ice thickness (mm)", :air-humidity-min "Air humidity % min", :daily-maintenances-weekends "Daily maintenances on weekends", :air-humidity-max "Air humidity % max", :daily-maintenances-week-days "Daily maintenances on weekdays", :maintenance-water-temperature-c "Maintenance water temperature", :ice-surface-temperature-c "Ice surface temperature", :weekly-maintenances "Weekly maintenances", :skating-area-temperature-c "Skating area temperature (at 1m height)", :daily-open-hours "Daily open hours", :average-water-consumption-l "Average water consumption (l) / maintenance"}, :map.demographics {:headline "Analysis tool", :tooltip "Analysis tool", :helper-text "Select sports facility on the map.", :copyright1 "Statistics of Finland 2019/2020", :copyright2 "1x1km and 250x250m population grids", :copyright3 "with license"}, :lipas.swimming-pool.slides {:add-slide "Add Slide", :edit-slide "Edit slide", :headline "Slides"}, :notifications {:get-failed "Couldn't get data.", :save-failed "Saving failed", :save-success "Saving succeeded" :ie "Internet Explorer is not a supported browser. Please use another web browser, e.g. Chrome, Firefox or Edge."}, :lipas.swimming-pool.energy-saving {:filter-rinse-water-heat-recovery? "Filter rinse water heat recovery?", :headline "Energy saving", :shower-water-heat-recovery? "Shower water heat recovery?"}, :ice-form {:headline "Report readings", :headline-short "Report readings", :select-rink "Select stadium"}, :restricted {:login-or-register "Please login or register"}, :lipas.ice-stadium.rinks {:add-rink "Add rink", :edit-rink "Edit rink", :headline "Rinks"}, :lipas.sports-site {:properties "Properties", :delete-tooltip "Delete sports facility...", :headline "sports faclities", :new-site-of-type "New {1}", :address "Address", :new-site "New Sports Facility", :phone-number "Phone number", :admin "Admin", :surface-materials "Surface materials", :www "Web-site", :name "Finnish name", :reservations-link "Reservations", :construction-year "Construction year", :type "Type", :delete "Delete {1}", :renovation-years "Renovation years", :name-localized-se "Swedish name", :status "Status", :id "LIPAS-ID", :details-in-portal "Click here to see details", :comment "More information", :ownership "Ownership", :name-short "Name", :basic-data "General", :delete-reason "Reason", :event-date "Modified", :email-public "Email (public)", :add-new "Add Sports Facility", :contact "Contact", :owner "Owner", :marketing-name "Marketing name"}, :status {:active "Active", :planned "Planned" :incorrect-data "Incorrect data", :out-of-service-permanently "Permanently out of service", :out-of-service-temporarily "Temporarily out of service"}, :register {:headline "Register", :link "Sign up here" :thank-you-for-registering "Thank you for registering! You wil receive an email once we've updated your permissions."}, :map.address-search {:title "Find address", :tooltip "Find address"}, :ice-comparison {:headline "Compare"}, :lipas.visitors {:headline "Visitors", :monthly-visitors-in-year "Monthly visitors in {1}", :not-reported "Visitors not reported", :not-reported-monthly "No monthly data", :spectators-count "Spectators count", :total-count "Visitors count"}, :lipas.energy-stats {:headline "Energy consumption in {1}", :energy-reported-for "Electricity, heat and water consumption reported for {1}", :report "Report consumption", :disclaimer "*Based on reported consumption in {1}", :reported "Reported {1}", :cold-mwh "Cold MWh", :hall-missing? "Is your data missing from the diagram?", :not-reported "Not reported {1}", :water-m3 "Water m³", :electricity-mwh "Electricity MWh", :heat-mwh "Heat MWh", :energy-mwh "Energy MWh"}, :map.basemap {:copyright "© National Land Survey", :maastokartta "Terrain", :ortokuva "Satellite", :taustakartta "Default"}, :map.overlay {:tooltip "Other layers" :mml-kiinteisto "Property boundaries" :light-traffic "Light traffic" :retkikartta-snowmobile-tracks "Metsähallitus snowmobile tracks"} :lipas.swimming-pool.pools {:add-pool "Add pool", :edit-pool "Edit pool", :headline "Pools", :structure "Structure"}, :condensate-energy-targets {:hall-heating "Hall heating", :maintenance-water-heating "Maintenance water heating", :other-space-heating "Other heating", :service-water-heating "Service water heating", :snow-melting "Snow melting", :track-heating "Track heating"}, :refrigerants {:CO2 "CO2", :R134A "R134A", :R22 "R22", :R404A "R404A", :R407A "R407A", :R407C "R407C", :R717 "R717"}, :harrastuspassi {:disclaimer "When the option “May be shown in Harrastuspassi.fi” is ticked, the information regarding the sport facility will be transferred automatically to the Harrastuspassi.fi. I agree to update in the Lipas service any changes to information regarding the sport facility. The site administrator is responsible for the accuracy of information and safety of the location. Facility information is shown in Harrastuspassi.fi only if the municipality has a contract with Harrastuspassi.fi service provider."} :retkikartta {:disclaimer "When the option “May be shown in Excursionmap.fi” is ticked, the information regarding the open air exercise location will be transferred once in every 24 hours automatically to the Excursionmap.fi service, maintained by Metsähallitus. I agree to update in the Lipas service any changes to information regarding an open air exercise location. The site administrator is responsible for the accuracy of information, safety of the location, responses to feedback and possible costs related to private roads."}, :reset-password {:change-password "Change password", :enter-new-password "Enter new password", :get-new-link "Get new reset link", :headline "Forgot password?", :helper-text "We will email password reset link to you.", :password-helper-text "Password must be at least 6 characters long", :reset-link-sent "Reset link sent! Please check your email!", :reset-success "Password has been reset! Please login with the new password."}, :reports {:contacts "Contacts", :download-as-excel "Download Excel", :select-fields "Select field", :selected-fields "Selected fields", :shortcuts "Shortcuts", :tooltip "Create Excel from search results"}, :heat-sources {:district-heating "District heating", :private-power-station "Private power station"}, :map.import {:headline "Import geometries", :geoJSON "Upload .json file containing FeatureCollection. Coordinates must be in WGS84 format.", :gpx "Coordinates must be in WGS84 format", :supported-formats "Supported formats are {1}", :replace-existing? "Replace existing geometries", :select-encoding "Select encoding", :tab-header "Import", :kml "Coordinates must be in WGS84 format", :shapefile "Import zip file containing .shp .dbf and .prj file.", :import-selected "Import selected", :tooltip "Import from file", :unknown-format "Unkonwn format '{1}'"}, :error {:email-conflict "Email is already in use", :email-not-found "Email address is not registered", :invalid-form "Fix fields marked with red", :no-data "No data", :reset-token-expired "Password reset failed. Link has expired.", :unknown "Unknown error occurred. :/", :user-not-found "User not found.", :username-conflict "Username is already in use"}, :reminders {:description "We will email the message to you at the selected time", :after-one-month "After one month", :placeholder "Remember to check sports-facility \"{1}\" {2}", :select-date "Select date", :tomorrow "Tomorrow", :title "Add reminder", :after-six-months "After six months", :in-a-year "In a year", :message "Message", :in-a-week "In a week"}, :units {:days-in-year "days a year", :hours-per-day "hours a day", :pcs "pcs", :percent "%", :person "person", :times-per-day "times a day", :times-per-week "times a wekk"}, :lipas.energy-consumption {:contains-other-buildings? "Readings contain also other buildings or spaces", :headline "Energy consumption", :yearly "Yearly", :report "Report readings", :electricity "Electricity MWh", :headline-year "Energy consumption in {1}", :monthly? "I want to report monthly energy consumption", :reported-for-year "Energy consumption reported for {1}", :monthly "Monthly", :operating-hours "Operating hours", :not-reported "Energy consumption not reported", :not-reported-monthly "No monthly data available", :heat "Heat (acquired) MWh", :cold "Cold energy (acquired) MWh", :comment "Comment", :water "Water m³", :monthly-readings-in-year "Monthly energy consumption in {1}"}, :ice {:description "Ice stadiums portal contains data about ice stadiums energy consumption and related factors.", :large "Grand hall > 3000 persons", :competition "Competition hall < 3000 persons", :headline "Ice stadiums", :video "Video", :comparison "Compare venues", :size-category "Size category", :basic-data-of-halls "General information about building and facilities", :updating-basic-data "Updating general information", :entering-energy-data "Reporing energy consumption", :small "Small competition hall > 500 persons", :watch "Watch", :video-description "Pihjalalinna Areena - An Energy Efficient Ice Stadium"}, :lipas.location {:address "Address", :city "City", :city-code "City code", :headline "Location", :neighborhood "Neighborhood", :postal-code "Postal code", :postal-office "Postal office"}, :lipas.user.permissions {:admin? "Admin", :all-cities? "Permission to all cities", :all-types? "Permission to all types", :cities "Access to sports faclities in cities", :sports-sites "Access to sports faclities", :types "Access to sports faclities of type"}, :help {:headline "Help", :permissions-help "Please contact us in case you need more permissions", :permissions-help-body "I need permissions to following sports facilities:", :permissions-help-subject "I need more permissions"}, :ceiling-structures {:concrete "Concrete", :double-t-beam "Double-T", :glass "Glass", :hollow-core-slab "Hollow-core slab", :solid-rock "Solid rock", :steel "Steel", :wood "Wood"}, :data-users {:data-user? "Do you use LIPAS-data?", :email-body "Tell us", :email-subject "We also use LIPAS-data", :headline "Data users", :tell-us "Tell us"}, :lipas.swimming-pool.facilities {:showers-men-count "Mens showers count", :lockers-men-count "Mens lockers count", :headline "Other services", :platforms-5m-count "5 m platforms count", :kiosk? "Kiosk / cafeteria", :hydro-neck-massage-spots-count "Neck hydro massage spots count", :lockers-unisex-count "Unisex lockers count", :platforms-10m-count "10 m platforms count", :hydro-massage-spots-count "Other hydro massage spots count", :lockers-women-count "Womens lockers count", :platforms-7.5m-count "7.5 m platforms count", :gym? "Gym", :showers-unisex-count "Unisex showers count", :platforms-1m-count "1 m platforms count", :showers-women-count "Womens showers count", :platforms-3m-count "3 m platforms count"}, :sauna-types {:infrared-sauna "Infrared sauna", :other-sauna "Other sauna", :sauna "Sauna", :steam-sauna "Steam sauna"}, :stats-metrics {:investments "Investments", :net-costs "Net costs", :operating-expenses "Operating expenses", :operating-incomes "Operating incomes", :subsidies "Granted subsidies"}, :refrigerant-solutions {:CO2 "CO2", :H2ONH3 "H2O/NH3", :cacl "CaCl", :ethanol-water "Ethanol-water", :ethylene-glycol "Ethylene glycol", :freezium "Freezium", :water-glycol "Water-glycol"}, :user {:admin-page-link "Admin page", :front-page-link "front page", :greeting "Hello {1} {2}!", :headline "Profile", :ice-stadiums-link "Ice stadiums", :promo-headline "Important", :promo1-text "Swimming pools", :swimming-pools-link "Swimming pools"}, :building-materials {:brick "Brick", :concrete "Concrete", :solid-rock "Solid rock", :steel "Steel", :wood "Wood"}, :stats {:disclaimer-headline "Data sources" :general-disclaimer-1 "Lipas.fi Finland’s sport venues and places, outdoor routes and recreational areas data is open data under license: Attribution 4.0 International (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/deed.en." :general-disclaimer-2 "You are free to use, adapt and share Lipas.fi data in any way, as long as the source is mentioned (Lipas.fi data, University of Jyväskylä, date/year of data upload or relevant information)." :general-disclaimer-3 "Note, that Lipas.fi data is updated by municipalities, other owners of sport facilities and Lipas.fi administrators at the University of Jyväskylä, Finland. Data accuracy, uniformity or comparability between municipalities is not guaranteed. In the Lipas.fi statistics, all material is based on the data in Lipas database and possible missing information may affect the results." :finance-disclaimer "Data on finances of sport and youth sector in municipalities: Statistics Finland open data. The material was downloaded from Statistics Finland's interface service in 2001-2019 with the license CC BY 4.0. Notice, that municipalities are responsible for updating financial information to Statistics Finland’s database. Data uniformity and data comparability between years or between municipalities is not guaranteed." :description "Statistics of sports facilities and related municipality finances", :filter-types "Filter types", :length-km-sum "Total route length km", :headline "Statistics", :select-years "Select years", :browse-to "Go to statistics", :select-issuer "Select issuer", :select-unit "Select unit", :bullet3 "Subsidies", :finance-stats "Finances", :select-city "Select city", :area-m2-min "Min area m²", :filter-cities "Filter cities", :select-metrics "Select metrics", :area-m2-count "Area m² reported count", :show-ranking "Show ranking", :age-structure-stats "Construction years", :subsidies-count "Subsidies count", :area-m2-sum "Total area m²", :select-metric "Select metric", :bullet2 "Sports facility statistics", :area-m2-max "Max area m²", :select-grouping "Grouping", :select-city-service "Select city service", :region "Region", :show-comparison "Show comparison", :length-km-avg "Average route length km", :sports-sites-count "Total count", :length-km-min "Min route length km", :country-avg "(country average)", :length-km-count "Route length reported count", :population "Population", :sports-stats "Sports faclities", :select-cities "Select cities", :subsidies "Subsidies", :select-interval "Select interval", :bullet1 "Economic Figures of Sport and Youth sector", :area-m2-avg "Average area m²", :age-structure "Construction years", :length-km-max "Max route length km", :total-amount-1000e "Total amount (€1000)", :city-stats "City statistics"}, :pool-structures {:concrete "Concrete", :hardened-plastic "Hardened plastic", :steel "Steel"}, :map {:retkikartta-checkbox-reminder "Remember to tick \"May be shown in ExcursionMap.fi\" later in sports facility properties.", :zoom-to-user "Zoom to my location", :remove "Remove", :modify-polygon "Modify area", :draw-polygon "Add area", :retkikartta-problems-warning "Please fix problems displayed on the map in case this route should be visible also in Retkikartta.fi", :edit-later-hint "You can modify geometries later", :center-map-to-site "Center map to sports-facility", :draw-hole "Add hole", :split-linestring "Split", :delete-vertices-hint "Vertices can be deleted by pressing alt-key and clicking.", :calculate-route-length "Calculate route length", :remove-polygon "Remove area", :modify-linestring "Modify route", :download-gpx "Download GPX", :add-to-map "Add to map", :bounding-box-filter "Search from map area", :remove-linestring "Remove route", :draw-geoms "Draw", :confirm-remove "Are you sure you want to delete selected geometry?", :draw "Draw", :draw-linestring "Add route", :modify "You can move the point on the map", :zoom-to-site "Zoom map to sports facility's location", :kink "Self intersection. Please fix either by re-routing or splitting the segment.", :zoom-closer "Please zoom closer"}, :supporting-structures {:brick "Brick", :concrete "Concrete", :concrete-beam "Concrete beam", :concrete-pillar "Concrete pillar", :solid-rock "Solid rock", :steel "Steel", :wood "Wood"}, :owner {:unknown "Unknown", :municipal-consortium "Municipal consortium", :other "Other", :company-ltd "Company ltd", :city "City", :state "State", :registered-association "Registered association", :foundation "Foundation", :city-main-owner "City main owner"}, :menu {:frontpage "Home", :headline "LIPAS", :jyu "University of Jyväskylä", :main-menu "Main menu"}, :dryer-types {:cooling-coil "Cooling coil", :munters "Munters", :none "None"}, :physical-units {:mm "mm", :hour "h", :m3 "m³", :m "m", :temperature-c "Temperature °C", :l "l", :mwh "MWh", :m2 "m²", :celsius "°C"}, :lipas.swimming-pool.water-treatment {:activated-carbon? "Activated carbon", :filtering-methods "Filtering methods", :headline "Water treatment", :ozonation? "Ozonation", :uv-treatment? "UV-treatment"}, :statuses {:edited "{1} (edited)"}, :lipas.user {:email "Email", :permissions "Permissions", :permissions-example "Access to update Jyväskylä ice stadiums.", :saved-searches "Saved searches", :report-energy-and-visitors "Report visitors and energy consumption", :permission-to-cities "You have permission to following cities:", :password "Password", :lastname "Last name", :save-report "Save template", :sports-sites "My sites", :permission-to-all-cities "You have permission to all cities", :username "Username", :history "History", :saved-reports "Saved templates", :contact-info "Contact info", :permission-to-all-types "You have permission to all types", :requested-permissions "Requested permissions", :email-example "email@example.com", :permission-to-portal-sites "You have permission to following sports facilities:", :permissions-help "Describe what permissions you wish to have", :report-energy-consumption "Report energy consumption", :firstname "First name", :save-search "Save search", :view-basic-info "View basic info", :no-permissions "You don't have permission to publish changes to any sites.", :username-example "tane12", :permission-to-types "You have permission to following types:"}, :heat-recovery-types {:liquid-circulation "Liquid circulation", :plate-heat-exchanger "Plate heat exchanger", :thermal-wheel "Thermal wheel"}}})
5463
(ns lipas.i18n.generated) ;; From csv ;; (def dicts {:fi {:analysis {:headline "Analyysityökalu (beta)" :description "Analyysityökalulla voi arvioida liikuntaolosuhteiden tarjontaa ja saavutettavuutta vertailemalla liikuntapaikan etäisyyttä ja matkustusaikoja suhteessa muihin liikuntapaikkoihin, väestöön sekä oppilaitoksiin." :description2 "Väestöaineistona käytetään Tilastokeskuksen 250x250m ja 1x1km ruutuaineistoja, joista selviää kussakin ruudussa olevan väestön jakauma kolmessa ikäryhmässä (0-14, 15-65, 65-)." :description3 "Matka-aikojen laskeminen eri kulkutavoilla (kävellen, polkupyörällä, autolla) perustuu avoimeen OpenStreetMap-aineistoon ja OSRM-työkaluun." :description4 "Oppilaitosten nimi- ja sijaintitiedot perustuvat Tilastokeskuksen avoimeen aineistoon. Varhaiskasvatusyksiköiden nimi- ja sijaintitiedoissa käytetään LIKES:n keräämää ja luovuttamaa aineistoa." :add-new "Lisää uusi" :distance "Etäisyys" :travel-time "Matka-aika" :zones "Korit" :zone "Kori" :schools "Koulut" :daycare "Varhaiskasvatusyksikkö" :elementary-school "Peruskoulu" :high-school "Lukio" :elementary-and-high-school "Perus- ja lukioasteen koulu" :special-school "Erityiskoulu" :population "Väestö" :direct "Linnuntietä" :by-foot "Kävellen" :by-car "Autolla" :by-bicycle "Polkupyörällä" :analysis-buffer "Analyysialue" :filter-types "Suodata tyypin mukaan" :settings "Asetukset" :settings-map "Kartalla näkyvät kohteet" :settings-zones "Etäisyydet ja matka-ajat" :settings-help "Analyysialue määräytyy suurimman etäisyyskorin mukaan. Myöskään matka-aikoja ei lasketa tämän alueen ulkopuolelta."} :sport {:description "LIPAS tarjoaa ajantasaisen tiedon Suomen julkisista liikuntapaikoista ja virkistyskohteista avoimessa tietokannassa.", :headline "Liikuntapaikat", :open-interfaces "Avoimet rajapinnat", :up-to-date-information "Ajantasainen tieto Suomen liikuntapaikoista", :updating-tools "Päivitystyökalut tiedontuottajille"}, :confirm {:discard-changes? "Tahdotko kumota tekemäsi muutokset?", :headline "Varmistus", :no "Ei", :press-again-to-delete "Varmista painamalla uudestaan", :resurrect? "Tahdotko palauttaa liikuntapaikan aktiiviseksi?", :save-basic-data? "Haluatko tallentaa perustiedot?", :yes "Kyllä"}, :lipas.swimming-pool.saunas {:accessible? "Esteetön", :add-sauna "Lisää sauna", :edit-sauna "Muokkaa saunaa", :headline "Saunat", :men? "Miehet", :women? "Naiset"}, :slide-structures {:concrete "Betoni", :hardened-plastic "Lujitemuovi", :steel "Teräs"}, :lipas.swimming-pool.conditions {:open-days-in-year "Aukiolopäivät vuodessa", :open-hours-mon "Maanantaisin", :headline "Aukiolo", :open-hours-wed "Keskiviikkoisin", :open-hours-thu "Torstaisin", :open-hours-fri "Perjantaisin", :open-hours-tue "Tiistaisin", :open-hours-sun "Sunnuntaisin", :daily-open-hours "Aukiolotunnit päivässä", :open-hours-sat "Lauantaisin"}, :lipas.ice-stadium.ventilation {:dryer-duty-type "Ilmankuivauksen käyttötapa", :dryer-type "Ilmankuivaustapa", :headline "Hallin ilmanvaihto", :heat-pump-type "Lämpöpumpputyyppi", :heat-recovery-efficiency "Lämmöntalteenoton hyötysuhde %", :heat-recovery-type "Lämmöntalteenoton tyyppi"}, :swim {:description "Uimahalliportaali sisältää hallien perus- ja energiankulutustietoja sekä ohjeita energiatehokkuuden parantamiseen.", :latest-updates "Viimeksi päivitetyt tiedot", :headline "Uimahalli​portaali", :basic-data-of-halls "Uimahallien perustiedot", :updating-basic-data "Perustietojen päivitys", :edit "Uimahalli​portaali", :entering-energy-data "Energiankulutustietojen syöttäminen", :list "Hallien tiedot", :visualizations "Hallien vertailu"}, :home-page {:description "Etusivu", :headline "Etusivu"}, :ice-energy {:description "Ajantasaisen tietopaketin löydät Jääkiekkoliiton sivuilta.", :energy-calculator "Jäähallin energialaskuri", :finhockey-link "Siirry Jääkiekkoliiton sivuille", :headline "Energia​info"}, :filtering-methods {:activated-carbon "Aktiivihiili", :coal "Hiili", :membrane-filtration "Kalvosuodatus", :multi-layer-filtering "Monikerrossuodatus", :open-sand "Avohiekka", :other "Muu", :precipitation "Saostus", :pressure-sand "Painehiekka"}, :open-data {:description "Linkit ja ohjeet rajapintojen käyttöön.", :headline "Avoin data", :rest "REST", :wms-wfs "WMS & WFS"}, :lipas.swimming-pool.pool {:accessibility "Saavutettavuus", :outdoor-pool? "Ulkoallas"}, :pool-types {:multipurpose-pool "Monitoimiallas", :whirlpool-bath "Poreallas", :main-pool "Pääallas", :therapy-pool "Terapia-allas", :fitness-pool "Kuntouintiallas", :diving-pool "Hyppyallas", :childrens-pool "Lastenallas", :paddling-pool "Kahluuallas", :cold-pool "Kylmäallas", :other-pool "Muu allas", :teaching-pool "Opetusallas"}, :lipas.ice-stadium.envelope {:base-floor-structure "Alapohjan laatan rakenne", :headline "Vaipan rakenne", :insulated-ceiling? "Yläpohja lämpöeristetty", :insulated-exterior? "Ulkoseinä lämpöeristetty", :low-emissivity-coating? "Yläpohjassa matalaemissiiviteettipinnoite (heijastus/säteily)"}, :disclaimer {:headline "HUOMIO!", :test-version "Tämä on LIPAS-sovelluksen testiversio ja tarkoitettu koekäyttöön. Muutokset eivät tallennu oikeaan Lipakseen."}, :admin {:private-foundation "Yksityinen / säätiö", :city-other "Kunta / muu", :unknown "Ei tietoa", :municipal-consortium "Kuntayhtymä", :private-company "Yksityinen / yritys", :private-association "Yksityinen / yhdistys", :other "Muu", :city-technical-services "Kunta / tekninen toimi", :city-sports "Kunta / liikuntatoimi", :state "Valtio", :city-education "Kunta / opetustoimi"}, :accessibility {:lift "Allasnostin", :low-rise-stairs "Loivat portaat", :mobile-lift "Siirrettävä allasnostin", :slope "Luiska"}, :general {:description "Kuvaus", :hall "Halli", :women "Naiset", :total-short "Yht.", :done "Valmis", :updated "Päivitetty", :name "<NAME>", :reported "Ilmoitettu", :type "Tyyppi", :last-modified "Muokattu viimeksi", :here "tästä", :event "Tapahtuma", :structure "Rakenne", :general-info "Yleiset tiedot", :comment "Kommentti", :measures "Mitat", :men "Miehet"}, :dryer-duty-types {:automatic "Automaattinen", :manual "Manuaali"}, :swim-energy {:description "Ajantasaisen tietopaketin löydät UKTY:n ja SUH:n sivuilta.", :headline "Energia​info", :headline-short "Info", :suh-link "Siirry SUH:n sivuille", :ukty-link "Siirry UKTY:n sivuille"}, :time {:two-years-ago "2 vuotta sitten", :date "Päivämäärä", :hour "Tunti", :this-month "Tässä kuussa", :time "Aika", :less-than-hour-ago "Alle tunti sitten", :start "Alkoi", :this-week "Tällä viikolla", :today "Tänään", :month "Kuukausi", :long-time-ago "Kauan sitten", :year "Vuosi", :just-a-moment-ago "Hetki sitten", :yesterday "Eilen", :three-years-ago "3 vuotta sitten", :end "Päättyi", :this-year "Tänä vuonna", :last-year "Viime vuonna"}, :ice-resurfacer-fuels {:LPG "Nestekaasu", :electicity "Sähkö", :gasoline "Bensiini", :natural-gas "Maakaasu", :propane "Propaani"}, :ice-rinks {:headline "Hallien tiedot"}, :month {:sep "Syyskuu", :jan "Tammikuu", :jun "Kesäkuu", :oct "Lokakuu", :jul "Heinäkuu", :apr "Huhtikuu", :feb "Helmikuu", :nov "Marraskuu", :may "Toukokuu", :mar "Maaliskuu", :dec "Joulukuu", :aug "Elokuu"}, :type {:name "Liikuntapaikkatyyppi", :main-category "Pääryhmä", :sub-category "Alaryhmä", :type-code "Tyyppikoodi"}, :duration {:hour "tuntia", :month "kuukautta", :years "vuotta", :years-short "v"}, :size-categories {:competition "Kilpahalli < 3000 hlö", :large "Suurhalli > 3000 hlö", :small "Pieni kilpahalli > 500 hlö"}, :lipas.admin {:access-all-sites "Sinulla on pääkäyttäjän oikeudet. Voit muokata kaikkia liikuntapaikkoja.", :confirm-magic-link "Haluatko varmasti lähettää taikalinkin käyttäjälle {1}?", :headline "Admin", :magic-link "Taikalinkki", :select-magic-link-template "Valitse saatekirje", :send-magic-link "Taikalinkki käyttäjälle {1}", :users "Käyttäjät"}, :lipas.ice-stadium.refrigeration {:headline "Kylmätekniikka", :refrigerant-solution-amount-l "Rataliuoksen määrä (l)", :individual-metering? "Alamittaroitu", :original? "Alkuperäinen", :refrigerant "Kylmäaine", :refrigerant-solution "Rataliuos", :condensate-energy-main-targets "Lauhdelämmön pääkäyttökohde", :power-kw "Kylmäkoneen sähköteho (kW)", :condensate-energy-recycling? "Lauhde-energia hyötykäytetty", :refrigerant-amount-kg "Kylmäaineen määrä (kg)"}, :lipas.building {:headline "Rakennus", :total-volume-m3 "Bruttotilavuus m³", :staff-count "Henkilökunnan lukumäärä", :piled? "Paalutettu", :heat-sections? "Allastila on jaettu lämpötilaosioihin", :total-ice-area-m2 "Jääpinta-ala m²", :main-construction-materials "Päärakennusmateriaalit", :main-designers "Pääsuunnittelijat", :total-pool-room-area-m2 "Allashuoneen pinta-ala m²", :heat-source "Lämmönlähde", :total-surface-area-m2 "Bruttopinta-ala m² (kokonaisala)", :total-water-area-m2 "Vesipinta-ala m²", :ceiling-structures "Yläpohjan rakenteet", :supporting-structures "Kantavat rakenteet", :seating-capacity "Katsomokapasiteetti"}, :heat-pump-types {:air-source "Ilmalämpöpumppu", :air-water-source "Ilma-vesilämpöpumppu", :exhaust-air-source "Poistoilmalämpöpumppu", :ground-source "Maalämpöpumppu", :none "Ei lämpöpumppua"}, :search {:table-view "Näytä hakutulokset taulukossa", :headline "Haku", :results-count "{1} hakutulosta", :placeholder "Etsi...", :retkikartta-filter "Retkikartta.fi-kohteet", :harrastuspassi-filter "Harrastuspassi.fi-kohteet", :filters "Rajaa hakua", :search-more "Hae lisää...", :page-size "Näytä kerralla", :search "Hae", :permissions-filter "Näytä kohteet joita voin muokata", :display-closest-first "Näytä lähimmät kohteet ensin", :list-view "Näytä hakutulokset listana", :pagination "Tulokset {1}-{2}", :school-use-filter "Koulujen liikuntapaikat", :clear-filters "Poista rajaukset"}, :map.tools {:drawing-tooltip "Piirtotyökalu valittu", :drawing-hole-tooltip "Reikäpiirtotyökalu valittu", :edit-tool "Muokkaustyökalu", :importing-tooltip "Tuontityökalu valittu", :deleting-tooltip "Poistotyökalu valittu", :splitting-tooltip "Katkaisutyökalu valittu"}, :partners {:headline "Kehittä​misessä mukana"}, :actions {:duplicate "Kopioi", :resurrect "Palauta", :select-year "Valitse vuosi", :select-owners "Valitse omistajat", :select-admins "Valitse ylläpitäjät", :select-tool "Valitse työkalu", :save-draft "Tallenna luonnos", :redo "Tee uudelleen", :open-main-menu "Avaa päävalikko", :back-to-listing "Takaisin listaukseen", :filter-surface-materials "Rajaa pintamateriaalit", :browse "siirry", :select-type "Valitse tyyppi", :edit "Muokkaa", :filter-construction-year "Rajaa rakennusvuodet", :submit "Lähetä", :choose-energy "Valitse energia", :delete "Poista", :browse-to-map "Siirry kartalle", :save "Tallenna", :close "Sulje", :filter-area-m2 "Rajaa liikuntapinta-ala m²", :show-account-menu "Avaa käyttäjävalikko", :fill-required-fields "Täytä pakolliset kentät", :undo "Kumoa", :browse-to-portal "Siirry portaaliin", :download-excel "Lataa Excel", :fill-data "Täytä tiedot", :select-statuses "Liikuntapaikan tila", :select-cities "Valitse kunnat", :select-hint "Valitse...", :discard "Kumoa", :more "Lisää...", :cancel "Peruuta", :select-columns "Valitse tietokentät", :add "Lisää", :show-all-years "Näytä kaikki vuodet", :download "Lataa", :select-hall "Valitse halli", :clear-selections "Poista valinnat", :select "Valitse", :select-types "Valitse tyypit"}, :dimensions {:area-m2 "Pinta-ala m²", :depth-max-m "Syvyys max m", :depth-min-m "Syvyys min m", :length-m "Pituus m", :surface-area-m2 "Pinta-ala m²", :volume-m3 "Tilavuus m³", :width-m "Leveys m"}, :login {:headline "Kirjaudu", :login-here "täältä", :login-with-password "Kirjaudu salasanalla", :password "<PASSWORD>", :logout "Kirjaudu ulos", :username "Sähköposti / <PASSWORD>", :login-help "Jos olet jo LIPAS-käyttäjä, voit tilata suoran sisäänkirjautumislinkin sähköpostiisi", :login "Kirjaudu", :magic-link-help "Jos olet jo LIPAS-käyttäjä, voit tilata suoran sisäänkirjautumislinkin sähköpostiisi. Linkkiä käyttämällä sinun ei tarvitse muistaa salasanaasi.", :order-magic-link "Lähetä linkki sähköpostiini", :login-with-magic-link "Kirjaudu sähköpostilla", :bad-credentials "Käyttäjätunnus tai salasana ei kelpaa", :magic-link-ordered "Linkki on lähetetty ja sen pitäisi saapua sähköpostiisi parin minuutin sisällä. Tarkistathan myös roskapostin!", :username-example "<EMAIL>", :forgot-password? "<PASSWORD>?"}, :lipas.ice-stadium.conditions {:open-months "Aukiolokuukaudet vuodessa", :headline "Käyttöolosuhteet", :ice-resurfacer-fuel "Jäänhoitokoneen polttoaine", :stand-temperature-c "Katsomon tavoiteltu keskilämpötila ottelun aikana", :ice-average-thickness-mm "Jään keskipaksuus mm", :air-humidity-min "Ilman suhteellinen kosteus % min", :daily-maintenances-weekends "Jäähoitokerrat viikonlppuina", :air-humidity-max "Ilman suhteellinen kosteus % max", :daily-maintenances-week-days "Jäähoitokerrat arkipäivinä", :maintenance-water-temperature-c "Jäähoitoveden lämpötila (tavoite +40)", :ice-surface-temperature-c "Jään pinnan lämpötila", :weekly-maintenances "Jäänhoitokerrat viikossa", :skating-area-temperature-c "Luistelualueen lämpötila 1 m korkeudella", :daily-open-hours "Käyttötunnit päivässä", :average-water-consumption-l "Keskimääräinen jäänhoitoon käytetty veden määrä (per ajo)"}, :map.demographics {:headline "Analyysityökalu", :tooltip "Analyysityökalu", :helper-text "Valitse liikuntapaikka kartalta tai lisää uusi analysoitava kohde ", :copyright1 "Väestötiedoissa käytetään Tilastokeskuksen vuoden 2019", :copyright2 "1x1 km ruutuaineistoa", :copyright3 "lisenssillä" :copyright4 ", sekä vuoden 2020 250x250m ruutuaineistoa suljetulla lisenssillä."}, :lipas.swimming-pool.slides {:add-slide "Lisää liukumäki", :edit-slide "Muokkaa liukumäkeä", :headline "Liukumäet"}, :notifications {:get-failed "Tietojen hakeminen epäonnistui.", :save-failed "Tallennus epäonnistui", :save-success "Tallennus onnistui" :ie (str "Internet Explorer ei ole tuettu selain. " "Suosittelemme käyttämään toista selainta, " "esim. Chrome, Firefox tai Edge.")}, :lipas.swimming-pool.energy-saving {:filter-rinse-water-heat-recovery? "Suodattimien huuhteluveden lämmöntalteenotto", :headline "Energian​säästö​toimet", :shower-water-heat-recovery? "Suihkuveden lämmöntalteenotto"}, :ice-form {:headline "Nestekaasu", :headline-short "Sähkö", :select-rink "Nestekaasu"}, :restricted {:login-or-register "Kirjaudu sisään tai rekisteröidy"}, :lipas.ice-stadium.rinks {:add-rink "Lisää rata", :edit-rink "Muokkaa rataa", :headline "Radat"}, :lipas.sports-site {:properties "Lisätiedot", :delete-tooltip "Poista liikuntapaikka...", :headline "Liikuntapaikka", :new-site-of-type "Uusi {1}", :address "Osoite", :new-site "Uusi liikuntapaikka", :phone-number "Puhelinnumero", :admin "Ylläpitäjä", :surface-materials "Pintamateriaalit", :www "Web-sivu", :name "Nimi suomeksi", :reservations-link "Tilavaraukset", :construction-year "Rakennus​vuosi", :type "Tyyppi", :delete "Poista {1}", :renovation-years "Perus​korjaus​vuodet", :name-localized-se "Nimi ruotsiksi", :status "Liikuntapaikan tila", :id "LIPAS-ID", :details-in-portal "Näytä kaikki lisätiedot", :comment "Lisätieto", :ownership "Omistus", :name-short "Nimi", :basic-data "Perustiedot", :delete-reason "Poiston syy", :event-date "Muokattu", :email-public "Sähköposti (julkinen)", :add-new "Lisää liikuntapaikka", :contact "Yhteystiedot", :owner "Omistaja", :marketing-name "<NAME>"}, :status {:active "Toiminnassa", :planned "Suunniteltu" :incorrect-data "Väärä tieto", :out-of-service-permanently "Poistettu käytöstä pysyvästi", :out-of-service-temporarily "Poistettu käytöstä väliaikaisesti"}, :register {:headline "Rekisteröidy", :link "Rekisteröidy" :thank-you-for-registering "Kiitos rekisteröitymisestä! Saat sähköpostiisi viestin kun sinulle on myönnetty käyttöoikeudet."}, :map.address-search {:title "Etsi osoite", :tooltip "Etsi osoite"}, :ice-comparison {:headline "Hallien vertailu"}, :lipas.visitors {:headline "Kävijämäärät", :monthly-visitors-in-year "Kuukausittaiset kävijämäärät vuonna {1}", :not-reported "Ei kävijämäärätietoja", :not-reported-monthly "Ei kuukausitason tietoja", :spectators-count "Katsojamäärä", :total-count "Käyttäjämäärä"}, :lipas.energy-stats {:headline "Hallien energiankulutus vuonna {1}", :energy-reported-for "Sähkön-, lämmön- ja vedenkulutus ilmoitettu vuodelta {1}", :report "Ilmoita lukemat", :disclaimer "*Perustuu ilmoitettuihin kulutuksiin vuonna {1}", :reported "Ilmoitettu {1}", :cold-mwh "Kylmä MWh", :hall-missing? "Puuttuvatko hallisi tiedot kuvasta?", :not-reported "Ei tietoa {1}", :water-m3 "Vesi m³", :electricity-mwh "Sähkö MWh", :heat-mwh "Lämpö MWh", :energy-mwh "Sähkö + lämpö MWh"}, :map.basemap {:copyright "© Maanmittauslaitos", :maastokartta "Maastokartta", :ortokuva "Ilmakuva", :taustakartta "Taustakartta"}, :map.overlay {:tooltip "Muut karttatasot" :mml-kiinteisto "Kiinteistörajat" :light-traffic "Kevyen liikenteen väylät" :retkikartta-snowmobile-tracks "Metsähallituksen moottorikelkkaurat"} :lipas.swimming-pool.pools {:add-pool "Lisää allas", :edit-pool "Muokkaa allasta", :headline "Altaat", :structure "Rakenne"}, :condensate-energy-targets {:hall-heating "Hallin lämmitys", :maintenance-water-heating "Jäänhoitoveden lämmitys", :other-space-heating "Muun tilan lämmitys", :service-water-heating "Käyttöveden lämmitys", :snow-melting "Lumensulatus", :track-heating "Ratapohjan lämmitys"}, :refrigerants {:CO2 "CO2 (hiilidioksidi)", :R134A "R134A", :R22 "R22", :R404A "R404A", :R407A "R407A", :R407C "R407C", :R717 "R717"}, :harrastuspassi {:disclaimer "Kun ”saa julkaista Harrastuspassissa” – ruutu on rastitettu, liikuntapaikan tiedot siirretään automaattisesti Harrastuspassi-palveluun. Sitoudun päivittämään liikuntapaikan tietojen muutokset viipymättä Lippaaseen. Paikan hallinnoijalla on vastuu tietojen oikeellisuudesta ja paikan turvallisuudesta. Tiedot näkyvät Harrastuspassissa vain, mikäli kunnalla on sopimus Harrastuspassin käytöstä Harrastuspassin palveluntuottajan kanssa."} :retkikartta {:disclaimer "Kun ”Saa julkaista Retkikartassa” -ruutu on rastitettu, luontoliikuntapaikan tiedot siirretään automaattisesti Metsähallituksen ylläpitämään Retkikartta.fi -karttapalveluun kerran vuorokaudessa. Sitoudun päivittämään luontoliikuntapaikan tietojen muutokset viipymättä Lippaaseen. Paikan hallinnoijalla on vastuu tietojen oikeellisuudesta, paikan turvallisuudesta, palautteisiin vastaamisesta ja mahdollisista yksityisteihin liittyvistä kustannuksista."}, :reset-password {:change-password "<PASSWORD>", :enter-new-password "<PASSWORD>", :get-new-link "Tilaa uusi vaihtolinkki", :headline "Unohtuiko salasana?", :helper-text "Lähetämme salasanan vaihtolinkin sinulle sähköpostitse.", :password-helper-text "Salasanassa on oltava vähintään 6 merkkiä", :reset-link-sent "Linkki lähetetty! Tarkista sähköpostisi.", :reset-success "Salasana vaihdettu! Kirjaudu sisään uudella salasanalla."}, :reports {:contacts "Yhteys​tiedot", :download-as-excel "Luo raportti", :select-fields "Valitse raportin kentät", :selected-fields "Valitut kentät", :shortcuts "Pikavalinnat", :tooltip "Luo Excel-raportti hakutuloksista"}, :heat-sources {:district-heating "Kaukolämpö", :private-power-station "Oma voimalaitos"}, :map.import {:headline "Tuo geometriat", :geoJSON "Tuo .json-tiedosto, joka sisältää GeoJSON FeatureCollection -objektin. Lähtöaineiston pitää olla WGS84-koordinaatistossa.", :gpx "Lähtöaineiston pitää olla WGS84-koordinaatistossa.", :supported-formats "Tuetut tiedostomuodot ovat {1}", :replace-existing? "Korvaa nykyiset geometriat", :select-encoding "Valitse merkistö", :tab-header "Tuo tiedostosta", :kml "Lähtöaineiston pitää olla WGS84 koordinaatistossa.", :shapefile "Tuo .shp-, .dbf- ja .prj-tiedostot pakattuna .zip-muotoon.", :import-selected "Tuo valitut", :tooltip "Tuo geometriat tiedostosta", :unknown-format "Tuntematon tiedostopääte '{1}'"}, :error {:email-conflict "Sähköpostiosoite on jo käytössä", :email-not-found "Sähköpostiosoitetta ei ole rekisteröity.", :invalid-form "Korjaa punaisella merkityt kohdat", :no-data "Ei tietoja", :reset-token-expired "Salasanan vaihto epäonnistui. Linkki on vanhentunut.", :unknown "Tuntematon virhe tapahtui. :/", :user-not-found "Käyttäjää ei löydy.", :username-conflict "Käyttäjätunnus on jo käytössä"}, :reminders {:description "Viesti lähetetään sähköpostiisi valittuna ajankohtana", :after-one-month "Kuukauden kuluttua", :placeholder "Muista tarkistaa liikuntapaikka \"{1}\" {2}", :select-date "Valitse päivämäärä", :tomorrow "Huomenna", :title "Lisää muistutus", :after-six-months "Puolen vuoden kuluttua", :in-a-year "Vuoden kuluttua", :message "Viesti", :in-a-week "Viikon kuluttua"}, :units {:days-in-year "päivää vuodessa", :hours-per-day "tuntia päivässä", :pcs "kpl", :percent "%", :person "hlö", :times-per-day "kertaa päivässä", :times-per-week "kertaa viikossa"}, :lipas.energy-consumption {:contains-other-buildings? "Energialukemat sisältävät myös muita rakennuksia tai tiloja", :headline "Energian​kulutus", :yearly "Vuositasolla*", :report "Ilmoita lukemat", :electricity "Sähköenergia MWh", :headline-year "Lukemat vuonna {1}", :monthly? "Haluan ilmoittaa energiankulutuksen kuukausitasolla", :reported-for-year "Vuoden {1} energiankulutus ilmoitettu", :monthly "Kuukausitasolla", :operating-hours "Käyttötunnit", :not-reported "Ei energiankulutustietoja", :not-reported-monthly "Ei kuukausikulutustietoja", :heat "Lämpöenergia (ostettu) MWh", :cold "Kylmäenergia (ostettu) MWh", :comment "Kommentti", :water "Vesi m³", :monthly-readings-in-year "Kuukausikulutukset vuonna {1}"}, :ice {:description "Jäähalliportaali sisältää hallien perus- ja energiankulutustietoja sekä ohjeita energiatehokkuuden parantamiseen.", :large "Suurhalli > 3000 hlö", :competition "Kilpahalli < 3000 hlö", :headline "Jäähalli​portaali", :video "Video", :comparison "Hallien vertailu", :size-category "Kokoluokitus", :basic-data-of-halls "Jäähallien perustiedot", :updating-basic-data "Perustietojen päivitys", :entering-energy-data "Energiankulutustietojen syöttäminen", :small "Pieni kilpahalli > 500 hlö", :watch "Katso", :video-description "Pihlajalinna Areena on energiatehokas jäähalli"}, :lipas.location {:address "Katuosoite", :city "Kunta", :city-code "Kuntanumero", :headline "Sijainti", :neighborhood "Kuntaosa", :postal-code "Postinumero", :postal-office "Postitoimipaikka"}, :lipas.user.permissions {:admin? "Admin", :all-cities? "Oikeus kaikkiin kuntiin", :all-types? "Oikeus kaikkiin tyyppeihin", :cities "Kunnat", :sports-sites "Liikuntapaikat", :types "Tyypit"}, :help {:headline "Ohjeet", :permissions-help "Jos haluat lisää käyttöoikeuksia, ota yhteyttä ", :permissions-help-body "Haluan käyttöoikeudet seuraaviin liikuntapaikkoihin:", :permissions-help-subject "Haluan lisää käyttöoikeuksia"}, :ceiling-structures {:concrete "Betoni", :double-t-beam "TT-laatta", :glass "Lasi", :hollow-core-slab "Ontelolaatta", :solid-rock "Kallio", :steel "Teräs", :wood "Puu"}, :data-users {:data-user? "Käytätkö LIPAS-dataa?", :email-body "Mukavaa että hyödynnät LIPAS-dataa! Kirjoita tähän kuka olet ja miten hyödynnät Lipasta. Käytätkö mahdollisesti jotain rajapinnoistamme?", :email-subject "Mekin käytämme LIPAS-dataa", :headline "Lipasta hyödyntävät", :tell-us "Kerro siitä meille"}, :lipas.swimming-pool.facilities {:showers-men-count "Miesten suihkut lkm", :lockers-men-count "Miesten pukukaapit lkm", :headline "Muut palvelut", :platforms-5m-count "5 m hyppypaikkojen lkm", :kiosk? "Kioski / kahvio", :hydro-neck-massage-spots-count "Niskahierontapisteiden lkm", :lockers-unisex-count "Unisex pukukaapit lkm", :platforms-10m-count "10 m hyppypaikkojen lkm", :hydro-massage-spots-count "Muiden hierontapisteiden lkm", :lockers-women-count "Naisten pukukaapit lkm", :platforms-7.5m-count "7.5 m hyppypaikkojen lkm", :gym? "Kuntosali", :showers-unisex-count "Unisex suihkut lkm", :platforms-1m-count "1 m hyppypaikkojen lkm", :showers-women-count "Naisten suihkut lkm", :platforms-3m-count "3 m hyppypaikkojen lkm"}, :sauna-types {:infrared-sauna "Infrapunasauna", :other-sauna "Muu sauna", :sauna "Sauna", :steam-sauna "Höyrysauna"}, :stats-metrics {:investments "Investoinnit", :net-costs "Nettokustannukset", :operating-expenses "Käyttökustannukset", :operating-incomes "Käyttötuotot", :subsidies "Kunnan myöntämät avustukset"}, :refrigerant-solutions {:CO2 "CO2", :H2ONH3 "H2O/NH3", :cacl "CaCl", :ethanol-water "Etanoli-vesi", :ethylene-glycol "Etyleeniglykoli", :freezium "Freezium", :water-glycol "Vesi-glykoli"}, :user {:headline "Oma sivu", :admin-page-link "Siirry admin-sivulle", :promo1-link "Näytä TEAviisari-kohteet jotka voin päivittää", :swimming-pools-link "Uimahallit", :promo-headline "Ajankohtaista", :front-page-link "Siirry etusivulle", :promo1-text "Opetus- ja kulttuuriministeriö pyytää kuntia täydentämään erityisesti sisäliikuntapaikkojen rakennusvuosien ja peruskorjausvuosien tiedot. Tieto on tärkeää mm. liikuntapaikkojen korjausvelkaa arvioitaessa.", :ice-stadiums-link "Jäähallit", :greeting "Hei {1} {2}!", :promo1-topic "Kiitos että käytät Lipas.fi-palvelua!"}, :building-materials {:brick "Tiili", :concrete "Betoni", :solid-rock "Kallio", :steel "Teräs", :wood "Puu"}, :stats {:disclaimer-headline "Tietolähde" :general-disclaimer-1 "Lipas.fi – Suomen liikuntapaikat, ulkoilureitit ja virkistysalueet: Nimeä 4.0 Kansainvälinen (CC BY 4.0)." :general-disclaimer-2 "Voit vapaasti käyttää, kopioida, jakaa ja muokata aineistoa. Aineistolähteeseen tulee viitata esimerkiksi näin: Liikuntapaikat: Lipas.fi Jyväskylän yliopisto, otospäivä. Lisätietoja Creative Commons. https://creativecommons.org/licenses/by/4.0/deed.fi" :general-disclaimer-3 "Huomaa, että Lipas-tietokannan tiedot perustuvat kuntien ja muiden liikuntapaikkojen omistajien Lipas-tietokantaan syöttämiin tietoihin sekä Jyväskylän yliopiston Lipas-ylläpitäjien tuottamaan aineistoon. Tietojen kattavuutta, virheettömyyttä, ajantasaisuutta ja yhdenmukaisuutta ei voida taata. Lipas.fi –tilastot -osiossa tilastojen laskenta perustuu tietokantaan tallennettuihin tietoihin. Mahdolliset puuttuvat tiedot vaikuttavat laskelmiin." :finance-disclaimer "Aineistolähde: Tilastokeskus avoimet tilastoaineistot. Huomaa, että kunnat vastaavat itse virallisten taloustietojensa tallentamisesta Tilastokeskuksen tietokantaan Tilastokeskuksen ohjeiden perusteella. Tietojen yhdenmukaisuudesta tai aikasarjojen jatkuvuudesta ei voida antaa takeita." :description "Kuntien viralliset tilinpäätöstiedot liikunta- ja nuorisotoimien osalta. Kunta voi seurata omaa menokehitystään ja vertailla sitä muihin kuntiin.", :filter-types "Rajaa tyypit", :length-km-sum "Liikuntareittien pituus km yhteensä", :headline "Tilastot", :select-years "Valitse vuodet", :browse-to "Siirry tilastoihin", :select-issuer "Valitse myöntäjä", :select-unit "Valitse yksikkö", :bullet3 "Avustukset", :finance-stats "Talous​tiedot", :select-city "Valitse kunta", :area-m2-min "Liikuntapinta-ala m² min", :filter-cities "Rajaa kunnat", :select-metrics "Valitse suureet", :area-m2-count "Liikuntapinta-ala m² ilmoitettu lkm", :show-ranking "Näytä ranking", :age-structure-stats "Rakennus​vuodet", :subsidies-count "Avustusten lkm", :area-m2-sum "Liikuntapinta-ala m² yhteensä", :select-metric "Valitse suure", :bullet2 "Liikuntapaikkatilastot", :area-m2-max "Liikuntapinta-ala m² max", :select-grouping "Ryhmittely", :select-city-service "Valitse toimi", :region "Alue", :show-comparison "Näytä vertailu", :length-km-avg "Liikuntareitin pituus km keskiarvo", :sports-sites-count "Liikuntapaikkojen lkm", :length-km-min "Liikuntareitin pituus km min", :country-avg "(maan keskiarvo)", :length-km-count "Liikuntareitin pituus ilmoitettu lkm", :population "Asukasluku", :sports-stats "Liikunta​paikat", :select-cities "Valitse kunnat", :subsidies "Avustukset", :select-interval "Valitse aikaväli", :bullet1 "Liikunta- ja nuorisotoimen taloustiedot", :area-m2-avg "Liikuntapinta-ala m² keskiarvo", :age-structure "Liikunta​paikkojen rakennus​vuodet", :length-km-max "Liikuntareitin pituus km max", :total-amount-1000e "Yht. (1000 €)", :city-stats "Kunta​tilastot"}, :pool-structures {:concrete "Betoni", :hardened-plastic "Lujitemuovi", :steel "Teräs"}, :map {:retkikartta-checkbox-reminder "Muista myös valita \"Saa julkaista Retkikartta.fi -palvelussa\" ruksi seuraavan vaiheen lisätiedoissa.\"", :zoom-to-user "Kohdista sijaintiini", :remove "Poista", :modify-polygon "Muokkaa aluetta", :draw-polygon "Lisää alue", :retkikartta-problems-warning "Korjaa kartalle merkityt ongelmat, jos haluat, että kohde siirtyy Retkikartalle.", :edit-later-hint "Voit muokata geometriaa myös myöhemmin", :center-map-to-site "Kohdista kartta liikuntapaikkaan", :draw-hole "Lisää reikä", :split-linestring "Katkaise reittiosa", :delete-vertices-hint "Yksittäisiä pisteitä voi poistaa pitämällä alt-näppäintä pohjassa ja klikkaamalla pistettä.", :calculate-route-length "Laske reitin pituus automaattisesti", :remove-polygon "Poista alue", :modify-linestring "Muokkaa reittiä", :download-gpx "Lataa GPX", :add-to-map "Lisää kartalle", :bounding-box-filter "Hae kartan alueelta", :remove-linestring "Poista reittiosa", :draw-geoms "Piirrä", :confirm-remove "Haluatko varmasti poistaa valitun geometrian?", :draw "Lisää kartalle", :draw-linestring "Lisää reittiosa", :modify "Voit raahata pistettä kartalla", :zoom-to-site "Kohdista kartta liikuntapaikkaan", :kink "Muuta reitin kulkua niin, että reittiosa ei risteä itsensä kanssa. Voit tarvittaessa katkaista reitin useampaan osaan.", :zoom-closer "Kartta täytyy zoomata lähemmäs"}, :supporting-structures {:brick "Tiili", :concrete "Betoni", :concrete-beam "Betonipalkki", :concrete-pillar "Betonipilari", :solid-rock "Kallio", :steel "Teräs", :wood "Puu"}, :owner {:unknown "Ei tietoa", :municipal-consortium "Kuntayhtymä", :other "Muu", :company-ltd "Yritys", :city "Kunta", :state "Valtio", :registered-association "Rekisteröity yhdistys", :foundation "Säätiö", :city-main-owner "Kuntaenemmistöinen yritys"}, :menu {:frontpage "Etusivu", :headline "LIPAS", :jyu "Jyväskylän yliopisto", :main-menu "Päävalikko"}, :dryer-types {:cooling-coil "Jäähdytyspatteri", :munters "Muntters", :none "Ei ilmankuivausta"}, :physical-units {:mm "mm", :hour "h", :m3 "m³", :m "m", :temperature-c "Lämpötila °C", :l "l", :mwh "MWh", :m2 "m²", :celsius "°C"}, :lipas.swimming-pool.water-treatment {:activated-carbon? "Aktiivihiili", :filtering-methods "Suodatustapa", :headline "Vedenkäsittely", :ozonation? "Otsonointi", :uv-treatment? "UV-käsittely"}, :statuses {:edited "{1} (muokattu)"}, :lipas.user {:email "Sähköposti", :permissions "Käyttöoikeudet", :permissions-example "Oikeus päivittää Jyväskylän jäähallien tietoja.", :saved-searches "Tallennetut haut", :report-energy-and-visitors "Ilmoita energia- ja kävijämäärätiedot", :permission-to-cities "Sinulla on käyttöoikeus seuraaviin kuntiin:", :password "<PASSWORD>", :lastname "<NAME>", :save-report "Tallenna raporttipohja", :sports-sites "Omat kohteet", :permission-to-all-cities "Sinulla on käyttöoikeus kaikkiin kuntiin", :username "Käyttäjätunnus", :history "Historia", :saved-reports "Tallennetut raporttipohjat", :contact-info "Yhteystiedot", :permission-to-all-types "Sinulla on käyttöoikeus kaikkiin liikuntapaikkatyyppeihin", :requested-permissions "Pyydetyt oikeudet", :email-example "<EMAIL>", :permission-to-portal-sites "Sinulla on käyttöoikeus seuraaviin yksittäisiin liikuntapaikkoihin:", :permissions-help "Kerro, mitä tietoja haluat päivittää Lipaksessa", :report-energy-consumption "Ilmoita energiankulutus", :firstname "<NAME>", :save-search "Tallenna haku", :view-basic-info "Tarkista perustiedot", :no-permissions "Sinulle ei ole vielä myönnetty käyttöoikeuksia.", :username-example "tane12", :permission-to-types "Sinulla on käyttöoikeus seuraaviin liikuntapaikkatyyppeihin:"}, :heat-recovery-types {:liquid-circulation "Nestekierto", :plate-heat-exchanger "Levysiirrin", :thermal-wheel "Pyörivä"}}, :se {:sport {:description "LIPAS är en landsomfattande databas för offentliga finländska idrottsplatser.", :headline "Idrottsanläggningar", :open-interfaces "Öppna gränssnitt", :up-to-date-information "Aktuell data om finska idrottsanläggningar", :updating-tools "Uppdateringsverktyg"}, :confirm {:discard-changes? "Vill du förkasta ändringar?", :headline "Bekräftelse", :no "Nej", :press-again-to-delete "Klicka igen för att radera", :resurrect? "Vill du spara grunddata?", :save-basic-data? "Vill du spara grunddata?", :yes "Ja"}, :lipas.swimming-pool.saunas {:accessible? "Tillgängligt", :add-sauna "Lägg till en bastu", :edit-sauna "Redigera bastun", :headline "Bastur", :men? "Män", :women? "Kvinnor"}, :slide-structures {:concrete "Betong", :hardened-plastic "Öppna gränssnitt", :steel "Stål"}, :lipas.swimming-pool.conditions {:open-days-in-year "Fredagar", :open-hours-mon "Måndagar", :headline "Öppettider", :open-hours-wed "Onsdagar", :open-hours-thu "Torsdagar", :open-hours-fri "Fredagar", :open-hours-tue "Tisdagar", :open-hours-sun "Söndagar", :daily-open-hours "Dagliga öppettider", :open-hours-sat "Lördagar"}, :lipas.ice-stadium.ventilation {:dryer-duty-type "Gatuadress", :dryer-type "Kommun", :heat-pump-type "Gatuadress", :heat-recovery-efficiency "Kommun", :heat-recovery-type "Gatuadress"}, :swim {:basic-data-of-halls "Simhallsportal", :edit "Simhallsportal", :entering-energy-data "Datum", :headline "Simhallsportal", :latest-updates "Timme", :list "Energi information", :updating-basic-data "Information", :visualizations "Energi information"}, :home-page {:description "LIPAS-system innehåller information av idrottsanläggningar, idrottsrutter och friluftsregioner. Data är öppen CC4.0 International.", :headline "Startsida"}, :ice-energy {:finhockey-link "El", :headline "Bensin"}, :filtering-methods {:activated-carbon "Kol", :coal "Kol", :membrane-filtration "Annat", :open-sand "Annat", :other "Annat", :precipitation "Beskrivning", :pressure-sand "Kommentar"}, :open-data {:description "Länkar och information om gränssnitten", :headline "Öppna data", :rest "REST", :wms-wfs "WMS & WFS"}, :lipas.swimming-pool.pool {:accessibility "Tillgänglighet", :outdoor-pool? "Utomhus simbassäng"}, :pool-types {:multipurpose-pool "Allaktivitetsbassäng", :whirlpool-bath "Bubbelbad", :main-pool "Huvudsbassäng", :therapy-pool "Terapibassäng", :fitness-pool "Konditionsbassäng", :diving-pool "Hoppbassäng", :childrens-pool "Barnbassäng", :paddling-pool "Plaskdamm", :cold-pool "Kallbassäng", :other-pool "Annan bassäng", :teaching-pool "Undervisningsbassäng"}, :disclaimer {:headline "OBS!", :test-version "Automatisk"}, :admin {:private-foundation "Privat / stiftelse", :city-other "Kommun / annat", :unknown "Okänt", :municipal-consortium "Samkommun", :private-company "Privat / företag", :private-association "Privat / förening", :other "Annat", :city-technical-services "Kommun / teknisk väsende", :city-sports "Kommun/ idrottsväsende", :state "Stat", :city-education "Kommun / utbildingsväsende"}, :accessibility {:lift "Lyft i bassängen", :slope "Ramp"}, :general {:description "Beskrivning", :hall "Hall", :women "K<NAME>", :total-short "Totalt", :done "Färdig", :updated "Uppdaterad", :name "<NAME>", :reported "Rapporterad", :type "Typ", :last-modified "Senaste redigerad", :here "här", :event "Händelse", :structure "Struktur", :general-info "Allmänna uppgifter", :comment "Kommentar", :measures "Mått", :men "Män"}, :dryer-duty-types {:automatic "Automatisk", :manual "Manual"}, :swim-energy {:description "Information", :headline "Energi information", :headline-short "Information", :suh-link "Datum", :ukty-link "Slutade"}, :time {:two-years-ago "För 2 år sedan", :date "Datum", :hour "Timme", :this-month "Den här månaden", :time "Tid", :less-than-hour-ago "För mindre än en timme sedan", :start "Började", :this-week "Den här veckan", :today "I dag", :month "Månad", :long-time-ago "För länge sedan", :year "År", :just-a-moment-ago "För en stund sedan", :yesterday "I går", :three-years-ago "För 3 år sedan", :end "Slutade", :this-year "Det här året", :last-year "Förra året"}, :ice-resurfacer-fuels {:LPG "El", :electicity "El", :gasoline "Bensin", :natural-gas "Naturgas", :propane "Propan"}, :ice-rinks {:headline "Du har admin rättigheter."}, :month {:sep "September", :jan "Januari", :jun "Juni", :oct "Oktober", :jul "Juli", :apr "April", :feb "Februari", :nov "November", :may "<NAME>", :mar "Mars", :dec "December", :aug "Augusti"}, :type {:name "Idrottsanläggningstyp", :main-category "Huvudkategori", :sub-category "Underkategori", :type-code "Typkod"}, :duration {:hour "timmar", :month "månader", :years "år", :years-short "år"}, :size-categories {:large "Betong"}, :lipas.admin {:access-all-sites "Du har admin rättigheter.", :confirm-magic-link "Är du säker på att du vill skicka magic link till {1}?", :headline "Admin", :magic-link "Magic link", :select-magic-link-template "Välj brev", :send-magic-link "Skicka magic link till användare", :users "Användare"}, :lipas.building {:headline "Byggnad", :total-volume-m3 "Areal av vatten m²", :staff-count "Antalet personal", :heat-sections? "Antalet personal", :total-ice-area-m2 "Areal av is m²", :main-designers "Antalet personal", :total-pool-room-area-m2 "Areal av vatten m²", :total-water-area-m2 "Areal av vatten m²", :ceiling-structures "Byggnad", :supporting-structures "Areal av is m²", :seating-capacity "Antalet personal"}, :search {:table-view "Visa resultaten i tabellen", :headline "Sökning", :results-count "{1} resultat", :placeholder "Sök...", :retkikartta-filter "Retkikartta.fi-platser", :filters "Filtrera sökning", :search-more "Sök mer...", :page-size "Visa", :search "Sök", :permissions-filter "Visa platser som jag kan redigera", :display-closest-first "Visa närmaste platser först", :list-view "Visa resultaten i listan", :pagination "Resultaten {1}-{2}", :school-use-filter "Idrottsanläggningar nära skolor", :clear-filters "Avmarkera filter"}, :map.tools {:drawing-tooltip "Ritningsverktyg vald", :drawing-hole-tooltip "Hålverktyg vald", :edit-tool "Redigeringsverktyg", :importing-tooltip "Importeringsverktyg vald", :deleting-tooltip "Borttagningsverktyg vald", :splitting-tooltip "Klippningsverktyg vald"}, :partners {:headline "Tillsammans med"}, :actions {:duplicate "Kopiera", :resurrect "Öppna huvudmeny", :select-year "Välj år", :select-owners "Välj ägare", :select-admins "Välj administratörer", :select-tool "Välj verktyg", :save-draft "Spara utkast", :redo "Gör igen", :open-main-menu "Öppna huvudmeny", :back-to-listing "Till listan", :filter-surface-materials "Avgränsa enligt ytmaterial", :browse "flytta dig", :select-type "Välj typ", :edit "Redigera", :filter-construction-year "Avgränsa enligt byggnadsår", :submit "Skicka", :choose-energy "Välj energi", :delete "Radera", :browse-to-map "Flytta dig till kartan", :save "Spara", :close "Stäng", :filter-area-m2 "Avgränsa enligt areal m²", :show-account-menu "Öppna kontomeny", :fill-required-fields "Fyll i obligatoriska fält", :undo "Ångra", :browse-to-portal "Flytta dig till portalen", :download-excel "Ladda ner Excel", :fill-data "Fyll i informationen", :select-statuses "Status", :select-cities "Välj kommuner", :select-hint "Välj...", :discard "Förkasta", :more "Mer...", :cancel "Avbryta", :select-columns "Välj datafält", :add "Tillägg ", :show-all-years "Visa alla år", :download "Ladda ner", :select-hall "Välj hall", :clear-selections "Ta bort val", :select "Välj", :select-types "Välj typer"}, :dimensions {:area-m2 "Areal m²", :depth-max-m "Djup max m", :depth-min-m "Djup min m", :length-m "Längd m", :surface-area-m2 "Areal m²", :volume-m3 "Volym m3", :width-m "Bredd m"}, :login {:headline "Logga in", :login-here "här", :login-with-password "<PASSWORD>", :password "<PASSWORD>", :logout "Logga ut", :username "E-post / användarnamn", :login-help "Om du har ett användarnamn till LIPAS, du kan också logga in med e-post", :login "Logga in", :magic-link-help "Om du har ett användarnamn till LIPAS, du kan beställa en logga in-länk till din e-post.", :order-magic-link "Skicka länken till min e-post", :login-with-magic-link "Logga in med e-post", :bad-credentials "Lösenord eller användarnamn är felaktigt", :magic-link-ordered "Länken har skickats och den är snart i din e-post. Kolla också spam!", :username-example "<EMAIL>", :forgot-password? "<PASSWORD>?"}, :map.demographics {:headline "Befolkning", :tooltip "Visa befolkning", :helper-text "Välj idrottsanläggning på kartan.", :copyright1 "Befolkningsinformation: Statistikcentralen 2019 årets", :copyright2 "1 km * 1 km data", :copyright3 "licens"}, :lipas.swimming-pool.slides {:add-slide "Lägg till en rutschbana", :edit-slide "Redigera rutschbanan", :headline "Rutschbanor"}, :notifications {:get-failed "Datasökning misslyckades.", :save-failed "Sparningen misslyckades", :save-success "Sparningen lyckades" :ie (str "Internet Explorer stöds inte. Vi rekommenderar du använder t.ex. Chrome, Firefox eller Edge.")}, :lipas.swimming-pool.energy-saving {:filter-rinse-water-heat-recovery? "Gym", :headline "Andra tjänster", :shower-water-heat-recovery? "Gym"}, :ice-form {:headline "Naturgas", :headline-short "El", :select-rink "Bensin"}, :restricted {:login-or-register "Logga in eller registrera dig"}, :lipas.sports-site {:properties "Ytterligare information", :delete-tooltip "Ta bort idrottsanläggningen...", :headline "Idrottsanläggning", :new-site-of-type "Ny {1}", :address "Adress", :new-site "Ny idrottsplats", :phone-number "Telefonnummer", :admin "Administratör", :surface-materials "Ytmaterial", :www "Webbsida", :name "<NAME> på <NAME>", :reservations-link "Bokningar", :construction-year "Byggår", :type "Typ", :delete "Ta bort {1}", :renovation-years "Renoveringsår", :name-localized-se "Namn på svenska", :status "Status", :id "LIPAS-ID", :details-in-portal "Visa alla ytterligare information", :comment "Ytterligare information", :ownership "Ägare", :name-short "Namn", :basic-data "Grunddata", :delete-reason "Orsak", :event-date "Redigerad", :email-public "E-post (publik)", :add-new "Lägg till en idrottsanläggning", :contact "Kontaktinformation", :owner "Ägare", :marketing-name "<NAME>"}, :status {:active "Aktiv", :planned "Planerad" :incorrect-data "Fel information", :out-of-service-permanently "Permanent ur funktion", :out-of-service-temporarily "Tillfälligt ur funktion"}, :register {:headline "Registrera", :link "Registrera här" :thank-you-for-registering "Tack för registrering! Du vill få e-posten snart."}, :map.address-search {:title "Sök address", :tooltip "Sök address"}, :ice-comparison {:headline "Jämförelse av hallar"}, :lipas.visitors {:headline "Användare", :not-reported "Glömt lösenordet?", :not-reported-monthly "Lösenord eller användarnamn är felaktigt", :spectators-count "Glömt ditt lösenord?", :total-count "Lösenord eller användarnamn är felaktigt"}, :lipas.energy-stats {:headline "Värme MWh", :energy-reported-for "Värme MWh", :disclaimer "El MWh", :reported "Vatten m³", :cold-mwh "El + värme MWh", :hall-missing? "Vatten m³", :not-reported "Vatten m³", :water-m3 "Vatten m³", :electricity-mwh "El MWh", :heat-mwh "Värme MWh", :energy-mwh "El + värme MWh"}, :map.basemap {:copyright "© Lantmäteriverket", :maastokartta "Terrängkarta", :ortokuva "Flygfoto", :taustakartta "Bakgrundskarta"}, :lipas.swimming-pool.pools {:add-pool "Lägg till en bassäng", :edit-pool "Redigera bassängen", :headline "Bassänger", :structure "Struktur"}, :condensate-energy-targets {:service-water-heating "Nej", :snow-melting "Vill du förkasta ändringar?", :track-heating "Vill du förkasta ändringar?"}, :refrigerants {:CO2 "CO2 (koldioxid)", :R134A "R134A", :R22 "R22", :R404A "R404A", :R407A "R407A", :R407C "R407C", :R717 "R717"}, :harrastuspassi {:disclaimer "När du kryssat för rutan ”Kan visas på Harrastuspassi.fi” flyttas uppgifterna om idrottsanläggningen automatiskt till Harrastuspassi.fi. Jag förbinder mig att uppdatera ändringar i uppgifterna om idrottsanläggningen utan dröjsmål i Lipas. Anläggningens administratör ansvarar för uppgifternas riktighet och anläggningens säkerhet. Uppgifterna visas i Harrastuspassi.fi om kommunen har kontrakt med Harrastuspassi.fi administratör för att använda Harrastuspassi.fi."} :retkikartta {:disclaimer "När du kryssat för rutan ”Kan visas på Utflyktskarta.fi” flyttas uppgifterna om naturutflyktsmålet automatiskt till karttjänsten Utflyktskarta.fi som Forststyrelsen administrerar. Uppgifter överförs till karttjänsten en gång i dygnet. Jag förbinder mig att uppdatera ändringar i uppgifterna om naturutflyktsmålet utan dröjsmål i Lipas. Utflyktsmålets administratör ansvarar för uppgifternas riktighet och utflyktsmålets säkerhet samt för svar på respons och för eventuella kostnader i samband med privata vägar."}, :reset-password {:change-password "<PASSWORD>", :enter-new-password "<PASSWORD>", :get-new-link "Bestella ny återställningslänk", :headline "Glömt lösenordet?", :helper-text "Vi ska skicka en återställningslänk till din e-post.", :password-helper-text "Lösenordet måste innehålla minst 6 tecken.", :reset-link-sent "Länken har skickats! Kolla din e-post.", :reset-success "Lösenordet har ändrats! Logga in med ditt nya lösenord."}, :reports {:contacts "Kontaktuppgifter", :download-as-excel "Skapa Excel", :select-fields "Välj fält för rapport", :selected-fields "Vald fält", :shortcuts "Genvägar", :tooltip "Skapa Excel-rapport från resultaten"}, :heat-sources {:district-heating "Om du behöver ytterligare användarrättigheter, kontakt ", :private-power-station "Hjälp"}, :map.import {:headline "Importera geometri", :geoJSON "Laddar upp .json file som innehåller GeoJSON FeatureCollect object. Koordinater måste vara i WGS84 koordinatsystem.", :gpx "Utgångsmaterial måste vara i WGS84 koordinatsystem.", :supported-formats "Filformat som passar är {1}", :replace-existing? "Ersätt gammal geometri", :select-encoding "Välj teckenuppsättning", :tab-header "Importera från filen", :kml "Utgångsmaterial måste vara i WGS84 koordinatsystem.", :shapefile "Importera .shp .dbf och .prj filer i packade .zip filen.", :import-selected "Importera valda", :tooltip "Importera geometrier från filen", :unknown-format "Okänt filformat '{1}'"}, :error {:email-conflict "E-post är redan registrerad", :email-not-found "E-post är inte registrerad", :invalid-form "Korrigera röda fält", :no-data "Ingen information", :reset-token-expired "Lösenordet har inte ändrats. Länken har utgått.", :unknown "Ett okänt fel uppstod. :/", :user-not-found "Användare hittas inte.", :username-conflict "An<NAME>arnam<NAME> redan används"}, :reminders {:description "Meddelandet ska skickas till din e-post på vald tid.", :after-one-month "Om en månad", :placeholder "Kom ihåg att kolla idrottsanläggningen \"{1}\" {2}", :select-date "Välj datum", :tomorrow "I morgon", :title "Lägg till en påminnelse", :after-six-months "Om halv år", :in-a-year "Om ett år", :message "Meddelande", :in-a-week "Om en vecka"}, :units {:days-in-year "dagar per år", :hours-per-day "timmar per dag", :pcs "st", :percent "%", :person "pers.", :times-per-day "gånger per dag", :times-per-week "gånger per vecka"}, :lipas.energy-consumption {:cold "Kommentar", :comment "Kommentar", :monthly? "Vatten m³", :operating-hours "Vatten m³", :report "El MWh", :reported-for-year "Vatten m³", :water "Vatten m³", :yearly "El MWh"}, :ice {:description "Stor tävlingshall > 3000", :large "Stor tävlingshall > 3000", :competition "Tävlingsishall < 3000 person", :headline "Ishallsportal", :video "Video", :comparison "Jämförelse av hallar", :size-category "Storlek kategori", :basic-data-of-halls "Grunddata av ishallar", :updating-basic-data "Uppdatering av grunddata", :entering-energy-data "Ishallsportal", :small "Liten tävlingshall > 500 person", :watch "Titta", :video-description "Titta"}, :lipas.location {:address "Gatuadress", :city "Kommun", :city-code "Kommunkod", :headline "Position", :neighborhood "Kommundel", :postal-code "Postnummer", :postal-office "Postkontor"}, :lipas.user.permissions {:admin? "Admin", :all-cities? "Rättighet till alla kommuner", :all-types? "Rättighet till alla typer", :cities "Kommuner", :sports-sites "Idrottsanläggning", :types "Typer"}, :help {:headline "Hjälp", :permissions-help "Om du behöver ytterligare användarrättigheter, kontakt ", :permissions-help-body "Jag behöver användarrättigheter till följande platser:", :permissions-help-subject "Jag behöver mera användarrättigheter"}, :ceiling-structures {:concrete "Betong", :double-t-beam "TT-bricka", :glass "Glas", :hollow-core-slab "Häll", :solid-rock "Häll", :steel "Stål", :wood "Trä"}, :data-users {:data-user? "Använder du LIPAS-data?", :email-body "Vi använder också LIPAS-data", :email-subject "Vi använder också LIPAS-data", :headline "Några som använder LIPAS-data", :tell-us "Berättä om det för oss"}, :lipas.swimming-pool.facilities {:showers-men-count "Antalet duschar för män", :lockers-men-count "Antalet omklädningsskåp för män", :headline "Andra tjänster", :platforms-5m-count "Antalet 5 m hopplatser", :kiosk? "Kiosk / café", :hydro-neck-massage-spots-count "Antal av nackemassagepunkter", :lockers-unisex-count "Antalet unisex omklädningsskåp", :platforms-10m-count "Antalet 10 m hopplatser", :hydro-massage-spots-count "Antal av andra massagepunkter", :lockers-women-count "Antalet omklädningsskåp för kvinnor", :platforms-7.5m-count "Antalet 7.5 m hopplatser", :gym? "Gym", :showers-unisex-count "Antalet unisex duschar", :platforms-1m-count "Antalet 1 m hopplatser", :showers-women-count "Antalet duschar för kvinnor", :platforms-3m-count "Antalet 3 m hopplatser"}, :sauna-types {:infrared-sauna "Infraröd bastu", :other-sauna "Annan bastu", :sauna "Bastu", :steam-sauna "Ångbastu"}, :stats-metrics {:investments "Investeringar", :net-costs "Nettokostnader", :operating-expenses "Driftskostnader", :operating-incomes "Driftsintäkter", :subsidies "Understöd och bidrag från kommunen"}, :refrigerant-solutions {:CO2 "CO2", :H2ONH3 "H2O/NH3", :cacl "CaCl", :ethanol-water "Freezium", :ethylene-glycol "R134A", :freezium "Freezium", :water-glycol "R134A"}, :user {:headline "Mitt konto", :admin-page-link "Gå till adminsidan", :promo1-link "Visa gymnastiksaler som jag kan uppdatera", :swimming-pools-link "Simhallsportal", :promo-headline "Aktuellt", :front-page-link "Gå till framsidan", :promo1-text "Undervisnings- och kulturministeriet önskar att kommuner kompletterar information om byggnadsår och renoveringår om idrottsplatser inomhus. Informationen är viktig för utvärdering av renoveringsskuld i idrottsplatser.", :ice-stadiums-link "Ishallsportal", :greeting "Hej {1} {2} !", :promo1-topic "Tack för att du använder Lipas.fi!"}, :building-materials {:brick "Tegel", :concrete "Betong", :solid-rock "Häll", :steel "Stål", :wood "Trä"}, :stats {:disclaimer-headline "Datakälla" :general-disclaimer-1 "Lipas.fi idrottsanläggningar, friluftsleder och friluftsområden i Finland: Erkännande 4.0 Internationell (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/deed.sv" :general-disclaimer-2 "Du har tillstånd att dela, kopiera och vidaredistribuera materialet oavsett medium eller format, bearbeta, remixa, transformera, och bygg vidare på materialet, för alla ändamål, även kommersiellt. Du måste ge ett korrekt erkännande om du använder Lipas-data, till exempel “Idrottsplatser: Lipas.fi, Jyväskylä Universitet, datum/år”." :general-disclaimer-3 "Observera, att Lipas.fi data är uppdaterat av kommuner och andra ägare av idrottsplatser samt Lipas.fi administratörer i Jyväskylä Universitet. Omfattning, riktighet eller enhetlighet kan inte garanteras. I Lipas.fi statistik är material baserat på data i Lipas.fi databas. Återstående information kan påverka beräkningar." :finance-disclaimer "Ekonomiska uppgifter av kommuners idrotts- och ungdomsväsende: Statistikcentralen öppen data. Materialet har laddats ner från Statistikcentralens gränssnittstjänst 2001-2019 med licensen CC BY 4.0. Observera, att kommunerna ansvarar själva för att uppdatera sina ekonomiska uppgifter i Statistikcentralens databas. Enhetlighet och jämförbarhet mellan åren eller kommunerna kan inte garanteras." :description "Ekonomiska uppgifter om idrotts- och ungdomsväsende. Kommunen kan observera hur kostnader utvecklas över tid.", :filter-types "Välj typer", :length-km-sum "Idrottsrutters totalt längd ", :headline "Statistik", :select-years "Välj år", :browse-to "Gå till statistiken", :select-issuer "Välj understödare", :select-unit "Välj måttenhet", :bullet3 "Bidrag", :finance-stats "Ekonomiska uppgifter", :select-city "Välj kommun", :area-m2-min "Minimum idrottsareal m²", :filter-cities "Välj kommuner", :select-metrics "Välj storheter", :area-m2-count "Antal av platser med idrottsareal information", :show-ranking "Visa rankning", :age-structure-stats "Byggnadsår", :subsidies-count "Antal av bidrag", :area-m2-sum "Totalt idrottsareal m²", :select-metric "Välj storhet", :bullet2 "Statistiken om idrottsanläggningar", :area-m2-max "Maximum idrottsareal m²", :select-grouping "Gruppering", :select-city-service "Välj administratör", :region "Region", :show-comparison "Visa jämförelse", :length-km-avg "Medeltal av idrottsruttens längd", :sports-sites-count "Antal av idrottsanläggningar", :length-km-min "Minimum idrottsruttens längd", :country-avg "(medeltal för hela landet)", :length-km-count "Antal av idrottsrutter med längd information", :population "Folkmängd", :sports-stats "Idrottsanläggningar", :select-cities "Välj kommuner", :subsidies "Bidrag", :select-interval "Välj intervall", :bullet1 "Ekonomiska uppgifter om idrotts- och ungdomsväsende", :area-m2-avg "Medeltal av idrottsareal m²", :age-structure "Byggnadsår av idrottsanläggningar", :length-km-max "Maximum idrottsruttens längd", :total-amount-1000e "Totalt (1000 €)", :city-stats "Kommunstatistik"}, :pool-structures {:concrete "Betong", :hardened-plastic "Barnbassäng", :steel "Stål"}, :map {:retkikartta-checkbox-reminder "Välj också igen \"Kan visas i Retkikartta.fi - service\" i följande steg i ytterligare information.", :zoom-to-user "Zooma in till min position", :remove "Ta bort", :modify-polygon "Modifera området", :draw-polygon "Lägg till område", :retkikartta-problems-warning "Korrigera problem som är märkta på kartan för att visa i Retkikartta.fi.", :edit-later-hint "Du kan modifera geometrin också senare", :center-map-to-site "Fokusera kartan på platsen", :draw-hole "Lägg till hål", :split-linestring "Klippa ruttdel", :delete-vertices-hint "För att ta bort en punkt, tryck och håll alt-knappen och klicka på punkten", :calculate-route-length "Räkna ut längden", :remove-polygon "Ta bort område", :modify-linestring "Modifera rutten", :download-gpx "Ladda ner GPX", :add-to-map "Lägg till på karta", :bounding-box-filter "Sök i området", :remove-linestring "Ta bort ruttdel", :draw-geoms "Rita", :confirm-remove "Är du säker att du vill ta bort geometrin?", :draw "Lägg till på karta", :draw-linestring "Lägg till ruttdel", :modify "Du kan dra punkten på kartan", :zoom-to-site "Zooma in till sportplats", :kink "Korrigera så att ruttdelen inte korsar själv", :zoom-closer "Zooma in"}, :supporting-structures {:brick "Tegel", :concrete "Betong", :concrete-beam "Häll", :concrete-pillar "Stål", :solid-rock "Häll", :steel "Stål", :wood "Trä"}, :owner {:unknown "Ingen information", :municipal-consortium "Samkommun", :other "An<NAME>", :company-ltd "Företag", :city "Kommun", :state "Stat", :registered-association "Registrerad förening", :foundation "Stiftelse", :city-main-owner "Företag med kommun som majoritetsägare"}, :menu {:frontpage "Framsidan", :headline "LIPAS", :jyu "Jyväskylä universitet", :main-menu "Huvudmeny"}, :dryer-types {:cooling-coil "timmar", :munters "månader", :none "timmar"}, :physical-units {:mm "mm", :hour "h", :m3 "m³", :m "m", :temperature-c "Temperatur °C", :l "l", :mwh "MWh", :m2 "m²", :celsius "°C"}, :lipas.swimming-pool.water-treatment {:filtering-methods "E-post", :headline "Kontaktuppgifter", :ozonation? "E-post", :uv-treatment? "Kontaktuppgifter"}, :statuses {:edited "{1} (redigerad)"}, :lipas.user {:email "E-post", :permissions "Rättigheter", :permissions-example "Rätt att uppdatera Jyväskylä ishallen.", :saved-searches "Sparad sök", :report-energy-and-visitors "Spara raportmodellen", :permission-to-cities "Du har rättighet att uppdatera de här kommunerna:", :password "<PASSWORD>", :lastname "<NAME>", :save-report "Spara raportmodellen", :sports-sites "Egna platser", :permission-to-all-cities "Du har rättighet att uppdatera alla kommuner", :username "Användarnamn", :history "Historia", :saved-reports "Sparad raportmodeller", :contact-info "Kontaktuppgifter", :permission-to-all-types "Du har rättighet att uppdatera alla typer", :requested-permissions "Begärda rättigheter", :email-example "<EMAIL>", :permission-to-portal-sites "Du har rättighet att uppdatera de här platserna:", :permissions-help "Skriv vad du vill uppdatera i Lipas", :report-energy-consumption "Begärda rättigheter", :firstname "Förnamn", :save-search "Spara söket", :view-basic-info "Kolla ut grunddata", :no-permissions "Användarnamn till Lipas har inte ännu konfirmerats", :username-example "tane12", :permission-to-types "Du har rättighet att uppdatera de här typerna:"}, :heat-recovery-types {:thermal-wheel "Hjälp"}}, :en {:analysis {:headline "Analysis tool (beta)" :add-new "Add new" :distance "Distance" :travel-time "Travel time" :zones "Baskets" :zone "Basket" :schools "Schools" :daycare "Early childhood education" :elementary-school "Elementary school" :high-school "High school" :elementary-and-high-school "Elementary and high school" :special-school "Special education school" :direct "Beeline" :by-foot "By foot" :by-car "By car" :by-bicycle "By bicycle" :population "Population" :analysis-buffer "Analysis buffer" :filter-types "Filter by type" :settings "Settings" :settings-map "What's visible on map" :settings-zones "Distances and travel times" :settings-help "Note: analysis area will be determined by the maximum distance defined here. Travel times are not calculated outside the maximum distance."} :sport {:description "LIPAS is the national database of sport facilities and their conditions in Finland.", :headline "Sports Faclities", :open-interfaces "Open data and APIs", :up-to-date-information "Up-to-date information about sports facilities", :updating-tools "Tools for data maintainers"}, :confirm {:discard-changes? "Do you want to discard all changes?", :headline "Confirmation", :no "No", :press-again-to-delete "Press again to delete", :resurrect? "Are you sure you want to resurrect this sports facility?", :save-basic-data? "Do you want to save general information?", :yes "Yes"}, :lipas.swimming-pool.saunas {:accessible? "Accessible", :add-sauna "Add sauna", :edit-sauna "Edit sauna", :headline "Saunas", :men? "Men", :women? "Women"}, :slide-structures {:concrete "Concrete", :hardened-plastic "Hardened plastic", :steel "Steel"}, :lipas.swimming-pool.conditions {:open-days-in-year "Open days in year", :open-hours-mon "Mondays", :headline "Open hours", :open-hours-wed "Wednesdays", :open-hours-thu "Thursdays", :open-hours-fri "Fridays", :open-hours-tue "Tuesdays", :open-hours-sun "Sundays", :daily-open-hours "Daily open hours", :open-hours-sat "Saturdays"}, :lipas.ice-stadium.ventilation {:dryer-duty-type "Dryer duty type", :dryer-type "Dryer type", :headline "Ventilation", :heat-pump-type "Heat pump type", :heat-recovery-efficiency "Heat recovery efficiency", :heat-recovery-type "Heat recovery type"}, :swim {:description "Swimming pools portal contains data about indoor swimming pools energy consumption and related factors.", :latest-updates "Latest updates", :headline "Swimming pools", :basic-data-of-halls "General information about building and facilities", :updating-basic-data "Updating general information", :edit "Report consumption", :entering-energy-data "Reporing energy consumption", :list "Pools list", :visualizations "Comparison"}, :home-page {:description "LIPAS system has information on sport facilities, routes and recreational areas and economy. The content is open data under the CC4.0 International licence.", :headline "Front page"}, :ice-energy {:description "Up-to-date information can be found from Finhockey association web-site.", :energy-calculator "Ice stadium energy concumption calculator", :finhockey-link "Browse to Finhockey web-site", :headline "Energy Info"}, :filtering-methods {:activated-carbon "Activated carbon", :coal "Coal", :membrane-filtration "Membrane filtration", :multi-layer-filtering "Multi-layer filtering", :open-sand "Open sand", :other "Other", :precipitation "Precipitation", :pressure-sand "Pressure sand"}, :open-data {:description "Interface links and instructions", :headline "Open Data", :rest "REST", :wms-wfs "WMS & WFS"}, :lipas.swimming-pool.pool {:accessibility "Accessibility", :outdoor-pool? "Outdoor pool"}, :pool-types {:multipurpose-pool "Multi-purpose pool", :whirlpool-bath "Whirlpool bath", :main-pool "Main pool", :therapy-pool "Therapy pool", :fitness-pool "Fitness pool", :diving-pool "Diving pool", :childrens-pool "Childrens pool", :paddling-pool "Paddling pool", :cold-pool "Cold pool", :other-pool "Other pool", :teaching-pool "Teaching pool"}, :lipas.ice-stadium.envelope {:base-floor-structure "Base floor structure", :headline "Envelope structure", :insulated-ceiling? "Insulated ceiling", :insulated-exterior? "Insulated exterior", :low-emissivity-coating? "Low emissivity coating"}, :disclaimer {:headline "NOTICE!", :test-version "This is LIPAS TEST-ENVIRONMENT. Changes made here don't affect the production system."}, :admin {:private-foundation "Private / foundation", :city-other "City / other", :unknown "Unknown", :municipal-consortium "Municipal consortium", :private-company "Private / company", :private-association "Private / association", :other "Other", :city-technical-services "City / technical services", :city-sports "City / sports", :state "State", :city-education "City / education"}, :accessibility {:lift "Pool lift", :low-rise-stairs "Low rise stairs", :mobile-lift "Mobile pool lift", :slope "Slope"}, :general {:description "Description", :hall "Hall", :women "Women", :total-short "Total", :done "Done", :updated "Updated", :name "<NAME>", :reported "Reported", :type "Type", :last-modified "Last modified", :here "here", :event "Event", :structure "Structure", :general-info "General information", :comment "Comment", :measures "Measures", :men "Men"}, :dryer-duty-types {:automatic "Automatic", :manual "Manual"}, :swim-energy {:description "Up-to-date information can be found from UKTY and SUH web-sites.", :headline "Energy info", :headline-short "Info", :suh-link "Browse to SUH web-site", :ukty-link "Browse to UKTY web-site"}, :time {:two-years-ago "2 years ago", :date "Date", :hour "Hour", :this-month "This month", :time "Time", :less-than-hour-ago "Less than an hour ago", :start "Started", :this-week "This week", :today "Today", :month "Month", :long-time-ago "Long time ago", :year "Year", :just-a-moment-ago "Just a moment ago", :yesterday "Yesterday", :three-years-ago "3 years ago", :end "Ended", :this-year "This year", :last-year "Last year"}, :ice-resurfacer-fuels {:LPG "LPG", :electicity "Electricity", :gasoline "Gasoline", :natural-gas "Natural gas", :propane "Propane"}, :ice-rinks {:headline "Venue details"}, :month {:sep "September", :jan "January", :jun "June", :oct "October", :jul "July", :apr "April", :feb "February", :nov "November", :may "May", :mar "March", :dec "December", :aug "August"}, :type {:name "Type", :main-category "Main category", :sub-category "Sub category", :type-code "Type code"}, :duration {:hour "hours", :month "months", :years "years", :years-short "y"}, :size-categories {:competition "Competition < 3000 persons", :large "Large > 3000 persons", :small "Small > 500 persons"}, :lipas.admin {:access-all-sites "You have admin permissions.", :confirm-magic-link "Are you sure you want to send magic link to {1}?", :headline "Admin", :magic-link "Magic Link", :select-magic-link-template "Select letter", :send-magic-link "Send magic link to {1}", :users "Users"}, :lipas.ice-stadium.refrigeration {:headline "Refrigeration", :refrigerant-solution-amount-l "Refrigerant solution amount (l)", :individual-metering? "Individual metering", :original? "Original", :refrigerant "Refrigerant", :refrigerant-solution "Refrigerant solution", :condensate-energy-main-targets "Condensate energy main target", :power-kw "Power (kW)", :condensate-energy-recycling? "Condensate energy recycling", :refrigerant-amount-kg "Refrigerant amount (kg)"}, :lipas.building {:headline "Building", :total-volume-m3 "Volume m³", :staff-count "Staff count", :piled? "Piled", :heat-sections? "Pool room is divided to heat sections?", :total-ice-area-m2 "Ice surface area m²", :main-construction-materials "Main construction materials", :main-designers "Main designers", :total-pool-room-area-m2 "Pool room area m²", :heat-source "Heat source", :total-surface-area-m2 "Area m²", :total-water-area-m2 "Water surface area m²", :ceiling-structures "Ceiling structures", :supporting-structures "Supporting structures", :seating-capacity "Seating capacity"}, :heat-pump-types {:air-source "Air source heat pump", :air-water-source "Air-water source heat pump", :exhaust-air-source "Exhaust air source heat pump", :ground-source "Ground source heat pump", :none "None"}, :search {:table-view "Table view", :headline "Search", :results-count "{1} results", :placeholder "Search...", :retkikartta-filter "Retkikartta.fi", :filters "Filters", :search-more "Search more...", :page-size "Page size", :search "Search", :permissions-filter "Show only sites that I can edit", :display-closest-first "Display nearest first", :list-view "List view", :pagination "Results {1}-{2}", :school-use-filter "Used by schools", :clear-filters "Clear filters"}, :map.tools {:drawing-tooltip "Draw tool selected", :drawing-hole-tooltip "Draw hole tool selected", :edit-tool "Edit tool", :importing-tooltip "Import tool selected", :deleting-tooltip "Delete tool selected", :splitting-tooltip "Split tool selected"}, :partners {:headline "In association with"}, :actions {:duplicate "Duplicate", :resurrect "Resurrect", :select-year "Select year", :select-owners "Select owners", :select-admins "Select administrators", :select-tool "Select tool", :save-draft "Save draft", :redo "Redo", :open-main-menu "Open main menu", :back-to-listing "Back to list view", :filter-surface-materials "Filter surface materials", :browse "Browse", :select-type "Select types", :edit "Edit", :filter-construction-year "Filter construction years", :submit "Submit", :choose-energy "Choose energy", :delete "Delete", :browse-to-map "Go to map view", :save "Save", :close "Close", :filter-area-m2 "Filter area m²", :show-account-menu "Open account menu", :fill-required-fields "Please fill all required fields", :undo "Undo", :browse-to-portal "Enter portal", :download-excel "Download Excel", :fill-data "Fill", :select-statuses "Status", :select-cities "Select cities", :select-hint "Select...", :discard "Discard", :more "More...", :cancel "Cancel", :select-columns "Select fields", :add "Add", :show-all-years "Show all years", :download "Download", :select-hall "Select hall", :clear-selections "Clear", :select "Select", :select-types "Select types"}, :dimensions {:area-m2 "Area m²", :depth-max-m "Depth max m", :depth-min-m "Depth min m", :length-m "Length m", :surface-area-m2 "Surface area m²", :volume-m3 "Volume m³", :width-m "Width m"}, :login {:headline "Login", :login-here "here", :login-with-password "<PASSWORD> with <PASSWORD>", :password "<PASSWORD>", :logout "Log out", :username "Email / Username", :login-help "If you are already a LIPAS-user you can login using just your email address.", :login "Login", :magic-link-help "Order login link", :order-magic-link "Order login link", :login-with-magic-link "Login with email", :bad-credentials "Wrong username or password", :magic-link-ordered "Password", :username-example "<EMAIL>", :forgot-password? "Forgot password?"}, :lipas.ice-stadium.conditions {:open-months "Open months in year", :headline "Conditions", :ice-resurfacer-fuel "Ice resurfacer fuel", :stand-temperature-c "Stand temperature (during match)", :ice-average-thickness-mm "Average ice thickness (mm)", :air-humidity-min "Air humidity % min", :daily-maintenances-weekends "Daily maintenances on weekends", :air-humidity-max "Air humidity % max", :daily-maintenances-week-days "Daily maintenances on weekdays", :maintenance-water-temperature-c "Maintenance water temperature", :ice-surface-temperature-c "Ice surface temperature", :weekly-maintenances "Weekly maintenances", :skating-area-temperature-c "Skating area temperature (at 1m height)", :daily-open-hours "Daily open hours", :average-water-consumption-l "Average water consumption (l) / maintenance"}, :map.demographics {:headline "Analysis tool", :tooltip "Analysis tool", :helper-text "Select sports facility on the map.", :copyright1 "Statistics of Finland 2019/2020", :copyright2 "1x1km and 250x250m population grids", :copyright3 "with license"}, :lipas.swimming-pool.slides {:add-slide "Add Slide", :edit-slide "Edit slide", :headline "Slides"}, :notifications {:get-failed "Couldn't get data.", :save-failed "Saving failed", :save-success "Saving succeeded" :ie "Internet Explorer is not a supported browser. Please use another web browser, e.g. Chrome, Firefox or Edge."}, :lipas.swimming-pool.energy-saving {:filter-rinse-water-heat-recovery? "Filter rinse water heat recovery?", :headline "Energy saving", :shower-water-heat-recovery? "Shower water heat recovery?"}, :ice-form {:headline "Report readings", :headline-short "Report readings", :select-rink "Select stadium"}, :restricted {:login-or-register "Please login or register"}, :lipas.ice-stadium.rinks {:add-rink "Add rink", :edit-rink "Edit rink", :headline "Rinks"}, :lipas.sports-site {:properties "Properties", :delete-tooltip "Delete sports facility...", :headline "sports faclities", :new-site-of-type "New {1}", :address "Address", :new-site "New Sports Facility", :phone-number "Phone number", :admin "Admin", :surface-materials "Surface materials", :www "Web-site", :name "Finnish name", :reservations-link "Reservations", :construction-year "Construction year", :type "Type", :delete "Delete {1}", :renovation-years "Renovation years", :name-localized-se "Swedish name", :status "Status", :id "LIPAS-ID", :details-in-portal "Click here to see details", :comment "More information", :ownership "Ownership", :name-short "Name", :basic-data "General", :delete-reason "Reason", :event-date "Modified", :email-public "Email (public)", :add-new "Add Sports Facility", :contact "Contact", :owner "Owner", :marketing-name "Marketing name"}, :status {:active "Active", :planned "Planned" :incorrect-data "Incorrect data", :out-of-service-permanently "Permanently out of service", :out-of-service-temporarily "Temporarily out of service"}, :register {:headline "Register", :link "Sign up here" :thank-you-for-registering "Thank you for registering! You wil receive an email once we've updated your permissions."}, :map.address-search {:title "Find address", :tooltip "Find address"}, :ice-comparison {:headline "Compare"}, :lipas.visitors {:headline "Visitors", :monthly-visitors-in-year "Monthly visitors in {1}", :not-reported "Visitors not reported", :not-reported-monthly "No monthly data", :spectators-count "Spectators count", :total-count "Visitors count"}, :lipas.energy-stats {:headline "Energy consumption in {1}", :energy-reported-for "Electricity, heat and water consumption reported for {1}", :report "Report consumption", :disclaimer "*Based on reported consumption in {1}", :reported "Reported {1}", :cold-mwh "Cold MWh", :hall-missing? "Is your data missing from the diagram?", :not-reported "Not reported {1}", :water-m3 "Water m³", :electricity-mwh "Electricity MWh", :heat-mwh "Heat MWh", :energy-mwh "Energy MWh"}, :map.basemap {:copyright "© National Land Survey", :maastokartta "Terrain", :ortokuva "Satellite", :taustakartta "Default"}, :map.overlay {:tooltip "Other layers" :mml-kiinteisto "Property boundaries" :light-traffic "Light traffic" :retkikartta-snowmobile-tracks "Metsähallitus snowmobile tracks"} :lipas.swimming-pool.pools {:add-pool "Add pool", :edit-pool "Edit pool", :headline "Pools", :structure "Structure"}, :condensate-energy-targets {:hall-heating "Hall heating", :maintenance-water-heating "Maintenance water heating", :other-space-heating "Other heating", :service-water-heating "Service water heating", :snow-melting "Snow melting", :track-heating "Track heating"}, :refrigerants {:CO2 "CO2", :R134A "R134A", :R22 "R22", :R404A "R404A", :R407A "R407A", :R407C "R407C", :R717 "R717"}, :harrastuspassi {:disclaimer "When the option “May be shown in Harrastuspassi.fi” is ticked, the information regarding the sport facility will be transferred automatically to the Harrastuspassi.fi. I agree to update in the Lipas service any changes to information regarding the sport facility. The site administrator is responsible for the accuracy of information and safety of the location. Facility information is shown in Harrastuspassi.fi only if the municipality has a contract with Harrastuspassi.fi service provider."} :retkikartta {:disclaimer "When the option “May be shown in Excursionmap.fi” is ticked, the information regarding the open air exercise location will be transferred once in every 24 hours automatically to the Excursionmap.fi service, maintained by Metsähallitus. I agree to update in the Lipas service any changes to information regarding an open air exercise location. The site administrator is responsible for the accuracy of information, safety of the location, responses to feedback and possible costs related to private roads."}, :reset-password {:change-password "<PASSWORD>", :enter-new-password "<PASSWORD>", :get-new-link "Get new reset link", :headline "Forgot password?", :helper-text "We will email password reset link to you.", :password-helper-text "Password must be at least 6 characters long", :reset-link-sent "Reset link sent! Please check your email!", :reset-success "Password has been reset! Please login with the new password."}, :reports {:contacts "Contacts", :download-as-excel "Download Excel", :select-fields "Select field", :selected-fields "Selected fields", :shortcuts "Shortcuts", :tooltip "Create Excel from search results"}, :heat-sources {:district-heating "District heating", :private-power-station "Private power station"}, :map.import {:headline "Import geometries", :geoJSON "Upload .json file containing FeatureCollection. Coordinates must be in WGS84 format.", :gpx "Coordinates must be in WGS84 format", :supported-formats "Supported formats are {1}", :replace-existing? "Replace existing geometries", :select-encoding "Select encoding", :tab-header "Import", :kml "Coordinates must be in WGS84 format", :shapefile "Import zip file containing .shp .dbf and .prj file.", :import-selected "Import selected", :tooltip "Import from file", :unknown-format "Unkonwn format '{1}'"}, :error {:email-conflict "Email is already in use", :email-not-found "Email address is not registered", :invalid-form "Fix fields marked with red", :no-data "No data", :reset-token-expired "Password reset failed. Link has expired.", :unknown "Unknown error occurred. :/", :user-not-found "User not found.", :username-conflict "Username is already in use"}, :reminders {:description "We will email the message to you at the selected time", :after-one-month "After one month", :placeholder "Remember to check sports-facility \"{1}\" {2}", :select-date "Select date", :tomorrow "Tomorrow", :title "Add reminder", :after-six-months "After six months", :in-a-year "In a year", :message "Message", :in-a-week "In a week"}, :units {:days-in-year "days a year", :hours-per-day "hours a day", :pcs "pcs", :percent "%", :person "person", :times-per-day "times a day", :times-per-week "times a wekk"}, :lipas.energy-consumption {:contains-other-buildings? "Readings contain also other buildings or spaces", :headline "Energy consumption", :yearly "Yearly", :report "Report readings", :electricity "Electricity MWh", :headline-year "Energy consumption in {1}", :monthly? "I want to report monthly energy consumption", :reported-for-year "Energy consumption reported for {1}", :monthly "Monthly", :operating-hours "Operating hours", :not-reported "Energy consumption not reported", :not-reported-monthly "No monthly data available", :heat "Heat (acquired) MWh", :cold "Cold energy (acquired) MWh", :comment "Comment", :water "Water m³", :monthly-readings-in-year "Monthly energy consumption in {1}"}, :ice {:description "Ice stadiums portal contains data about ice stadiums energy consumption and related factors.", :large "Grand hall > 3000 persons", :competition "Competition hall < 3000 persons", :headline "Ice stadiums", :video "Video", :comparison "Compare venues", :size-category "Size category", :basic-data-of-halls "General information about building and facilities", :updating-basic-data "Updating general information", :entering-energy-data "Reporing energy consumption", :small "Small competition hall > 500 persons", :watch "Watch", :video-description "<NAME> - An Energy Efficient Ice Stadium"}, :lipas.location {:address "Address", :city "City", :city-code "City code", :headline "Location", :neighborhood "Neighborhood", :postal-code "Postal code", :postal-office "Postal office"}, :lipas.user.permissions {:admin? "Admin", :all-cities? "Permission to all cities", :all-types? "Permission to all types", :cities "Access to sports faclities in cities", :sports-sites "Access to sports faclities", :types "Access to sports faclities of type"}, :help {:headline "Help", :permissions-help "Please contact us in case you need more permissions", :permissions-help-body "I need permissions to following sports facilities:", :permissions-help-subject "I need more permissions"}, :ceiling-structures {:concrete "Concrete", :double-t-beam "Double-T", :glass "Glass", :hollow-core-slab "Hollow-core slab", :solid-rock "Solid rock", :steel "Steel", :wood "Wood"}, :data-users {:data-user? "Do you use LIPAS-data?", :email-body "Tell us", :email-subject "We also use LIPAS-data", :headline "Data users", :tell-us "Tell us"}, :lipas.swimming-pool.facilities {:showers-men-count "Mens showers count", :lockers-men-count "Mens lockers count", :headline "Other services", :platforms-5m-count "5 m platforms count", :kiosk? "Kiosk / cafeteria", :hydro-neck-massage-spots-count "Neck hydro massage spots count", :lockers-unisex-count "Unisex lockers count", :platforms-10m-count "10 m platforms count", :hydro-massage-spots-count "Other hydro massage spots count", :lockers-women-count "Womens lockers count", :platforms-7.5m-count "7.5 m platforms count", :gym? "Gym", :showers-unisex-count "Unisex showers count", :platforms-1m-count "1 m platforms count", :showers-women-count "Womens showers count", :platforms-3m-count "3 m platforms count"}, :sauna-types {:infrared-sauna "Infrared sauna", :other-sauna "Other sauna", :sauna "Sauna", :steam-sauna "Steam sauna"}, :stats-metrics {:investments "Investments", :net-costs "Net costs", :operating-expenses "Operating expenses", :operating-incomes "Operating incomes", :subsidies "Granted subsidies"}, :refrigerant-solutions {:CO2 "CO2", :H2ONH3 "H2O/NH3", :cacl "CaCl", :ethanol-water "Ethanol-water", :ethylene-glycol "Ethylene glycol", :freezium "Freezium", :water-glycol "Water-glycol"}, :user {:admin-page-link "Admin page", :front-page-link "front page", :greeting "Hello {1} {2}!", :headline "Profile", :ice-stadiums-link "Ice stadiums", :promo-headline "Important", :promo1-text "Swimming pools", :swimming-pools-link "Swimming pools"}, :building-materials {:brick "Brick", :concrete "Concrete", :solid-rock "Solid rock", :steel "Steel", :wood "Wood"}, :stats {:disclaimer-headline "Data sources" :general-disclaimer-1 "Lipas.fi Finland’s sport venues and places, outdoor routes and recreational areas data is open data under license: Attribution 4.0 International (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/deed.en." :general-disclaimer-2 "You are free to use, adapt and share Lipas.fi data in any way, as long as the source is mentioned (Lipas.fi data, University of Jyväskylä, date/year of data upload or relevant information)." :general-disclaimer-3 "Note, that Lipas.fi data is updated by municipalities, other owners of sport facilities and Lipas.fi administrators at the University of Jyväskylä, Finland. Data accuracy, uniformity or comparability between municipalities is not guaranteed. In the Lipas.fi statistics, all material is based on the data in Lipas database and possible missing information may affect the results." :finance-disclaimer "Data on finances of sport and youth sector in municipalities: Statistics Finland open data. The material was downloaded from Statistics Finland's interface service in 2001-2019 with the license CC BY 4.0. Notice, that municipalities are responsible for updating financial information to Statistics Finland’s database. Data uniformity and data comparability between years or between municipalities is not guaranteed." :description "Statistics of sports facilities and related municipality finances", :filter-types "Filter types", :length-km-sum "Total route length km", :headline "Statistics", :select-years "Select years", :browse-to "Go to statistics", :select-issuer "Select issuer", :select-unit "Select unit", :bullet3 "Subsidies", :finance-stats "Finances", :select-city "Select city", :area-m2-min "Min area m²", :filter-cities "Filter cities", :select-metrics "Select metrics", :area-m2-count "Area m² reported count", :show-ranking "Show ranking", :age-structure-stats "Construction years", :subsidies-count "Subsidies count", :area-m2-sum "Total area m²", :select-metric "Select metric", :bullet2 "Sports facility statistics", :area-m2-max "Max area m²", :select-grouping "Grouping", :select-city-service "Select city service", :region "Region", :show-comparison "Show comparison", :length-km-avg "Average route length km", :sports-sites-count "Total count", :length-km-min "Min route length km", :country-avg "(country average)", :length-km-count "Route length reported count", :population "Population", :sports-stats "Sports faclities", :select-cities "Select cities", :subsidies "Subsidies", :select-interval "Select interval", :bullet1 "Economic Figures of Sport and Youth sector", :area-m2-avg "Average area m²", :age-structure "Construction years", :length-km-max "Max route length km", :total-amount-1000e "Total amount (€1000)", :city-stats "City statistics"}, :pool-structures {:concrete "Concrete", :hardened-plastic "Hardened plastic", :steel "Steel"}, :map {:retkikartta-checkbox-reminder "Remember to tick \"May be shown in ExcursionMap.fi\" later in sports facility properties.", :zoom-to-user "Zoom to my location", :remove "Remove", :modify-polygon "Modify area", :draw-polygon "Add area", :retkikartta-problems-warning "Please fix problems displayed on the map in case this route should be visible also in Retkikartta.fi", :edit-later-hint "You can modify geometries later", :center-map-to-site "Center map to sports-facility", :draw-hole "Add hole", :split-linestring "Split", :delete-vertices-hint "Vertices can be deleted by pressing alt-key and clicking.", :calculate-route-length "Calculate route length", :remove-polygon "Remove area", :modify-linestring "Modify route", :download-gpx "Download GPX", :add-to-map "Add to map", :bounding-box-filter "Search from map area", :remove-linestring "Remove route", :draw-geoms "Draw", :confirm-remove "Are you sure you want to delete selected geometry?", :draw "Draw", :draw-linestring "Add route", :modify "You can move the point on the map", :zoom-to-site "Zoom map to sports facility's location", :kink "Self intersection. Please fix either by re-routing or splitting the segment.", :zoom-closer "Please zoom closer"}, :supporting-structures {:brick "Brick", :concrete "Concrete", :concrete-beam "Concrete beam", :concrete-pillar "Concrete pillar", :solid-rock "Solid rock", :steel "Steel", :wood "Wood"}, :owner {:unknown "Unknown", :municipal-consortium "Municipal consortium", :other "Other", :company-ltd "Company ltd", :city "City", :state "State", :registered-association "Registered association", :foundation "Foundation", :city-main-owner "City main owner"}, :menu {:frontpage "Home", :headline "LIPAS", :jyu "University of Jyväskylä", :main-menu "Main menu"}, :dryer-types {:cooling-coil "Cooling coil", :munters "Munters", :none "None"}, :physical-units {:mm "mm", :hour "h", :m3 "m³", :m "m", :temperature-c "Temperature °C", :l "l", :mwh "MWh", :m2 "m²", :celsius "°C"}, :lipas.swimming-pool.water-treatment {:activated-carbon? "Activated carbon", :filtering-methods "Filtering methods", :headline "Water treatment", :ozonation? "Ozonation", :uv-treatment? "UV-treatment"}, :statuses {:edited "{1} (edited)"}, :lipas.user {:email "Email", :permissions "Permissions", :permissions-example "Access to update Jyväskylä ice stadiums.", :saved-searches "Saved searches", :report-energy-and-visitors "Report visitors and energy consumption", :permission-to-cities "You have permission to following cities:", :password "<PASSWORD>", :lastname "Last name", :save-report "Save template", :sports-sites "My sites", :permission-to-all-cities "You have permission to all cities", :username "Username", :history "History", :saved-reports "Saved templates", :contact-info "Contact info", :permission-to-all-types "You have permission to all types", :requested-permissions "Requested permissions", :email-example "<EMAIL>", :permission-to-portal-sites "You have permission to following sports facilities:", :permissions-help "Describe what permissions you wish to have", :report-energy-consumption "Report energy consumption", :firstname "First name", :save-search "Save search", :view-basic-info "View basic info", :no-permissions "You don't have permission to publish changes to any sites.", :username-example "tane12", :permission-to-types "You have permission to following types:"}, :heat-recovery-types {:liquid-circulation "Liquid circulation", :plate-heat-exchanger "Plate heat exchanger", :thermal-wheel "Thermal wheel"}}})
true
(ns lipas.i18n.generated) ;; From csv ;; (def dicts {:fi {:analysis {:headline "Analyysityökalu (beta)" :description "Analyysityökalulla voi arvioida liikuntaolosuhteiden tarjontaa ja saavutettavuutta vertailemalla liikuntapaikan etäisyyttä ja matkustusaikoja suhteessa muihin liikuntapaikkoihin, väestöön sekä oppilaitoksiin." :description2 "Väestöaineistona käytetään Tilastokeskuksen 250x250m ja 1x1km ruutuaineistoja, joista selviää kussakin ruudussa olevan väestön jakauma kolmessa ikäryhmässä (0-14, 15-65, 65-)." :description3 "Matka-aikojen laskeminen eri kulkutavoilla (kävellen, polkupyörällä, autolla) perustuu avoimeen OpenStreetMap-aineistoon ja OSRM-työkaluun." :description4 "Oppilaitosten nimi- ja sijaintitiedot perustuvat Tilastokeskuksen avoimeen aineistoon. Varhaiskasvatusyksiköiden nimi- ja sijaintitiedoissa käytetään LIKES:n keräämää ja luovuttamaa aineistoa." :add-new "Lisää uusi" :distance "Etäisyys" :travel-time "Matka-aika" :zones "Korit" :zone "Kori" :schools "Koulut" :daycare "Varhaiskasvatusyksikkö" :elementary-school "Peruskoulu" :high-school "Lukio" :elementary-and-high-school "Perus- ja lukioasteen koulu" :special-school "Erityiskoulu" :population "Väestö" :direct "Linnuntietä" :by-foot "Kävellen" :by-car "Autolla" :by-bicycle "Polkupyörällä" :analysis-buffer "Analyysialue" :filter-types "Suodata tyypin mukaan" :settings "Asetukset" :settings-map "Kartalla näkyvät kohteet" :settings-zones "Etäisyydet ja matka-ajat" :settings-help "Analyysialue määräytyy suurimman etäisyyskorin mukaan. Myöskään matka-aikoja ei lasketa tämän alueen ulkopuolelta."} :sport {:description "LIPAS tarjoaa ajantasaisen tiedon Suomen julkisista liikuntapaikoista ja virkistyskohteista avoimessa tietokannassa.", :headline "Liikuntapaikat", :open-interfaces "Avoimet rajapinnat", :up-to-date-information "Ajantasainen tieto Suomen liikuntapaikoista", :updating-tools "Päivitystyökalut tiedontuottajille"}, :confirm {:discard-changes? "Tahdotko kumota tekemäsi muutokset?", :headline "Varmistus", :no "Ei", :press-again-to-delete "Varmista painamalla uudestaan", :resurrect? "Tahdotko palauttaa liikuntapaikan aktiiviseksi?", :save-basic-data? "Haluatko tallentaa perustiedot?", :yes "Kyllä"}, :lipas.swimming-pool.saunas {:accessible? "Esteetön", :add-sauna "Lisää sauna", :edit-sauna "Muokkaa saunaa", :headline "Saunat", :men? "Miehet", :women? "Naiset"}, :slide-structures {:concrete "Betoni", :hardened-plastic "Lujitemuovi", :steel "Teräs"}, :lipas.swimming-pool.conditions {:open-days-in-year "Aukiolopäivät vuodessa", :open-hours-mon "Maanantaisin", :headline "Aukiolo", :open-hours-wed "Keskiviikkoisin", :open-hours-thu "Torstaisin", :open-hours-fri "Perjantaisin", :open-hours-tue "Tiistaisin", :open-hours-sun "Sunnuntaisin", :daily-open-hours "Aukiolotunnit päivässä", :open-hours-sat "Lauantaisin"}, :lipas.ice-stadium.ventilation {:dryer-duty-type "Ilmankuivauksen käyttötapa", :dryer-type "Ilmankuivaustapa", :headline "Hallin ilmanvaihto", :heat-pump-type "Lämpöpumpputyyppi", :heat-recovery-efficiency "Lämmöntalteenoton hyötysuhde %", :heat-recovery-type "Lämmöntalteenoton tyyppi"}, :swim {:description "Uimahalliportaali sisältää hallien perus- ja energiankulutustietoja sekä ohjeita energiatehokkuuden parantamiseen.", :latest-updates "Viimeksi päivitetyt tiedot", :headline "Uimahalli​portaali", :basic-data-of-halls "Uimahallien perustiedot", :updating-basic-data "Perustietojen päivitys", :edit "Uimahalli​portaali", :entering-energy-data "Energiankulutustietojen syöttäminen", :list "Hallien tiedot", :visualizations "Hallien vertailu"}, :home-page {:description "Etusivu", :headline "Etusivu"}, :ice-energy {:description "Ajantasaisen tietopaketin löydät Jääkiekkoliiton sivuilta.", :energy-calculator "Jäähallin energialaskuri", :finhockey-link "Siirry Jääkiekkoliiton sivuille", :headline "Energia​info"}, :filtering-methods {:activated-carbon "Aktiivihiili", :coal "Hiili", :membrane-filtration "Kalvosuodatus", :multi-layer-filtering "Monikerrossuodatus", :open-sand "Avohiekka", :other "Muu", :precipitation "Saostus", :pressure-sand "Painehiekka"}, :open-data {:description "Linkit ja ohjeet rajapintojen käyttöön.", :headline "Avoin data", :rest "REST", :wms-wfs "WMS & WFS"}, :lipas.swimming-pool.pool {:accessibility "Saavutettavuus", :outdoor-pool? "Ulkoallas"}, :pool-types {:multipurpose-pool "Monitoimiallas", :whirlpool-bath "Poreallas", :main-pool "Pääallas", :therapy-pool "Terapia-allas", :fitness-pool "Kuntouintiallas", :diving-pool "Hyppyallas", :childrens-pool "Lastenallas", :paddling-pool "Kahluuallas", :cold-pool "Kylmäallas", :other-pool "Muu allas", :teaching-pool "Opetusallas"}, :lipas.ice-stadium.envelope {:base-floor-structure "Alapohjan laatan rakenne", :headline "Vaipan rakenne", :insulated-ceiling? "Yläpohja lämpöeristetty", :insulated-exterior? "Ulkoseinä lämpöeristetty", :low-emissivity-coating? "Yläpohjassa matalaemissiiviteettipinnoite (heijastus/säteily)"}, :disclaimer {:headline "HUOMIO!", :test-version "Tämä on LIPAS-sovelluksen testiversio ja tarkoitettu koekäyttöön. Muutokset eivät tallennu oikeaan Lipakseen."}, :admin {:private-foundation "Yksityinen / säätiö", :city-other "Kunta / muu", :unknown "Ei tietoa", :municipal-consortium "Kuntayhtymä", :private-company "Yksityinen / yritys", :private-association "Yksityinen / yhdistys", :other "Muu", :city-technical-services "Kunta / tekninen toimi", :city-sports "Kunta / liikuntatoimi", :state "Valtio", :city-education "Kunta / opetustoimi"}, :accessibility {:lift "Allasnostin", :low-rise-stairs "Loivat portaat", :mobile-lift "Siirrettävä allasnostin", :slope "Luiska"}, :general {:description "Kuvaus", :hall "Halli", :women "Naiset", :total-short "Yht.", :done "Valmis", :updated "Päivitetty", :name "PI:NAME:<NAME>END_PI", :reported "Ilmoitettu", :type "Tyyppi", :last-modified "Muokattu viimeksi", :here "tästä", :event "Tapahtuma", :structure "Rakenne", :general-info "Yleiset tiedot", :comment "Kommentti", :measures "Mitat", :men "Miehet"}, :dryer-duty-types {:automatic "Automaattinen", :manual "Manuaali"}, :swim-energy {:description "Ajantasaisen tietopaketin löydät UKTY:n ja SUH:n sivuilta.", :headline "Energia​info", :headline-short "Info", :suh-link "Siirry SUH:n sivuille", :ukty-link "Siirry UKTY:n sivuille"}, :time {:two-years-ago "2 vuotta sitten", :date "Päivämäärä", :hour "Tunti", :this-month "Tässä kuussa", :time "Aika", :less-than-hour-ago "Alle tunti sitten", :start "Alkoi", :this-week "Tällä viikolla", :today "Tänään", :month "Kuukausi", :long-time-ago "Kauan sitten", :year "Vuosi", :just-a-moment-ago "Hetki sitten", :yesterday "Eilen", :three-years-ago "3 vuotta sitten", :end "Päättyi", :this-year "Tänä vuonna", :last-year "Viime vuonna"}, :ice-resurfacer-fuels {:LPG "Nestekaasu", :electicity "Sähkö", :gasoline "Bensiini", :natural-gas "Maakaasu", :propane "Propaani"}, :ice-rinks {:headline "Hallien tiedot"}, :month {:sep "Syyskuu", :jan "Tammikuu", :jun "Kesäkuu", :oct "Lokakuu", :jul "Heinäkuu", :apr "Huhtikuu", :feb "Helmikuu", :nov "Marraskuu", :may "Toukokuu", :mar "Maaliskuu", :dec "Joulukuu", :aug "Elokuu"}, :type {:name "Liikuntapaikkatyyppi", :main-category "Pääryhmä", :sub-category "Alaryhmä", :type-code "Tyyppikoodi"}, :duration {:hour "tuntia", :month "kuukautta", :years "vuotta", :years-short "v"}, :size-categories {:competition "Kilpahalli < 3000 hlö", :large "Suurhalli > 3000 hlö", :small "Pieni kilpahalli > 500 hlö"}, :lipas.admin {:access-all-sites "Sinulla on pääkäyttäjän oikeudet. Voit muokata kaikkia liikuntapaikkoja.", :confirm-magic-link "Haluatko varmasti lähettää taikalinkin käyttäjälle {1}?", :headline "Admin", :magic-link "Taikalinkki", :select-magic-link-template "Valitse saatekirje", :send-magic-link "Taikalinkki käyttäjälle {1}", :users "Käyttäjät"}, :lipas.ice-stadium.refrigeration {:headline "Kylmätekniikka", :refrigerant-solution-amount-l "Rataliuoksen määrä (l)", :individual-metering? "Alamittaroitu", :original? "Alkuperäinen", :refrigerant "Kylmäaine", :refrigerant-solution "Rataliuos", :condensate-energy-main-targets "Lauhdelämmön pääkäyttökohde", :power-kw "Kylmäkoneen sähköteho (kW)", :condensate-energy-recycling? "Lauhde-energia hyötykäytetty", :refrigerant-amount-kg "Kylmäaineen määrä (kg)"}, :lipas.building {:headline "Rakennus", :total-volume-m3 "Bruttotilavuus m³", :staff-count "Henkilökunnan lukumäärä", :piled? "Paalutettu", :heat-sections? "Allastila on jaettu lämpötilaosioihin", :total-ice-area-m2 "Jääpinta-ala m²", :main-construction-materials "Päärakennusmateriaalit", :main-designers "Pääsuunnittelijat", :total-pool-room-area-m2 "Allashuoneen pinta-ala m²", :heat-source "Lämmönlähde", :total-surface-area-m2 "Bruttopinta-ala m² (kokonaisala)", :total-water-area-m2 "Vesipinta-ala m²", :ceiling-structures "Yläpohjan rakenteet", :supporting-structures "Kantavat rakenteet", :seating-capacity "Katsomokapasiteetti"}, :heat-pump-types {:air-source "Ilmalämpöpumppu", :air-water-source "Ilma-vesilämpöpumppu", :exhaust-air-source "Poistoilmalämpöpumppu", :ground-source "Maalämpöpumppu", :none "Ei lämpöpumppua"}, :search {:table-view "Näytä hakutulokset taulukossa", :headline "Haku", :results-count "{1} hakutulosta", :placeholder "Etsi...", :retkikartta-filter "Retkikartta.fi-kohteet", :harrastuspassi-filter "Harrastuspassi.fi-kohteet", :filters "Rajaa hakua", :search-more "Hae lisää...", :page-size "Näytä kerralla", :search "Hae", :permissions-filter "Näytä kohteet joita voin muokata", :display-closest-first "Näytä lähimmät kohteet ensin", :list-view "Näytä hakutulokset listana", :pagination "Tulokset {1}-{2}", :school-use-filter "Koulujen liikuntapaikat", :clear-filters "Poista rajaukset"}, :map.tools {:drawing-tooltip "Piirtotyökalu valittu", :drawing-hole-tooltip "Reikäpiirtotyökalu valittu", :edit-tool "Muokkaustyökalu", :importing-tooltip "Tuontityökalu valittu", :deleting-tooltip "Poistotyökalu valittu", :splitting-tooltip "Katkaisutyökalu valittu"}, :partners {:headline "Kehittä​misessä mukana"}, :actions {:duplicate "Kopioi", :resurrect "Palauta", :select-year "Valitse vuosi", :select-owners "Valitse omistajat", :select-admins "Valitse ylläpitäjät", :select-tool "Valitse työkalu", :save-draft "Tallenna luonnos", :redo "Tee uudelleen", :open-main-menu "Avaa päävalikko", :back-to-listing "Takaisin listaukseen", :filter-surface-materials "Rajaa pintamateriaalit", :browse "siirry", :select-type "Valitse tyyppi", :edit "Muokkaa", :filter-construction-year "Rajaa rakennusvuodet", :submit "Lähetä", :choose-energy "Valitse energia", :delete "Poista", :browse-to-map "Siirry kartalle", :save "Tallenna", :close "Sulje", :filter-area-m2 "Rajaa liikuntapinta-ala m²", :show-account-menu "Avaa käyttäjävalikko", :fill-required-fields "Täytä pakolliset kentät", :undo "Kumoa", :browse-to-portal "Siirry portaaliin", :download-excel "Lataa Excel", :fill-data "Täytä tiedot", :select-statuses "Liikuntapaikan tila", :select-cities "Valitse kunnat", :select-hint "Valitse...", :discard "Kumoa", :more "Lisää...", :cancel "Peruuta", :select-columns "Valitse tietokentät", :add "Lisää", :show-all-years "Näytä kaikki vuodet", :download "Lataa", :select-hall "Valitse halli", :clear-selections "Poista valinnat", :select "Valitse", :select-types "Valitse tyypit"}, :dimensions {:area-m2 "Pinta-ala m²", :depth-max-m "Syvyys max m", :depth-min-m "Syvyys min m", :length-m "Pituus m", :surface-area-m2 "Pinta-ala m²", :volume-m3 "Tilavuus m³", :width-m "Leveys m"}, :login {:headline "Kirjaudu", :login-here "täältä", :login-with-password "Kirjaudu salasanalla", :password "PI:PASSWORD:<PASSWORD>END_PI", :logout "Kirjaudu ulos", :username "Sähköposti / PI:PASSWORD:<PASSWORD>END_PI", :login-help "Jos olet jo LIPAS-käyttäjä, voit tilata suoran sisäänkirjautumislinkin sähköpostiisi", :login "Kirjaudu", :magic-link-help "Jos olet jo LIPAS-käyttäjä, voit tilata suoran sisäänkirjautumislinkin sähköpostiisi. Linkkiä käyttämällä sinun ei tarvitse muistaa salasanaasi.", :order-magic-link "Lähetä linkki sähköpostiini", :login-with-magic-link "Kirjaudu sähköpostilla", :bad-credentials "Käyttäjätunnus tai salasana ei kelpaa", :magic-link-ordered "Linkki on lähetetty ja sen pitäisi saapua sähköpostiisi parin minuutin sisällä. Tarkistathan myös roskapostin!", :username-example "PI:EMAIL:<EMAIL>END_PI", :forgot-password? "PI:PASSWORD:<PASSWORD>END_PI?"}, :lipas.ice-stadium.conditions {:open-months "Aukiolokuukaudet vuodessa", :headline "Käyttöolosuhteet", :ice-resurfacer-fuel "Jäänhoitokoneen polttoaine", :stand-temperature-c "Katsomon tavoiteltu keskilämpötila ottelun aikana", :ice-average-thickness-mm "Jään keskipaksuus mm", :air-humidity-min "Ilman suhteellinen kosteus % min", :daily-maintenances-weekends "Jäähoitokerrat viikonlppuina", :air-humidity-max "Ilman suhteellinen kosteus % max", :daily-maintenances-week-days "Jäähoitokerrat arkipäivinä", :maintenance-water-temperature-c "Jäähoitoveden lämpötila (tavoite +40)", :ice-surface-temperature-c "Jään pinnan lämpötila", :weekly-maintenances "Jäänhoitokerrat viikossa", :skating-area-temperature-c "Luistelualueen lämpötila 1 m korkeudella", :daily-open-hours "Käyttötunnit päivässä", :average-water-consumption-l "Keskimääräinen jäänhoitoon käytetty veden määrä (per ajo)"}, :map.demographics {:headline "Analyysityökalu", :tooltip "Analyysityökalu", :helper-text "Valitse liikuntapaikka kartalta tai lisää uusi analysoitava kohde ", :copyright1 "Väestötiedoissa käytetään Tilastokeskuksen vuoden 2019", :copyright2 "1x1 km ruutuaineistoa", :copyright3 "lisenssillä" :copyright4 ", sekä vuoden 2020 250x250m ruutuaineistoa suljetulla lisenssillä."}, :lipas.swimming-pool.slides {:add-slide "Lisää liukumäki", :edit-slide "Muokkaa liukumäkeä", :headline "Liukumäet"}, :notifications {:get-failed "Tietojen hakeminen epäonnistui.", :save-failed "Tallennus epäonnistui", :save-success "Tallennus onnistui" :ie (str "Internet Explorer ei ole tuettu selain. " "Suosittelemme käyttämään toista selainta, " "esim. Chrome, Firefox tai Edge.")}, :lipas.swimming-pool.energy-saving {:filter-rinse-water-heat-recovery? "Suodattimien huuhteluveden lämmöntalteenotto", :headline "Energian​säästö​toimet", :shower-water-heat-recovery? "Suihkuveden lämmöntalteenotto"}, :ice-form {:headline "Nestekaasu", :headline-short "Sähkö", :select-rink "Nestekaasu"}, :restricted {:login-or-register "Kirjaudu sisään tai rekisteröidy"}, :lipas.ice-stadium.rinks {:add-rink "Lisää rata", :edit-rink "Muokkaa rataa", :headline "Radat"}, :lipas.sports-site {:properties "Lisätiedot", :delete-tooltip "Poista liikuntapaikka...", :headline "Liikuntapaikka", :new-site-of-type "Uusi {1}", :address "Osoite", :new-site "Uusi liikuntapaikka", :phone-number "Puhelinnumero", :admin "Ylläpitäjä", :surface-materials "Pintamateriaalit", :www "Web-sivu", :name "Nimi suomeksi", :reservations-link "Tilavaraukset", :construction-year "Rakennus​vuosi", :type "Tyyppi", :delete "Poista {1}", :renovation-years "Perus​korjaus​vuodet", :name-localized-se "Nimi ruotsiksi", :status "Liikuntapaikan tila", :id "LIPAS-ID", :details-in-portal "Näytä kaikki lisätiedot", :comment "Lisätieto", :ownership "Omistus", :name-short "Nimi", :basic-data "Perustiedot", :delete-reason "Poiston syy", :event-date "Muokattu", :email-public "Sähköposti (julkinen)", :add-new "Lisää liikuntapaikka", :contact "Yhteystiedot", :owner "Omistaja", :marketing-name "PI:NAME:<NAME>END_PI"}, :status {:active "Toiminnassa", :planned "Suunniteltu" :incorrect-data "Väärä tieto", :out-of-service-permanently "Poistettu käytöstä pysyvästi", :out-of-service-temporarily "Poistettu käytöstä väliaikaisesti"}, :register {:headline "Rekisteröidy", :link "Rekisteröidy" :thank-you-for-registering "Kiitos rekisteröitymisestä! Saat sähköpostiisi viestin kun sinulle on myönnetty käyttöoikeudet."}, :map.address-search {:title "Etsi osoite", :tooltip "Etsi osoite"}, :ice-comparison {:headline "Hallien vertailu"}, :lipas.visitors {:headline "Kävijämäärät", :monthly-visitors-in-year "Kuukausittaiset kävijämäärät vuonna {1}", :not-reported "Ei kävijämäärätietoja", :not-reported-monthly "Ei kuukausitason tietoja", :spectators-count "Katsojamäärä", :total-count "Käyttäjämäärä"}, :lipas.energy-stats {:headline "Hallien energiankulutus vuonna {1}", :energy-reported-for "Sähkön-, lämmön- ja vedenkulutus ilmoitettu vuodelta {1}", :report "Ilmoita lukemat", :disclaimer "*Perustuu ilmoitettuihin kulutuksiin vuonna {1}", :reported "Ilmoitettu {1}", :cold-mwh "Kylmä MWh", :hall-missing? "Puuttuvatko hallisi tiedot kuvasta?", :not-reported "Ei tietoa {1}", :water-m3 "Vesi m³", :electricity-mwh "Sähkö MWh", :heat-mwh "Lämpö MWh", :energy-mwh "Sähkö + lämpö MWh"}, :map.basemap {:copyright "© Maanmittauslaitos", :maastokartta "Maastokartta", :ortokuva "Ilmakuva", :taustakartta "Taustakartta"}, :map.overlay {:tooltip "Muut karttatasot" :mml-kiinteisto "Kiinteistörajat" :light-traffic "Kevyen liikenteen väylät" :retkikartta-snowmobile-tracks "Metsähallituksen moottorikelkkaurat"} :lipas.swimming-pool.pools {:add-pool "Lisää allas", :edit-pool "Muokkaa allasta", :headline "Altaat", :structure "Rakenne"}, :condensate-energy-targets {:hall-heating "Hallin lämmitys", :maintenance-water-heating "Jäänhoitoveden lämmitys", :other-space-heating "Muun tilan lämmitys", :service-water-heating "Käyttöveden lämmitys", :snow-melting "Lumensulatus", :track-heating "Ratapohjan lämmitys"}, :refrigerants {:CO2 "CO2 (hiilidioksidi)", :R134A "R134A", :R22 "R22", :R404A "R404A", :R407A "R407A", :R407C "R407C", :R717 "R717"}, :harrastuspassi {:disclaimer "Kun ”saa julkaista Harrastuspassissa” – ruutu on rastitettu, liikuntapaikan tiedot siirretään automaattisesti Harrastuspassi-palveluun. Sitoudun päivittämään liikuntapaikan tietojen muutokset viipymättä Lippaaseen. Paikan hallinnoijalla on vastuu tietojen oikeellisuudesta ja paikan turvallisuudesta. Tiedot näkyvät Harrastuspassissa vain, mikäli kunnalla on sopimus Harrastuspassin käytöstä Harrastuspassin palveluntuottajan kanssa."} :retkikartta {:disclaimer "Kun ”Saa julkaista Retkikartassa” -ruutu on rastitettu, luontoliikuntapaikan tiedot siirretään automaattisesti Metsähallituksen ylläpitämään Retkikartta.fi -karttapalveluun kerran vuorokaudessa. Sitoudun päivittämään luontoliikuntapaikan tietojen muutokset viipymättä Lippaaseen. Paikan hallinnoijalla on vastuu tietojen oikeellisuudesta, paikan turvallisuudesta, palautteisiin vastaamisesta ja mahdollisista yksityisteihin liittyvistä kustannuksista."}, :reset-password {:change-password "PI:PASSWORD:<PASSWORD>END_PI", :enter-new-password "PI:PASSWORD:<PASSWORD>END_PI", :get-new-link "Tilaa uusi vaihtolinkki", :headline "Unohtuiko salasana?", :helper-text "Lähetämme salasanan vaihtolinkin sinulle sähköpostitse.", :password-helper-text "Salasanassa on oltava vähintään 6 merkkiä", :reset-link-sent "Linkki lähetetty! Tarkista sähköpostisi.", :reset-success "Salasana vaihdettu! Kirjaudu sisään uudella salasanalla."}, :reports {:contacts "Yhteys​tiedot", :download-as-excel "Luo raportti", :select-fields "Valitse raportin kentät", :selected-fields "Valitut kentät", :shortcuts "Pikavalinnat", :tooltip "Luo Excel-raportti hakutuloksista"}, :heat-sources {:district-heating "Kaukolämpö", :private-power-station "Oma voimalaitos"}, :map.import {:headline "Tuo geometriat", :geoJSON "Tuo .json-tiedosto, joka sisältää GeoJSON FeatureCollection -objektin. Lähtöaineiston pitää olla WGS84-koordinaatistossa.", :gpx "Lähtöaineiston pitää olla WGS84-koordinaatistossa.", :supported-formats "Tuetut tiedostomuodot ovat {1}", :replace-existing? "Korvaa nykyiset geometriat", :select-encoding "Valitse merkistö", :tab-header "Tuo tiedostosta", :kml "Lähtöaineiston pitää olla WGS84 koordinaatistossa.", :shapefile "Tuo .shp-, .dbf- ja .prj-tiedostot pakattuna .zip-muotoon.", :import-selected "Tuo valitut", :tooltip "Tuo geometriat tiedostosta", :unknown-format "Tuntematon tiedostopääte '{1}'"}, :error {:email-conflict "Sähköpostiosoite on jo käytössä", :email-not-found "Sähköpostiosoitetta ei ole rekisteröity.", :invalid-form "Korjaa punaisella merkityt kohdat", :no-data "Ei tietoja", :reset-token-expired "Salasanan vaihto epäonnistui. Linkki on vanhentunut.", :unknown "Tuntematon virhe tapahtui. :/", :user-not-found "Käyttäjää ei löydy.", :username-conflict "Käyttäjätunnus on jo käytössä"}, :reminders {:description "Viesti lähetetään sähköpostiisi valittuna ajankohtana", :after-one-month "Kuukauden kuluttua", :placeholder "Muista tarkistaa liikuntapaikka \"{1}\" {2}", :select-date "Valitse päivämäärä", :tomorrow "Huomenna", :title "Lisää muistutus", :after-six-months "Puolen vuoden kuluttua", :in-a-year "Vuoden kuluttua", :message "Viesti", :in-a-week "Viikon kuluttua"}, :units {:days-in-year "päivää vuodessa", :hours-per-day "tuntia päivässä", :pcs "kpl", :percent "%", :person "hlö", :times-per-day "kertaa päivässä", :times-per-week "kertaa viikossa"}, :lipas.energy-consumption {:contains-other-buildings? "Energialukemat sisältävät myös muita rakennuksia tai tiloja", :headline "Energian​kulutus", :yearly "Vuositasolla*", :report "Ilmoita lukemat", :electricity "Sähköenergia MWh", :headline-year "Lukemat vuonna {1}", :monthly? "Haluan ilmoittaa energiankulutuksen kuukausitasolla", :reported-for-year "Vuoden {1} energiankulutus ilmoitettu", :monthly "Kuukausitasolla", :operating-hours "Käyttötunnit", :not-reported "Ei energiankulutustietoja", :not-reported-monthly "Ei kuukausikulutustietoja", :heat "Lämpöenergia (ostettu) MWh", :cold "Kylmäenergia (ostettu) MWh", :comment "Kommentti", :water "Vesi m³", :monthly-readings-in-year "Kuukausikulutukset vuonna {1}"}, :ice {:description "Jäähalliportaali sisältää hallien perus- ja energiankulutustietoja sekä ohjeita energiatehokkuuden parantamiseen.", :large "Suurhalli > 3000 hlö", :competition "Kilpahalli < 3000 hlö", :headline "Jäähalli​portaali", :video "Video", :comparison "Hallien vertailu", :size-category "Kokoluokitus", :basic-data-of-halls "Jäähallien perustiedot", :updating-basic-data "Perustietojen päivitys", :entering-energy-data "Energiankulutustietojen syöttäminen", :small "Pieni kilpahalli > 500 hlö", :watch "Katso", :video-description "Pihlajalinna Areena on energiatehokas jäähalli"}, :lipas.location {:address "Katuosoite", :city "Kunta", :city-code "Kuntanumero", :headline "Sijainti", :neighborhood "Kuntaosa", :postal-code "Postinumero", :postal-office "Postitoimipaikka"}, :lipas.user.permissions {:admin? "Admin", :all-cities? "Oikeus kaikkiin kuntiin", :all-types? "Oikeus kaikkiin tyyppeihin", :cities "Kunnat", :sports-sites "Liikuntapaikat", :types "Tyypit"}, :help {:headline "Ohjeet", :permissions-help "Jos haluat lisää käyttöoikeuksia, ota yhteyttä ", :permissions-help-body "Haluan käyttöoikeudet seuraaviin liikuntapaikkoihin:", :permissions-help-subject "Haluan lisää käyttöoikeuksia"}, :ceiling-structures {:concrete "Betoni", :double-t-beam "TT-laatta", :glass "Lasi", :hollow-core-slab "Ontelolaatta", :solid-rock "Kallio", :steel "Teräs", :wood "Puu"}, :data-users {:data-user? "Käytätkö LIPAS-dataa?", :email-body "Mukavaa että hyödynnät LIPAS-dataa! Kirjoita tähän kuka olet ja miten hyödynnät Lipasta. Käytätkö mahdollisesti jotain rajapinnoistamme?", :email-subject "Mekin käytämme LIPAS-dataa", :headline "Lipasta hyödyntävät", :tell-us "Kerro siitä meille"}, :lipas.swimming-pool.facilities {:showers-men-count "Miesten suihkut lkm", :lockers-men-count "Miesten pukukaapit lkm", :headline "Muut palvelut", :platforms-5m-count "5 m hyppypaikkojen lkm", :kiosk? "Kioski / kahvio", :hydro-neck-massage-spots-count "Niskahierontapisteiden lkm", :lockers-unisex-count "Unisex pukukaapit lkm", :platforms-10m-count "10 m hyppypaikkojen lkm", :hydro-massage-spots-count "Muiden hierontapisteiden lkm", :lockers-women-count "Naisten pukukaapit lkm", :platforms-7.5m-count "7.5 m hyppypaikkojen lkm", :gym? "Kuntosali", :showers-unisex-count "Unisex suihkut lkm", :platforms-1m-count "1 m hyppypaikkojen lkm", :showers-women-count "Naisten suihkut lkm", :platforms-3m-count "3 m hyppypaikkojen lkm"}, :sauna-types {:infrared-sauna "Infrapunasauna", :other-sauna "Muu sauna", :sauna "Sauna", :steam-sauna "Höyrysauna"}, :stats-metrics {:investments "Investoinnit", :net-costs "Nettokustannukset", :operating-expenses "Käyttökustannukset", :operating-incomes "Käyttötuotot", :subsidies "Kunnan myöntämät avustukset"}, :refrigerant-solutions {:CO2 "CO2", :H2ONH3 "H2O/NH3", :cacl "CaCl", :ethanol-water "Etanoli-vesi", :ethylene-glycol "Etyleeniglykoli", :freezium "Freezium", :water-glycol "Vesi-glykoli"}, :user {:headline "Oma sivu", :admin-page-link "Siirry admin-sivulle", :promo1-link "Näytä TEAviisari-kohteet jotka voin päivittää", :swimming-pools-link "Uimahallit", :promo-headline "Ajankohtaista", :front-page-link "Siirry etusivulle", :promo1-text "Opetus- ja kulttuuriministeriö pyytää kuntia täydentämään erityisesti sisäliikuntapaikkojen rakennusvuosien ja peruskorjausvuosien tiedot. Tieto on tärkeää mm. liikuntapaikkojen korjausvelkaa arvioitaessa.", :ice-stadiums-link "Jäähallit", :greeting "Hei {1} {2}!", :promo1-topic "Kiitos että käytät Lipas.fi-palvelua!"}, :building-materials {:brick "Tiili", :concrete "Betoni", :solid-rock "Kallio", :steel "Teräs", :wood "Puu"}, :stats {:disclaimer-headline "Tietolähde" :general-disclaimer-1 "Lipas.fi – Suomen liikuntapaikat, ulkoilureitit ja virkistysalueet: Nimeä 4.0 Kansainvälinen (CC BY 4.0)." :general-disclaimer-2 "Voit vapaasti käyttää, kopioida, jakaa ja muokata aineistoa. Aineistolähteeseen tulee viitata esimerkiksi näin: Liikuntapaikat: Lipas.fi Jyväskylän yliopisto, otospäivä. Lisätietoja Creative Commons. https://creativecommons.org/licenses/by/4.0/deed.fi" :general-disclaimer-3 "Huomaa, että Lipas-tietokannan tiedot perustuvat kuntien ja muiden liikuntapaikkojen omistajien Lipas-tietokantaan syöttämiin tietoihin sekä Jyväskylän yliopiston Lipas-ylläpitäjien tuottamaan aineistoon. Tietojen kattavuutta, virheettömyyttä, ajantasaisuutta ja yhdenmukaisuutta ei voida taata. Lipas.fi –tilastot -osiossa tilastojen laskenta perustuu tietokantaan tallennettuihin tietoihin. Mahdolliset puuttuvat tiedot vaikuttavat laskelmiin." :finance-disclaimer "Aineistolähde: Tilastokeskus avoimet tilastoaineistot. Huomaa, että kunnat vastaavat itse virallisten taloustietojensa tallentamisesta Tilastokeskuksen tietokantaan Tilastokeskuksen ohjeiden perusteella. Tietojen yhdenmukaisuudesta tai aikasarjojen jatkuvuudesta ei voida antaa takeita." :description "Kuntien viralliset tilinpäätöstiedot liikunta- ja nuorisotoimien osalta. Kunta voi seurata omaa menokehitystään ja vertailla sitä muihin kuntiin.", :filter-types "Rajaa tyypit", :length-km-sum "Liikuntareittien pituus km yhteensä", :headline "Tilastot", :select-years "Valitse vuodet", :browse-to "Siirry tilastoihin", :select-issuer "Valitse myöntäjä", :select-unit "Valitse yksikkö", :bullet3 "Avustukset", :finance-stats "Talous​tiedot", :select-city "Valitse kunta", :area-m2-min "Liikuntapinta-ala m² min", :filter-cities "Rajaa kunnat", :select-metrics "Valitse suureet", :area-m2-count "Liikuntapinta-ala m² ilmoitettu lkm", :show-ranking "Näytä ranking", :age-structure-stats "Rakennus​vuodet", :subsidies-count "Avustusten lkm", :area-m2-sum "Liikuntapinta-ala m² yhteensä", :select-metric "Valitse suure", :bullet2 "Liikuntapaikkatilastot", :area-m2-max "Liikuntapinta-ala m² max", :select-grouping "Ryhmittely", :select-city-service "Valitse toimi", :region "Alue", :show-comparison "Näytä vertailu", :length-km-avg "Liikuntareitin pituus km keskiarvo", :sports-sites-count "Liikuntapaikkojen lkm", :length-km-min "Liikuntareitin pituus km min", :country-avg "(maan keskiarvo)", :length-km-count "Liikuntareitin pituus ilmoitettu lkm", :population "Asukasluku", :sports-stats "Liikunta​paikat", :select-cities "Valitse kunnat", :subsidies "Avustukset", :select-interval "Valitse aikaväli", :bullet1 "Liikunta- ja nuorisotoimen taloustiedot", :area-m2-avg "Liikuntapinta-ala m² keskiarvo", :age-structure "Liikunta​paikkojen rakennus​vuodet", :length-km-max "Liikuntareitin pituus km max", :total-amount-1000e "Yht. (1000 €)", :city-stats "Kunta​tilastot"}, :pool-structures {:concrete "Betoni", :hardened-plastic "Lujitemuovi", :steel "Teräs"}, :map {:retkikartta-checkbox-reminder "Muista myös valita \"Saa julkaista Retkikartta.fi -palvelussa\" ruksi seuraavan vaiheen lisätiedoissa.\"", :zoom-to-user "Kohdista sijaintiini", :remove "Poista", :modify-polygon "Muokkaa aluetta", :draw-polygon "Lisää alue", :retkikartta-problems-warning "Korjaa kartalle merkityt ongelmat, jos haluat, että kohde siirtyy Retkikartalle.", :edit-later-hint "Voit muokata geometriaa myös myöhemmin", :center-map-to-site "Kohdista kartta liikuntapaikkaan", :draw-hole "Lisää reikä", :split-linestring "Katkaise reittiosa", :delete-vertices-hint "Yksittäisiä pisteitä voi poistaa pitämällä alt-näppäintä pohjassa ja klikkaamalla pistettä.", :calculate-route-length "Laske reitin pituus automaattisesti", :remove-polygon "Poista alue", :modify-linestring "Muokkaa reittiä", :download-gpx "Lataa GPX", :add-to-map "Lisää kartalle", :bounding-box-filter "Hae kartan alueelta", :remove-linestring "Poista reittiosa", :draw-geoms "Piirrä", :confirm-remove "Haluatko varmasti poistaa valitun geometrian?", :draw "Lisää kartalle", :draw-linestring "Lisää reittiosa", :modify "Voit raahata pistettä kartalla", :zoom-to-site "Kohdista kartta liikuntapaikkaan", :kink "Muuta reitin kulkua niin, että reittiosa ei risteä itsensä kanssa. Voit tarvittaessa katkaista reitin useampaan osaan.", :zoom-closer "Kartta täytyy zoomata lähemmäs"}, :supporting-structures {:brick "Tiili", :concrete "Betoni", :concrete-beam "Betonipalkki", :concrete-pillar "Betonipilari", :solid-rock "Kallio", :steel "Teräs", :wood "Puu"}, :owner {:unknown "Ei tietoa", :municipal-consortium "Kuntayhtymä", :other "Muu", :company-ltd "Yritys", :city "Kunta", :state "Valtio", :registered-association "Rekisteröity yhdistys", :foundation "Säätiö", :city-main-owner "Kuntaenemmistöinen yritys"}, :menu {:frontpage "Etusivu", :headline "LIPAS", :jyu "Jyväskylän yliopisto", :main-menu "Päävalikko"}, :dryer-types {:cooling-coil "Jäähdytyspatteri", :munters "Muntters", :none "Ei ilmankuivausta"}, :physical-units {:mm "mm", :hour "h", :m3 "m³", :m "m", :temperature-c "Lämpötila °C", :l "l", :mwh "MWh", :m2 "m²", :celsius "°C"}, :lipas.swimming-pool.water-treatment {:activated-carbon? "Aktiivihiili", :filtering-methods "Suodatustapa", :headline "Vedenkäsittely", :ozonation? "Otsonointi", :uv-treatment? "UV-käsittely"}, :statuses {:edited "{1} (muokattu)"}, :lipas.user {:email "Sähköposti", :permissions "Käyttöoikeudet", :permissions-example "Oikeus päivittää Jyväskylän jäähallien tietoja.", :saved-searches "Tallennetut haut", :report-energy-and-visitors "Ilmoita energia- ja kävijämäärätiedot", :permission-to-cities "Sinulla on käyttöoikeus seuraaviin kuntiin:", :password "PI:PASSWORD:<PASSWORD>END_PI", :lastname "PI:NAME:<NAME>END_PI", :save-report "Tallenna raporttipohja", :sports-sites "Omat kohteet", :permission-to-all-cities "Sinulla on käyttöoikeus kaikkiin kuntiin", :username "Käyttäjätunnus", :history "Historia", :saved-reports "Tallennetut raporttipohjat", :contact-info "Yhteystiedot", :permission-to-all-types "Sinulla on käyttöoikeus kaikkiin liikuntapaikkatyyppeihin", :requested-permissions "Pyydetyt oikeudet", :email-example "PI:EMAIL:<EMAIL>END_PI", :permission-to-portal-sites "Sinulla on käyttöoikeus seuraaviin yksittäisiin liikuntapaikkoihin:", :permissions-help "Kerro, mitä tietoja haluat päivittää Lipaksessa", :report-energy-consumption "Ilmoita energiankulutus", :firstname "PI:NAME:<NAME>END_PI", :save-search "Tallenna haku", :view-basic-info "Tarkista perustiedot", :no-permissions "Sinulle ei ole vielä myönnetty käyttöoikeuksia.", :username-example "tane12", :permission-to-types "Sinulla on käyttöoikeus seuraaviin liikuntapaikkatyyppeihin:"}, :heat-recovery-types {:liquid-circulation "Nestekierto", :plate-heat-exchanger "Levysiirrin", :thermal-wheel "Pyörivä"}}, :se {:sport {:description "LIPAS är en landsomfattande databas för offentliga finländska idrottsplatser.", :headline "Idrottsanläggningar", :open-interfaces "Öppna gränssnitt", :up-to-date-information "Aktuell data om finska idrottsanläggningar", :updating-tools "Uppdateringsverktyg"}, :confirm {:discard-changes? "Vill du förkasta ändringar?", :headline "Bekräftelse", :no "Nej", :press-again-to-delete "Klicka igen för att radera", :resurrect? "Vill du spara grunddata?", :save-basic-data? "Vill du spara grunddata?", :yes "Ja"}, :lipas.swimming-pool.saunas {:accessible? "Tillgängligt", :add-sauna "Lägg till en bastu", :edit-sauna "Redigera bastun", :headline "Bastur", :men? "Män", :women? "Kvinnor"}, :slide-structures {:concrete "Betong", :hardened-plastic "Öppna gränssnitt", :steel "Stål"}, :lipas.swimming-pool.conditions {:open-days-in-year "Fredagar", :open-hours-mon "Måndagar", :headline "Öppettider", :open-hours-wed "Onsdagar", :open-hours-thu "Torsdagar", :open-hours-fri "Fredagar", :open-hours-tue "Tisdagar", :open-hours-sun "Söndagar", :daily-open-hours "Dagliga öppettider", :open-hours-sat "Lördagar"}, :lipas.ice-stadium.ventilation {:dryer-duty-type "Gatuadress", :dryer-type "Kommun", :heat-pump-type "Gatuadress", :heat-recovery-efficiency "Kommun", :heat-recovery-type "Gatuadress"}, :swim {:basic-data-of-halls "Simhallsportal", :edit "Simhallsportal", :entering-energy-data "Datum", :headline "Simhallsportal", :latest-updates "Timme", :list "Energi information", :updating-basic-data "Information", :visualizations "Energi information"}, :home-page {:description "LIPAS-system innehåller information av idrottsanläggningar, idrottsrutter och friluftsregioner. Data är öppen CC4.0 International.", :headline "Startsida"}, :ice-energy {:finhockey-link "El", :headline "Bensin"}, :filtering-methods {:activated-carbon "Kol", :coal "Kol", :membrane-filtration "Annat", :open-sand "Annat", :other "Annat", :precipitation "Beskrivning", :pressure-sand "Kommentar"}, :open-data {:description "Länkar och information om gränssnitten", :headline "Öppna data", :rest "REST", :wms-wfs "WMS & WFS"}, :lipas.swimming-pool.pool {:accessibility "Tillgänglighet", :outdoor-pool? "Utomhus simbassäng"}, :pool-types {:multipurpose-pool "Allaktivitetsbassäng", :whirlpool-bath "Bubbelbad", :main-pool "Huvudsbassäng", :therapy-pool "Terapibassäng", :fitness-pool "Konditionsbassäng", :diving-pool "Hoppbassäng", :childrens-pool "Barnbassäng", :paddling-pool "Plaskdamm", :cold-pool "Kallbassäng", :other-pool "Annan bassäng", :teaching-pool "Undervisningsbassäng"}, :disclaimer {:headline "OBS!", :test-version "Automatisk"}, :admin {:private-foundation "Privat / stiftelse", :city-other "Kommun / annat", :unknown "Okänt", :municipal-consortium "Samkommun", :private-company "Privat / företag", :private-association "Privat / förening", :other "Annat", :city-technical-services "Kommun / teknisk väsende", :city-sports "Kommun/ idrottsväsende", :state "Stat", :city-education "Kommun / utbildingsväsende"}, :accessibility {:lift "Lyft i bassängen", :slope "Ramp"}, :general {:description "Beskrivning", :hall "Hall", :women "KPI:NAME:<NAME>END_PI", :total-short "Totalt", :done "Färdig", :updated "Uppdaterad", :name "PI:NAME:<NAME>END_PI", :reported "Rapporterad", :type "Typ", :last-modified "Senaste redigerad", :here "här", :event "Händelse", :structure "Struktur", :general-info "Allmänna uppgifter", :comment "Kommentar", :measures "Mått", :men "Män"}, :dryer-duty-types {:automatic "Automatisk", :manual "Manual"}, :swim-energy {:description "Information", :headline "Energi information", :headline-short "Information", :suh-link "Datum", :ukty-link "Slutade"}, :time {:two-years-ago "För 2 år sedan", :date "Datum", :hour "Timme", :this-month "Den här månaden", :time "Tid", :less-than-hour-ago "För mindre än en timme sedan", :start "Började", :this-week "Den här veckan", :today "I dag", :month "Månad", :long-time-ago "För länge sedan", :year "År", :just-a-moment-ago "För en stund sedan", :yesterday "I går", :three-years-ago "För 3 år sedan", :end "Slutade", :this-year "Det här året", :last-year "Förra året"}, :ice-resurfacer-fuels {:LPG "El", :electicity "El", :gasoline "Bensin", :natural-gas "Naturgas", :propane "Propan"}, :ice-rinks {:headline "Du har admin rättigheter."}, :month {:sep "September", :jan "Januari", :jun "Juni", :oct "Oktober", :jul "Juli", :apr "April", :feb "Februari", :nov "November", :may "PI:NAME:<NAME>END_PI", :mar "Mars", :dec "December", :aug "Augusti"}, :type {:name "Idrottsanläggningstyp", :main-category "Huvudkategori", :sub-category "Underkategori", :type-code "Typkod"}, :duration {:hour "timmar", :month "månader", :years "år", :years-short "år"}, :size-categories {:large "Betong"}, :lipas.admin {:access-all-sites "Du har admin rättigheter.", :confirm-magic-link "Är du säker på att du vill skicka magic link till {1}?", :headline "Admin", :magic-link "Magic link", :select-magic-link-template "Välj brev", :send-magic-link "Skicka magic link till användare", :users "Användare"}, :lipas.building {:headline "Byggnad", :total-volume-m3 "Areal av vatten m²", :staff-count "Antalet personal", :heat-sections? "Antalet personal", :total-ice-area-m2 "Areal av is m²", :main-designers "Antalet personal", :total-pool-room-area-m2 "Areal av vatten m²", :total-water-area-m2 "Areal av vatten m²", :ceiling-structures "Byggnad", :supporting-structures "Areal av is m²", :seating-capacity "Antalet personal"}, :search {:table-view "Visa resultaten i tabellen", :headline "Sökning", :results-count "{1} resultat", :placeholder "Sök...", :retkikartta-filter "Retkikartta.fi-platser", :filters "Filtrera sökning", :search-more "Sök mer...", :page-size "Visa", :search "Sök", :permissions-filter "Visa platser som jag kan redigera", :display-closest-first "Visa närmaste platser först", :list-view "Visa resultaten i listan", :pagination "Resultaten {1}-{2}", :school-use-filter "Idrottsanläggningar nära skolor", :clear-filters "Avmarkera filter"}, :map.tools {:drawing-tooltip "Ritningsverktyg vald", :drawing-hole-tooltip "Hålverktyg vald", :edit-tool "Redigeringsverktyg", :importing-tooltip "Importeringsverktyg vald", :deleting-tooltip "Borttagningsverktyg vald", :splitting-tooltip "Klippningsverktyg vald"}, :partners {:headline "Tillsammans med"}, :actions {:duplicate "Kopiera", :resurrect "Öppna huvudmeny", :select-year "Välj år", :select-owners "Välj ägare", :select-admins "Välj administratörer", :select-tool "Välj verktyg", :save-draft "Spara utkast", :redo "Gör igen", :open-main-menu "Öppna huvudmeny", :back-to-listing "Till listan", :filter-surface-materials "Avgränsa enligt ytmaterial", :browse "flytta dig", :select-type "Välj typ", :edit "Redigera", :filter-construction-year "Avgränsa enligt byggnadsår", :submit "Skicka", :choose-energy "Välj energi", :delete "Radera", :browse-to-map "Flytta dig till kartan", :save "Spara", :close "Stäng", :filter-area-m2 "Avgränsa enligt areal m²", :show-account-menu "Öppna kontomeny", :fill-required-fields "Fyll i obligatoriska fält", :undo "Ångra", :browse-to-portal "Flytta dig till portalen", :download-excel "Ladda ner Excel", :fill-data "Fyll i informationen", :select-statuses "Status", :select-cities "Välj kommuner", :select-hint "Välj...", :discard "Förkasta", :more "Mer...", :cancel "Avbryta", :select-columns "Välj datafält", :add "Tillägg ", :show-all-years "Visa alla år", :download "Ladda ner", :select-hall "Välj hall", :clear-selections "Ta bort val", :select "Välj", :select-types "Välj typer"}, :dimensions {:area-m2 "Areal m²", :depth-max-m "Djup max m", :depth-min-m "Djup min m", :length-m "Längd m", :surface-area-m2 "Areal m²", :volume-m3 "Volym m3", :width-m "Bredd m"}, :login {:headline "Logga in", :login-here "här", :login-with-password "PI:PASSWORD:<PASSWORD>END_PI", :password "PI:PASSWORD:<PASSWORD>END_PI", :logout "Logga ut", :username "E-post / användarnamn", :login-help "Om du har ett användarnamn till LIPAS, du kan också logga in med e-post", :login "Logga in", :magic-link-help "Om du har ett användarnamn till LIPAS, du kan beställa en logga in-länk till din e-post.", :order-magic-link "Skicka länken till min e-post", :login-with-magic-link "Logga in med e-post", :bad-credentials "Lösenord eller användarnamn är felaktigt", :magic-link-ordered "Länken har skickats och den är snart i din e-post. Kolla också spam!", :username-example "PI:EMAIL:<EMAIL>END_PI", :forgot-password? "PI:PASSWORD:<PASSWORD>END_PI?"}, :map.demographics {:headline "Befolkning", :tooltip "Visa befolkning", :helper-text "Välj idrottsanläggning på kartan.", :copyright1 "Befolkningsinformation: Statistikcentralen 2019 årets", :copyright2 "1 km * 1 km data", :copyright3 "licens"}, :lipas.swimming-pool.slides {:add-slide "Lägg till en rutschbana", :edit-slide "Redigera rutschbanan", :headline "Rutschbanor"}, :notifications {:get-failed "Datasökning misslyckades.", :save-failed "Sparningen misslyckades", :save-success "Sparningen lyckades" :ie (str "Internet Explorer stöds inte. Vi rekommenderar du använder t.ex. Chrome, Firefox eller Edge.")}, :lipas.swimming-pool.energy-saving {:filter-rinse-water-heat-recovery? "Gym", :headline "Andra tjänster", :shower-water-heat-recovery? "Gym"}, :ice-form {:headline "Naturgas", :headline-short "El", :select-rink "Bensin"}, :restricted {:login-or-register "Logga in eller registrera dig"}, :lipas.sports-site {:properties "Ytterligare information", :delete-tooltip "Ta bort idrottsanläggningen...", :headline "Idrottsanläggning", :new-site-of-type "Ny {1}", :address "Adress", :new-site "Ny idrottsplats", :phone-number "Telefonnummer", :admin "Administratör", :surface-materials "Ytmaterial", :www "Webbsida", :name "PI:NAME:<NAME>END_PI på PI:NAME:<NAME>END_PI", :reservations-link "Bokningar", :construction-year "Byggår", :type "Typ", :delete "Ta bort {1}", :renovation-years "Renoveringsår", :name-localized-se "Namn på svenska", :status "Status", :id "LIPAS-ID", :details-in-portal "Visa alla ytterligare information", :comment "Ytterligare information", :ownership "Ägare", :name-short "Namn", :basic-data "Grunddata", :delete-reason "Orsak", :event-date "Redigerad", :email-public "E-post (publik)", :add-new "Lägg till en idrottsanläggning", :contact "Kontaktinformation", :owner "Ägare", :marketing-name "PI:NAME:<NAME>END_PI"}, :status {:active "Aktiv", :planned "Planerad" :incorrect-data "Fel information", :out-of-service-permanently "Permanent ur funktion", :out-of-service-temporarily "Tillfälligt ur funktion"}, :register {:headline "Registrera", :link "Registrera här" :thank-you-for-registering "Tack för registrering! Du vill få e-posten snart."}, :map.address-search {:title "Sök address", :tooltip "Sök address"}, :ice-comparison {:headline "Jämförelse av hallar"}, :lipas.visitors {:headline "Användare", :not-reported "Glömt lösenordet?", :not-reported-monthly "Lösenord eller användarnamn är felaktigt", :spectators-count "Glömt ditt lösenord?", :total-count "Lösenord eller användarnamn är felaktigt"}, :lipas.energy-stats {:headline "Värme MWh", :energy-reported-for "Värme MWh", :disclaimer "El MWh", :reported "Vatten m³", :cold-mwh "El + värme MWh", :hall-missing? "Vatten m³", :not-reported "Vatten m³", :water-m3 "Vatten m³", :electricity-mwh "El MWh", :heat-mwh "Värme MWh", :energy-mwh "El + värme MWh"}, :map.basemap {:copyright "© Lantmäteriverket", :maastokartta "Terrängkarta", :ortokuva "Flygfoto", :taustakartta "Bakgrundskarta"}, :lipas.swimming-pool.pools {:add-pool "Lägg till en bassäng", :edit-pool "Redigera bassängen", :headline "Bassänger", :structure "Struktur"}, :condensate-energy-targets {:service-water-heating "Nej", :snow-melting "Vill du förkasta ändringar?", :track-heating "Vill du förkasta ändringar?"}, :refrigerants {:CO2 "CO2 (koldioxid)", :R134A "R134A", :R22 "R22", :R404A "R404A", :R407A "R407A", :R407C "R407C", :R717 "R717"}, :harrastuspassi {:disclaimer "När du kryssat för rutan ”Kan visas på Harrastuspassi.fi” flyttas uppgifterna om idrottsanläggningen automatiskt till Harrastuspassi.fi. Jag förbinder mig att uppdatera ändringar i uppgifterna om idrottsanläggningen utan dröjsmål i Lipas. Anläggningens administratör ansvarar för uppgifternas riktighet och anläggningens säkerhet. Uppgifterna visas i Harrastuspassi.fi om kommunen har kontrakt med Harrastuspassi.fi administratör för att använda Harrastuspassi.fi."} :retkikartta {:disclaimer "När du kryssat för rutan ”Kan visas på Utflyktskarta.fi” flyttas uppgifterna om naturutflyktsmålet automatiskt till karttjänsten Utflyktskarta.fi som Forststyrelsen administrerar. Uppgifter överförs till karttjänsten en gång i dygnet. Jag förbinder mig att uppdatera ändringar i uppgifterna om naturutflyktsmålet utan dröjsmål i Lipas. Utflyktsmålets administratör ansvarar för uppgifternas riktighet och utflyktsmålets säkerhet samt för svar på respons och för eventuella kostnader i samband med privata vägar."}, :reset-password {:change-password "PI:PASSWORD:<PASSWORD>END_PI", :enter-new-password "PI:PASSWORD:<PASSWORD>END_PI", :get-new-link "Bestella ny återställningslänk", :headline "Glömt lösenordet?", :helper-text "Vi ska skicka en återställningslänk till din e-post.", :password-helper-text "Lösenordet måste innehålla minst 6 tecken.", :reset-link-sent "Länken har skickats! Kolla din e-post.", :reset-success "Lösenordet har ändrats! Logga in med ditt nya lösenord."}, :reports {:contacts "Kontaktuppgifter", :download-as-excel "Skapa Excel", :select-fields "Välj fält för rapport", :selected-fields "Vald fält", :shortcuts "Genvägar", :tooltip "Skapa Excel-rapport från resultaten"}, :heat-sources {:district-heating "Om du behöver ytterligare användarrättigheter, kontakt ", :private-power-station "Hjälp"}, :map.import {:headline "Importera geometri", :geoJSON "Laddar upp .json file som innehåller GeoJSON FeatureCollect object. Koordinater måste vara i WGS84 koordinatsystem.", :gpx "Utgångsmaterial måste vara i WGS84 koordinatsystem.", :supported-formats "Filformat som passar är {1}", :replace-existing? "Ersätt gammal geometri", :select-encoding "Välj teckenuppsättning", :tab-header "Importera från filen", :kml "Utgångsmaterial måste vara i WGS84 koordinatsystem.", :shapefile "Importera .shp .dbf och .prj filer i packade .zip filen.", :import-selected "Importera valda", :tooltip "Importera geometrier från filen", :unknown-format "Okänt filformat '{1}'"}, :error {:email-conflict "E-post är redan registrerad", :email-not-found "E-post är inte registrerad", :invalid-form "Korrigera röda fält", :no-data "Ingen information", :reset-token-expired "Lösenordet har inte ändrats. Länken har utgått.", :unknown "Ett okänt fel uppstod. :/", :user-not-found "Användare hittas inte.", :username-conflict "AnPI:NAME:<NAME>END_PIarnamPI:NAME:<NAME>END_PI redan används"}, :reminders {:description "Meddelandet ska skickas till din e-post på vald tid.", :after-one-month "Om en månad", :placeholder "Kom ihåg att kolla idrottsanläggningen \"{1}\" {2}", :select-date "Välj datum", :tomorrow "I morgon", :title "Lägg till en påminnelse", :after-six-months "Om halv år", :in-a-year "Om ett år", :message "Meddelande", :in-a-week "Om en vecka"}, :units {:days-in-year "dagar per år", :hours-per-day "timmar per dag", :pcs "st", :percent "%", :person "pers.", :times-per-day "gånger per dag", :times-per-week "gånger per vecka"}, :lipas.energy-consumption {:cold "Kommentar", :comment "Kommentar", :monthly? "Vatten m³", :operating-hours "Vatten m³", :report "El MWh", :reported-for-year "Vatten m³", :water "Vatten m³", :yearly "El MWh"}, :ice {:description "Stor tävlingshall > 3000", :large "Stor tävlingshall > 3000", :competition "Tävlingsishall < 3000 person", :headline "Ishallsportal", :video "Video", :comparison "Jämförelse av hallar", :size-category "Storlek kategori", :basic-data-of-halls "Grunddata av ishallar", :updating-basic-data "Uppdatering av grunddata", :entering-energy-data "Ishallsportal", :small "Liten tävlingshall > 500 person", :watch "Titta", :video-description "Titta"}, :lipas.location {:address "Gatuadress", :city "Kommun", :city-code "Kommunkod", :headline "Position", :neighborhood "Kommundel", :postal-code "Postnummer", :postal-office "Postkontor"}, :lipas.user.permissions {:admin? "Admin", :all-cities? "Rättighet till alla kommuner", :all-types? "Rättighet till alla typer", :cities "Kommuner", :sports-sites "Idrottsanläggning", :types "Typer"}, :help {:headline "Hjälp", :permissions-help "Om du behöver ytterligare användarrättigheter, kontakt ", :permissions-help-body "Jag behöver användarrättigheter till följande platser:", :permissions-help-subject "Jag behöver mera användarrättigheter"}, :ceiling-structures {:concrete "Betong", :double-t-beam "TT-bricka", :glass "Glas", :hollow-core-slab "Häll", :solid-rock "Häll", :steel "Stål", :wood "Trä"}, :data-users {:data-user? "Använder du LIPAS-data?", :email-body "Vi använder också LIPAS-data", :email-subject "Vi använder också LIPAS-data", :headline "Några som använder LIPAS-data", :tell-us "Berättä om det för oss"}, :lipas.swimming-pool.facilities {:showers-men-count "Antalet duschar för män", :lockers-men-count "Antalet omklädningsskåp för män", :headline "Andra tjänster", :platforms-5m-count "Antalet 5 m hopplatser", :kiosk? "Kiosk / café", :hydro-neck-massage-spots-count "Antal av nackemassagepunkter", :lockers-unisex-count "Antalet unisex omklädningsskåp", :platforms-10m-count "Antalet 10 m hopplatser", :hydro-massage-spots-count "Antal av andra massagepunkter", :lockers-women-count "Antalet omklädningsskåp för kvinnor", :platforms-7.5m-count "Antalet 7.5 m hopplatser", :gym? "Gym", :showers-unisex-count "Antalet unisex duschar", :platforms-1m-count "Antalet 1 m hopplatser", :showers-women-count "Antalet duschar för kvinnor", :platforms-3m-count "Antalet 3 m hopplatser"}, :sauna-types {:infrared-sauna "Infraröd bastu", :other-sauna "Annan bastu", :sauna "Bastu", :steam-sauna "Ångbastu"}, :stats-metrics {:investments "Investeringar", :net-costs "Nettokostnader", :operating-expenses "Driftskostnader", :operating-incomes "Driftsintäkter", :subsidies "Understöd och bidrag från kommunen"}, :refrigerant-solutions {:CO2 "CO2", :H2ONH3 "H2O/NH3", :cacl "CaCl", :ethanol-water "Freezium", :ethylene-glycol "R134A", :freezium "Freezium", :water-glycol "R134A"}, :user {:headline "Mitt konto", :admin-page-link "Gå till adminsidan", :promo1-link "Visa gymnastiksaler som jag kan uppdatera", :swimming-pools-link "Simhallsportal", :promo-headline "Aktuellt", :front-page-link "Gå till framsidan", :promo1-text "Undervisnings- och kulturministeriet önskar att kommuner kompletterar information om byggnadsår och renoveringår om idrottsplatser inomhus. Informationen är viktig för utvärdering av renoveringsskuld i idrottsplatser.", :ice-stadiums-link "Ishallsportal", :greeting "Hej {1} {2} !", :promo1-topic "Tack för att du använder Lipas.fi!"}, :building-materials {:brick "Tegel", :concrete "Betong", :solid-rock "Häll", :steel "Stål", :wood "Trä"}, :stats {:disclaimer-headline "Datakälla" :general-disclaimer-1 "Lipas.fi idrottsanläggningar, friluftsleder och friluftsområden i Finland: Erkännande 4.0 Internationell (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/deed.sv" :general-disclaimer-2 "Du har tillstånd att dela, kopiera och vidaredistribuera materialet oavsett medium eller format, bearbeta, remixa, transformera, och bygg vidare på materialet, för alla ändamål, även kommersiellt. Du måste ge ett korrekt erkännande om du använder Lipas-data, till exempel “Idrottsplatser: Lipas.fi, Jyväskylä Universitet, datum/år”." :general-disclaimer-3 "Observera, att Lipas.fi data är uppdaterat av kommuner och andra ägare av idrottsplatser samt Lipas.fi administratörer i Jyväskylä Universitet. Omfattning, riktighet eller enhetlighet kan inte garanteras. I Lipas.fi statistik är material baserat på data i Lipas.fi databas. Återstående information kan påverka beräkningar." :finance-disclaimer "Ekonomiska uppgifter av kommuners idrotts- och ungdomsväsende: Statistikcentralen öppen data. Materialet har laddats ner från Statistikcentralens gränssnittstjänst 2001-2019 med licensen CC BY 4.0. Observera, att kommunerna ansvarar själva för att uppdatera sina ekonomiska uppgifter i Statistikcentralens databas. Enhetlighet och jämförbarhet mellan åren eller kommunerna kan inte garanteras." :description "Ekonomiska uppgifter om idrotts- och ungdomsväsende. Kommunen kan observera hur kostnader utvecklas över tid.", :filter-types "Välj typer", :length-km-sum "Idrottsrutters totalt längd ", :headline "Statistik", :select-years "Välj år", :browse-to "Gå till statistiken", :select-issuer "Välj understödare", :select-unit "Välj måttenhet", :bullet3 "Bidrag", :finance-stats "Ekonomiska uppgifter", :select-city "Välj kommun", :area-m2-min "Minimum idrottsareal m²", :filter-cities "Välj kommuner", :select-metrics "Välj storheter", :area-m2-count "Antal av platser med idrottsareal information", :show-ranking "Visa rankning", :age-structure-stats "Byggnadsår", :subsidies-count "Antal av bidrag", :area-m2-sum "Totalt idrottsareal m²", :select-metric "Välj storhet", :bullet2 "Statistiken om idrottsanläggningar", :area-m2-max "Maximum idrottsareal m²", :select-grouping "Gruppering", :select-city-service "Välj administratör", :region "Region", :show-comparison "Visa jämförelse", :length-km-avg "Medeltal av idrottsruttens längd", :sports-sites-count "Antal av idrottsanläggningar", :length-km-min "Minimum idrottsruttens längd", :country-avg "(medeltal för hela landet)", :length-km-count "Antal av idrottsrutter med längd information", :population "Folkmängd", :sports-stats "Idrottsanläggningar", :select-cities "Välj kommuner", :subsidies "Bidrag", :select-interval "Välj intervall", :bullet1 "Ekonomiska uppgifter om idrotts- och ungdomsväsende", :area-m2-avg "Medeltal av idrottsareal m²", :age-structure "Byggnadsår av idrottsanläggningar", :length-km-max "Maximum idrottsruttens längd", :total-amount-1000e "Totalt (1000 €)", :city-stats "Kommunstatistik"}, :pool-structures {:concrete "Betong", :hardened-plastic "Barnbassäng", :steel "Stål"}, :map {:retkikartta-checkbox-reminder "Välj också igen \"Kan visas i Retkikartta.fi - service\" i följande steg i ytterligare information.", :zoom-to-user "Zooma in till min position", :remove "Ta bort", :modify-polygon "Modifera området", :draw-polygon "Lägg till område", :retkikartta-problems-warning "Korrigera problem som är märkta på kartan för att visa i Retkikartta.fi.", :edit-later-hint "Du kan modifera geometrin också senare", :center-map-to-site "Fokusera kartan på platsen", :draw-hole "Lägg till hål", :split-linestring "Klippa ruttdel", :delete-vertices-hint "För att ta bort en punkt, tryck och håll alt-knappen och klicka på punkten", :calculate-route-length "Räkna ut längden", :remove-polygon "Ta bort område", :modify-linestring "Modifera rutten", :download-gpx "Ladda ner GPX", :add-to-map "Lägg till på karta", :bounding-box-filter "Sök i området", :remove-linestring "Ta bort ruttdel", :draw-geoms "Rita", :confirm-remove "Är du säker att du vill ta bort geometrin?", :draw "Lägg till på karta", :draw-linestring "Lägg till ruttdel", :modify "Du kan dra punkten på kartan", :zoom-to-site "Zooma in till sportplats", :kink "Korrigera så att ruttdelen inte korsar själv", :zoom-closer "Zooma in"}, :supporting-structures {:brick "Tegel", :concrete "Betong", :concrete-beam "Häll", :concrete-pillar "Stål", :solid-rock "Häll", :steel "Stål", :wood "Trä"}, :owner {:unknown "Ingen information", :municipal-consortium "Samkommun", :other "AnPI:NAME:<NAME>END_PI", :company-ltd "Företag", :city "Kommun", :state "Stat", :registered-association "Registrerad förening", :foundation "Stiftelse", :city-main-owner "Företag med kommun som majoritetsägare"}, :menu {:frontpage "Framsidan", :headline "LIPAS", :jyu "Jyväskylä universitet", :main-menu "Huvudmeny"}, :dryer-types {:cooling-coil "timmar", :munters "månader", :none "timmar"}, :physical-units {:mm "mm", :hour "h", :m3 "m³", :m "m", :temperature-c "Temperatur °C", :l "l", :mwh "MWh", :m2 "m²", :celsius "°C"}, :lipas.swimming-pool.water-treatment {:filtering-methods "E-post", :headline "Kontaktuppgifter", :ozonation? "E-post", :uv-treatment? "Kontaktuppgifter"}, :statuses {:edited "{1} (redigerad)"}, :lipas.user {:email "E-post", :permissions "Rättigheter", :permissions-example "Rätt att uppdatera Jyväskylä ishallen.", :saved-searches "Sparad sök", :report-energy-and-visitors "Spara raportmodellen", :permission-to-cities "Du har rättighet att uppdatera de här kommunerna:", :password "PI:PASSWORD:<PASSWORD>END_PI", :lastname "PI:NAME:<NAME>END_PI", :save-report "Spara raportmodellen", :sports-sites "Egna platser", :permission-to-all-cities "Du har rättighet att uppdatera alla kommuner", :username "Användarnamn", :history "Historia", :saved-reports "Sparad raportmodeller", :contact-info "Kontaktuppgifter", :permission-to-all-types "Du har rättighet att uppdatera alla typer", :requested-permissions "Begärda rättigheter", :email-example "PI:EMAIL:<EMAIL>END_PI", :permission-to-portal-sites "Du har rättighet att uppdatera de här platserna:", :permissions-help "Skriv vad du vill uppdatera i Lipas", :report-energy-consumption "Begärda rättigheter", :firstname "Förnamn", :save-search "Spara söket", :view-basic-info "Kolla ut grunddata", :no-permissions "Användarnamn till Lipas har inte ännu konfirmerats", :username-example "tane12", :permission-to-types "Du har rättighet att uppdatera de här typerna:"}, :heat-recovery-types {:thermal-wheel "Hjälp"}}, :en {:analysis {:headline "Analysis tool (beta)" :add-new "Add new" :distance "Distance" :travel-time "Travel time" :zones "Baskets" :zone "Basket" :schools "Schools" :daycare "Early childhood education" :elementary-school "Elementary school" :high-school "High school" :elementary-and-high-school "Elementary and high school" :special-school "Special education school" :direct "Beeline" :by-foot "By foot" :by-car "By car" :by-bicycle "By bicycle" :population "Population" :analysis-buffer "Analysis buffer" :filter-types "Filter by type" :settings "Settings" :settings-map "What's visible on map" :settings-zones "Distances and travel times" :settings-help "Note: analysis area will be determined by the maximum distance defined here. Travel times are not calculated outside the maximum distance."} :sport {:description "LIPAS is the national database of sport facilities and their conditions in Finland.", :headline "Sports Faclities", :open-interfaces "Open data and APIs", :up-to-date-information "Up-to-date information about sports facilities", :updating-tools "Tools for data maintainers"}, :confirm {:discard-changes? "Do you want to discard all changes?", :headline "Confirmation", :no "No", :press-again-to-delete "Press again to delete", :resurrect? "Are you sure you want to resurrect this sports facility?", :save-basic-data? "Do you want to save general information?", :yes "Yes"}, :lipas.swimming-pool.saunas {:accessible? "Accessible", :add-sauna "Add sauna", :edit-sauna "Edit sauna", :headline "Saunas", :men? "Men", :women? "Women"}, :slide-structures {:concrete "Concrete", :hardened-plastic "Hardened plastic", :steel "Steel"}, :lipas.swimming-pool.conditions {:open-days-in-year "Open days in year", :open-hours-mon "Mondays", :headline "Open hours", :open-hours-wed "Wednesdays", :open-hours-thu "Thursdays", :open-hours-fri "Fridays", :open-hours-tue "Tuesdays", :open-hours-sun "Sundays", :daily-open-hours "Daily open hours", :open-hours-sat "Saturdays"}, :lipas.ice-stadium.ventilation {:dryer-duty-type "Dryer duty type", :dryer-type "Dryer type", :headline "Ventilation", :heat-pump-type "Heat pump type", :heat-recovery-efficiency "Heat recovery efficiency", :heat-recovery-type "Heat recovery type"}, :swim {:description "Swimming pools portal contains data about indoor swimming pools energy consumption and related factors.", :latest-updates "Latest updates", :headline "Swimming pools", :basic-data-of-halls "General information about building and facilities", :updating-basic-data "Updating general information", :edit "Report consumption", :entering-energy-data "Reporing energy consumption", :list "Pools list", :visualizations "Comparison"}, :home-page {:description "LIPAS system has information on sport facilities, routes and recreational areas and economy. The content is open data under the CC4.0 International licence.", :headline "Front page"}, :ice-energy {:description "Up-to-date information can be found from Finhockey association web-site.", :energy-calculator "Ice stadium energy concumption calculator", :finhockey-link "Browse to Finhockey web-site", :headline "Energy Info"}, :filtering-methods {:activated-carbon "Activated carbon", :coal "Coal", :membrane-filtration "Membrane filtration", :multi-layer-filtering "Multi-layer filtering", :open-sand "Open sand", :other "Other", :precipitation "Precipitation", :pressure-sand "Pressure sand"}, :open-data {:description "Interface links and instructions", :headline "Open Data", :rest "REST", :wms-wfs "WMS & WFS"}, :lipas.swimming-pool.pool {:accessibility "Accessibility", :outdoor-pool? "Outdoor pool"}, :pool-types {:multipurpose-pool "Multi-purpose pool", :whirlpool-bath "Whirlpool bath", :main-pool "Main pool", :therapy-pool "Therapy pool", :fitness-pool "Fitness pool", :diving-pool "Diving pool", :childrens-pool "Childrens pool", :paddling-pool "Paddling pool", :cold-pool "Cold pool", :other-pool "Other pool", :teaching-pool "Teaching pool"}, :lipas.ice-stadium.envelope {:base-floor-structure "Base floor structure", :headline "Envelope structure", :insulated-ceiling? "Insulated ceiling", :insulated-exterior? "Insulated exterior", :low-emissivity-coating? "Low emissivity coating"}, :disclaimer {:headline "NOTICE!", :test-version "This is LIPAS TEST-ENVIRONMENT. Changes made here don't affect the production system."}, :admin {:private-foundation "Private / foundation", :city-other "City / other", :unknown "Unknown", :municipal-consortium "Municipal consortium", :private-company "Private / company", :private-association "Private / association", :other "Other", :city-technical-services "City / technical services", :city-sports "City / sports", :state "State", :city-education "City / education"}, :accessibility {:lift "Pool lift", :low-rise-stairs "Low rise stairs", :mobile-lift "Mobile pool lift", :slope "Slope"}, :general {:description "Description", :hall "Hall", :women "Women", :total-short "Total", :done "Done", :updated "Updated", :name "PI:NAME:<NAME>END_PI", :reported "Reported", :type "Type", :last-modified "Last modified", :here "here", :event "Event", :structure "Structure", :general-info "General information", :comment "Comment", :measures "Measures", :men "Men"}, :dryer-duty-types {:automatic "Automatic", :manual "Manual"}, :swim-energy {:description "Up-to-date information can be found from UKTY and SUH web-sites.", :headline "Energy info", :headline-short "Info", :suh-link "Browse to SUH web-site", :ukty-link "Browse to UKTY web-site"}, :time {:two-years-ago "2 years ago", :date "Date", :hour "Hour", :this-month "This month", :time "Time", :less-than-hour-ago "Less than an hour ago", :start "Started", :this-week "This week", :today "Today", :month "Month", :long-time-ago "Long time ago", :year "Year", :just-a-moment-ago "Just a moment ago", :yesterday "Yesterday", :three-years-ago "3 years ago", :end "Ended", :this-year "This year", :last-year "Last year"}, :ice-resurfacer-fuels {:LPG "LPG", :electicity "Electricity", :gasoline "Gasoline", :natural-gas "Natural gas", :propane "Propane"}, :ice-rinks {:headline "Venue details"}, :month {:sep "September", :jan "January", :jun "June", :oct "October", :jul "July", :apr "April", :feb "February", :nov "November", :may "May", :mar "March", :dec "December", :aug "August"}, :type {:name "Type", :main-category "Main category", :sub-category "Sub category", :type-code "Type code"}, :duration {:hour "hours", :month "months", :years "years", :years-short "y"}, :size-categories {:competition "Competition < 3000 persons", :large "Large > 3000 persons", :small "Small > 500 persons"}, :lipas.admin {:access-all-sites "You have admin permissions.", :confirm-magic-link "Are you sure you want to send magic link to {1}?", :headline "Admin", :magic-link "Magic Link", :select-magic-link-template "Select letter", :send-magic-link "Send magic link to {1}", :users "Users"}, :lipas.ice-stadium.refrigeration {:headline "Refrigeration", :refrigerant-solution-amount-l "Refrigerant solution amount (l)", :individual-metering? "Individual metering", :original? "Original", :refrigerant "Refrigerant", :refrigerant-solution "Refrigerant solution", :condensate-energy-main-targets "Condensate energy main target", :power-kw "Power (kW)", :condensate-energy-recycling? "Condensate energy recycling", :refrigerant-amount-kg "Refrigerant amount (kg)"}, :lipas.building {:headline "Building", :total-volume-m3 "Volume m³", :staff-count "Staff count", :piled? "Piled", :heat-sections? "Pool room is divided to heat sections?", :total-ice-area-m2 "Ice surface area m²", :main-construction-materials "Main construction materials", :main-designers "Main designers", :total-pool-room-area-m2 "Pool room area m²", :heat-source "Heat source", :total-surface-area-m2 "Area m²", :total-water-area-m2 "Water surface area m²", :ceiling-structures "Ceiling structures", :supporting-structures "Supporting structures", :seating-capacity "Seating capacity"}, :heat-pump-types {:air-source "Air source heat pump", :air-water-source "Air-water source heat pump", :exhaust-air-source "Exhaust air source heat pump", :ground-source "Ground source heat pump", :none "None"}, :search {:table-view "Table view", :headline "Search", :results-count "{1} results", :placeholder "Search...", :retkikartta-filter "Retkikartta.fi", :filters "Filters", :search-more "Search more...", :page-size "Page size", :search "Search", :permissions-filter "Show only sites that I can edit", :display-closest-first "Display nearest first", :list-view "List view", :pagination "Results {1}-{2}", :school-use-filter "Used by schools", :clear-filters "Clear filters"}, :map.tools {:drawing-tooltip "Draw tool selected", :drawing-hole-tooltip "Draw hole tool selected", :edit-tool "Edit tool", :importing-tooltip "Import tool selected", :deleting-tooltip "Delete tool selected", :splitting-tooltip "Split tool selected"}, :partners {:headline "In association with"}, :actions {:duplicate "Duplicate", :resurrect "Resurrect", :select-year "Select year", :select-owners "Select owners", :select-admins "Select administrators", :select-tool "Select tool", :save-draft "Save draft", :redo "Redo", :open-main-menu "Open main menu", :back-to-listing "Back to list view", :filter-surface-materials "Filter surface materials", :browse "Browse", :select-type "Select types", :edit "Edit", :filter-construction-year "Filter construction years", :submit "Submit", :choose-energy "Choose energy", :delete "Delete", :browse-to-map "Go to map view", :save "Save", :close "Close", :filter-area-m2 "Filter area m²", :show-account-menu "Open account menu", :fill-required-fields "Please fill all required fields", :undo "Undo", :browse-to-portal "Enter portal", :download-excel "Download Excel", :fill-data "Fill", :select-statuses "Status", :select-cities "Select cities", :select-hint "Select...", :discard "Discard", :more "More...", :cancel "Cancel", :select-columns "Select fields", :add "Add", :show-all-years "Show all years", :download "Download", :select-hall "Select hall", :clear-selections "Clear", :select "Select", :select-types "Select types"}, :dimensions {:area-m2 "Area m²", :depth-max-m "Depth max m", :depth-min-m "Depth min m", :length-m "Length m", :surface-area-m2 "Surface area m²", :volume-m3 "Volume m³", :width-m "Width m"}, :login {:headline "Login", :login-here "here", :login-with-password "PI:PASSWORD:<PASSWORD>END_PI with PI:PASSWORD:<PASSWORD>END_PI", :password "PI:PASSWORD:<PASSWORD>END_PI", :logout "Log out", :username "Email / Username", :login-help "If you are already a LIPAS-user you can login using just your email address.", :login "Login", :magic-link-help "Order login link", :order-magic-link "Order login link", :login-with-magic-link "Login with email", :bad-credentials "Wrong username or password", :magic-link-ordered "Password", :username-example "PI:EMAIL:<EMAIL>END_PI", :forgot-password? "Forgot password?"}, :lipas.ice-stadium.conditions {:open-months "Open months in year", :headline "Conditions", :ice-resurfacer-fuel "Ice resurfacer fuel", :stand-temperature-c "Stand temperature (during match)", :ice-average-thickness-mm "Average ice thickness (mm)", :air-humidity-min "Air humidity % min", :daily-maintenances-weekends "Daily maintenances on weekends", :air-humidity-max "Air humidity % max", :daily-maintenances-week-days "Daily maintenances on weekdays", :maintenance-water-temperature-c "Maintenance water temperature", :ice-surface-temperature-c "Ice surface temperature", :weekly-maintenances "Weekly maintenances", :skating-area-temperature-c "Skating area temperature (at 1m height)", :daily-open-hours "Daily open hours", :average-water-consumption-l "Average water consumption (l) / maintenance"}, :map.demographics {:headline "Analysis tool", :tooltip "Analysis tool", :helper-text "Select sports facility on the map.", :copyright1 "Statistics of Finland 2019/2020", :copyright2 "1x1km and 250x250m population grids", :copyright3 "with license"}, :lipas.swimming-pool.slides {:add-slide "Add Slide", :edit-slide "Edit slide", :headline "Slides"}, :notifications {:get-failed "Couldn't get data.", :save-failed "Saving failed", :save-success "Saving succeeded" :ie "Internet Explorer is not a supported browser. Please use another web browser, e.g. Chrome, Firefox or Edge."}, :lipas.swimming-pool.energy-saving {:filter-rinse-water-heat-recovery? "Filter rinse water heat recovery?", :headline "Energy saving", :shower-water-heat-recovery? "Shower water heat recovery?"}, :ice-form {:headline "Report readings", :headline-short "Report readings", :select-rink "Select stadium"}, :restricted {:login-or-register "Please login or register"}, :lipas.ice-stadium.rinks {:add-rink "Add rink", :edit-rink "Edit rink", :headline "Rinks"}, :lipas.sports-site {:properties "Properties", :delete-tooltip "Delete sports facility...", :headline "sports faclities", :new-site-of-type "New {1}", :address "Address", :new-site "New Sports Facility", :phone-number "Phone number", :admin "Admin", :surface-materials "Surface materials", :www "Web-site", :name "Finnish name", :reservations-link "Reservations", :construction-year "Construction year", :type "Type", :delete "Delete {1}", :renovation-years "Renovation years", :name-localized-se "Swedish name", :status "Status", :id "LIPAS-ID", :details-in-portal "Click here to see details", :comment "More information", :ownership "Ownership", :name-short "Name", :basic-data "General", :delete-reason "Reason", :event-date "Modified", :email-public "Email (public)", :add-new "Add Sports Facility", :contact "Contact", :owner "Owner", :marketing-name "Marketing name"}, :status {:active "Active", :planned "Planned" :incorrect-data "Incorrect data", :out-of-service-permanently "Permanently out of service", :out-of-service-temporarily "Temporarily out of service"}, :register {:headline "Register", :link "Sign up here" :thank-you-for-registering "Thank you for registering! You wil receive an email once we've updated your permissions."}, :map.address-search {:title "Find address", :tooltip "Find address"}, :ice-comparison {:headline "Compare"}, :lipas.visitors {:headline "Visitors", :monthly-visitors-in-year "Monthly visitors in {1}", :not-reported "Visitors not reported", :not-reported-monthly "No monthly data", :spectators-count "Spectators count", :total-count "Visitors count"}, :lipas.energy-stats {:headline "Energy consumption in {1}", :energy-reported-for "Electricity, heat and water consumption reported for {1}", :report "Report consumption", :disclaimer "*Based on reported consumption in {1}", :reported "Reported {1}", :cold-mwh "Cold MWh", :hall-missing? "Is your data missing from the diagram?", :not-reported "Not reported {1}", :water-m3 "Water m³", :electricity-mwh "Electricity MWh", :heat-mwh "Heat MWh", :energy-mwh "Energy MWh"}, :map.basemap {:copyright "© National Land Survey", :maastokartta "Terrain", :ortokuva "Satellite", :taustakartta "Default"}, :map.overlay {:tooltip "Other layers" :mml-kiinteisto "Property boundaries" :light-traffic "Light traffic" :retkikartta-snowmobile-tracks "Metsähallitus snowmobile tracks"} :lipas.swimming-pool.pools {:add-pool "Add pool", :edit-pool "Edit pool", :headline "Pools", :structure "Structure"}, :condensate-energy-targets {:hall-heating "Hall heating", :maintenance-water-heating "Maintenance water heating", :other-space-heating "Other heating", :service-water-heating "Service water heating", :snow-melting "Snow melting", :track-heating "Track heating"}, :refrigerants {:CO2 "CO2", :R134A "R134A", :R22 "R22", :R404A "R404A", :R407A "R407A", :R407C "R407C", :R717 "R717"}, :harrastuspassi {:disclaimer "When the option “May be shown in Harrastuspassi.fi” is ticked, the information regarding the sport facility will be transferred automatically to the Harrastuspassi.fi. I agree to update in the Lipas service any changes to information regarding the sport facility. The site administrator is responsible for the accuracy of information and safety of the location. Facility information is shown in Harrastuspassi.fi only if the municipality has a contract with Harrastuspassi.fi service provider."} :retkikartta {:disclaimer "When the option “May be shown in Excursionmap.fi” is ticked, the information regarding the open air exercise location will be transferred once in every 24 hours automatically to the Excursionmap.fi service, maintained by Metsähallitus. I agree to update in the Lipas service any changes to information regarding an open air exercise location. The site administrator is responsible for the accuracy of information, safety of the location, responses to feedback and possible costs related to private roads."}, :reset-password {:change-password "PI:PASSWORD:<PASSWORD>END_PI", :enter-new-password "PI:PASSWORD:<PASSWORD>END_PI", :get-new-link "Get new reset link", :headline "Forgot password?", :helper-text "We will email password reset link to you.", :password-helper-text "Password must be at least 6 characters long", :reset-link-sent "Reset link sent! Please check your email!", :reset-success "Password has been reset! Please login with the new password."}, :reports {:contacts "Contacts", :download-as-excel "Download Excel", :select-fields "Select field", :selected-fields "Selected fields", :shortcuts "Shortcuts", :tooltip "Create Excel from search results"}, :heat-sources {:district-heating "District heating", :private-power-station "Private power station"}, :map.import {:headline "Import geometries", :geoJSON "Upload .json file containing FeatureCollection. Coordinates must be in WGS84 format.", :gpx "Coordinates must be in WGS84 format", :supported-formats "Supported formats are {1}", :replace-existing? "Replace existing geometries", :select-encoding "Select encoding", :tab-header "Import", :kml "Coordinates must be in WGS84 format", :shapefile "Import zip file containing .shp .dbf and .prj file.", :import-selected "Import selected", :tooltip "Import from file", :unknown-format "Unkonwn format '{1}'"}, :error {:email-conflict "Email is already in use", :email-not-found "Email address is not registered", :invalid-form "Fix fields marked with red", :no-data "No data", :reset-token-expired "Password reset failed. Link has expired.", :unknown "Unknown error occurred. :/", :user-not-found "User not found.", :username-conflict "Username is already in use"}, :reminders {:description "We will email the message to you at the selected time", :after-one-month "After one month", :placeholder "Remember to check sports-facility \"{1}\" {2}", :select-date "Select date", :tomorrow "Tomorrow", :title "Add reminder", :after-six-months "After six months", :in-a-year "In a year", :message "Message", :in-a-week "In a week"}, :units {:days-in-year "days a year", :hours-per-day "hours a day", :pcs "pcs", :percent "%", :person "person", :times-per-day "times a day", :times-per-week "times a wekk"}, :lipas.energy-consumption {:contains-other-buildings? "Readings contain also other buildings or spaces", :headline "Energy consumption", :yearly "Yearly", :report "Report readings", :electricity "Electricity MWh", :headline-year "Energy consumption in {1}", :monthly? "I want to report monthly energy consumption", :reported-for-year "Energy consumption reported for {1}", :monthly "Monthly", :operating-hours "Operating hours", :not-reported "Energy consumption not reported", :not-reported-monthly "No monthly data available", :heat "Heat (acquired) MWh", :cold "Cold energy (acquired) MWh", :comment "Comment", :water "Water m³", :monthly-readings-in-year "Monthly energy consumption in {1}"}, :ice {:description "Ice stadiums portal contains data about ice stadiums energy consumption and related factors.", :large "Grand hall > 3000 persons", :competition "Competition hall < 3000 persons", :headline "Ice stadiums", :video "Video", :comparison "Compare venues", :size-category "Size category", :basic-data-of-halls "General information about building and facilities", :updating-basic-data "Updating general information", :entering-energy-data "Reporing energy consumption", :small "Small competition hall > 500 persons", :watch "Watch", :video-description "PI:NAME:<NAME>END_PI - An Energy Efficient Ice Stadium"}, :lipas.location {:address "Address", :city "City", :city-code "City code", :headline "Location", :neighborhood "Neighborhood", :postal-code "Postal code", :postal-office "Postal office"}, :lipas.user.permissions {:admin? "Admin", :all-cities? "Permission to all cities", :all-types? "Permission to all types", :cities "Access to sports faclities in cities", :sports-sites "Access to sports faclities", :types "Access to sports faclities of type"}, :help {:headline "Help", :permissions-help "Please contact us in case you need more permissions", :permissions-help-body "I need permissions to following sports facilities:", :permissions-help-subject "I need more permissions"}, :ceiling-structures {:concrete "Concrete", :double-t-beam "Double-T", :glass "Glass", :hollow-core-slab "Hollow-core slab", :solid-rock "Solid rock", :steel "Steel", :wood "Wood"}, :data-users {:data-user? "Do you use LIPAS-data?", :email-body "Tell us", :email-subject "We also use LIPAS-data", :headline "Data users", :tell-us "Tell us"}, :lipas.swimming-pool.facilities {:showers-men-count "Mens showers count", :lockers-men-count "Mens lockers count", :headline "Other services", :platforms-5m-count "5 m platforms count", :kiosk? "Kiosk / cafeteria", :hydro-neck-massage-spots-count "Neck hydro massage spots count", :lockers-unisex-count "Unisex lockers count", :platforms-10m-count "10 m platforms count", :hydro-massage-spots-count "Other hydro massage spots count", :lockers-women-count "Womens lockers count", :platforms-7.5m-count "7.5 m platforms count", :gym? "Gym", :showers-unisex-count "Unisex showers count", :platforms-1m-count "1 m platforms count", :showers-women-count "Womens showers count", :platforms-3m-count "3 m platforms count"}, :sauna-types {:infrared-sauna "Infrared sauna", :other-sauna "Other sauna", :sauna "Sauna", :steam-sauna "Steam sauna"}, :stats-metrics {:investments "Investments", :net-costs "Net costs", :operating-expenses "Operating expenses", :operating-incomes "Operating incomes", :subsidies "Granted subsidies"}, :refrigerant-solutions {:CO2 "CO2", :H2ONH3 "H2O/NH3", :cacl "CaCl", :ethanol-water "Ethanol-water", :ethylene-glycol "Ethylene glycol", :freezium "Freezium", :water-glycol "Water-glycol"}, :user {:admin-page-link "Admin page", :front-page-link "front page", :greeting "Hello {1} {2}!", :headline "Profile", :ice-stadiums-link "Ice stadiums", :promo-headline "Important", :promo1-text "Swimming pools", :swimming-pools-link "Swimming pools"}, :building-materials {:brick "Brick", :concrete "Concrete", :solid-rock "Solid rock", :steel "Steel", :wood "Wood"}, :stats {:disclaimer-headline "Data sources" :general-disclaimer-1 "Lipas.fi Finland’s sport venues and places, outdoor routes and recreational areas data is open data under license: Attribution 4.0 International (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/deed.en." :general-disclaimer-2 "You are free to use, adapt and share Lipas.fi data in any way, as long as the source is mentioned (Lipas.fi data, University of Jyväskylä, date/year of data upload or relevant information)." :general-disclaimer-3 "Note, that Lipas.fi data is updated by municipalities, other owners of sport facilities and Lipas.fi administrators at the University of Jyväskylä, Finland. Data accuracy, uniformity or comparability between municipalities is not guaranteed. In the Lipas.fi statistics, all material is based on the data in Lipas database and possible missing information may affect the results." :finance-disclaimer "Data on finances of sport and youth sector in municipalities: Statistics Finland open data. The material was downloaded from Statistics Finland's interface service in 2001-2019 with the license CC BY 4.0. Notice, that municipalities are responsible for updating financial information to Statistics Finland’s database. Data uniformity and data comparability between years or between municipalities is not guaranteed." :description "Statistics of sports facilities and related municipality finances", :filter-types "Filter types", :length-km-sum "Total route length km", :headline "Statistics", :select-years "Select years", :browse-to "Go to statistics", :select-issuer "Select issuer", :select-unit "Select unit", :bullet3 "Subsidies", :finance-stats "Finances", :select-city "Select city", :area-m2-min "Min area m²", :filter-cities "Filter cities", :select-metrics "Select metrics", :area-m2-count "Area m² reported count", :show-ranking "Show ranking", :age-structure-stats "Construction years", :subsidies-count "Subsidies count", :area-m2-sum "Total area m²", :select-metric "Select metric", :bullet2 "Sports facility statistics", :area-m2-max "Max area m²", :select-grouping "Grouping", :select-city-service "Select city service", :region "Region", :show-comparison "Show comparison", :length-km-avg "Average route length km", :sports-sites-count "Total count", :length-km-min "Min route length km", :country-avg "(country average)", :length-km-count "Route length reported count", :population "Population", :sports-stats "Sports faclities", :select-cities "Select cities", :subsidies "Subsidies", :select-interval "Select interval", :bullet1 "Economic Figures of Sport and Youth sector", :area-m2-avg "Average area m²", :age-structure "Construction years", :length-km-max "Max route length km", :total-amount-1000e "Total amount (€1000)", :city-stats "City statistics"}, :pool-structures {:concrete "Concrete", :hardened-plastic "Hardened plastic", :steel "Steel"}, :map {:retkikartta-checkbox-reminder "Remember to tick \"May be shown in ExcursionMap.fi\" later in sports facility properties.", :zoom-to-user "Zoom to my location", :remove "Remove", :modify-polygon "Modify area", :draw-polygon "Add area", :retkikartta-problems-warning "Please fix problems displayed on the map in case this route should be visible also in Retkikartta.fi", :edit-later-hint "You can modify geometries later", :center-map-to-site "Center map to sports-facility", :draw-hole "Add hole", :split-linestring "Split", :delete-vertices-hint "Vertices can be deleted by pressing alt-key and clicking.", :calculate-route-length "Calculate route length", :remove-polygon "Remove area", :modify-linestring "Modify route", :download-gpx "Download GPX", :add-to-map "Add to map", :bounding-box-filter "Search from map area", :remove-linestring "Remove route", :draw-geoms "Draw", :confirm-remove "Are you sure you want to delete selected geometry?", :draw "Draw", :draw-linestring "Add route", :modify "You can move the point on the map", :zoom-to-site "Zoom map to sports facility's location", :kink "Self intersection. Please fix either by re-routing or splitting the segment.", :zoom-closer "Please zoom closer"}, :supporting-structures {:brick "Brick", :concrete "Concrete", :concrete-beam "Concrete beam", :concrete-pillar "Concrete pillar", :solid-rock "Solid rock", :steel "Steel", :wood "Wood"}, :owner {:unknown "Unknown", :municipal-consortium "Municipal consortium", :other "Other", :company-ltd "Company ltd", :city "City", :state "State", :registered-association "Registered association", :foundation "Foundation", :city-main-owner "City main owner"}, :menu {:frontpage "Home", :headline "LIPAS", :jyu "University of Jyväskylä", :main-menu "Main menu"}, :dryer-types {:cooling-coil "Cooling coil", :munters "Munters", :none "None"}, :physical-units {:mm "mm", :hour "h", :m3 "m³", :m "m", :temperature-c "Temperature °C", :l "l", :mwh "MWh", :m2 "m²", :celsius "°C"}, :lipas.swimming-pool.water-treatment {:activated-carbon? "Activated carbon", :filtering-methods "Filtering methods", :headline "Water treatment", :ozonation? "Ozonation", :uv-treatment? "UV-treatment"}, :statuses {:edited "{1} (edited)"}, :lipas.user {:email "Email", :permissions "Permissions", :permissions-example "Access to update Jyväskylä ice stadiums.", :saved-searches "Saved searches", :report-energy-and-visitors "Report visitors and energy consumption", :permission-to-cities "You have permission to following cities:", :password "PI:PASSWORD:<PASSWORD>END_PI", :lastname "Last name", :save-report "Save template", :sports-sites "My sites", :permission-to-all-cities "You have permission to all cities", :username "Username", :history "History", :saved-reports "Saved templates", :contact-info "Contact info", :permission-to-all-types "You have permission to all types", :requested-permissions "Requested permissions", :email-example "PI:EMAIL:<EMAIL>END_PI", :permission-to-portal-sites "You have permission to following sports facilities:", :permissions-help "Describe what permissions you wish to have", :report-energy-consumption "Report energy consumption", :firstname "First name", :save-search "Save search", :view-basic-info "View basic info", :no-permissions "You don't have permission to publish changes to any sites.", :username-example "tane12", :permission-to-types "You have permission to following types:"}, :heat-recovery-types {:liquid-circulation "Liquid circulation", :plate-heat-exchanger "Plate heat exchanger", :thermal-wheel "Thermal wheel"}}})
[ { "context": ":class \"inverse line-height\"}\n \"HI, my name is Sepehr, and I'm coo coo for creative programming! From f", "end": 858, "score": 0.9998447299003601, "start": 852, "tag": "NAME", "value": "Sepehr" } ]
src/cljs/my_website/views/about/panel.cljs
sansarip/my-website
0
(ns my-website.views.about.panel (:require [my-website.styles :refer [color-palette screen-sizes font-sizes spacing-sizes]] [my-website.utilities :refer [->css-grid-areas word-concat]] [my-website.components.flexbox :refer [flexbox]] [my-website.components.image :refer [image]] [my-website.views.about.styles :as styles] [spade.core :refer [defclass]])) (defn panel [] [:> flexbox {:extra-classes (styles/container-class) :justify-content "space-between" :align-content "center" :justify-items "center" :align-items "start" :wrap "nowrap"} [:div {:class (styles/description-class)} [:h1 {:class "inverse"} "About me"] [:p {:class "inverse line-height"} "HI, my name is Sepehr, and I'm coo coo for creative programming! From faulting segments in C, collecting garbage in Java, cooking spaghetti with JavaScript, doing everything in Python, to composing code as " [:i "d a t a"] " in Clojure, and everything in between - I'm an engineer who's done and seen a lot, folks \uD83D\uDC40 These days I've found myself wondering the realms of functional programming + category theory, and learning from the wise sages I encounter along with sharing the fruits of knowledge with hungry students also on their own journeys."]] [:> image {:extraClasses (word-concat (styles/image-class)) :src "assets/profpic.png"}]])
118354
(ns my-website.views.about.panel (:require [my-website.styles :refer [color-palette screen-sizes font-sizes spacing-sizes]] [my-website.utilities :refer [->css-grid-areas word-concat]] [my-website.components.flexbox :refer [flexbox]] [my-website.components.image :refer [image]] [my-website.views.about.styles :as styles] [spade.core :refer [defclass]])) (defn panel [] [:> flexbox {:extra-classes (styles/container-class) :justify-content "space-between" :align-content "center" :justify-items "center" :align-items "start" :wrap "nowrap"} [:div {:class (styles/description-class)} [:h1 {:class "inverse"} "About me"] [:p {:class "inverse line-height"} "HI, my name is <NAME>, and I'm coo coo for creative programming! From faulting segments in C, collecting garbage in Java, cooking spaghetti with JavaScript, doing everything in Python, to composing code as " [:i "d a t a"] " in Clojure, and everything in between - I'm an engineer who's done and seen a lot, folks \uD83D\uDC40 These days I've found myself wondering the realms of functional programming + category theory, and learning from the wise sages I encounter along with sharing the fruits of knowledge with hungry students also on their own journeys."]] [:> image {:extraClasses (word-concat (styles/image-class)) :src "assets/profpic.png"}]])
true
(ns my-website.views.about.panel (:require [my-website.styles :refer [color-palette screen-sizes font-sizes spacing-sizes]] [my-website.utilities :refer [->css-grid-areas word-concat]] [my-website.components.flexbox :refer [flexbox]] [my-website.components.image :refer [image]] [my-website.views.about.styles :as styles] [spade.core :refer [defclass]])) (defn panel [] [:> flexbox {:extra-classes (styles/container-class) :justify-content "space-between" :align-content "center" :justify-items "center" :align-items "start" :wrap "nowrap"} [:div {:class (styles/description-class)} [:h1 {:class "inverse"} "About me"] [:p {:class "inverse line-height"} "HI, my name is PI:NAME:<NAME>END_PI, and I'm coo coo for creative programming! From faulting segments in C, collecting garbage in Java, cooking spaghetti with JavaScript, doing everything in Python, to composing code as " [:i "d a t a"] " in Clojure, and everything in between - I'm an engineer who's done and seen a lot, folks \uD83D\uDC40 These days I've found myself wondering the realms of functional programming + category theory, and learning from the wise sages I encounter along with sharing the fruits of knowledge with hungry students also on their own journeys."]] [:> image {:extraClasses (word-concat (styles/image-class)) :src "assets/profpic.png"}]])
[ { "context": ";;\n;;\n;; Copyright 2013-2015 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic", "end": 33, "score": 0.9373519420623779, "start": 30, "tag": "NAME", "value": "Net" }, { "context": "te]\n \"-- Generated by PigPen: https://github.com/Netflix/PigPen\\n\\n\")\n\n(defn commands->script\n \"Transform", "end": 13539, "score": 0.9992545247077942, "start": 13532, "tag": "USERNAME", "value": "Netflix" } ]
pigpen-pig/src/main/clojure/pigpen/pig/script.clj
ombagus/Netflix
327
;; ;; ;; Copyright 2013-2015 Netflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.pig.script "Contains functions for converting an expression graph into a Pig script Nothing in here will be used directly with normal PigPen usage. See pigpen.core and pigpen.pig " (:refer-clojure :exclude [replace]) (:require [clojure.string :refer [join replace]] [schema.core :as s] [pigpen.model :as m] [pigpen.extensions.core :refer [zip]] [pigpen.raw :as raw] [pigpen.pig.runtime])) (set! *warn-on-reflection* true) (defn ^:private escape+quote [f] (str "'" (when f (-> f (clojure.string/replace "\\" "\\\\") (clojure.string/replace "'" "\\'"))) "'")) (defn ^:private escape-id [id] (clojure.string/replace id "-" "_")) (defn ^:private format-field ([field] (format-field nil field)) ([context field] (cond (string? field) (escape+quote field) (symbol? field) (case context (:group :reduce) (if (= (name field) "group") (name field) (str (namespace field) "." (name field))) :join (str (namespace field) "::" (name field)) (name field))))) (defn ^:private type->pig-type [type] (case type :int "int" :long "long" :float "float" :double "double" :string "chararray" :boolean "boolean" :binary "bytearray")) (def ^:private clj->op {"and" " AND " "or" " OR " "=" " == " "not=" " != " "<" " < " ">" " > " "<=" " <= " ">=" " >= "}) (defn ^:private expr->script ([expr] (expr->script {} expr)) ([scope expr] (cond (nil? expr) nil (number? expr) (cond ;; This is not ideal, but it prevents Pig from blowing up when you use big numbers (and (instance? Long expr) (not (< Integer/MIN_VALUE expr Integer/MAX_VALUE))) (str expr "L") :else (str expr)) (string? expr) (escape+quote expr) (symbol? expr) (if (.startsWith (name expr) "?") (subs (name expr) 1) (if-let [v (scope expr)] (expr->script scope v) (throw (ex-info (str "Unable to resolve symbol " expr) {:expr expr :scope scope})))) ;; TODO Verify arities ;; TODO Add NOT (seq? expr) (case (first expr) clojure.core/let (let [[_ scope body] expr scope (->> scope (partition 2) (map vec) (into {}))] (expr->script scope body)) quote (expr->script scope (second expr)) (let [[op & exprs] expr exprs' (map (partial expr->script scope) exprs) pig-expr (clojure.string/join (clj->op (name op)) exprs')] (str "(" pig-expr ")"))) :else (throw (IllegalArgumentException. (str "Unknown expression:" (type expr) " " expr)))))) ;; TODO add descriptive comment before each command (defmulti command->script "Converts an individual command into the equivalent Pig script" (fn [{:keys [type]} state] type)) ;; ********** Util ********** (s/defmethod command->script :field [{:keys [field]} :- m/FieldExpr {:keys [last-command]}] (let [context (some->> last-command name (re-find #"[a-z]+") keyword)] [nil (format-field context field)])) (s/defmethod command->script :code [{:keys [udf init func args]} :- m/CodeExpr {:keys [last-command]}] (let [id (raw/pigsym "udf") context (some->> last-command name (re-find #"[a-z]+") keyword) pig-args (->> args (map (partial format-field context)) (join ", ")) udf (pigpen.pig.runtime/udf-lookup udf)] [(str "DEFINE " id " " udf "(" (escape+quote init) "," (escape+quote func) ");\n\n") (str id "(" pig-args ")")])) (defmethod command->script :register [{:keys [jar]} state] {:pre [(string? jar) (not-empty jar)]} (str "REGISTER " jar ";\n\n")) (defmethod command->script :option [{:keys [option value]} state] {:pre [option value]} (str "SET " (name option) " " value ";\n\n")) ;; ********** IO ********** (defmulti storage->script (juxt :type :storage)) (defmethod storage->script [:load :binary] [{:keys [fields]}] (let [pig-fields (->> fields (map format-field) (join ", "))] (str "BinStorage()"))) (defmethod storage->script [:load :string] [{:keys [fields]}] (let [pig-fields (->> fields (map format-field) (map #(str % ":chararray")) (join ", "))] (str "PigStorage('\\n')\n AS (" pig-fields ")"))) (defmethod storage->script [:store :binary] [_] (str "BinStorage()")) (defmethod storage->script [:store :string] [_] (str "PigStorage()")) (defn storage->script' [command] (str "\n USING " (storage->script command))) (s/defmethod command->script :load [{:keys [id location] :as command} :- m/Load state] (let [pig-id (escape-id id) pig-storage (storage->script' command)] (str pig-id " = LOAD '" location "'" pig-storage ";\n\n"))) (s/defmethod command->script :store [{:keys [ancestors location] :as command} :- m/Store state] (let [relation-id (escape-id (first ancestors)) pig-storage (storage->script' command)] (str "STORE " relation-id " INTO '" location "'" pig-storage ";\n\n"))) ;; ********** Map ********** (s/defmethod command->script :projection [{:keys [expr flatten alias types] :as p} :- m/Projection state] (let [[pig-define pig-code] (command->script expr state) pig-code (if flatten (str "FLATTEN(" pig-code ")") pig-code) pig-schema (as-> alias % (map (fn [a t] (str (name a) (when (keyword? t) (str ":" (type->pig-type t))) (when (string? t) (str ":" t)))) % (concat types (repeat nil))) (join ", " %) (str " AS (" % ")"))] [pig-define (str pig-code pig-schema)])) (s/defmethod command->script :project [{:keys [id ancestors projections opts]} :- m/Project state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id) pig-projections (->> projections (mapv #(command->script % (assoc state :last-command (first ancestors))))) pig-defines (->> pig-projections (map first) (join)) pig-projections (->> pig-projections (map second) (join ",\n "))] (str pig-defines pig-id " = FOREACH " relation-id " GENERATE\n " pig-projections ";\n\n"))) (defmethod command->script :sort-opts [{:keys [parallel]} state] (let [pig-parallel (if parallel (str " PARALLEL " parallel))] (str pig-parallel))) (s/defmethod command->script :sort [{:keys [id ancestors key comp opts]} :- m/Sort state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id) pig-key (format-field key) pig-comp (clojure.string/upper-case (name comp)) pig-opts (command->script opts state)] (str pig-id " = ORDER " relation-id " BY " pig-key " " pig-comp pig-opts ";\n\n"))) (defmethod command->script :rank-opts [{:keys [dense]} state] (if dense " DENSE")) (s/defmethod command->script :rank [{:keys [id ancestors key comp opts]} :- (assoc m/Rank (s/optional-key :key) m/Field (s/optional-key :comp) (s/enum :asc :desc)) state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id) pig-sort (when key (str " BY " (format-field key) " " (clojure.string/upper-case (name comp)))) pig-opts (command->script opts state)] (str pig-id " = RANK " relation-id pig-sort pig-opts ";\n\n"))) ;; ********** Filter ********** (s/defmethod command->script :filter [{:keys [id ancestors expr]} :- m/Filter state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id) pig-expr (expr->script expr)] (if pig-expr (str pig-id " = FILTER " relation-id " BY " pig-expr ";\n\n") (str pig-id " = " relation-id ";\n\n")))) (s/defmethod command->script :take [{:keys [id ancestors n opts]} :- m/Take state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id)] (str pig-id " = LIMIT " relation-id " " n ";\n\n"))) (s/defmethod command->script :sample [{:keys [id ancestors p opts]} :- m/Sample state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id)] (str pig-id " = SAMPLE " relation-id " " p ";\n\n"))) ;; ********** Join ********** (s/defmethod command->script :reduce [{:keys [id keys join-types ancestors opts]} :- m/Reduce state] (let [pig-id (escape-id id) relation-id (escape-id (first ancestors))] (str pig-id " = COGROUP " relation-id " ALL;\n\n"))) (defmethod command->script :group-opts [{:keys [strategy parallel]} state] (let [pig-using (if strategy (str " USING '" (name strategy) "'")) pig-parallel (if parallel (str " PARALLEL " parallel))] (str pig-using pig-parallel))) (s/defmethod command->script :group [{:keys [id keys join-types ancestors opts]} :- m/Group state] (let [pig-id (escape-id id) pig-clauses (join ", " (zip [r ancestors k keys j join-types] (str (escape-id r) " BY " (format-field k) (if (= j :required) " INNER")))) pig-opts (command->script opts state)] (str pig-id " = COGROUP " pig-clauses pig-opts ";\n\n"))) (defmethod command->script :join-opts [{:keys [strategy parallel]} state] (let [pig-using (if strategy (str " USING '" (name strategy) "'")) pig-parallel (if parallel (str " PARALLEL " parallel))] (str pig-using pig-parallel))) (s/defmethod command->script :join [{:keys [id keys join-types ancestors opts]} :- m/Join state] (let [pig-id (escape-id id) clauses (zip [r ancestors k keys] (str (escape-id r) " BY " (format-field k))) pig-join (case join-types [:required :optional] " LEFT OUTER" [:optional :required] " RIGHT OUTER" [:optional :optional] " FULL OUTER" "") pig-clauses (join (str pig-join ", ") clauses) pig-opts (command->script opts state)] (str pig-id " = JOIN " pig-clauses pig-opts ";\n\n"))) ;; ********** Set ********** (defmethod command->script :distinct-opts [{:keys [partition-by partition-type parallel]} {:keys [partitioner]}] (let [n (when partition-by (swap! partitioner inc)) pig-set (when partition-by (str "SET PigPenPartitioner" n "_type " (escape+quote (name (or partition-type :frozen))) ";\n" "SET PigPenPartitioner" n "_init '';\n" "SET PigPenPartitioner" n "_func " (escape+quote partition-by) ";\n\n")) pig-partition (when partition-by (str " PARTITION BY pigpen.PigPenPartitioner.PigPenPartitioner" n)) pig-parallel (when parallel (str " PARALLEL " parallel))] [pig-set (str pig-partition pig-parallel)])) (s/defmethod command->script :distinct [{:keys [id ancestors opts]} :- m/Distinct state] (let [relation-id (first ancestors) [pig-set pig-opts] (command->script opts state)] (str pig-set id " = DISTINCT " relation-id pig-opts ";\n\n"))) (defmethod command->script :concat-opts [{:keys [parallel]} state] (let [pig-parallel (if parallel (str " PARALLEL " parallel))] (str pig-parallel))) (s/defmethod command->script :concat [{:keys [id ancestors opts]} :- m/Concat state] (let [pig-id (escape-id id) pig-ancestors (->> ancestors (map escape-id) (join ", ")) pig-opts (command->script opts state)] (str pig-id " = UNION " pig-ancestors pig-opts ";\n\n"))) ;; ********** Script ********** (s/defmethod command->script :noop [{:keys [id ancestors fields]} :- m/NoOp state] (let [relation-id (first ancestors)] (str id " = FOREACH " relation-id " GENERATE\n " (join ", " (map format-field fields)) ";\n\n"))) (defmethod command->script :store-many [command state] "-- Generated by PigPen: https://github.com/Netflix/PigPen\n\n") (defn commands->script "Transforms a sequence of commands into a Pig script" [commands] (binding [*print-length* false *print-level* false] (let [state {:partitioner (atom -1)}] (apply str (for [command commands] (command->script command state))))))
94745
;; ;; ;; Copyright 2013-2015 <NAME>flix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.pig.script "Contains functions for converting an expression graph into a Pig script Nothing in here will be used directly with normal PigPen usage. See pigpen.core and pigpen.pig " (:refer-clojure :exclude [replace]) (:require [clojure.string :refer [join replace]] [schema.core :as s] [pigpen.model :as m] [pigpen.extensions.core :refer [zip]] [pigpen.raw :as raw] [pigpen.pig.runtime])) (set! *warn-on-reflection* true) (defn ^:private escape+quote [f] (str "'" (when f (-> f (clojure.string/replace "\\" "\\\\") (clojure.string/replace "'" "\\'"))) "'")) (defn ^:private escape-id [id] (clojure.string/replace id "-" "_")) (defn ^:private format-field ([field] (format-field nil field)) ([context field] (cond (string? field) (escape+quote field) (symbol? field) (case context (:group :reduce) (if (= (name field) "group") (name field) (str (namespace field) "." (name field))) :join (str (namespace field) "::" (name field)) (name field))))) (defn ^:private type->pig-type [type] (case type :int "int" :long "long" :float "float" :double "double" :string "chararray" :boolean "boolean" :binary "bytearray")) (def ^:private clj->op {"and" " AND " "or" " OR " "=" " == " "not=" " != " "<" " < " ">" " > " "<=" " <= " ">=" " >= "}) (defn ^:private expr->script ([expr] (expr->script {} expr)) ([scope expr] (cond (nil? expr) nil (number? expr) (cond ;; This is not ideal, but it prevents Pig from blowing up when you use big numbers (and (instance? Long expr) (not (< Integer/MIN_VALUE expr Integer/MAX_VALUE))) (str expr "L") :else (str expr)) (string? expr) (escape+quote expr) (symbol? expr) (if (.startsWith (name expr) "?") (subs (name expr) 1) (if-let [v (scope expr)] (expr->script scope v) (throw (ex-info (str "Unable to resolve symbol " expr) {:expr expr :scope scope})))) ;; TODO Verify arities ;; TODO Add NOT (seq? expr) (case (first expr) clojure.core/let (let [[_ scope body] expr scope (->> scope (partition 2) (map vec) (into {}))] (expr->script scope body)) quote (expr->script scope (second expr)) (let [[op & exprs] expr exprs' (map (partial expr->script scope) exprs) pig-expr (clojure.string/join (clj->op (name op)) exprs')] (str "(" pig-expr ")"))) :else (throw (IllegalArgumentException. (str "Unknown expression:" (type expr) " " expr)))))) ;; TODO add descriptive comment before each command (defmulti command->script "Converts an individual command into the equivalent Pig script" (fn [{:keys [type]} state] type)) ;; ********** Util ********** (s/defmethod command->script :field [{:keys [field]} :- m/FieldExpr {:keys [last-command]}] (let [context (some->> last-command name (re-find #"[a-z]+") keyword)] [nil (format-field context field)])) (s/defmethod command->script :code [{:keys [udf init func args]} :- m/CodeExpr {:keys [last-command]}] (let [id (raw/pigsym "udf") context (some->> last-command name (re-find #"[a-z]+") keyword) pig-args (->> args (map (partial format-field context)) (join ", ")) udf (pigpen.pig.runtime/udf-lookup udf)] [(str "DEFINE " id " " udf "(" (escape+quote init) "," (escape+quote func) ");\n\n") (str id "(" pig-args ")")])) (defmethod command->script :register [{:keys [jar]} state] {:pre [(string? jar) (not-empty jar)]} (str "REGISTER " jar ";\n\n")) (defmethod command->script :option [{:keys [option value]} state] {:pre [option value]} (str "SET " (name option) " " value ";\n\n")) ;; ********** IO ********** (defmulti storage->script (juxt :type :storage)) (defmethod storage->script [:load :binary] [{:keys [fields]}] (let [pig-fields (->> fields (map format-field) (join ", "))] (str "BinStorage()"))) (defmethod storage->script [:load :string] [{:keys [fields]}] (let [pig-fields (->> fields (map format-field) (map #(str % ":chararray")) (join ", "))] (str "PigStorage('\\n')\n AS (" pig-fields ")"))) (defmethod storage->script [:store :binary] [_] (str "BinStorage()")) (defmethod storage->script [:store :string] [_] (str "PigStorage()")) (defn storage->script' [command] (str "\n USING " (storage->script command))) (s/defmethod command->script :load [{:keys [id location] :as command} :- m/Load state] (let [pig-id (escape-id id) pig-storage (storage->script' command)] (str pig-id " = LOAD '" location "'" pig-storage ";\n\n"))) (s/defmethod command->script :store [{:keys [ancestors location] :as command} :- m/Store state] (let [relation-id (escape-id (first ancestors)) pig-storage (storage->script' command)] (str "STORE " relation-id " INTO '" location "'" pig-storage ";\n\n"))) ;; ********** Map ********** (s/defmethod command->script :projection [{:keys [expr flatten alias types] :as p} :- m/Projection state] (let [[pig-define pig-code] (command->script expr state) pig-code (if flatten (str "FLATTEN(" pig-code ")") pig-code) pig-schema (as-> alias % (map (fn [a t] (str (name a) (when (keyword? t) (str ":" (type->pig-type t))) (when (string? t) (str ":" t)))) % (concat types (repeat nil))) (join ", " %) (str " AS (" % ")"))] [pig-define (str pig-code pig-schema)])) (s/defmethod command->script :project [{:keys [id ancestors projections opts]} :- m/Project state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id) pig-projections (->> projections (mapv #(command->script % (assoc state :last-command (first ancestors))))) pig-defines (->> pig-projections (map first) (join)) pig-projections (->> pig-projections (map second) (join ",\n "))] (str pig-defines pig-id " = FOREACH " relation-id " GENERATE\n " pig-projections ";\n\n"))) (defmethod command->script :sort-opts [{:keys [parallel]} state] (let [pig-parallel (if parallel (str " PARALLEL " parallel))] (str pig-parallel))) (s/defmethod command->script :sort [{:keys [id ancestors key comp opts]} :- m/Sort state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id) pig-key (format-field key) pig-comp (clojure.string/upper-case (name comp)) pig-opts (command->script opts state)] (str pig-id " = ORDER " relation-id " BY " pig-key " " pig-comp pig-opts ";\n\n"))) (defmethod command->script :rank-opts [{:keys [dense]} state] (if dense " DENSE")) (s/defmethod command->script :rank [{:keys [id ancestors key comp opts]} :- (assoc m/Rank (s/optional-key :key) m/Field (s/optional-key :comp) (s/enum :asc :desc)) state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id) pig-sort (when key (str " BY " (format-field key) " " (clojure.string/upper-case (name comp)))) pig-opts (command->script opts state)] (str pig-id " = RANK " relation-id pig-sort pig-opts ";\n\n"))) ;; ********** Filter ********** (s/defmethod command->script :filter [{:keys [id ancestors expr]} :- m/Filter state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id) pig-expr (expr->script expr)] (if pig-expr (str pig-id " = FILTER " relation-id " BY " pig-expr ";\n\n") (str pig-id " = " relation-id ";\n\n")))) (s/defmethod command->script :take [{:keys [id ancestors n opts]} :- m/Take state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id)] (str pig-id " = LIMIT " relation-id " " n ";\n\n"))) (s/defmethod command->script :sample [{:keys [id ancestors p opts]} :- m/Sample state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id)] (str pig-id " = SAMPLE " relation-id " " p ";\n\n"))) ;; ********** Join ********** (s/defmethod command->script :reduce [{:keys [id keys join-types ancestors opts]} :- m/Reduce state] (let [pig-id (escape-id id) relation-id (escape-id (first ancestors))] (str pig-id " = COGROUP " relation-id " ALL;\n\n"))) (defmethod command->script :group-opts [{:keys [strategy parallel]} state] (let [pig-using (if strategy (str " USING '" (name strategy) "'")) pig-parallel (if parallel (str " PARALLEL " parallel))] (str pig-using pig-parallel))) (s/defmethod command->script :group [{:keys [id keys join-types ancestors opts]} :- m/Group state] (let [pig-id (escape-id id) pig-clauses (join ", " (zip [r ancestors k keys j join-types] (str (escape-id r) " BY " (format-field k) (if (= j :required) " INNER")))) pig-opts (command->script opts state)] (str pig-id " = COGROUP " pig-clauses pig-opts ";\n\n"))) (defmethod command->script :join-opts [{:keys [strategy parallel]} state] (let [pig-using (if strategy (str " USING '" (name strategy) "'")) pig-parallel (if parallel (str " PARALLEL " parallel))] (str pig-using pig-parallel))) (s/defmethod command->script :join [{:keys [id keys join-types ancestors opts]} :- m/Join state] (let [pig-id (escape-id id) clauses (zip [r ancestors k keys] (str (escape-id r) " BY " (format-field k))) pig-join (case join-types [:required :optional] " LEFT OUTER" [:optional :required] " RIGHT OUTER" [:optional :optional] " FULL OUTER" "") pig-clauses (join (str pig-join ", ") clauses) pig-opts (command->script opts state)] (str pig-id " = JOIN " pig-clauses pig-opts ";\n\n"))) ;; ********** Set ********** (defmethod command->script :distinct-opts [{:keys [partition-by partition-type parallel]} {:keys [partitioner]}] (let [n (when partition-by (swap! partitioner inc)) pig-set (when partition-by (str "SET PigPenPartitioner" n "_type " (escape+quote (name (or partition-type :frozen))) ";\n" "SET PigPenPartitioner" n "_init '';\n" "SET PigPenPartitioner" n "_func " (escape+quote partition-by) ";\n\n")) pig-partition (when partition-by (str " PARTITION BY pigpen.PigPenPartitioner.PigPenPartitioner" n)) pig-parallel (when parallel (str " PARALLEL " parallel))] [pig-set (str pig-partition pig-parallel)])) (s/defmethod command->script :distinct [{:keys [id ancestors opts]} :- m/Distinct state] (let [relation-id (first ancestors) [pig-set pig-opts] (command->script opts state)] (str pig-set id " = DISTINCT " relation-id pig-opts ";\n\n"))) (defmethod command->script :concat-opts [{:keys [parallel]} state] (let [pig-parallel (if parallel (str " PARALLEL " parallel))] (str pig-parallel))) (s/defmethod command->script :concat [{:keys [id ancestors opts]} :- m/Concat state] (let [pig-id (escape-id id) pig-ancestors (->> ancestors (map escape-id) (join ", ")) pig-opts (command->script opts state)] (str pig-id " = UNION " pig-ancestors pig-opts ";\n\n"))) ;; ********** Script ********** (s/defmethod command->script :noop [{:keys [id ancestors fields]} :- m/NoOp state] (let [relation-id (first ancestors)] (str id " = FOREACH " relation-id " GENERATE\n " (join ", " (map format-field fields)) ";\n\n"))) (defmethod command->script :store-many [command state] "-- Generated by PigPen: https://github.com/Netflix/PigPen\n\n") (defn commands->script "Transforms a sequence of commands into a Pig script" [commands] (binding [*print-length* false *print-level* false] (let [state {:partitioner (atom -1)}] (apply str (for [command commands] (command->script command state))))))
true
;; ;; ;; Copyright 2013-2015 PI:NAME:<NAME>END_PIflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.pig.script "Contains functions for converting an expression graph into a Pig script Nothing in here will be used directly with normal PigPen usage. See pigpen.core and pigpen.pig " (:refer-clojure :exclude [replace]) (:require [clojure.string :refer [join replace]] [schema.core :as s] [pigpen.model :as m] [pigpen.extensions.core :refer [zip]] [pigpen.raw :as raw] [pigpen.pig.runtime])) (set! *warn-on-reflection* true) (defn ^:private escape+quote [f] (str "'" (when f (-> f (clojure.string/replace "\\" "\\\\") (clojure.string/replace "'" "\\'"))) "'")) (defn ^:private escape-id [id] (clojure.string/replace id "-" "_")) (defn ^:private format-field ([field] (format-field nil field)) ([context field] (cond (string? field) (escape+quote field) (symbol? field) (case context (:group :reduce) (if (= (name field) "group") (name field) (str (namespace field) "." (name field))) :join (str (namespace field) "::" (name field)) (name field))))) (defn ^:private type->pig-type [type] (case type :int "int" :long "long" :float "float" :double "double" :string "chararray" :boolean "boolean" :binary "bytearray")) (def ^:private clj->op {"and" " AND " "or" " OR " "=" " == " "not=" " != " "<" " < " ">" " > " "<=" " <= " ">=" " >= "}) (defn ^:private expr->script ([expr] (expr->script {} expr)) ([scope expr] (cond (nil? expr) nil (number? expr) (cond ;; This is not ideal, but it prevents Pig from blowing up when you use big numbers (and (instance? Long expr) (not (< Integer/MIN_VALUE expr Integer/MAX_VALUE))) (str expr "L") :else (str expr)) (string? expr) (escape+quote expr) (symbol? expr) (if (.startsWith (name expr) "?") (subs (name expr) 1) (if-let [v (scope expr)] (expr->script scope v) (throw (ex-info (str "Unable to resolve symbol " expr) {:expr expr :scope scope})))) ;; TODO Verify arities ;; TODO Add NOT (seq? expr) (case (first expr) clojure.core/let (let [[_ scope body] expr scope (->> scope (partition 2) (map vec) (into {}))] (expr->script scope body)) quote (expr->script scope (second expr)) (let [[op & exprs] expr exprs' (map (partial expr->script scope) exprs) pig-expr (clojure.string/join (clj->op (name op)) exprs')] (str "(" pig-expr ")"))) :else (throw (IllegalArgumentException. (str "Unknown expression:" (type expr) " " expr)))))) ;; TODO add descriptive comment before each command (defmulti command->script "Converts an individual command into the equivalent Pig script" (fn [{:keys [type]} state] type)) ;; ********** Util ********** (s/defmethod command->script :field [{:keys [field]} :- m/FieldExpr {:keys [last-command]}] (let [context (some->> last-command name (re-find #"[a-z]+") keyword)] [nil (format-field context field)])) (s/defmethod command->script :code [{:keys [udf init func args]} :- m/CodeExpr {:keys [last-command]}] (let [id (raw/pigsym "udf") context (some->> last-command name (re-find #"[a-z]+") keyword) pig-args (->> args (map (partial format-field context)) (join ", ")) udf (pigpen.pig.runtime/udf-lookup udf)] [(str "DEFINE " id " " udf "(" (escape+quote init) "," (escape+quote func) ");\n\n") (str id "(" pig-args ")")])) (defmethod command->script :register [{:keys [jar]} state] {:pre [(string? jar) (not-empty jar)]} (str "REGISTER " jar ";\n\n")) (defmethod command->script :option [{:keys [option value]} state] {:pre [option value]} (str "SET " (name option) " " value ";\n\n")) ;; ********** IO ********** (defmulti storage->script (juxt :type :storage)) (defmethod storage->script [:load :binary] [{:keys [fields]}] (let [pig-fields (->> fields (map format-field) (join ", "))] (str "BinStorage()"))) (defmethod storage->script [:load :string] [{:keys [fields]}] (let [pig-fields (->> fields (map format-field) (map #(str % ":chararray")) (join ", "))] (str "PigStorage('\\n')\n AS (" pig-fields ")"))) (defmethod storage->script [:store :binary] [_] (str "BinStorage()")) (defmethod storage->script [:store :string] [_] (str "PigStorage()")) (defn storage->script' [command] (str "\n USING " (storage->script command))) (s/defmethod command->script :load [{:keys [id location] :as command} :- m/Load state] (let [pig-id (escape-id id) pig-storage (storage->script' command)] (str pig-id " = LOAD '" location "'" pig-storage ";\n\n"))) (s/defmethod command->script :store [{:keys [ancestors location] :as command} :- m/Store state] (let [relation-id (escape-id (first ancestors)) pig-storage (storage->script' command)] (str "STORE " relation-id " INTO '" location "'" pig-storage ";\n\n"))) ;; ********** Map ********** (s/defmethod command->script :projection [{:keys [expr flatten alias types] :as p} :- m/Projection state] (let [[pig-define pig-code] (command->script expr state) pig-code (if flatten (str "FLATTEN(" pig-code ")") pig-code) pig-schema (as-> alias % (map (fn [a t] (str (name a) (when (keyword? t) (str ":" (type->pig-type t))) (when (string? t) (str ":" t)))) % (concat types (repeat nil))) (join ", " %) (str " AS (" % ")"))] [pig-define (str pig-code pig-schema)])) (s/defmethod command->script :project [{:keys [id ancestors projections opts]} :- m/Project state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id) pig-projections (->> projections (mapv #(command->script % (assoc state :last-command (first ancestors))))) pig-defines (->> pig-projections (map first) (join)) pig-projections (->> pig-projections (map second) (join ",\n "))] (str pig-defines pig-id " = FOREACH " relation-id " GENERATE\n " pig-projections ";\n\n"))) (defmethod command->script :sort-opts [{:keys [parallel]} state] (let [pig-parallel (if parallel (str " PARALLEL " parallel))] (str pig-parallel))) (s/defmethod command->script :sort [{:keys [id ancestors key comp opts]} :- m/Sort state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id) pig-key (format-field key) pig-comp (clojure.string/upper-case (name comp)) pig-opts (command->script opts state)] (str pig-id " = ORDER " relation-id " BY " pig-key " " pig-comp pig-opts ";\n\n"))) (defmethod command->script :rank-opts [{:keys [dense]} state] (if dense " DENSE")) (s/defmethod command->script :rank [{:keys [id ancestors key comp opts]} :- (assoc m/Rank (s/optional-key :key) m/Field (s/optional-key :comp) (s/enum :asc :desc)) state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id) pig-sort (when key (str " BY " (format-field key) " " (clojure.string/upper-case (name comp)))) pig-opts (command->script opts state)] (str pig-id " = RANK " relation-id pig-sort pig-opts ";\n\n"))) ;; ********** Filter ********** (s/defmethod command->script :filter [{:keys [id ancestors expr]} :- m/Filter state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id) pig-expr (expr->script expr)] (if pig-expr (str pig-id " = FILTER " relation-id " BY " pig-expr ";\n\n") (str pig-id " = " relation-id ";\n\n")))) (s/defmethod command->script :take [{:keys [id ancestors n opts]} :- m/Take state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id)] (str pig-id " = LIMIT " relation-id " " n ";\n\n"))) (s/defmethod command->script :sample [{:keys [id ancestors p opts]} :- m/Sample state] (let [relation-id (escape-id (first ancestors)) pig-id (escape-id id)] (str pig-id " = SAMPLE " relation-id " " p ";\n\n"))) ;; ********** Join ********** (s/defmethod command->script :reduce [{:keys [id keys join-types ancestors opts]} :- m/Reduce state] (let [pig-id (escape-id id) relation-id (escape-id (first ancestors))] (str pig-id " = COGROUP " relation-id " ALL;\n\n"))) (defmethod command->script :group-opts [{:keys [strategy parallel]} state] (let [pig-using (if strategy (str " USING '" (name strategy) "'")) pig-parallel (if parallel (str " PARALLEL " parallel))] (str pig-using pig-parallel))) (s/defmethod command->script :group [{:keys [id keys join-types ancestors opts]} :- m/Group state] (let [pig-id (escape-id id) pig-clauses (join ", " (zip [r ancestors k keys j join-types] (str (escape-id r) " BY " (format-field k) (if (= j :required) " INNER")))) pig-opts (command->script opts state)] (str pig-id " = COGROUP " pig-clauses pig-opts ";\n\n"))) (defmethod command->script :join-opts [{:keys [strategy parallel]} state] (let [pig-using (if strategy (str " USING '" (name strategy) "'")) pig-parallel (if parallel (str " PARALLEL " parallel))] (str pig-using pig-parallel))) (s/defmethod command->script :join [{:keys [id keys join-types ancestors opts]} :- m/Join state] (let [pig-id (escape-id id) clauses (zip [r ancestors k keys] (str (escape-id r) " BY " (format-field k))) pig-join (case join-types [:required :optional] " LEFT OUTER" [:optional :required] " RIGHT OUTER" [:optional :optional] " FULL OUTER" "") pig-clauses (join (str pig-join ", ") clauses) pig-opts (command->script opts state)] (str pig-id " = JOIN " pig-clauses pig-opts ";\n\n"))) ;; ********** Set ********** (defmethod command->script :distinct-opts [{:keys [partition-by partition-type parallel]} {:keys [partitioner]}] (let [n (when partition-by (swap! partitioner inc)) pig-set (when partition-by (str "SET PigPenPartitioner" n "_type " (escape+quote (name (or partition-type :frozen))) ";\n" "SET PigPenPartitioner" n "_init '';\n" "SET PigPenPartitioner" n "_func " (escape+quote partition-by) ";\n\n")) pig-partition (when partition-by (str " PARTITION BY pigpen.PigPenPartitioner.PigPenPartitioner" n)) pig-parallel (when parallel (str " PARALLEL " parallel))] [pig-set (str pig-partition pig-parallel)])) (s/defmethod command->script :distinct [{:keys [id ancestors opts]} :- m/Distinct state] (let [relation-id (first ancestors) [pig-set pig-opts] (command->script opts state)] (str pig-set id " = DISTINCT " relation-id pig-opts ";\n\n"))) (defmethod command->script :concat-opts [{:keys [parallel]} state] (let [pig-parallel (if parallel (str " PARALLEL " parallel))] (str pig-parallel))) (s/defmethod command->script :concat [{:keys [id ancestors opts]} :- m/Concat state] (let [pig-id (escape-id id) pig-ancestors (->> ancestors (map escape-id) (join ", ")) pig-opts (command->script opts state)] (str pig-id " = UNION " pig-ancestors pig-opts ";\n\n"))) ;; ********** Script ********** (s/defmethod command->script :noop [{:keys [id ancestors fields]} :- m/NoOp state] (let [relation-id (first ancestors)] (str id " = FOREACH " relation-id " GENERATE\n " (join ", " (map format-field fields)) ";\n\n"))) (defmethod command->script :store-many [command state] "-- Generated by PigPen: https://github.com/Netflix/PigPen\n\n") (defn commands->script "Transforms a sequence of commands into a Pig script" [commands] (binding [*print-length* false *print-level* false] (let [state {:partitioner (atom -1)}] (apply str (for [command commands] (command->script command state))))))
[ { "context": "rds {:pits [1]} :items {:arrows [1]} :players {\"joe\" {}})]\n (should= {1 {}} (:caverns game))\n ", "end": 752, "score": 0.5010281801223755, "start": 751, "tag": "NAME", "value": "e" }, { "context": "\"\n (dosync\n (alter @game kill-player \"Thor\" \"wumpus\"))\n (let [command (fn [game player]", "end": 2036, "score": 0.9715350866317749, "start": 2032, "tag": "NAME", "value": "Thor" }, { "context": "(dosync\n (alter @game kill-player \"Thor\" \"wumpus\"))\n (let [command (fn [game player] (assoc g", "end": 2045, "score": 0.48335301876068115, "start": 2040, "tag": "USERNAME", "value": "umpus" }, { "context": "\"\n (dosync\n (alter @game kill-player \"Thor\" \"wumpus\"))\n (let [report (perform-command @", "end": 2289, "score": 0.9578619599342346, "start": 2285, "tag": "NAME", "value": "Thor" }, { "context": " (dosync\n (alter @game kill-player \"Thor\" \"wumpus\"))\n (let [report (perform-command @game \"Tho", "end": 2298, "score": 0.5952132940292358, "start": 2292, "tag": "USERNAME", "value": "wumpus" } ]
hunt_the_wumpus/spec/hunt_the_wumpus/model/game_spec.clj
trptcolin/clojureslim
5
(ns hunt-the-wumpus.model.game-spec (:use [speclj.core] [hunt-the-wumpus.model.game] [hunt-the-wumpus.model.report :only (hazard-report player-report item-report game-over-report)] [hunt-the-wumpus.model.item :only (items-of items-in place-item)] [hunt-the-wumpus.model.player :only (place-player kill-player player-dead?)] [hunt-the-wumpus.model.hazard :only (place-hazard)])) (describe "Game" (it "creating an empty game" (let [game (new-game)] (should= {} (:caverns game)) (should= {} (:hazards game)) (should= {} (:items game)) (should= {} (:players game)))) (it "creates a populated game" (let [game (new-game :caverns {1 {}} :hazards {:pits [1]} :items {:arrows [1]} :players {"joe" {}})] (should= {1 {}} (:caverns game)) (should= {:pits [1]} (:hazards game)) (should= {:arrows [1]} (:items game)) (should= {"joe" {}} (:players game)))) (it "performs a command" (let [game-ref (ref (new-game :caverns {1 {:east 2}} :players {"player-1" {:cavern 1}})) report (perform-command game-ref "player-1" (fn [game player] (assoc game :foo player)))] (should= "player-1" (:foo @game-ref)) (should= ["You can go east."] (:cavern-messages report)))) (context "with arrows" (with game (ref (-> (new-game :caverns {1 {:east 2}}) (place-player "Thor" 1) (place-item :arrow 1)))) (it "players pick up items in the current room" (should= [:arrow] (items-in @@game 1)) (perform-command @game "Thor" (fn [game player] game)) (should= [] (items-in @@game 1)) (should= [:arrow] (items-of @@game "Thor"))) (it "player dies when meeting the wumpus" (dosync (alter @game place-hazard "wumpus" 1)) (let [command (fn [game player] game)] (perform-command @game "Thor" command) (should= true (player-dead? @@game "Thor")))) (it "dead players are not allowed to do stuff" (dosync (alter @game kill-player "Thor" "wumpus")) (let [command (fn [game player] (assoc game :fooey true))] (perform-command @game "Thor" command) (should= nil (:fooey @@game)))) (it "reports a player is dead" (dosync (alter @game kill-player "Thor" "wumpus")) (let [report (perform-command @game "Thor" (fn [game player] game))] (should= "Your game is over. Go in peace." (:error report)))) ) (it "reports hazards" (with-redefs [hazard-report (fn [& args] ["Woohoo!"])] (let [report (perform-command (ref (new-game)) "player-1" (fn [game player]))] (should= ["Woohoo!"] (:hazard-messages report))))) (it "reports the end of the game" (with-redefs [game-over-report (fn [& args] ["Oh noez..."])] (let [report (perform-command (ref (new-game)) "player-1" (fn [game player]))] (should= {:game-over-messages ["Oh noez..."]} report)))) (it "reports player events" (with-redefs [player-report (fn [& args] ["Yahoo!"])] (let [report (perform-command (ref (new-game)) "player-1" (fn [game player]))] (should= ["Yahoo!"] (:player-messages report))))) (it "reports on items" (with-redefs [item-report (fn [& args] ["Stuff!"])] (let [report (perform-command (ref (new-game)) "player-1" (fn [game player]))] (should= ["Stuff!"] (:item-messages report))))) )
36224
(ns hunt-the-wumpus.model.game-spec (:use [speclj.core] [hunt-the-wumpus.model.game] [hunt-the-wumpus.model.report :only (hazard-report player-report item-report game-over-report)] [hunt-the-wumpus.model.item :only (items-of items-in place-item)] [hunt-the-wumpus.model.player :only (place-player kill-player player-dead?)] [hunt-the-wumpus.model.hazard :only (place-hazard)])) (describe "Game" (it "creating an empty game" (let [game (new-game)] (should= {} (:caverns game)) (should= {} (:hazards game)) (should= {} (:items game)) (should= {} (:players game)))) (it "creates a populated game" (let [game (new-game :caverns {1 {}} :hazards {:pits [1]} :items {:arrows [1]} :players {"jo<NAME>" {}})] (should= {1 {}} (:caverns game)) (should= {:pits [1]} (:hazards game)) (should= {:arrows [1]} (:items game)) (should= {"joe" {}} (:players game)))) (it "performs a command" (let [game-ref (ref (new-game :caverns {1 {:east 2}} :players {"player-1" {:cavern 1}})) report (perform-command game-ref "player-1" (fn [game player] (assoc game :foo player)))] (should= "player-1" (:foo @game-ref)) (should= ["You can go east."] (:cavern-messages report)))) (context "with arrows" (with game (ref (-> (new-game :caverns {1 {:east 2}}) (place-player "Thor" 1) (place-item :arrow 1)))) (it "players pick up items in the current room" (should= [:arrow] (items-in @@game 1)) (perform-command @game "Thor" (fn [game player] game)) (should= [] (items-in @@game 1)) (should= [:arrow] (items-of @@game "Thor"))) (it "player dies when meeting the wumpus" (dosync (alter @game place-hazard "wumpus" 1)) (let [command (fn [game player] game)] (perform-command @game "Thor" command) (should= true (player-dead? @@game "Thor")))) (it "dead players are not allowed to do stuff" (dosync (alter @game kill-player "<NAME>" "wumpus")) (let [command (fn [game player] (assoc game :fooey true))] (perform-command @game "Thor" command) (should= nil (:fooey @@game)))) (it "reports a player is dead" (dosync (alter @game kill-player "<NAME>" "wumpus")) (let [report (perform-command @game "Thor" (fn [game player] game))] (should= "Your game is over. Go in peace." (:error report)))) ) (it "reports hazards" (with-redefs [hazard-report (fn [& args] ["Woohoo!"])] (let [report (perform-command (ref (new-game)) "player-1" (fn [game player]))] (should= ["Woohoo!"] (:hazard-messages report))))) (it "reports the end of the game" (with-redefs [game-over-report (fn [& args] ["Oh noez..."])] (let [report (perform-command (ref (new-game)) "player-1" (fn [game player]))] (should= {:game-over-messages ["Oh noez..."]} report)))) (it "reports player events" (with-redefs [player-report (fn [& args] ["Yahoo!"])] (let [report (perform-command (ref (new-game)) "player-1" (fn [game player]))] (should= ["Yahoo!"] (:player-messages report))))) (it "reports on items" (with-redefs [item-report (fn [& args] ["Stuff!"])] (let [report (perform-command (ref (new-game)) "player-1" (fn [game player]))] (should= ["Stuff!"] (:item-messages report))))) )
true
(ns hunt-the-wumpus.model.game-spec (:use [speclj.core] [hunt-the-wumpus.model.game] [hunt-the-wumpus.model.report :only (hazard-report player-report item-report game-over-report)] [hunt-the-wumpus.model.item :only (items-of items-in place-item)] [hunt-the-wumpus.model.player :only (place-player kill-player player-dead?)] [hunt-the-wumpus.model.hazard :only (place-hazard)])) (describe "Game" (it "creating an empty game" (let [game (new-game)] (should= {} (:caverns game)) (should= {} (:hazards game)) (should= {} (:items game)) (should= {} (:players game)))) (it "creates a populated game" (let [game (new-game :caverns {1 {}} :hazards {:pits [1]} :items {:arrows [1]} :players {"joPI:NAME:<NAME>END_PI" {}})] (should= {1 {}} (:caverns game)) (should= {:pits [1]} (:hazards game)) (should= {:arrows [1]} (:items game)) (should= {"joe" {}} (:players game)))) (it "performs a command" (let [game-ref (ref (new-game :caverns {1 {:east 2}} :players {"player-1" {:cavern 1}})) report (perform-command game-ref "player-1" (fn [game player] (assoc game :foo player)))] (should= "player-1" (:foo @game-ref)) (should= ["You can go east."] (:cavern-messages report)))) (context "with arrows" (with game (ref (-> (new-game :caverns {1 {:east 2}}) (place-player "Thor" 1) (place-item :arrow 1)))) (it "players pick up items in the current room" (should= [:arrow] (items-in @@game 1)) (perform-command @game "Thor" (fn [game player] game)) (should= [] (items-in @@game 1)) (should= [:arrow] (items-of @@game "Thor"))) (it "player dies when meeting the wumpus" (dosync (alter @game place-hazard "wumpus" 1)) (let [command (fn [game player] game)] (perform-command @game "Thor" command) (should= true (player-dead? @@game "Thor")))) (it "dead players are not allowed to do stuff" (dosync (alter @game kill-player "PI:NAME:<NAME>END_PI" "wumpus")) (let [command (fn [game player] (assoc game :fooey true))] (perform-command @game "Thor" command) (should= nil (:fooey @@game)))) (it "reports a player is dead" (dosync (alter @game kill-player "PI:NAME:<NAME>END_PI" "wumpus")) (let [report (perform-command @game "Thor" (fn [game player] game))] (should= "Your game is over. Go in peace." (:error report)))) ) (it "reports hazards" (with-redefs [hazard-report (fn [& args] ["Woohoo!"])] (let [report (perform-command (ref (new-game)) "player-1" (fn [game player]))] (should= ["Woohoo!"] (:hazard-messages report))))) (it "reports the end of the game" (with-redefs [game-over-report (fn [& args] ["Oh noez..."])] (let [report (perform-command (ref (new-game)) "player-1" (fn [game player]))] (should= {:game-over-messages ["Oh noez..."]} report)))) (it "reports player events" (with-redefs [player-report (fn [& args] ["Yahoo!"])] (let [report (perform-command (ref (new-game)) "player-1" (fn [game player]))] (should= ["Yahoo!"] (:player-messages report))))) (it "reports on items" (with-redefs [item-report (fn [& args] ["Stuff!"])] (let [report (perform-command (ref (new-game)) "player-1" (fn [game player]))] (should= ["Stuff!"] (:item-messages report))))) )
[ { "context": "cription \"Timetracker\"\n :url \"https://github.com/lshift/timetracker-web\"\n :license {:name \"Proprietary\"}", "end": 95, "score": 0.999455451965332, "start": 89, "tag": "USERNAME", "value": "lshift" }, { "context": "act-with-addons \"15.2.1-0\"]\n [com.andrewmcveigh/cljs-time \"0.5.0-alpha1\"]\n [com.f", "end": 547, "score": 0.7462738156318665, "start": 534, "tag": "USERNAME", "value": "andrewmcveigh" }, { "context": " [org.seleniumhq.selenium/selenium-server \"2.52.0\"]\n [com.fasterxm", "end": 4013, "score": 0.9914321899414062, "start": 4007, "tag": "IP_ADDRESS", "value": "2.52.0" }, { "context": " [com.fasterxml.jackson.core/jackson-databind \"2.4.1.3\"]\n [hickory \"0.6", "end": 4103, "score": 0.9905611872673035, "start": 4096, "tag": "IP_ADDRESS", "value": "2.4.1.3" } ]
project.clj
lshift/timetracker
0
(defproject time-tracker "1.0.0" :description "Timetracker" :url "https://github.com/lshift/timetracker-web" :license {:name "Proprietary"} :min-lein-version "2.0.0" ;; Note to developer. Please keep these sorted in alphabetical order. :dependencies [[ch.qos.logback/logback-classic "1.1.6"] [clj-bonecp-url "0.1.1"] [clj-http "2.2.0"] [clj-time "0.11.0"] [cljs-ajax "0.5.8"] [cljsjs/react-with-addons "15.2.1-0"] [com.andrewmcveigh/cljs-time "0.5.0-alpha1"] [com.fasterxml.jackson.core/jackson-core "2.7.3"] [com.google.guava/guava "19.0"] [com.jolbox/bonecp "0.8.0.RELEASE"] [com.stuartsierra/component "0.3.1"] [commons-codec "1.10"] [compojure "1.5.1"] [enlive "1.1.6"] [environ "1.0.3"] [kioo "0.5.0-SNAPSHOT" :exclusions [cljsjs/react]] [liberator "0.14.0"] [org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "1.9.293"] [org.clojure/core.async "0.2.374"] [org.clojure/core.match "0.2.2"] [org.clojure/data.json "0.2.6"] [org.clojure/java.jdbc "0.6.1"] [org.clojure/test.check "0.9.0"] [org.clojure/tools.logging "0.3.1"] [org.clojure/tools.nrepl "0.2.12"] [org.flywaydb/flyway-core "4.0"] [postgresql/postgresql "9.3-1102.jdbc41"] [prismatic/schema "1.0.5"] [reagent "0.6.0" :exclusions [cljsjs/react]] [ring "1.5.0"] [ring/ring-jetty-adapter "1.5.0"] [ring/ring-json "0.4.0"] [com.cemerick/url "0.1.1"] [sablono "0.7.0" :exclusions [cljsjs/react]] [secretary "1.2.3"] [yesql "0.5.3"]] ; Note that these only seem to apply to application dependencies, not plugins ; If you have a common dependency, lock it down in :dependencies not here :managed-dependencies [[com.cemerick/clojurescript.test "0.1.0"] [com.google.code.gson/gson "2.3.1"] [commons-io "2.5"] [hiccup "1.0.5"] [org.eclipse.jetty/jetty-io "9.2.12.v20150709"] [org.eclipse.jetty/jetty-util "9.2.12.v20150709"]] :plugins [[lein-cljsbuild "1.1.3"] [lein-shell "0.5.0"] [lein-environ "1.0.3"] [lein-cljfmt "0.5.3" :exclusions [org.clojure/clojure]]] :profiles {:dev {:plugins [[com.cemerick/austin "0.1.6" :exclusions [org.clojure/clojurescript org.clojure/clojure]] [lein-doo "0.1.6" :exclusions [org.clojure/clojure]] [lein-junit "1.1.8" :exclusions [org.clojure/clojure]] [lein-figwheel "0.5.8" :exclusions [org.clojure/clojure]] [lein-auto "0.1.2"]] :dependencies [[org.clojure/tools.namespace "0.2.10"] [ring/ring-mock "0.3.0"] [com.cemerick/pomegranate "0.3.0"] [org.codehaus.plexus/plexus-utils "3.0"] [com.hypirion/io "0.3.1"] [org.hamcrest/hamcrest-library "1.3"] [junit/junit "4.12"] [org.apache.commons/commons-pool2 "2.2"] [org.apache.commons/commons-lang3 "3.4"] [org.seleniumhq.selenium/selenium-java "2.52.0"] [org.seleniumhq.selenium/selenium-htmlunit-driver "2.52.0"] [org.seleniumhq.selenium/selenium-server "2.52.0"] [com.fasterxml.jackson.core/jackson-databind "2.4.1.3"] [hickory "0.6.0"] [clj-webdriver "0.7.2"]] :source-paths ["dev"] :junit ["test/java"] :junit-formatter "xml" :junit-results-dir "test-results" :java-source-paths ["test/java"] :junit-test-file-pattern #".*IT.java$" :aot ^:replace []} :local-dev {:env {:database-url "postgres://timetracker:ttpass6@localhost/timetracker-test"}} :teamcity {:plugins [[lein-teamcity "0.2.2"]] :monkeypatch-clojure-test false}} :source-paths ["src/clj" "test/clj"] :resource-paths ["resources"] :aot [time-tracker.main, clojure.tools.logging.impl] :main time-tracker.main :repl-options {:init-ns user} :javac-options ["-target" "1.8" "-source" "1.8"] :jvm-opts ^:replace ["-XX:-TieredCompilation"] :doo {:build "test" :debug true} :figwheel {:repl false} :cljsbuild {:builds {:dev {:source-paths ["src/clj"] :figwheel {:on-jsload "time-tracker.bootstrap/fig-reload"} :compiler {:main time-tracker.bootstrap :output-to "target/classes/time_tracker/public/out/timetracker.js" :output-dir "target/classes/time_tracker/public/out" :asset-path "out" :optimizations :none :source-map true}} :prod {:source-paths ["src/clj"] :compiler {:main time-tracker.bootstrap :output-to "target/classes/time_tracker/public/out/timetracker.js" :output-dir "target/classes/time_tracker/public/out/prod-js" :optimizations :advanced :source-map "target/classes/time_tracker/public/out/timetracker.js.map"}} :test {:source-paths ["src/clj" "test/clj"] :compiler {:main time-tracker.core-test :target :nodejs :output-to "target/cljs/run-tests.js" :output-dir "target/cljs" :optimizations :none :pretty-print true}}}})
51456
(defproject time-tracker "1.0.0" :description "Timetracker" :url "https://github.com/lshift/timetracker-web" :license {:name "Proprietary"} :min-lein-version "2.0.0" ;; Note to developer. Please keep these sorted in alphabetical order. :dependencies [[ch.qos.logback/logback-classic "1.1.6"] [clj-bonecp-url "0.1.1"] [clj-http "2.2.0"] [clj-time "0.11.0"] [cljs-ajax "0.5.8"] [cljsjs/react-with-addons "15.2.1-0"] [com.andrewmcveigh/cljs-time "0.5.0-alpha1"] [com.fasterxml.jackson.core/jackson-core "2.7.3"] [com.google.guava/guava "19.0"] [com.jolbox/bonecp "0.8.0.RELEASE"] [com.stuartsierra/component "0.3.1"] [commons-codec "1.10"] [compojure "1.5.1"] [enlive "1.1.6"] [environ "1.0.3"] [kioo "0.5.0-SNAPSHOT" :exclusions [cljsjs/react]] [liberator "0.14.0"] [org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "1.9.293"] [org.clojure/core.async "0.2.374"] [org.clojure/core.match "0.2.2"] [org.clojure/data.json "0.2.6"] [org.clojure/java.jdbc "0.6.1"] [org.clojure/test.check "0.9.0"] [org.clojure/tools.logging "0.3.1"] [org.clojure/tools.nrepl "0.2.12"] [org.flywaydb/flyway-core "4.0"] [postgresql/postgresql "9.3-1102.jdbc41"] [prismatic/schema "1.0.5"] [reagent "0.6.0" :exclusions [cljsjs/react]] [ring "1.5.0"] [ring/ring-jetty-adapter "1.5.0"] [ring/ring-json "0.4.0"] [com.cemerick/url "0.1.1"] [sablono "0.7.0" :exclusions [cljsjs/react]] [secretary "1.2.3"] [yesql "0.5.3"]] ; Note that these only seem to apply to application dependencies, not plugins ; If you have a common dependency, lock it down in :dependencies not here :managed-dependencies [[com.cemerick/clojurescript.test "0.1.0"] [com.google.code.gson/gson "2.3.1"] [commons-io "2.5"] [hiccup "1.0.5"] [org.eclipse.jetty/jetty-io "9.2.12.v20150709"] [org.eclipse.jetty/jetty-util "9.2.12.v20150709"]] :plugins [[lein-cljsbuild "1.1.3"] [lein-shell "0.5.0"] [lein-environ "1.0.3"] [lein-cljfmt "0.5.3" :exclusions [org.clojure/clojure]]] :profiles {:dev {:plugins [[com.cemerick/austin "0.1.6" :exclusions [org.clojure/clojurescript org.clojure/clojure]] [lein-doo "0.1.6" :exclusions [org.clojure/clojure]] [lein-junit "1.1.8" :exclusions [org.clojure/clojure]] [lein-figwheel "0.5.8" :exclusions [org.clojure/clojure]] [lein-auto "0.1.2"]] :dependencies [[org.clojure/tools.namespace "0.2.10"] [ring/ring-mock "0.3.0"] [com.cemerick/pomegranate "0.3.0"] [org.codehaus.plexus/plexus-utils "3.0"] [com.hypirion/io "0.3.1"] [org.hamcrest/hamcrest-library "1.3"] [junit/junit "4.12"] [org.apache.commons/commons-pool2 "2.2"] [org.apache.commons/commons-lang3 "3.4"] [org.seleniumhq.selenium/selenium-java "2.52.0"] [org.seleniumhq.selenium/selenium-htmlunit-driver "2.52.0"] [org.seleniumhq.selenium/selenium-server "2.52.0"] [com.fasterxml.jackson.core/jackson-databind "172.16.58.3"] [hickory "0.6.0"] [clj-webdriver "0.7.2"]] :source-paths ["dev"] :junit ["test/java"] :junit-formatter "xml" :junit-results-dir "test-results" :java-source-paths ["test/java"] :junit-test-file-pattern #".*IT.java$" :aot ^:replace []} :local-dev {:env {:database-url "postgres://timetracker:ttpass6@localhost/timetracker-test"}} :teamcity {:plugins [[lein-teamcity "0.2.2"]] :monkeypatch-clojure-test false}} :source-paths ["src/clj" "test/clj"] :resource-paths ["resources"] :aot [time-tracker.main, clojure.tools.logging.impl] :main time-tracker.main :repl-options {:init-ns user} :javac-options ["-target" "1.8" "-source" "1.8"] :jvm-opts ^:replace ["-XX:-TieredCompilation"] :doo {:build "test" :debug true} :figwheel {:repl false} :cljsbuild {:builds {:dev {:source-paths ["src/clj"] :figwheel {:on-jsload "time-tracker.bootstrap/fig-reload"} :compiler {:main time-tracker.bootstrap :output-to "target/classes/time_tracker/public/out/timetracker.js" :output-dir "target/classes/time_tracker/public/out" :asset-path "out" :optimizations :none :source-map true}} :prod {:source-paths ["src/clj"] :compiler {:main time-tracker.bootstrap :output-to "target/classes/time_tracker/public/out/timetracker.js" :output-dir "target/classes/time_tracker/public/out/prod-js" :optimizations :advanced :source-map "target/classes/time_tracker/public/out/timetracker.js.map"}} :test {:source-paths ["src/clj" "test/clj"] :compiler {:main time-tracker.core-test :target :nodejs :output-to "target/cljs/run-tests.js" :output-dir "target/cljs" :optimizations :none :pretty-print true}}}})
true
(defproject time-tracker "1.0.0" :description "Timetracker" :url "https://github.com/lshift/timetracker-web" :license {:name "Proprietary"} :min-lein-version "2.0.0" ;; Note to developer. Please keep these sorted in alphabetical order. :dependencies [[ch.qos.logback/logback-classic "1.1.6"] [clj-bonecp-url "0.1.1"] [clj-http "2.2.0"] [clj-time "0.11.0"] [cljs-ajax "0.5.8"] [cljsjs/react-with-addons "15.2.1-0"] [com.andrewmcveigh/cljs-time "0.5.0-alpha1"] [com.fasterxml.jackson.core/jackson-core "2.7.3"] [com.google.guava/guava "19.0"] [com.jolbox/bonecp "0.8.0.RELEASE"] [com.stuartsierra/component "0.3.1"] [commons-codec "1.10"] [compojure "1.5.1"] [enlive "1.1.6"] [environ "1.0.3"] [kioo "0.5.0-SNAPSHOT" :exclusions [cljsjs/react]] [liberator "0.14.0"] [org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "1.9.293"] [org.clojure/core.async "0.2.374"] [org.clojure/core.match "0.2.2"] [org.clojure/data.json "0.2.6"] [org.clojure/java.jdbc "0.6.1"] [org.clojure/test.check "0.9.0"] [org.clojure/tools.logging "0.3.1"] [org.clojure/tools.nrepl "0.2.12"] [org.flywaydb/flyway-core "4.0"] [postgresql/postgresql "9.3-1102.jdbc41"] [prismatic/schema "1.0.5"] [reagent "0.6.0" :exclusions [cljsjs/react]] [ring "1.5.0"] [ring/ring-jetty-adapter "1.5.0"] [ring/ring-json "0.4.0"] [com.cemerick/url "0.1.1"] [sablono "0.7.0" :exclusions [cljsjs/react]] [secretary "1.2.3"] [yesql "0.5.3"]] ; Note that these only seem to apply to application dependencies, not plugins ; If you have a common dependency, lock it down in :dependencies not here :managed-dependencies [[com.cemerick/clojurescript.test "0.1.0"] [com.google.code.gson/gson "2.3.1"] [commons-io "2.5"] [hiccup "1.0.5"] [org.eclipse.jetty/jetty-io "9.2.12.v20150709"] [org.eclipse.jetty/jetty-util "9.2.12.v20150709"]] :plugins [[lein-cljsbuild "1.1.3"] [lein-shell "0.5.0"] [lein-environ "1.0.3"] [lein-cljfmt "0.5.3" :exclusions [org.clojure/clojure]]] :profiles {:dev {:plugins [[com.cemerick/austin "0.1.6" :exclusions [org.clojure/clojurescript org.clojure/clojure]] [lein-doo "0.1.6" :exclusions [org.clojure/clojure]] [lein-junit "1.1.8" :exclusions [org.clojure/clojure]] [lein-figwheel "0.5.8" :exclusions [org.clojure/clojure]] [lein-auto "0.1.2"]] :dependencies [[org.clojure/tools.namespace "0.2.10"] [ring/ring-mock "0.3.0"] [com.cemerick/pomegranate "0.3.0"] [org.codehaus.plexus/plexus-utils "3.0"] [com.hypirion/io "0.3.1"] [org.hamcrest/hamcrest-library "1.3"] [junit/junit "4.12"] [org.apache.commons/commons-pool2 "2.2"] [org.apache.commons/commons-lang3 "3.4"] [org.seleniumhq.selenium/selenium-java "2.52.0"] [org.seleniumhq.selenium/selenium-htmlunit-driver "2.52.0"] [org.seleniumhq.selenium/selenium-server "2.52.0"] [com.fasterxml.jackson.core/jackson-databind "PI:IP_ADDRESS:172.16.58.3END_PI"] [hickory "0.6.0"] [clj-webdriver "0.7.2"]] :source-paths ["dev"] :junit ["test/java"] :junit-formatter "xml" :junit-results-dir "test-results" :java-source-paths ["test/java"] :junit-test-file-pattern #".*IT.java$" :aot ^:replace []} :local-dev {:env {:database-url "postgres://timetracker:ttpass6@localhost/timetracker-test"}} :teamcity {:plugins [[lein-teamcity "0.2.2"]] :monkeypatch-clojure-test false}} :source-paths ["src/clj" "test/clj"] :resource-paths ["resources"] :aot [time-tracker.main, clojure.tools.logging.impl] :main time-tracker.main :repl-options {:init-ns user} :javac-options ["-target" "1.8" "-source" "1.8"] :jvm-opts ^:replace ["-XX:-TieredCompilation"] :doo {:build "test" :debug true} :figwheel {:repl false} :cljsbuild {:builds {:dev {:source-paths ["src/clj"] :figwheel {:on-jsload "time-tracker.bootstrap/fig-reload"} :compiler {:main time-tracker.bootstrap :output-to "target/classes/time_tracker/public/out/timetracker.js" :output-dir "target/classes/time_tracker/public/out" :asset-path "out" :optimizations :none :source-map true}} :prod {:source-paths ["src/clj"] :compiler {:main time-tracker.bootstrap :output-to "target/classes/time_tracker/public/out/timetracker.js" :output-dir "target/classes/time_tracker/public/out/prod-js" :optimizations :advanced :source-map "target/classes/time_tracker/public/out/timetracker.js.map"}} :test {:source-paths ["src/clj" "test/clj"] :compiler {:main time-tracker.core-test :target :nodejs :output-to "target/cljs/run-tests.js" :output-dir "target/cljs" :optimizations :none :pretty-print true}}}})
[ { "context": " (if username\n [id (assoc settings :username username :password password)]\n [id settings])))\n\n(def", "end": 1122, "score": 0.5443965792655945, "start": 1114, "tag": "USERNAME", "value": "username" }, { "context": " password (.readPassword (System/console) \"%s\"\n (into-array [", "end": 2028, "score": 0.9142105579376221, "start": 2027, "tag": "PASSWORD", "value": "s" }, { "context": "ssword: \"]))]\n [id (assoc settings :username username :password password)]))))\n\n(defn repo-for [project", "end": 2140, "score": 0.9014809131622314, "start": 2132, "tag": "USERNAME", "value": "username" } ]
test/conflicts/mined/leiningen-0e132292b715c0f59fe22f5556025ab6183655da-153eda65b7f8be8e0744d1cdc65ca227f03eff3/B.clj
nazrhom/vcs-clojure
3
(ns leiningen.deploy "Build and deploy jar to remote repository." (:require [cemerick.pomegranate.aether :as aether] [leiningen.core.classpath :as classpath] [leiningen.core.main :as main] [leiningen.core.eval :as eval] [leiningen.core.user :as user] [leiningen.core.utils :as utils] [clojure.java.io :as io] [leiningen.pom :as pom] [leiningen.jar :as jar] [clojure.java.shell :as sh] [clojure.string :as str])) (defn- abort-message [message] (cond (re-find #"Return code is 405" message) (str message "\n" "Ensure you are deploying over SSL.") (re-find #"Return code is 401" message) (str message "\n" "See `lein help deploy` for an explanation of how to" " specify credentials.") :else message)) (defn add-auth-from-url [[id settings]] (let [url (utils/build-url id) user-info (and url (.getUserInfo url)) [username password] (and user-info (.split user-info ":"))] (if username [id (assoc settings :username username :password password)] [id settings]))) (defn add-auth-interactively [[id settings]] (cond (or (and (:username settings) (some settings [:password :passphrase :private-key-file])) (.startsWith (:url settings) "file://")) [id settings] @utils/rebound-io? (main/abort "No credentials found for" id "\nPassword prompts are not supported when ran after other" "(potentially)\ninteractive tasks. Maybe setting up credentials" "may be an idea?\n\nSee `lein help gpg` for an explanation of" "how to specify credentials.") :else (do (println "No credentials found for" id) (println "See `lein help gpg` for how to configure credentials.") (print "Username: ") (flush) (let [username (read-line) password (.readPassword (System/console) "%s" (into-array ["Password: "]))] [id (assoc settings :username username :password password)])))) (defn repo-for [project name] (let [[settings] (for [[id settings] (concat (:deploy-repositories project) (:repositories project) [[name {:url name}]]) :when (= id name)] settings)] (-> [name settings] (classpath/add-repo-auth) (add-auth-from-url) (add-auth-interactively)))) (defn sign [file] (let [exit (binding [*out* (java.io.StringWriter.) eval/*pump-in* false] ; gpg handles reading by itself (eval/sh (user/gpg-program) "--yes" "-ab" "--" file))] (when-not (zero? exit) (main/abort "Could not sign" file)) (str file ".asc"))) (defn signature-for [extension file] {[:extension extension] (sign file)}) (defn signature-for-artifact [[coords artifact-file]] {(apply concat (update-in (apply hash-map coords) [:extension] #(str (or % "jar") ".asc"))) (sign artifact-file)}) (defn sign-for-repo? [repo] (:sign-releases (second repo) true)) (defn files-for [project signed?] (let [artifacts (merge {[:extension "pom"] (pom/pom project)} (jar/jar project))] (if (and signed? (not (.endsWith (:version project) "-SNAPSHOT"))) (reduce merge artifacts (map signature-for-artifact artifacts)) artifacts))) (defn warn-missing-metadata [project] (doseq [key [:description :license :url]] (when (or (nil? (project key)) (re-find #"FIXME" (str (project key)))) (main/info "WARNING: please set" key "in project.clj.")))) (defn- in-branches [branches] (-> (sh/sh "git" "rev-parse" "--abbrev-ref" "HEAD") :out butlast str/join branches not)) (defn deploy "Build jar and deploy to remote repository. The target repository will be looked up in :repositories in project.clj: :repositories [[\"snapshots\" \"https://internal.repo/snapshots\"] [\"releases\" \"https://internal.repo/releases\"] [\"alternate\" \"https://other.server/repo\"]] If you don't provide a repository name to deploy to, either \"snapshots\" or \"releases\" will be used depending on your project's current version. See `lein help deploying` under \"Authentication\" for instructions on how to configure your credentials so you are not prompted on each deploy." ([project repository-name] (let [branches (set (:deploy-branches project))] (when (and (seq branches) (in-branches branches)) (apply main/abort "Can only deploy from branches listed in :deploy-branches:" branches))) (warn-missing-metadata project) (let [repo (repo-for project repository-name) files (files-for project (sign-for-repo? repo))] (try (main/debug "Deploying" files "to" repo) (aether/deploy :coordinates [(symbol (:group project) (:name project)) (:version project)] :artifact-map files :transfer-listener :stdout :repository [repo]) (catch org.sonatype.aether.deployment.DeploymentException e (when main/*debug* (.printStackTrace e)) (main/abort (abort-message (.getMessage e))))))) ([project] (deploy project (if (pom/snapshot? project) "snapshots" "releases"))))
108872
(ns leiningen.deploy "Build and deploy jar to remote repository." (:require [cemerick.pomegranate.aether :as aether] [leiningen.core.classpath :as classpath] [leiningen.core.main :as main] [leiningen.core.eval :as eval] [leiningen.core.user :as user] [leiningen.core.utils :as utils] [clojure.java.io :as io] [leiningen.pom :as pom] [leiningen.jar :as jar] [clojure.java.shell :as sh] [clojure.string :as str])) (defn- abort-message [message] (cond (re-find #"Return code is 405" message) (str message "\n" "Ensure you are deploying over SSL.") (re-find #"Return code is 401" message) (str message "\n" "See `lein help deploy` for an explanation of how to" " specify credentials.") :else message)) (defn add-auth-from-url [[id settings]] (let [url (utils/build-url id) user-info (and url (.getUserInfo url)) [username password] (and user-info (.split user-info ":"))] (if username [id (assoc settings :username username :password password)] [id settings]))) (defn add-auth-interactively [[id settings]] (cond (or (and (:username settings) (some settings [:password :passphrase :private-key-file])) (.startsWith (:url settings) "file://")) [id settings] @utils/rebound-io? (main/abort "No credentials found for" id "\nPassword prompts are not supported when ran after other" "(potentially)\ninteractive tasks. Maybe setting up credentials" "may be an idea?\n\nSee `lein help gpg` for an explanation of" "how to specify credentials.") :else (do (println "No credentials found for" id) (println "See `lein help gpg` for how to configure credentials.") (print "Username: ") (flush) (let [username (read-line) password (.readPassword (System/console) "%<PASSWORD>" (into-array ["Password: "]))] [id (assoc settings :username username :password password)])))) (defn repo-for [project name] (let [[settings] (for [[id settings] (concat (:deploy-repositories project) (:repositories project) [[name {:url name}]]) :when (= id name)] settings)] (-> [name settings] (classpath/add-repo-auth) (add-auth-from-url) (add-auth-interactively)))) (defn sign [file] (let [exit (binding [*out* (java.io.StringWriter.) eval/*pump-in* false] ; gpg handles reading by itself (eval/sh (user/gpg-program) "--yes" "-ab" "--" file))] (when-not (zero? exit) (main/abort "Could not sign" file)) (str file ".asc"))) (defn signature-for [extension file] {[:extension extension] (sign file)}) (defn signature-for-artifact [[coords artifact-file]] {(apply concat (update-in (apply hash-map coords) [:extension] #(str (or % "jar") ".asc"))) (sign artifact-file)}) (defn sign-for-repo? [repo] (:sign-releases (second repo) true)) (defn files-for [project signed?] (let [artifacts (merge {[:extension "pom"] (pom/pom project)} (jar/jar project))] (if (and signed? (not (.endsWith (:version project) "-SNAPSHOT"))) (reduce merge artifacts (map signature-for-artifact artifacts)) artifacts))) (defn warn-missing-metadata [project] (doseq [key [:description :license :url]] (when (or (nil? (project key)) (re-find #"FIXME" (str (project key)))) (main/info "WARNING: please set" key "in project.clj.")))) (defn- in-branches [branches] (-> (sh/sh "git" "rev-parse" "--abbrev-ref" "HEAD") :out butlast str/join branches not)) (defn deploy "Build jar and deploy to remote repository. The target repository will be looked up in :repositories in project.clj: :repositories [[\"snapshots\" \"https://internal.repo/snapshots\"] [\"releases\" \"https://internal.repo/releases\"] [\"alternate\" \"https://other.server/repo\"]] If you don't provide a repository name to deploy to, either \"snapshots\" or \"releases\" will be used depending on your project's current version. See `lein help deploying` under \"Authentication\" for instructions on how to configure your credentials so you are not prompted on each deploy." ([project repository-name] (let [branches (set (:deploy-branches project))] (when (and (seq branches) (in-branches branches)) (apply main/abort "Can only deploy from branches listed in :deploy-branches:" branches))) (warn-missing-metadata project) (let [repo (repo-for project repository-name) files (files-for project (sign-for-repo? repo))] (try (main/debug "Deploying" files "to" repo) (aether/deploy :coordinates [(symbol (:group project) (:name project)) (:version project)] :artifact-map files :transfer-listener :stdout :repository [repo]) (catch org.sonatype.aether.deployment.DeploymentException e (when main/*debug* (.printStackTrace e)) (main/abort (abort-message (.getMessage e))))))) ([project] (deploy project (if (pom/snapshot? project) "snapshots" "releases"))))
true
(ns leiningen.deploy "Build and deploy jar to remote repository." (:require [cemerick.pomegranate.aether :as aether] [leiningen.core.classpath :as classpath] [leiningen.core.main :as main] [leiningen.core.eval :as eval] [leiningen.core.user :as user] [leiningen.core.utils :as utils] [clojure.java.io :as io] [leiningen.pom :as pom] [leiningen.jar :as jar] [clojure.java.shell :as sh] [clojure.string :as str])) (defn- abort-message [message] (cond (re-find #"Return code is 405" message) (str message "\n" "Ensure you are deploying over SSL.") (re-find #"Return code is 401" message) (str message "\n" "See `lein help deploy` for an explanation of how to" " specify credentials.") :else message)) (defn add-auth-from-url [[id settings]] (let [url (utils/build-url id) user-info (and url (.getUserInfo url)) [username password] (and user-info (.split user-info ":"))] (if username [id (assoc settings :username username :password password)] [id settings]))) (defn add-auth-interactively [[id settings]] (cond (or (and (:username settings) (some settings [:password :passphrase :private-key-file])) (.startsWith (:url settings) "file://")) [id settings] @utils/rebound-io? (main/abort "No credentials found for" id "\nPassword prompts are not supported when ran after other" "(potentially)\ninteractive tasks. Maybe setting up credentials" "may be an idea?\n\nSee `lein help gpg` for an explanation of" "how to specify credentials.") :else (do (println "No credentials found for" id) (println "See `lein help gpg` for how to configure credentials.") (print "Username: ") (flush) (let [username (read-line) password (.readPassword (System/console) "%PI:PASSWORD:<PASSWORD>END_PI" (into-array ["Password: "]))] [id (assoc settings :username username :password password)])))) (defn repo-for [project name] (let [[settings] (for [[id settings] (concat (:deploy-repositories project) (:repositories project) [[name {:url name}]]) :when (= id name)] settings)] (-> [name settings] (classpath/add-repo-auth) (add-auth-from-url) (add-auth-interactively)))) (defn sign [file] (let [exit (binding [*out* (java.io.StringWriter.) eval/*pump-in* false] ; gpg handles reading by itself (eval/sh (user/gpg-program) "--yes" "-ab" "--" file))] (when-not (zero? exit) (main/abort "Could not sign" file)) (str file ".asc"))) (defn signature-for [extension file] {[:extension extension] (sign file)}) (defn signature-for-artifact [[coords artifact-file]] {(apply concat (update-in (apply hash-map coords) [:extension] #(str (or % "jar") ".asc"))) (sign artifact-file)}) (defn sign-for-repo? [repo] (:sign-releases (second repo) true)) (defn files-for [project signed?] (let [artifacts (merge {[:extension "pom"] (pom/pom project)} (jar/jar project))] (if (and signed? (not (.endsWith (:version project) "-SNAPSHOT"))) (reduce merge artifacts (map signature-for-artifact artifacts)) artifacts))) (defn warn-missing-metadata [project] (doseq [key [:description :license :url]] (when (or (nil? (project key)) (re-find #"FIXME" (str (project key)))) (main/info "WARNING: please set" key "in project.clj.")))) (defn- in-branches [branches] (-> (sh/sh "git" "rev-parse" "--abbrev-ref" "HEAD") :out butlast str/join branches not)) (defn deploy "Build jar and deploy to remote repository. The target repository will be looked up in :repositories in project.clj: :repositories [[\"snapshots\" \"https://internal.repo/snapshots\"] [\"releases\" \"https://internal.repo/releases\"] [\"alternate\" \"https://other.server/repo\"]] If you don't provide a repository name to deploy to, either \"snapshots\" or \"releases\" will be used depending on your project's current version. See `lein help deploying` under \"Authentication\" for instructions on how to configure your credentials so you are not prompted on each deploy." ([project repository-name] (let [branches (set (:deploy-branches project))] (when (and (seq branches) (in-branches branches)) (apply main/abort "Can only deploy from branches listed in :deploy-branches:" branches))) (warn-missing-metadata project) (let [repo (repo-for project repository-name) files (files-for project (sign-for-repo? repo))] (try (main/debug "Deploying" files "to" repo) (aether/deploy :coordinates [(symbol (:group project) (:name project)) (:version project)] :artifact-map files :transfer-listener :stdout :repository [repo]) (catch org.sonatype.aether.deployment.DeploymentException e (when main/*debug* (.printStackTrace e)) (main/abort (abort-message (.getMessage e))))))) ([project] (deploy project (if (pom/snapshot? project) "snapshots" "releases"))))
[ { "context": "03-12-13T18:30:02Z</updated>\n <author>\n <name>John Doe</name>\n </author>\n <id>urn:uuid:60a76c80-d399-1", "end": 1480, "score": 0.9997835755348206, "start": 1472, "tag": "NAME", "value": "John Doe" } ]
clj-rome/test/clj_rome/parser_test.clj
mmcgrana/clj-garden
8
(ns clj-rome.parser-test (:use clj-unit.core clj-rome.parser) (:import (java.io ByteArrayInputStream))) (def +rss-example-str+ "<?xml version=\"1.0\"?> <rss version=\"2.0\"> <channel> <title>Example Channel</title> <link>http://example.com/</link> <description>My example channel</description> <item> <title>News for September the Second</title> <link>http://example.com/2002/09/01</link> <description>other things happened today</description> </item> <item> <title>News for September the First</title> <link>http://example.com/2002/09/02</link> </item> </channel> </rss>") (def +rss-example-output+ {:channel {:title "Example Channel", :description "My example channel", :link "http://example.com/" :pub-date nil}, :entries (list {:title "News for September the Second", :description "other things happened today", :link "http://example.com/2002/09/01", :pub-date nil, :guid "http://example.com/2002/09/01"} {:title "News for September the First", :description nil, :link "http://example.com/2002/09/02", :pub-date nil, :guid "http://example.com/2002/09/02"})}) (def +atom-example-str+ "<?xml version=\"1.0\" encoding=\"utf-8\"?> <feed xmlns=\"http://www.w3.org/2005/Atom\"> <title>Example Feed</title> <link href=\"http://example.org/\"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>John Doe</name> </author> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href=\"http://example.org/2003/12/13/atom03\"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> </entry> </feed>") (def +atom-example-output+ {:channel {:title "Example Feed", :description nil, :link "http://example.org/", :pub-date (java.util.Date. (long 1071340202000))}, :entries (list {:title "Atom-Powered Robots Run Amok", :description "Some text.", :link "http://example.org/2003/12/13/atom03", :pub-date nil, :guid "urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"})}) (deftest "rss parsing works" (assert= +rss-example-output+ (parse-feed (ByteArrayInputStream. (.getBytes +rss-example-str+))))) (deftest "atom parsing works" (assert= +atom-example-output+ (parse-feed (ByteArrayInputStream. (.getBytes +atom-example-str+)))))
74155
(ns clj-rome.parser-test (:use clj-unit.core clj-rome.parser) (:import (java.io ByteArrayInputStream))) (def +rss-example-str+ "<?xml version=\"1.0\"?> <rss version=\"2.0\"> <channel> <title>Example Channel</title> <link>http://example.com/</link> <description>My example channel</description> <item> <title>News for September the Second</title> <link>http://example.com/2002/09/01</link> <description>other things happened today</description> </item> <item> <title>News for September the First</title> <link>http://example.com/2002/09/02</link> </item> </channel> </rss>") (def +rss-example-output+ {:channel {:title "Example Channel", :description "My example channel", :link "http://example.com/" :pub-date nil}, :entries (list {:title "News for September the Second", :description "other things happened today", :link "http://example.com/2002/09/01", :pub-date nil, :guid "http://example.com/2002/09/01"} {:title "News for September the First", :description nil, :link "http://example.com/2002/09/02", :pub-date nil, :guid "http://example.com/2002/09/02"})}) (def +atom-example-str+ "<?xml version=\"1.0\" encoding=\"utf-8\"?> <feed xmlns=\"http://www.w3.org/2005/Atom\"> <title>Example Feed</title> <link href=\"http://example.org/\"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name><NAME></name> </author> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href=\"http://example.org/2003/12/13/atom03\"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> </entry> </feed>") (def +atom-example-output+ {:channel {:title "Example Feed", :description nil, :link "http://example.org/", :pub-date (java.util.Date. (long 1071340202000))}, :entries (list {:title "Atom-Powered Robots Run Amok", :description "Some text.", :link "http://example.org/2003/12/13/atom03", :pub-date nil, :guid "urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"})}) (deftest "rss parsing works" (assert= +rss-example-output+ (parse-feed (ByteArrayInputStream. (.getBytes +rss-example-str+))))) (deftest "atom parsing works" (assert= +atom-example-output+ (parse-feed (ByteArrayInputStream. (.getBytes +atom-example-str+)))))
true
(ns clj-rome.parser-test (:use clj-unit.core clj-rome.parser) (:import (java.io ByteArrayInputStream))) (def +rss-example-str+ "<?xml version=\"1.0\"?> <rss version=\"2.0\"> <channel> <title>Example Channel</title> <link>http://example.com/</link> <description>My example channel</description> <item> <title>News for September the Second</title> <link>http://example.com/2002/09/01</link> <description>other things happened today</description> </item> <item> <title>News for September the First</title> <link>http://example.com/2002/09/02</link> </item> </channel> </rss>") (def +rss-example-output+ {:channel {:title "Example Channel", :description "My example channel", :link "http://example.com/" :pub-date nil}, :entries (list {:title "News for September the Second", :description "other things happened today", :link "http://example.com/2002/09/01", :pub-date nil, :guid "http://example.com/2002/09/01"} {:title "News for September the First", :description nil, :link "http://example.com/2002/09/02", :pub-date nil, :guid "http://example.com/2002/09/02"})}) (def +atom-example-str+ "<?xml version=\"1.0\" encoding=\"utf-8\"?> <feed xmlns=\"http://www.w3.org/2005/Atom\"> <title>Example Feed</title> <link href=\"http://example.org/\"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>PI:NAME:<NAME>END_PI</name> </author> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href=\"http://example.org/2003/12/13/atom03\"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> </entry> </feed>") (def +atom-example-output+ {:channel {:title "Example Feed", :description nil, :link "http://example.org/", :pub-date (java.util.Date. (long 1071340202000))}, :entries (list {:title "Atom-Powered Robots Run Amok", :description "Some text.", :link "http://example.org/2003/12/13/atom03", :pub-date nil, :guid "urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"})}) (deftest "rss parsing works" (assert= +rss-example-output+ (parse-feed (ByteArrayInputStream. (.getBytes +rss-example-str+))))) (deftest "atom parsing works" (assert= +atom-example-output+ (parse-feed (ByteArrayInputStream. (.getBytes +atom-example-str+)))))
[ { "context": "e]\n (let [data [{:id 1000\n :name \"Luke\"\n :home_planet \"Tatooine\"\n ", "end": 1136, "score": 0.9991436004638672, "start": 1132, "tag": "NAME", "value": "Luke" }, { "context": "\"]}\n {:id 2000\n :name \"Lando Calrissian\"\n :home_planet \"Socorro\"\n ", "end": 1295, "score": 0.9997579455375671, "start": 1279, "tag": "NAME", "value": "Lando Calrissian" } ]
resources/leiningen/new/luminus/graphql/src/services.clj
spradnyesh/luminus-template
0
(ns <<project-ns>>.routes.services (:require [com.walmartlabs.lacinia.util :refer [attach-resolvers]] [com.walmartlabs.lacinia.schema :as schema] [com.walmartlabs.lacinia :as lacinia] [clojure.data.json :as json] [clojure.edn :as edn] [ring.util.http-response :refer :all] [compojure.api.sweet :refer :all]<% if auth %> [compojure.api.meta :refer [restructure-param]] [buddy.auth.accessrules :refer [restrict]] [buddy.auth :refer [authenticated?]]<% endif %>)) <% if auth %> (defn access-error [_ _] (unauthorized {:error "unauthorized"})) (defn wrap-restricted [handler rule] (restrict handler {:handler rule :on-error access-error})) (defmethod restructure-param :auth-rules [_ rule acc] (update-in acc [:middleware] conj [wrap-restricted rule])) (defmethod restructure-param :current-user [_ binding acc] (update-in acc [:letks] into [binding `(:identity ~'+compojure-api-request+)])) <% endif %> (defn get-hero [context args value] (let [data [{:id 1000 :name "Luke" :home_planet "Tatooine" :appears_in ["NEWHOPE" "EMPIRE" "JEDI"]} {:id 2000 :name "Lando Calrissian" :home_planet "Socorro" :appears_in ["EMPIRE" "JEDI"]}]] (first data))) (def compiled-schema (-> "resources/graphql/schema.edn" slurp edn/read-string (attach-resolvers {:get-hero get-hero :get-droid (constantly {})}) schema/compile)) (defn format-params [query] (let [parsed (json/read-str query)] ;;-> placeholder - need to ensure query meets graphql syntax (str "query { hero(id: \"1000\") { name appears_in }}"))) (defn execute-request [query] (let [vars nil context nil] (-> (lacinia/execute compiled-schema query vars context) (json/write-str)))) (defapi service-routes<% if auth %> (GET "/authenticated" [] :auth-rules authenticated? :current-user user (ok {:user user})) <% endif %> (POST "/api" [:as {body :body}] (ok (execute-request (slurp body)))))
45501
(ns <<project-ns>>.routes.services (:require [com.walmartlabs.lacinia.util :refer [attach-resolvers]] [com.walmartlabs.lacinia.schema :as schema] [com.walmartlabs.lacinia :as lacinia] [clojure.data.json :as json] [clojure.edn :as edn] [ring.util.http-response :refer :all] [compojure.api.sweet :refer :all]<% if auth %> [compojure.api.meta :refer [restructure-param]] [buddy.auth.accessrules :refer [restrict]] [buddy.auth :refer [authenticated?]]<% endif %>)) <% if auth %> (defn access-error [_ _] (unauthorized {:error "unauthorized"})) (defn wrap-restricted [handler rule] (restrict handler {:handler rule :on-error access-error})) (defmethod restructure-param :auth-rules [_ rule acc] (update-in acc [:middleware] conj [wrap-restricted rule])) (defmethod restructure-param :current-user [_ binding acc] (update-in acc [:letks] into [binding `(:identity ~'+compojure-api-request+)])) <% endif %> (defn get-hero [context args value] (let [data [{:id 1000 :name "<NAME>" :home_planet "Tatooine" :appears_in ["NEWHOPE" "EMPIRE" "JEDI"]} {:id 2000 :name "<NAME>" :home_planet "Socorro" :appears_in ["EMPIRE" "JEDI"]}]] (first data))) (def compiled-schema (-> "resources/graphql/schema.edn" slurp edn/read-string (attach-resolvers {:get-hero get-hero :get-droid (constantly {})}) schema/compile)) (defn format-params [query] (let [parsed (json/read-str query)] ;;-> placeholder - need to ensure query meets graphql syntax (str "query { hero(id: \"1000\") { name appears_in }}"))) (defn execute-request [query] (let [vars nil context nil] (-> (lacinia/execute compiled-schema query vars context) (json/write-str)))) (defapi service-routes<% if auth %> (GET "/authenticated" [] :auth-rules authenticated? :current-user user (ok {:user user})) <% endif %> (POST "/api" [:as {body :body}] (ok (execute-request (slurp body)))))
true
(ns <<project-ns>>.routes.services (:require [com.walmartlabs.lacinia.util :refer [attach-resolvers]] [com.walmartlabs.lacinia.schema :as schema] [com.walmartlabs.lacinia :as lacinia] [clojure.data.json :as json] [clojure.edn :as edn] [ring.util.http-response :refer :all] [compojure.api.sweet :refer :all]<% if auth %> [compojure.api.meta :refer [restructure-param]] [buddy.auth.accessrules :refer [restrict]] [buddy.auth :refer [authenticated?]]<% endif %>)) <% if auth %> (defn access-error [_ _] (unauthorized {:error "unauthorized"})) (defn wrap-restricted [handler rule] (restrict handler {:handler rule :on-error access-error})) (defmethod restructure-param :auth-rules [_ rule acc] (update-in acc [:middleware] conj [wrap-restricted rule])) (defmethod restructure-param :current-user [_ binding acc] (update-in acc [:letks] into [binding `(:identity ~'+compojure-api-request+)])) <% endif %> (defn get-hero [context args value] (let [data [{:id 1000 :name "PI:NAME:<NAME>END_PI" :home_planet "Tatooine" :appears_in ["NEWHOPE" "EMPIRE" "JEDI"]} {:id 2000 :name "PI:NAME:<NAME>END_PI" :home_planet "Socorro" :appears_in ["EMPIRE" "JEDI"]}]] (first data))) (def compiled-schema (-> "resources/graphql/schema.edn" slurp edn/read-string (attach-resolvers {:get-hero get-hero :get-droid (constantly {})}) schema/compile)) (defn format-params [query] (let [parsed (json/read-str query)] ;;-> placeholder - need to ensure query meets graphql syntax (str "query { hero(id: \"1000\") { name appears_in }}"))) (defn execute-request [query] (let [vars nil context nil] (-> (lacinia/execute compiled-schema query vars context) (json/write-str)))) (defapi service-routes<% if auth %> (GET "/authenticated" [] :auth-rules authenticated? :current-user user (ok {:user user})) <% endif %> (POST "/api" [:as {body :body}] (ok (execute-request (slurp body)))))
[ { "context": "\n \n {:doc \"fix reduce latex output\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"2018-10-29\"}\n \n (:require [clojur", "end": 307, "score": 0.9641649723052979, "start": 271, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/scripts/clojure/sicpplus/scripts/reduce.clj
palisades-lakes/sicpplus
0
;; clj src/scripts/clojure/sicpplus/scripts/reduce.clj (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns sicpplus.scripts.reduce {:doc "fix reduce latex output" :author "palisades dot lakes at gmail dot com" :version "2018-10-29"} (:require [clojure.java.io :as io] [clojure.string :as s])) ;;---------------------------------------------------------------- (defn- frac [^String line] #_(println "in:" line) (let [result (s/replace line #"^( .+) & = [\s]*\\left\( (.+) \\right\)[\s]* / [\s]*\\left\( (.+?) \\right\)[\s]*(\\?\\?)[\s]*$" "$1 & = \\\\frac\n{$2}\n{$3} $4")] #_(println "out:" result) result)) ;;---------------------------------------------------------------- (defn- repair [^String fpath] (println fpath) (let [f (io/file fpath) parent (.getParent f) fname (s/join "." (butlast (s/split (.getName f) #"\."))) text (slurp f) text (s/replace text #"\$$" "") text (s/replace text "/" " / ") text (s/replace text "\\left(" " \\left( ") text (s/replace text "\\right)" " \\right) ") text (s/replace text "{equation}" "{align}") text (s/replace text "\\left\\{" "") text (s/replace text "\\right\\}" "") text (s/replace text "\r" "") text (s/replace text "\n" " ") text (s/replace text "\\begin{align}" "\n\\begin{align}\n") text (s/replace text "\\end{align}" "\n\\end{align}\n\n") text (s/replace text "," " \\\\\n ") text (s/replace text "=" " & = ") text (s/replace text "-" " - ") text (s/replace text #"([axyd]{1})([0123]{1})" "$1_$2") text (s/replace text "sqrt" "\\sqrt") text (s/replace text #"mu([0123]{1})" "\\\\mu_$1") #_(println text) text (s/join "\n" (mapv frac (filter #(not (or (s/includes? % "***") (s/includes? % "\\documentstyle") (s/includes? % "\\begin{doc") (s/includes? % "\\end{doc") (s/includes? % "end$") )) (s/split-lines text)))) #_(println text) ] (spit (io/file parent (str fname ".tex")) text))) ;;---------------------------------------------------------------- (defn- filetype [f] (last (s/split (.getName (io/file f)) #"\."))) (defn rawtex? [f] (= "rawtex" (filetype f))) ;;---------------------------------------------------------------- #_(repair "docs/interpolation/monomial-yddd4.rawtex") (doseq [path (filter rawtex? (file-seq (io/file "docs/interpolation")))] (repair path))
12877
;; clj src/scripts/clojure/sicpplus/scripts/reduce.clj (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns sicpplus.scripts.reduce {:doc "fix reduce latex output" :author "<EMAIL>" :version "2018-10-29"} (:require [clojure.java.io :as io] [clojure.string :as s])) ;;---------------------------------------------------------------- (defn- frac [^String line] #_(println "in:" line) (let [result (s/replace line #"^( .+) & = [\s]*\\left\( (.+) \\right\)[\s]* / [\s]*\\left\( (.+?) \\right\)[\s]*(\\?\\?)[\s]*$" "$1 & = \\\\frac\n{$2}\n{$3} $4")] #_(println "out:" result) result)) ;;---------------------------------------------------------------- (defn- repair [^String fpath] (println fpath) (let [f (io/file fpath) parent (.getParent f) fname (s/join "." (butlast (s/split (.getName f) #"\."))) text (slurp f) text (s/replace text #"\$$" "") text (s/replace text "/" " / ") text (s/replace text "\\left(" " \\left( ") text (s/replace text "\\right)" " \\right) ") text (s/replace text "{equation}" "{align}") text (s/replace text "\\left\\{" "") text (s/replace text "\\right\\}" "") text (s/replace text "\r" "") text (s/replace text "\n" " ") text (s/replace text "\\begin{align}" "\n\\begin{align}\n") text (s/replace text "\\end{align}" "\n\\end{align}\n\n") text (s/replace text "," " \\\\\n ") text (s/replace text "=" " & = ") text (s/replace text "-" " - ") text (s/replace text #"([axyd]{1})([0123]{1})" "$1_$2") text (s/replace text "sqrt" "\\sqrt") text (s/replace text #"mu([0123]{1})" "\\\\mu_$1") #_(println text) text (s/join "\n" (mapv frac (filter #(not (or (s/includes? % "***") (s/includes? % "\\documentstyle") (s/includes? % "\\begin{doc") (s/includes? % "\\end{doc") (s/includes? % "end$") )) (s/split-lines text)))) #_(println text) ] (spit (io/file parent (str fname ".tex")) text))) ;;---------------------------------------------------------------- (defn- filetype [f] (last (s/split (.getName (io/file f)) #"\."))) (defn rawtex? [f] (= "rawtex" (filetype f))) ;;---------------------------------------------------------------- #_(repair "docs/interpolation/monomial-yddd4.rawtex") (doseq [path (filter rawtex? (file-seq (io/file "docs/interpolation")))] (repair path))
true
;; clj src/scripts/clojure/sicpplus/scripts/reduce.clj (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns sicpplus.scripts.reduce {:doc "fix reduce latex output" :author "PI:EMAIL:<EMAIL>END_PI" :version "2018-10-29"} (:require [clojure.java.io :as io] [clojure.string :as s])) ;;---------------------------------------------------------------- (defn- frac [^String line] #_(println "in:" line) (let [result (s/replace line #"^( .+) & = [\s]*\\left\( (.+) \\right\)[\s]* / [\s]*\\left\( (.+?) \\right\)[\s]*(\\?\\?)[\s]*$" "$1 & = \\\\frac\n{$2}\n{$3} $4")] #_(println "out:" result) result)) ;;---------------------------------------------------------------- (defn- repair [^String fpath] (println fpath) (let [f (io/file fpath) parent (.getParent f) fname (s/join "." (butlast (s/split (.getName f) #"\."))) text (slurp f) text (s/replace text #"\$$" "") text (s/replace text "/" " / ") text (s/replace text "\\left(" " \\left( ") text (s/replace text "\\right)" " \\right) ") text (s/replace text "{equation}" "{align}") text (s/replace text "\\left\\{" "") text (s/replace text "\\right\\}" "") text (s/replace text "\r" "") text (s/replace text "\n" " ") text (s/replace text "\\begin{align}" "\n\\begin{align}\n") text (s/replace text "\\end{align}" "\n\\end{align}\n\n") text (s/replace text "," " \\\\\n ") text (s/replace text "=" " & = ") text (s/replace text "-" " - ") text (s/replace text #"([axyd]{1})([0123]{1})" "$1_$2") text (s/replace text "sqrt" "\\sqrt") text (s/replace text #"mu([0123]{1})" "\\\\mu_$1") #_(println text) text (s/join "\n" (mapv frac (filter #(not (or (s/includes? % "***") (s/includes? % "\\documentstyle") (s/includes? % "\\begin{doc") (s/includes? % "\\end{doc") (s/includes? % "end$") )) (s/split-lines text)))) #_(println text) ] (spit (io/file parent (str fname ".tex")) text))) ;;---------------------------------------------------------------- (defn- filetype [f] (last (s/split (.getName (io/file f)) #"\."))) (defn rawtex? [f] (= "rawtex" (filetype f))) ;;---------------------------------------------------------------- #_(repair "docs/interpolation/monomial-yddd4.rawtex") (doseq [path (filter rawtex? (file-seq (io/file "docs/interpolation")))] (repair path))
[ { "context": "(ns cs253.GPproject)\n\n;; Keith Denning and Rajwol Joshi\n\n;; Initialization\n\n(defn rand-f", "end": 38, "score": 0.9998583793640137, "start": 25, "tag": "NAME", "value": "Keith Denning" }, { "context": "(ns cs253.GPproject)\n\n;; Keith Denning and Rajwol Joshi\n\n;; Initialization\n\n(defn rand-frontier-tree\n \"T", "end": 55, "score": 0.9998651146888733, "start": 43, "tag": "NAME", "value": "Rajwol Joshi" } ]
GP-Project/GPproject.clj
denningk/cs253Project
1
(ns cs253.GPproject) ;; Keith Denning and Rajwol Joshi ;; Initialization (defn rand-frontier-tree "This function generates a random subtree with one function and its arguments." [terminal-set function-set] (list (rand-nth function-set) (rand-nth terminal-set) (rand-nth terminal-set))) (defn rand-terminal "This function returns a random terminal from the terminal set." [terminal-set] (list (rand-nth terminal-set))) ; Tree Generation (defn full-tree "This function creates a random full-tree" [terminal-set function-set max-depth] (list (rand-nth function-set) (if (= 1 max-depth) (rand-nth terminal-set) (full-tree terminal-set function-set (dec max-depth))) (if (= 1 max-depth) (rand-nth terminal-set) (full-tree terminal-set function-set (dec max-depth))))) (defn grow-tree "This function creates a random grow-tree" [terminal-set function-set max-depth] (let [item (rand-nth (concat function-set terminal-set))] (if (some #(= item %) terminal-set) item (list item (if (or (= 1 max-depth) (some #(= item %) terminal-set)) (rand-nth terminal-set) (grow-tree terminal-set function-set (dec max-depth))) (if (or (= 1 max-depth) (some #(= item %) terminal-set)) (rand-nth terminal-set) (grow-tree terminal-set function-set (dec max-depth))) )))) ; Population Generation (defn gen-population "This program generates a population of randomly generated programs. Uses a loop." [num-pop max-depth terminal-set function-set] (loop [pop '() num num-pop] (if (= num 0) pop (recur (conj pop (if (< (rand-int 10) 5) (full-tree terminal-set function-set max-depth) (grow-tree terminal-set function-set max-depth))) (dec num))))) (defn make-population "Makes a population of n number of program-trees of a inputed max-depth using terminal-set and function-set. Does not use a loop." [pop-num terminal-set function-set max-depth] (list (take (* 0.5 pop-num)(repeatedly #(full-tree terminal-set function-set max-depth))) (take (* 0.5 pop-num)(repeatedly #(grow-tree terminal-set function-set max-depth))))) ;; Fitness Evaluation ; Use 10 data points (def test-cases [{:x -10 :y -1007} {:x -8 :y -517} {:x -6 :y -219} {:x -4 :y -65} {:x -2 :y -7} {:x 0 :y 3} {:x 1 :y 5} {:x 3 :y 33} {:x 5 :y 133} {:x 7 :y 353} {:x 9 :y 741}]) (defn make-program-into-fn [program] (eval (list 'fn '[x] program))) (defn fitness-prog "This function finds the fitness of a single program." [program test-cases] (apply +' (map (fn[test-case] (let [x (:x test-case) y (:y test-case) func-program (make-program-into-fn program)] ; In case 'program' is a terminal (Math/abs (int (- (if (= 1 (number? program)) ; Otherwise causes cast error (nth program 0 1) (func-program x)) y))))) test-cases))) (defn fitness-eval "This function creates a map of functions with their respective error values." [population test-cases] (map (fn [program] {:function program :fitness (fitness-prog program test-cases)}) population)) ;; Parent Selection ; We decided to implement tournament selection (defn single-tourney "This function runs a single round of a tournament. It returns the function which wins the tourney. If there is a tie, the winner is chosen randomly." [&programs] (let [best-error (apply min (map :fitness &programs))] (:function (rand-nth (filter #(= best-error (:fitness %)) &programs))))) (defn tournament-selection "This function generates a list of programs which can be used as parents for the next generation. 2 to 4 programs are chosen to participate in each round." [pop-maps] (repeatedly (count pop-maps) #(single-tourney (repeatedly (rand-nth (range 2 4)) (fn [](rand-nth pop-maps)))))) ; Ephemeral Random Constant defined (defn erc "This function is an ephemeral random constant." [] (rand-nth (range -50 50))) ; Protected division (defn pd "Protected division, to protect against divide by zero." [x y] (if (= y 0) 1 (/ x y))) ;; Variation (def instructions '{+ 2 * 2 - 2 pd 2}) (defn program-size [prog] (if (seq? prog) (count (flatten prog)) 1)) (defn select-random-subtree "Given a program, selects a random subtree and returns it." ([prog] (select-random-subtree prog (rand-int (program-size prog)))) ([prog subtree-index] (cond (not (seq? prog)) prog (and (zero? subtree-index) (some #{(first prog)} (keys instructions))) prog (< subtree-index (program-size (first prog))) (recur (first prog) subtree-index) :else (recur (rest prog) (- subtree-index (program-size (first prog))))))) (defn replace-random-subtree "Given a program and a replacement-subtree, replace a random node in the program with the replacement-subtree." ([prog replacement-subtree] (replace-random-subtree prog replacement-subtree (rand-int (program-size prog)))) ([prog replacement-subtree subtree-index] (cond (not (seq? prog)) replacement-subtree (zero? subtree-index) replacement-subtree :else (map (fn [element start-index] (if (<= start-index subtree-index (+ start-index -1 (program-size element))) (replace-random-subtree element replacement-subtree (- subtree-index start-index)) element)) prog (cons 0 (reductions + (map program-size prog))))))) (defn crossover "This function performs a crossover on two programs and returns the new program." [prog1 prog2] (replace-random-subtree prog2 (select-random-subtree prog1))) (defn mutation "This function takes a random node in a subtree and replaces it with another random node." [program terminal-set function-set max-depth] (replace-random-subtree program (if (> (rand-int 10) 5) ; Replaces with a terminal 50% of time (rand-terminal terminal-set) (grow-tree terminal-set function-set max-depth)))) ; Combines all variation techniques (defn evolve "This function takes a collection of selected parents and evolves them." [parents terminal-set function-set max-depth] (loop [new-pop '() evolve-num (count parents)] (let [probability (rand-int 100)] ; Reproduction 10%, Mutation 40%, Crossover 50% (cond (and (> probability 90) (> evolve-num 0)) (recur (conj new-pop (rand-nth parents)) (dec evolve-num)) (and (> probability 50) (> evolve-num 0)) (recur (conj new-pop (mutation (rand-nth parents) terminal-set function-set max-depth)) (dec evolve-num)) (and (> probability 0) (> evolve-num 0)) (recur (conj new-pop (crossover (rand-nth parents) (rand-nth parents))) (dec evolve-num)) :else new-pop)))) (defn best-fitness "This functions finds thes the function with the best fitness and outputs its value" [pop-maps] (apply min (map :fitness pop-maps))) ;; Main Function (defn genetic-programming "This function runs the genetic programming system. For every generation, it displays the generation number, the best program of that generation, and the total error of the best program." [] (let [function-set '(+ - * pd) terminal-set '(1 2 3 x) max-depth 2 pop-size 5 max-gen 3] (loop [current-pop (gen-population max-depth pop-size terminal-set function-set) ; Initialize population gen-num 0 best-program nil best-prog-error nil] (println "Generation Number:" gen-num "\nThe best program was:" best-program "\nThe error of the best program was:" best-prog-error) (if (or (= gen-num max-gen) (= best-prog-error 0)) ; Continue until solution found or if max generation reached (do (println "\nGenetic Evolution finished!") (println "The best program is:") best-program) (let [current-fitness (fitness-eval current-pop test-cases) ; Fitness evaluation best-prog (single-tourney current-fitness) ; Finds best program of generation best-prog-fitness (best-fitness current-fitness)] (recur (evolve (tournament-selection current-fitness) ; Selection and evolution terminal-set function-set max-depth) (inc gen-num) best-prog best-prog-fitness)))))) ;; An error continues to occur in the "fitness-eval" function. If a program is a single terminal, ;; a cast error is thrown because those single-terminal programs cannot be used as funcions. We attempted ;; to fix this error but we were not able to even though the code that we added seems like it should work. ;; If the genetic programming system is run enough times, it will eventually run all the way through with a low ;; population and low generation.
42835
(ns cs253.GPproject) ;; <NAME> and <NAME> ;; Initialization (defn rand-frontier-tree "This function generates a random subtree with one function and its arguments." [terminal-set function-set] (list (rand-nth function-set) (rand-nth terminal-set) (rand-nth terminal-set))) (defn rand-terminal "This function returns a random terminal from the terminal set." [terminal-set] (list (rand-nth terminal-set))) ; Tree Generation (defn full-tree "This function creates a random full-tree" [terminal-set function-set max-depth] (list (rand-nth function-set) (if (= 1 max-depth) (rand-nth terminal-set) (full-tree terminal-set function-set (dec max-depth))) (if (= 1 max-depth) (rand-nth terminal-set) (full-tree terminal-set function-set (dec max-depth))))) (defn grow-tree "This function creates a random grow-tree" [terminal-set function-set max-depth] (let [item (rand-nth (concat function-set terminal-set))] (if (some #(= item %) terminal-set) item (list item (if (or (= 1 max-depth) (some #(= item %) terminal-set)) (rand-nth terminal-set) (grow-tree terminal-set function-set (dec max-depth))) (if (or (= 1 max-depth) (some #(= item %) terminal-set)) (rand-nth terminal-set) (grow-tree terminal-set function-set (dec max-depth))) )))) ; Population Generation (defn gen-population "This program generates a population of randomly generated programs. Uses a loop." [num-pop max-depth terminal-set function-set] (loop [pop '() num num-pop] (if (= num 0) pop (recur (conj pop (if (< (rand-int 10) 5) (full-tree terminal-set function-set max-depth) (grow-tree terminal-set function-set max-depth))) (dec num))))) (defn make-population "Makes a population of n number of program-trees of a inputed max-depth using terminal-set and function-set. Does not use a loop." [pop-num terminal-set function-set max-depth] (list (take (* 0.5 pop-num)(repeatedly #(full-tree terminal-set function-set max-depth))) (take (* 0.5 pop-num)(repeatedly #(grow-tree terminal-set function-set max-depth))))) ;; Fitness Evaluation ; Use 10 data points (def test-cases [{:x -10 :y -1007} {:x -8 :y -517} {:x -6 :y -219} {:x -4 :y -65} {:x -2 :y -7} {:x 0 :y 3} {:x 1 :y 5} {:x 3 :y 33} {:x 5 :y 133} {:x 7 :y 353} {:x 9 :y 741}]) (defn make-program-into-fn [program] (eval (list 'fn '[x] program))) (defn fitness-prog "This function finds the fitness of a single program." [program test-cases] (apply +' (map (fn[test-case] (let [x (:x test-case) y (:y test-case) func-program (make-program-into-fn program)] ; In case 'program' is a terminal (Math/abs (int (- (if (= 1 (number? program)) ; Otherwise causes cast error (nth program 0 1) (func-program x)) y))))) test-cases))) (defn fitness-eval "This function creates a map of functions with their respective error values." [population test-cases] (map (fn [program] {:function program :fitness (fitness-prog program test-cases)}) population)) ;; Parent Selection ; We decided to implement tournament selection (defn single-tourney "This function runs a single round of a tournament. It returns the function which wins the tourney. If there is a tie, the winner is chosen randomly." [&programs] (let [best-error (apply min (map :fitness &programs))] (:function (rand-nth (filter #(= best-error (:fitness %)) &programs))))) (defn tournament-selection "This function generates a list of programs which can be used as parents for the next generation. 2 to 4 programs are chosen to participate in each round." [pop-maps] (repeatedly (count pop-maps) #(single-tourney (repeatedly (rand-nth (range 2 4)) (fn [](rand-nth pop-maps)))))) ; Ephemeral Random Constant defined (defn erc "This function is an ephemeral random constant." [] (rand-nth (range -50 50))) ; Protected division (defn pd "Protected division, to protect against divide by zero." [x y] (if (= y 0) 1 (/ x y))) ;; Variation (def instructions '{+ 2 * 2 - 2 pd 2}) (defn program-size [prog] (if (seq? prog) (count (flatten prog)) 1)) (defn select-random-subtree "Given a program, selects a random subtree and returns it." ([prog] (select-random-subtree prog (rand-int (program-size prog)))) ([prog subtree-index] (cond (not (seq? prog)) prog (and (zero? subtree-index) (some #{(first prog)} (keys instructions))) prog (< subtree-index (program-size (first prog))) (recur (first prog) subtree-index) :else (recur (rest prog) (- subtree-index (program-size (first prog))))))) (defn replace-random-subtree "Given a program and a replacement-subtree, replace a random node in the program with the replacement-subtree." ([prog replacement-subtree] (replace-random-subtree prog replacement-subtree (rand-int (program-size prog)))) ([prog replacement-subtree subtree-index] (cond (not (seq? prog)) replacement-subtree (zero? subtree-index) replacement-subtree :else (map (fn [element start-index] (if (<= start-index subtree-index (+ start-index -1 (program-size element))) (replace-random-subtree element replacement-subtree (- subtree-index start-index)) element)) prog (cons 0 (reductions + (map program-size prog))))))) (defn crossover "This function performs a crossover on two programs and returns the new program." [prog1 prog2] (replace-random-subtree prog2 (select-random-subtree prog1))) (defn mutation "This function takes a random node in a subtree and replaces it with another random node." [program terminal-set function-set max-depth] (replace-random-subtree program (if (> (rand-int 10) 5) ; Replaces with a terminal 50% of time (rand-terminal terminal-set) (grow-tree terminal-set function-set max-depth)))) ; Combines all variation techniques (defn evolve "This function takes a collection of selected parents and evolves them." [parents terminal-set function-set max-depth] (loop [new-pop '() evolve-num (count parents)] (let [probability (rand-int 100)] ; Reproduction 10%, Mutation 40%, Crossover 50% (cond (and (> probability 90) (> evolve-num 0)) (recur (conj new-pop (rand-nth parents)) (dec evolve-num)) (and (> probability 50) (> evolve-num 0)) (recur (conj new-pop (mutation (rand-nth parents) terminal-set function-set max-depth)) (dec evolve-num)) (and (> probability 0) (> evolve-num 0)) (recur (conj new-pop (crossover (rand-nth parents) (rand-nth parents))) (dec evolve-num)) :else new-pop)))) (defn best-fitness "This functions finds thes the function with the best fitness and outputs its value" [pop-maps] (apply min (map :fitness pop-maps))) ;; Main Function (defn genetic-programming "This function runs the genetic programming system. For every generation, it displays the generation number, the best program of that generation, and the total error of the best program." [] (let [function-set '(+ - * pd) terminal-set '(1 2 3 x) max-depth 2 pop-size 5 max-gen 3] (loop [current-pop (gen-population max-depth pop-size terminal-set function-set) ; Initialize population gen-num 0 best-program nil best-prog-error nil] (println "Generation Number:" gen-num "\nThe best program was:" best-program "\nThe error of the best program was:" best-prog-error) (if (or (= gen-num max-gen) (= best-prog-error 0)) ; Continue until solution found or if max generation reached (do (println "\nGenetic Evolution finished!") (println "The best program is:") best-program) (let [current-fitness (fitness-eval current-pop test-cases) ; Fitness evaluation best-prog (single-tourney current-fitness) ; Finds best program of generation best-prog-fitness (best-fitness current-fitness)] (recur (evolve (tournament-selection current-fitness) ; Selection and evolution terminal-set function-set max-depth) (inc gen-num) best-prog best-prog-fitness)))))) ;; An error continues to occur in the "fitness-eval" function. If a program is a single terminal, ;; a cast error is thrown because those single-terminal programs cannot be used as funcions. We attempted ;; to fix this error but we were not able to even though the code that we added seems like it should work. ;; If the genetic programming system is run enough times, it will eventually run all the way through with a low ;; population and low generation.
true
(ns cs253.GPproject) ;; PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI ;; Initialization (defn rand-frontier-tree "This function generates a random subtree with one function and its arguments." [terminal-set function-set] (list (rand-nth function-set) (rand-nth terminal-set) (rand-nth terminal-set))) (defn rand-terminal "This function returns a random terminal from the terminal set." [terminal-set] (list (rand-nth terminal-set))) ; Tree Generation (defn full-tree "This function creates a random full-tree" [terminal-set function-set max-depth] (list (rand-nth function-set) (if (= 1 max-depth) (rand-nth terminal-set) (full-tree terminal-set function-set (dec max-depth))) (if (= 1 max-depth) (rand-nth terminal-set) (full-tree terminal-set function-set (dec max-depth))))) (defn grow-tree "This function creates a random grow-tree" [terminal-set function-set max-depth] (let [item (rand-nth (concat function-set terminal-set))] (if (some #(= item %) terminal-set) item (list item (if (or (= 1 max-depth) (some #(= item %) terminal-set)) (rand-nth terminal-set) (grow-tree terminal-set function-set (dec max-depth))) (if (or (= 1 max-depth) (some #(= item %) terminal-set)) (rand-nth terminal-set) (grow-tree terminal-set function-set (dec max-depth))) )))) ; Population Generation (defn gen-population "This program generates a population of randomly generated programs. Uses a loop." [num-pop max-depth terminal-set function-set] (loop [pop '() num num-pop] (if (= num 0) pop (recur (conj pop (if (< (rand-int 10) 5) (full-tree terminal-set function-set max-depth) (grow-tree terminal-set function-set max-depth))) (dec num))))) (defn make-population "Makes a population of n number of program-trees of a inputed max-depth using terminal-set and function-set. Does not use a loop." [pop-num terminal-set function-set max-depth] (list (take (* 0.5 pop-num)(repeatedly #(full-tree terminal-set function-set max-depth))) (take (* 0.5 pop-num)(repeatedly #(grow-tree terminal-set function-set max-depth))))) ;; Fitness Evaluation ; Use 10 data points (def test-cases [{:x -10 :y -1007} {:x -8 :y -517} {:x -6 :y -219} {:x -4 :y -65} {:x -2 :y -7} {:x 0 :y 3} {:x 1 :y 5} {:x 3 :y 33} {:x 5 :y 133} {:x 7 :y 353} {:x 9 :y 741}]) (defn make-program-into-fn [program] (eval (list 'fn '[x] program))) (defn fitness-prog "This function finds the fitness of a single program." [program test-cases] (apply +' (map (fn[test-case] (let [x (:x test-case) y (:y test-case) func-program (make-program-into-fn program)] ; In case 'program' is a terminal (Math/abs (int (- (if (= 1 (number? program)) ; Otherwise causes cast error (nth program 0 1) (func-program x)) y))))) test-cases))) (defn fitness-eval "This function creates a map of functions with their respective error values." [population test-cases] (map (fn [program] {:function program :fitness (fitness-prog program test-cases)}) population)) ;; Parent Selection ; We decided to implement tournament selection (defn single-tourney "This function runs a single round of a tournament. It returns the function which wins the tourney. If there is a tie, the winner is chosen randomly." [&programs] (let [best-error (apply min (map :fitness &programs))] (:function (rand-nth (filter #(= best-error (:fitness %)) &programs))))) (defn tournament-selection "This function generates a list of programs which can be used as parents for the next generation. 2 to 4 programs are chosen to participate in each round." [pop-maps] (repeatedly (count pop-maps) #(single-tourney (repeatedly (rand-nth (range 2 4)) (fn [](rand-nth pop-maps)))))) ; Ephemeral Random Constant defined (defn erc "This function is an ephemeral random constant." [] (rand-nth (range -50 50))) ; Protected division (defn pd "Protected division, to protect against divide by zero." [x y] (if (= y 0) 1 (/ x y))) ;; Variation (def instructions '{+ 2 * 2 - 2 pd 2}) (defn program-size [prog] (if (seq? prog) (count (flatten prog)) 1)) (defn select-random-subtree "Given a program, selects a random subtree and returns it." ([prog] (select-random-subtree prog (rand-int (program-size prog)))) ([prog subtree-index] (cond (not (seq? prog)) prog (and (zero? subtree-index) (some #{(first prog)} (keys instructions))) prog (< subtree-index (program-size (first prog))) (recur (first prog) subtree-index) :else (recur (rest prog) (- subtree-index (program-size (first prog))))))) (defn replace-random-subtree "Given a program and a replacement-subtree, replace a random node in the program with the replacement-subtree." ([prog replacement-subtree] (replace-random-subtree prog replacement-subtree (rand-int (program-size prog)))) ([prog replacement-subtree subtree-index] (cond (not (seq? prog)) replacement-subtree (zero? subtree-index) replacement-subtree :else (map (fn [element start-index] (if (<= start-index subtree-index (+ start-index -1 (program-size element))) (replace-random-subtree element replacement-subtree (- subtree-index start-index)) element)) prog (cons 0 (reductions + (map program-size prog))))))) (defn crossover "This function performs a crossover on two programs and returns the new program." [prog1 prog2] (replace-random-subtree prog2 (select-random-subtree prog1))) (defn mutation "This function takes a random node in a subtree and replaces it with another random node." [program terminal-set function-set max-depth] (replace-random-subtree program (if (> (rand-int 10) 5) ; Replaces with a terminal 50% of time (rand-terminal terminal-set) (grow-tree terminal-set function-set max-depth)))) ; Combines all variation techniques (defn evolve "This function takes a collection of selected parents and evolves them." [parents terminal-set function-set max-depth] (loop [new-pop '() evolve-num (count parents)] (let [probability (rand-int 100)] ; Reproduction 10%, Mutation 40%, Crossover 50% (cond (and (> probability 90) (> evolve-num 0)) (recur (conj new-pop (rand-nth parents)) (dec evolve-num)) (and (> probability 50) (> evolve-num 0)) (recur (conj new-pop (mutation (rand-nth parents) terminal-set function-set max-depth)) (dec evolve-num)) (and (> probability 0) (> evolve-num 0)) (recur (conj new-pop (crossover (rand-nth parents) (rand-nth parents))) (dec evolve-num)) :else new-pop)))) (defn best-fitness "This functions finds thes the function with the best fitness and outputs its value" [pop-maps] (apply min (map :fitness pop-maps))) ;; Main Function (defn genetic-programming "This function runs the genetic programming system. For every generation, it displays the generation number, the best program of that generation, and the total error of the best program." [] (let [function-set '(+ - * pd) terminal-set '(1 2 3 x) max-depth 2 pop-size 5 max-gen 3] (loop [current-pop (gen-population max-depth pop-size terminal-set function-set) ; Initialize population gen-num 0 best-program nil best-prog-error nil] (println "Generation Number:" gen-num "\nThe best program was:" best-program "\nThe error of the best program was:" best-prog-error) (if (or (= gen-num max-gen) (= best-prog-error 0)) ; Continue until solution found or if max generation reached (do (println "\nGenetic Evolution finished!") (println "The best program is:") best-program) (let [current-fitness (fitness-eval current-pop test-cases) ; Fitness evaluation best-prog (single-tourney current-fitness) ; Finds best program of generation best-prog-fitness (best-fitness current-fitness)] (recur (evolve (tournament-selection current-fitness) ; Selection and evolution terminal-set function-set max-depth) (inc gen-num) best-prog best-prog-fitness)))))) ;; An error continues to occur in the "fitness-eval" function. If a program is a single terminal, ;; a cast error is thrown because those single-terminal programs cannot be used as funcions. We attempted ;; to fix this error but we were not able to even though the code that we added seems like it should work. ;; If the genetic programming system is run enough times, it will eventually run all the way through with a low ;; population and low generation.
[ { "context": "#(/ % 3) [1 2 3])))\n\n(def stooges [\"Moe\" \"Larry\" \"Curly\" \"Shemp\"])\n(first stooges) ; -> \"Moe\"\n(second s", "end": 1232, "score": 0.5765084624290466, "start": 1229, "tag": "NAME", "value": "Cur" }, { "context": "(first stooges) ; -> \"Moe\"\n(second stooges) ; -> \"Larry\"\n(last stooges) ; -> \"Shemp\"\n(nth stooges 2) ", "end": 1297, "score": 0.723762571811676, "start": 1296, "tag": "NAME", "value": "L" }, { "context": "second stooges) ; -> \"Larry\"\n(last stooges) ; -> \"Shemp\"\n(nth stooges 2) ; indexes start at 0 -> \"Curly", "end": 1327, "score": 0.7175276875495911, "start": 1324, "tag": "NAME", "value": "She" }, { "context": " \"Shemp\"\n(nth stooges 2) ; indexes start at 0 -> \"Curly\"\n\n(next stooges) ; -> (\"Larry\" \"Curly\" \"Shemp\")\n(", "end": 1377, "score": 0.7092031240463257, "start": 1372, "tag": "NAME", "value": "Curly" }, { "context": "exes start at 0 -> \"Curly\"\n\n(next stooges) ; -> (\"Larry\" \"Curly\" \"Shemp\")\n(butlast stooges) ; -> (\"Moe\" \"", "end": 1407, "score": 0.9878212809562683, "start": 1402, "tag": "NAME", "value": "Larry" }, { "context": "rt at 0 -> \"Curly\"\n\n(next stooges) ; -> (\"Larry\" \"Curly\" \"Shemp\")\n(butlast stooges) ; -> (\"Moe\" \"Larry\" \"", "end": 1415, "score": 0.9792039394378662, "start": 1410, "tag": "NAME", "value": "Curly" }, { "context": "-> \"Curly\"\n\n(next stooges) ; -> (\"Larry\" \"Curly\" \"Shemp\")\n(butlast stooges) ; -> (\"Moe\" \"Larry\" \"Curly\")\n", "end": 1423, "score": 0.8812474012374878, "start": 1418, "tag": "NAME", "value": "Shemp" }, { "context": "\"Larry\" \"Curly\" \"Shemp\")\n(butlast stooges) ; -> (\"Moe\" \"Larry\" \"Curly\")\n(drop-last 2 stooges) ; -> (\"Mo", "end": 1454, "score": 0.9465583562850952, "start": 1451, "tag": "NAME", "value": "Moe" }, { "context": "\" \"Curly\" \"Shemp\")\n(butlast stooges) ; -> (\"Moe\" \"Larry\" \"Curly\")\n(drop-last 2 stooges) ; -> (\"Moe\" \"Larr", "end": 1462, "score": 0.9553178548812866, "start": 1457, "tag": "NAME", "value": "Larry" }, { "context": "\" \"Shemp\")\n(butlast stooges) ; -> (\"Moe\" \"Larry\" \"Curly\")\n(drop-last 2 stooges) ; -> (\"Moe\" \"Larry\")\n; Ge", "end": 1470, "score": 0.9269348978996277, "start": 1465, "tag": "NAME", "value": "Curly" }, { "context": "oe\" \"Larry\" \"Curly\")\n(drop-last 2 stooges) ; -> (\"Moe\" \"Larry\")\n; Get names containing more than three ", "end": 1505, "score": 0.9337625503540039, "start": 1502, "tag": "NAME", "value": "Moe" }, { "context": "arry\" \"Curly\")\n(drop-last 2 stooges) ; -> (\"Moe\" \"Larry\")\n; Get names containing more than three characte", "end": 1513, "score": 0.9232810735702515, "start": 1508, "tag": "NAME", "value": "Larry" }, { "context": "racters.\n(filter #(> (count %) 3) stooges) ; -> (\"Larry\" \"Curly\" \"Shemp\")\n(nthnext stooges 2) ; -> (\"Curl", "end": 1613, "score": 0.9865982532501221, "start": 1608, "tag": "NAME", "value": "Larry" }, { "context": "\n(filter #(> (count %) 3) stooges) ; -> (\"Larry\" \"Curly\" \"Shemp\")\n(nthnext stooges 2) ; -> (\"Curly\" \"Shem", "end": 1621, "score": 0.9804159998893738, "start": 1616, "tag": "NAME", "value": "Curly" }, { "context": " #(> (count %) 3) stooges) ; -> (\"Larry\" \"Curly\" \"Shemp\")\n(nthnext stooges 2) ; -> (\"Curly\" \"Shemp\")\n\n(pr", "end": 1629, "score": 0.9443209767341614, "start": 1624, "tag": "NAME", "value": "Shemp" }, { "context": "arry\" \"Curly\" \"Shemp\")\n(nthnext stooges 2) ; -> (\"Curly\" \"Shemp\")\n\n(println (apply + [2 4 7]))\n\n\n(def sto", "end": 1664, "score": 0.6396079659461975, "start": 1659, "tag": "NAME", "value": "Curly" }, { "context": "urly\" \"Shemp\")\n(nthnext stooges 2) ; -> (\"Curly\" \"Shemp\")\n\n(println (apply + [2 4 7]))\n\n\n(def stooges (li", "end": 1672, "score": 0.7209153175354004, "start": 1667, "tag": "NAME", "value": "Shemp" }, { "context": "(println (apply + [2 4 7]))\n\n\n(def stooges (list \"Moe\" \"Larry\" \"Curly\")) ; list\n(def stooges (quote (\"M", "end": 1729, "score": 0.8977724313735962, "start": 1726, "tag": "NAME", "value": "Moe" }, { "context": "ln (apply + [2 4 7]))\n\n\n(def stooges (list \"Moe\" \"Larry\" \"Curly\")) ; list\n(def stooges (quote (\"Moe\" \"Lar", "end": 1737, "score": 0.9137263298034668, "start": 1732, "tag": "NAME", "value": "Larry" }, { "context": " [2 4 7]))\n\n\n(def stooges (list \"Moe\" \"Larry\" \"Curly\")) ; list\n(def stooges (quote (\"Moe\" \"Larry\" \"Cur", "end": 1745, "score": 0.9209572076797485, "start": 1743, "tag": "NAME", "value": "ly" }, { "context": "e\" \"Larry\" \"Curly\")) ; list\n(def stooges (quote (\"Moe\" \"Larry\" \"Curly\"))) ; list\n(def stooges '(\"Moe\" \"", "end": 1781, "score": 0.7762104868888855, "start": 1778, "tag": "NAME", "value": "Moe" }, { "context": "rry\" \"Curly\")) ; list\n(def stooges (quote (\"Moe\" \"Larry\" \"Curly\"))) ; list\n(def stooges '(\"Moe\" \"Larry\" \"", "end": 1789, "score": 0.7309267520904541, "start": 1784, "tag": "NAME", "value": "Larry" }, { "context": "\")) ; list\n(def stooges (quote (\"Moe\" \"Larry\" \"Curly\"))) ; list\n(def stooges '(\"Moe\" \"Larry\" \"Curly\"))", "end": 1797, "score": 0.5743507742881775, "start": 1795, "tag": "NAME", "value": "ly" }, { "context": " (\"Moe\" \"Larry\" \"Curly\"))) ; list\n(def stooges '(\"Moe\" \"Larry\" \"Curly\")) ; list\n\n\n;(some #(= % \"Moe\") s", "end": 1828, "score": 0.8047875165939331, "start": 1825, "tag": "NAME", "value": "Moe" }, { "context": "\" \"Larry\" \"Curly\"))) ; list\n(def stooges '(\"Moe\" \"Larry\" \"Curly\")) ; list\n\n\n;(some #(= % \"Moe\") stooges) ", "end": 1836, "score": 0.7247582674026489, "start": 1831, "tag": "NAME", "value": "Larry" }, { "context": "Curly\"))) ; list\n(def stooges '(\"Moe\" \"Larry\" \"Curly\")) ; list\n\n\n;(some #(= % \"Moe\") stooges) ; -> tru", "end": 1844, "score": 0.727166473865509, "start": 1842, "tag": "NAME", "value": "ly" }, { "context": " '(\"Moe\" \"Larry\" \"Curly\")) ; list\n\n\n;(some #(= % \"Moe\") stooges) ; -> true\n;(some #(= % \"Mark\") stooges", "end": 1874, "score": 0.8083086609840393, "start": 1871, "tag": "NAME", "value": "Moe" }, { "context": "ome #(= % \"Moe\") stooges) ; -> true\n;(some #(= % \"Mark\") stooges) ; -> nil\n\n(println (contains? (set sto", "end": 1914, "score": 0.9782652258872986, "start": 1910, "tag": "NAME", "value": "Mark" }, { "context": "p)) \"cherry\"))\n(def person {\n :name \"Mark Volkmann\"\n :address {\n ", "end": 2919, "score": 0.9998261332511902, "start": 2906, "tag": "NAME", "value": "Mark Volkmann" } ]
src/main/scripts/basic.clj
johnnywale/clojure-learning
0
(in-ns 'user) (defn hello [name] (println "hello" name)) (hello "dfaf") (def vowel? (set "aeiou")) (defn pig-latin [word] (let [first-letter (first word)] (if (vowel? first-letter) (str word "ay") (str (subs word 1) first-letter "ay") )) ) (println (pig-latin "red")) (println (pig-latin "orange")) (def v 1) ; v is a global binding (defn f1 [] (println "f1: v =" v)) ; global binding (defn f2 [] (println "f2: before let v =" v) ; global binding (let [v 2] ; creates local binding v that shadows global one (println "f2: in let, v =" v) ; local binding (f1)) (println "f2: after let v =" v)) ; global binding (defn f3 [] (println "f3: before binding v =" v) ; global binding (binding [v 3] ; same global binding with new, temporary value (println "f3: in binding, v =" v) ; global binding (f1)) (println "f3: after binding v =" v)) ; global binding (defn f4 [] (def v 4)) ; changes the value of the global binding ;(f2) ;(f3) ;(f4) (println "after calling f4, v =" v) (println (count [19 "yellow" true])) (println (reverse [2 4 7])) (println (map + [2 4 7] [5 6] [1 2 3 4])) (println (map #(+ % 1) (map #(/ % 3) [1 2 3]))) (def stooges ["Moe" "Larry" "Curly" "Shemp"]) (first stooges) ; -> "Moe" (second stooges) ; -> "Larry" (last stooges) ; -> "Shemp" (nth stooges 2) ; indexes start at 0 -> "Curly" (next stooges) ; -> ("Larry" "Curly" "Shemp") (butlast stooges) ; -> ("Moe" "Larry" "Curly") (drop-last 2 stooges) ; -> ("Moe" "Larry") ; Get names containing more than three characters. (filter #(> (count %) 3) stooges) ; -> ("Larry" "Curly" "Shemp") (nthnext stooges 2) ; -> ("Curly" "Shemp") (println (apply + [2 4 7])) (def stooges (list "Moe" "Larry" "Curly")) ; list (def stooges (quote ("Moe" "Larry" "Curly"))) ; list (def stooges '("Moe" "Larry" "Curly")) ; list ;(some #(= % "Moe") stooges) ; -> true ;(some #(= % "Mark") stooges) ; -> nil (println (contains? (set stooges) "Moe")) ; convert to list set and use contains (def conbined_list (into (list "aa" "bb" "cc") (list "dd" "ee" "ff"))) (println (reverse conbined_list)) (def may_be "fff") (println (get ["AAA" "BB" "DDD" may_be] 1 "unknown")) ; get only work for vector (println (get ["AAA" "BB" "DDD" may_be] 10 "unknown")) ; get only work for vector (def simple_set #{"ab","ac","ae"}) (println (simple_set "ab") (simple_set "aaa")) (println (if (nil? (simple_set "aaa")) "abbb" "dff")) (def popsicle-map (hash-map :red "cherry", :green :apple , :purple :grape)) (def popsicle-map {:red :cherry, :green :apple, :purple :grape}) ; same as previous (def popsicle-map (sorted-map :red "cherry", :green :apple , :purple :grape)) (println (contains? popsicle-map :red)) (println (some #{"cherry"} (vals popsicle-map))) (println (vals popsicle-map)) (println (contains? (set (vals popsicle-map)) "cherry")) (def person { :name "Mark Volkmann" :address { :street "644 Glen Summit" :city "St. Charles" :state "Missouri" :zip 63304} :employer { :name "Object Computing, Inc." :address { :street "12140 Woodcrest Executive Drive, Suite 250" :city "Creve Coeur" :state "Missouri" :zip 63141}}}) (println(get-in person [:employer :address :city])) (-> person :employer :address :city) ; explained below (reduce get person [:employer :address :city]) ; explained below (println (reduce + '(1 2 3) ) ) (def vehicle-struct (create-struct :make :model :year :color)) ; long way (defstruct vehicle-struct :make :model :year :color) ; short way (def vehicle (struct vehicle-struct "Toyota" "Prius" 2009,"RED")) (def my (accessor vehicle-struct :make)) (println(my vehicle)) ; -> "Toyota" (println(get-in vehicle [:make])) ; -> "Toyota" (println (vehicle :make))
65727
(in-ns 'user) (defn hello [name] (println "hello" name)) (hello "dfaf") (def vowel? (set "aeiou")) (defn pig-latin [word] (let [first-letter (first word)] (if (vowel? first-letter) (str word "ay") (str (subs word 1) first-letter "ay") )) ) (println (pig-latin "red")) (println (pig-latin "orange")) (def v 1) ; v is a global binding (defn f1 [] (println "f1: v =" v)) ; global binding (defn f2 [] (println "f2: before let v =" v) ; global binding (let [v 2] ; creates local binding v that shadows global one (println "f2: in let, v =" v) ; local binding (f1)) (println "f2: after let v =" v)) ; global binding (defn f3 [] (println "f3: before binding v =" v) ; global binding (binding [v 3] ; same global binding with new, temporary value (println "f3: in binding, v =" v) ; global binding (f1)) (println "f3: after binding v =" v)) ; global binding (defn f4 [] (def v 4)) ; changes the value of the global binding ;(f2) ;(f3) ;(f4) (println "after calling f4, v =" v) (println (count [19 "yellow" true])) (println (reverse [2 4 7])) (println (map + [2 4 7] [5 6] [1 2 3 4])) (println (map #(+ % 1) (map #(/ % 3) [1 2 3]))) (def stooges ["Moe" "Larry" "<NAME>ly" "Shemp"]) (first stooges) ; -> "Moe" (second stooges) ; -> "<NAME>arry" (last stooges) ; -> "<NAME>mp" (nth stooges 2) ; indexes start at 0 -> "<NAME>" (next stooges) ; -> ("<NAME>" "<NAME>" "<NAME>") (butlast stooges) ; -> ("<NAME>" "<NAME>" "<NAME>") (drop-last 2 stooges) ; -> ("<NAME>" "<NAME>") ; Get names containing more than three characters. (filter #(> (count %) 3) stooges) ; -> ("<NAME>" "<NAME>" "<NAME>") (nthnext stooges 2) ; -> ("<NAME>" "<NAME>") (println (apply + [2 4 7])) (def stooges (list "<NAME>" "<NAME>" "Cur<NAME>")) ; list (def stooges (quote ("<NAME>" "<NAME>" "Cur<NAME>"))) ; list (def stooges '("<NAME>" "<NAME>" "Cur<NAME>")) ; list ;(some #(= % "<NAME>") stooges) ; -> true ;(some #(= % "<NAME>") stooges) ; -> nil (println (contains? (set stooges) "Moe")) ; convert to list set and use contains (def conbined_list (into (list "aa" "bb" "cc") (list "dd" "ee" "ff"))) (println (reverse conbined_list)) (def may_be "fff") (println (get ["AAA" "BB" "DDD" may_be] 1 "unknown")) ; get only work for vector (println (get ["AAA" "BB" "DDD" may_be] 10 "unknown")) ; get only work for vector (def simple_set #{"ab","ac","ae"}) (println (simple_set "ab") (simple_set "aaa")) (println (if (nil? (simple_set "aaa")) "abbb" "dff")) (def popsicle-map (hash-map :red "cherry", :green :apple , :purple :grape)) (def popsicle-map {:red :cherry, :green :apple, :purple :grape}) ; same as previous (def popsicle-map (sorted-map :red "cherry", :green :apple , :purple :grape)) (println (contains? popsicle-map :red)) (println (some #{"cherry"} (vals popsicle-map))) (println (vals popsicle-map)) (println (contains? (set (vals popsicle-map)) "cherry")) (def person { :name "<NAME>" :address { :street "644 Glen Summit" :city "St. Charles" :state "Missouri" :zip 63304} :employer { :name "Object Computing, Inc." :address { :street "12140 Woodcrest Executive Drive, Suite 250" :city "Creve Coeur" :state "Missouri" :zip 63141}}}) (println(get-in person [:employer :address :city])) (-> person :employer :address :city) ; explained below (reduce get person [:employer :address :city]) ; explained below (println (reduce + '(1 2 3) ) ) (def vehicle-struct (create-struct :make :model :year :color)) ; long way (defstruct vehicle-struct :make :model :year :color) ; short way (def vehicle (struct vehicle-struct "Toyota" "Prius" 2009,"RED")) (def my (accessor vehicle-struct :make)) (println(my vehicle)) ; -> "Toyota" (println(get-in vehicle [:make])) ; -> "Toyota" (println (vehicle :make))
true
(in-ns 'user) (defn hello [name] (println "hello" name)) (hello "dfaf") (def vowel? (set "aeiou")) (defn pig-latin [word] (let [first-letter (first word)] (if (vowel? first-letter) (str word "ay") (str (subs word 1) first-letter "ay") )) ) (println (pig-latin "red")) (println (pig-latin "orange")) (def v 1) ; v is a global binding (defn f1 [] (println "f1: v =" v)) ; global binding (defn f2 [] (println "f2: before let v =" v) ; global binding (let [v 2] ; creates local binding v that shadows global one (println "f2: in let, v =" v) ; local binding (f1)) (println "f2: after let v =" v)) ; global binding (defn f3 [] (println "f3: before binding v =" v) ; global binding (binding [v 3] ; same global binding with new, temporary value (println "f3: in binding, v =" v) ; global binding (f1)) (println "f3: after binding v =" v)) ; global binding (defn f4 [] (def v 4)) ; changes the value of the global binding ;(f2) ;(f3) ;(f4) (println "after calling f4, v =" v) (println (count [19 "yellow" true])) (println (reverse [2 4 7])) (println (map + [2 4 7] [5 6] [1 2 3 4])) (println (map #(+ % 1) (map #(/ % 3) [1 2 3]))) (def stooges ["Moe" "Larry" "PI:NAME:<NAME>END_PIly" "Shemp"]) (first stooges) ; -> "Moe" (second stooges) ; -> "PI:NAME:<NAME>END_PIarry" (last stooges) ; -> "PI:NAME:<NAME>END_PImp" (nth stooges 2) ; indexes start at 0 -> "PI:NAME:<NAME>END_PI" (next stooges) ; -> ("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") (butlast stooges) ; -> ("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") (drop-last 2 stooges) ; -> ("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") ; Get names containing more than three characters. (filter #(> (count %) 3) stooges) ; -> ("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") (nthnext stooges 2) ; -> ("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") (println (apply + [2 4 7])) (def stooges (list "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "CurPI:NAME:<NAME>END_PI")) ; list (def stooges (quote ("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "CurPI:NAME:<NAME>END_PI"))) ; list (def stooges '("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "CurPI:NAME:<NAME>END_PI")) ; list ;(some #(= % "PI:NAME:<NAME>END_PI") stooges) ; -> true ;(some #(= % "PI:NAME:<NAME>END_PI") stooges) ; -> nil (println (contains? (set stooges) "Moe")) ; convert to list set and use contains (def conbined_list (into (list "aa" "bb" "cc") (list "dd" "ee" "ff"))) (println (reverse conbined_list)) (def may_be "fff") (println (get ["AAA" "BB" "DDD" may_be] 1 "unknown")) ; get only work for vector (println (get ["AAA" "BB" "DDD" may_be] 10 "unknown")) ; get only work for vector (def simple_set #{"ab","ac","ae"}) (println (simple_set "ab") (simple_set "aaa")) (println (if (nil? (simple_set "aaa")) "abbb" "dff")) (def popsicle-map (hash-map :red "cherry", :green :apple , :purple :grape)) (def popsicle-map {:red :cherry, :green :apple, :purple :grape}) ; same as previous (def popsicle-map (sorted-map :red "cherry", :green :apple , :purple :grape)) (println (contains? popsicle-map :red)) (println (some #{"cherry"} (vals popsicle-map))) (println (vals popsicle-map)) (println (contains? (set (vals popsicle-map)) "cherry")) (def person { :name "PI:NAME:<NAME>END_PI" :address { :street "644 Glen Summit" :city "St. Charles" :state "Missouri" :zip 63304} :employer { :name "Object Computing, Inc." :address { :street "12140 Woodcrest Executive Drive, Suite 250" :city "Creve Coeur" :state "Missouri" :zip 63141}}}) (println(get-in person [:employer :address :city])) (-> person :employer :address :city) ; explained below (reduce get person [:employer :address :city]) ; explained below (println (reduce + '(1 2 3) ) ) (def vehicle-struct (create-struct :make :model :year :color)) ; long way (defstruct vehicle-struct :make :model :year :color) ; short way (def vehicle (struct vehicle-struct "Toyota" "Prius" 2009,"RED")) (def my (accessor vehicle-struct :make)) (println(my vehicle)) ; -> "Toyota" (println(get-in vehicle [:make])) ; -> "Toyota" (println (vehicle :make))
[ { "context": ":authorize-url \"https://login.microsoftonline.com/60c86d26-b84a-4f67-b697-ce6ed68d1552/oauth2/v2.0/au", "end": 427, "score": 0.47527411580085754, "start": 426, "tag": "KEY", "value": "6" }, { "context": "authorize-url \"https://login.microsoftonline.com/60c86d26-b84a-4f67-b697-ce6ed68d1552/oauth2/v2.0/authorize\"\n :client-id \"1cbf02d2-20", "end": 462, "score": 0.6009688377380371, "start": 427, "tag": "PASSWORD", "value": "0c86d26-b84a-4f67-b697-ce6ed68d1552" } ]
src/app/domain/settings.cljc
Cukac/shadow-electron-starter
0
(ns app.domain.settings #?(:cljs (:require-macros [app.domain.settings :refer [env-var]]))) #?(:clj (defmacro env-var [env-var-name] (System/getenv env-var-name))) (def backend-endpoint (env-var "BACKEND_URL")) (def jwt-ls-name "als-education-jwt") (def ad-id-token-ls-name "ad-id-token") (def ad-access-token-ls-name "ad-access-token") (def ad-query-params {:authorize-url "https://login.microsoftonline.com/60c86d26-b84a-4f67-b697-ce6ed68d1552/oauth2/v2.0/authorize" :client-id "1cbf02d2-20f2-487a-bbab-8f705c437033" :redirect-uri "https://als-demo.verybigthings.com/azure-ad/callback" :response-type "id_token token" :scope "openid email profile" :state #js{:page "login"}})
86
(ns app.domain.settings #?(:cljs (:require-macros [app.domain.settings :refer [env-var]]))) #?(:clj (defmacro env-var [env-var-name] (System/getenv env-var-name))) (def backend-endpoint (env-var "BACKEND_URL")) (def jwt-ls-name "als-education-jwt") (def ad-id-token-ls-name "ad-id-token") (def ad-access-token-ls-name "ad-access-token") (def ad-query-params {:authorize-url "https://login.microsoftonline.com/<KEY> <PASSWORD>/oauth2/v2.0/authorize" :client-id "1cbf02d2-20f2-487a-bbab-8f705c437033" :redirect-uri "https://als-demo.verybigthings.com/azure-ad/callback" :response-type "id_token token" :scope "openid email profile" :state #js{:page "login"}})
true
(ns app.domain.settings #?(:cljs (:require-macros [app.domain.settings :refer [env-var]]))) #?(:clj (defmacro env-var [env-var-name] (System/getenv env-var-name))) (def backend-endpoint (env-var "BACKEND_URL")) (def jwt-ls-name "als-education-jwt") (def ad-id-token-ls-name "ad-id-token") (def ad-access-token-ls-name "ad-access-token") (def ad-query-params {:authorize-url "https://login.microsoftonline.com/PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI/oauth2/v2.0/authorize" :client-id "1cbf02d2-20f2-487a-bbab-8f705c437033" :redirect-uri "https://als-demo.verybigthings.com/azure-ad/callback" :response-type "id_token token" :scope "openid email profile" :state #js{:page "login"}})
[ { "context": ";;\n;;\n;; Copyright 2013-2015 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic", "end": 33, "score": 0.9699524641036987, "start": 30, "tag": "NAME", "value": "Net" } ]
pigpen-core/src/main/clojure/pigpen/runtime.clj
ombagus/Netflix
327
;; ;; ;; Copyright 2013-2015 Netflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.runtime "Functions for evaluating user code at runtime") (set! *warn-on-reflection* true) (defmacro with-ns "Evaluates f within ns. Calls (require 'ns) first." [ns f] `(do (require '~ns) (binding [*ns* (find-ns '~ns)] (eval '~f)))) (defn map->bind "For use with pigpen.core.op/bind$ Takes a map-style function (one that takes a single input and returns a single output) and returns a bind function that performs the same logic. Example: (map->bind (fn [x] (* x x))) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [f] (fn [rf] (fn [result input] (rf result [(apply f input)])))) (defn mapcat->bind "For use with pigpen.core.op/bind$ Takes a mapcat-style function (one that takes a single input and returns zero to many outputs) and returns a bind function that performs the same logic. Example: (mapcat->bind (fn [x] (seq x))) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [f] (fn [rf] (fn [result input] (reduce rf result (map vector (apply f input)))))) (defn filter->bind "For use with pigpen.core.op/bind$ Takes a filter-style function (one that takes a single input and returns a boolean output) and returns a bind function that performs the same logic. Example: (filter->bind (fn [x] (even? x))) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [f] (fn [rf] (fn [result input] (if (apply f input) (rf result input) result)))) (defn key-selector->bind "For use with pigpen.core.op/bind$ Creates a key-selector function based on `f`. The resulting bind function returns a tuple of [(f x) x]. This is generally used to separate a key for subsequent use in a sort, group, or join. Example: (key-selector->bind (fn [x] (:foo x))) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [f] (fn [rf] (fn [result input] (rf result [(apply f input) (first input)])))) (defn keyword-field-selector->bind "For use with pigpen.core.op/bind$ Selects a set of fields from a map and projects them as native fields. The bind function takes a single arg, which is a map with keyword keys. The parameter `fields` is a sequence of keywords to select. The input relation should have a single field that is a map value. Example: (keyword-field-selector->bind [:foo :bar :baz]) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [fields] (fn [rf] (fn [result [input]] (when-not (map? input) (throw (ex-info "Expected map with keyword keys." {:input input}))) (rf result (map input fields))))) (defn indexed-field-selector->bind "For use with pigpen.core.op/bind$ Selects the first n fields and projects them as fields. The input relation should have a single field, which is sequential. Applies f to the remaining args. Example: (indexed-field-selector->bind 2 pr-str) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [n f] (fn [rf] (fn [result [input]] (rf result (concat (take n input) [(f (drop n input))]))))) (defn process->bind "Wraps the output of pre- and post-process with a vector." [f] (fn [rf] (fn [result input] (rf result (f input))))) (defn args->map "Returns a fn that converts a list of args into a map of named parameter values. Applies f to all the values." [f] (fn [& args] (->> args (partition 2) (map (fn [[k v]] [(keyword k) (f v)])) (into {})))) (defn sentinel-nil "Coerces nils into a sentinel value. Useful for nil handling in outer joins." [value] (if (nil? value) ::nil value)) (defn debug [& args] "Creates a debug string for the tuple" (try (->> args (mapcat (juxt type str)) (clojure.string/join "\t")) (catch Exception z (str "Error getting value: " z)))) (defn eval-string "Reads code from a string & evaluates it" [f] (when (not-empty f) (try (eval (read-string f)) (catch Throwable z (throw (RuntimeException. (str "Exception evaluating: " f) z)))))) (defprotocol HybridToClojure (hybrid->clojure [value] "Converts a hybrid data structure into 100% clojure. Platforms should add methods for any types they expect to see.")) (extend-protocol HybridToClojure nil (hybrid->clojure [value] value) Object (hybrid->clojure [value] value) java.util.Map (hybrid->clojure [value] (->> value (map (fn [[k v]] [(hybrid->clojure k) (hybrid->clojure v)])) (into {})))) (defprotocol NativeToClojure (native->clojure [value] "Converts native data structures into 100% clojure. Platforms should add methods for any types they expect to see. No clojure should be seen here.")) (extend-protocol NativeToClojure nil (native->clojure [value] value) Object (native->clojure [value] value) java.util.Map (native->clojure [value] (->> value (map (fn [[k v]] [(native->clojure k) (native->clojure v)])) (into {})))) (defmulti pre-process "Optionally deserializes incoming data. Should return a fn that takes a single 'args' param and returns a seq of processed args. 'platform' is what will be running the code (:pig, :cascading, etc). 'serialization-type' defines which of the fields to serialize. It will be one of: :native - everything should be native values. You may need to coerce host types into clojure types here. :frozen - deserialize everything " (fn [platform serialization-type] [platform serialization-type])) (defmethod pre-process :default [_ _] identity) (defmulti post-process "Optionally serializes outgoing data. Should return a fn that takes a single 'args' param and returns a seq of processed args. 'platform' is what will be running the code (:pig, :cascading, etc). 'serialization-type' defines which of the fields to serialize. It will be one of: :native - don't serialize :frozen - serialize everything :frozen-with-nils - serialize everything except nils :native-key-frozen-val - expect a tuple, freeze only the second value " (fn [platform serialization-type] [platform serialization-type])) (defmethod post-process :default [_ _] identity)
75054
;; ;; ;; Copyright 2013-2015 <NAME>flix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.runtime "Functions for evaluating user code at runtime") (set! *warn-on-reflection* true) (defmacro with-ns "Evaluates f within ns. Calls (require 'ns) first." [ns f] `(do (require '~ns) (binding [*ns* (find-ns '~ns)] (eval '~f)))) (defn map->bind "For use with pigpen.core.op/bind$ Takes a map-style function (one that takes a single input and returns a single output) and returns a bind function that performs the same logic. Example: (map->bind (fn [x] (* x x))) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [f] (fn [rf] (fn [result input] (rf result [(apply f input)])))) (defn mapcat->bind "For use with pigpen.core.op/bind$ Takes a mapcat-style function (one that takes a single input and returns zero to many outputs) and returns a bind function that performs the same logic. Example: (mapcat->bind (fn [x] (seq x))) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [f] (fn [rf] (fn [result input] (reduce rf result (map vector (apply f input)))))) (defn filter->bind "For use with pigpen.core.op/bind$ Takes a filter-style function (one that takes a single input and returns a boolean output) and returns a bind function that performs the same logic. Example: (filter->bind (fn [x] (even? x))) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [f] (fn [rf] (fn [result input] (if (apply f input) (rf result input) result)))) (defn key-selector->bind "For use with pigpen.core.op/bind$ Creates a key-selector function based on `f`. The resulting bind function returns a tuple of [(f x) x]. This is generally used to separate a key for subsequent use in a sort, group, or join. Example: (key-selector->bind (fn [x] (:foo x))) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [f] (fn [rf] (fn [result input] (rf result [(apply f input) (first input)])))) (defn keyword-field-selector->bind "For use with pigpen.core.op/bind$ Selects a set of fields from a map and projects them as native fields. The bind function takes a single arg, which is a map with keyword keys. The parameter `fields` is a sequence of keywords to select. The input relation should have a single field that is a map value. Example: (keyword-field-selector->bind [:foo :bar :baz]) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [fields] (fn [rf] (fn [result [input]] (when-not (map? input) (throw (ex-info "Expected map with keyword keys." {:input input}))) (rf result (map input fields))))) (defn indexed-field-selector->bind "For use with pigpen.core.op/bind$ Selects the first n fields and projects them as fields. The input relation should have a single field, which is sequential. Applies f to the remaining args. Example: (indexed-field-selector->bind 2 pr-str) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [n f] (fn [rf] (fn [result [input]] (rf result (concat (take n input) [(f (drop n input))]))))) (defn process->bind "Wraps the output of pre- and post-process with a vector." [f] (fn [rf] (fn [result input] (rf result (f input))))) (defn args->map "Returns a fn that converts a list of args into a map of named parameter values. Applies f to all the values." [f] (fn [& args] (->> args (partition 2) (map (fn [[k v]] [(keyword k) (f v)])) (into {})))) (defn sentinel-nil "Coerces nils into a sentinel value. Useful for nil handling in outer joins." [value] (if (nil? value) ::nil value)) (defn debug [& args] "Creates a debug string for the tuple" (try (->> args (mapcat (juxt type str)) (clojure.string/join "\t")) (catch Exception z (str "Error getting value: " z)))) (defn eval-string "Reads code from a string & evaluates it" [f] (when (not-empty f) (try (eval (read-string f)) (catch Throwable z (throw (RuntimeException. (str "Exception evaluating: " f) z)))))) (defprotocol HybridToClojure (hybrid->clojure [value] "Converts a hybrid data structure into 100% clojure. Platforms should add methods for any types they expect to see.")) (extend-protocol HybridToClojure nil (hybrid->clojure [value] value) Object (hybrid->clojure [value] value) java.util.Map (hybrid->clojure [value] (->> value (map (fn [[k v]] [(hybrid->clojure k) (hybrid->clojure v)])) (into {})))) (defprotocol NativeToClojure (native->clojure [value] "Converts native data structures into 100% clojure. Platforms should add methods for any types they expect to see. No clojure should be seen here.")) (extend-protocol NativeToClojure nil (native->clojure [value] value) Object (native->clojure [value] value) java.util.Map (native->clojure [value] (->> value (map (fn [[k v]] [(native->clojure k) (native->clojure v)])) (into {})))) (defmulti pre-process "Optionally deserializes incoming data. Should return a fn that takes a single 'args' param and returns a seq of processed args. 'platform' is what will be running the code (:pig, :cascading, etc). 'serialization-type' defines which of the fields to serialize. It will be one of: :native - everything should be native values. You may need to coerce host types into clojure types here. :frozen - deserialize everything " (fn [platform serialization-type] [platform serialization-type])) (defmethod pre-process :default [_ _] identity) (defmulti post-process "Optionally serializes outgoing data. Should return a fn that takes a single 'args' param and returns a seq of processed args. 'platform' is what will be running the code (:pig, :cascading, etc). 'serialization-type' defines which of the fields to serialize. It will be one of: :native - don't serialize :frozen - serialize everything :frozen-with-nils - serialize everything except nils :native-key-frozen-val - expect a tuple, freeze only the second value " (fn [platform serialization-type] [platform serialization-type])) (defmethod post-process :default [_ _] identity)
true
;; ;; ;; Copyright 2013-2015 PI:NAME:<NAME>END_PIflix, Inc. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns pigpen.runtime "Functions for evaluating user code at runtime") (set! *warn-on-reflection* true) (defmacro with-ns "Evaluates f within ns. Calls (require 'ns) first." [ns f] `(do (require '~ns) (binding [*ns* (find-ns '~ns)] (eval '~f)))) (defn map->bind "For use with pigpen.core.op/bind$ Takes a map-style function (one that takes a single input and returns a single output) and returns a bind function that performs the same logic. Example: (map->bind (fn [x] (* x x))) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [f] (fn [rf] (fn [result input] (rf result [(apply f input)])))) (defn mapcat->bind "For use with pigpen.core.op/bind$ Takes a mapcat-style function (one that takes a single input and returns zero to many outputs) and returns a bind function that performs the same logic. Example: (mapcat->bind (fn [x] (seq x))) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [f] (fn [rf] (fn [result input] (reduce rf result (map vector (apply f input)))))) (defn filter->bind "For use with pigpen.core.op/bind$ Takes a filter-style function (one that takes a single input and returns a boolean output) and returns a bind function that performs the same logic. Example: (filter->bind (fn [x] (even? x))) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [f] (fn [rf] (fn [result input] (if (apply f input) (rf result input) result)))) (defn key-selector->bind "For use with pigpen.core.op/bind$ Creates a key-selector function based on `f`. The resulting bind function returns a tuple of [(f x) x]. This is generally used to separate a key for subsequent use in a sort, group, or join. Example: (key-selector->bind (fn [x] (:foo x))) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [f] (fn [rf] (fn [result input] (rf result [(apply f input) (first input)])))) (defn keyword-field-selector->bind "For use with pigpen.core.op/bind$ Selects a set of fields from a map and projects them as native fields. The bind function takes a single arg, which is a map with keyword keys. The parameter `fields` is a sequence of keywords to select. The input relation should have a single field that is a map value. Example: (keyword-field-selector->bind [:foo :bar :baz]) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [fields] (fn [rf] (fn [result [input]] (when-not (map? input) (throw (ex-info "Expected map with keyword keys." {:input input}))) (rf result (map input fields))))) (defn indexed-field-selector->bind "For use with pigpen.core.op/bind$ Selects the first n fields and projects them as fields. The input relation should have a single field, which is sequential. Applies f to the remaining args. Example: (indexed-field-selector->bind 2 pr-str) See also: pigpen.core.op/bind$ " {:added "0.3.0"} [n f] (fn [rf] (fn [result [input]] (rf result (concat (take n input) [(f (drop n input))]))))) (defn process->bind "Wraps the output of pre- and post-process with a vector." [f] (fn [rf] (fn [result input] (rf result (f input))))) (defn args->map "Returns a fn that converts a list of args into a map of named parameter values. Applies f to all the values." [f] (fn [& args] (->> args (partition 2) (map (fn [[k v]] [(keyword k) (f v)])) (into {})))) (defn sentinel-nil "Coerces nils into a sentinel value. Useful for nil handling in outer joins." [value] (if (nil? value) ::nil value)) (defn debug [& args] "Creates a debug string for the tuple" (try (->> args (mapcat (juxt type str)) (clojure.string/join "\t")) (catch Exception z (str "Error getting value: " z)))) (defn eval-string "Reads code from a string & evaluates it" [f] (when (not-empty f) (try (eval (read-string f)) (catch Throwable z (throw (RuntimeException. (str "Exception evaluating: " f) z)))))) (defprotocol HybridToClojure (hybrid->clojure [value] "Converts a hybrid data structure into 100% clojure. Platforms should add methods for any types they expect to see.")) (extend-protocol HybridToClojure nil (hybrid->clojure [value] value) Object (hybrid->clojure [value] value) java.util.Map (hybrid->clojure [value] (->> value (map (fn [[k v]] [(hybrid->clojure k) (hybrid->clojure v)])) (into {})))) (defprotocol NativeToClojure (native->clojure [value] "Converts native data structures into 100% clojure. Platforms should add methods for any types they expect to see. No clojure should be seen here.")) (extend-protocol NativeToClojure nil (native->clojure [value] value) Object (native->clojure [value] value) java.util.Map (native->clojure [value] (->> value (map (fn [[k v]] [(native->clojure k) (native->clojure v)])) (into {})))) (defmulti pre-process "Optionally deserializes incoming data. Should return a fn that takes a single 'args' param and returns a seq of processed args. 'platform' is what will be running the code (:pig, :cascading, etc). 'serialization-type' defines which of the fields to serialize. It will be one of: :native - everything should be native values. You may need to coerce host types into clojure types here. :frozen - deserialize everything " (fn [platform serialization-type] [platform serialization-type])) (defmethod pre-process :default [_ _] identity) (defmulti post-process "Optionally serializes outgoing data. Should return a fn that takes a single 'args' param and returns a seq of processed args. 'platform' is what will be running the code (:pig, :cascading, etc). 'serialization-type' defines which of the fields to serialize. It will be one of: :native - don't serialize :frozen - serialize everything :frozen-with-nils - serialize everything except nils :native-key-frozen-val - expect a tuple, freeze only the second value " (fn [platform serialization-type] [platform serialization-type])) (defmethod post-process :default [_ _] identity)
[ { "context": "est namespacefy-map\n (is (= (namespacefy {:name \"Seppo\" :id 1}\n {:ns :product.domai", "end": 661, "score": 0.995566189289093, "start": 656, "tag": "NAME", "value": "Seppo" }, { "context": "n.person})\n {:product.domain.person/name \"Seppo\"\n :product.domain.person/id 1})))\n\n(deft", "end": 766, "score": 0.9401351809501648, "start": 761, "tag": "NAME", "value": "Seppo" }, { "context": " namespacefy-coll\n (is (= (namespacefy '({:name \"Seppo\" :id 1})\n {:ns :product.doma", "end": 874, "score": 0.9965946078300476, "start": 869, "tag": "NAME", "value": "Seppo" }, { "context": "person})\n '({:product.domain.person/name \"Seppo\"\n :product.domain.person/id 1}))))\n\n(d", "end": 982, "score": 0.9479885697364807, "start": 977, "tag": "NAME", "value": "Seppo" }, { "context": "is (= (namespacefy (java.util.ArrayList. [{:name \"Seppo\" :id 1}])\n {:ns :product.dom", "end": 1120, "score": 0.9949894547462463, "start": 1115, "tag": "NAME", "value": "Seppo" }, { "context": "n.person}))\n '({:product.domain.person/name \"Seppo\"\n :product.domain.person/id 1})))\n\n(defte", "end": 1227, "score": 0.9853439927101135, "start": 1222, "tag": "NAME", "value": "Seppo" }, { "context": "ence\n (is (= (namespacefy (map identity [{:name \"Seppo\" :id 1}])\n {:ns :product.dom", "end": 1356, "score": 0.9968116879463196, "start": 1351, "tag": "NAME", "value": "Seppo" }, { "context": ".person})\n [{:product.domain.person/name \"Seppo\"\n :product.domain.person/id 1}])))\n\n(de", "end": 1464, "score": 0.9883039593696594, "start": 1459, "tag": "NAME", "value": "Seppo" }, { "context": "t namespacefy-set\n (is (= (namespacefy #{{:name \"Seppo\" :id 1}}\n {:ns :product.doma", "end": 1573, "score": 0.9937713742256165, "start": 1568, "tag": "NAME", "value": "Seppo" }, { "context": "person})\n #{{:product.domain.person/name \"Seppo\"\n :product.domain.person/id 1}})))\n\n(d", "end": 1681, "score": 0.9561235308647156, "start": 1676, "tag": "NAME", "value": "Seppo" }, { "context": "espacefy-nested-map\n (is (= (namespacefy {:name \"Seppo\"\n :id 1\n ", "end": 1796, "score": 0.999086856842041, "start": 1791, "tag": "NAME", "value": "Seppo" }, { "context": "ddress}}})\n {:product.domain.person/name \"Seppo\"\n :product.domain.person/id 1\n ", "end": 2325, "score": 0.9993756413459778, "start": 2320, "tag": "NAME", "value": "Seppo" }, { "context": "y-deeply-nested-map\n (is (= (namespacefy {:name \"Seppo\"\n :id 1\n ", "end": 2752, "score": 0.9992029666900635, "start": 2747, "tag": "NAME", "value": "Seppo" }, { "context": ".gps}}}}})\n {:product.domain.person/name \"Seppo\"\n :product.domain.person/id 1\n ", "end": 3310, "score": 0.9991914629936218, "start": 3305, "tag": "NAME", "value": "Seppo" }, { "context": "omain.gps/y 0}}}))\n\n (is (= (namespacefy {:name \"Seppo\"\n :id 1\n ", "end": 3856, "score": 0.9990420937538147, "start": 3851, "tag": "NAME", "value": "Seppo" }, { "context": ".gps}}}}})\n {:product.domain.person/name \"Seppo\"\n :product.domain.person/id 1\n ", "end": 4582, "score": 0.9997616410255432, "start": 4577, "tag": "NAME", "value": "Seppo" }, { "context": "pacefy-coll-of-maps\n (is (= (namespacefy {:name \"Seppo\"\n :id 1\n ", "end": 5213, "score": 0.9997077584266663, "start": 5208, "tag": "NAME", "value": "Seppo" }, { "context": "n.task}}})\n {:product.domain.person/name \"Seppo\"\n :product.domain.person/id 1\n ", "end": 5557, "score": 0.9996914863586426, "start": 5552, "tag": "NAME", "value": "Seppo" }, { "context": " Inner value is nil\n (is (= (namespacefy {:name \"Seppo\"\n :address nil}\n ", "end": 9788, "score": 0.9961554408073425, "start": 9783, "tag": "NAME", "value": "Seppo" }, { "context": "ddress}}})\n {:product.domain.person/name \"Seppo\"\n :product.domain.person/address nil})))", "end": 9994, "score": 0.9825688004493713, "start": 9989, "tag": "NAME", "value": "Seppo" }, { "context": "wn? IllegalArgumentException (namespacefy {:name \"Seppo\"} {}))))\n\n; Unnamespacefy\n\n(deftest unnamespacefy", "end": 10408, "score": 0.8912293314933777, "start": 10403, "tag": "NAME", "value": "Seppo" }, { "context": "s (= (unnamespacefy {:product.domain.person/name \"Seppo\"\n :product.domain.person/", "end": 10529, "score": 0.9572219848632812, "start": 10524, "tag": "NAME", "value": "Seppo" }, { "context": " :product.domain.person/id 1})\n {:name \"Seppo\" :id 1}))\n (is (= (unnamespacefy {:name \"Seppo\"\n", "end": 10608, "score": 0.9964267611503601, "start": 10603, "tag": "NAME", "value": "Seppo" }, { "context": " \"Seppo\" :id 1}))\n (is (= (unnamespacefy {:name \"Seppo\"\n :id 1})\n {:name", "end": 10656, "score": 0.9921696782112122, "start": 10651, "tag": "NAME", "value": "Seppo" }, { "context": " :id 1})\n {:name \"Seppo\" :id 1}))\n (is (= (unnamespacefy {:product.domai", "end": 10713, "score": 0.9971372485160828, "start": 10708, "tag": "NAME", "value": "Seppo" }, { "context": "s (= (unnamespacefy {:product.domain.person/name \"Seppo\"\n :id 1})\n {:name", "end": 10783, "score": 0.9126574993133545, "start": 10778, "tag": "NAME", "value": "Seppo" }, { "context": " :id 1})\n {:name \"Seppo\" :id 1})))\n\n(deftest unnamespacefy-coll\n (is (= ", "end": 10840, "score": 0.9959792494773865, "start": 10835, "tag": "NAME", "value": "Seppo" }, { "context": "(= (unnamespacefy '({:product.domain.person/name \"Seppo\"\n :product.domain.perso", "end": 10942, "score": 0.934140145778656, "start": 10937, "tag": "NAME", "value": "Seppo" }, { "context": ":product.domain.person/id 1}))\n '({:name \"Seppo\" :id 1}))))\n\n(deftest unnamespacefy-array-list\n ", "end": 11026, "score": 0.9957404136657715, "start": 11021, "tag": "NAME", "value": "Seppo" }, { "context": "a.util.ArrayList. '[{:product.domain.person/name \"Seppo\"\n ", "end": 11157, "score": 0.7049177289009094, "start": 11152, "tag": "NAME", "value": "Seppo" }, { "context": "product.domain.person/id 1}]))\n '({:name \"Seppo\" :id 1}))))\n\n(deftest unnamespacefy-set\n (is (= ", "end": 11264, "score": 0.9942050576210022, "start": 11259, "tag": "NAME", "value": "Seppo" }, { "context": "(= (unnamespacefy #{{:product.domain.person/name \"Seppo\"\n :product.domain.perso", "end": 11366, "score": 0.7868146896362305, "start": 11361, "tag": "NAME", "value": "Seppo" }, { "context": ":product.domain.person/id 1}})\n #{{:name \"Seppo\" :id 1}})))\n\n(deftest unnamespacefy-lazy-sequence", "end": 11450, "score": 0.9683859348297119, "start": 11445, "tag": "NAME", "value": "Seppo" }, { "context": "cefy (map identity [{:product.domain.person/name \"Seppo\"\n :product", "end": 11575, "score": 0.9563438892364502, "start": 11570, "tag": "NAME", "value": "Seppo" }, { "context": ":product.domain.person/id 1}]))\n [{:name \"Seppo\" :id 1}])))\n\n(deftest unnamespacefy-nested-map\n ", "end": 11672, "score": 0.9955592155456543, "start": 11667, "tag": "NAME", "value": "Seppo" }, { "context": "s (= (unnamespacefy {:product.domain.player/name \"Seppo\"\n :product.domain.player/", "end": 11779, "score": 0.8229572176933289, "start": 11774, "tag": "NAME", "value": "Seppo" }, { "context": "ks {:product.domain.task/id 6}})\n {:name \"Seppo\" :id 1 :tasks {:product.domain.task/id 6}}))\n\n (", "end": 11940, "score": 0.9703397154808044, "start": 11935, "tag": "NAME", "value": "Seppo" }, { "context": "s (= (unnamespacefy {:product.domain.player/name \"Seppo\"\n :product.domain.player/", "end": 12046, "score": 0.8091042637825012, "start": 12041, "tag": "NAME", "value": "Seppo" }, { "context": "t #{:product.domain.player/id}})\n {:name \"Seppo\" :product.domain.player/id 666 :tasks {:product.d", "end": 12272, "score": 0.9493011832237244, "start": 12267, "tag": "NAME", "value": "Seppo" }, { "context": "s (= (unnamespacefy {:product.domain.player/name \"Seppo\"\n :product.domain.player/", "end": 12402, "score": 0.9157383441925049, "start": 12397, "tag": "NAME", "value": "Seppo" }, { "context": "t #{:product.domain.player/id}})\n {:name \"Seppo\" :product.domain.player/id 666 :task {:id 6}}))\n\n", "end": 12640, "score": 0.9483510851860046, "start": 12635, "tag": "NAME", "value": "Seppo" }, { "context": "s (= (unnamespacefy {:product.domain.player/name \"Seppo\"\n :product.domain.player/", "end": 13105, "score": 0.7116773724555969, "start": 13100, "tag": "NAME", "value": "Seppo" }, { "context": " {:recur? true})\n {:name \"Seppo\" :id 1 :tasks [{:id 6}\n ", "end": 13390, "score": 0.9656656384468079, "start": 13385, "tag": "NAME", "value": "Seppo" }, { "context": "s (= (unnamespacefy {:product.domain.player/name \"Seppo\"\n :product.domain.player", "end": 13523, "score": 0.5823022127151489, "start": 13519, "tag": "NAME", "value": "Sepp" }, { "context": " {:recur? true})\n {:name \"Seppo\" :id 1 :tasks '({:id 6}\n ", "end": 13812, "score": 0.9698494076728821, "start": 13807, "tag": "NAME", "value": "Seppo" }, { "context": "s (= (unnamespacefy {:product.domain.player/name \"Seppo\"\n :product.domain.player/", "end": 13949, "score": 0.6653043627738953, "start": 13944, "tag": "NAME", "value": "Seppo" }, { "context": " {:recur? true})\n {:name \"Seppo\" :id 1 :tasks #{{:id 6}\n ", "end": 14236, "score": 0.9580011367797852, "start": 14231, "tag": "NAME", "value": "Seppo" }, { "context": "s (= (unnamespacefy {:product.domain.player/name \"Seppo\"\n :product.domain.player/", "end": 14372, "score": 0.8662049770355225, "start": 14367, "tag": "NAME", "value": "Seppo" }, { "context": " {:recur? true})\n {:name \"Seppo\" :id 1 :tasks [{:id 6}\n ", "end": 14590, "score": 0.9763384461402893, "start": 14585, "tag": "NAME", "value": "Seppo" }, { "context": "s (= (unnamespacefy {:product.domain.person/name \"Seppo\"\n :product.domain.task/na", "end": 16125, "score": 0.7506619095802307, "start": 16120, "tag": "NAME", "value": "Seppo" }, { "context": "n.task/name :task-name}})\n {:person-name \"Seppo\"\n :task-name \"Important task\"}))\n (is (", "end": 16374, "score": 0.9982698559761047, "start": 16369, "tag": "NAME", "value": "Seppo" }, { "context": "s (= (unnamespacefy {:product.domain.person/name \"Seppo\"\n :name \"foo\"}\n ", "end": 16476, "score": 0.9269487857818604, "start": 16471, "tag": "NAME", "value": "Seppo" }, { "context": "rson/name :person-name}})\n {:person-name \"Seppo\"\n :name \"foo\"}))\n (is (= (unnamespacefy", "end": 16623, "score": 0.9989693760871887, "start": 16618, "tag": "NAME", "value": "Seppo" }, { "context": ")\n {:person-name \"Seppo\"\n :name \"foo\"}))\n (is (= (unnamespacefy {:product.domain.pers", "end": 16645, "score": 0.820209264755249, "start": 16642, "tag": "NAME", "value": "foo" }, { "context": "s (= (unnamespacefy {:product.domain.person/name \"Seppo\"\n :product.domain.task/na", "end": 16709, "score": 0.9319531321525574, "start": 16704, "tag": "NAME", "value": "Seppo" }, { "context": "n.task/name :task-name}})\n {:person-name \"Seppo\"\n :task-name \"Important task\"\n ", "end": 17016, "score": 0.9982765316963196, "start": 17011, "tag": "NAME", "value": "Seppo" }, { "context": "n.task/name :task-name}})\n {:person-name \"Seppo\"\n :task-name \"Important task\"\n ", "end": 17425, "score": 0.9973648190498352, "start": 17420, "tag": "NAME", "value": "Seppo" }, { "context": "s (= (unnamespacefy {:product.domain.person/name \"Seppo\"\n :product.domain.person/", "end": 17578, "score": 0.9107735753059387, "start": 17573, "tag": "NAME", "value": "Seppo" }, { "context": "duct.domain.person/address nil})\n {:name \"Seppo\"\n :address nil}))\n (is (= (unnamespacef", "end": 17664, "score": 0.991276204586029, "start": 17659, "tag": "NAME", "value": "Seppo" }, { "context": " :address nil})\n {:name \"Seppo\"\n :address nil}))\n (is (nil? (unnamespa", "end": 17815, "score": 0.9780645370483398, "start": 17810, "tag": "NAME", "value": "Seppo" } ]
test/namespacefy/core_test.clj
Jarzka/namespacefy
18
(ns namespacefy.core-test (:require [clojure.test :refer :all] [namespacefy.core :refer [namespacefy unnamespacefy get-un assoc-un]])) ; Namespacefy (deftest namespacefy-keyword (is (= (namespacefy :address {:ns :product.domain}) :product.domain/address)) (is (= (namespacefy :foo {:ns :domain}) :domain/foo))) (deftest namespacefy-with-same-regular-keywords (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.person/name "Seppo" :product.domain.task/name "Useless task"})))) (deftest namespacefy-map (is (= (namespacefy {:name "Seppo" :id 1} {:ns :product.domain.person}) {:product.domain.person/name "Seppo" :product.domain.person/id 1}))) (deftest namespacefy-coll (is (= (namespacefy '({:name "Seppo" :id 1}) {:ns :product.domain.person}) '({:product.domain.person/name "Seppo" :product.domain.person/id 1})))) (deftest namespacefy-array-list (is (= (namespacefy (java.util.ArrayList. [{:name "Seppo" :id 1}]) {:ns :product.domain.person})) '({:product.domain.person/name "Seppo" :product.domain.person/id 1}))) (deftest namespacefy-lazy-sequence (is (= (namespacefy (map identity [{:name "Seppo" :id 1}]) {:ns :product.domain.person}) [{:product.domain.person/name "Seppo" :product.domain.person/id 1}]))) (deftest namespacefy-set (is (= (namespacefy #{{:name "Seppo" :id 1}} {:ns :product.domain.person}) #{{:product.domain.person/name "Seppo" :product.domain.person/id 1}}))) (deftest namespacefy-nested-map (is (= (namespacefy {:name "Seppo" :id 1 :address {:address "Pihlajakatu 23" :city "Helsinki" :country "Finland"} :foo nil :modified nil} {:ns :product.domain.person :except #{:foo} :custom {:modified :our.ui/modified} :inner {:address {:ns :product.domain.address}}}) {:product.domain.person/name "Seppo" :product.domain.person/id 1 :product.domain.person/address {:product.domain.address/address "Pihlajakatu 23" :product.domain.address/city "Helsinki" :product.domain.address/country "Finland"} :foo nil :our.ui/modified nil}))) (deftest namespacefy-deeply-nested-map (is (= (namespacefy {:name "Seppo" :id 1 :address {:address "Pihlajakatu 23" :city "Helsinki" :country "Finland" :gps-location {:x 0 :y 0}}} {:ns :product.domain.person :inner {:address {:ns :product.domain.address :inner {:gps-location {:ns :product.domain.gps}}}}}) {:product.domain.person/name "Seppo" :product.domain.person/id 1 :product.domain.person/address {:product.domain.address/address "Pihlajakatu 23" :product.domain.address/city "Helsinki" :product.domain.address/country "Finland" :product.domain.address/gps-location {:product.domain.gps/x 0 :product.domain.gps/y 0}}})) (is (= (namespacefy {:name "Seppo" :id 1 :address {:address "Pihlajakatu 23" :city "Helsinki" :country "Finland" :gps-location {:x 0 :y 0}} :foo nil :modified nil} {:ns :product.domain.person :except #{:foo} :custom {:modified :our.ui/modified} :inner {:address {:ns :product.domain.address :inner {:gps-location {:ns :product.domain.gps}}}}}) {:product.domain.person/name "Seppo" :product.domain.person/id 1 :product.domain.person/address {:product.domain.address/address "Pihlajakatu 23" :product.domain.address/city "Helsinki" :product.domain.address/country "Finland" :product.domain.address/gps-location {:product.domain.gps/x 0 :product.domain.gps/y 0}} :foo nil :our.ui/modified nil}))) (deftest namespacefy-coll-of-maps (is (= (namespacefy {:name "Seppo" :id 1 :tasks [{:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"}]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/name "Seppo" :product.domain.person/id 1 :product.domain.person/tasks [{:product.domain.task/id 6 :product.domain.task/description "Do something useful"} {:product.domain.task/id 7 :product.domain.task/description "Do something useless"}]})) (is (= (namespacefy {:tasks '({:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"})} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks '({:product.domain.task/id 6 :product.domain.task/description "Do something useful"} {:product.domain.task/id 7 :product.domain.task/description "Do something useless"})})) (is (= (namespacefy {:tasks (map #(-> {:id %}) [1 2 3])} ;; Test lazy sequence {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [{:product.domain.task/id 1} {:product.domain.task/id 2} {:product.domain.task/id 3}]})) (is (= (namespacefy {:tasks #{{:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"}}} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks #{{:product.domain.task/description "Do something useful" :product.domain.task/id 6} {:product.domain.task/description "Do something useless" :product.domain.task/id 7}}}))) (deftest namespacefy-coll-things ;; Coll of colls (is (= (namespacefy {:tasks [[{:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"}] (java.util.ArrayList. [{:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"}])]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [[{:product.domain.task/id 6 :product.domain.task/description "Do something useful"} {:product.domain.task/id 7 :product.domain.task/description "Do something useless"}] [{:product.domain.task/id 6 :product.domain.task/description "Do something useful"} {:product.domain.task/id 7 :product.domain.task/description "Do something useless"}]]})) ;; Coll of keywords should not do anything (is (= (namespacefy {:tasks [:one :two :three]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [:one :two :three]})) ;; Coll of nils should not do anything (is (= (namespacefy {:tasks [nil nil nil]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [nil nil nil]})) ;; Coll of multiple types (let [object (new Object)] (is (= (namespacefy {:tasks [nil :keyword object]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [nil :keyword object]})))) (deftest namespacefy-nil (is (nil? (namespacefy nil {:ns :product.domain.person}))) ;; Inner value is nil (is (= (namespacefy {:name "Seppo" :address nil} {:ns :product.domain.person :inner {:address {:ns :product.domain.address}}}) {:product.domain.person/name "Seppo" :product.domain.person/address nil}))) (deftest namespacefy-empty (is (= (namespacefy {} {:ns :product.domain.person}) {}))) (deftest namespacefy-bad-data (is (thrown? IllegalArgumentException (namespacefy \k {:ns :product.domain.person}))) (is (thrown? IllegalArgumentException (namespacefy 123 {:ns :product.domain.person}))) (is (thrown? IllegalArgumentException (namespacefy {:name "Seppo"} {})))) ; Unnamespacefy (deftest unnamespacefy-simple-map (is (= (unnamespacefy {:product.domain.person/name "Seppo" :product.domain.person/id 1}) {:name "Seppo" :id 1})) (is (= (unnamespacefy {:name "Seppo" :id 1}) {:name "Seppo" :id 1})) (is (= (unnamespacefy {:product.domain.person/name "Seppo" :id 1}) {:name "Seppo" :id 1}))) (deftest unnamespacefy-coll (is (= (unnamespacefy '({:product.domain.person/name "Seppo" :product.domain.person/id 1})) '({:name "Seppo" :id 1})))) (deftest unnamespacefy-array-list (is (= (unnamespacefy (java.util.ArrayList. '[{:product.domain.person/name "Seppo" :product.domain.person/id 1}])) '({:name "Seppo" :id 1})))) (deftest unnamespacefy-set (is (= (unnamespacefy #{{:product.domain.person/name "Seppo" :product.domain.person/id 1}}) #{{:name "Seppo" :id 1}}))) (deftest unnamespacefy-lazy-sequence (is (= (unnamespacefy (map identity [{:product.domain.person/name "Seppo" :product.domain.person/id 1}])) [{:name "Seppo" :id 1}]))) (deftest unnamespacefy-nested-map (is (= (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.player/id 1 :product.domain.player/tasks {:product.domain.task/id 6}}) {:name "Seppo" :id 1 :tasks {:product.domain.task/id 6}})) (is (= (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.player/id 666 :product.domain.player/tasks {:product.domain.task/id 6}} {:except #{:product.domain.player/id}}) {:name "Seppo" :product.domain.player/id 666 :tasks {:product.domain.task/id 6}})) (is (= (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.player/id 666 :product.domain.player/task {:product.domain.task/id 6}} {:recur? true :except #{:product.domain.player/id}}) {:name "Seppo" :product.domain.player/id 666 :task {:id 6}})) (is (= (unnamespacefy {:stuff {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"}}) {:stuff {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"}}) "No conflicts occur since recur is not used")) (deftest unnamespacefy-coll-of-maps (is (= (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.player/id 1 :product.domain.player/tasks [{:product.domain.task/id 6} {:product.domain.task/id 7}]} {:recur? true}) {:name "Seppo" :id 1 :tasks [{:id 6} {:id 7}]})) (is (= (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.player/id 1 :product.domain.player/tasks '({:product.domain.task/id 6} {:product.domain.task/id 7})} {:recur? true}) {:name "Seppo" :id 1 :tasks '({:id 6} {:id 7})})) (is (= (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.player/id 1 :product.domain.player/tasks #{{:product.domain.task/id 6} {:product.domain.task/id 7}}} {:recur? true}) {:name "Seppo" :id 1 :tasks #{{:id 6} {:id 7}}})) (is (= (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.player/id 1 :product.domain.player/tasks (map #(-> {:product.domain.task/id %}) [6 7])} {:recur? true}) {:name "Seppo" :id 1 :tasks [{:id 6} {:id 7}]}))) (deftest unnamespacefy-coll-of-things ;; Coll of colls (is (= (unnamespacefy {:product.domain.player/tasks [[{:product.domain.task/id 6} {:product.domain.task/id 7}] (java.util.ArrayList. [{:product.domain.task/id 6} {:product.domain.task/id 7}])]} {:recur? true}) {:tasks [[{:id 6} {:id 7}] [{:id 6} {:id 7}]]})) ;; Coll of keywords should not do anything (is (= (unnamespacefy {:product.domain.player/tasks [:one :two :three]} {:recur? true}) {:tasks [:one :two :three]})) ;; Coll of nils (is (= (unnamespacefy {:product.domain.player/tasks [nil nil nil]} {:recur? true}) {:tasks [nil nil nil]})) ;; Coll of multiple types (let [object (new Object)] (is (= (unnamespacefy {:product.domain.player/tasks [nil object :omg]} {:recur? true}) {:tasks [nil object :omg]})))) (deftest unnamespacefy-keyword (is (= (unnamespacefy :product.domain.person/address) :address)) (is (= (unnamespacefy :address) :address))) (deftest unnamespacefy-resolving-conflicts (is (= (unnamespacefy {:product.domain.person/name "Seppo" :product.domain.task/name "Important task"} {:custom {:product.domain.person/name :person-name :product.domain.task/name :task-name}}) {:person-name "Seppo" :task-name "Important task"})) (is (= (unnamespacefy {:product.domain.person/name "Seppo" :name "foo"} {:custom {:product.domain.person/name :person-name}}) {:person-name "Seppo" :name "foo"})) (is (= (unnamespacefy {:product.domain.person/name "Seppo" :product.domain.task/name "Important task" :product.domain.person/score 666} {:custom {:product.domain.person/name :person-name :product.domain.task/name :task-name}}) {:person-name "Seppo" :task-name "Important task" :score 666})) (is (= (unnamespacefy {:product.domain.person/name "Seppo" :product.domain.task/name "Important task" :name "foo"} {:custom {:product.domain.person/name :person-name :product.domain.task/name :task-name}}) {:person-name "Seppo" :task-name "Important task" :name "foo"}))) (deftest unnamespacefy-nil (is (= (unnamespacefy {:product.domain.person/name "Seppo" :product.domain.person/address nil}) {:name "Seppo" :address nil})) (is (= (unnamespacefy {:product.domain.person/name "Seppo" :address nil}) {:name "Seppo" :address nil})) (is (nil? (unnamespacefy nil)))) (deftest unnamespacefy-bad-data (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"}))) (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :name "foo"}))) (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"} {:custom nil}))) (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.task/name "Important task" :product.domain.player/id 1 :product.domain.task/id 2} ;; Resolve :name conflict, but there is still :id {:custom {:product.domain.player/name :person-name :product.domain.task/name :task-name}}))) (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"} {:custom 123}))) (is (thrown? IllegalArgumentException (unnamespacefy {:stuff {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"}} {:recur? true}))) (is (thrown? IllegalArgumentException (unnamespacefy 123))) (is (thrown? IllegalArgumentException (unnamespacefy "hello"))) (is (thrown? IllegalArgumentException (unnamespacefy \a)))) ;; -- get-un (deftest get-un-works ;; Basic tests (is (= (get-un {:product.domain.player/name "Player"} :name) "Player")) (is (= (get-un {:product.domain.player/name "The Task"} :name) "The Task")) (is (= (get-un {:name "The Task"} :name) "The Task")) ;; Key is not present in the map -> nil (is (= (get-un {:name "The Task"} :id) nil)) (is (= (get-un {:product.domain.player/name "Player"} :id) nil)) (is (= (get-un {:name "The Task"} "name") nil)) (is (= (get-un {:name "The Task"} 1) nil)) ;; If the map is nil, should always return nil (is (= (get-un nil 1) nil)) (is (= (get-un nil "name") nil)) (is (= (get-un nil :name) nil))) (deftest get-un-works-correctly-with-bad-data ;; Unable to resolve the correct key (is (thrown? IllegalArgumentException (get-un {:product.domain.player/name "Player" :product.domain.task/name "The Task"} :name))) (is (thrown? IllegalArgumentException (get-un {:product.domain.player/name "Player" :product.domain.task/name "The Task"} 123))) ;; Map is not a map or the keys are not keywords (is (thrown? IllegalArgumentException (get-un 123 :name))) (is (thrown? IllegalArgumentException (get-un {"1" "hello"} :name))) (is (thrown? IllegalArgumentException (get-un {"1" "hello"} "1"))) (is (thrown? IllegalArgumentException (get-un {1 "hello"} :name))) (is (thrown? IllegalArgumentException (get-un {1 "hello"} 1))) (is (thrown? IllegalArgumentException (get-un 123 123)))) ;; -- assoc-un (deftest assoc-un-works ;; Basic tests (is (= (assoc-un {:product.domain.player/name "Player"} :name "Player Zero") {:product.domain.player/name "Player Zero"})) (is (= (assoc-un {:product.domain.task/name "The Task"} :name "The Task 123") {:product.domain.task/name "The Task 123"})) (is (= (assoc-un {:name "Player"} :name "Player Zero") {:name "Player Zero"})) ;; Map is nil or empty (is (= (assoc-un nil :name "Player Zero") nil)) (is (= (assoc-un nil 1 :a) nil)) (is (= (assoc-un {} 1 :a) {})) ;; Key is not present in the map (is (= (assoc-un {:foo :bar} :name "Seppo") {:foo :bar})) (is (= (assoc-un {:foo :bar} nil "Seppo") {:foo :bar})) (is (= (assoc-un {:foo :bar} {} {}) {:foo :bar}))) (deftest assoc-un-works-correctly-with-bad-data ;; Unable to resolve the correct key (is (thrown? IllegalArgumentException (assoc-un {:product.domain.task/name "The Task" :product.domain.player/name "Seppo"} :name "Which one!?"))) ;; Map is not a map or the keys are not keywords (is (thrown? IllegalArgumentException (assoc-un 123 123 "Player Zero"))) (is (thrown? IllegalArgumentException (assoc-un [] 123 "Player Zero"))) (is (thrown? IllegalArgumentException (assoc-un {"name" "Player"} "name" "Player Zero"))) (is (thrown? IllegalArgumentException (assoc-un "Hello" 123 "Player Zero"))))
67440
(ns namespacefy.core-test (:require [clojure.test :refer :all] [namespacefy.core :refer [namespacefy unnamespacefy get-un assoc-un]])) ; Namespacefy (deftest namespacefy-keyword (is (= (namespacefy :address {:ns :product.domain}) :product.domain/address)) (is (= (namespacefy :foo {:ns :domain}) :domain/foo))) (deftest namespacefy-with-same-regular-keywords (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.person/name "Seppo" :product.domain.task/name "Useless task"})))) (deftest namespacefy-map (is (= (namespacefy {:name "<NAME>" :id 1} {:ns :product.domain.person}) {:product.domain.person/name "<NAME>" :product.domain.person/id 1}))) (deftest namespacefy-coll (is (= (namespacefy '({:name "<NAME>" :id 1}) {:ns :product.domain.person}) '({:product.domain.person/name "<NAME>" :product.domain.person/id 1})))) (deftest namespacefy-array-list (is (= (namespacefy (java.util.ArrayList. [{:name "<NAME>" :id 1}]) {:ns :product.domain.person})) '({:product.domain.person/name "<NAME>" :product.domain.person/id 1}))) (deftest namespacefy-lazy-sequence (is (= (namespacefy (map identity [{:name "<NAME>" :id 1}]) {:ns :product.domain.person}) [{:product.domain.person/name "<NAME>" :product.domain.person/id 1}]))) (deftest namespacefy-set (is (= (namespacefy #{{:name "<NAME>" :id 1}} {:ns :product.domain.person}) #{{:product.domain.person/name "<NAME>" :product.domain.person/id 1}}))) (deftest namespacefy-nested-map (is (= (namespacefy {:name "<NAME>" :id 1 :address {:address "Pihlajakatu 23" :city "Helsinki" :country "Finland"} :foo nil :modified nil} {:ns :product.domain.person :except #{:foo} :custom {:modified :our.ui/modified} :inner {:address {:ns :product.domain.address}}}) {:product.domain.person/name "<NAME>" :product.domain.person/id 1 :product.domain.person/address {:product.domain.address/address "Pihlajakatu 23" :product.domain.address/city "Helsinki" :product.domain.address/country "Finland"} :foo nil :our.ui/modified nil}))) (deftest namespacefy-deeply-nested-map (is (= (namespacefy {:name "<NAME>" :id 1 :address {:address "Pihlajakatu 23" :city "Helsinki" :country "Finland" :gps-location {:x 0 :y 0}}} {:ns :product.domain.person :inner {:address {:ns :product.domain.address :inner {:gps-location {:ns :product.domain.gps}}}}}) {:product.domain.person/name "<NAME>" :product.domain.person/id 1 :product.domain.person/address {:product.domain.address/address "Pihlajakatu 23" :product.domain.address/city "Helsinki" :product.domain.address/country "Finland" :product.domain.address/gps-location {:product.domain.gps/x 0 :product.domain.gps/y 0}}})) (is (= (namespacefy {:name "<NAME>" :id 1 :address {:address "Pihlajakatu 23" :city "Helsinki" :country "Finland" :gps-location {:x 0 :y 0}} :foo nil :modified nil} {:ns :product.domain.person :except #{:foo} :custom {:modified :our.ui/modified} :inner {:address {:ns :product.domain.address :inner {:gps-location {:ns :product.domain.gps}}}}}) {:product.domain.person/name "<NAME>" :product.domain.person/id 1 :product.domain.person/address {:product.domain.address/address "Pihlajakatu 23" :product.domain.address/city "Helsinki" :product.domain.address/country "Finland" :product.domain.address/gps-location {:product.domain.gps/x 0 :product.domain.gps/y 0}} :foo nil :our.ui/modified nil}))) (deftest namespacefy-coll-of-maps (is (= (namespacefy {:name "<NAME>" :id 1 :tasks [{:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"}]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/name "<NAME>" :product.domain.person/id 1 :product.domain.person/tasks [{:product.domain.task/id 6 :product.domain.task/description "Do something useful"} {:product.domain.task/id 7 :product.domain.task/description "Do something useless"}]})) (is (= (namespacefy {:tasks '({:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"})} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks '({:product.domain.task/id 6 :product.domain.task/description "Do something useful"} {:product.domain.task/id 7 :product.domain.task/description "Do something useless"})})) (is (= (namespacefy {:tasks (map #(-> {:id %}) [1 2 3])} ;; Test lazy sequence {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [{:product.domain.task/id 1} {:product.domain.task/id 2} {:product.domain.task/id 3}]})) (is (= (namespacefy {:tasks #{{:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"}}} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks #{{:product.domain.task/description "Do something useful" :product.domain.task/id 6} {:product.domain.task/description "Do something useless" :product.domain.task/id 7}}}))) (deftest namespacefy-coll-things ;; Coll of colls (is (= (namespacefy {:tasks [[{:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"}] (java.util.ArrayList. [{:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"}])]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [[{:product.domain.task/id 6 :product.domain.task/description "Do something useful"} {:product.domain.task/id 7 :product.domain.task/description "Do something useless"}] [{:product.domain.task/id 6 :product.domain.task/description "Do something useful"} {:product.domain.task/id 7 :product.domain.task/description "Do something useless"}]]})) ;; Coll of keywords should not do anything (is (= (namespacefy {:tasks [:one :two :three]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [:one :two :three]})) ;; Coll of nils should not do anything (is (= (namespacefy {:tasks [nil nil nil]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [nil nil nil]})) ;; Coll of multiple types (let [object (new Object)] (is (= (namespacefy {:tasks [nil :keyword object]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [nil :keyword object]})))) (deftest namespacefy-nil (is (nil? (namespacefy nil {:ns :product.domain.person}))) ;; Inner value is nil (is (= (namespacefy {:name "<NAME>" :address nil} {:ns :product.domain.person :inner {:address {:ns :product.domain.address}}}) {:product.domain.person/name "<NAME>" :product.domain.person/address nil}))) (deftest namespacefy-empty (is (= (namespacefy {} {:ns :product.domain.person}) {}))) (deftest namespacefy-bad-data (is (thrown? IllegalArgumentException (namespacefy \k {:ns :product.domain.person}))) (is (thrown? IllegalArgumentException (namespacefy 123 {:ns :product.domain.person}))) (is (thrown? IllegalArgumentException (namespacefy {:name "<NAME>"} {})))) ; Unnamespacefy (deftest unnamespacefy-simple-map (is (= (unnamespacefy {:product.domain.person/name "<NAME>" :product.domain.person/id 1}) {:name "<NAME>" :id 1})) (is (= (unnamespacefy {:name "<NAME>" :id 1}) {:name "<NAME>" :id 1})) (is (= (unnamespacefy {:product.domain.person/name "<NAME>" :id 1}) {:name "<NAME>" :id 1}))) (deftest unnamespacefy-coll (is (= (unnamespacefy '({:product.domain.person/name "<NAME>" :product.domain.person/id 1})) '({:name "<NAME>" :id 1})))) (deftest unnamespacefy-array-list (is (= (unnamespacefy (java.util.ArrayList. '[{:product.domain.person/name "<NAME>" :product.domain.person/id 1}])) '({:name "<NAME>" :id 1})))) (deftest unnamespacefy-set (is (= (unnamespacefy #{{:product.domain.person/name "<NAME>" :product.domain.person/id 1}}) #{{:name "<NAME>" :id 1}}))) (deftest unnamespacefy-lazy-sequence (is (= (unnamespacefy (map identity [{:product.domain.person/name "<NAME>" :product.domain.person/id 1}])) [{:name "<NAME>" :id 1}]))) (deftest unnamespacefy-nested-map (is (= (unnamespacefy {:product.domain.player/name "<NAME>" :product.domain.player/id 1 :product.domain.player/tasks {:product.domain.task/id 6}}) {:name "<NAME>" :id 1 :tasks {:product.domain.task/id 6}})) (is (= (unnamespacefy {:product.domain.player/name "<NAME>" :product.domain.player/id 666 :product.domain.player/tasks {:product.domain.task/id 6}} {:except #{:product.domain.player/id}}) {:name "<NAME>" :product.domain.player/id 666 :tasks {:product.domain.task/id 6}})) (is (= (unnamespacefy {:product.domain.player/name "<NAME>" :product.domain.player/id 666 :product.domain.player/task {:product.domain.task/id 6}} {:recur? true :except #{:product.domain.player/id}}) {:name "<NAME>" :product.domain.player/id 666 :task {:id 6}})) (is (= (unnamespacefy {:stuff {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"}}) {:stuff {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"}}) "No conflicts occur since recur is not used")) (deftest unnamespacefy-coll-of-maps (is (= (unnamespacefy {:product.domain.player/name "<NAME>" :product.domain.player/id 1 :product.domain.player/tasks [{:product.domain.task/id 6} {:product.domain.task/id 7}]} {:recur? true}) {:name "<NAME>" :id 1 :tasks [{:id 6} {:id 7}]})) (is (= (unnamespacefy {:product.domain.player/name "<NAME>o" :product.domain.player/id 1 :product.domain.player/tasks '({:product.domain.task/id 6} {:product.domain.task/id 7})} {:recur? true}) {:name "<NAME>" :id 1 :tasks '({:id 6} {:id 7})})) (is (= (unnamespacefy {:product.domain.player/name "<NAME>" :product.domain.player/id 1 :product.domain.player/tasks #{{:product.domain.task/id 6} {:product.domain.task/id 7}}} {:recur? true}) {:name "<NAME>" :id 1 :tasks #{{:id 6} {:id 7}}})) (is (= (unnamespacefy {:product.domain.player/name "<NAME>" :product.domain.player/id 1 :product.domain.player/tasks (map #(-> {:product.domain.task/id %}) [6 7])} {:recur? true}) {:name "<NAME>" :id 1 :tasks [{:id 6} {:id 7}]}))) (deftest unnamespacefy-coll-of-things ;; Coll of colls (is (= (unnamespacefy {:product.domain.player/tasks [[{:product.domain.task/id 6} {:product.domain.task/id 7}] (java.util.ArrayList. [{:product.domain.task/id 6} {:product.domain.task/id 7}])]} {:recur? true}) {:tasks [[{:id 6} {:id 7}] [{:id 6} {:id 7}]]})) ;; Coll of keywords should not do anything (is (= (unnamespacefy {:product.domain.player/tasks [:one :two :three]} {:recur? true}) {:tasks [:one :two :three]})) ;; Coll of nils (is (= (unnamespacefy {:product.domain.player/tasks [nil nil nil]} {:recur? true}) {:tasks [nil nil nil]})) ;; Coll of multiple types (let [object (new Object)] (is (= (unnamespacefy {:product.domain.player/tasks [nil object :omg]} {:recur? true}) {:tasks [nil object :omg]})))) (deftest unnamespacefy-keyword (is (= (unnamespacefy :product.domain.person/address) :address)) (is (= (unnamespacefy :address) :address))) (deftest unnamespacefy-resolving-conflicts (is (= (unnamespacefy {:product.domain.person/name "<NAME>" :product.domain.task/name "Important task"} {:custom {:product.domain.person/name :person-name :product.domain.task/name :task-name}}) {:person-name "<NAME>" :task-name "Important task"})) (is (= (unnamespacefy {:product.domain.person/name "<NAME>" :name "foo"} {:custom {:product.domain.person/name :person-name}}) {:person-name "<NAME>" :name "<NAME>"})) (is (= (unnamespacefy {:product.domain.person/name "<NAME>" :product.domain.task/name "Important task" :product.domain.person/score 666} {:custom {:product.domain.person/name :person-name :product.domain.task/name :task-name}}) {:person-name "<NAME>" :task-name "Important task" :score 666})) (is (= (unnamespacefy {:product.domain.person/name "Seppo" :product.domain.task/name "Important task" :name "foo"} {:custom {:product.domain.person/name :person-name :product.domain.task/name :task-name}}) {:person-name "<NAME>" :task-name "Important task" :name "foo"}))) (deftest unnamespacefy-nil (is (= (unnamespacefy {:product.domain.person/name "<NAME>" :product.domain.person/address nil}) {:name "<NAME>" :address nil})) (is (= (unnamespacefy {:product.domain.person/name "Seppo" :address nil}) {:name "<NAME>" :address nil})) (is (nil? (unnamespacefy nil)))) (deftest unnamespacefy-bad-data (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"}))) (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :name "foo"}))) (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"} {:custom nil}))) (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.task/name "Important task" :product.domain.player/id 1 :product.domain.task/id 2} ;; Resolve :name conflict, but there is still :id {:custom {:product.domain.player/name :person-name :product.domain.task/name :task-name}}))) (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"} {:custom 123}))) (is (thrown? IllegalArgumentException (unnamespacefy {:stuff {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"}} {:recur? true}))) (is (thrown? IllegalArgumentException (unnamespacefy 123))) (is (thrown? IllegalArgumentException (unnamespacefy "hello"))) (is (thrown? IllegalArgumentException (unnamespacefy \a)))) ;; -- get-un (deftest get-un-works ;; Basic tests (is (= (get-un {:product.domain.player/name "Player"} :name) "Player")) (is (= (get-un {:product.domain.player/name "The Task"} :name) "The Task")) (is (= (get-un {:name "The Task"} :name) "The Task")) ;; Key is not present in the map -> nil (is (= (get-un {:name "The Task"} :id) nil)) (is (= (get-un {:product.domain.player/name "Player"} :id) nil)) (is (= (get-un {:name "The Task"} "name") nil)) (is (= (get-un {:name "The Task"} 1) nil)) ;; If the map is nil, should always return nil (is (= (get-un nil 1) nil)) (is (= (get-un nil "name") nil)) (is (= (get-un nil :name) nil))) (deftest get-un-works-correctly-with-bad-data ;; Unable to resolve the correct key (is (thrown? IllegalArgumentException (get-un {:product.domain.player/name "Player" :product.domain.task/name "The Task"} :name))) (is (thrown? IllegalArgumentException (get-un {:product.domain.player/name "Player" :product.domain.task/name "The Task"} 123))) ;; Map is not a map or the keys are not keywords (is (thrown? IllegalArgumentException (get-un 123 :name))) (is (thrown? IllegalArgumentException (get-un {"1" "hello"} :name))) (is (thrown? IllegalArgumentException (get-un {"1" "hello"} "1"))) (is (thrown? IllegalArgumentException (get-un {1 "hello"} :name))) (is (thrown? IllegalArgumentException (get-un {1 "hello"} 1))) (is (thrown? IllegalArgumentException (get-un 123 123)))) ;; -- assoc-un (deftest assoc-un-works ;; Basic tests (is (= (assoc-un {:product.domain.player/name "Player"} :name "Player Zero") {:product.domain.player/name "Player Zero"})) (is (= (assoc-un {:product.domain.task/name "The Task"} :name "The Task 123") {:product.domain.task/name "The Task 123"})) (is (= (assoc-un {:name "Player"} :name "Player Zero") {:name "Player Zero"})) ;; Map is nil or empty (is (= (assoc-un nil :name "Player Zero") nil)) (is (= (assoc-un nil 1 :a) nil)) (is (= (assoc-un {} 1 :a) {})) ;; Key is not present in the map (is (= (assoc-un {:foo :bar} :name "Seppo") {:foo :bar})) (is (= (assoc-un {:foo :bar} nil "Seppo") {:foo :bar})) (is (= (assoc-un {:foo :bar} {} {}) {:foo :bar}))) (deftest assoc-un-works-correctly-with-bad-data ;; Unable to resolve the correct key (is (thrown? IllegalArgumentException (assoc-un {:product.domain.task/name "The Task" :product.domain.player/name "Seppo"} :name "Which one!?"))) ;; Map is not a map or the keys are not keywords (is (thrown? IllegalArgumentException (assoc-un 123 123 "Player Zero"))) (is (thrown? IllegalArgumentException (assoc-un [] 123 "Player Zero"))) (is (thrown? IllegalArgumentException (assoc-un {"name" "Player"} "name" "Player Zero"))) (is (thrown? IllegalArgumentException (assoc-un "Hello" 123 "Player Zero"))))
true
(ns namespacefy.core-test (:require [clojure.test :refer :all] [namespacefy.core :refer [namespacefy unnamespacefy get-un assoc-un]])) ; Namespacefy (deftest namespacefy-keyword (is (= (namespacefy :address {:ns :product.domain}) :product.domain/address)) (is (= (namespacefy :foo {:ns :domain}) :domain/foo))) (deftest namespacefy-with-same-regular-keywords (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.person/name "Seppo" :product.domain.task/name "Useless task"})))) (deftest namespacefy-map (is (= (namespacefy {:name "PI:NAME:<NAME>END_PI" :id 1} {:ns :product.domain.person}) {:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/id 1}))) (deftest namespacefy-coll (is (= (namespacefy '({:name "PI:NAME:<NAME>END_PI" :id 1}) {:ns :product.domain.person}) '({:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/id 1})))) (deftest namespacefy-array-list (is (= (namespacefy (java.util.ArrayList. [{:name "PI:NAME:<NAME>END_PI" :id 1}]) {:ns :product.domain.person})) '({:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/id 1}))) (deftest namespacefy-lazy-sequence (is (= (namespacefy (map identity [{:name "PI:NAME:<NAME>END_PI" :id 1}]) {:ns :product.domain.person}) [{:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/id 1}]))) (deftest namespacefy-set (is (= (namespacefy #{{:name "PI:NAME:<NAME>END_PI" :id 1}} {:ns :product.domain.person}) #{{:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/id 1}}))) (deftest namespacefy-nested-map (is (= (namespacefy {:name "PI:NAME:<NAME>END_PI" :id 1 :address {:address "Pihlajakatu 23" :city "Helsinki" :country "Finland"} :foo nil :modified nil} {:ns :product.domain.person :except #{:foo} :custom {:modified :our.ui/modified} :inner {:address {:ns :product.domain.address}}}) {:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/id 1 :product.domain.person/address {:product.domain.address/address "Pihlajakatu 23" :product.domain.address/city "Helsinki" :product.domain.address/country "Finland"} :foo nil :our.ui/modified nil}))) (deftest namespacefy-deeply-nested-map (is (= (namespacefy {:name "PI:NAME:<NAME>END_PI" :id 1 :address {:address "Pihlajakatu 23" :city "Helsinki" :country "Finland" :gps-location {:x 0 :y 0}}} {:ns :product.domain.person :inner {:address {:ns :product.domain.address :inner {:gps-location {:ns :product.domain.gps}}}}}) {:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/id 1 :product.domain.person/address {:product.domain.address/address "Pihlajakatu 23" :product.domain.address/city "Helsinki" :product.domain.address/country "Finland" :product.domain.address/gps-location {:product.domain.gps/x 0 :product.domain.gps/y 0}}})) (is (= (namespacefy {:name "PI:NAME:<NAME>END_PI" :id 1 :address {:address "Pihlajakatu 23" :city "Helsinki" :country "Finland" :gps-location {:x 0 :y 0}} :foo nil :modified nil} {:ns :product.domain.person :except #{:foo} :custom {:modified :our.ui/modified} :inner {:address {:ns :product.domain.address :inner {:gps-location {:ns :product.domain.gps}}}}}) {:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/id 1 :product.domain.person/address {:product.domain.address/address "Pihlajakatu 23" :product.domain.address/city "Helsinki" :product.domain.address/country "Finland" :product.domain.address/gps-location {:product.domain.gps/x 0 :product.domain.gps/y 0}} :foo nil :our.ui/modified nil}))) (deftest namespacefy-coll-of-maps (is (= (namespacefy {:name "PI:NAME:<NAME>END_PI" :id 1 :tasks [{:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"}]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/id 1 :product.domain.person/tasks [{:product.domain.task/id 6 :product.domain.task/description "Do something useful"} {:product.domain.task/id 7 :product.domain.task/description "Do something useless"}]})) (is (= (namespacefy {:tasks '({:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"})} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks '({:product.domain.task/id 6 :product.domain.task/description "Do something useful"} {:product.domain.task/id 7 :product.domain.task/description "Do something useless"})})) (is (= (namespacefy {:tasks (map #(-> {:id %}) [1 2 3])} ;; Test lazy sequence {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [{:product.domain.task/id 1} {:product.domain.task/id 2} {:product.domain.task/id 3}]})) (is (= (namespacefy {:tasks #{{:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"}}} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks #{{:product.domain.task/description "Do something useful" :product.domain.task/id 6} {:product.domain.task/description "Do something useless" :product.domain.task/id 7}}}))) (deftest namespacefy-coll-things ;; Coll of colls (is (= (namespacefy {:tasks [[{:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"}] (java.util.ArrayList. [{:id 6 :description "Do something useful"} {:id 7 :description "Do something useless"}])]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [[{:product.domain.task/id 6 :product.domain.task/description "Do something useful"} {:product.domain.task/id 7 :product.domain.task/description "Do something useless"}] [{:product.domain.task/id 6 :product.domain.task/description "Do something useful"} {:product.domain.task/id 7 :product.domain.task/description "Do something useless"}]]})) ;; Coll of keywords should not do anything (is (= (namespacefy {:tasks [:one :two :three]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [:one :two :three]})) ;; Coll of nils should not do anything (is (= (namespacefy {:tasks [nil nil nil]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [nil nil nil]})) ;; Coll of multiple types (let [object (new Object)] (is (= (namespacefy {:tasks [nil :keyword object]} {:ns :product.domain.person :inner {:tasks {:ns :product.domain.task}}}) {:product.domain.person/tasks [nil :keyword object]})))) (deftest namespacefy-nil (is (nil? (namespacefy nil {:ns :product.domain.person}))) ;; Inner value is nil (is (= (namespacefy {:name "PI:NAME:<NAME>END_PI" :address nil} {:ns :product.domain.person :inner {:address {:ns :product.domain.address}}}) {:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/address nil}))) (deftest namespacefy-empty (is (= (namespacefy {} {:ns :product.domain.person}) {}))) (deftest namespacefy-bad-data (is (thrown? IllegalArgumentException (namespacefy \k {:ns :product.domain.person}))) (is (thrown? IllegalArgumentException (namespacefy 123 {:ns :product.domain.person}))) (is (thrown? IllegalArgumentException (namespacefy {:name "PI:NAME:<NAME>END_PI"} {})))) ; Unnamespacefy (deftest unnamespacefy-simple-map (is (= (unnamespacefy {:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/id 1}) {:name "PI:NAME:<NAME>END_PI" :id 1})) (is (= (unnamespacefy {:name "PI:NAME:<NAME>END_PI" :id 1}) {:name "PI:NAME:<NAME>END_PI" :id 1})) (is (= (unnamespacefy {:product.domain.person/name "PI:NAME:<NAME>END_PI" :id 1}) {:name "PI:NAME:<NAME>END_PI" :id 1}))) (deftest unnamespacefy-coll (is (= (unnamespacefy '({:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/id 1})) '({:name "PI:NAME:<NAME>END_PI" :id 1})))) (deftest unnamespacefy-array-list (is (= (unnamespacefy (java.util.ArrayList. '[{:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/id 1}])) '({:name "PI:NAME:<NAME>END_PI" :id 1})))) (deftest unnamespacefy-set (is (= (unnamespacefy #{{:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/id 1}}) #{{:name "PI:NAME:<NAME>END_PI" :id 1}}))) (deftest unnamespacefy-lazy-sequence (is (= (unnamespacefy (map identity [{:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/id 1}])) [{:name "PI:NAME:<NAME>END_PI" :id 1}]))) (deftest unnamespacefy-nested-map (is (= (unnamespacefy {:product.domain.player/name "PI:NAME:<NAME>END_PI" :product.domain.player/id 1 :product.domain.player/tasks {:product.domain.task/id 6}}) {:name "PI:NAME:<NAME>END_PI" :id 1 :tasks {:product.domain.task/id 6}})) (is (= (unnamespacefy {:product.domain.player/name "PI:NAME:<NAME>END_PI" :product.domain.player/id 666 :product.domain.player/tasks {:product.domain.task/id 6}} {:except #{:product.domain.player/id}}) {:name "PI:NAME:<NAME>END_PI" :product.domain.player/id 666 :tasks {:product.domain.task/id 6}})) (is (= (unnamespacefy {:product.domain.player/name "PI:NAME:<NAME>END_PI" :product.domain.player/id 666 :product.domain.player/task {:product.domain.task/id 6}} {:recur? true :except #{:product.domain.player/id}}) {:name "PI:NAME:<NAME>END_PI" :product.domain.player/id 666 :task {:id 6}})) (is (= (unnamespacefy {:stuff {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"}}) {:stuff {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"}}) "No conflicts occur since recur is not used")) (deftest unnamespacefy-coll-of-maps (is (= (unnamespacefy {:product.domain.player/name "PI:NAME:<NAME>END_PI" :product.domain.player/id 1 :product.domain.player/tasks [{:product.domain.task/id 6} {:product.domain.task/id 7}]} {:recur? true}) {:name "PI:NAME:<NAME>END_PI" :id 1 :tasks [{:id 6} {:id 7}]})) (is (= (unnamespacefy {:product.domain.player/name "PI:NAME:<NAME>END_PIo" :product.domain.player/id 1 :product.domain.player/tasks '({:product.domain.task/id 6} {:product.domain.task/id 7})} {:recur? true}) {:name "PI:NAME:<NAME>END_PI" :id 1 :tasks '({:id 6} {:id 7})})) (is (= (unnamespacefy {:product.domain.player/name "PI:NAME:<NAME>END_PI" :product.domain.player/id 1 :product.domain.player/tasks #{{:product.domain.task/id 6} {:product.domain.task/id 7}}} {:recur? true}) {:name "PI:NAME:<NAME>END_PI" :id 1 :tasks #{{:id 6} {:id 7}}})) (is (= (unnamespacefy {:product.domain.player/name "PI:NAME:<NAME>END_PI" :product.domain.player/id 1 :product.domain.player/tasks (map #(-> {:product.domain.task/id %}) [6 7])} {:recur? true}) {:name "PI:NAME:<NAME>END_PI" :id 1 :tasks [{:id 6} {:id 7}]}))) (deftest unnamespacefy-coll-of-things ;; Coll of colls (is (= (unnamespacefy {:product.domain.player/tasks [[{:product.domain.task/id 6} {:product.domain.task/id 7}] (java.util.ArrayList. [{:product.domain.task/id 6} {:product.domain.task/id 7}])]} {:recur? true}) {:tasks [[{:id 6} {:id 7}] [{:id 6} {:id 7}]]})) ;; Coll of keywords should not do anything (is (= (unnamespacefy {:product.domain.player/tasks [:one :two :three]} {:recur? true}) {:tasks [:one :two :three]})) ;; Coll of nils (is (= (unnamespacefy {:product.domain.player/tasks [nil nil nil]} {:recur? true}) {:tasks [nil nil nil]})) ;; Coll of multiple types (let [object (new Object)] (is (= (unnamespacefy {:product.domain.player/tasks [nil object :omg]} {:recur? true}) {:tasks [nil object :omg]})))) (deftest unnamespacefy-keyword (is (= (unnamespacefy :product.domain.person/address) :address)) (is (= (unnamespacefy :address) :address))) (deftest unnamespacefy-resolving-conflicts (is (= (unnamespacefy {:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.task/name "Important task"} {:custom {:product.domain.person/name :person-name :product.domain.task/name :task-name}}) {:person-name "PI:NAME:<NAME>END_PI" :task-name "Important task"})) (is (= (unnamespacefy {:product.domain.person/name "PI:NAME:<NAME>END_PI" :name "foo"} {:custom {:product.domain.person/name :person-name}}) {:person-name "PI:NAME:<NAME>END_PI" :name "PI:NAME:<NAME>END_PI"})) (is (= (unnamespacefy {:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.task/name "Important task" :product.domain.person/score 666} {:custom {:product.domain.person/name :person-name :product.domain.task/name :task-name}}) {:person-name "PI:NAME:<NAME>END_PI" :task-name "Important task" :score 666})) (is (= (unnamespacefy {:product.domain.person/name "Seppo" :product.domain.task/name "Important task" :name "foo"} {:custom {:product.domain.person/name :person-name :product.domain.task/name :task-name}}) {:person-name "PI:NAME:<NAME>END_PI" :task-name "Important task" :name "foo"}))) (deftest unnamespacefy-nil (is (= (unnamespacefy {:product.domain.person/name "PI:NAME:<NAME>END_PI" :product.domain.person/address nil}) {:name "PI:NAME:<NAME>END_PI" :address nil})) (is (= (unnamespacefy {:product.domain.person/name "Seppo" :address nil}) {:name "PI:NAME:<NAME>END_PI" :address nil})) (is (nil? (unnamespacefy nil)))) (deftest unnamespacefy-bad-data (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"}))) (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :name "foo"}))) (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"} {:custom nil}))) (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.task/name "Important task" :product.domain.player/id 1 :product.domain.task/id 2} ;; Resolve :name conflict, but there is still :id {:custom {:product.domain.player/name :person-name :product.domain.task/name :task-name}}))) (is (thrown? IllegalArgumentException (unnamespacefy {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"} {:custom 123}))) (is (thrown? IllegalArgumentException (unnamespacefy {:stuff {:product.domain.player/name "Seppo" :product.domain.task/name "Important task"}} {:recur? true}))) (is (thrown? IllegalArgumentException (unnamespacefy 123))) (is (thrown? IllegalArgumentException (unnamespacefy "hello"))) (is (thrown? IllegalArgumentException (unnamespacefy \a)))) ;; -- get-un (deftest get-un-works ;; Basic tests (is (= (get-un {:product.domain.player/name "Player"} :name) "Player")) (is (= (get-un {:product.domain.player/name "The Task"} :name) "The Task")) (is (= (get-un {:name "The Task"} :name) "The Task")) ;; Key is not present in the map -> nil (is (= (get-un {:name "The Task"} :id) nil)) (is (= (get-un {:product.domain.player/name "Player"} :id) nil)) (is (= (get-un {:name "The Task"} "name") nil)) (is (= (get-un {:name "The Task"} 1) nil)) ;; If the map is nil, should always return nil (is (= (get-un nil 1) nil)) (is (= (get-un nil "name") nil)) (is (= (get-un nil :name) nil))) (deftest get-un-works-correctly-with-bad-data ;; Unable to resolve the correct key (is (thrown? IllegalArgumentException (get-un {:product.domain.player/name "Player" :product.domain.task/name "The Task"} :name))) (is (thrown? IllegalArgumentException (get-un {:product.domain.player/name "Player" :product.domain.task/name "The Task"} 123))) ;; Map is not a map or the keys are not keywords (is (thrown? IllegalArgumentException (get-un 123 :name))) (is (thrown? IllegalArgumentException (get-un {"1" "hello"} :name))) (is (thrown? IllegalArgumentException (get-un {"1" "hello"} "1"))) (is (thrown? IllegalArgumentException (get-un {1 "hello"} :name))) (is (thrown? IllegalArgumentException (get-un {1 "hello"} 1))) (is (thrown? IllegalArgumentException (get-un 123 123)))) ;; -- assoc-un (deftest assoc-un-works ;; Basic tests (is (= (assoc-un {:product.domain.player/name "Player"} :name "Player Zero") {:product.domain.player/name "Player Zero"})) (is (= (assoc-un {:product.domain.task/name "The Task"} :name "The Task 123") {:product.domain.task/name "The Task 123"})) (is (= (assoc-un {:name "Player"} :name "Player Zero") {:name "Player Zero"})) ;; Map is nil or empty (is (= (assoc-un nil :name "Player Zero") nil)) (is (= (assoc-un nil 1 :a) nil)) (is (= (assoc-un {} 1 :a) {})) ;; Key is not present in the map (is (= (assoc-un {:foo :bar} :name "Seppo") {:foo :bar})) (is (= (assoc-un {:foo :bar} nil "Seppo") {:foo :bar})) (is (= (assoc-un {:foo :bar} {} {}) {:foo :bar}))) (deftest assoc-un-works-correctly-with-bad-data ;; Unable to resolve the correct key (is (thrown? IllegalArgumentException (assoc-un {:product.domain.task/name "The Task" :product.domain.player/name "Seppo"} :name "Which one!?"))) ;; Map is not a map or the keys are not keywords (is (thrown? IllegalArgumentException (assoc-un 123 123 "Player Zero"))) (is (thrown? IllegalArgumentException (assoc-un [] 123 "Player Zero"))) (is (thrown? IllegalArgumentException (assoc-un {"name" "Player"} "name" "Player Zero"))) (is (thrown? IllegalArgumentException (assoc-un "Hello" 123 "Player Zero"))))
[ { "context": "name card))))\n\n;; <languagelist>\n;; <card name=\"Goblin Arsonist\">\n;; <set code=\"APC\">\n;; <name></name>\n", "end": 2318, "score": 0.9998757839202881, "start": 2303, "tag": "NAME", "value": "Goblin Arsonist" } ]
src/loa/format/language_xml.clj
karmag/loa
4
(ns loa.format.language-xml (:use (loa.util (xml :only (tag tag-attr))))) (defn- language->xml [set-name lang-data] (tag-attr :set {:name set-name} (when (:name lang-data) (tag :name (:name lang-data))) (when (:typelist lang-data) (tag :type (:typelist lang-data))) (when-not (empty? (:rulelist lang-data)) (apply tag :rulelist (map #(tag :rule %) (:rulelist lang-data)))) (when (:flavor lang-data) (tag :flavor (:flavor lang-data))) (when (:multi lang-data) (let [lang-data (:multi lang-data)] (tag :multi (when (:name lang-data) (tag :name (:name lang-data))) (when (:typelist lang-data) (tag :type (:typelist lang-data))) (when-not (empty? (:rulelist lang-data)) (apply tag :rulelist (map #(tag :rule %) (:rulelist lang-data)))) (when (:flavor lang-data) (tag :flavor (:flavor lang-data)))))))) (defn- get-entries [card] (for [set-data (-> card :sets vals) :when (not-empty (:language set-data)) [lang lang-data] (:language set-data)] {:lang lang :set (:set-name set-data) :xml (language->xml (:set-name set-data) lang-data)})) (defn- sort-by-language [entry-coll] (reduce (fn [m {:keys [lang set xml]}] (if (get m lang) (update-in m [lang] conj xml) (assoc m lang [xml]))) nil (sort-by :set entry-coll))) (defn- refine-entries [card-name entry-map] (reduce (fn [m [lang xml-coll]] (assoc m lang (apply tag-attr :card {:name card-name} xml-coll))) nil entry-map)) (defn to-xml "Returns a map of language-name to xml-data. If no language data is available in the card nil is returned." [card] (->> card get-entries sort-by-language (refine-entries (:name card)))) ;; <languagelist> ;; <card name="Goblin Arsonist"> ;; <set code="APC"> ;; <name></name> ;; <type></type> ;; <rulelist> ;; <rule></rule> ;; ... ;; </rulelist> ;; <flavor></flavor> ;; <multi>...</multi> ;; </set> ;; ... ;; </card> ;; </languagelist>
110371
(ns loa.format.language-xml (:use (loa.util (xml :only (tag tag-attr))))) (defn- language->xml [set-name lang-data] (tag-attr :set {:name set-name} (when (:name lang-data) (tag :name (:name lang-data))) (when (:typelist lang-data) (tag :type (:typelist lang-data))) (when-not (empty? (:rulelist lang-data)) (apply tag :rulelist (map #(tag :rule %) (:rulelist lang-data)))) (when (:flavor lang-data) (tag :flavor (:flavor lang-data))) (when (:multi lang-data) (let [lang-data (:multi lang-data)] (tag :multi (when (:name lang-data) (tag :name (:name lang-data))) (when (:typelist lang-data) (tag :type (:typelist lang-data))) (when-not (empty? (:rulelist lang-data)) (apply tag :rulelist (map #(tag :rule %) (:rulelist lang-data)))) (when (:flavor lang-data) (tag :flavor (:flavor lang-data)))))))) (defn- get-entries [card] (for [set-data (-> card :sets vals) :when (not-empty (:language set-data)) [lang lang-data] (:language set-data)] {:lang lang :set (:set-name set-data) :xml (language->xml (:set-name set-data) lang-data)})) (defn- sort-by-language [entry-coll] (reduce (fn [m {:keys [lang set xml]}] (if (get m lang) (update-in m [lang] conj xml) (assoc m lang [xml]))) nil (sort-by :set entry-coll))) (defn- refine-entries [card-name entry-map] (reduce (fn [m [lang xml-coll]] (assoc m lang (apply tag-attr :card {:name card-name} xml-coll))) nil entry-map)) (defn to-xml "Returns a map of language-name to xml-data. If no language data is available in the card nil is returned." [card] (->> card get-entries sort-by-language (refine-entries (:name card)))) ;; <languagelist> ;; <card name="<NAME>"> ;; <set code="APC"> ;; <name></name> ;; <type></type> ;; <rulelist> ;; <rule></rule> ;; ... ;; </rulelist> ;; <flavor></flavor> ;; <multi>...</multi> ;; </set> ;; ... ;; </card> ;; </languagelist>
true
(ns loa.format.language-xml (:use (loa.util (xml :only (tag tag-attr))))) (defn- language->xml [set-name lang-data] (tag-attr :set {:name set-name} (when (:name lang-data) (tag :name (:name lang-data))) (when (:typelist lang-data) (tag :type (:typelist lang-data))) (when-not (empty? (:rulelist lang-data)) (apply tag :rulelist (map #(tag :rule %) (:rulelist lang-data)))) (when (:flavor lang-data) (tag :flavor (:flavor lang-data))) (when (:multi lang-data) (let [lang-data (:multi lang-data)] (tag :multi (when (:name lang-data) (tag :name (:name lang-data))) (when (:typelist lang-data) (tag :type (:typelist lang-data))) (when-not (empty? (:rulelist lang-data)) (apply tag :rulelist (map #(tag :rule %) (:rulelist lang-data)))) (when (:flavor lang-data) (tag :flavor (:flavor lang-data)))))))) (defn- get-entries [card] (for [set-data (-> card :sets vals) :when (not-empty (:language set-data)) [lang lang-data] (:language set-data)] {:lang lang :set (:set-name set-data) :xml (language->xml (:set-name set-data) lang-data)})) (defn- sort-by-language [entry-coll] (reduce (fn [m {:keys [lang set xml]}] (if (get m lang) (update-in m [lang] conj xml) (assoc m lang [xml]))) nil (sort-by :set entry-coll))) (defn- refine-entries [card-name entry-map] (reduce (fn [m [lang xml-coll]] (assoc m lang (apply tag-attr :card {:name card-name} xml-coll))) nil entry-map)) (defn to-xml "Returns a map of language-name to xml-data. If no language data is available in the card nil is returned." [card] (->> card get-entries sort-by-language (refine-entries (:name card)))) ;; <languagelist> ;; <card name="PI:NAME:<NAME>END_PI"> ;; <set code="APC"> ;; <name></name> ;; <type></type> ;; <rulelist> ;; <rule></rule> ;; ... ;; </rulelist> ;; <flavor></flavor> ;; <multi>...</multi> ;; </set> ;; ... ;; </card> ;; </languagelist>
[ { "context": ";\n;; },\n\n\n ;; [^{:type String, :default \"Jones\", :notify false, :read-only true, :attrsync true}", "end": 4910, "score": 0.9986749887466431, "start": 4905, "tag": "NAME", "value": "Jones" }, { "context": "r doc string here\"\n [^{:type String, :default \"Jones\", :notify false, :read-only true, :attrsync true}", "end": 5676, "score": 0.9932571649551392, "start": 5671, "tag": "NAME", "value": "Jones" }, { "context": " :js [\"foo.js\"]}\n [^{:type String, :default \"Jones\", :notify false, :read-only true, :attrsync true}", "end": 7430, "score": 0.9674054384231567, "start": 7425, "tag": "NAME", "value": "Jones" } ]
testx/miraj.clj
mobileink/-polymirage
17
(ns test.miraj (:require [miraj.core :refer :all] [miraj.html :as h :refer :all] [hiccup.page :refer [html5]] [clojure.tools.logging :as log :only [trace debug error info]] [clojure.pprint :as pp] [clojure.tools.reader :as reader] [clojure.tools.reader.edn :as edn] [clojure.tools.reader.reader-types :as readers] [cljs.core :as cljs] [cljs.analyzer :as ana] [cljs.compiler :as c] [cljs.closure :as cc] [cljs.env :as env]) (:import [java.io StringReader])) (println "loading test.miraj") (log/trace "trace loading test.miraje") (co-ns "dashboard" (:require [polymer.iron :as iron :refer [ajax flex-layout icons list pages selector]] ;; => link href="polymer/iron-list/iron-list.html", etc. [polymer.paper :as paper :refer [button drawer-panel icon-button item material menu scroll-header-panel spinner styles toolbar]] ;; the nasty html/js way - note the typo, namespace is ignored: ;; [dashboard.components :html "components/my-greeting/my-greeting.html"] ;; the cool clojure/clojurescript way: [dashboard.components :refer [my-list my-greeting]] [visionmedia.page :js "scripts/lib/page/page.js"] ;; [theme.iron-list :html "styles/lib/page/page.js"] )) (co-defn my-foo [] [:link {:rel "import" :href "polymer/polymer/polymer.html"}] [:link {:rel "import" :href "styles/shared/style-modules.html"}] [:dom-module#my-foo [:template [:style {:include "shared-styles"}] [:ul [:template {:is "dom-repeat" :items "{{items}}"} [:li [:span {:class "paper-font-body1"}"{{item}}"]]]]]]) ;; (log/trace (:name (meta (var my-foo))) (meta (var my-foo))) ;; (pp/pprint my-foo) (println (h/span {:class "paper-font-body1"}"{{item}}")) (println (h/span {:class "paper-font-body1"} "this is an " (h/i "important") " sentence.")) (println (h/li (h/span {:class "paper-font-body1"}"{{item}}"))) (println (h/ul {:foo 0 :bar 1} (h/li (h/span {:class "paper-font-body1"}"{{item}}")) (h/li (h/span {:class "paper-font-body2"}"{{item}}")) (h/li (h/span {:class "paper-font-body3"}"{{item}}")) )) (println (h/ul (h/template {:is "dom-repeat" :items "{{items}}"} (h/li (h/span {:class "paper-font-body1"}"{{item}}"))))) (println (h/dom-module {:id "my-foo"} (h/template (h/style {:include "shared-styles"}) (h/ul (h/template {:is "dom-repeat" :items "{{items}}"} (h/li (h/span {:class "paper-font-body1"}"{{item}}")) (h/li (h/span {:class "paper-font-body2"}"{{item}}")) (h/li (h/span {:class "paper-font-body3"}"{{item}}"))))))) (println (h/link {:rel "import" :href "polymer/polymer/polymer.html"}) (h/link {:rel "import" :href "styles/shared/style-modules.html"}) (h/dom-module {:id "my-foo"} (h/template (h/style {:include "shared-styles"}) (h/ul (h/template {:is "dom-repeat" :items "{{items}}"} (h/li (h/span {:class "paper-font-body1"}"{{item}}")) (h/li {:id "special"} (h/span {:class "paper-font-body2"}"{{item}}")) (h/li (h/span {:class "paper-font-body3"} (str "here's some " (h/i "important") " news!"))) (h/li (h/span {:class "paper-font-body1"}"{{item}}"))))))) (first (read1 "(for [item items] (h/li item))")) ;; (let [form (read1 "(for [item items] (h/li item))")] ;; "(if x true false)")] ;; (pp/pprint (ana/parse (first form) user-env form nil nil))) ;; (let [form (read1 "(for [item items] (h/li item))")] ;; "(if x true false)")] ;; (pp/pprint (ana/analyze user-env form))) (let [form (read1 "(if x true false)")] (pp/pprint (ana/parse (first form) user-env form nil nil))) (let [form (read1 "(foo 1)")] (pp/pprint (ana/analyze user-env form))) (cljs->js (if x true false)) (cljs->js (fn [a b] (+ a b))) (cljs->js (foo 1)) (cljs->js (_typeChanged [type] (this-as me ))) (cljs->js (defn _typeChanged [type] (this-as me ))) (let [form (read1 "(fn [a b] (+ a b))")] (with-out-str (c/emit (ana/analyze user-env form)))) (let [form (read1 "(foo 1)")] (pp/pprint (ana/analyze user-env form))) ;; from iron-meta: ;; _typeChanged: function(type) { ;; this._unregisterKey(this.key); ;; if (!metaDatas[type]) { ;; metaDatas[type] = {}; ;; } ;; this._metaData = metaDatas[type]; ;; if (!metaArrays[type]) { ;; metaArrays[type] = []; ;; } ;; this.list = metaArrays[type]; ;; this._registerKeyValue(this.key, this.value); ;; }, ;; [^{:type String, :default "Jones", :notify false, :read-only true, :attrsync true} ;; author ;; ^{:type Content, :default nil} ;; content] (println (dom-repeat [thing things] (h/li "thing") (h/li "thing")) ) (cljs->js (fn [])) (let [thing "items"] (println (h/li thing))) (let [li "items"] (str "foo " li " bar")) (ctor->template (my-list [author content] (h/dom-module ;; ID = ctor string, added automatically (h/template (h/style {:include "shared-styles"}) (h/ul (dom-repeat [item items] (h/li (h/span {:class "paper-font-body1"} item)) )))))) (co-type my-list "doc string here" (my-list ;; ctor -> dom-module "ctor doc string here" [^{:type String, :default "Jones", :notify false, :read-only true, :attrsync true} author ^{:type Content, :default nil} content] ;; FIXME: link, script, etc. is metadata! (h/link {:rel "import" :href "polymer/polymer/polymer.html"}) (h/link {:rel "import" :href "styles/shared/style-modules.html"}) (h/dom-module ;; ID = ctor string, added automatically (h/template (h/style {:include "shared-styles"}) (h/ul (h/template {:is "dom-repeat" :items "{{items}}"} (h/li (h/span {:class "paper-font-body1"}"{{item}}")) (h/li {:id "special"} (h/span {:class "paper-font-body2"}"{{item}}")) (h/li (h/span {:class "paper-font-body3"}"{{item}}")) ))))) MutationObservation ;; protocol based on MutationObserver http://www.w3.org/TR/dom/#mutationobserver (author (fn [e] ...)) ;; instead of "observed" attr on "author" prop descriptor Polymer.Gesture ;; gesture events protocol (down (fn [this e] ...)) (up (fn [this e] ...)) (tap (fn [this e] ...)) ;; registers handler fn as listener for tap on the my-list elt (tap (fn [#special e] ...)) ;; respond to tap event on elt with id "special" (track (fn [e] ...)) DOM.Events ;; protocol ;; behaviors are protocols Polymer.PaperButtonBehavior (active ...) (disabled ...) (toggle ...) (addOwnKeyBinding ...) (active ...) ) ;; alternative ctor defn: (ctor "my-list" "MyList value constructor" ;; instead of a bunch of [:link...] decls we use metadata: ^{:imports ["polymer/polymer/polymer.html" "styles/shared/style-modules.html"] ;; (h/style {:include "shared-styles"}) - goes inside template elt :css ["foo.css"] :js ["foo.js"]} [^{:type String, :default "Jones", :notify false, :read-only true, :attrsync true} author list-items ;; make arg to dom-repeat explicit ^{:type Content, :default nil} content] ;; no need for explicit dom-module, nor immediate template (h/ul (for [item list-items] ;; instead of <template is="dom-repeat"...> ;; TODO: make index explicit using std clojure (seq ;; FIXME: do we need this? (h/li (h/span {:class "paper-font-body1"} item)) (h/li :#special (h/span {:class "paper-font-body2"} item)) (h/li (h/span {:class "paper-font-body3"} item))) ))) ;; a ctor expr will emit a dom-module string. we want to be able to ;; use any and all of clojure for defining the ctor, while ;; metaprogramming the html/js/css. ;; For example, we might use (for [item items]...) to generate a ;; static list, using some data defined outside of the ctor defn. the ;; result will be a hardcoded ul containing some li elements. but we ;; also want to use ordinary clojure to express things like ;; dom-repeat. The trick here is to detect use of formal args. so if ;; list-items is listed as a formal arg to the ctor, and we detect ;; that it is used in a for clause, eg. (for [item list-items]...) we ;; know that the dom-repeat is indicated. as a double check, "item" ;; is also required in dom-repeat. ;; in short, we determine at compile time that some clojure ;; expressions should be interpreted as "co-expressions", and ;; translated into Polymer. iow we treat clojure as polysemous; its ;; expressions only ever have meaning "under an interpretation". that ;; interpretation is almost always the standard interpretation, but we ;; can use meta-programming to enable alternative interpretations. ;; dom-repeat example from ;; https://www.polymer-project.org/1.0/docs/devguide/templates.html#dom-repeat ;; <dom-module id="employee-list"> ;; <template> ;; <div> Employee list: </div> ;; <template is="dom-repeat" items="{{employees}}"> ;; <div># <span>{{index}}</span></div> ;; <div>First name: <span>{{item.first}}</span></div> ;; <div>Last name: <span>{{item.last}}</span></div> ;; </template> ;; </template>
103269
(ns test.miraj (:require [miraj.core :refer :all] [miraj.html :as h :refer :all] [hiccup.page :refer [html5]] [clojure.tools.logging :as log :only [trace debug error info]] [clojure.pprint :as pp] [clojure.tools.reader :as reader] [clojure.tools.reader.edn :as edn] [clojure.tools.reader.reader-types :as readers] [cljs.core :as cljs] [cljs.analyzer :as ana] [cljs.compiler :as c] [cljs.closure :as cc] [cljs.env :as env]) (:import [java.io StringReader])) (println "loading test.miraj") (log/trace "trace loading test.miraje") (co-ns "dashboard" (:require [polymer.iron :as iron :refer [ajax flex-layout icons list pages selector]] ;; => link href="polymer/iron-list/iron-list.html", etc. [polymer.paper :as paper :refer [button drawer-panel icon-button item material menu scroll-header-panel spinner styles toolbar]] ;; the nasty html/js way - note the typo, namespace is ignored: ;; [dashboard.components :html "components/my-greeting/my-greeting.html"] ;; the cool clojure/clojurescript way: [dashboard.components :refer [my-list my-greeting]] [visionmedia.page :js "scripts/lib/page/page.js"] ;; [theme.iron-list :html "styles/lib/page/page.js"] )) (co-defn my-foo [] [:link {:rel "import" :href "polymer/polymer/polymer.html"}] [:link {:rel "import" :href "styles/shared/style-modules.html"}] [:dom-module#my-foo [:template [:style {:include "shared-styles"}] [:ul [:template {:is "dom-repeat" :items "{{items}}"} [:li [:span {:class "paper-font-body1"}"{{item}}"]]]]]]) ;; (log/trace (:name (meta (var my-foo))) (meta (var my-foo))) ;; (pp/pprint my-foo) (println (h/span {:class "paper-font-body1"}"{{item}}")) (println (h/span {:class "paper-font-body1"} "this is an " (h/i "important") " sentence.")) (println (h/li (h/span {:class "paper-font-body1"}"{{item}}"))) (println (h/ul {:foo 0 :bar 1} (h/li (h/span {:class "paper-font-body1"}"{{item}}")) (h/li (h/span {:class "paper-font-body2"}"{{item}}")) (h/li (h/span {:class "paper-font-body3"}"{{item}}")) )) (println (h/ul (h/template {:is "dom-repeat" :items "{{items}}"} (h/li (h/span {:class "paper-font-body1"}"{{item}}"))))) (println (h/dom-module {:id "my-foo"} (h/template (h/style {:include "shared-styles"}) (h/ul (h/template {:is "dom-repeat" :items "{{items}}"} (h/li (h/span {:class "paper-font-body1"}"{{item}}")) (h/li (h/span {:class "paper-font-body2"}"{{item}}")) (h/li (h/span {:class "paper-font-body3"}"{{item}}"))))))) (println (h/link {:rel "import" :href "polymer/polymer/polymer.html"}) (h/link {:rel "import" :href "styles/shared/style-modules.html"}) (h/dom-module {:id "my-foo"} (h/template (h/style {:include "shared-styles"}) (h/ul (h/template {:is "dom-repeat" :items "{{items}}"} (h/li (h/span {:class "paper-font-body1"}"{{item}}")) (h/li {:id "special"} (h/span {:class "paper-font-body2"}"{{item}}")) (h/li (h/span {:class "paper-font-body3"} (str "here's some " (h/i "important") " news!"))) (h/li (h/span {:class "paper-font-body1"}"{{item}}"))))))) (first (read1 "(for [item items] (h/li item))")) ;; (let [form (read1 "(for [item items] (h/li item))")] ;; "(if x true false)")] ;; (pp/pprint (ana/parse (first form) user-env form nil nil))) ;; (let [form (read1 "(for [item items] (h/li item))")] ;; "(if x true false)")] ;; (pp/pprint (ana/analyze user-env form))) (let [form (read1 "(if x true false)")] (pp/pprint (ana/parse (first form) user-env form nil nil))) (let [form (read1 "(foo 1)")] (pp/pprint (ana/analyze user-env form))) (cljs->js (if x true false)) (cljs->js (fn [a b] (+ a b))) (cljs->js (foo 1)) (cljs->js (_typeChanged [type] (this-as me ))) (cljs->js (defn _typeChanged [type] (this-as me ))) (let [form (read1 "(fn [a b] (+ a b))")] (with-out-str (c/emit (ana/analyze user-env form)))) (let [form (read1 "(foo 1)")] (pp/pprint (ana/analyze user-env form))) ;; from iron-meta: ;; _typeChanged: function(type) { ;; this._unregisterKey(this.key); ;; if (!metaDatas[type]) { ;; metaDatas[type] = {}; ;; } ;; this._metaData = metaDatas[type]; ;; if (!metaArrays[type]) { ;; metaArrays[type] = []; ;; } ;; this.list = metaArrays[type]; ;; this._registerKeyValue(this.key, this.value); ;; }, ;; [^{:type String, :default "<NAME>", :notify false, :read-only true, :attrsync true} ;; author ;; ^{:type Content, :default nil} ;; content] (println (dom-repeat [thing things] (h/li "thing") (h/li "thing")) ) (cljs->js (fn [])) (let [thing "items"] (println (h/li thing))) (let [li "items"] (str "foo " li " bar")) (ctor->template (my-list [author content] (h/dom-module ;; ID = ctor string, added automatically (h/template (h/style {:include "shared-styles"}) (h/ul (dom-repeat [item items] (h/li (h/span {:class "paper-font-body1"} item)) )))))) (co-type my-list "doc string here" (my-list ;; ctor -> dom-module "ctor doc string here" [^{:type String, :default "<NAME>", :notify false, :read-only true, :attrsync true} author ^{:type Content, :default nil} content] ;; FIXME: link, script, etc. is metadata! (h/link {:rel "import" :href "polymer/polymer/polymer.html"}) (h/link {:rel "import" :href "styles/shared/style-modules.html"}) (h/dom-module ;; ID = ctor string, added automatically (h/template (h/style {:include "shared-styles"}) (h/ul (h/template {:is "dom-repeat" :items "{{items}}"} (h/li (h/span {:class "paper-font-body1"}"{{item}}")) (h/li {:id "special"} (h/span {:class "paper-font-body2"}"{{item}}")) (h/li (h/span {:class "paper-font-body3"}"{{item}}")) ))))) MutationObservation ;; protocol based on MutationObserver http://www.w3.org/TR/dom/#mutationobserver (author (fn [e] ...)) ;; instead of "observed" attr on "author" prop descriptor Polymer.Gesture ;; gesture events protocol (down (fn [this e] ...)) (up (fn [this e] ...)) (tap (fn [this e] ...)) ;; registers handler fn as listener for tap on the my-list elt (tap (fn [#special e] ...)) ;; respond to tap event on elt with id "special" (track (fn [e] ...)) DOM.Events ;; protocol ;; behaviors are protocols Polymer.PaperButtonBehavior (active ...) (disabled ...) (toggle ...) (addOwnKeyBinding ...) (active ...) ) ;; alternative ctor defn: (ctor "my-list" "MyList value constructor" ;; instead of a bunch of [:link...] decls we use metadata: ^{:imports ["polymer/polymer/polymer.html" "styles/shared/style-modules.html"] ;; (h/style {:include "shared-styles"}) - goes inside template elt :css ["foo.css"] :js ["foo.js"]} [^{:type String, :default "<NAME>", :notify false, :read-only true, :attrsync true} author list-items ;; make arg to dom-repeat explicit ^{:type Content, :default nil} content] ;; no need for explicit dom-module, nor immediate template (h/ul (for [item list-items] ;; instead of <template is="dom-repeat"...> ;; TODO: make index explicit using std clojure (seq ;; FIXME: do we need this? (h/li (h/span {:class "paper-font-body1"} item)) (h/li :#special (h/span {:class "paper-font-body2"} item)) (h/li (h/span {:class "paper-font-body3"} item))) ))) ;; a ctor expr will emit a dom-module string. we want to be able to ;; use any and all of clojure for defining the ctor, while ;; metaprogramming the html/js/css. ;; For example, we might use (for [item items]...) to generate a ;; static list, using some data defined outside of the ctor defn. the ;; result will be a hardcoded ul containing some li elements. but we ;; also want to use ordinary clojure to express things like ;; dom-repeat. The trick here is to detect use of formal args. so if ;; list-items is listed as a formal arg to the ctor, and we detect ;; that it is used in a for clause, eg. (for [item list-items]...) we ;; know that the dom-repeat is indicated. as a double check, "item" ;; is also required in dom-repeat. ;; in short, we determine at compile time that some clojure ;; expressions should be interpreted as "co-expressions", and ;; translated into Polymer. iow we treat clojure as polysemous; its ;; expressions only ever have meaning "under an interpretation". that ;; interpretation is almost always the standard interpretation, but we ;; can use meta-programming to enable alternative interpretations. ;; dom-repeat example from ;; https://www.polymer-project.org/1.0/docs/devguide/templates.html#dom-repeat ;; <dom-module id="employee-list"> ;; <template> ;; <div> Employee list: </div> ;; <template is="dom-repeat" items="{{employees}}"> ;; <div># <span>{{index}}</span></div> ;; <div>First name: <span>{{item.first}}</span></div> ;; <div>Last name: <span>{{item.last}}</span></div> ;; </template> ;; </template>
true
(ns test.miraj (:require [miraj.core :refer :all] [miraj.html :as h :refer :all] [hiccup.page :refer [html5]] [clojure.tools.logging :as log :only [trace debug error info]] [clojure.pprint :as pp] [clojure.tools.reader :as reader] [clojure.tools.reader.edn :as edn] [clojure.tools.reader.reader-types :as readers] [cljs.core :as cljs] [cljs.analyzer :as ana] [cljs.compiler :as c] [cljs.closure :as cc] [cljs.env :as env]) (:import [java.io StringReader])) (println "loading test.miraj") (log/trace "trace loading test.miraje") (co-ns "dashboard" (:require [polymer.iron :as iron :refer [ajax flex-layout icons list pages selector]] ;; => link href="polymer/iron-list/iron-list.html", etc. [polymer.paper :as paper :refer [button drawer-panel icon-button item material menu scroll-header-panel spinner styles toolbar]] ;; the nasty html/js way - note the typo, namespace is ignored: ;; [dashboard.components :html "components/my-greeting/my-greeting.html"] ;; the cool clojure/clojurescript way: [dashboard.components :refer [my-list my-greeting]] [visionmedia.page :js "scripts/lib/page/page.js"] ;; [theme.iron-list :html "styles/lib/page/page.js"] )) (co-defn my-foo [] [:link {:rel "import" :href "polymer/polymer/polymer.html"}] [:link {:rel "import" :href "styles/shared/style-modules.html"}] [:dom-module#my-foo [:template [:style {:include "shared-styles"}] [:ul [:template {:is "dom-repeat" :items "{{items}}"} [:li [:span {:class "paper-font-body1"}"{{item}}"]]]]]]) ;; (log/trace (:name (meta (var my-foo))) (meta (var my-foo))) ;; (pp/pprint my-foo) (println (h/span {:class "paper-font-body1"}"{{item}}")) (println (h/span {:class "paper-font-body1"} "this is an " (h/i "important") " sentence.")) (println (h/li (h/span {:class "paper-font-body1"}"{{item}}"))) (println (h/ul {:foo 0 :bar 1} (h/li (h/span {:class "paper-font-body1"}"{{item}}")) (h/li (h/span {:class "paper-font-body2"}"{{item}}")) (h/li (h/span {:class "paper-font-body3"}"{{item}}")) )) (println (h/ul (h/template {:is "dom-repeat" :items "{{items}}"} (h/li (h/span {:class "paper-font-body1"}"{{item}}"))))) (println (h/dom-module {:id "my-foo"} (h/template (h/style {:include "shared-styles"}) (h/ul (h/template {:is "dom-repeat" :items "{{items}}"} (h/li (h/span {:class "paper-font-body1"}"{{item}}")) (h/li (h/span {:class "paper-font-body2"}"{{item}}")) (h/li (h/span {:class "paper-font-body3"}"{{item}}"))))))) (println (h/link {:rel "import" :href "polymer/polymer/polymer.html"}) (h/link {:rel "import" :href "styles/shared/style-modules.html"}) (h/dom-module {:id "my-foo"} (h/template (h/style {:include "shared-styles"}) (h/ul (h/template {:is "dom-repeat" :items "{{items}}"} (h/li (h/span {:class "paper-font-body1"}"{{item}}")) (h/li {:id "special"} (h/span {:class "paper-font-body2"}"{{item}}")) (h/li (h/span {:class "paper-font-body3"} (str "here's some " (h/i "important") " news!"))) (h/li (h/span {:class "paper-font-body1"}"{{item}}"))))))) (first (read1 "(for [item items] (h/li item))")) ;; (let [form (read1 "(for [item items] (h/li item))")] ;; "(if x true false)")] ;; (pp/pprint (ana/parse (first form) user-env form nil nil))) ;; (let [form (read1 "(for [item items] (h/li item))")] ;; "(if x true false)")] ;; (pp/pprint (ana/analyze user-env form))) (let [form (read1 "(if x true false)")] (pp/pprint (ana/parse (first form) user-env form nil nil))) (let [form (read1 "(foo 1)")] (pp/pprint (ana/analyze user-env form))) (cljs->js (if x true false)) (cljs->js (fn [a b] (+ a b))) (cljs->js (foo 1)) (cljs->js (_typeChanged [type] (this-as me ))) (cljs->js (defn _typeChanged [type] (this-as me ))) (let [form (read1 "(fn [a b] (+ a b))")] (with-out-str (c/emit (ana/analyze user-env form)))) (let [form (read1 "(foo 1)")] (pp/pprint (ana/analyze user-env form))) ;; from iron-meta: ;; _typeChanged: function(type) { ;; this._unregisterKey(this.key); ;; if (!metaDatas[type]) { ;; metaDatas[type] = {}; ;; } ;; this._metaData = metaDatas[type]; ;; if (!metaArrays[type]) { ;; metaArrays[type] = []; ;; } ;; this.list = metaArrays[type]; ;; this._registerKeyValue(this.key, this.value); ;; }, ;; [^{:type String, :default "PI:NAME:<NAME>END_PI", :notify false, :read-only true, :attrsync true} ;; author ;; ^{:type Content, :default nil} ;; content] (println (dom-repeat [thing things] (h/li "thing") (h/li "thing")) ) (cljs->js (fn [])) (let [thing "items"] (println (h/li thing))) (let [li "items"] (str "foo " li " bar")) (ctor->template (my-list [author content] (h/dom-module ;; ID = ctor string, added automatically (h/template (h/style {:include "shared-styles"}) (h/ul (dom-repeat [item items] (h/li (h/span {:class "paper-font-body1"} item)) )))))) (co-type my-list "doc string here" (my-list ;; ctor -> dom-module "ctor doc string here" [^{:type String, :default "PI:NAME:<NAME>END_PI", :notify false, :read-only true, :attrsync true} author ^{:type Content, :default nil} content] ;; FIXME: link, script, etc. is metadata! (h/link {:rel "import" :href "polymer/polymer/polymer.html"}) (h/link {:rel "import" :href "styles/shared/style-modules.html"}) (h/dom-module ;; ID = ctor string, added automatically (h/template (h/style {:include "shared-styles"}) (h/ul (h/template {:is "dom-repeat" :items "{{items}}"} (h/li (h/span {:class "paper-font-body1"}"{{item}}")) (h/li {:id "special"} (h/span {:class "paper-font-body2"}"{{item}}")) (h/li (h/span {:class "paper-font-body3"}"{{item}}")) ))))) MutationObservation ;; protocol based on MutationObserver http://www.w3.org/TR/dom/#mutationobserver (author (fn [e] ...)) ;; instead of "observed" attr on "author" prop descriptor Polymer.Gesture ;; gesture events protocol (down (fn [this e] ...)) (up (fn [this e] ...)) (tap (fn [this e] ...)) ;; registers handler fn as listener for tap on the my-list elt (tap (fn [#special e] ...)) ;; respond to tap event on elt with id "special" (track (fn [e] ...)) DOM.Events ;; protocol ;; behaviors are protocols Polymer.PaperButtonBehavior (active ...) (disabled ...) (toggle ...) (addOwnKeyBinding ...) (active ...) ) ;; alternative ctor defn: (ctor "my-list" "MyList value constructor" ;; instead of a bunch of [:link...] decls we use metadata: ^{:imports ["polymer/polymer/polymer.html" "styles/shared/style-modules.html"] ;; (h/style {:include "shared-styles"}) - goes inside template elt :css ["foo.css"] :js ["foo.js"]} [^{:type String, :default "PI:NAME:<NAME>END_PI", :notify false, :read-only true, :attrsync true} author list-items ;; make arg to dom-repeat explicit ^{:type Content, :default nil} content] ;; no need for explicit dom-module, nor immediate template (h/ul (for [item list-items] ;; instead of <template is="dom-repeat"...> ;; TODO: make index explicit using std clojure (seq ;; FIXME: do we need this? (h/li (h/span {:class "paper-font-body1"} item)) (h/li :#special (h/span {:class "paper-font-body2"} item)) (h/li (h/span {:class "paper-font-body3"} item))) ))) ;; a ctor expr will emit a dom-module string. we want to be able to ;; use any and all of clojure for defining the ctor, while ;; metaprogramming the html/js/css. ;; For example, we might use (for [item items]...) to generate a ;; static list, using some data defined outside of the ctor defn. the ;; result will be a hardcoded ul containing some li elements. but we ;; also want to use ordinary clojure to express things like ;; dom-repeat. The trick here is to detect use of formal args. so if ;; list-items is listed as a formal arg to the ctor, and we detect ;; that it is used in a for clause, eg. (for [item list-items]...) we ;; know that the dom-repeat is indicated. as a double check, "item" ;; is also required in dom-repeat. ;; in short, we determine at compile time that some clojure ;; expressions should be interpreted as "co-expressions", and ;; translated into Polymer. iow we treat clojure as polysemous; its ;; expressions only ever have meaning "under an interpretation". that ;; interpretation is almost always the standard interpretation, but we ;; can use meta-programming to enable alternative interpretations. ;; dom-repeat example from ;; https://www.polymer-project.org/1.0/docs/devguide/templates.html#dom-repeat ;; <dom-module id="employee-list"> ;; <template> ;; <div> Employee list: </div> ;; <template is="dom-repeat" items="{{employees}}"> ;; <div># <span>{{index}}</span></div> ;; <div>First name: <span>{{item.first}}</span></div> ;; <div>Last name: <span>{{item.last}}</span></div> ;; </template> ;; </template>
[ { "context": "rrible multiplicity of possible\n;; configurations. Tom White, in the wonderful [Hadoop: The Definitive\n;; Guid", "end": 2601, "score": 0.9892014265060425, "start": 2592, "tag": "NAME", "value": "Tom White" }, { "context": "://goo.gl/Bh4zU) page... I have to\n;; say, though, Michael G. Noll's [single node](http://goo.gl/8ogSk)\n;; and [mult", "end": 3084, "score": 0.9986425638198853, "start": 3069, "tag": "NAME", "value": "Michael G. Noll" }, { "context": "de)\n :user (keyword user)\n :id_rsa])))\n\n(de", "end": 5960, "score": 0.5985532999038696, "start": 5956, "tag": "USERNAME", "value": "user" }, { "context": " XML with pretty-print formatting, as described by Nurullah Akaya\n in [this post](http://goo.gl/Y9OVO).\"\n [xml-str", "end": 9160, "score": 0.9997051358222961, "start": 9146, "tag": "NAME", "value": "Nurullah Akaya" } ]
src/pallet/crate/hadoop.clj
solackerman/hadoop-crate
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 pallet.crate.hadoop "Pallet crate to manage Hadoop installation and configuration." (:use [pallet.extensions :only (def-phase-fn phase-fn)]) (:require [pallet.script.lib :as lib] [pallet.thread-expr :as thread] [pallet.parameter :as parameter] [pallet.stevedore :as stevedore] [pallet.compute :as compute] [pallet.session :as session] [pallet.action.directory :as directory] [pallet.action.exec-script :as exec-script] [pallet.action.file :as file] [pallet.action.remote-directory :as remote-directory] [pallet.action.remote-file :as remote-file] [pallet.crate.etc-hosts :as etc-hosts] [pallet.action.user :as user] [pallet.script :as script] [clojure.contrib.prxml :as prxml] [clojure.string :as string] [clojure.tools.logging :as log] [pallet.crate.ssh-key :as ssh-key] [pallet.crate.java :as java]) (:import [java.io StringReader StringWriter] [javax.xml.transform TransformerFactory OutputKeys] [javax.xml.transform.stream StreamSource StreamResult])) ;; #### General Utilities ;; ;; This one is generally quite useful, and may end up in stevedore. (defn format-exports "Formats `export` lines for inclusion in a shell script." [& kv-pairs] (string/join (for [[k v] (partition 2 kv-pairs)] (format "export %s=%s\n" (name k) v)))) ;; ## Hadoop Configuration ;; ;; This crate contains all information required to set up and ;; configure a fully functional installation of Apache's Hadoop. It ;; seems that the biggest roadblock potential hadoop adopters face is ;; the confounding, terrible multiplicity of possible ;; configurations. Tom White, in the wonderful [Hadoop: The Definitive ;; Guide](http://goo.gl/nPWWk), states the case well: "Hadoop has a ;; bewildering number of configuration properties". ;; ;; We aim to provide sane, intelligent defaults that adjust themselves ;; based on a given cluster's size and particular distribution of ;; machines. ;; ;; The following phases are informed to some degree by Hadoop's ;; official [Getting Started](http://goo.gl/Bh4zU) page... I have to ;; say, though, Michael G. Noll's [single node](http://goo.gl/8ogSk) ;; and [multiple node](http://goo.gl/NIWoK) hadoop cluster tutorials ;; were immensely helpful. ;; ### Hadoop Defaults ;; ;; For this first version of the crate, we chose to lock down a few ;; parameters that'll be customizable down the road. (We've got a few ;; ideas on how to provide default overrides in a clean way, using ;; environments. Stay tuned!) In particular, we lock down version, ;; Hadoop's final location, and the name of the hadoop user and group ;; to be installed on each machine in the cluster. (defn versioned-home "Default Hadoop location, based on version number." [version] (format "/usr/local/hadoop-%s" version)) (def default-version "0.20.2") (def hadoop-home (versioned-home default-version)) (def hadoop-user "hadoop") (def hadoop-group "hadoop") ;; ### User Creation ;; ;; For the various nodes of a hadoop cluster to communicate with one ;; another, they need to share a common user with common ;; permissions. Something to keep in mind when manually logging in to ;; nodes -- hadoop java processes will run as the `hadoop` user, so ;; calls to `jps` as anyone else will show nothing running. If you'd ;;like to run a test job, ssh into the machine and run ;; ;; `sudo su - hadoop` ;; ;; before interacting with hadoop. (def-phase-fn create-hadoop-user "Create a hadoop user on a cluster node. We add the hadoop binary directory and a `JAVA_HOME` setting to `$PATH` to facilitate development when manually logged in to some particular node." [] (user/group hadoop-group :system true) (user/user hadoop-user :group hadoop-group :system true :create-home true :shell :bash) (remote-file/remote-file (format "/home/%s/.bash_profile" hadoop-user) :owner hadoop-user :group hadoop-group :literal true :content (format-exports :JAVA_HOME (stevedore/script (~java/java-home)) :PATH (format "$PATH:%s/bin" hadoop-home)))) ;; Once the hadoop user is created, we create an ssh key for that user ;; and share it around the cluster. The jobtracker needs passwordless ;; ssh access into every cluster node running a task tracker, so that ;; it can distribute the data processing code that these machines need ;; to do anything useful. (defn- get-node-ids-for-group "Get the id of the nodes in a group node" [request tag] (let [nodes (session/nodes-in-group request tag)] (map compute/id nodes))) (defn- get-keys-for-group "Returns the ssh key for a user in a group" [request tag user] (for [node (get-node-ids-for-group request tag)] (parameter/get-for request [:host (keyword node) :user (keyword user) :id_rsa]))) (defn- authorize-key [request local-user group remote-user] (let [keys (get-keys-for-group request group remote-user)] (thread/for-> request [key keys] (ssh-key/authorize-key local-user key)))) (def-phase-fn authorize-groups "Authorizes the master node to ssh into this node." [local-users tag-remote-users-map] (for [local-user local-users [group remote-users] tag-remote-users-map remote-user remote-users] (authorize-key local-user group remote-user))) ;; In the current iteration, `publish-ssh-key` phase should only be ;; called on the job-tracker, and will only work with a subsequent ;; `authorize-jobtracker` phase on the same request. Pallet is ;; stateless between transactions, and the ssh key needs some way to ;; get between nodes. Currently, we store the new ssh key in the request. (def-phase-fn publish-ssh-key [] (expose-request-as [request] (let [id (session/target-id request) tag (session/group-name request) key-name (format "%s_%s_key" tag id)] (ssh-key/generate-key hadoop-user :comment key-name) (ssh-key/record-public-key hadoop-user)))) (def-phase-fn authorize-tag "configures all nodes to accept passwordless ssh requests from the node with the supplied tag." [master-tag] (let [tag (name master-tag)] (authorize-groups [hadoop-user] {tag [hadoop-user]}))) ;; ### Installation ;; ;; `url` points to Cloudera's installation of Hadoop. Future ;; iterations of this crate will support the default apache build. ;; ;; TODO -- support switching between cloudera and regular. Regular, we ;; should give a version -- cloudera, it doesn't really mean much. (defn url "Download URL for the Cloudera CDH3 distribution of Hadoop, generated for the supplied version." [version] (case version :cloudera (format "http://archive.cloudera.com/cdh/3/hadoop-%s-cdh3u0.tar.gz" default-version) :apache (format "http://www.apache.org/dist/hadoop/core/hadoop-%s/hadoop-%s.tar.gz" default-version default-version))) (def-phase-fn install "First phase to be called when configuring a hadoop cluster. This phase creates a common hadoop user, and downloads and unpacks the default Cloudera hadoop distribution." [build] (let [url (url build)] create-hadoop-user (remote-directory/remote-directory hadoop-home :url url :unpack :tar :tar-options "xz" :owner hadoop-user :group hadoop-user))) ;; ### Configuration ;; ;; Hadoop has three main configuration files, each of which are a ;; series of key-value pairs, stored as XML files. Before cluster ;; configuration, we need some way to pretty-print human readable XML ;; representing the configuration properties that we'll store in a ;; clojure map. (defn ppxml "Accepts an XML string with no newline formatting and returns the same XML with pretty-print formatting, as described by Nurullah Akaya in [this post](http://goo.gl/Y9OVO)." [xml-str] (let [in (StreamSource. (StringReader. xml-str)) out (StreamResult. (StringWriter.)) transformer (.newTransformer (TransformerFactory/newInstance))] (doseq [[prop val] {OutputKeys/INDENT "yes" OutputKeys/METHOD "xml" "{http://xml.apache.org/xslt}indent-amount" "2"}] (.setOutputProperty transformer prop val)) (.transform transformer in out) (str (.getWriter out)))) (defn property->xml "Returns a nested sequence representing the XML for a hadoop configuration property. if `final?` is true, `<final>true</final>` is added to the XML entry, preventing any hadoop job from overriding the property." [property final?] [:property (filter identity [[:name {} (name (key property))] [:value {} (val property)] (when final? [:final {} "true"])])]) (declare final-properties) (defn properties->xml "Converts a map of [property value] entries into a string of XML with pretty-print formatting." [properties] (ppxml (with-out-str (prxml/prxml [:decl! {:version "1.0"}] [:configuration (map #(property->xml % (final-properties (key %))) properties)])))) ;; ### Sane Defaults ;; ;; As mentioned before, Hadoop configuration can be a bit ;; bewildering. Default values and descriptions of the meaning of each ;; setting can be found here: ;; ;; http://hadoop.apache.org/core/docs/r0.20.0/mapred-default.html ;; http://hadoop.apache.org/core/docs/r0.20.0/hdfs-default.html ;; http://hadoop.apache.org/core/docs/r0.20.0/core-default.html ;; ;; We override a number of these below based on suggestions found in ;; various posts. We'll supply more information on the justification ;; for each of these as we move forward with our dynamic "sane ;; defaults" system. (defn default-properties "Returns a nested map of Hadoop default configuration properties, named according to the 0.20 api." [name-node-ip job-tracker-ip pid-dir log-dir] (let [owner-dir (stevedore/script (~lib/user-home ~hadoop-user)) owner-subdir (partial str owner-dir)] {:hdfs-site {:dfs.data.dir (owner-subdir "/dfs/data") :dfs.name.dir (owner-subdir "/dfs/name") :dfs.datanode.du.reserved 1073741824 :dfs.namenode.handler.count 10 :dfs.permissions.enabled true :dfs.replication 3 :dfs.datanode.max.xcievers 4096} :mapred-site {:tasktracker.http.threads 46 :mapred.local.dir (owner-subdir "/mapred/local") :mapred.system.dir "/hadoop/mapred/system" :mapred.child.java.opts "-Xmx550m" :mapred.job.tracker (format "%s:8021" job-tracker-ip) :mapred.job.tracker.handler.count 10 :mapred.map.tasks.speculative.execution true :mapred.reduce.tasks.speculative.execution false :mapred.reduce.parallel.copies 10 :mapred.reduce.tasks 5 :mapred.submit.replication 10 :mapred.tasktracker.map.tasks.maximum 2 :mapred.tasktracker.reduce.tasks.maximum 1 :mapred.compress.map.output true :mapred.output.compression.type "BLOCK"} :core-site {:fs.checkpoint.dir (owner-subdir "/dfs/secondary") :fs.default.name (format "hdfs://%s:8020" name-node-ip) :fs.trash.interval 1440 :io.file.buffer.size 65536 :hadoop.tmp.dir "/tmp/hadoop" :hadoop.rpc.socket.factory.class.default "org.apache.hadoop.net.StandardSocketFactory" :hadoop.rpc.socket.factory.class.ClientProtocol "" :hadoop.rpc.socket.factory.class.JobSubmissionProtocol "" :io.compression.codecs (str "org.apache.hadoop.io.compress.DefaultCodec," "org.apache.hadoop.io.compress.GzipCodec")} :hadoop-env {:HADOOP_PID_DIR pid-dir :HADOOP_LOG_DIR log-dir :HADOOP_SSH_OPTS "\"-o StrictHostKeyChecking=no\"" :HADOOP_OPTS "\"-Djava.net.preferIPv4Stack=true\""}})) ;; Final properties are properties that can't be overridden during the ;; execution of a job. We're not sure that these are the right ;; properties to lock, as of now -- this will become more clear as we ;; move forward with sane defaults. In the meantime, any suggestions ;; would be much appreciated. (def final-properties #{:dfs.block.size :dfs.data.dir :dfs.datanode.du.reserved :dfs.datanode.handler.count :dfs.hosts :dfs.hosts.exclude :dfs.name.dir :dfs.namenode.handler.count :dfs.permissions :fs.checkpoint.dir :fs.trash.interval :hadoop.tmp.dir :mapred.child.ulimit :mapred.job.tracker.handler.count :mapred.local.dir :mapred.tasktracker.map.tasks.maximum :mapred.tasktracker.reduce.tasks.maximum :tasktracker.http.threads :hadoop.rpc.socket.factory.class.default :hadoop.rpc.socket.factory.class.ClientProtocol :hadoop.rpc.socket.factory.class.JobSubmissionProtocol}) (defmacro with-overwrite "Executes the body with binding remote-file/force-overwrite to true, thus allowing pallet to overwrite files without complaining about MD5 clashes. This is a hack to make overwriting `pallet.action.remote-file/force-overwrite` work in both pallet 0.6.x and pallet 0.7+, since this variable was renamed to *force-overwrite* It threads the session because it needs to play nice with def-phase-fn..." [session & body] (if (ns-resolve 'pallet.action.remote-file 'force-overwrite) `(binding [remote-file/force-overwrite true] (-> ~session ~@body)) `(binding [remote-file/*force-overwrite* true] (-> ~session ~@body)))) (def-phase-fn config-files "Accepts a base directory and a map of [config-filename, property-map] pairs, and augments the supplied request to allow for the creation of each referenced configuration file within the base directory." [config-dir properties] (with-overwrite (for [[filename props] properties] (remote-file/remote-file (format "%s/%s.xml" config-dir (name filename)) :content (properties->xml props) :owner hadoop-user :group hadoop-group)))) (def merge-config (partial merge-with merge)) (defn merge-and-split-config "Merges a set of custom hadoop configuration option maps into the current defaults, and returns a 2-vector where the first item is a map of *-site files, and the second item is a map of exports for `hadoop-env.sh`. If a conflict exists, entries in `new-props` knock out entries in `default-props`." [default-props new-props] (let [prop-map (merge-config default-props new-props) corekey-seq [:core-site :hdfs-site :mapred-site] envkey-seq [:hadoop-env]] (map #(select-keys prop-map %) [corekey-seq envkey-seq]))) (def-phase-fn env-file "Phase that creates the `hadoop-env.sh` file with references to the supplied pid and log dirs. `hadoop-env.sh` will be placed within the supplied config directory." [config-dir env-map] (for [[fname exports] env-map :let [fname (name fname) export-seq (flatten (seq exports))]] (remote-file/remote-file (format "%s/%s.sh" config-dir fname) :content (apply format-exports export-seq)))) ;; We do our development on local machines using `vmfest`, which ;; brought us in context with the next problem. Some clouds -- ;; Amazon's EC2, for example -- require nodes to be configured with ;; private IP addresses. Hadoop is designed for use within private ;; clusters, so this is typically the right choice. Sometimes, ;; however, public IP addresses are preferable, as in a virtual ;; machine setup. ;; ;; Hadoop takes the IP addresses in `fs.default.name`, ;; `mapred.job.tracker` and performs a reverse DNS lookup, tracking ;; each machine by its hostname. If your cluster isn't set up to ;; handle DNS lookup, you might run into some interesting issues. On ;; these VMs, for example, reverse DNS lookups by the virtual machines ;; on each other caused every VM to resolve to the hostname of my home ;; router. This can cause jobs to limp along or fail msyteriously. We ;; have a workaround involved the `/etc/hosts` file planned for a ;; future iteration. (defn get-master-ip "Returns the IP address of a particular type of master node, as defined by tag. IP-type can be `:private` or `:public`. Function logs a warning if more than one master exists." [request ip-type tag] {:pre [(contains? #{:public :private} ip-type)]} (let [[master :as nodes] (session/nodes-in-group request tag) kind (name tag)] (when (> (count nodes) 1) (log/warn (format "There are more than one %s" kind))) (if-not master (log/error (format "There is no %s defined!" kind)) ((case ip-type :private compute/private-ip :public compute/primary-ip) master)))) (def-phase-fn configure "Configures a Hadoop cluster by creating all required default directories, and populating the proper configuration file options. The `properties` parameter must be a map of the form {:core-site {:key val...} :hdfs-site {:key val ...} :mapred-site {:key val ...} :hadoop-env {:export val ...}} No other top-level keys are supported at this time." [ip-type namenode-tag jobtracker-tag properties] (expose-request-as [request] (let [conf-dir (str hadoop-home "/conf") etc-conf-dir (stevedore/script (str (~lib/config-root) "/hadoop")) nn-ip (get-master-ip request ip-type namenode-tag) jt-ip (get-master-ip request ip-type jobtracker-tag) pid-dir (stevedore/script (str (~lib/pid-root) "/hadoop")) log-dir (stevedore/script (str (~lib/log-root) "/hadoop")) defaults (default-properties nn-ip jt-ip pid-dir log-dir) [props env] (merge-and-split-config defaults properties) tmp-dir (get-in properties [:core-site :hadoop.tmp.dir])] (for [path [conf-dir tmp-dir log-dir pid-dir]] (directory/directory path :owner hadoop-user :group hadoop-group :mode "0755")) (file/symbolic-link conf-dir etc-conf-dir) (config-files conf-dir props) (env-file conf-dir env)))) ;; The following script allows for proper transmission of SSH ;; commands, with hadoop's required `JAVA_HOME` property all set. (script/defscript as-user [user & command]) (script/defimpl as-user :default [user & command] (su -s "/bin/bash" ~user -c "\"" (str "export JAVA_HOME=" (~java/java-home) ";") ~@command "\"")) (script/defimpl as-user [#{:yum}] [user & command] ("/sbin/runuser" -s "/bin/bash" - ~user -c ~@command)) ;; Hadoop services, or `roles`, are all run by the `hadoop-daemon.sh` ;; command. Other scripts exist, such as `hadoop-daemons.sh` (for ;; running commands on many nodes at once), but pallet takes over for ;; a good number of these. The following `phase-fn` takes care to only ;; start a hadoop service that's not already running for the `hadoop` ;; user. Future iterations may provide the ability to force some ;; daemon service to restart. (def-phase-fn hadoop-service "Run a Hadoop service" [hadoop-daemon description] (exec-script/exec-checked-script (str "Start Hadoop " description) (~as-user ~hadoop-user ~(stevedore/script (if-not (pipe (jps) (grep "-i" ~hadoop-daemon)) ((str ~hadoop-home "/bin/hadoop-daemon.sh") "start" ~hadoop-daemon)))))) (def-phase-fn hadoop-command "Runs '$ hadoop `args`' on each machine in the request. Command runs as the hadoop user." [& args] (exec-script/exec-checked-script (apply str "hadoop " (interpose " " args)) (~as-user ~hadoop-user (str ~hadoop-home "/bin/hadoop") ~@args))) ;; `format-hdfs` is, effectively, a call to ;; ;; `(hadoop-command "namenode" "-format") ;; ;; that call would only work the first time, however. On subsequent ;;format requests, hadoop tells the user that the namenode has already ;;been formatted, and asks for confirmation. The current version of ;;`format-namenode` sends a default "N" every time. (def-phase-fn format-hdfs "Formats HDFS for the first time. If HDFS has already been formatted, does nothing." [] (exec-script/exec-script (~as-user ~hadoop-user (pipe (echo "N") ((str ~hadoop-home "/bin/hadoop") "namenode" "-format"))))) ;; And, here we are at the end! The following five functions activate ;; each of the five distinct roles that hadoop nodes may take on. (def-phase-fn name-node "Collection of all subphases required for a namenode." [data-dir] format-hdfs (hadoop-service "namenode" "Name Node") (hadoop-command "dfsadmin" "-safemode" "wait") (hadoop-command "fs" "-mkdir" data-dir) (hadoop-command "fs" "-chmod" "+w" data-dir)) (def-phase-fn secondary-name-node [] (hadoop-service "secondarynamenode" "secondary name node")) (def-phase-fn job-tracker [] (hadoop-service "jobtracker" "job tracker")) (def-phase-fn data-node [] (hadoop-service "datanode" "data node")) (def-phase-fn task-tracker [] (hadoop-service "tasktracker" "task tracker")) (def-phase-fn setup-etc-hosts "Adds the ip addresses and host names of all nodes in all the groups in `groups` to the `/etc/hosts` file in this node. :private-ip will use the private ip address of the nodes instead of the public one " [groups & {:keys [private-ip] :as options}] (expose-request-as [session] (let [groups (map name groups) node-name (session/target-name session)] (etc-hosts/hostname node-name) (thread/for-> [group groups] (etc-hosts/hosts-for-group group :private-ip private-ip)) (etc-hosts/hosts))))
116625
;; 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 pallet.crate.hadoop "Pallet crate to manage Hadoop installation and configuration." (:use [pallet.extensions :only (def-phase-fn phase-fn)]) (:require [pallet.script.lib :as lib] [pallet.thread-expr :as thread] [pallet.parameter :as parameter] [pallet.stevedore :as stevedore] [pallet.compute :as compute] [pallet.session :as session] [pallet.action.directory :as directory] [pallet.action.exec-script :as exec-script] [pallet.action.file :as file] [pallet.action.remote-directory :as remote-directory] [pallet.action.remote-file :as remote-file] [pallet.crate.etc-hosts :as etc-hosts] [pallet.action.user :as user] [pallet.script :as script] [clojure.contrib.prxml :as prxml] [clojure.string :as string] [clojure.tools.logging :as log] [pallet.crate.ssh-key :as ssh-key] [pallet.crate.java :as java]) (:import [java.io StringReader StringWriter] [javax.xml.transform TransformerFactory OutputKeys] [javax.xml.transform.stream StreamSource StreamResult])) ;; #### General Utilities ;; ;; This one is generally quite useful, and may end up in stevedore. (defn format-exports "Formats `export` lines for inclusion in a shell script." [& kv-pairs] (string/join (for [[k v] (partition 2 kv-pairs)] (format "export %s=%s\n" (name k) v)))) ;; ## Hadoop Configuration ;; ;; This crate contains all information required to set up and ;; configure a fully functional installation of Apache's Hadoop. It ;; seems that the biggest roadblock potential hadoop adopters face is ;; the confounding, terrible multiplicity of possible ;; configurations. <NAME>, in the wonderful [Hadoop: The Definitive ;; Guide](http://goo.gl/nPWWk), states the case well: "Hadoop has a ;; bewildering number of configuration properties". ;; ;; We aim to provide sane, intelligent defaults that adjust themselves ;; based on a given cluster's size and particular distribution of ;; machines. ;; ;; The following phases are informed to some degree by Hadoop's ;; official [Getting Started](http://goo.gl/Bh4zU) page... I have to ;; say, though, <NAME>'s [single node](http://goo.gl/8ogSk) ;; and [multiple node](http://goo.gl/NIWoK) hadoop cluster tutorials ;; were immensely helpful. ;; ### Hadoop Defaults ;; ;; For this first version of the crate, we chose to lock down a few ;; parameters that'll be customizable down the road. (We've got a few ;; ideas on how to provide default overrides in a clean way, using ;; environments. Stay tuned!) In particular, we lock down version, ;; Hadoop's final location, and the name of the hadoop user and group ;; to be installed on each machine in the cluster. (defn versioned-home "Default Hadoop location, based on version number." [version] (format "/usr/local/hadoop-%s" version)) (def default-version "0.20.2") (def hadoop-home (versioned-home default-version)) (def hadoop-user "hadoop") (def hadoop-group "hadoop") ;; ### User Creation ;; ;; For the various nodes of a hadoop cluster to communicate with one ;; another, they need to share a common user with common ;; permissions. Something to keep in mind when manually logging in to ;; nodes -- hadoop java processes will run as the `hadoop` user, so ;; calls to `jps` as anyone else will show nothing running. If you'd ;;like to run a test job, ssh into the machine and run ;; ;; `sudo su - hadoop` ;; ;; before interacting with hadoop. (def-phase-fn create-hadoop-user "Create a hadoop user on a cluster node. We add the hadoop binary directory and a `JAVA_HOME` setting to `$PATH` to facilitate development when manually logged in to some particular node." [] (user/group hadoop-group :system true) (user/user hadoop-user :group hadoop-group :system true :create-home true :shell :bash) (remote-file/remote-file (format "/home/%s/.bash_profile" hadoop-user) :owner hadoop-user :group hadoop-group :literal true :content (format-exports :JAVA_HOME (stevedore/script (~java/java-home)) :PATH (format "$PATH:%s/bin" hadoop-home)))) ;; Once the hadoop user is created, we create an ssh key for that user ;; and share it around the cluster. The jobtracker needs passwordless ;; ssh access into every cluster node running a task tracker, so that ;; it can distribute the data processing code that these machines need ;; to do anything useful. (defn- get-node-ids-for-group "Get the id of the nodes in a group node" [request tag] (let [nodes (session/nodes-in-group request tag)] (map compute/id nodes))) (defn- get-keys-for-group "Returns the ssh key for a user in a group" [request tag user] (for [node (get-node-ids-for-group request tag)] (parameter/get-for request [:host (keyword node) :user (keyword user) :id_rsa]))) (defn- authorize-key [request local-user group remote-user] (let [keys (get-keys-for-group request group remote-user)] (thread/for-> request [key keys] (ssh-key/authorize-key local-user key)))) (def-phase-fn authorize-groups "Authorizes the master node to ssh into this node." [local-users tag-remote-users-map] (for [local-user local-users [group remote-users] tag-remote-users-map remote-user remote-users] (authorize-key local-user group remote-user))) ;; In the current iteration, `publish-ssh-key` phase should only be ;; called on the job-tracker, and will only work with a subsequent ;; `authorize-jobtracker` phase on the same request. Pallet is ;; stateless between transactions, and the ssh key needs some way to ;; get between nodes. Currently, we store the new ssh key in the request. (def-phase-fn publish-ssh-key [] (expose-request-as [request] (let [id (session/target-id request) tag (session/group-name request) key-name (format "%s_%s_key" tag id)] (ssh-key/generate-key hadoop-user :comment key-name) (ssh-key/record-public-key hadoop-user)))) (def-phase-fn authorize-tag "configures all nodes to accept passwordless ssh requests from the node with the supplied tag." [master-tag] (let [tag (name master-tag)] (authorize-groups [hadoop-user] {tag [hadoop-user]}))) ;; ### Installation ;; ;; `url` points to Cloudera's installation of Hadoop. Future ;; iterations of this crate will support the default apache build. ;; ;; TODO -- support switching between cloudera and regular. Regular, we ;; should give a version -- cloudera, it doesn't really mean much. (defn url "Download URL for the Cloudera CDH3 distribution of Hadoop, generated for the supplied version." [version] (case version :cloudera (format "http://archive.cloudera.com/cdh/3/hadoop-%s-cdh3u0.tar.gz" default-version) :apache (format "http://www.apache.org/dist/hadoop/core/hadoop-%s/hadoop-%s.tar.gz" default-version default-version))) (def-phase-fn install "First phase to be called when configuring a hadoop cluster. This phase creates a common hadoop user, and downloads and unpacks the default Cloudera hadoop distribution." [build] (let [url (url build)] create-hadoop-user (remote-directory/remote-directory hadoop-home :url url :unpack :tar :tar-options "xz" :owner hadoop-user :group hadoop-user))) ;; ### Configuration ;; ;; Hadoop has three main configuration files, each of which are a ;; series of key-value pairs, stored as XML files. Before cluster ;; configuration, we need some way to pretty-print human readable XML ;; representing the configuration properties that we'll store in a ;; clojure map. (defn ppxml "Accepts an XML string with no newline formatting and returns the same XML with pretty-print formatting, as described by <NAME> in [this post](http://goo.gl/Y9OVO)." [xml-str] (let [in (StreamSource. (StringReader. xml-str)) out (StreamResult. (StringWriter.)) transformer (.newTransformer (TransformerFactory/newInstance))] (doseq [[prop val] {OutputKeys/INDENT "yes" OutputKeys/METHOD "xml" "{http://xml.apache.org/xslt}indent-amount" "2"}] (.setOutputProperty transformer prop val)) (.transform transformer in out) (str (.getWriter out)))) (defn property->xml "Returns a nested sequence representing the XML for a hadoop configuration property. if `final?` is true, `<final>true</final>` is added to the XML entry, preventing any hadoop job from overriding the property." [property final?] [:property (filter identity [[:name {} (name (key property))] [:value {} (val property)] (when final? [:final {} "true"])])]) (declare final-properties) (defn properties->xml "Converts a map of [property value] entries into a string of XML with pretty-print formatting." [properties] (ppxml (with-out-str (prxml/prxml [:decl! {:version "1.0"}] [:configuration (map #(property->xml % (final-properties (key %))) properties)])))) ;; ### Sane Defaults ;; ;; As mentioned before, Hadoop configuration can be a bit ;; bewildering. Default values and descriptions of the meaning of each ;; setting can be found here: ;; ;; http://hadoop.apache.org/core/docs/r0.20.0/mapred-default.html ;; http://hadoop.apache.org/core/docs/r0.20.0/hdfs-default.html ;; http://hadoop.apache.org/core/docs/r0.20.0/core-default.html ;; ;; We override a number of these below based on suggestions found in ;; various posts. We'll supply more information on the justification ;; for each of these as we move forward with our dynamic "sane ;; defaults" system. (defn default-properties "Returns a nested map of Hadoop default configuration properties, named according to the 0.20 api." [name-node-ip job-tracker-ip pid-dir log-dir] (let [owner-dir (stevedore/script (~lib/user-home ~hadoop-user)) owner-subdir (partial str owner-dir)] {:hdfs-site {:dfs.data.dir (owner-subdir "/dfs/data") :dfs.name.dir (owner-subdir "/dfs/name") :dfs.datanode.du.reserved 1073741824 :dfs.namenode.handler.count 10 :dfs.permissions.enabled true :dfs.replication 3 :dfs.datanode.max.xcievers 4096} :mapred-site {:tasktracker.http.threads 46 :mapred.local.dir (owner-subdir "/mapred/local") :mapred.system.dir "/hadoop/mapred/system" :mapred.child.java.opts "-Xmx550m" :mapred.job.tracker (format "%s:8021" job-tracker-ip) :mapred.job.tracker.handler.count 10 :mapred.map.tasks.speculative.execution true :mapred.reduce.tasks.speculative.execution false :mapred.reduce.parallel.copies 10 :mapred.reduce.tasks 5 :mapred.submit.replication 10 :mapred.tasktracker.map.tasks.maximum 2 :mapred.tasktracker.reduce.tasks.maximum 1 :mapred.compress.map.output true :mapred.output.compression.type "BLOCK"} :core-site {:fs.checkpoint.dir (owner-subdir "/dfs/secondary") :fs.default.name (format "hdfs://%s:8020" name-node-ip) :fs.trash.interval 1440 :io.file.buffer.size 65536 :hadoop.tmp.dir "/tmp/hadoop" :hadoop.rpc.socket.factory.class.default "org.apache.hadoop.net.StandardSocketFactory" :hadoop.rpc.socket.factory.class.ClientProtocol "" :hadoop.rpc.socket.factory.class.JobSubmissionProtocol "" :io.compression.codecs (str "org.apache.hadoop.io.compress.DefaultCodec," "org.apache.hadoop.io.compress.GzipCodec")} :hadoop-env {:HADOOP_PID_DIR pid-dir :HADOOP_LOG_DIR log-dir :HADOOP_SSH_OPTS "\"-o StrictHostKeyChecking=no\"" :HADOOP_OPTS "\"-Djava.net.preferIPv4Stack=true\""}})) ;; Final properties are properties that can't be overridden during the ;; execution of a job. We're not sure that these are the right ;; properties to lock, as of now -- this will become more clear as we ;; move forward with sane defaults. In the meantime, any suggestions ;; would be much appreciated. (def final-properties #{:dfs.block.size :dfs.data.dir :dfs.datanode.du.reserved :dfs.datanode.handler.count :dfs.hosts :dfs.hosts.exclude :dfs.name.dir :dfs.namenode.handler.count :dfs.permissions :fs.checkpoint.dir :fs.trash.interval :hadoop.tmp.dir :mapred.child.ulimit :mapred.job.tracker.handler.count :mapred.local.dir :mapred.tasktracker.map.tasks.maximum :mapred.tasktracker.reduce.tasks.maximum :tasktracker.http.threads :hadoop.rpc.socket.factory.class.default :hadoop.rpc.socket.factory.class.ClientProtocol :hadoop.rpc.socket.factory.class.JobSubmissionProtocol}) (defmacro with-overwrite "Executes the body with binding remote-file/force-overwrite to true, thus allowing pallet to overwrite files without complaining about MD5 clashes. This is a hack to make overwriting `pallet.action.remote-file/force-overwrite` work in both pallet 0.6.x and pallet 0.7+, since this variable was renamed to *force-overwrite* It threads the session because it needs to play nice with def-phase-fn..." [session & body] (if (ns-resolve 'pallet.action.remote-file 'force-overwrite) `(binding [remote-file/force-overwrite true] (-> ~session ~@body)) `(binding [remote-file/*force-overwrite* true] (-> ~session ~@body)))) (def-phase-fn config-files "Accepts a base directory and a map of [config-filename, property-map] pairs, and augments the supplied request to allow for the creation of each referenced configuration file within the base directory." [config-dir properties] (with-overwrite (for [[filename props] properties] (remote-file/remote-file (format "%s/%s.xml" config-dir (name filename)) :content (properties->xml props) :owner hadoop-user :group hadoop-group)))) (def merge-config (partial merge-with merge)) (defn merge-and-split-config "Merges a set of custom hadoop configuration option maps into the current defaults, and returns a 2-vector where the first item is a map of *-site files, and the second item is a map of exports for `hadoop-env.sh`. If a conflict exists, entries in `new-props` knock out entries in `default-props`." [default-props new-props] (let [prop-map (merge-config default-props new-props) corekey-seq [:core-site :hdfs-site :mapred-site] envkey-seq [:hadoop-env]] (map #(select-keys prop-map %) [corekey-seq envkey-seq]))) (def-phase-fn env-file "Phase that creates the `hadoop-env.sh` file with references to the supplied pid and log dirs. `hadoop-env.sh` will be placed within the supplied config directory." [config-dir env-map] (for [[fname exports] env-map :let [fname (name fname) export-seq (flatten (seq exports))]] (remote-file/remote-file (format "%s/%s.sh" config-dir fname) :content (apply format-exports export-seq)))) ;; We do our development on local machines using `vmfest`, which ;; brought us in context with the next problem. Some clouds -- ;; Amazon's EC2, for example -- require nodes to be configured with ;; private IP addresses. Hadoop is designed for use within private ;; clusters, so this is typically the right choice. Sometimes, ;; however, public IP addresses are preferable, as in a virtual ;; machine setup. ;; ;; Hadoop takes the IP addresses in `fs.default.name`, ;; `mapred.job.tracker` and performs a reverse DNS lookup, tracking ;; each machine by its hostname. If your cluster isn't set up to ;; handle DNS lookup, you might run into some interesting issues. On ;; these VMs, for example, reverse DNS lookups by the virtual machines ;; on each other caused every VM to resolve to the hostname of my home ;; router. This can cause jobs to limp along or fail msyteriously. We ;; have a workaround involved the `/etc/hosts` file planned for a ;; future iteration. (defn get-master-ip "Returns the IP address of a particular type of master node, as defined by tag. IP-type can be `:private` or `:public`. Function logs a warning if more than one master exists." [request ip-type tag] {:pre [(contains? #{:public :private} ip-type)]} (let [[master :as nodes] (session/nodes-in-group request tag) kind (name tag)] (when (> (count nodes) 1) (log/warn (format "There are more than one %s" kind))) (if-not master (log/error (format "There is no %s defined!" kind)) ((case ip-type :private compute/private-ip :public compute/primary-ip) master)))) (def-phase-fn configure "Configures a Hadoop cluster by creating all required default directories, and populating the proper configuration file options. The `properties` parameter must be a map of the form {:core-site {:key val...} :hdfs-site {:key val ...} :mapred-site {:key val ...} :hadoop-env {:export val ...}} No other top-level keys are supported at this time." [ip-type namenode-tag jobtracker-tag properties] (expose-request-as [request] (let [conf-dir (str hadoop-home "/conf") etc-conf-dir (stevedore/script (str (~lib/config-root) "/hadoop")) nn-ip (get-master-ip request ip-type namenode-tag) jt-ip (get-master-ip request ip-type jobtracker-tag) pid-dir (stevedore/script (str (~lib/pid-root) "/hadoop")) log-dir (stevedore/script (str (~lib/log-root) "/hadoop")) defaults (default-properties nn-ip jt-ip pid-dir log-dir) [props env] (merge-and-split-config defaults properties) tmp-dir (get-in properties [:core-site :hadoop.tmp.dir])] (for [path [conf-dir tmp-dir log-dir pid-dir]] (directory/directory path :owner hadoop-user :group hadoop-group :mode "0755")) (file/symbolic-link conf-dir etc-conf-dir) (config-files conf-dir props) (env-file conf-dir env)))) ;; The following script allows for proper transmission of SSH ;; commands, with hadoop's required `JAVA_HOME` property all set. (script/defscript as-user [user & command]) (script/defimpl as-user :default [user & command] (su -s "/bin/bash" ~user -c "\"" (str "export JAVA_HOME=" (~java/java-home) ";") ~@command "\"")) (script/defimpl as-user [#{:yum}] [user & command] ("/sbin/runuser" -s "/bin/bash" - ~user -c ~@command)) ;; Hadoop services, or `roles`, are all run by the `hadoop-daemon.sh` ;; command. Other scripts exist, such as `hadoop-daemons.sh` (for ;; running commands on many nodes at once), but pallet takes over for ;; a good number of these. The following `phase-fn` takes care to only ;; start a hadoop service that's not already running for the `hadoop` ;; user. Future iterations may provide the ability to force some ;; daemon service to restart. (def-phase-fn hadoop-service "Run a Hadoop service" [hadoop-daemon description] (exec-script/exec-checked-script (str "Start Hadoop " description) (~as-user ~hadoop-user ~(stevedore/script (if-not (pipe (jps) (grep "-i" ~hadoop-daemon)) ((str ~hadoop-home "/bin/hadoop-daemon.sh") "start" ~hadoop-daemon)))))) (def-phase-fn hadoop-command "Runs '$ hadoop `args`' on each machine in the request. Command runs as the hadoop user." [& args] (exec-script/exec-checked-script (apply str "hadoop " (interpose " " args)) (~as-user ~hadoop-user (str ~hadoop-home "/bin/hadoop") ~@args))) ;; `format-hdfs` is, effectively, a call to ;; ;; `(hadoop-command "namenode" "-format") ;; ;; that call would only work the first time, however. On subsequent ;;format requests, hadoop tells the user that the namenode has already ;;been formatted, and asks for confirmation. The current version of ;;`format-namenode` sends a default "N" every time. (def-phase-fn format-hdfs "Formats HDFS for the first time. If HDFS has already been formatted, does nothing." [] (exec-script/exec-script (~as-user ~hadoop-user (pipe (echo "N") ((str ~hadoop-home "/bin/hadoop") "namenode" "-format"))))) ;; And, here we are at the end! The following five functions activate ;; each of the five distinct roles that hadoop nodes may take on. (def-phase-fn name-node "Collection of all subphases required for a namenode." [data-dir] format-hdfs (hadoop-service "namenode" "Name Node") (hadoop-command "dfsadmin" "-safemode" "wait") (hadoop-command "fs" "-mkdir" data-dir) (hadoop-command "fs" "-chmod" "+w" data-dir)) (def-phase-fn secondary-name-node [] (hadoop-service "secondarynamenode" "secondary name node")) (def-phase-fn job-tracker [] (hadoop-service "jobtracker" "job tracker")) (def-phase-fn data-node [] (hadoop-service "datanode" "data node")) (def-phase-fn task-tracker [] (hadoop-service "tasktracker" "task tracker")) (def-phase-fn setup-etc-hosts "Adds the ip addresses and host names of all nodes in all the groups in `groups` to the `/etc/hosts` file in this node. :private-ip will use the private ip address of the nodes instead of the public one " [groups & {:keys [private-ip] :as options}] (expose-request-as [session] (let [groups (map name groups) node-name (session/target-name session)] (etc-hosts/hostname node-name) (thread/for-> [group groups] (etc-hosts/hosts-for-group group :private-ip private-ip)) (etc-hosts/hosts))))
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 pallet.crate.hadoop "Pallet crate to manage Hadoop installation and configuration." (:use [pallet.extensions :only (def-phase-fn phase-fn)]) (:require [pallet.script.lib :as lib] [pallet.thread-expr :as thread] [pallet.parameter :as parameter] [pallet.stevedore :as stevedore] [pallet.compute :as compute] [pallet.session :as session] [pallet.action.directory :as directory] [pallet.action.exec-script :as exec-script] [pallet.action.file :as file] [pallet.action.remote-directory :as remote-directory] [pallet.action.remote-file :as remote-file] [pallet.crate.etc-hosts :as etc-hosts] [pallet.action.user :as user] [pallet.script :as script] [clojure.contrib.prxml :as prxml] [clojure.string :as string] [clojure.tools.logging :as log] [pallet.crate.ssh-key :as ssh-key] [pallet.crate.java :as java]) (:import [java.io StringReader StringWriter] [javax.xml.transform TransformerFactory OutputKeys] [javax.xml.transform.stream StreamSource StreamResult])) ;; #### General Utilities ;; ;; This one is generally quite useful, and may end up in stevedore. (defn format-exports "Formats `export` lines for inclusion in a shell script." [& kv-pairs] (string/join (for [[k v] (partition 2 kv-pairs)] (format "export %s=%s\n" (name k) v)))) ;; ## Hadoop Configuration ;; ;; This crate contains all information required to set up and ;; configure a fully functional installation of Apache's Hadoop. It ;; seems that the biggest roadblock potential hadoop adopters face is ;; the confounding, terrible multiplicity of possible ;; configurations. PI:NAME:<NAME>END_PI, in the wonderful [Hadoop: The Definitive ;; Guide](http://goo.gl/nPWWk), states the case well: "Hadoop has a ;; bewildering number of configuration properties". ;; ;; We aim to provide sane, intelligent defaults that adjust themselves ;; based on a given cluster's size and particular distribution of ;; machines. ;; ;; The following phases are informed to some degree by Hadoop's ;; official [Getting Started](http://goo.gl/Bh4zU) page... I have to ;; say, though, PI:NAME:<NAME>END_PI's [single node](http://goo.gl/8ogSk) ;; and [multiple node](http://goo.gl/NIWoK) hadoop cluster tutorials ;; were immensely helpful. ;; ### Hadoop Defaults ;; ;; For this first version of the crate, we chose to lock down a few ;; parameters that'll be customizable down the road. (We've got a few ;; ideas on how to provide default overrides in a clean way, using ;; environments. Stay tuned!) In particular, we lock down version, ;; Hadoop's final location, and the name of the hadoop user and group ;; to be installed on each machine in the cluster. (defn versioned-home "Default Hadoop location, based on version number." [version] (format "/usr/local/hadoop-%s" version)) (def default-version "0.20.2") (def hadoop-home (versioned-home default-version)) (def hadoop-user "hadoop") (def hadoop-group "hadoop") ;; ### User Creation ;; ;; For the various nodes of a hadoop cluster to communicate with one ;; another, they need to share a common user with common ;; permissions. Something to keep in mind when manually logging in to ;; nodes -- hadoop java processes will run as the `hadoop` user, so ;; calls to `jps` as anyone else will show nothing running. If you'd ;;like to run a test job, ssh into the machine and run ;; ;; `sudo su - hadoop` ;; ;; before interacting with hadoop. (def-phase-fn create-hadoop-user "Create a hadoop user on a cluster node. We add the hadoop binary directory and a `JAVA_HOME` setting to `$PATH` to facilitate development when manually logged in to some particular node." [] (user/group hadoop-group :system true) (user/user hadoop-user :group hadoop-group :system true :create-home true :shell :bash) (remote-file/remote-file (format "/home/%s/.bash_profile" hadoop-user) :owner hadoop-user :group hadoop-group :literal true :content (format-exports :JAVA_HOME (stevedore/script (~java/java-home)) :PATH (format "$PATH:%s/bin" hadoop-home)))) ;; Once the hadoop user is created, we create an ssh key for that user ;; and share it around the cluster. The jobtracker needs passwordless ;; ssh access into every cluster node running a task tracker, so that ;; it can distribute the data processing code that these machines need ;; to do anything useful. (defn- get-node-ids-for-group "Get the id of the nodes in a group node" [request tag] (let [nodes (session/nodes-in-group request tag)] (map compute/id nodes))) (defn- get-keys-for-group "Returns the ssh key for a user in a group" [request tag user] (for [node (get-node-ids-for-group request tag)] (parameter/get-for request [:host (keyword node) :user (keyword user) :id_rsa]))) (defn- authorize-key [request local-user group remote-user] (let [keys (get-keys-for-group request group remote-user)] (thread/for-> request [key keys] (ssh-key/authorize-key local-user key)))) (def-phase-fn authorize-groups "Authorizes the master node to ssh into this node." [local-users tag-remote-users-map] (for [local-user local-users [group remote-users] tag-remote-users-map remote-user remote-users] (authorize-key local-user group remote-user))) ;; In the current iteration, `publish-ssh-key` phase should only be ;; called on the job-tracker, and will only work with a subsequent ;; `authorize-jobtracker` phase on the same request. Pallet is ;; stateless between transactions, and the ssh key needs some way to ;; get between nodes. Currently, we store the new ssh key in the request. (def-phase-fn publish-ssh-key [] (expose-request-as [request] (let [id (session/target-id request) tag (session/group-name request) key-name (format "%s_%s_key" tag id)] (ssh-key/generate-key hadoop-user :comment key-name) (ssh-key/record-public-key hadoop-user)))) (def-phase-fn authorize-tag "configures all nodes to accept passwordless ssh requests from the node with the supplied tag." [master-tag] (let [tag (name master-tag)] (authorize-groups [hadoop-user] {tag [hadoop-user]}))) ;; ### Installation ;; ;; `url` points to Cloudera's installation of Hadoop. Future ;; iterations of this crate will support the default apache build. ;; ;; TODO -- support switching between cloudera and regular. Regular, we ;; should give a version -- cloudera, it doesn't really mean much. (defn url "Download URL for the Cloudera CDH3 distribution of Hadoop, generated for the supplied version." [version] (case version :cloudera (format "http://archive.cloudera.com/cdh/3/hadoop-%s-cdh3u0.tar.gz" default-version) :apache (format "http://www.apache.org/dist/hadoop/core/hadoop-%s/hadoop-%s.tar.gz" default-version default-version))) (def-phase-fn install "First phase to be called when configuring a hadoop cluster. This phase creates a common hadoop user, and downloads and unpacks the default Cloudera hadoop distribution." [build] (let [url (url build)] create-hadoop-user (remote-directory/remote-directory hadoop-home :url url :unpack :tar :tar-options "xz" :owner hadoop-user :group hadoop-user))) ;; ### Configuration ;; ;; Hadoop has three main configuration files, each of which are a ;; series of key-value pairs, stored as XML files. Before cluster ;; configuration, we need some way to pretty-print human readable XML ;; representing the configuration properties that we'll store in a ;; clojure map. (defn ppxml "Accepts an XML string with no newline formatting and returns the same XML with pretty-print formatting, as described by PI:NAME:<NAME>END_PI in [this post](http://goo.gl/Y9OVO)." [xml-str] (let [in (StreamSource. (StringReader. xml-str)) out (StreamResult. (StringWriter.)) transformer (.newTransformer (TransformerFactory/newInstance))] (doseq [[prop val] {OutputKeys/INDENT "yes" OutputKeys/METHOD "xml" "{http://xml.apache.org/xslt}indent-amount" "2"}] (.setOutputProperty transformer prop val)) (.transform transformer in out) (str (.getWriter out)))) (defn property->xml "Returns a nested sequence representing the XML for a hadoop configuration property. if `final?` is true, `<final>true</final>` is added to the XML entry, preventing any hadoop job from overriding the property." [property final?] [:property (filter identity [[:name {} (name (key property))] [:value {} (val property)] (when final? [:final {} "true"])])]) (declare final-properties) (defn properties->xml "Converts a map of [property value] entries into a string of XML with pretty-print formatting." [properties] (ppxml (with-out-str (prxml/prxml [:decl! {:version "1.0"}] [:configuration (map #(property->xml % (final-properties (key %))) properties)])))) ;; ### Sane Defaults ;; ;; As mentioned before, Hadoop configuration can be a bit ;; bewildering. Default values and descriptions of the meaning of each ;; setting can be found here: ;; ;; http://hadoop.apache.org/core/docs/r0.20.0/mapred-default.html ;; http://hadoop.apache.org/core/docs/r0.20.0/hdfs-default.html ;; http://hadoop.apache.org/core/docs/r0.20.0/core-default.html ;; ;; We override a number of these below based on suggestions found in ;; various posts. We'll supply more information on the justification ;; for each of these as we move forward with our dynamic "sane ;; defaults" system. (defn default-properties "Returns a nested map of Hadoop default configuration properties, named according to the 0.20 api." [name-node-ip job-tracker-ip pid-dir log-dir] (let [owner-dir (stevedore/script (~lib/user-home ~hadoop-user)) owner-subdir (partial str owner-dir)] {:hdfs-site {:dfs.data.dir (owner-subdir "/dfs/data") :dfs.name.dir (owner-subdir "/dfs/name") :dfs.datanode.du.reserved 1073741824 :dfs.namenode.handler.count 10 :dfs.permissions.enabled true :dfs.replication 3 :dfs.datanode.max.xcievers 4096} :mapred-site {:tasktracker.http.threads 46 :mapred.local.dir (owner-subdir "/mapred/local") :mapred.system.dir "/hadoop/mapred/system" :mapred.child.java.opts "-Xmx550m" :mapred.job.tracker (format "%s:8021" job-tracker-ip) :mapred.job.tracker.handler.count 10 :mapred.map.tasks.speculative.execution true :mapred.reduce.tasks.speculative.execution false :mapred.reduce.parallel.copies 10 :mapred.reduce.tasks 5 :mapred.submit.replication 10 :mapred.tasktracker.map.tasks.maximum 2 :mapred.tasktracker.reduce.tasks.maximum 1 :mapred.compress.map.output true :mapred.output.compression.type "BLOCK"} :core-site {:fs.checkpoint.dir (owner-subdir "/dfs/secondary") :fs.default.name (format "hdfs://%s:8020" name-node-ip) :fs.trash.interval 1440 :io.file.buffer.size 65536 :hadoop.tmp.dir "/tmp/hadoop" :hadoop.rpc.socket.factory.class.default "org.apache.hadoop.net.StandardSocketFactory" :hadoop.rpc.socket.factory.class.ClientProtocol "" :hadoop.rpc.socket.factory.class.JobSubmissionProtocol "" :io.compression.codecs (str "org.apache.hadoop.io.compress.DefaultCodec," "org.apache.hadoop.io.compress.GzipCodec")} :hadoop-env {:HADOOP_PID_DIR pid-dir :HADOOP_LOG_DIR log-dir :HADOOP_SSH_OPTS "\"-o StrictHostKeyChecking=no\"" :HADOOP_OPTS "\"-Djava.net.preferIPv4Stack=true\""}})) ;; Final properties are properties that can't be overridden during the ;; execution of a job. We're not sure that these are the right ;; properties to lock, as of now -- this will become more clear as we ;; move forward with sane defaults. In the meantime, any suggestions ;; would be much appreciated. (def final-properties #{:dfs.block.size :dfs.data.dir :dfs.datanode.du.reserved :dfs.datanode.handler.count :dfs.hosts :dfs.hosts.exclude :dfs.name.dir :dfs.namenode.handler.count :dfs.permissions :fs.checkpoint.dir :fs.trash.interval :hadoop.tmp.dir :mapred.child.ulimit :mapred.job.tracker.handler.count :mapred.local.dir :mapred.tasktracker.map.tasks.maximum :mapred.tasktracker.reduce.tasks.maximum :tasktracker.http.threads :hadoop.rpc.socket.factory.class.default :hadoop.rpc.socket.factory.class.ClientProtocol :hadoop.rpc.socket.factory.class.JobSubmissionProtocol}) (defmacro with-overwrite "Executes the body with binding remote-file/force-overwrite to true, thus allowing pallet to overwrite files without complaining about MD5 clashes. This is a hack to make overwriting `pallet.action.remote-file/force-overwrite` work in both pallet 0.6.x and pallet 0.7+, since this variable was renamed to *force-overwrite* It threads the session because it needs to play nice with def-phase-fn..." [session & body] (if (ns-resolve 'pallet.action.remote-file 'force-overwrite) `(binding [remote-file/force-overwrite true] (-> ~session ~@body)) `(binding [remote-file/*force-overwrite* true] (-> ~session ~@body)))) (def-phase-fn config-files "Accepts a base directory and a map of [config-filename, property-map] pairs, and augments the supplied request to allow for the creation of each referenced configuration file within the base directory." [config-dir properties] (with-overwrite (for [[filename props] properties] (remote-file/remote-file (format "%s/%s.xml" config-dir (name filename)) :content (properties->xml props) :owner hadoop-user :group hadoop-group)))) (def merge-config (partial merge-with merge)) (defn merge-and-split-config "Merges a set of custom hadoop configuration option maps into the current defaults, and returns a 2-vector where the first item is a map of *-site files, and the second item is a map of exports for `hadoop-env.sh`. If a conflict exists, entries in `new-props` knock out entries in `default-props`." [default-props new-props] (let [prop-map (merge-config default-props new-props) corekey-seq [:core-site :hdfs-site :mapred-site] envkey-seq [:hadoop-env]] (map #(select-keys prop-map %) [corekey-seq envkey-seq]))) (def-phase-fn env-file "Phase that creates the `hadoop-env.sh` file with references to the supplied pid and log dirs. `hadoop-env.sh` will be placed within the supplied config directory." [config-dir env-map] (for [[fname exports] env-map :let [fname (name fname) export-seq (flatten (seq exports))]] (remote-file/remote-file (format "%s/%s.sh" config-dir fname) :content (apply format-exports export-seq)))) ;; We do our development on local machines using `vmfest`, which ;; brought us in context with the next problem. Some clouds -- ;; Amazon's EC2, for example -- require nodes to be configured with ;; private IP addresses. Hadoop is designed for use within private ;; clusters, so this is typically the right choice. Sometimes, ;; however, public IP addresses are preferable, as in a virtual ;; machine setup. ;; ;; Hadoop takes the IP addresses in `fs.default.name`, ;; `mapred.job.tracker` and performs a reverse DNS lookup, tracking ;; each machine by its hostname. If your cluster isn't set up to ;; handle DNS lookup, you might run into some interesting issues. On ;; these VMs, for example, reverse DNS lookups by the virtual machines ;; on each other caused every VM to resolve to the hostname of my home ;; router. This can cause jobs to limp along or fail msyteriously. We ;; have a workaround involved the `/etc/hosts` file planned for a ;; future iteration. (defn get-master-ip "Returns the IP address of a particular type of master node, as defined by tag. IP-type can be `:private` or `:public`. Function logs a warning if more than one master exists." [request ip-type tag] {:pre [(contains? #{:public :private} ip-type)]} (let [[master :as nodes] (session/nodes-in-group request tag) kind (name tag)] (when (> (count nodes) 1) (log/warn (format "There are more than one %s" kind))) (if-not master (log/error (format "There is no %s defined!" kind)) ((case ip-type :private compute/private-ip :public compute/primary-ip) master)))) (def-phase-fn configure "Configures a Hadoop cluster by creating all required default directories, and populating the proper configuration file options. The `properties` parameter must be a map of the form {:core-site {:key val...} :hdfs-site {:key val ...} :mapred-site {:key val ...} :hadoop-env {:export val ...}} No other top-level keys are supported at this time." [ip-type namenode-tag jobtracker-tag properties] (expose-request-as [request] (let [conf-dir (str hadoop-home "/conf") etc-conf-dir (stevedore/script (str (~lib/config-root) "/hadoop")) nn-ip (get-master-ip request ip-type namenode-tag) jt-ip (get-master-ip request ip-type jobtracker-tag) pid-dir (stevedore/script (str (~lib/pid-root) "/hadoop")) log-dir (stevedore/script (str (~lib/log-root) "/hadoop")) defaults (default-properties nn-ip jt-ip pid-dir log-dir) [props env] (merge-and-split-config defaults properties) tmp-dir (get-in properties [:core-site :hadoop.tmp.dir])] (for [path [conf-dir tmp-dir log-dir pid-dir]] (directory/directory path :owner hadoop-user :group hadoop-group :mode "0755")) (file/symbolic-link conf-dir etc-conf-dir) (config-files conf-dir props) (env-file conf-dir env)))) ;; The following script allows for proper transmission of SSH ;; commands, with hadoop's required `JAVA_HOME` property all set. (script/defscript as-user [user & command]) (script/defimpl as-user :default [user & command] (su -s "/bin/bash" ~user -c "\"" (str "export JAVA_HOME=" (~java/java-home) ";") ~@command "\"")) (script/defimpl as-user [#{:yum}] [user & command] ("/sbin/runuser" -s "/bin/bash" - ~user -c ~@command)) ;; Hadoop services, or `roles`, are all run by the `hadoop-daemon.sh` ;; command. Other scripts exist, such as `hadoop-daemons.sh` (for ;; running commands on many nodes at once), but pallet takes over for ;; a good number of these. The following `phase-fn` takes care to only ;; start a hadoop service that's not already running for the `hadoop` ;; user. Future iterations may provide the ability to force some ;; daemon service to restart. (def-phase-fn hadoop-service "Run a Hadoop service" [hadoop-daemon description] (exec-script/exec-checked-script (str "Start Hadoop " description) (~as-user ~hadoop-user ~(stevedore/script (if-not (pipe (jps) (grep "-i" ~hadoop-daemon)) ((str ~hadoop-home "/bin/hadoop-daemon.sh") "start" ~hadoop-daemon)))))) (def-phase-fn hadoop-command "Runs '$ hadoop `args`' on each machine in the request. Command runs as the hadoop user." [& args] (exec-script/exec-checked-script (apply str "hadoop " (interpose " " args)) (~as-user ~hadoop-user (str ~hadoop-home "/bin/hadoop") ~@args))) ;; `format-hdfs` is, effectively, a call to ;; ;; `(hadoop-command "namenode" "-format") ;; ;; that call would only work the first time, however. On subsequent ;;format requests, hadoop tells the user that the namenode has already ;;been formatted, and asks for confirmation. The current version of ;;`format-namenode` sends a default "N" every time. (def-phase-fn format-hdfs "Formats HDFS for the first time. If HDFS has already been formatted, does nothing." [] (exec-script/exec-script (~as-user ~hadoop-user (pipe (echo "N") ((str ~hadoop-home "/bin/hadoop") "namenode" "-format"))))) ;; And, here we are at the end! The following five functions activate ;; each of the five distinct roles that hadoop nodes may take on. (def-phase-fn name-node "Collection of all subphases required for a namenode." [data-dir] format-hdfs (hadoop-service "namenode" "Name Node") (hadoop-command "dfsadmin" "-safemode" "wait") (hadoop-command "fs" "-mkdir" data-dir) (hadoop-command "fs" "-chmod" "+w" data-dir)) (def-phase-fn secondary-name-node [] (hadoop-service "secondarynamenode" "secondary name node")) (def-phase-fn job-tracker [] (hadoop-service "jobtracker" "job tracker")) (def-phase-fn data-node [] (hadoop-service "datanode" "data node")) (def-phase-fn task-tracker [] (hadoop-service "tasktracker" "task tracker")) (def-phase-fn setup-etc-hosts "Adds the ip addresses and host names of all nodes in all the groups in `groups` to the `/etc/hosts` file in this node. :private-ip will use the private ip address of the nodes instead of the public one " [groups & {:keys [private-ip] :as options}] (expose-request-as [session] (let [groups (map name groups) node-name (session/target-name session)] (etc-hosts/hostname node-name) (thread/for-> [group groups] (etc-hosts/hosts-for-group group :private-ip private-ip)) (etc-hosts/hosts))))
[ { "context": "ence 2))\n(println (average 1 3))\n(println (greet \"Bob\"))\n(println (s2dhms 90061))\n(println (dhms2s 1 1 ", "end": 501, "score": 0.9880030155181885, "start": 498, "tag": "NAME", "value": "Bob" } ]
COMP1005/t1/t1.clj
hansolo669/Class
0
(ns t1) (defn -main [& args]) (defn kilometers2miles [d] (* d 0.62137)) (defn circumference [r] (* (* 2 3.1415) r)) (defn average [x y] (/ (+ x y) 2)) (defn greet [name] (str "Hi, " name)) (defn s2dhms [t] [ (int (/ (/ (/ t 60) 60) 24)) (int (mod (/ (/ t 60) 60) 24)) (int (mod (/ t 60) 60)) (int (mod t 60)) ]) (defn dhms2s [d h m s] (+ (* (* (* d 24) 60) 60) (* (* h 60) 60) (* m 60) s)) (println (kilometers2miles 3)) (println (circumference 2)) (println (average 1 3)) (println (greet "Bob")) (println (s2dhms 90061)) (println (dhms2s 1 1 1 1))
7478
(ns t1) (defn -main [& args]) (defn kilometers2miles [d] (* d 0.62137)) (defn circumference [r] (* (* 2 3.1415) r)) (defn average [x y] (/ (+ x y) 2)) (defn greet [name] (str "Hi, " name)) (defn s2dhms [t] [ (int (/ (/ (/ t 60) 60) 24)) (int (mod (/ (/ t 60) 60) 24)) (int (mod (/ t 60) 60)) (int (mod t 60)) ]) (defn dhms2s [d h m s] (+ (* (* (* d 24) 60) 60) (* (* h 60) 60) (* m 60) s)) (println (kilometers2miles 3)) (println (circumference 2)) (println (average 1 3)) (println (greet "<NAME>")) (println (s2dhms 90061)) (println (dhms2s 1 1 1 1))
true
(ns t1) (defn -main [& args]) (defn kilometers2miles [d] (* d 0.62137)) (defn circumference [r] (* (* 2 3.1415) r)) (defn average [x y] (/ (+ x y) 2)) (defn greet [name] (str "Hi, " name)) (defn s2dhms [t] [ (int (/ (/ (/ t 60) 60) 24)) (int (mod (/ (/ t 60) 60) 24)) (int (mod (/ t 60) 60)) (int (mod t 60)) ]) (defn dhms2s [d h m s] (+ (* (* (* d 24) 60) 60) (* (* h 60) 60) (* m 60) s)) (println (kilometers2miles 3)) (println (circumference 2)) (println (average 1 3)) (println (greet "PI:NAME:<NAME>END_PI")) (println (s2dhms 90061)) (println (dhms2s 1 1 1 1))
[ { "context": "; Copyright 2016 David O'Meara\n;\n; Licensed under the Apache License, Version 2.", "end": 30, "score": 0.9998534321784973, "start": 17, "tag": "NAME", "value": "David O'Meara" } ]
src-cljs/ui/coordination.cljs
davidomeara/fnedit
0
; Copyright 2016 David O'Meara ; ; 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 ui.coordination (:require-macros [cljs.core.async.macros :refer [go go-loop]]) (:require [clojure.set :as set] [cljs.core.async :refer [chan <! >! timeout]] [ui.data :as data] [ui.clr :as clr] [ui.debug :as debug] [ui.events :as events] [ui.utils :as utils])) (defn root-path [state] (->> state :root first ((fn [[k v]] k)) :path)) (defn- clj-extension? [name] (let [n (count name)] (if (>= n 4) (= (subs name (- n 4) n) ".clj") false))) (defn load-folder [state root-path channel] (go (swap! state assoc :open-directories (<! (clr/async-eval 'core.fs/remove-deleted-directories (:open-directories @state)))) (swap! state assoc :root (<! (clr/async-eval 'core.fs/root-directory root-path (:open-directories @state)))))) (defn- assoc-clj-validation-warning [s] (assoc-in s [:new-file :validation] "The script must have the extension .clj")) (defn delete-file-dialog [state channel] (go (swap! state assoc-in [:delete-file :caption] "Are you sure you would like to delete this file?") (loop [] (case (-> channel <! first) :yes (let [{:keys [exception]} (<! (clr/async-eval 'core.fs/delete (get-in @state [:opened-file :path])))] (if exception (do (swap! state assoc-in [:delete-file :exception] exception) (recur)) (swap! state dissoc :opened-file))) :no nil (recur))) (swap! state dissoc :delete-file) (<! (load-folder state (root-path @state) channel)))) (defn focus [state] (if (:opened-file state) (assoc-in state [:opened-file :focus] (js/Date.)) state)) (defn swap-focus! [state] (swap! state focus)) (defn evaluate [state to-from-fn] (let [opened (:opened-file state) [from to] (to-from-fn opened) text (:text opened)] (->> text (clr/winforms-sync-eval (root-path state) from to) (data/update-results state) focus))) (defn evaluate-script [state] (evaluate state (fn [opened] [0 (count (:text opened))]))) (defn evaluate-form [state] (evaluate state #(if-let [x (:cursor-selection %)] x [-1 -1]))) (defn cannot-save-file "Displays exception, returns false." [state message channel] (go (swap! state update-in [:save-file] merge {:caption "Cannot save file" :exception message}) (loop [] (case (-> channel <! first) :ok nil (recur))) (swap! state dissoc :save-file) false)) (declare save) (defn save-as "Returns true if success, false if failed or canceled." [state channel] (go (let [{:keys [status result]} (<! (clr/winforms-async-eval 'core.fs/save-as (root-path @state) (if-let [n (get-in @state [:opened-file :name])] n "new.clj")))] (case status :success (do (swap! state update-in [:opened-file] merge result) (save state channel)) :cancel false :exception (<! (cannot-save-file state result channel)) false)))) (defn save "Returns true if success, false if failed or canceled." [state channel] (go (if (get-in @state [:opened-file :path]) (let [{:keys [status result]} (<! (clr/async-eval 'core.fs/save (get-in @state [:opened-file :path]) (get-in @state [:opened-file :text])))] (case status :success (do (swap! state update-in [:opened-file] merge (merge {:dirty? false} result)) (<! (load-folder state (root-path @state) channel)) true) :exception (do (<! (cannot-save-file state result channel)) (save-as state channel)) false)) (save-as state channel)) (swap-focus! state))) (defn close-file? "Returns true if file was closed, false if not." [state channel] (go (if (or (get-in @state [:opened-file :dirty?]) (let [path (get-in @state [:opened-file :path])] (when path (not (<! (clr/async-eval 'core.fs/exists path)))))) (do (swap! state assoc-in [:close-file :caption] "Would you like to save this file before closing it?") (let [result (loop [] (case (-> channel <! first) :yes (if (<! (save state channel)) true (recur)) :no true :cancel false (recur)))] (swap! state dissoc :close-file) result)) true))) (defn open-folder-browser-dialog [state channel] (go (let [{:keys [path cancel exception]} (<! (clr/winforms-async-eval 'core.fs/folder-browser-dialog))] (if exception (do (swap! state assoc-in [:open-root-directory :caption] "Cannot open directory") (loop [] (case (-> channel <! first) :ok nil (recur))) (swap! state dissoc :open-root-directory)) (when path (swap! state assoc :open-directories #{path}) (<! (load-folder state path channel))))) (swap-focus! state))) (defn next-opened-id [state] (:opened-id-count (swap! state update-in [:opened-id-count] inc))) (defn new-file [state channel] (go (when (<! (close-file? state channel)) (swap! state assoc :opened-file {:id (next-opened-id state) :name "untitled" :text "" :dirty? true})) (swap-focus! state))) (defn do-open-file [state channel path] (go (let [{:keys [name text last-write-time exception]} (<! (clr/async-eval 'core.fs/read-all-text path))] (if exception (do (swap! state assoc-in [:open-file :caption] "Cannot open file") (loop [] (case (-> channel <! first) :ok nil (recur))) (swap! state dissoc :open-file)) (when (and path text) (swap! state assoc :opened-file {:id (next-opened-id state) :path path :name name :last-write-time last-write-time :text text})))) (<! (load-folder state (root-path @state) channel)))) (defn open-file [state channel path] (go (when (<! (close-file? state channel)) (if (= (get-in @state [:opened-file :path]) path) (swap! state dissoc :opened-file) (<! (do-open-file state channel path)))))) (defn reload-file [state channel] (go (let [reload-time (<! (clr/async-eval 'core.fs/last-write-time (get-in @state [:opened-file :path]))) opened-time (get-in @state [:opened-file :last-write-time])] (when opened-time (if reload-time (when (> (.getTime reload-time) (.getTime opened-time)) (swap! state assoc-in [:reloaded-file :caption] "The file has been changed outside this editor. Would you like to reload it?") (loop [] (case (-> channel <! first) :yes (let [path (get-in @state [:opened-file :path])] (swap! state dissoc :opened-file) (<! (do-open-file state channel path))) :no (swap! state assoc-in [:opened-file :dirty?] true) (recur))) (swap! state dissoc :reloaded-file) (swap! state assoc-in [:opened-file :last-write-time] reload-time)) (swap! state assoc-in [:opened-file :dirty?] true)))) (<! (load-folder state (root-path @state) channel)))) (defn toggle-open-directory [state channel path] (go (swap! state update-in [:open-directories] utils/toggle path) (<! (load-folder state (root-path @state) channel)))) (defn periodically-send [c v] (go (while true (<! (timeout 2000)) (>! c v)))) (defn set-left-width! [state client-x] (let [actual-client-x (- client-x 4) min-left-width (get-in @state [:splitter :min-left-width]) width (if (< actual-client-x min-left-width) min-left-width client-x)] (swap! state assoc-in [:splitter :left-width] width) true)) (defn splitter-down [state channel] (swap! state assoc-in [:splitter :dragging] true) (go-loop [] (let [[action client-x] (<! channel)] (if (case [(get-in @state [:splitter :dragging]) action] [true :move] (set-left-width! state client-x) [true :up] false true) (recur) (swap! state update-in [:splitter] dissoc :dragging))))) (defn- path-or-name [opened-file] (if-let [path (:path opened-file)] path (:name opened-file))) (defn edit-file-status [state] (str "Editing " (path-or-name (:opened-file state)))) (defn process-main-commands [state channel] (go (while true (let [[cmd arg] (<! channel)] (case cmd ; toolbar :open-root-directory (<! (open-folder-browser-dialog state channel)) :new (<! (new-file state channel)) :delete (<! (delete-file-dialog state channel)) :save (<! (save state channel)) :evaluate-form (swap! state evaluate-form) :evaluate-script (swap! state evaluate-script) ; tree :toggle-open-directory (<! (toggle-open-directory state channel arg)) :open-file (<! (open-file state channel arg)) ; behind the scenes :reload-file (<! (reload-file state channel)) ; file :before-change (swap! state data/shift-results arg) :change (swap! state data/update-text arg) :cursor-selection (swap! state data/update-cursor-selection arg) ; splitter :splitter-down (<! (splitter-down state channel)) :default))))) (defn process-anytime-commands [state ui-channel main-channel] (go (while true (let [[cmd arg] (<! ui-channel)] (swap! state assoc :last-command [cmd arg]) (case cmd ; status :hover (swap! state assoc :hover arg) :unhover (swap! state dissoc :hover) :focus (swap! state assoc :focus arg) :focus-editor (swap! state assoc :focus (edit-file-status @state)) :blur (swap! state dissoc :focus) (>! main-channel [cmd arg])))))) (defn process-commands [state ui-channel] (let [main-channel (chan)] (process-anytime-commands state ui-channel main-channel) (process-main-commands state main-channel) (periodically-send ui-channel [:reload-file])))
113449
; Copyright 2016 <NAME> ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns ui.coordination (:require-macros [cljs.core.async.macros :refer [go go-loop]]) (:require [clojure.set :as set] [cljs.core.async :refer [chan <! >! timeout]] [ui.data :as data] [ui.clr :as clr] [ui.debug :as debug] [ui.events :as events] [ui.utils :as utils])) (defn root-path [state] (->> state :root first ((fn [[k v]] k)) :path)) (defn- clj-extension? [name] (let [n (count name)] (if (>= n 4) (= (subs name (- n 4) n) ".clj") false))) (defn load-folder [state root-path channel] (go (swap! state assoc :open-directories (<! (clr/async-eval 'core.fs/remove-deleted-directories (:open-directories @state)))) (swap! state assoc :root (<! (clr/async-eval 'core.fs/root-directory root-path (:open-directories @state)))))) (defn- assoc-clj-validation-warning [s] (assoc-in s [:new-file :validation] "The script must have the extension .clj")) (defn delete-file-dialog [state channel] (go (swap! state assoc-in [:delete-file :caption] "Are you sure you would like to delete this file?") (loop [] (case (-> channel <! first) :yes (let [{:keys [exception]} (<! (clr/async-eval 'core.fs/delete (get-in @state [:opened-file :path])))] (if exception (do (swap! state assoc-in [:delete-file :exception] exception) (recur)) (swap! state dissoc :opened-file))) :no nil (recur))) (swap! state dissoc :delete-file) (<! (load-folder state (root-path @state) channel)))) (defn focus [state] (if (:opened-file state) (assoc-in state [:opened-file :focus] (js/Date.)) state)) (defn swap-focus! [state] (swap! state focus)) (defn evaluate [state to-from-fn] (let [opened (:opened-file state) [from to] (to-from-fn opened) text (:text opened)] (->> text (clr/winforms-sync-eval (root-path state) from to) (data/update-results state) focus))) (defn evaluate-script [state] (evaluate state (fn [opened] [0 (count (:text opened))]))) (defn evaluate-form [state] (evaluate state #(if-let [x (:cursor-selection %)] x [-1 -1]))) (defn cannot-save-file "Displays exception, returns false." [state message channel] (go (swap! state update-in [:save-file] merge {:caption "Cannot save file" :exception message}) (loop [] (case (-> channel <! first) :ok nil (recur))) (swap! state dissoc :save-file) false)) (declare save) (defn save-as "Returns true if success, false if failed or canceled." [state channel] (go (let [{:keys [status result]} (<! (clr/winforms-async-eval 'core.fs/save-as (root-path @state) (if-let [n (get-in @state [:opened-file :name])] n "new.clj")))] (case status :success (do (swap! state update-in [:opened-file] merge result) (save state channel)) :cancel false :exception (<! (cannot-save-file state result channel)) false)))) (defn save "Returns true if success, false if failed or canceled." [state channel] (go (if (get-in @state [:opened-file :path]) (let [{:keys [status result]} (<! (clr/async-eval 'core.fs/save (get-in @state [:opened-file :path]) (get-in @state [:opened-file :text])))] (case status :success (do (swap! state update-in [:opened-file] merge (merge {:dirty? false} result)) (<! (load-folder state (root-path @state) channel)) true) :exception (do (<! (cannot-save-file state result channel)) (save-as state channel)) false)) (save-as state channel)) (swap-focus! state))) (defn close-file? "Returns true if file was closed, false if not." [state channel] (go (if (or (get-in @state [:opened-file :dirty?]) (let [path (get-in @state [:opened-file :path])] (when path (not (<! (clr/async-eval 'core.fs/exists path)))))) (do (swap! state assoc-in [:close-file :caption] "Would you like to save this file before closing it?") (let [result (loop [] (case (-> channel <! first) :yes (if (<! (save state channel)) true (recur)) :no true :cancel false (recur)))] (swap! state dissoc :close-file) result)) true))) (defn open-folder-browser-dialog [state channel] (go (let [{:keys [path cancel exception]} (<! (clr/winforms-async-eval 'core.fs/folder-browser-dialog))] (if exception (do (swap! state assoc-in [:open-root-directory :caption] "Cannot open directory") (loop [] (case (-> channel <! first) :ok nil (recur))) (swap! state dissoc :open-root-directory)) (when path (swap! state assoc :open-directories #{path}) (<! (load-folder state path channel))))) (swap-focus! state))) (defn next-opened-id [state] (:opened-id-count (swap! state update-in [:opened-id-count] inc))) (defn new-file [state channel] (go (when (<! (close-file? state channel)) (swap! state assoc :opened-file {:id (next-opened-id state) :name "untitled" :text "" :dirty? true})) (swap-focus! state))) (defn do-open-file [state channel path] (go (let [{:keys [name text last-write-time exception]} (<! (clr/async-eval 'core.fs/read-all-text path))] (if exception (do (swap! state assoc-in [:open-file :caption] "Cannot open file") (loop [] (case (-> channel <! first) :ok nil (recur))) (swap! state dissoc :open-file)) (when (and path text) (swap! state assoc :opened-file {:id (next-opened-id state) :path path :name name :last-write-time last-write-time :text text})))) (<! (load-folder state (root-path @state) channel)))) (defn open-file [state channel path] (go (when (<! (close-file? state channel)) (if (= (get-in @state [:opened-file :path]) path) (swap! state dissoc :opened-file) (<! (do-open-file state channel path)))))) (defn reload-file [state channel] (go (let [reload-time (<! (clr/async-eval 'core.fs/last-write-time (get-in @state [:opened-file :path]))) opened-time (get-in @state [:opened-file :last-write-time])] (when opened-time (if reload-time (when (> (.getTime reload-time) (.getTime opened-time)) (swap! state assoc-in [:reloaded-file :caption] "The file has been changed outside this editor. Would you like to reload it?") (loop [] (case (-> channel <! first) :yes (let [path (get-in @state [:opened-file :path])] (swap! state dissoc :opened-file) (<! (do-open-file state channel path))) :no (swap! state assoc-in [:opened-file :dirty?] true) (recur))) (swap! state dissoc :reloaded-file) (swap! state assoc-in [:opened-file :last-write-time] reload-time)) (swap! state assoc-in [:opened-file :dirty?] true)))) (<! (load-folder state (root-path @state) channel)))) (defn toggle-open-directory [state channel path] (go (swap! state update-in [:open-directories] utils/toggle path) (<! (load-folder state (root-path @state) channel)))) (defn periodically-send [c v] (go (while true (<! (timeout 2000)) (>! c v)))) (defn set-left-width! [state client-x] (let [actual-client-x (- client-x 4) min-left-width (get-in @state [:splitter :min-left-width]) width (if (< actual-client-x min-left-width) min-left-width client-x)] (swap! state assoc-in [:splitter :left-width] width) true)) (defn splitter-down [state channel] (swap! state assoc-in [:splitter :dragging] true) (go-loop [] (let [[action client-x] (<! channel)] (if (case [(get-in @state [:splitter :dragging]) action] [true :move] (set-left-width! state client-x) [true :up] false true) (recur) (swap! state update-in [:splitter] dissoc :dragging))))) (defn- path-or-name [opened-file] (if-let [path (:path opened-file)] path (:name opened-file))) (defn edit-file-status [state] (str "Editing " (path-or-name (:opened-file state)))) (defn process-main-commands [state channel] (go (while true (let [[cmd arg] (<! channel)] (case cmd ; toolbar :open-root-directory (<! (open-folder-browser-dialog state channel)) :new (<! (new-file state channel)) :delete (<! (delete-file-dialog state channel)) :save (<! (save state channel)) :evaluate-form (swap! state evaluate-form) :evaluate-script (swap! state evaluate-script) ; tree :toggle-open-directory (<! (toggle-open-directory state channel arg)) :open-file (<! (open-file state channel arg)) ; behind the scenes :reload-file (<! (reload-file state channel)) ; file :before-change (swap! state data/shift-results arg) :change (swap! state data/update-text arg) :cursor-selection (swap! state data/update-cursor-selection arg) ; splitter :splitter-down (<! (splitter-down state channel)) :default))))) (defn process-anytime-commands [state ui-channel main-channel] (go (while true (let [[cmd arg] (<! ui-channel)] (swap! state assoc :last-command [cmd arg]) (case cmd ; status :hover (swap! state assoc :hover arg) :unhover (swap! state dissoc :hover) :focus (swap! state assoc :focus arg) :focus-editor (swap! state assoc :focus (edit-file-status @state)) :blur (swap! state dissoc :focus) (>! main-channel [cmd arg])))))) (defn process-commands [state ui-channel] (let [main-channel (chan)] (process-anytime-commands state ui-channel main-channel) (process-main-commands state main-channel) (periodically-send ui-channel [:reload-file])))
true
; Copyright 2016 PI:NAME:<NAME>END_PI ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns ui.coordination (:require-macros [cljs.core.async.macros :refer [go go-loop]]) (:require [clojure.set :as set] [cljs.core.async :refer [chan <! >! timeout]] [ui.data :as data] [ui.clr :as clr] [ui.debug :as debug] [ui.events :as events] [ui.utils :as utils])) (defn root-path [state] (->> state :root first ((fn [[k v]] k)) :path)) (defn- clj-extension? [name] (let [n (count name)] (if (>= n 4) (= (subs name (- n 4) n) ".clj") false))) (defn load-folder [state root-path channel] (go (swap! state assoc :open-directories (<! (clr/async-eval 'core.fs/remove-deleted-directories (:open-directories @state)))) (swap! state assoc :root (<! (clr/async-eval 'core.fs/root-directory root-path (:open-directories @state)))))) (defn- assoc-clj-validation-warning [s] (assoc-in s [:new-file :validation] "The script must have the extension .clj")) (defn delete-file-dialog [state channel] (go (swap! state assoc-in [:delete-file :caption] "Are you sure you would like to delete this file?") (loop [] (case (-> channel <! first) :yes (let [{:keys [exception]} (<! (clr/async-eval 'core.fs/delete (get-in @state [:opened-file :path])))] (if exception (do (swap! state assoc-in [:delete-file :exception] exception) (recur)) (swap! state dissoc :opened-file))) :no nil (recur))) (swap! state dissoc :delete-file) (<! (load-folder state (root-path @state) channel)))) (defn focus [state] (if (:opened-file state) (assoc-in state [:opened-file :focus] (js/Date.)) state)) (defn swap-focus! [state] (swap! state focus)) (defn evaluate [state to-from-fn] (let [opened (:opened-file state) [from to] (to-from-fn opened) text (:text opened)] (->> text (clr/winforms-sync-eval (root-path state) from to) (data/update-results state) focus))) (defn evaluate-script [state] (evaluate state (fn [opened] [0 (count (:text opened))]))) (defn evaluate-form [state] (evaluate state #(if-let [x (:cursor-selection %)] x [-1 -1]))) (defn cannot-save-file "Displays exception, returns false." [state message channel] (go (swap! state update-in [:save-file] merge {:caption "Cannot save file" :exception message}) (loop [] (case (-> channel <! first) :ok nil (recur))) (swap! state dissoc :save-file) false)) (declare save) (defn save-as "Returns true if success, false if failed or canceled." [state channel] (go (let [{:keys [status result]} (<! (clr/winforms-async-eval 'core.fs/save-as (root-path @state) (if-let [n (get-in @state [:opened-file :name])] n "new.clj")))] (case status :success (do (swap! state update-in [:opened-file] merge result) (save state channel)) :cancel false :exception (<! (cannot-save-file state result channel)) false)))) (defn save "Returns true if success, false if failed or canceled." [state channel] (go (if (get-in @state [:opened-file :path]) (let [{:keys [status result]} (<! (clr/async-eval 'core.fs/save (get-in @state [:opened-file :path]) (get-in @state [:opened-file :text])))] (case status :success (do (swap! state update-in [:opened-file] merge (merge {:dirty? false} result)) (<! (load-folder state (root-path @state) channel)) true) :exception (do (<! (cannot-save-file state result channel)) (save-as state channel)) false)) (save-as state channel)) (swap-focus! state))) (defn close-file? "Returns true if file was closed, false if not." [state channel] (go (if (or (get-in @state [:opened-file :dirty?]) (let [path (get-in @state [:opened-file :path])] (when path (not (<! (clr/async-eval 'core.fs/exists path)))))) (do (swap! state assoc-in [:close-file :caption] "Would you like to save this file before closing it?") (let [result (loop [] (case (-> channel <! first) :yes (if (<! (save state channel)) true (recur)) :no true :cancel false (recur)))] (swap! state dissoc :close-file) result)) true))) (defn open-folder-browser-dialog [state channel] (go (let [{:keys [path cancel exception]} (<! (clr/winforms-async-eval 'core.fs/folder-browser-dialog))] (if exception (do (swap! state assoc-in [:open-root-directory :caption] "Cannot open directory") (loop [] (case (-> channel <! first) :ok nil (recur))) (swap! state dissoc :open-root-directory)) (when path (swap! state assoc :open-directories #{path}) (<! (load-folder state path channel))))) (swap-focus! state))) (defn next-opened-id [state] (:opened-id-count (swap! state update-in [:opened-id-count] inc))) (defn new-file [state channel] (go (when (<! (close-file? state channel)) (swap! state assoc :opened-file {:id (next-opened-id state) :name "untitled" :text "" :dirty? true})) (swap-focus! state))) (defn do-open-file [state channel path] (go (let [{:keys [name text last-write-time exception]} (<! (clr/async-eval 'core.fs/read-all-text path))] (if exception (do (swap! state assoc-in [:open-file :caption] "Cannot open file") (loop [] (case (-> channel <! first) :ok nil (recur))) (swap! state dissoc :open-file)) (when (and path text) (swap! state assoc :opened-file {:id (next-opened-id state) :path path :name name :last-write-time last-write-time :text text})))) (<! (load-folder state (root-path @state) channel)))) (defn open-file [state channel path] (go (when (<! (close-file? state channel)) (if (= (get-in @state [:opened-file :path]) path) (swap! state dissoc :opened-file) (<! (do-open-file state channel path)))))) (defn reload-file [state channel] (go (let [reload-time (<! (clr/async-eval 'core.fs/last-write-time (get-in @state [:opened-file :path]))) opened-time (get-in @state [:opened-file :last-write-time])] (when opened-time (if reload-time (when (> (.getTime reload-time) (.getTime opened-time)) (swap! state assoc-in [:reloaded-file :caption] "The file has been changed outside this editor. Would you like to reload it?") (loop [] (case (-> channel <! first) :yes (let [path (get-in @state [:opened-file :path])] (swap! state dissoc :opened-file) (<! (do-open-file state channel path))) :no (swap! state assoc-in [:opened-file :dirty?] true) (recur))) (swap! state dissoc :reloaded-file) (swap! state assoc-in [:opened-file :last-write-time] reload-time)) (swap! state assoc-in [:opened-file :dirty?] true)))) (<! (load-folder state (root-path @state) channel)))) (defn toggle-open-directory [state channel path] (go (swap! state update-in [:open-directories] utils/toggle path) (<! (load-folder state (root-path @state) channel)))) (defn periodically-send [c v] (go (while true (<! (timeout 2000)) (>! c v)))) (defn set-left-width! [state client-x] (let [actual-client-x (- client-x 4) min-left-width (get-in @state [:splitter :min-left-width]) width (if (< actual-client-x min-left-width) min-left-width client-x)] (swap! state assoc-in [:splitter :left-width] width) true)) (defn splitter-down [state channel] (swap! state assoc-in [:splitter :dragging] true) (go-loop [] (let [[action client-x] (<! channel)] (if (case [(get-in @state [:splitter :dragging]) action] [true :move] (set-left-width! state client-x) [true :up] false true) (recur) (swap! state update-in [:splitter] dissoc :dragging))))) (defn- path-or-name [opened-file] (if-let [path (:path opened-file)] path (:name opened-file))) (defn edit-file-status [state] (str "Editing " (path-or-name (:opened-file state)))) (defn process-main-commands [state channel] (go (while true (let [[cmd arg] (<! channel)] (case cmd ; toolbar :open-root-directory (<! (open-folder-browser-dialog state channel)) :new (<! (new-file state channel)) :delete (<! (delete-file-dialog state channel)) :save (<! (save state channel)) :evaluate-form (swap! state evaluate-form) :evaluate-script (swap! state evaluate-script) ; tree :toggle-open-directory (<! (toggle-open-directory state channel arg)) :open-file (<! (open-file state channel arg)) ; behind the scenes :reload-file (<! (reload-file state channel)) ; file :before-change (swap! state data/shift-results arg) :change (swap! state data/update-text arg) :cursor-selection (swap! state data/update-cursor-selection arg) ; splitter :splitter-down (<! (splitter-down state channel)) :default))))) (defn process-anytime-commands [state ui-channel main-channel] (go (while true (let [[cmd arg] (<! ui-channel)] (swap! state assoc :last-command [cmd arg]) (case cmd ; status :hover (swap! state assoc :hover arg) :unhover (swap! state dissoc :hover) :focus (swap! state assoc :focus arg) :focus-editor (swap! state assoc :focus (edit-file-status @state)) :blur (swap! state dissoc :focus) (>! main-channel [cmd arg])))))) (defn process-commands [state ui-channel] (let [main-channel (chan)] (process-anytime-commands state ui-channel main-channel) (process-main-commands state main-channel) (periodically-send ui-channel [:reload-file])))
[ { "context": "[service-id service-context]]\n [robert.hooke :as rh]\n [slingshot.slingshot :refer [", "end": 3133, "score": 0.5941591858863831, "start": 3128, "tag": "NAME", "value": "hooke" } ]
src/puppetlabs/puppetdb/cli/services.clj
grimradical/puppetdb
0
(ns puppetlabs.puppetdb.cli.services "Main entrypoint PuppetDB consists of several, cooperating components: * Command processing PuppetDB uses a CQRS pattern for making changes to its domain objects (facts, catalogs, etc). Instead of simply submitting data to PuppetDB and having it figure out the intent, the intent needs to explicitly be codified as part of the operation. This is known as a \"command\" (e.g. \"replace the current facts for node X\"). Commands are processed asynchronously, however we try to do our best to ensure that once a command has been accepted, it will eventually be executed. Ordering is also preserved. To do this, all incoming commands are placed in a message queue which the command processing subsystem reads from in FIFO order. Refer to `puppetlabs.puppetdb.command` for more details. * Message queue We use an embedded instance of AciveMQ to handle queueing duties for the command processing subsystem. The message queue is persistent, and it only allows connections from within the same VM. Refer to `puppetlabs.puppetdb.mq` for more details. * REST interface All interaction with PuppetDB is conducted via its REST API. We embed an instance of Jetty to handle web server duties. Commands that come in via REST are relayed to the message queue. Read-only requests are serviced synchronously. * Database sweeper As catalogs are modified, unused records may accumulate and stale data may linger in the database. We periodically sweep the database, compacting it and performing regular cleanup so we can maintain acceptable performance." (:require [clj-time.core :refer [ago]] [clojure.java.io :as io] [clojure.tools.logging :as log] [compojure.core :as compojure] [overtone.at-at :refer [mk-pool interspaced]] [puppetlabs.kitchensink.core :as kitchensink] [puppetlabs.puppetdb.cheshire :as json] [puppetlabs.puppetdb.command.constants :refer [command-names]] [puppetlabs.puppetdb.command.dlo :as dlo] [puppetlabs.puppetdb.config :as conf] [puppetlabs.puppetdb.http.server :as server] [puppetlabs.puppetdb.jdbc :as jdbc] [puppetlabs.puppetdb.meta.version :as version] [puppetlabs.puppetdb.scf.storage-utils :as sutils] [puppetlabs.puppetdb.mq :as mq] [puppetlabs.puppetdb.query-eng :as qeng] [puppetlabs.puppetdb.query.population :as pop] [puppetlabs.puppetdb.scf.migrate :refer [migrate! indexes!]] [puppetlabs.puppetdb.scf.storage :as scf-store] [puppetlabs.puppetdb.time :refer [to-seconds to-millis parse-period format-period period?]] [puppetlabs.puppetdb.utils :as utils] [puppetlabs.trapperkeeper.core :refer [defservice] :as tk] [puppetlabs.trapperkeeper.services :refer [service-id service-context]] [robert.hooke :as rh] [slingshot.slingshot :refer [throw+ try+]]) (:import [javax.jms ExceptionListener])) (def cli-description "Main PuppetDB daemon") ;; ## Wiring ;; ;; The following functions setup interaction between the main ;; PuppetDB components. (defn auto-expire-nodes! "Expire nodes which haven't had any activity (catalog/fact submission) for more than `node-ttl`." [node-ttl db] {:pre [(map? db) (period? node-ttl)]} (try (kitchensink/demarcate (format "sweep of stale nodes (threshold: %s)" (format-period node-ttl)) (jdbc/with-transacted-connection db (doseq [node (scf-store/stale-nodes (ago node-ttl))] (log/infof "Auto-expiring node %s" node) (scf-store/expire-node! node)))) (catch Exception e (log/error e "Error while deactivating stale nodes")))) (defn purge-nodes! "Delete nodes which have been *deactivated or expired* longer than `node-purge-ttl`." [node-purge-ttl db] {:pre [(map? db) (period? node-purge-ttl)]} (try (kitchensink/demarcate (format "purge deactivated and expired nodes (threshold: %s)" (format-period node-purge-ttl)) (jdbc/with-transacted-connection db (scf-store/purge-deactivated-and-expired-nodes! (ago node-purge-ttl)))) (catch Exception e (log/error e "Error while purging deactivated and expired nodes")))) (defn sweep-reports! "Delete reports which are older than than `report-ttl`." [report-ttl db] {:pre [(map? db) (period? report-ttl)]} (try (kitchensink/demarcate (format "sweep of stale reports (threshold: %s)" (format-period report-ttl)) (jdbc/with-transacted-connection db (scf-store/delete-reports-older-than! (ago report-ttl)))) (catch Exception e (log/error e "Error while sweeping reports")))) (defn compress-dlo! "Compresses discarded message which are older than `dlo-compression-threshold`." [dlo dlo-compression-threshold] (try (kitchensink/demarcate (format "compression of discarded messages (threshold: %s)" (format-period dlo-compression-threshold)) (dlo/compress! dlo dlo-compression-threshold)) (catch Exception e (log/error e "Error while compressing discarded messages")))) (defn garbage-collect! "Perform garbage collection on `db`, which means deleting any orphaned data. This basically just wraps the corresponding scf.storage function with some logging and other ceremony. Exceptions are logged but otherwise ignored." [db] {:pre [(map? db)]} (try (kitchensink/demarcate "database garbage collection" (scf-store/garbage-collect! db)) (catch Exception e (log/error e "Error during garbage collection")))) (defn maybe-check-for-updates [config read-db] (if (conf/foss? config) (-> config conf/update-server (version/check-for-updates! read-db)) (log/debug "Skipping update check on Puppet Enterprise"))) (defn shutdown-mq "Explicitly shut down the queue `broker`" [{:keys [broker mq-factory mq-connection]}] (when broker (log/info "Shutting down the messsage queues.") (mq/stop-broker! broker))) (defn stop-puppetdb "Shuts down PuppetDB, releasing resources when possible.  If this is not a normal shutdown, emergency? must be set, which currently just produces a fatal level level log message, instead of info." [context] (log/info "Shutdown request received; puppetdb exiting.") (shutdown-mq context) (when-let [ds (get-in context [:shared-globals :scf-write-db :datasource])] (.close ds)) (when-let [ds (get-in context [:shared-globals :scf-read-db :datasource])] (.close ds)) context) (defn- transfer-old-messages! [mq-endpoint] (let [[pending exists?] (try+ [(mq/queue-size "localhost" "com.puppetlabs.puppetdb.commands") true] (catch [:type ::mq/queue-not-found] ex [0 false]))] (when (pos? pending) (log/infof "Transferring %d commands from legacy queue" pending) (let [n (mq/transfer-messages! "localhost" "com.puppetlabs.puppetdb.commands" mq-endpoint)] (log/infof "Transferred %d commands from legacy queue" n))) (when exists? (mq/remove-queue! "localhost" "com.puppetlabs.puppetdb.commands") (log/info "Removed legacy queue")))) (defn initialize-schema "Ensure the database is migrated to the latest version, and warn if it's deprecated, log and exit if it's unsupported." [db-conn-pool config] (jdbc/with-db-connection db-conn-pool (scf-store/validate-database-version #(System/exit 1)) @sutils/db-metadata (migrate! db-conn-pool) (indexes! config))) (defn init-with-db "All initialization operations needing a database connection should happen here. This function creates a connection pool using `write-db-config` that will hang until it is able to make a connection to the database. This covers the case of the database not being fully started when PuppetDB starts. This connection pool will be opened and closed within the body of this function." [write-db-config config] (with-open [init-db-pool (jdbc/make-connection-pool (assoc write-db-config ;; Block waiting to grab a connection :connection-timeout 0 ;; Only allocate connections when needed :pool-availability-threshold 0))] (let [db-pool-map {:datasource init-db-pool}] (initialize-schema db-pool-map config)))) (defn start-puppetdb [context config service get-registered-endpoints] {:pre [(map? context) (map? config)] :post [(map? %) (every? (partial contains? %) [:broker])]} (let [{:keys [global jetty database read-database puppetdb command-processing]} config {:keys [vardir]} global {:keys [gc-interval dlo-compression-interval node-ttl node-purge-ttl report-ttl]} database {:keys [dlo-compression-threshold]} command-processing {:keys [disable-update-checking]} puppetdb write-db (jdbc/pooled-datasource database) read-db (jdbc/pooled-datasource (assoc read-database :read-only? true)) discard-dir (io/file (conf/mq-discard-dir config))] (when-let [v (version/version)] (log/infof "PuppetDB version %s" v)) (init-with-db database config) (pop/initialize-metrics write-db) (when (.exists discard-dir) (dlo/create-metrics-for-dlo! discard-dir)) (let [broker (try (log/info "Starting broker") (mq/build-and-start-broker! "localhost" (conf/mq-dir config) command-processing) (catch java.io.EOFException e (log/error "EOF Exception caught during broker start, this " "might be due to KahaDB corruption. Consult the " "PuppetDB troubleshooting guide.") (throw e))) globals {:scf-read-db read-db :scf-write-db write-db}] (transfer-old-messages! (conf/mq-endpoint config)) (when-not disable-update-checking (maybe-check-for-updates config read-db)) ;; Pretty much this helper just knows our job-pool and gc-interval (let [job-pool (mk-pool) gc-interval-millis (to-millis gc-interval) dlo-compression-interval-millis (to-millis dlo-compression-interval) seconds-pos? (comp pos? to-seconds) db-maintenance-tasks (fn [] (do (when (seconds-pos? node-ttl) (auto-expire-nodes! node-ttl write-db)) (when (seconds-pos? node-purge-ttl) (purge-nodes! node-purge-ttl write-db)) (when (seconds-pos? report-ttl) (sweep-reports! report-ttl write-db)) ;; Order is important here to ensure ;; anything referencing an env or resource ;; param is purged first (garbage-collect! write-db)))] (when (pos? gc-interval-millis) ;; Run database maintenance tasks seqentially to avoid ;; competition. Each task must handle its own errors. (interspaced gc-interval-millis db-maintenance-tasks job-pool)) (when (pos? dlo-compression-interval-millis) (interspaced dlo-compression-interval-millis #(compress-dlo! dlo-compression-threshold discard-dir) job-pool))) (assoc context :broker broker :shared-globals globals)))) (defprotocol PuppetDBServer (shared-globals [this]) (set-url-prefix [this url-prefix]) (query [this query-obj version query-expr paging-options row-callback-fn] "Call `row-callback-fn' for matching rows. The `paging-options' should be a map containing :order_by, :offset, and/or :limit.")) (defservice puppetdb-service "Defines a trapperkeeper service for PuppetDB; this service is responsible for initializing all of the PuppetDB subsystems and registering shutdown hooks that trapperkeeper will call on exit." PuppetDBServer [[:DefaultedConfig get-config] [:WebroutingService add-ring-handler get-registered-endpoints]] (init [this context] (assoc context :url-prefix (atom nil))) (start [this context] (start-puppetdb context (get-config) this get-registered-endpoints)) (stop [this context] (stop-puppetdb context)) (set-url-prefix [this url-prefix] (let [old-url-prefix (:url-prefix (service-context this))] (when-not (compare-and-set! old-url-prefix nil url-prefix) (throw+ {:url-prefix old-url-prefix :new-url-prefix url-prefix :type ::url-prefix-already-set} (format "Attempt to set url-prefix to %s when it's already been set to %s" url-prefix @old-url-prefix))))) (shared-globals [this] (:shared-globals (service-context this))) (query [this query-obj version query-expr paging-options row-callback-fn] (let [{db :scf-read-db} (get (service-context this) :shared-globals) url-prefix @(get (service-context this) :url-prefix)] (qeng/stream-query-result query-obj version query-expr paging-options db url-prefix row-callback-fn)))) (def ^{:arglists `([& args]) :doc "Starts PuppetDB as a service via Trapperkeeper. Aguments TK's normal config parsing to do a bit of extra customization."} -main (fn [& args] (rh/add-hook #'puppetlabs.trapperkeeper.config/parse-config-data #'conf/hook-tk-parse-config-data) (apply tk/main args)))
71718
(ns puppetlabs.puppetdb.cli.services "Main entrypoint PuppetDB consists of several, cooperating components: * Command processing PuppetDB uses a CQRS pattern for making changes to its domain objects (facts, catalogs, etc). Instead of simply submitting data to PuppetDB and having it figure out the intent, the intent needs to explicitly be codified as part of the operation. This is known as a \"command\" (e.g. \"replace the current facts for node X\"). Commands are processed asynchronously, however we try to do our best to ensure that once a command has been accepted, it will eventually be executed. Ordering is also preserved. To do this, all incoming commands are placed in a message queue which the command processing subsystem reads from in FIFO order. Refer to `puppetlabs.puppetdb.command` for more details. * Message queue We use an embedded instance of AciveMQ to handle queueing duties for the command processing subsystem. The message queue is persistent, and it only allows connections from within the same VM. Refer to `puppetlabs.puppetdb.mq` for more details. * REST interface All interaction with PuppetDB is conducted via its REST API. We embed an instance of Jetty to handle web server duties. Commands that come in via REST are relayed to the message queue. Read-only requests are serviced synchronously. * Database sweeper As catalogs are modified, unused records may accumulate and stale data may linger in the database. We periodically sweep the database, compacting it and performing regular cleanup so we can maintain acceptable performance." (:require [clj-time.core :refer [ago]] [clojure.java.io :as io] [clojure.tools.logging :as log] [compojure.core :as compojure] [overtone.at-at :refer [mk-pool interspaced]] [puppetlabs.kitchensink.core :as kitchensink] [puppetlabs.puppetdb.cheshire :as json] [puppetlabs.puppetdb.command.constants :refer [command-names]] [puppetlabs.puppetdb.command.dlo :as dlo] [puppetlabs.puppetdb.config :as conf] [puppetlabs.puppetdb.http.server :as server] [puppetlabs.puppetdb.jdbc :as jdbc] [puppetlabs.puppetdb.meta.version :as version] [puppetlabs.puppetdb.scf.storage-utils :as sutils] [puppetlabs.puppetdb.mq :as mq] [puppetlabs.puppetdb.query-eng :as qeng] [puppetlabs.puppetdb.query.population :as pop] [puppetlabs.puppetdb.scf.migrate :refer [migrate! indexes!]] [puppetlabs.puppetdb.scf.storage :as scf-store] [puppetlabs.puppetdb.time :refer [to-seconds to-millis parse-period format-period period?]] [puppetlabs.puppetdb.utils :as utils] [puppetlabs.trapperkeeper.core :refer [defservice] :as tk] [puppetlabs.trapperkeeper.services :refer [service-id service-context]] [robert.<NAME> :as rh] [slingshot.slingshot :refer [throw+ try+]]) (:import [javax.jms ExceptionListener])) (def cli-description "Main PuppetDB daemon") ;; ## Wiring ;; ;; The following functions setup interaction between the main ;; PuppetDB components. (defn auto-expire-nodes! "Expire nodes which haven't had any activity (catalog/fact submission) for more than `node-ttl`." [node-ttl db] {:pre [(map? db) (period? node-ttl)]} (try (kitchensink/demarcate (format "sweep of stale nodes (threshold: %s)" (format-period node-ttl)) (jdbc/with-transacted-connection db (doseq [node (scf-store/stale-nodes (ago node-ttl))] (log/infof "Auto-expiring node %s" node) (scf-store/expire-node! node)))) (catch Exception e (log/error e "Error while deactivating stale nodes")))) (defn purge-nodes! "Delete nodes which have been *deactivated or expired* longer than `node-purge-ttl`." [node-purge-ttl db] {:pre [(map? db) (period? node-purge-ttl)]} (try (kitchensink/demarcate (format "purge deactivated and expired nodes (threshold: %s)" (format-period node-purge-ttl)) (jdbc/with-transacted-connection db (scf-store/purge-deactivated-and-expired-nodes! (ago node-purge-ttl)))) (catch Exception e (log/error e "Error while purging deactivated and expired nodes")))) (defn sweep-reports! "Delete reports which are older than than `report-ttl`." [report-ttl db] {:pre [(map? db) (period? report-ttl)]} (try (kitchensink/demarcate (format "sweep of stale reports (threshold: %s)" (format-period report-ttl)) (jdbc/with-transacted-connection db (scf-store/delete-reports-older-than! (ago report-ttl)))) (catch Exception e (log/error e "Error while sweeping reports")))) (defn compress-dlo! "Compresses discarded message which are older than `dlo-compression-threshold`." [dlo dlo-compression-threshold] (try (kitchensink/demarcate (format "compression of discarded messages (threshold: %s)" (format-period dlo-compression-threshold)) (dlo/compress! dlo dlo-compression-threshold)) (catch Exception e (log/error e "Error while compressing discarded messages")))) (defn garbage-collect! "Perform garbage collection on `db`, which means deleting any orphaned data. This basically just wraps the corresponding scf.storage function with some logging and other ceremony. Exceptions are logged but otherwise ignored." [db] {:pre [(map? db)]} (try (kitchensink/demarcate "database garbage collection" (scf-store/garbage-collect! db)) (catch Exception e (log/error e "Error during garbage collection")))) (defn maybe-check-for-updates [config read-db] (if (conf/foss? config) (-> config conf/update-server (version/check-for-updates! read-db)) (log/debug "Skipping update check on Puppet Enterprise"))) (defn shutdown-mq "Explicitly shut down the queue `broker`" [{:keys [broker mq-factory mq-connection]}] (when broker (log/info "Shutting down the messsage queues.") (mq/stop-broker! broker))) (defn stop-puppetdb "Shuts down PuppetDB, releasing resources when possible.  If this is not a normal shutdown, emergency? must be set, which currently just produces a fatal level level log message, instead of info." [context] (log/info "Shutdown request received; puppetdb exiting.") (shutdown-mq context) (when-let [ds (get-in context [:shared-globals :scf-write-db :datasource])] (.close ds)) (when-let [ds (get-in context [:shared-globals :scf-read-db :datasource])] (.close ds)) context) (defn- transfer-old-messages! [mq-endpoint] (let [[pending exists?] (try+ [(mq/queue-size "localhost" "com.puppetlabs.puppetdb.commands") true] (catch [:type ::mq/queue-not-found] ex [0 false]))] (when (pos? pending) (log/infof "Transferring %d commands from legacy queue" pending) (let [n (mq/transfer-messages! "localhost" "com.puppetlabs.puppetdb.commands" mq-endpoint)] (log/infof "Transferred %d commands from legacy queue" n))) (when exists? (mq/remove-queue! "localhost" "com.puppetlabs.puppetdb.commands") (log/info "Removed legacy queue")))) (defn initialize-schema "Ensure the database is migrated to the latest version, and warn if it's deprecated, log and exit if it's unsupported." [db-conn-pool config] (jdbc/with-db-connection db-conn-pool (scf-store/validate-database-version #(System/exit 1)) @sutils/db-metadata (migrate! db-conn-pool) (indexes! config))) (defn init-with-db "All initialization operations needing a database connection should happen here. This function creates a connection pool using `write-db-config` that will hang until it is able to make a connection to the database. This covers the case of the database not being fully started when PuppetDB starts. This connection pool will be opened and closed within the body of this function." [write-db-config config] (with-open [init-db-pool (jdbc/make-connection-pool (assoc write-db-config ;; Block waiting to grab a connection :connection-timeout 0 ;; Only allocate connections when needed :pool-availability-threshold 0))] (let [db-pool-map {:datasource init-db-pool}] (initialize-schema db-pool-map config)))) (defn start-puppetdb [context config service get-registered-endpoints] {:pre [(map? context) (map? config)] :post [(map? %) (every? (partial contains? %) [:broker])]} (let [{:keys [global jetty database read-database puppetdb command-processing]} config {:keys [vardir]} global {:keys [gc-interval dlo-compression-interval node-ttl node-purge-ttl report-ttl]} database {:keys [dlo-compression-threshold]} command-processing {:keys [disable-update-checking]} puppetdb write-db (jdbc/pooled-datasource database) read-db (jdbc/pooled-datasource (assoc read-database :read-only? true)) discard-dir (io/file (conf/mq-discard-dir config))] (when-let [v (version/version)] (log/infof "PuppetDB version %s" v)) (init-with-db database config) (pop/initialize-metrics write-db) (when (.exists discard-dir) (dlo/create-metrics-for-dlo! discard-dir)) (let [broker (try (log/info "Starting broker") (mq/build-and-start-broker! "localhost" (conf/mq-dir config) command-processing) (catch java.io.EOFException e (log/error "EOF Exception caught during broker start, this " "might be due to KahaDB corruption. Consult the " "PuppetDB troubleshooting guide.") (throw e))) globals {:scf-read-db read-db :scf-write-db write-db}] (transfer-old-messages! (conf/mq-endpoint config)) (when-not disable-update-checking (maybe-check-for-updates config read-db)) ;; Pretty much this helper just knows our job-pool and gc-interval (let [job-pool (mk-pool) gc-interval-millis (to-millis gc-interval) dlo-compression-interval-millis (to-millis dlo-compression-interval) seconds-pos? (comp pos? to-seconds) db-maintenance-tasks (fn [] (do (when (seconds-pos? node-ttl) (auto-expire-nodes! node-ttl write-db)) (when (seconds-pos? node-purge-ttl) (purge-nodes! node-purge-ttl write-db)) (when (seconds-pos? report-ttl) (sweep-reports! report-ttl write-db)) ;; Order is important here to ensure ;; anything referencing an env or resource ;; param is purged first (garbage-collect! write-db)))] (when (pos? gc-interval-millis) ;; Run database maintenance tasks seqentially to avoid ;; competition. Each task must handle its own errors. (interspaced gc-interval-millis db-maintenance-tasks job-pool)) (when (pos? dlo-compression-interval-millis) (interspaced dlo-compression-interval-millis #(compress-dlo! dlo-compression-threshold discard-dir) job-pool))) (assoc context :broker broker :shared-globals globals)))) (defprotocol PuppetDBServer (shared-globals [this]) (set-url-prefix [this url-prefix]) (query [this query-obj version query-expr paging-options row-callback-fn] "Call `row-callback-fn' for matching rows. The `paging-options' should be a map containing :order_by, :offset, and/or :limit.")) (defservice puppetdb-service "Defines a trapperkeeper service for PuppetDB; this service is responsible for initializing all of the PuppetDB subsystems and registering shutdown hooks that trapperkeeper will call on exit." PuppetDBServer [[:DefaultedConfig get-config] [:WebroutingService add-ring-handler get-registered-endpoints]] (init [this context] (assoc context :url-prefix (atom nil))) (start [this context] (start-puppetdb context (get-config) this get-registered-endpoints)) (stop [this context] (stop-puppetdb context)) (set-url-prefix [this url-prefix] (let [old-url-prefix (:url-prefix (service-context this))] (when-not (compare-and-set! old-url-prefix nil url-prefix) (throw+ {:url-prefix old-url-prefix :new-url-prefix url-prefix :type ::url-prefix-already-set} (format "Attempt to set url-prefix to %s when it's already been set to %s" url-prefix @old-url-prefix))))) (shared-globals [this] (:shared-globals (service-context this))) (query [this query-obj version query-expr paging-options row-callback-fn] (let [{db :scf-read-db} (get (service-context this) :shared-globals) url-prefix @(get (service-context this) :url-prefix)] (qeng/stream-query-result query-obj version query-expr paging-options db url-prefix row-callback-fn)))) (def ^{:arglists `([& args]) :doc "Starts PuppetDB as a service via Trapperkeeper. Aguments TK's normal config parsing to do a bit of extra customization."} -main (fn [& args] (rh/add-hook #'puppetlabs.trapperkeeper.config/parse-config-data #'conf/hook-tk-parse-config-data) (apply tk/main args)))
true
(ns puppetlabs.puppetdb.cli.services "Main entrypoint PuppetDB consists of several, cooperating components: * Command processing PuppetDB uses a CQRS pattern for making changes to its domain objects (facts, catalogs, etc). Instead of simply submitting data to PuppetDB and having it figure out the intent, the intent needs to explicitly be codified as part of the operation. This is known as a \"command\" (e.g. \"replace the current facts for node X\"). Commands are processed asynchronously, however we try to do our best to ensure that once a command has been accepted, it will eventually be executed. Ordering is also preserved. To do this, all incoming commands are placed in a message queue which the command processing subsystem reads from in FIFO order. Refer to `puppetlabs.puppetdb.command` for more details. * Message queue We use an embedded instance of AciveMQ to handle queueing duties for the command processing subsystem. The message queue is persistent, and it only allows connections from within the same VM. Refer to `puppetlabs.puppetdb.mq` for more details. * REST interface All interaction with PuppetDB is conducted via its REST API. We embed an instance of Jetty to handle web server duties. Commands that come in via REST are relayed to the message queue. Read-only requests are serviced synchronously. * Database sweeper As catalogs are modified, unused records may accumulate and stale data may linger in the database. We periodically sweep the database, compacting it and performing regular cleanup so we can maintain acceptable performance." (:require [clj-time.core :refer [ago]] [clojure.java.io :as io] [clojure.tools.logging :as log] [compojure.core :as compojure] [overtone.at-at :refer [mk-pool interspaced]] [puppetlabs.kitchensink.core :as kitchensink] [puppetlabs.puppetdb.cheshire :as json] [puppetlabs.puppetdb.command.constants :refer [command-names]] [puppetlabs.puppetdb.command.dlo :as dlo] [puppetlabs.puppetdb.config :as conf] [puppetlabs.puppetdb.http.server :as server] [puppetlabs.puppetdb.jdbc :as jdbc] [puppetlabs.puppetdb.meta.version :as version] [puppetlabs.puppetdb.scf.storage-utils :as sutils] [puppetlabs.puppetdb.mq :as mq] [puppetlabs.puppetdb.query-eng :as qeng] [puppetlabs.puppetdb.query.population :as pop] [puppetlabs.puppetdb.scf.migrate :refer [migrate! indexes!]] [puppetlabs.puppetdb.scf.storage :as scf-store] [puppetlabs.puppetdb.time :refer [to-seconds to-millis parse-period format-period period?]] [puppetlabs.puppetdb.utils :as utils] [puppetlabs.trapperkeeper.core :refer [defservice] :as tk] [puppetlabs.trapperkeeper.services :refer [service-id service-context]] [robert.PI:NAME:<NAME>END_PI :as rh] [slingshot.slingshot :refer [throw+ try+]]) (:import [javax.jms ExceptionListener])) (def cli-description "Main PuppetDB daemon") ;; ## Wiring ;; ;; The following functions setup interaction between the main ;; PuppetDB components. (defn auto-expire-nodes! "Expire nodes which haven't had any activity (catalog/fact submission) for more than `node-ttl`." [node-ttl db] {:pre [(map? db) (period? node-ttl)]} (try (kitchensink/demarcate (format "sweep of stale nodes (threshold: %s)" (format-period node-ttl)) (jdbc/with-transacted-connection db (doseq [node (scf-store/stale-nodes (ago node-ttl))] (log/infof "Auto-expiring node %s" node) (scf-store/expire-node! node)))) (catch Exception e (log/error e "Error while deactivating stale nodes")))) (defn purge-nodes! "Delete nodes which have been *deactivated or expired* longer than `node-purge-ttl`." [node-purge-ttl db] {:pre [(map? db) (period? node-purge-ttl)]} (try (kitchensink/demarcate (format "purge deactivated and expired nodes (threshold: %s)" (format-period node-purge-ttl)) (jdbc/with-transacted-connection db (scf-store/purge-deactivated-and-expired-nodes! (ago node-purge-ttl)))) (catch Exception e (log/error e "Error while purging deactivated and expired nodes")))) (defn sweep-reports! "Delete reports which are older than than `report-ttl`." [report-ttl db] {:pre [(map? db) (period? report-ttl)]} (try (kitchensink/demarcate (format "sweep of stale reports (threshold: %s)" (format-period report-ttl)) (jdbc/with-transacted-connection db (scf-store/delete-reports-older-than! (ago report-ttl)))) (catch Exception e (log/error e "Error while sweeping reports")))) (defn compress-dlo! "Compresses discarded message which are older than `dlo-compression-threshold`." [dlo dlo-compression-threshold] (try (kitchensink/demarcate (format "compression of discarded messages (threshold: %s)" (format-period dlo-compression-threshold)) (dlo/compress! dlo dlo-compression-threshold)) (catch Exception e (log/error e "Error while compressing discarded messages")))) (defn garbage-collect! "Perform garbage collection on `db`, which means deleting any orphaned data. This basically just wraps the corresponding scf.storage function with some logging and other ceremony. Exceptions are logged but otherwise ignored." [db] {:pre [(map? db)]} (try (kitchensink/demarcate "database garbage collection" (scf-store/garbage-collect! db)) (catch Exception e (log/error e "Error during garbage collection")))) (defn maybe-check-for-updates [config read-db] (if (conf/foss? config) (-> config conf/update-server (version/check-for-updates! read-db)) (log/debug "Skipping update check on Puppet Enterprise"))) (defn shutdown-mq "Explicitly shut down the queue `broker`" [{:keys [broker mq-factory mq-connection]}] (when broker (log/info "Shutting down the messsage queues.") (mq/stop-broker! broker))) (defn stop-puppetdb "Shuts down PuppetDB, releasing resources when possible.  If this is not a normal shutdown, emergency? must be set, which currently just produces a fatal level level log message, instead of info." [context] (log/info "Shutdown request received; puppetdb exiting.") (shutdown-mq context) (when-let [ds (get-in context [:shared-globals :scf-write-db :datasource])] (.close ds)) (when-let [ds (get-in context [:shared-globals :scf-read-db :datasource])] (.close ds)) context) (defn- transfer-old-messages! [mq-endpoint] (let [[pending exists?] (try+ [(mq/queue-size "localhost" "com.puppetlabs.puppetdb.commands") true] (catch [:type ::mq/queue-not-found] ex [0 false]))] (when (pos? pending) (log/infof "Transferring %d commands from legacy queue" pending) (let [n (mq/transfer-messages! "localhost" "com.puppetlabs.puppetdb.commands" mq-endpoint)] (log/infof "Transferred %d commands from legacy queue" n))) (when exists? (mq/remove-queue! "localhost" "com.puppetlabs.puppetdb.commands") (log/info "Removed legacy queue")))) (defn initialize-schema "Ensure the database is migrated to the latest version, and warn if it's deprecated, log and exit if it's unsupported." [db-conn-pool config] (jdbc/with-db-connection db-conn-pool (scf-store/validate-database-version #(System/exit 1)) @sutils/db-metadata (migrate! db-conn-pool) (indexes! config))) (defn init-with-db "All initialization operations needing a database connection should happen here. This function creates a connection pool using `write-db-config` that will hang until it is able to make a connection to the database. This covers the case of the database not being fully started when PuppetDB starts. This connection pool will be opened and closed within the body of this function." [write-db-config config] (with-open [init-db-pool (jdbc/make-connection-pool (assoc write-db-config ;; Block waiting to grab a connection :connection-timeout 0 ;; Only allocate connections when needed :pool-availability-threshold 0))] (let [db-pool-map {:datasource init-db-pool}] (initialize-schema db-pool-map config)))) (defn start-puppetdb [context config service get-registered-endpoints] {:pre [(map? context) (map? config)] :post [(map? %) (every? (partial contains? %) [:broker])]} (let [{:keys [global jetty database read-database puppetdb command-processing]} config {:keys [vardir]} global {:keys [gc-interval dlo-compression-interval node-ttl node-purge-ttl report-ttl]} database {:keys [dlo-compression-threshold]} command-processing {:keys [disable-update-checking]} puppetdb write-db (jdbc/pooled-datasource database) read-db (jdbc/pooled-datasource (assoc read-database :read-only? true)) discard-dir (io/file (conf/mq-discard-dir config))] (when-let [v (version/version)] (log/infof "PuppetDB version %s" v)) (init-with-db database config) (pop/initialize-metrics write-db) (when (.exists discard-dir) (dlo/create-metrics-for-dlo! discard-dir)) (let [broker (try (log/info "Starting broker") (mq/build-and-start-broker! "localhost" (conf/mq-dir config) command-processing) (catch java.io.EOFException e (log/error "EOF Exception caught during broker start, this " "might be due to KahaDB corruption. Consult the " "PuppetDB troubleshooting guide.") (throw e))) globals {:scf-read-db read-db :scf-write-db write-db}] (transfer-old-messages! (conf/mq-endpoint config)) (when-not disable-update-checking (maybe-check-for-updates config read-db)) ;; Pretty much this helper just knows our job-pool and gc-interval (let [job-pool (mk-pool) gc-interval-millis (to-millis gc-interval) dlo-compression-interval-millis (to-millis dlo-compression-interval) seconds-pos? (comp pos? to-seconds) db-maintenance-tasks (fn [] (do (when (seconds-pos? node-ttl) (auto-expire-nodes! node-ttl write-db)) (when (seconds-pos? node-purge-ttl) (purge-nodes! node-purge-ttl write-db)) (when (seconds-pos? report-ttl) (sweep-reports! report-ttl write-db)) ;; Order is important here to ensure ;; anything referencing an env or resource ;; param is purged first (garbage-collect! write-db)))] (when (pos? gc-interval-millis) ;; Run database maintenance tasks seqentially to avoid ;; competition. Each task must handle its own errors. (interspaced gc-interval-millis db-maintenance-tasks job-pool)) (when (pos? dlo-compression-interval-millis) (interspaced dlo-compression-interval-millis #(compress-dlo! dlo-compression-threshold discard-dir) job-pool))) (assoc context :broker broker :shared-globals globals)))) (defprotocol PuppetDBServer (shared-globals [this]) (set-url-prefix [this url-prefix]) (query [this query-obj version query-expr paging-options row-callback-fn] "Call `row-callback-fn' for matching rows. The `paging-options' should be a map containing :order_by, :offset, and/or :limit.")) (defservice puppetdb-service "Defines a trapperkeeper service for PuppetDB; this service is responsible for initializing all of the PuppetDB subsystems and registering shutdown hooks that trapperkeeper will call on exit." PuppetDBServer [[:DefaultedConfig get-config] [:WebroutingService add-ring-handler get-registered-endpoints]] (init [this context] (assoc context :url-prefix (atom nil))) (start [this context] (start-puppetdb context (get-config) this get-registered-endpoints)) (stop [this context] (stop-puppetdb context)) (set-url-prefix [this url-prefix] (let [old-url-prefix (:url-prefix (service-context this))] (when-not (compare-and-set! old-url-prefix nil url-prefix) (throw+ {:url-prefix old-url-prefix :new-url-prefix url-prefix :type ::url-prefix-already-set} (format "Attempt to set url-prefix to %s when it's already been set to %s" url-prefix @old-url-prefix))))) (shared-globals [this] (:shared-globals (service-context this))) (query [this query-obj version query-expr paging-options row-callback-fn] (let [{db :scf-read-db} (get (service-context this) :shared-globals) url-prefix @(get (service-context this) :url-prefix)] (qeng/stream-query-result query-obj version query-expr paging-options db url-prefix row-callback-fn)))) (def ^{:arglists `([& args]) :doc "Starts PuppetDB as a service via Trapperkeeper. Aguments TK's normal config parsing to do a bit of extra customization."} -main (fn [& args] (rh/add-hook #'puppetlabs.trapperkeeper.config/parse-config-data #'conf/hook-tk-parse-config-data) (apply tk/main args)))
[ { "context": "{}\n\n \"0\"\n \"nic\"\n \"zero\"\n (number 0)\n\n \"1\"\n \"jeden\"\n \"pojedynczy\"\n (number 1)\n\n \"2\"\n \"dwa\"\n \"pa", "end": 75, "score": 0.6830440759658813, "start": 70, "tag": "NAME", "value": "jeden" }, { "context": "\"nic\"\n \"zero\"\n (number 0)\n\n \"1\"\n \"jeden\"\n \"pojedynczy\"\n (number 1)\n\n \"2\"\n \"dwa\"\n \"para\"\n (number", "end": 88, "score": 0.5631243586540222, "start": 82, "tag": "NAME", "value": "jedync" }, { "context": "dzieści trzy\"\n \"0033\"\n (number 33)\n\n \"14\"\n \"czternaście\"\n (number 14)\n\n \"16\"\n \"szesnaście\"\n (numb", "end": 212, "score": 0.5570495128631592, "start": 207, "tag": "NAME", "value": "terna" }, { "context": "\n\n \"14\"\n \"czternaście\"\n (number 14)\n\n \"16\"\n \"szesnaście\"\n (number 16)\n\n \"17\"\n \"siedemnaście\"\n (number", "end": 253, "score": 0.7536719441413879, "start": 243, "tag": "NAME", "value": "szesnaście" }, { "context": ")\n\n \"16\"\n \"szesnaście\"\n (number 16)\n\n \"17\"\n \"siedemnaście\"\n (number 17)\n\n \"18\"\n \"osiemnaście\"\n (number ", "end": 292, "score": 0.6957926154136658, "start": 280, "tag": "NAME", "value": "siedemnaście" }, { "context": " \"17\"\n \"siedemnaście\"\n (number 17)\n\n \"18\"\n \"osiemnaście\"\n (number 18)\n\n \"1.1\"\n \"1.10\"\n \"01.10\"\n (num", "end": 330, "score": 0.7087898850440979, "start": 321, "tag": "NAME", "value": "iemnaście" } ]
resources/languages/pl/corpus/numbers.clj
guivn/duckling
922
( ; Context map {} "0" "nic" "zero" (number 0) "1" "jeden" "pojedynczy" (number 1) "2" "dwa" "para" (number 2) "33" "trzydzieści trzy" "0033" (number 33) "14" "czternaście" (number 14) "16" "szesnaście" (number 16) "17" "siedemnaście" (number 17) "18" "osiemnaście" (number 18) "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" (number 1200000) "- 1,200,000" "-1200000" "minus 1,200,000" "-1.2M" "-1200K" "-.0012G" (number -1200000) "5 tysięcy" "pięć tysięcy" (number 5000) "sto dwadzieścia dwa" (number 122) "dwieście tysięcy" (number 200000) "dwadzieścia jeden tysięcy i jedenaście" "dwadzieścia jeden tysięcy jedenaście" (number 21011) "siedemset dwadzieścia jeden tysięcy dwanaście" "siedemset dwadzieścia jeden tysięcy i dwanaście" (number 721012) "sześćdziesiąt pięć milionów" (number 65000000) "trzydzieści jeden milionów dwieście pięćdziesiąt sześć tysięcy siedemset dwadzieścia jeden" (number 31256721) "4ty" "czwarty" (ordinal 4) "piętnasta" (number 15) )
64445
( ; Context map {} "0" "nic" "zero" (number 0) "1" "<NAME>" "po<NAME>zy" (number 1) "2" "dwa" "para" (number 2) "33" "trzydzieści trzy" "0033" (number 33) "14" "cz<NAME>ście" (number 14) "16" "<NAME>" (number 16) "17" "<NAME>" (number 17) "18" "os<NAME>" (number 18) "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" (number 1200000) "- 1,200,000" "-1200000" "minus 1,200,000" "-1.2M" "-1200K" "-.0012G" (number -1200000) "5 tysięcy" "pięć tysięcy" (number 5000) "sto dwadzieścia dwa" (number 122) "dwieście tysięcy" (number 200000) "dwadzieścia jeden tysięcy i jedenaście" "dwadzieścia jeden tysięcy jedenaście" (number 21011) "siedemset dwadzieścia jeden tysięcy dwanaście" "siedemset dwadzieścia jeden tysięcy i dwanaście" (number 721012) "sześćdziesiąt pięć milionów" (number 65000000) "trzydzieści jeden milionów dwieście pięćdziesiąt sześć tysięcy siedemset dwadzieścia jeden" (number 31256721) "4ty" "czwarty" (ordinal 4) "piętnasta" (number 15) )
true
( ; Context map {} "0" "nic" "zero" (number 0) "1" "PI:NAME:<NAME>END_PI" "poPI:NAME:<NAME>END_PIzy" (number 1) "2" "dwa" "para" (number 2) "33" "trzydzieści trzy" "0033" (number 33) "14" "czPI:NAME:<NAME>END_PIście" (number 14) "16" "PI:NAME:<NAME>END_PI" (number 16) "17" "PI:NAME:<NAME>END_PI" (number 17) "18" "osPI:NAME:<NAME>END_PI" (number 18) "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" (number 1200000) "- 1,200,000" "-1200000" "minus 1,200,000" "-1.2M" "-1200K" "-.0012G" (number -1200000) "5 tysięcy" "pięć tysięcy" (number 5000) "sto dwadzieścia dwa" (number 122) "dwieście tysięcy" (number 200000) "dwadzieścia jeden tysięcy i jedenaście" "dwadzieścia jeden tysięcy jedenaście" (number 21011) "siedemset dwadzieścia jeden tysięcy dwanaście" "siedemset dwadzieścia jeden tysięcy i dwanaście" (number 721012) "sześćdziesiąt pięć milionów" (number 65000000) "trzydzieści jeden milionów dwieście pięćdziesiąt sześć tysięcy siedemset dwadzieścia jeden" (number 31256721) "4ty" "czwarty" (ordinal 4) "piętnasta" (number 15) )
[ { "context": ":as str]))\n\n(def welcome-help\n (str \"🤖 WELCOME TO DISTRAN HUMAN 🤖\\n\"\n \"* I organize breakfast for every Mon", "end": 381, "score": 0.6581488847732544, "start": 368, "tag": "NAME", "value": "DISTRAN HUMAN" }, { "context": " \"Study the code on [Github](https://github.com/studer-l/breakfastbot)\\n\"\n \"Want to talk to a human?", "end": 912, "score": 0.9952396750450134, "start": 904, "tag": "USERNAME", "value": "studer-l" }, { "context": "stbot)\\n\"\n \"Want to talk to a human? Ask @**Lukas Studer** for help.\"))\n\n(def reactivation-msg\n (str \"🤖 Y", "end": 982, "score": 0.9972947239875793, "start": 970, "tag": "NAME", "value": "Lukas Studer" } ]
src/breakfastbot/handlers/common.clj
studer-l/breakfastbot
0
(ns breakfastbot.handlers.common (:require [breakfastbot.date-utils :refer [next-monday]] [breakfastbot.markdown :as md] [clojure.tools.logging :refer [info debug]] [breakfastbot.handlers.eliza :refer [get-eliza-reply]] [java-time :as jt] [clojure.string :as str])) (def welcome-help (str "🤖 WELCOME TO DISTRAN HUMAN 🤖\n" "* I organize breakfast for every Monday at 9:00\n" "* Attendance is limited to puny humans 🙄\n" "* Every week I choose one member of the team to bring breakfast\n" "* Let me know if you cannot make it\n" "* To learn more, send me the message (in private or in the breakfast " "channel) `@**Breakfast Bot** help`, this is best achieved by typing" " `@Br` and then hitting the `<TAB>` key to complete my name.\n\n" "Study the code on [Github](https://github.com/studer-l/breakfastbot)\n" "Want to talk to a human? Ask @**Lukas Studer** for help.")) (def reactivation-msg (str "🤖 YOU HAVE BEEN REACTIVATED AND" " ARE EXPECTED TO ATTEND BREAKFASTS AGAIN 🤖")) (defn who-brings-answer [names date] (str "Official Bringer(s) of Breakfast on " (jt/format "d.M" date) ": " (str/join " and " (map md/mention names)))) (def answers {:ok-unhappy "Alright 🙄" :ok-happy "Great!" :eliza-reply get-eliza-reply :ack "🤖 ACKNOWLEDGED 🤖" :error-signed-off "ERROR: Already signed off! 😤\nDo you often have your head in the clouds?" :error-no-event "ERROR: No event scheduled for this date.\nDoes this make you feel sad?" :error-no-member "ERROR: Noone by this email is registered! 💣\nIs there anything else I can do for you?" :error-active "ERROR: Already marked as active!" :change-bringer (fn [fullnames] (str "OK 🙄 Breakfast duty relegated to: " (str/join " and " (map md/mention fullnames)))) :cancel (fn [when] (str "BREAKFAST ON " (jt/format when) " CANCELED!")) :welcome (fn [email] (str "🎉🎈 Welcome " (md/mention email) "!! 🎉🎈")) :reactivate reactivation-msg :welcome-help welcome-help :new-bringer "HUMAN! 🤖 You have been chosen to bring breakfast!" :who-brings who-brings-answer}) (defn changed-bringer? "Checks whether result of `db-ops/safe-remove implies a new person is responsible for breakfast" [result] (and (seqable? result) (= (first result) :ok-new-responsible))) (defn change-bringer-reply "Create appropriate (full) reply when changing bringer" [new-bringer] {:direct-reply ((:change-bringer answers) new-bringer) :notification {:who new-bringer :message (:new-bringer answers)} :update true}) (defn try-parse-date [when] (try (jt/local-date "d.M.yyyy" when) (catch Exception ex (info "Date parsing failed for input:" when) (throw (ex-info (str "Could not parse as valid breakfast date: \"" when "\", example format: \"23.4.2018\", must be a monday") {:public true}))))) (defn validate-date [date] (cond (< 5 (jt/time-between (jt/local-date) date :months)) (throw (ex-info (str "The date " (jt/format "d.M.yyyy" date) " is too far in the future!") {:public true})) (neg? (jt/time-between (jt/local-date) date :days)) (throw (ex-info (str "The date " (jt/format "d.M.yyyy" date) " is in the past!") {:public true})) :else date)) (defn person-date-matcher [regex author message] (let [matcher (re-matcher regex message)] (when (.matches matcher) (let [who (.group matcher "who") when (.group matcher "when")] (debug "parson-date-matcher, re-groups = " (re-groups matcher) ", who =" who ", when =" when) {:who (if (or (nil? who) (= who "me")) author who) :when (if-not when (next-monday) (let [date (try-parse-date when)] (validate-date date)))}))))
44448
(ns breakfastbot.handlers.common (:require [breakfastbot.date-utils :refer [next-monday]] [breakfastbot.markdown :as md] [clojure.tools.logging :refer [info debug]] [breakfastbot.handlers.eliza :refer [get-eliza-reply]] [java-time :as jt] [clojure.string :as str])) (def welcome-help (str "🤖 WELCOME TO <NAME> 🤖\n" "* I organize breakfast for every Monday at 9:00\n" "* Attendance is limited to puny humans 🙄\n" "* Every week I choose one member of the team to bring breakfast\n" "* Let me know if you cannot make it\n" "* To learn more, send me the message (in private or in the breakfast " "channel) `@**Breakfast Bot** help`, this is best achieved by typing" " `@Br` and then hitting the `<TAB>` key to complete my name.\n\n" "Study the code on [Github](https://github.com/studer-l/breakfastbot)\n" "Want to talk to a human? Ask @**<NAME>** for help.")) (def reactivation-msg (str "🤖 YOU HAVE BEEN REACTIVATED AND" " ARE EXPECTED TO ATTEND BREAKFASTS AGAIN 🤖")) (defn who-brings-answer [names date] (str "Official Bringer(s) of Breakfast on " (jt/format "d.M" date) ": " (str/join " and " (map md/mention names)))) (def answers {:ok-unhappy "Alright 🙄" :ok-happy "Great!" :eliza-reply get-eliza-reply :ack "🤖 ACKNOWLEDGED 🤖" :error-signed-off "ERROR: Already signed off! 😤\nDo you often have your head in the clouds?" :error-no-event "ERROR: No event scheduled for this date.\nDoes this make you feel sad?" :error-no-member "ERROR: Noone by this email is registered! 💣\nIs there anything else I can do for you?" :error-active "ERROR: Already marked as active!" :change-bringer (fn [fullnames] (str "OK 🙄 Breakfast duty relegated to: " (str/join " and " (map md/mention fullnames)))) :cancel (fn [when] (str "BREAKFAST ON " (jt/format when) " CANCELED!")) :welcome (fn [email] (str "🎉🎈 Welcome " (md/mention email) "!! 🎉🎈")) :reactivate reactivation-msg :welcome-help welcome-help :new-bringer "HUMAN! 🤖 You have been chosen to bring breakfast!" :who-brings who-brings-answer}) (defn changed-bringer? "Checks whether result of `db-ops/safe-remove implies a new person is responsible for breakfast" [result] (and (seqable? result) (= (first result) :ok-new-responsible))) (defn change-bringer-reply "Create appropriate (full) reply when changing bringer" [new-bringer] {:direct-reply ((:change-bringer answers) new-bringer) :notification {:who new-bringer :message (:new-bringer answers)} :update true}) (defn try-parse-date [when] (try (jt/local-date "d.M.yyyy" when) (catch Exception ex (info "Date parsing failed for input:" when) (throw (ex-info (str "Could not parse as valid breakfast date: \"" when "\", example format: \"23.4.2018\", must be a monday") {:public true}))))) (defn validate-date [date] (cond (< 5 (jt/time-between (jt/local-date) date :months)) (throw (ex-info (str "The date " (jt/format "d.M.yyyy" date) " is too far in the future!") {:public true})) (neg? (jt/time-between (jt/local-date) date :days)) (throw (ex-info (str "The date " (jt/format "d.M.yyyy" date) " is in the past!") {:public true})) :else date)) (defn person-date-matcher [regex author message] (let [matcher (re-matcher regex message)] (when (.matches matcher) (let [who (.group matcher "who") when (.group matcher "when")] (debug "parson-date-matcher, re-groups = " (re-groups matcher) ", who =" who ", when =" when) {:who (if (or (nil? who) (= who "me")) author who) :when (if-not when (next-monday) (let [date (try-parse-date when)] (validate-date date)))}))))
true
(ns breakfastbot.handlers.common (:require [breakfastbot.date-utils :refer [next-monday]] [breakfastbot.markdown :as md] [clojure.tools.logging :refer [info debug]] [breakfastbot.handlers.eliza :refer [get-eliza-reply]] [java-time :as jt] [clojure.string :as str])) (def welcome-help (str "🤖 WELCOME TO PI:NAME:<NAME>END_PI 🤖\n" "* I organize breakfast for every Monday at 9:00\n" "* Attendance is limited to puny humans 🙄\n" "* Every week I choose one member of the team to bring breakfast\n" "* Let me know if you cannot make it\n" "* To learn more, send me the message (in private or in the breakfast " "channel) `@**Breakfast Bot** help`, this is best achieved by typing" " `@Br` and then hitting the `<TAB>` key to complete my name.\n\n" "Study the code on [Github](https://github.com/studer-l/breakfastbot)\n" "Want to talk to a human? Ask @**PI:NAME:<NAME>END_PI** for help.")) (def reactivation-msg (str "🤖 YOU HAVE BEEN REACTIVATED AND" " ARE EXPECTED TO ATTEND BREAKFASTS AGAIN 🤖")) (defn who-brings-answer [names date] (str "Official Bringer(s) of Breakfast on " (jt/format "d.M" date) ": " (str/join " and " (map md/mention names)))) (def answers {:ok-unhappy "Alright 🙄" :ok-happy "Great!" :eliza-reply get-eliza-reply :ack "🤖 ACKNOWLEDGED 🤖" :error-signed-off "ERROR: Already signed off! 😤\nDo you often have your head in the clouds?" :error-no-event "ERROR: No event scheduled for this date.\nDoes this make you feel sad?" :error-no-member "ERROR: Noone by this email is registered! 💣\nIs there anything else I can do for you?" :error-active "ERROR: Already marked as active!" :change-bringer (fn [fullnames] (str "OK 🙄 Breakfast duty relegated to: " (str/join " and " (map md/mention fullnames)))) :cancel (fn [when] (str "BREAKFAST ON " (jt/format when) " CANCELED!")) :welcome (fn [email] (str "🎉🎈 Welcome " (md/mention email) "!! 🎉🎈")) :reactivate reactivation-msg :welcome-help welcome-help :new-bringer "HUMAN! 🤖 You have been chosen to bring breakfast!" :who-brings who-brings-answer}) (defn changed-bringer? "Checks whether result of `db-ops/safe-remove implies a new person is responsible for breakfast" [result] (and (seqable? result) (= (first result) :ok-new-responsible))) (defn change-bringer-reply "Create appropriate (full) reply when changing bringer" [new-bringer] {:direct-reply ((:change-bringer answers) new-bringer) :notification {:who new-bringer :message (:new-bringer answers)} :update true}) (defn try-parse-date [when] (try (jt/local-date "d.M.yyyy" when) (catch Exception ex (info "Date parsing failed for input:" when) (throw (ex-info (str "Could not parse as valid breakfast date: \"" when "\", example format: \"23.4.2018\", must be a monday") {:public true}))))) (defn validate-date [date] (cond (< 5 (jt/time-between (jt/local-date) date :months)) (throw (ex-info (str "The date " (jt/format "d.M.yyyy" date) " is too far in the future!") {:public true})) (neg? (jt/time-between (jt/local-date) date :days)) (throw (ex-info (str "The date " (jt/format "d.M.yyyy" date) " is in the past!") {:public true})) :else date)) (defn person-date-matcher [regex author message] (let [matcher (re-matcher regex message)] (when (.matches matcher) (let [who (.group matcher "who") when (.group matcher "when")] (debug "parson-date-matcher, re-groups = " (re-groups matcher) ", who =" who ", when =" when) {:who (if (or (nil? who) (= who "me")) author who) :when (if-not when (next-monday) (let [date (try-parse-date when)] (validate-date date)))}))))